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.

19318 lines
554 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.4.0-SNAPSHOT
  8. * @date 2014-01-22
  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 Hammer;
  33. if (typeof window !== 'undefined') {
  34. // load hammer.js only when running in a browser (where window is available)
  35. Hammer = window['Hammer'] || require('hammerjs');
  36. }
  37. else {
  38. Hammer = function () {
  39. throw Error('hammer.js is only available in a browser, not in node.js.');
  40. }
  41. }
  42. var mouseTrap;
  43. if (typeof window !== 'undefined') {
  44. // load mousetrap.js only when running in a browser (where window is available)
  45. mouseTrap = window['mouseTrap'] || require('mouseTrap');
  46. }
  47. else {
  48. mouseTrap = function () {
  49. throw Error('mouseTrap is only available in a browser, not in node.js.');
  50. }
  51. }
  52. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  53. // it here in that case.
  54. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  55. if(!Array.prototype.indexOf) {
  56. Array.prototype.indexOf = function(obj){
  57. for(var i = 0; i < this.length; i++){
  58. if(this[i] == obj){
  59. return i;
  60. }
  61. }
  62. return -1;
  63. };
  64. try {
  65. console.log("Warning: Ancient browser detected. Please update your browser");
  66. }
  67. catch (err) {
  68. }
  69. }
  70. // Internet Explorer 8 and older does not support Array.forEach, so we define
  71. // it here in that case.
  72. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  73. if (!Array.prototype.forEach) {
  74. Array.prototype.forEach = function(fn, scope) {
  75. for(var i = 0, len = this.length; i < len; ++i) {
  76. fn.call(scope || this, this[i], i, this);
  77. }
  78. }
  79. }
  80. // Internet Explorer 8 and older does not support Array.map, so we define it
  81. // here in that case.
  82. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  83. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  84. // Reference: http://es5.github.com/#x15.4.4.19
  85. if (!Array.prototype.map) {
  86. Array.prototype.map = function(callback, thisArg) {
  87. var T, A, k;
  88. if (this == null) {
  89. throw new TypeError(" this is null or not defined");
  90. }
  91. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  92. var O = Object(this);
  93. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  94. // 3. Let len be ToUint32(lenValue).
  95. var len = O.length >>> 0;
  96. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  97. // See: http://es5.github.com/#x9.11
  98. if (typeof callback !== "function") {
  99. throw new TypeError(callback + " is not a function");
  100. }
  101. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  102. if (thisArg) {
  103. T = thisArg;
  104. }
  105. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  106. // the standard built-in constructor with that name and len is the value of len.
  107. A = new Array(len);
  108. // 7. Let k be 0
  109. k = 0;
  110. // 8. Repeat, while k < len
  111. while(k < len) {
  112. var kValue, mappedValue;
  113. // a. Let Pk be ToString(k).
  114. // This is implicit for LHS operands of the in operator
  115. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  116. // This step can be combined with c
  117. // c. If kPresent is true, then
  118. if (k in O) {
  119. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  120. kValue = O[ k ];
  121. // ii. Let mappedValue be the result of calling the Call internal method of callback
  122. // with T as the this value and argument list containing kValue, k, and O.
  123. mappedValue = callback.call(T, kValue, k, O);
  124. // iii. Call the DefineOwnProperty internal method of A with arguments
  125. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  126. // and false.
  127. // In browsers that support Object.defineProperty, use the following:
  128. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  129. // For best browser support, use the following:
  130. A[ k ] = mappedValue;
  131. }
  132. // d. Increase k by 1.
  133. k++;
  134. }
  135. // 9. return A
  136. return A;
  137. };
  138. }
  139. // Internet Explorer 8 and older does not support Array.filter, so we define it
  140. // here in that case.
  141. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  142. if (!Array.prototype.filter) {
  143. Array.prototype.filter = function(fun /*, thisp */) {
  144. "use strict";
  145. if (this == null) {
  146. throw new TypeError();
  147. }
  148. var t = Object(this);
  149. var len = t.length >>> 0;
  150. if (typeof fun != "function") {
  151. throw new TypeError();
  152. }
  153. var res = [];
  154. var thisp = arguments[1];
  155. for (var i = 0; i < len; i++) {
  156. if (i in t) {
  157. var val = t[i]; // in case fun mutates this
  158. if (fun.call(thisp, val, i, t))
  159. res.push(val);
  160. }
  161. }
  162. return res;
  163. };
  164. }
  165. // Internet Explorer 8 and older does not support Object.keys, so we define it
  166. // here in that case.
  167. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  168. if (!Object.keys) {
  169. Object.keys = (function () {
  170. var hasOwnProperty = Object.prototype.hasOwnProperty,
  171. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  172. dontEnums = [
  173. 'toString',
  174. 'toLocaleString',
  175. 'valueOf',
  176. 'hasOwnProperty',
  177. 'isPrototypeOf',
  178. 'propertyIsEnumerable',
  179. 'constructor'
  180. ],
  181. dontEnumsLength = dontEnums.length;
  182. return function (obj) {
  183. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  184. throw new TypeError('Object.keys called on non-object');
  185. }
  186. var result = [];
  187. for (var prop in obj) {
  188. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  189. }
  190. if (hasDontEnumBug) {
  191. for (var i=0; i < dontEnumsLength; i++) {
  192. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  193. }
  194. }
  195. return result;
  196. }
  197. })()
  198. }
  199. // Internet Explorer 8 and older does not support Array.isArray,
  200. // so we define it here in that case.
  201. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  202. if(!Array.isArray) {
  203. Array.isArray = function (vArg) {
  204. return Object.prototype.toString.call(vArg) === "[object Array]";
  205. };
  206. }
  207. // Internet Explorer 8 and older does not support Function.bind,
  208. // so we define it here in that case.
  209. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  210. if (!Function.prototype.bind) {
  211. Function.prototype.bind = function (oThis) {
  212. if (typeof this !== "function") {
  213. // closest thing possible to the ECMAScript 5 internal IsCallable function
  214. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  215. }
  216. var aArgs = Array.prototype.slice.call(arguments, 1),
  217. fToBind = this,
  218. fNOP = function () {},
  219. fBound = function () {
  220. return fToBind.apply(this instanceof fNOP && oThis
  221. ? this
  222. : oThis,
  223. aArgs.concat(Array.prototype.slice.call(arguments)));
  224. };
  225. fNOP.prototype = this.prototype;
  226. fBound.prototype = new fNOP();
  227. return fBound;
  228. };
  229. }
  230. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  231. if (!Object.create) {
  232. Object.create = function (o) {
  233. if (arguments.length > 1) {
  234. throw new Error('Object.create implementation only accepts the first parameter.');
  235. }
  236. function F() {}
  237. F.prototype = o;
  238. return new F();
  239. };
  240. }
  241. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  242. if (!Function.prototype.bind) {
  243. Function.prototype.bind = function (oThis) {
  244. if (typeof this !== "function") {
  245. // closest thing possible to the ECMAScript 5 internal IsCallable function
  246. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  247. }
  248. var aArgs = Array.prototype.slice.call(arguments, 1),
  249. fToBind = this,
  250. fNOP = function () {},
  251. fBound = function () {
  252. return fToBind.apply(this instanceof fNOP && oThis
  253. ? this
  254. : oThis,
  255. aArgs.concat(Array.prototype.slice.call(arguments)));
  256. };
  257. fNOP.prototype = this.prototype;
  258. fBound.prototype = new fNOP();
  259. return fBound;
  260. };
  261. }
  262. /**
  263. * utility functions
  264. */
  265. var util = {};
  266. /**
  267. * Test whether given object is a number
  268. * @param {*} object
  269. * @return {Boolean} isNumber
  270. */
  271. util.isNumber = function isNumber(object) {
  272. return (object instanceof Number || typeof object == 'number');
  273. };
  274. /**
  275. * Test whether given object is a string
  276. * @param {*} object
  277. * @return {Boolean} isString
  278. */
  279. util.isString = function isString(object) {
  280. return (object instanceof String || typeof object == 'string');
  281. };
  282. /**
  283. * Test whether given object is a Date, or a String containing a Date
  284. * @param {Date | String} object
  285. * @return {Boolean} isDate
  286. */
  287. util.isDate = function isDate(object) {
  288. if (object instanceof Date) {
  289. return true;
  290. }
  291. else if (util.isString(object)) {
  292. // test whether this string contains a date
  293. var match = ASPDateRegex.exec(object);
  294. if (match) {
  295. return true;
  296. }
  297. else if (!isNaN(Date.parse(object))) {
  298. return true;
  299. }
  300. }
  301. return false;
  302. };
  303. /**
  304. * Test whether given object is an instance of google.visualization.DataTable
  305. * @param {*} object
  306. * @return {Boolean} isDataTable
  307. */
  308. util.isDataTable = function isDataTable(object) {
  309. return (typeof (google) !== 'undefined') &&
  310. (google.visualization) &&
  311. (google.visualization.DataTable) &&
  312. (object instanceof google.visualization.DataTable);
  313. };
  314. /**
  315. * Create a semi UUID
  316. * source: http://stackoverflow.com/a/105074/1262753
  317. * @return {String} uuid
  318. */
  319. util.randomUUID = function randomUUID () {
  320. var S4 = function () {
  321. return Math.floor(
  322. Math.random() * 0x10000 /* 65536 */
  323. ).toString(16);
  324. };
  325. return (
  326. S4() + S4() + '-' +
  327. S4() + '-' +
  328. S4() + '-' +
  329. S4() + '-' +
  330. S4() + S4() + S4()
  331. );
  332. };
  333. /**
  334. * Extend object a with the properties of object b or a series of objects
  335. * Only properties with defined values are copied
  336. * @param {Object} a
  337. * @param {... Object} b
  338. * @return {Object} a
  339. */
  340. util.extend = function (a, b) {
  341. for (var i = 1, len = arguments.length; i < len; i++) {
  342. var other = arguments[i];
  343. for (var prop in other) {
  344. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  345. a[prop] = other[prop];
  346. }
  347. }
  348. }
  349. return a;
  350. };
  351. /**
  352. * Convert an object to another type
  353. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  354. * @param {String | undefined} type Name of the type. Available types:
  355. * 'Boolean', 'Number', 'String',
  356. * 'Date', 'Moment', ISODate', 'ASPDate'.
  357. * @return {*} object
  358. * @throws Error
  359. */
  360. util.convert = function convert(object, type) {
  361. var match;
  362. if (object === undefined) {
  363. return undefined;
  364. }
  365. if (object === null) {
  366. return null;
  367. }
  368. if (!type) {
  369. return object;
  370. }
  371. if (!(typeof type === 'string') && !(type instanceof String)) {
  372. throw new Error('Type must be a string');
  373. }
  374. //noinspection FallthroughInSwitchStatementJS
  375. switch (type) {
  376. case 'boolean':
  377. case 'Boolean':
  378. return Boolean(object);
  379. case 'number':
  380. case 'Number':
  381. return Number(object.valueOf());
  382. case 'string':
  383. case 'String':
  384. return String(object);
  385. case 'Date':
  386. if (util.isNumber(object)) {
  387. return new Date(object);
  388. }
  389. if (object instanceof Date) {
  390. return new Date(object.valueOf());
  391. }
  392. else if (moment.isMoment(object)) {
  393. return new Date(object.valueOf());
  394. }
  395. if (util.isString(object)) {
  396. match = ASPDateRegex.exec(object);
  397. if (match) {
  398. // object is an ASP date
  399. return new Date(Number(match[1])); // parse number
  400. }
  401. else {
  402. return moment(object).toDate(); // parse string
  403. }
  404. }
  405. else {
  406. throw new Error(
  407. 'Cannot convert object of type ' + util.getType(object) +
  408. ' to type Date');
  409. }
  410. case 'Moment':
  411. if (util.isNumber(object)) {
  412. return moment(object);
  413. }
  414. if (object instanceof Date) {
  415. return moment(object.valueOf());
  416. }
  417. else if (moment.isMoment(object)) {
  418. return moment(object);
  419. }
  420. if (util.isString(object)) {
  421. match = ASPDateRegex.exec(object);
  422. if (match) {
  423. // object is an ASP date
  424. return moment(Number(match[1])); // parse number
  425. }
  426. else {
  427. return moment(object); // parse string
  428. }
  429. }
  430. else {
  431. throw new Error(
  432. 'Cannot convert object of type ' + util.getType(object) +
  433. ' to type Date');
  434. }
  435. case 'ISODate':
  436. if (util.isNumber(object)) {
  437. return new Date(object);
  438. }
  439. else if (object instanceof Date) {
  440. return object.toISOString();
  441. }
  442. else if (moment.isMoment(object)) {
  443. return object.toDate().toISOString();
  444. }
  445. else if (util.isString(object)) {
  446. match = ASPDateRegex.exec(object);
  447. if (match) {
  448. // object is an ASP date
  449. return new Date(Number(match[1])).toISOString(); // parse number
  450. }
  451. else {
  452. return new Date(object).toISOString(); // parse string
  453. }
  454. }
  455. else {
  456. throw new Error(
  457. 'Cannot convert object of type ' + util.getType(object) +
  458. ' to type ISODate');
  459. }
  460. case 'ASPDate':
  461. if (util.isNumber(object)) {
  462. return '/Date(' + object + ')/';
  463. }
  464. else if (object instanceof Date) {
  465. return '/Date(' + object.valueOf() + ')/';
  466. }
  467. else if (util.isString(object)) {
  468. match = ASPDateRegex.exec(object);
  469. var value;
  470. if (match) {
  471. // object is an ASP date
  472. value = new Date(Number(match[1])).valueOf(); // parse number
  473. }
  474. else {
  475. value = new Date(object).valueOf(); // parse string
  476. }
  477. return '/Date(' + value + ')/';
  478. }
  479. else {
  480. throw new Error(
  481. 'Cannot convert object of type ' + util.getType(object) +
  482. ' to type ASPDate');
  483. }
  484. default:
  485. throw new Error('Cannot convert object of type ' + util.getType(object) +
  486. ' to type "' + type + '"');
  487. }
  488. };
  489. // parse ASP.Net Date pattern,
  490. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  491. // code from http://momentjs.com/
  492. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  493. /**
  494. * Get the type of an object, for example util.getType([]) returns 'Array'
  495. * @param {*} object
  496. * @return {String} type
  497. */
  498. util.getType = function getType(object) {
  499. var type = typeof object;
  500. if (type == 'object') {
  501. if (object == null) {
  502. return 'null';
  503. }
  504. if (object instanceof Boolean) {
  505. return 'Boolean';
  506. }
  507. if (object instanceof Number) {
  508. return 'Number';
  509. }
  510. if (object instanceof String) {
  511. return 'String';
  512. }
  513. if (object instanceof Array) {
  514. return 'Array';
  515. }
  516. if (object instanceof Date) {
  517. return 'Date';
  518. }
  519. return 'Object';
  520. }
  521. else if (type == 'number') {
  522. return 'Number';
  523. }
  524. else if (type == 'boolean') {
  525. return 'Boolean';
  526. }
  527. else if (type == 'string') {
  528. return 'String';
  529. }
  530. return type;
  531. };
  532. /**
  533. * Retrieve the absolute left value of a DOM element
  534. * @param {Element} elem A dom element, for example a div
  535. * @return {number} left The absolute left position of this element
  536. * in the browser page.
  537. */
  538. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  539. var doc = document.documentElement;
  540. var body = document.body;
  541. var left = elem.offsetLeft;
  542. var e = elem.offsetParent;
  543. while (e != null && e != body && e != doc) {
  544. left += e.offsetLeft;
  545. left -= e.scrollLeft;
  546. e = e.offsetParent;
  547. }
  548. return left;
  549. };
  550. /**
  551. * Retrieve the absolute top value of a DOM element
  552. * @param {Element} elem A dom element, for example a div
  553. * @return {number} top The absolute top position of this element
  554. * in the browser page.
  555. */
  556. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  557. var doc = document.documentElement;
  558. var body = document.body;
  559. var top = elem.offsetTop;
  560. var e = elem.offsetParent;
  561. while (e != null && e != body && e != doc) {
  562. top += e.offsetTop;
  563. top -= e.scrollTop;
  564. e = e.offsetParent;
  565. }
  566. return top;
  567. };
  568. /**
  569. * Get the absolute, vertical mouse position from an event.
  570. * @param {Event} event
  571. * @return {Number} pageY
  572. */
  573. util.getPageY = function getPageY (event) {
  574. if ('pageY' in event) {
  575. return event.pageY;
  576. }
  577. else {
  578. var clientY;
  579. if (('targetTouches' in event) && event.targetTouches.length) {
  580. clientY = event.targetTouches[0].clientY;
  581. }
  582. else {
  583. clientY = event.clientY;
  584. }
  585. var doc = document.documentElement;
  586. var body = document.body;
  587. return clientY +
  588. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  589. ( doc && doc.clientTop || body && body.clientTop || 0 );
  590. }
  591. };
  592. /**
  593. * Get the absolute, horizontal mouse position from an event.
  594. * @param {Event} event
  595. * @return {Number} pageX
  596. */
  597. util.getPageX = function getPageX (event) {
  598. if ('pageY' in event) {
  599. return event.pageX;
  600. }
  601. else {
  602. var clientX;
  603. if (('targetTouches' in event) && event.targetTouches.length) {
  604. clientX = event.targetTouches[0].clientX;
  605. }
  606. else {
  607. clientX = event.clientX;
  608. }
  609. var doc = document.documentElement;
  610. var body = document.body;
  611. return clientX +
  612. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  613. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  614. }
  615. };
  616. /**
  617. * add a className to the given elements style
  618. * @param {Element} elem
  619. * @param {String} className
  620. */
  621. util.addClassName = function addClassName(elem, className) {
  622. var classes = elem.className.split(' ');
  623. if (classes.indexOf(className) == -1) {
  624. classes.push(className); // add the class to the array
  625. elem.className = classes.join(' ');
  626. }
  627. };
  628. /**
  629. * add a className to the given elements style
  630. * @param {Element} elem
  631. * @param {String} className
  632. */
  633. util.removeClassName = function removeClassname(elem, className) {
  634. var classes = elem.className.split(' ');
  635. var index = classes.indexOf(className);
  636. if (index != -1) {
  637. classes.splice(index, 1); // remove the class from the array
  638. elem.className = classes.join(' ');
  639. }
  640. };
  641. /**
  642. * For each method for both arrays and objects.
  643. * In case of an array, the built-in Array.forEach() is applied.
  644. * In case of an Object, the method loops over all properties of the object.
  645. * @param {Object | Array} object An Object or Array
  646. * @param {function} callback Callback method, called for each item in
  647. * the object or array with three parameters:
  648. * callback(value, index, object)
  649. */
  650. util.forEach = function forEach (object, callback) {
  651. var i,
  652. len;
  653. if (object instanceof Array) {
  654. // array
  655. for (i = 0, len = object.length; i < len; i++) {
  656. callback(object[i], i, object);
  657. }
  658. }
  659. else {
  660. // object
  661. for (i in object) {
  662. if (object.hasOwnProperty(i)) {
  663. callback(object[i], i, object);
  664. }
  665. }
  666. }
  667. };
  668. /**
  669. * Update a property in an object
  670. * @param {Object} object
  671. * @param {String} key
  672. * @param {*} value
  673. * @return {Boolean} changed
  674. */
  675. util.updateProperty = function updateProp (object, key, value) {
  676. if (object[key] !== value) {
  677. object[key] = value;
  678. return true;
  679. }
  680. else {
  681. return false;
  682. }
  683. };
  684. /**
  685. * Add and event listener. Works for all browsers
  686. * @param {Element} element An html element
  687. * @param {string} action The action, for example "click",
  688. * without the prefix "on"
  689. * @param {function} listener The callback function to be executed
  690. * @param {boolean} [useCapture]
  691. */
  692. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  693. if (element.addEventListener) {
  694. if (useCapture === undefined)
  695. useCapture = false;
  696. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  697. action = "DOMMouseScroll"; // For Firefox
  698. }
  699. element.addEventListener(action, listener, useCapture);
  700. } else {
  701. element.attachEvent("on" + action, listener); // IE browsers
  702. }
  703. };
  704. /**
  705. * Remove an event listener from an element
  706. * @param {Element} element An html dom element
  707. * @param {string} action The name of the event, for example "mousedown"
  708. * @param {function} listener The listener function
  709. * @param {boolean} [useCapture]
  710. */
  711. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  712. if (element.removeEventListener) {
  713. // non-IE browsers
  714. if (useCapture === undefined)
  715. useCapture = false;
  716. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  717. action = "DOMMouseScroll"; // For Firefox
  718. }
  719. element.removeEventListener(action, listener, useCapture);
  720. } else {
  721. // IE browsers
  722. element.detachEvent("on" + action, listener);
  723. }
  724. };
  725. /**
  726. * Get HTML element which is the target of the event
  727. * @param {Event} event
  728. * @return {Element} target element
  729. */
  730. util.getTarget = function getTarget(event) {
  731. // code from http://www.quirksmode.org/js/events_properties.html
  732. if (!event) {
  733. event = window.event;
  734. }
  735. var target;
  736. if (event.target) {
  737. target = event.target;
  738. }
  739. else if (event.srcElement) {
  740. target = event.srcElement;
  741. }
  742. if (target.nodeType != undefined && target.nodeType == 3) {
  743. // defeat Safari bug
  744. target = target.parentNode;
  745. }
  746. return target;
  747. };
  748. /**
  749. * Stop event propagation
  750. */
  751. util.stopPropagation = function stopPropagation(event) {
  752. if (!event)
  753. event = window.event;
  754. if (event.stopPropagation) {
  755. event.stopPropagation(); // non-IE browsers
  756. }
  757. else {
  758. event.cancelBubble = true; // IE browsers
  759. }
  760. };
  761. /**
  762. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  763. * @param {Element} element
  764. * @param {Event} event
  765. */
  766. util.fakeGesture = function fakeGesture (element, event) {
  767. var eventType = null;
  768. // for hammer.js 1.0.5
  769. return Hammer.event.collectEventData(this, eventType, event);
  770. // for hammer.js 1.0.6
  771. //var touches = Hammer.event.getTouchList(event, eventType);
  772. //return Hammer.event.collectEventData(this, eventType, touches, event);
  773. };
  774. /**
  775. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  776. */
  777. util.preventDefault = function preventDefault (event) {
  778. if (!event)
  779. event = window.event;
  780. if (event.preventDefault) {
  781. event.preventDefault(); // non-IE browsers
  782. }
  783. else {
  784. event.returnValue = false; // IE browsers
  785. }
  786. };
  787. util.option = {};
  788. /**
  789. * Convert a value into a boolean
  790. * @param {Boolean | function | undefined} value
  791. * @param {Boolean} [defaultValue]
  792. * @returns {Boolean} bool
  793. */
  794. util.option.asBoolean = function (value, defaultValue) {
  795. if (typeof value == 'function') {
  796. value = value();
  797. }
  798. if (value != null) {
  799. return (value != false);
  800. }
  801. return defaultValue || null;
  802. };
  803. /**
  804. * Convert a value into a number
  805. * @param {Boolean | function | undefined} value
  806. * @param {Number} [defaultValue]
  807. * @returns {Number} number
  808. */
  809. util.option.asNumber = function (value, defaultValue) {
  810. if (typeof value == 'function') {
  811. value = value();
  812. }
  813. if (value != null) {
  814. return Number(value) || defaultValue || null;
  815. }
  816. return defaultValue || null;
  817. };
  818. /**
  819. * Convert a value into a string
  820. * @param {String | function | undefined} value
  821. * @param {String} [defaultValue]
  822. * @returns {String} str
  823. */
  824. util.option.asString = function (value, defaultValue) {
  825. if (typeof value == 'function') {
  826. value = value();
  827. }
  828. if (value != null) {
  829. return String(value);
  830. }
  831. return defaultValue || null;
  832. };
  833. /**
  834. * Convert a size or location into a string with pixels or a percentage
  835. * @param {String | Number | function | undefined} value
  836. * @param {String} [defaultValue]
  837. * @returns {String} size
  838. */
  839. util.option.asSize = function (value, defaultValue) {
  840. if (typeof value == 'function') {
  841. value = value();
  842. }
  843. if (util.isString(value)) {
  844. return value;
  845. }
  846. else if (util.isNumber(value)) {
  847. return value + 'px';
  848. }
  849. else {
  850. return defaultValue || null;
  851. }
  852. };
  853. /**
  854. * Convert a value into a DOM element
  855. * @param {HTMLElement | function | undefined} value
  856. * @param {HTMLElement} [defaultValue]
  857. * @returns {HTMLElement | null} dom
  858. */
  859. util.option.asElement = function (value, defaultValue) {
  860. if (typeof value == 'function') {
  861. value = value();
  862. }
  863. return value || defaultValue || null;
  864. };
  865. /**
  866. * Event listener (singleton)
  867. */
  868. // TODO: replace usage of the event listener for the EventBus
  869. var events = {
  870. 'listeners': [],
  871. /**
  872. * Find a single listener by its object
  873. * @param {Object} object
  874. * @return {Number} index -1 when not found
  875. */
  876. 'indexOf': function (object) {
  877. var listeners = this.listeners;
  878. for (var i = 0, iMax = this.listeners.length; i < iMax; i++) {
  879. var listener = listeners[i];
  880. if (listener && listener.object == object) {
  881. return i;
  882. }
  883. }
  884. return -1;
  885. },
  886. /**
  887. * Add an event listener
  888. * @param {Object} object
  889. * @param {String} event The name of an event, for example 'select'
  890. * @param {function} callback The callback method, called when the
  891. * event takes place
  892. */
  893. 'addListener': function (object, event, callback) {
  894. var index = this.indexOf(object);
  895. var listener = this.listeners[index];
  896. if (!listener) {
  897. listener = {
  898. 'object': object,
  899. 'events': {}
  900. };
  901. this.listeners.push(listener);
  902. }
  903. var callbacks = listener.events[event];
  904. if (!callbacks) {
  905. callbacks = [];
  906. listener.events[event] = callbacks;
  907. }
  908. // add the callback if it does not yet exist
  909. if (callbacks.indexOf(callback) == -1) {
  910. callbacks.push(callback);
  911. }
  912. },
  913. /**
  914. * Remove an event listener
  915. * @param {Object} object
  916. * @param {String} event The name of an event, for example 'select'
  917. * @param {function} callback The registered callback method
  918. */
  919. 'removeListener': function (object, event, callback) {
  920. var index = this.indexOf(object);
  921. var listener = this.listeners[index];
  922. if (listener) {
  923. var callbacks = listener.events[event];
  924. if (callbacks) {
  925. index = callbacks.indexOf(callback);
  926. if (index != -1) {
  927. callbacks.splice(index, 1);
  928. }
  929. // remove the array when empty
  930. if (callbacks.length == 0) {
  931. delete listener.events[event];
  932. }
  933. }
  934. // count the number of registered events. remove listener when empty
  935. var count = 0;
  936. var events = listener.events;
  937. for (var e in events) {
  938. if (events.hasOwnProperty(e)) {
  939. count++;
  940. }
  941. }
  942. if (count == 0) {
  943. delete this.listeners[index];
  944. }
  945. }
  946. },
  947. /**
  948. * Remove all registered event listeners
  949. */
  950. 'removeAllListeners': function () {
  951. this.listeners = [];
  952. },
  953. /**
  954. * Trigger an event. All registered event handlers will be called
  955. * @param {Object} object
  956. * @param {String} event
  957. * @param {Object} properties (optional)
  958. */
  959. 'trigger': function (object, event, properties) {
  960. var index = this.indexOf(object);
  961. var listener = this.listeners[index];
  962. if (listener) {
  963. var callbacks = listener.events[event];
  964. if (callbacks) {
  965. for (var i = 0, iMax = callbacks.length; i < iMax; i++) {
  966. callbacks[i](properties);
  967. }
  968. }
  969. }
  970. }
  971. };
  972. /**
  973. * An event bus can be used to emit events, and to subscribe to events
  974. * @constructor EventBus
  975. */
  976. function EventBus() {
  977. this.subscriptions = [];
  978. }
  979. /**
  980. * Subscribe to an event
  981. * @param {String | RegExp} event The event can be a regular expression, or
  982. * a string with wildcards, like 'server.*'.
  983. * @param {function} callback. Callback are called with three parameters:
  984. * {String} event, {*} [data], {*} [source]
  985. * @param {*} [target]
  986. * @returns {String} id A subscription id
  987. */
  988. EventBus.prototype.on = function (event, callback, target) {
  989. var regexp = (event instanceof RegExp) ?
  990. event :
  991. new RegExp(event.replace('*', '\\w+'));
  992. var subscription = {
  993. id: util.randomUUID(),
  994. event: event,
  995. regexp: regexp,
  996. callback: (typeof callback === 'function') ? callback : null,
  997. target: target
  998. };
  999. this.subscriptions.push(subscription);
  1000. return subscription.id;
  1001. };
  1002. /**
  1003. * Unsubscribe from an event
  1004. * @param {String | Object} filter Filter for subscriptions to be removed
  1005. * Filter can be a string containing a
  1006. * subscription id, or an object containing
  1007. * one or more of the fields id, event,
  1008. * callback, and target.
  1009. */
  1010. EventBus.prototype.off = function (filter) {
  1011. var i = 0;
  1012. while (i < this.subscriptions.length) {
  1013. var subscription = this.subscriptions[i];
  1014. var match = true;
  1015. if (filter instanceof Object) {
  1016. // filter is an object. All fields must match
  1017. for (var prop in filter) {
  1018. if (filter.hasOwnProperty(prop)) {
  1019. if (filter[prop] !== subscription[prop]) {
  1020. match = false;
  1021. }
  1022. }
  1023. }
  1024. }
  1025. else {
  1026. // filter is a string, filter on id
  1027. match = (subscription.id == filter);
  1028. }
  1029. if (match) {
  1030. this.subscriptions.splice(i, 1);
  1031. }
  1032. else {
  1033. i++;
  1034. }
  1035. }
  1036. };
  1037. /**
  1038. * Emit an event
  1039. * @param {String} event
  1040. * @param {*} [data]
  1041. * @param {*} [source]
  1042. */
  1043. EventBus.prototype.emit = function (event, data, source) {
  1044. for (var i =0; i < this.subscriptions.length; i++) {
  1045. var subscription = this.subscriptions[i];
  1046. if (subscription.regexp.test(event)) {
  1047. if (subscription.callback) {
  1048. subscription.callback(event, data, source);
  1049. }
  1050. }
  1051. }
  1052. };
  1053. /**
  1054. * DataSet
  1055. *
  1056. * Usage:
  1057. * var dataSet = new DataSet({
  1058. * fieldId: '_id',
  1059. * convert: {
  1060. * // ...
  1061. * }
  1062. * });
  1063. *
  1064. * dataSet.add(item);
  1065. * dataSet.add(data);
  1066. * dataSet.update(item);
  1067. * dataSet.update(data);
  1068. * dataSet.remove(id);
  1069. * dataSet.remove(ids);
  1070. * var data = dataSet.get();
  1071. * var data = dataSet.get(id);
  1072. * var data = dataSet.get(ids);
  1073. * var data = dataSet.get(ids, options, data);
  1074. * dataSet.clear();
  1075. *
  1076. * A data set can:
  1077. * - add/remove/update data
  1078. * - gives triggers upon changes in the data
  1079. * - can import/export data in various data formats
  1080. *
  1081. * @param {Object} [options] Available options:
  1082. * {String} fieldId Field name of the id in the
  1083. * items, 'id' by default.
  1084. * {Object.<String, String} convert
  1085. * A map with field names as key,
  1086. * and the field type as value.
  1087. * @constructor DataSet
  1088. */
  1089. // TODO: add a DataSet constructor DataSet(data, options)
  1090. function DataSet (options) {
  1091. this.id = util.randomUUID();
  1092. this.options = options || {};
  1093. this.data = {}; // map with data indexed by id
  1094. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1095. this.convert = {}; // field types by field name
  1096. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1097. if (this.options.convert) {
  1098. for (var field in this.options.convert) {
  1099. if (this.options.convert.hasOwnProperty(field)) {
  1100. var value = this.options.convert[field];
  1101. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1102. this.convert[field] = 'Date';
  1103. }
  1104. else {
  1105. this.convert[field] = value;
  1106. }
  1107. }
  1108. }
  1109. }
  1110. // event subscribers
  1111. this.subscribers = {};
  1112. this.internalIds = {}; // internally generated id's
  1113. }
  1114. /**
  1115. * Subscribe to an event, add an event listener
  1116. * @param {String} event Event name. Available events: 'put', 'update',
  1117. * 'remove'
  1118. * @param {function} callback Callback method. Called with three parameters:
  1119. * {String} event
  1120. * {Object | null} params
  1121. * {String | Number} senderId
  1122. */
  1123. DataSet.prototype.subscribe = function (event, callback) {
  1124. var subscribers = this.subscribers[event];
  1125. if (!subscribers) {
  1126. subscribers = [];
  1127. this.subscribers[event] = subscribers;
  1128. }
  1129. subscribers.push({
  1130. callback: callback
  1131. });
  1132. };
  1133. /**
  1134. * Unsubscribe from an event, remove an event listener
  1135. * @param {String} event
  1136. * @param {function} callback
  1137. */
  1138. DataSet.prototype.unsubscribe = function (event, callback) {
  1139. var subscribers = this.subscribers[event];
  1140. if (subscribers) {
  1141. this.subscribers[event] = subscribers.filter(function (listener) {
  1142. return (listener.callback != callback);
  1143. });
  1144. }
  1145. };
  1146. /**
  1147. * Trigger an event
  1148. * @param {String} event
  1149. * @param {Object | null} params
  1150. * @param {String} [senderId] Optional id of the sender.
  1151. * @private
  1152. */
  1153. DataSet.prototype._trigger = function (event, params, senderId) {
  1154. if (event == '*') {
  1155. throw new Error('Cannot trigger event *');
  1156. }
  1157. var subscribers = [];
  1158. if (event in this.subscribers) {
  1159. subscribers = subscribers.concat(this.subscribers[event]);
  1160. }
  1161. if ('*' in this.subscribers) {
  1162. subscribers = subscribers.concat(this.subscribers['*']);
  1163. }
  1164. for (var i = 0; i < subscribers.length; i++) {
  1165. var subscriber = subscribers[i];
  1166. if (subscriber.callback) {
  1167. subscriber.callback(event, params, senderId || null);
  1168. }
  1169. }
  1170. };
  1171. /**
  1172. * Add data.
  1173. * Adding an item will fail when there already is an item with the same id.
  1174. * @param {Object | Array | DataTable} data
  1175. * @param {String} [senderId] Optional sender id
  1176. * @return {Array} addedIds Array with the ids of the added items
  1177. */
  1178. DataSet.prototype.add = function (data, senderId) {
  1179. var addedIds = [],
  1180. id,
  1181. me = this;
  1182. if (data instanceof Array) {
  1183. // Array
  1184. for (var i = 0, len = data.length; i < len; i++) {
  1185. id = me._addItem(data[i]);
  1186. addedIds.push(id);
  1187. }
  1188. }
  1189. else if (util.isDataTable(data)) {
  1190. // Google DataTable
  1191. var columns = this._getColumnNames(data);
  1192. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1193. var item = {};
  1194. for (var col = 0, cols = columns.length; col < cols; col++) {
  1195. var field = columns[col];
  1196. item[field] = data.getValue(row, col);
  1197. }
  1198. id = me._addItem(item);
  1199. addedIds.push(id);
  1200. }
  1201. }
  1202. else if (data instanceof Object) {
  1203. // Single item
  1204. id = me._addItem(data);
  1205. addedIds.push(id);
  1206. }
  1207. else {
  1208. throw new Error('Unknown dataType');
  1209. }
  1210. if (addedIds.length) {
  1211. this._trigger('add', {items: addedIds}, senderId);
  1212. }
  1213. return addedIds;
  1214. };
  1215. /**
  1216. * Update existing items. When an item does not exist, it will be created
  1217. * @param {Object | Array | DataTable} data
  1218. * @param {String} [senderId] Optional sender id
  1219. * @return {Array} updatedIds The ids of the added or updated items
  1220. */
  1221. DataSet.prototype.update = function (data, senderId) {
  1222. var addedIds = [],
  1223. updatedIds = [],
  1224. me = this,
  1225. fieldId = me.fieldId;
  1226. var addOrUpdate = function (item) {
  1227. var id = item[fieldId];
  1228. if (me.data[id]) {
  1229. // update item
  1230. id = me._updateItem(item);
  1231. updatedIds.push(id);
  1232. }
  1233. else {
  1234. // add new item
  1235. id = me._addItem(item);
  1236. addedIds.push(id);
  1237. }
  1238. };
  1239. if (data instanceof Array) {
  1240. // Array
  1241. for (var i = 0, len = data.length; i < len; i++) {
  1242. addOrUpdate(data[i]);
  1243. }
  1244. }
  1245. else if (util.isDataTable(data)) {
  1246. // Google DataTable
  1247. var columns = this._getColumnNames(data);
  1248. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1249. var item = {};
  1250. for (var col = 0, cols = columns.length; col < cols; col++) {
  1251. var field = columns[col];
  1252. item[field] = data.getValue(row, col);
  1253. }
  1254. addOrUpdate(item);
  1255. }
  1256. }
  1257. else if (data instanceof Object) {
  1258. // Single item
  1259. addOrUpdate(data);
  1260. }
  1261. else {
  1262. throw new Error('Unknown dataType');
  1263. }
  1264. if (addedIds.length) {
  1265. this._trigger('add', {items: addedIds}, senderId);
  1266. }
  1267. if (updatedIds.length) {
  1268. this._trigger('update', {items: updatedIds}, senderId);
  1269. }
  1270. return addedIds.concat(updatedIds);
  1271. };
  1272. /**
  1273. * Get a data item or multiple items.
  1274. *
  1275. * Usage:
  1276. *
  1277. * get()
  1278. * get(options: Object)
  1279. * get(options: Object, data: Array | DataTable)
  1280. *
  1281. * get(id: Number | String)
  1282. * get(id: Number | String, options: Object)
  1283. * get(id: Number | String, options: Object, data: Array | DataTable)
  1284. *
  1285. * get(ids: Number[] | String[])
  1286. * get(ids: Number[] | String[], options: Object)
  1287. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1288. *
  1289. * Where:
  1290. *
  1291. * {Number | String} id The id of an item
  1292. * {Number[] | String{}} ids An array with ids of items
  1293. * {Object} options An Object with options. Available options:
  1294. * {String} [type] Type of data to be returned. Can
  1295. * be 'DataTable' or 'Array' (default)
  1296. * {Object.<String, String>} [convert]
  1297. * {String[]} [fields] field names to be returned
  1298. * {function} [filter] filter items
  1299. * {String | function} [order] Order the items by
  1300. * a field name or custom sort function.
  1301. * {Array | DataTable} [data] If provided, items will be appended to this
  1302. * array or table. Required in case of Google
  1303. * DataTable.
  1304. *
  1305. * @throws Error
  1306. */
  1307. DataSet.prototype.get = function (args) {
  1308. var me = this;
  1309. var globalShowInternalIds = this.showInternalIds;
  1310. // parse the arguments
  1311. var id, ids, options, data;
  1312. var firstType = util.getType(arguments[0]);
  1313. if (firstType == 'String' || firstType == 'Number') {
  1314. // get(id [, options] [, data])
  1315. id = arguments[0];
  1316. options = arguments[1];
  1317. data = arguments[2];
  1318. }
  1319. else if (firstType == 'Array') {
  1320. // get(ids [, options] [, data])
  1321. ids = arguments[0];
  1322. options = arguments[1];
  1323. data = arguments[2];
  1324. }
  1325. else {
  1326. // get([, options] [, data])
  1327. options = arguments[0];
  1328. data = arguments[1];
  1329. }
  1330. // determine the return type
  1331. var type;
  1332. if (options && options.type) {
  1333. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1334. if (data && (type != util.getType(data))) {
  1335. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1336. 'does not correspond with specified options.type (' + options.type + ')');
  1337. }
  1338. if (type == 'DataTable' && !util.isDataTable(data)) {
  1339. throw new Error('Parameter "data" must be a DataTable ' +
  1340. 'when options.type is "DataTable"');
  1341. }
  1342. }
  1343. else if (data) {
  1344. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1345. }
  1346. else {
  1347. type = 'Array';
  1348. }
  1349. // we allow the setting of this value for a single get request.
  1350. if (options != undefined) {
  1351. if (options.showInternalIds != undefined) {
  1352. this.showInternalIds = options.showInternalIds;
  1353. }
  1354. }
  1355. // build options
  1356. var convert = options && options.convert || this.options.convert;
  1357. var filter = options && options.filter;
  1358. var items = [], item, itemId, i, len;
  1359. // convert items
  1360. if (id != undefined) {
  1361. // return a single item
  1362. item = me._getItem(id, convert);
  1363. if (filter && !filter(item)) {
  1364. item = null;
  1365. }
  1366. }
  1367. else if (ids != undefined) {
  1368. // return a subset of items
  1369. for (i = 0, len = ids.length; i < len; i++) {
  1370. item = me._getItem(ids[i], convert);
  1371. if (!filter || filter(item)) {
  1372. items.push(item);
  1373. }
  1374. }
  1375. }
  1376. else {
  1377. // return all items
  1378. for (itemId in this.data) {
  1379. if (this.data.hasOwnProperty(itemId)) {
  1380. item = me._getItem(itemId, convert);
  1381. if (!filter || filter(item)) {
  1382. items.push(item);
  1383. }
  1384. }
  1385. }
  1386. }
  1387. // restore the global value of showInternalIds
  1388. this.showInternalIds = globalShowInternalIds;
  1389. // order the results
  1390. if (options && options.order && id == undefined) {
  1391. this._sort(items, options.order);
  1392. }
  1393. // filter fields of the items
  1394. if (options && options.fields) {
  1395. var fields = options.fields;
  1396. if (id != undefined) {
  1397. item = this._filterFields(item, fields);
  1398. }
  1399. else {
  1400. for (i = 0, len = items.length; i < len; i++) {
  1401. items[i] = this._filterFields(items[i], fields);
  1402. }
  1403. }
  1404. }
  1405. // return the results
  1406. if (type == 'DataTable') {
  1407. var columns = this._getColumnNames(data);
  1408. if (id != undefined) {
  1409. // append a single item to the data table
  1410. me._appendRow(data, columns, item);
  1411. }
  1412. else {
  1413. // copy the items to the provided data table
  1414. for (i = 0, len = items.length; i < len; i++) {
  1415. me._appendRow(data, columns, items[i]);
  1416. }
  1417. }
  1418. return data;
  1419. }
  1420. else {
  1421. // return an array
  1422. if (id != undefined) {
  1423. // a single item
  1424. return item;
  1425. }
  1426. else {
  1427. // multiple items
  1428. if (data) {
  1429. // copy the items to the provided array
  1430. for (i = 0, len = items.length; i < len; i++) {
  1431. data.push(items[i]);
  1432. }
  1433. return data;
  1434. }
  1435. else {
  1436. // just return our array
  1437. return items;
  1438. }
  1439. }
  1440. }
  1441. };
  1442. /**
  1443. * Get ids of all items or from a filtered set of items.
  1444. * @param {Object} [options] An Object with options. Available options:
  1445. * {function} [filter] filter items
  1446. * {String | function} [order] Order the items by
  1447. * a field name or custom sort function.
  1448. * @return {Array} ids
  1449. */
  1450. DataSet.prototype.getIds = function (options) {
  1451. var data = this.data,
  1452. filter = options && options.filter,
  1453. order = options && options.order,
  1454. convert = options && options.convert || this.options.convert,
  1455. i,
  1456. len,
  1457. id,
  1458. item,
  1459. items,
  1460. ids = [];
  1461. if (filter) {
  1462. // get filtered items
  1463. if (order) {
  1464. // create ordered list
  1465. items = [];
  1466. for (id in data) {
  1467. if (data.hasOwnProperty(id)) {
  1468. item = this._getItem(id, convert);
  1469. if (filter(item)) {
  1470. items.push(item);
  1471. }
  1472. }
  1473. }
  1474. this._sort(items, order);
  1475. for (i = 0, len = items.length; i < len; i++) {
  1476. ids[i] = items[i][this.fieldId];
  1477. }
  1478. }
  1479. else {
  1480. // create unordered list
  1481. for (id in data) {
  1482. if (data.hasOwnProperty(id)) {
  1483. item = this._getItem(id, convert);
  1484. if (filter(item)) {
  1485. ids.push(item[this.fieldId]);
  1486. }
  1487. }
  1488. }
  1489. }
  1490. }
  1491. else {
  1492. // get all items
  1493. if (order) {
  1494. // create an ordered list
  1495. items = [];
  1496. for (id in data) {
  1497. if (data.hasOwnProperty(id)) {
  1498. items.push(data[id]);
  1499. }
  1500. }
  1501. this._sort(items, order);
  1502. for (i = 0, len = items.length; i < len; i++) {
  1503. ids[i] = items[i][this.fieldId];
  1504. }
  1505. }
  1506. else {
  1507. // create unordered list
  1508. for (id in data) {
  1509. if (data.hasOwnProperty(id)) {
  1510. item = data[id];
  1511. ids.push(item[this.fieldId]);
  1512. }
  1513. }
  1514. }
  1515. }
  1516. return ids;
  1517. };
  1518. /**
  1519. * Execute a callback function for every item in the dataset.
  1520. * The order of the items is not determined.
  1521. * @param {function} callback
  1522. * @param {Object} [options] Available options:
  1523. * {Object.<String, String>} [convert]
  1524. * {String[]} [fields] filter fields
  1525. * {function} [filter] filter items
  1526. * {String | function} [order] Order the items by
  1527. * a field name or custom sort function.
  1528. */
  1529. DataSet.prototype.forEach = function (callback, options) {
  1530. var filter = options && options.filter,
  1531. convert = options && options.convert || this.options.convert,
  1532. data = this.data,
  1533. item,
  1534. id;
  1535. if (options && options.order) {
  1536. // execute forEach on ordered list
  1537. var items = this.get(options);
  1538. for (var i = 0, len = items.length; i < len; i++) {
  1539. item = items[i];
  1540. id = item[this.fieldId];
  1541. callback(item, id);
  1542. }
  1543. }
  1544. else {
  1545. // unordered
  1546. for (id in data) {
  1547. if (data.hasOwnProperty(id)) {
  1548. item = this._getItem(id, convert);
  1549. if (!filter || filter(item)) {
  1550. callback(item, id);
  1551. }
  1552. }
  1553. }
  1554. }
  1555. };
  1556. /**
  1557. * Map every item in the dataset.
  1558. * @param {function} callback
  1559. * @param {Object} [options] Available options:
  1560. * {Object.<String, String>} [convert]
  1561. * {String[]} [fields] filter fields
  1562. * {function} [filter] filter items
  1563. * {String | function} [order] Order the items by
  1564. * a field name or custom sort function.
  1565. * @return {Object[]} mappedItems
  1566. */
  1567. DataSet.prototype.map = function (callback, options) {
  1568. var filter = options && options.filter,
  1569. convert = options && options.convert || this.options.convert,
  1570. mappedItems = [],
  1571. data = this.data,
  1572. item;
  1573. // convert and filter items
  1574. for (var id in data) {
  1575. if (data.hasOwnProperty(id)) {
  1576. item = this._getItem(id, convert);
  1577. if (!filter || filter(item)) {
  1578. mappedItems.push(callback(item, id));
  1579. }
  1580. }
  1581. }
  1582. // order items
  1583. if (options && options.order) {
  1584. this._sort(mappedItems, options.order);
  1585. }
  1586. return mappedItems;
  1587. };
  1588. /**
  1589. * Filter the fields of an item
  1590. * @param {Object} item
  1591. * @param {String[]} fields Field names
  1592. * @return {Object} filteredItem
  1593. * @private
  1594. */
  1595. DataSet.prototype._filterFields = function (item, fields) {
  1596. var filteredItem = {};
  1597. for (var field in item) {
  1598. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1599. filteredItem[field] = item[field];
  1600. }
  1601. }
  1602. return filteredItem;
  1603. };
  1604. /**
  1605. * Sort the provided array with items
  1606. * @param {Object[]} items
  1607. * @param {String | function} order A field name or custom sort function.
  1608. * @private
  1609. */
  1610. DataSet.prototype._sort = function (items, order) {
  1611. if (util.isString(order)) {
  1612. // order by provided field name
  1613. var name = order; // field name
  1614. items.sort(function (a, b) {
  1615. var av = a[name];
  1616. var bv = b[name];
  1617. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1618. });
  1619. }
  1620. else if (typeof order === 'function') {
  1621. // order by sort function
  1622. items.sort(order);
  1623. }
  1624. // TODO: extend order by an Object {field:String, direction:String}
  1625. // where direction can be 'asc' or 'desc'
  1626. else {
  1627. throw new TypeError('Order must be a function or a string');
  1628. }
  1629. };
  1630. /**
  1631. * Remove an object by pointer or by id
  1632. * @param {String | Number | Object | Array} id Object or id, or an array with
  1633. * objects or ids to be removed
  1634. * @param {String} [senderId] Optional sender id
  1635. * @return {Array} removedIds
  1636. */
  1637. DataSet.prototype.remove = function (id, senderId) {
  1638. var removedIds = [],
  1639. i, len, removedId;
  1640. if (id instanceof Array) {
  1641. for (i = 0, len = id.length; i < len; i++) {
  1642. removedId = this._remove(id[i]);
  1643. if (removedId != null) {
  1644. removedIds.push(removedId);
  1645. }
  1646. }
  1647. }
  1648. else {
  1649. removedId = this._remove(id);
  1650. if (removedId != null) {
  1651. removedIds.push(removedId);
  1652. }
  1653. }
  1654. if (removedIds.length) {
  1655. this._trigger('remove', {items: removedIds}, senderId);
  1656. }
  1657. return removedIds;
  1658. };
  1659. /**
  1660. * Remove an item by its id
  1661. * @param {Number | String | Object} id id or item
  1662. * @returns {Number | String | null} id
  1663. * @private
  1664. */
  1665. DataSet.prototype._remove = function (id) {
  1666. if (util.isNumber(id) || util.isString(id)) {
  1667. if (this.data[id]) {
  1668. delete this.data[id];
  1669. delete this.internalIds[id];
  1670. return id;
  1671. }
  1672. }
  1673. else if (id instanceof Object) {
  1674. var itemId = id[this.fieldId];
  1675. if (itemId && this.data[itemId]) {
  1676. delete this.data[itemId];
  1677. delete this.internalIds[itemId];
  1678. return itemId;
  1679. }
  1680. }
  1681. return null;
  1682. };
  1683. /**
  1684. * Clear the data
  1685. * @param {String} [senderId] Optional sender id
  1686. * @return {Array} removedIds The ids of all removed items
  1687. */
  1688. DataSet.prototype.clear = function (senderId) {
  1689. var ids = Object.keys(this.data);
  1690. this.data = {};
  1691. this.internalIds = {};
  1692. this._trigger('remove', {items: ids}, senderId);
  1693. return ids;
  1694. };
  1695. /**
  1696. * Find the item with maximum value of a specified field
  1697. * @param {String} field
  1698. * @return {Object | null} item Item containing max value, or null if no items
  1699. */
  1700. DataSet.prototype.max = function (field) {
  1701. var data = this.data,
  1702. max = null,
  1703. maxField = null;
  1704. for (var id in data) {
  1705. if (data.hasOwnProperty(id)) {
  1706. var item = data[id];
  1707. var itemField = item[field];
  1708. if (itemField != null && (!max || itemField > maxField)) {
  1709. max = item;
  1710. maxField = itemField;
  1711. }
  1712. }
  1713. }
  1714. return max;
  1715. };
  1716. /**
  1717. * Find the item with minimum value of a specified field
  1718. * @param {String} field
  1719. * @return {Object | null} item Item containing max value, or null if no items
  1720. */
  1721. DataSet.prototype.min = function (field) {
  1722. var data = this.data,
  1723. min = null,
  1724. minField = null;
  1725. for (var id in data) {
  1726. if (data.hasOwnProperty(id)) {
  1727. var item = data[id];
  1728. var itemField = item[field];
  1729. if (itemField != null && (!min || itemField < minField)) {
  1730. min = item;
  1731. minField = itemField;
  1732. }
  1733. }
  1734. }
  1735. return min;
  1736. };
  1737. /**
  1738. * Find all distinct values of a specified field
  1739. * @param {String} field
  1740. * @return {Array} values Array containing all distinct values. If the data
  1741. * items do not contain the specified field, an array
  1742. * containing a single value undefined is returned.
  1743. * The returned array is unordered.
  1744. */
  1745. DataSet.prototype.distinct = function (field) {
  1746. var data = this.data,
  1747. values = [],
  1748. fieldType = this.options.convert[field],
  1749. count = 0;
  1750. for (var prop in data) {
  1751. if (data.hasOwnProperty(prop)) {
  1752. var item = data[prop];
  1753. var value = util.convert(item[field], fieldType);
  1754. var exists = false;
  1755. for (var i = 0; i < count; i++) {
  1756. if (values[i] == value) {
  1757. exists = true;
  1758. break;
  1759. }
  1760. }
  1761. if (!exists) {
  1762. values[count] = value;
  1763. count++;
  1764. }
  1765. }
  1766. }
  1767. return values;
  1768. };
  1769. /**
  1770. * Add a single item. Will fail when an item with the same id already exists.
  1771. * @param {Object} item
  1772. * @return {String} id
  1773. * @private
  1774. */
  1775. DataSet.prototype._addItem = function (item) {
  1776. var id = item[this.fieldId];
  1777. if (id != undefined) {
  1778. // check whether this id is already taken
  1779. if (this.data[id]) {
  1780. // item already exists
  1781. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1782. }
  1783. }
  1784. else {
  1785. // generate an id
  1786. id = util.randomUUID();
  1787. item[this.fieldId] = id;
  1788. this.internalIds[id] = item;
  1789. }
  1790. var d = {};
  1791. for (var field in item) {
  1792. if (item.hasOwnProperty(field)) {
  1793. var fieldType = this.convert[field]; // type may be undefined
  1794. d[field] = util.convert(item[field], fieldType);
  1795. }
  1796. }
  1797. this.data[id] = d;
  1798. return id;
  1799. };
  1800. /**
  1801. * Get an item. Fields can be converted to a specific type
  1802. * @param {String} id
  1803. * @param {Object.<String, String>} [convert] field types to convert
  1804. * @return {Object | null} item
  1805. * @private
  1806. */
  1807. DataSet.prototype._getItem = function (id, convert) {
  1808. var field, value;
  1809. // get the item from the dataset
  1810. var raw = this.data[id];
  1811. if (!raw) {
  1812. return null;
  1813. }
  1814. // convert the items field types
  1815. var converted = {},
  1816. fieldId = this.fieldId,
  1817. internalIds = this.internalIds;
  1818. if (convert) {
  1819. for (field in raw) {
  1820. if (raw.hasOwnProperty(field)) {
  1821. value = raw[field];
  1822. // output all fields, except internal ids
  1823. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1824. converted[field] = util.convert(value, convert[field]);
  1825. }
  1826. }
  1827. }
  1828. }
  1829. else {
  1830. // no field types specified, no converting needed
  1831. for (field in raw) {
  1832. if (raw.hasOwnProperty(field)) {
  1833. value = raw[field];
  1834. // output all fields, except internal ids
  1835. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1836. converted[field] = value;
  1837. }
  1838. }
  1839. }
  1840. }
  1841. return converted;
  1842. };
  1843. /**
  1844. * Update a single item: merge with existing item.
  1845. * Will fail when the item has no id, or when there does not exist an item
  1846. * with the same id.
  1847. * @param {Object} item
  1848. * @return {String} id
  1849. * @private
  1850. */
  1851. DataSet.prototype._updateItem = function (item) {
  1852. var id = item[this.fieldId];
  1853. if (id == undefined) {
  1854. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1855. }
  1856. var d = this.data[id];
  1857. if (!d) {
  1858. // item doesn't exist
  1859. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1860. }
  1861. // merge with current item
  1862. for (var field in item) {
  1863. if (item.hasOwnProperty(field)) {
  1864. var fieldType = this.convert[field]; // type may be undefined
  1865. d[field] = util.convert(item[field], fieldType);
  1866. }
  1867. }
  1868. return id;
  1869. };
  1870. /**
  1871. * check if an id is an internal or external id
  1872. * @param id
  1873. * @returns {boolean}
  1874. * @private
  1875. */
  1876. DataSet.prototype.isInternalId = function(id) {
  1877. return (id in this.internalIds);
  1878. };
  1879. /**
  1880. * Get an array with the column names of a Google DataTable
  1881. * @param {DataTable} dataTable
  1882. * @return {String[]} columnNames
  1883. * @private
  1884. */
  1885. DataSet.prototype._getColumnNames = function (dataTable) {
  1886. var columns = [];
  1887. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1888. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1889. }
  1890. return columns;
  1891. };
  1892. /**
  1893. * Append an item as a row to the dataTable
  1894. * @param dataTable
  1895. * @param columns
  1896. * @param item
  1897. * @private
  1898. */
  1899. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1900. var row = dataTable.addRow();
  1901. for (var col = 0, cols = columns.length; col < cols; col++) {
  1902. var field = columns[col];
  1903. dataTable.setValue(row, col, item[field]);
  1904. }
  1905. };
  1906. /**
  1907. * DataView
  1908. *
  1909. * a dataview offers a filtered view on a dataset or an other dataview.
  1910. *
  1911. * @param {DataSet | DataView} data
  1912. * @param {Object} [options] Available options: see method get
  1913. *
  1914. * @constructor DataView
  1915. */
  1916. function DataView (data, options) {
  1917. this.id = util.randomUUID();
  1918. this.data = null;
  1919. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1920. this.options = options || {};
  1921. this.fieldId = 'id'; // name of the field containing id
  1922. this.subscribers = {}; // event subscribers
  1923. var me = this;
  1924. this.listener = function () {
  1925. me._onEvent.apply(me, arguments);
  1926. };
  1927. this.setData(data);
  1928. }
  1929. // TODO: implement a function .config() to dynamically update things like configured filter
  1930. // and trigger changes accordingly
  1931. /**
  1932. * Set a data source for the view
  1933. * @param {DataSet | DataView} data
  1934. */
  1935. DataView.prototype.setData = function (data) {
  1936. var ids, dataItems, i, len;
  1937. if (this.data) {
  1938. // unsubscribe from current dataset
  1939. if (this.data.unsubscribe) {
  1940. this.data.unsubscribe('*', this.listener);
  1941. }
  1942. // trigger a remove of all items in memory
  1943. ids = [];
  1944. for (var id in this.ids) {
  1945. if (this.ids.hasOwnProperty(id)) {
  1946. ids.push(id);
  1947. }
  1948. }
  1949. this.ids = {};
  1950. this._trigger('remove', {items: ids});
  1951. }
  1952. this.data = data;
  1953. if (this.data) {
  1954. // update fieldId
  1955. this.fieldId = this.options.fieldId ||
  1956. (this.data && this.data.options && this.data.options.fieldId) ||
  1957. 'id';
  1958. // trigger an add of all added items
  1959. ids = this.data.getIds({filter: this.options && this.options.filter});
  1960. for (i = 0, len = ids.length; i < len; i++) {
  1961. id = ids[i];
  1962. this.ids[id] = true;
  1963. }
  1964. this._trigger('add', {items: ids});
  1965. // subscribe to new dataset
  1966. if (this.data.subscribe) {
  1967. this.data.subscribe('*', this.listener);
  1968. }
  1969. }
  1970. };
  1971. /**
  1972. * Get data from the data view
  1973. *
  1974. * Usage:
  1975. *
  1976. * get()
  1977. * get(options: Object)
  1978. * get(options: Object, data: Array | DataTable)
  1979. *
  1980. * get(id: Number)
  1981. * get(id: Number, options: Object)
  1982. * get(id: Number, options: Object, data: Array | DataTable)
  1983. *
  1984. * get(ids: Number[])
  1985. * get(ids: Number[], options: Object)
  1986. * get(ids: Number[], options: Object, data: Array | DataTable)
  1987. *
  1988. * Where:
  1989. *
  1990. * {Number | String} id The id of an item
  1991. * {Number[] | String{}} ids An array with ids of items
  1992. * {Object} options An Object with options. Available options:
  1993. * {String} [type] Type of data to be returned. Can
  1994. * be 'DataTable' or 'Array' (default)
  1995. * {Object.<String, String>} [convert]
  1996. * {String[]} [fields] field names to be returned
  1997. * {function} [filter] filter items
  1998. * {String | function} [order] Order the items by
  1999. * a field name or custom sort function.
  2000. * {Array | DataTable} [data] If provided, items will be appended to this
  2001. * array or table. Required in case of Google
  2002. * DataTable.
  2003. * @param args
  2004. */
  2005. DataView.prototype.get = function (args) {
  2006. var me = this;
  2007. // parse the arguments
  2008. var ids, options, data;
  2009. var firstType = util.getType(arguments[0]);
  2010. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2011. // get(id(s) [, options] [, data])
  2012. ids = arguments[0]; // can be a single id or an array with ids
  2013. options = arguments[1];
  2014. data = arguments[2];
  2015. }
  2016. else {
  2017. // get([, options] [, data])
  2018. options = arguments[0];
  2019. data = arguments[1];
  2020. }
  2021. // extend the options with the default options and provided options
  2022. var viewOptions = util.extend({}, this.options, options);
  2023. // create a combined filter method when needed
  2024. if (this.options.filter && options && options.filter) {
  2025. viewOptions.filter = function (item) {
  2026. return me.options.filter(item) && options.filter(item);
  2027. }
  2028. }
  2029. // build up the call to the linked data set
  2030. var getArguments = [];
  2031. if (ids != undefined) {
  2032. getArguments.push(ids);
  2033. }
  2034. getArguments.push(viewOptions);
  2035. getArguments.push(data);
  2036. return this.data && this.data.get.apply(this.data, getArguments);
  2037. };
  2038. /**
  2039. * Get ids of all items or from a filtered set of items.
  2040. * @param {Object} [options] An Object with options. Available options:
  2041. * {function} [filter] filter items
  2042. * {String | function} [order] Order the items by
  2043. * a field name or custom sort function.
  2044. * @return {Array} ids
  2045. */
  2046. DataView.prototype.getIds = function (options) {
  2047. var ids;
  2048. if (this.data) {
  2049. var defaultFilter = this.options.filter;
  2050. var filter;
  2051. if (options && options.filter) {
  2052. if (defaultFilter) {
  2053. filter = function (item) {
  2054. return defaultFilter(item) && options.filter(item);
  2055. }
  2056. }
  2057. else {
  2058. filter = options.filter;
  2059. }
  2060. }
  2061. else {
  2062. filter = defaultFilter;
  2063. }
  2064. ids = this.data.getIds({
  2065. filter: filter,
  2066. order: options && options.order
  2067. });
  2068. }
  2069. else {
  2070. ids = [];
  2071. }
  2072. return ids;
  2073. };
  2074. /**
  2075. * Event listener. Will propagate all events from the connected data set to
  2076. * the subscribers of the DataView, but will filter the items and only trigger
  2077. * when there are changes in the filtered data set.
  2078. * @param {String} event
  2079. * @param {Object | null} params
  2080. * @param {String} senderId
  2081. * @private
  2082. */
  2083. DataView.prototype._onEvent = function (event, params, senderId) {
  2084. var i, len, id, item,
  2085. ids = params && params.items,
  2086. data = this.data,
  2087. added = [],
  2088. updated = [],
  2089. removed = [];
  2090. if (ids && data) {
  2091. switch (event) {
  2092. case 'add':
  2093. // filter the ids of the added items
  2094. for (i = 0, len = ids.length; i < len; i++) {
  2095. id = ids[i];
  2096. item = this.get(id);
  2097. if (item) {
  2098. this.ids[id] = true;
  2099. added.push(id);
  2100. }
  2101. }
  2102. break;
  2103. case 'update':
  2104. // determine the event from the views viewpoint: an updated
  2105. // item can be added, updated, or removed from this view.
  2106. for (i = 0, len = ids.length; i < len; i++) {
  2107. id = ids[i];
  2108. item = this.get(id);
  2109. if (item) {
  2110. if (this.ids[id]) {
  2111. updated.push(id);
  2112. }
  2113. else {
  2114. this.ids[id] = true;
  2115. added.push(id);
  2116. }
  2117. }
  2118. else {
  2119. if (this.ids[id]) {
  2120. delete this.ids[id];
  2121. removed.push(id);
  2122. }
  2123. else {
  2124. // nothing interesting for me :-(
  2125. }
  2126. }
  2127. }
  2128. break;
  2129. case 'remove':
  2130. // filter the ids of the removed items
  2131. for (i = 0, len = ids.length; i < len; i++) {
  2132. id = ids[i];
  2133. if (this.ids[id]) {
  2134. delete this.ids[id];
  2135. removed.push(id);
  2136. }
  2137. }
  2138. break;
  2139. }
  2140. if (added.length) {
  2141. this._trigger('add', {items: added}, senderId);
  2142. }
  2143. if (updated.length) {
  2144. this._trigger('update', {items: updated}, senderId);
  2145. }
  2146. if (removed.length) {
  2147. this._trigger('remove', {items: removed}, senderId);
  2148. }
  2149. }
  2150. };
  2151. // copy subscription functionality from DataSet
  2152. DataView.prototype.subscribe = DataSet.prototype.subscribe;
  2153. DataView.prototype.unsubscribe = DataSet.prototype.unsubscribe;
  2154. DataView.prototype._trigger = DataSet.prototype._trigger;
  2155. /**
  2156. * @constructor TimeStep
  2157. * The class TimeStep is an iterator for dates. You provide a start date and an
  2158. * end date. The class itself determines the best scale (step size) based on the
  2159. * provided start Date, end Date, and minimumStep.
  2160. *
  2161. * If minimumStep is provided, the step size is chosen as close as possible
  2162. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2163. * provided, the scale is set to 1 DAY.
  2164. * The minimumStep should correspond with the onscreen size of about 6 characters
  2165. *
  2166. * Alternatively, you can set a scale by hand.
  2167. * After creation, you can initialize the class by executing first(). Then you
  2168. * can iterate from the start date to the end date via next(). You can check if
  2169. * the end date is reached with the function hasNext(). After each step, you can
  2170. * retrieve the current date via getCurrent().
  2171. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2172. * days, to years.
  2173. *
  2174. * Version: 1.2
  2175. *
  2176. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2177. * or new Date(2010, 9, 21, 23, 45, 00)
  2178. * @param {Date} [end] The end date
  2179. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2180. */
  2181. TimeStep = function(start, end, minimumStep) {
  2182. // variables
  2183. this.current = new Date();
  2184. this._start = new Date();
  2185. this._end = new Date();
  2186. this.autoScale = true;
  2187. this.scale = TimeStep.SCALE.DAY;
  2188. this.step = 1;
  2189. // initialize the range
  2190. this.setRange(start, end, minimumStep);
  2191. };
  2192. /// enum scale
  2193. TimeStep.SCALE = {
  2194. MILLISECOND: 1,
  2195. SECOND: 2,
  2196. MINUTE: 3,
  2197. HOUR: 4,
  2198. DAY: 5,
  2199. WEEKDAY: 6,
  2200. MONTH: 7,
  2201. YEAR: 8
  2202. };
  2203. /**
  2204. * Set a new range
  2205. * If minimumStep is provided, the step size is chosen as close as possible
  2206. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2207. * provided, the scale is set to 1 DAY.
  2208. * The minimumStep should correspond with the onscreen size of about 6 characters
  2209. * @param {Date} [start] The start date and time.
  2210. * @param {Date} [end] The end date and time.
  2211. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2212. */
  2213. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2214. if (!(start instanceof Date) || !(end instanceof Date)) {
  2215. throw "No legal start or end date in method setRange";
  2216. }
  2217. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2218. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2219. if (this.autoScale) {
  2220. this.setMinimumStep(minimumStep);
  2221. }
  2222. };
  2223. /**
  2224. * Set the range iterator to the start date.
  2225. */
  2226. TimeStep.prototype.first = function() {
  2227. this.current = new Date(this._start.valueOf());
  2228. this.roundToMinor();
  2229. };
  2230. /**
  2231. * Round the current date to the first minor date value
  2232. * This must be executed once when the current date is set to start Date
  2233. */
  2234. TimeStep.prototype.roundToMinor = function() {
  2235. // round to floor
  2236. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2237. //noinspection FallthroughInSwitchStatementJS
  2238. switch (this.scale) {
  2239. case TimeStep.SCALE.YEAR:
  2240. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2241. this.current.setMonth(0);
  2242. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2243. case TimeStep.SCALE.DAY: // intentional fall through
  2244. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2245. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2246. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2247. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2248. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2249. }
  2250. if (this.step != 1) {
  2251. // round down to the first minor value that is a multiple of the current step size
  2252. switch (this.scale) {
  2253. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2254. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2255. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2256. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2257. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2258. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2259. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2260. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2261. default: break;
  2262. }
  2263. }
  2264. };
  2265. /**
  2266. * Check if the there is a next step
  2267. * @return {boolean} true if the current date has not passed the end date
  2268. */
  2269. TimeStep.prototype.hasNext = function () {
  2270. return (this.current.valueOf() <= this._end.valueOf());
  2271. };
  2272. /**
  2273. * Do the next step
  2274. */
  2275. TimeStep.prototype.next = function() {
  2276. var prev = this.current.valueOf();
  2277. // Two cases, needed to prevent issues with switching daylight savings
  2278. // (end of March and end of October)
  2279. if (this.current.getMonth() < 6) {
  2280. switch (this.scale) {
  2281. case TimeStep.SCALE.MILLISECOND:
  2282. this.current = new Date(this.current.valueOf() + this.step); break;
  2283. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2284. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2285. case TimeStep.SCALE.HOUR:
  2286. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2287. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2288. var h = this.current.getHours();
  2289. this.current.setHours(h - (h % this.step));
  2290. break;
  2291. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2292. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2293. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2294. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2295. default: break;
  2296. }
  2297. }
  2298. else {
  2299. switch (this.scale) {
  2300. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2301. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2302. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2303. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2304. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2305. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2306. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2307. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2308. default: break;
  2309. }
  2310. }
  2311. if (this.step != 1) {
  2312. // round down to the correct major value
  2313. switch (this.scale) {
  2314. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2315. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2316. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2317. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2318. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2319. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2320. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2321. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2322. default: break;
  2323. }
  2324. }
  2325. // safety mechanism: if current time is still unchanged, move to the end
  2326. if (this.current.valueOf() == prev) {
  2327. this.current = new Date(this._end.valueOf());
  2328. }
  2329. };
  2330. /**
  2331. * Get the current datetime
  2332. * @return {Date} current The current date
  2333. */
  2334. TimeStep.prototype.getCurrent = function() {
  2335. return this.current;
  2336. };
  2337. /**
  2338. * Set a custom scale. Autoscaling will be disabled.
  2339. * For example setScale(SCALE.MINUTES, 5) will result
  2340. * in minor steps of 5 minutes, and major steps of an hour.
  2341. *
  2342. * @param {TimeStep.SCALE} newScale
  2343. * A scale. Choose from SCALE.MILLISECOND,
  2344. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2345. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2346. * SCALE.YEAR.
  2347. * @param {Number} newStep A step size, by default 1. Choose for
  2348. * example 1, 2, 5, or 10.
  2349. */
  2350. TimeStep.prototype.setScale = function(newScale, newStep) {
  2351. this.scale = newScale;
  2352. if (newStep > 0) {
  2353. this.step = newStep;
  2354. }
  2355. this.autoScale = false;
  2356. };
  2357. /**
  2358. * Enable or disable autoscaling
  2359. * @param {boolean} enable If true, autoascaling is set true
  2360. */
  2361. TimeStep.prototype.setAutoScale = function (enable) {
  2362. this.autoScale = enable;
  2363. };
  2364. /**
  2365. * Automatically determine the scale that bests fits the provided minimum step
  2366. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2367. */
  2368. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2369. if (minimumStep == undefined) {
  2370. return;
  2371. }
  2372. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2373. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2374. var stepDay = (1000 * 60 * 60 * 24);
  2375. var stepHour = (1000 * 60 * 60);
  2376. var stepMinute = (1000 * 60);
  2377. var stepSecond = (1000);
  2378. var stepMillisecond= (1);
  2379. // find the smallest step that is larger than the provided minimumStep
  2380. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2381. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2382. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2383. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2384. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2385. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2386. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2387. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2388. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2389. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2390. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2391. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2392. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2393. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2394. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2395. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2396. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2397. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2398. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2399. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2400. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2401. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2402. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2403. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2404. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2405. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2406. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2407. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2408. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2409. };
  2410. /**
  2411. * Snap a date to a rounded value. The snap intervals are dependent on the
  2412. * current scale and step.
  2413. * @param {Date} date the date to be snapped
  2414. */
  2415. TimeStep.prototype.snap = function(date) {
  2416. if (this.scale == TimeStep.SCALE.YEAR) {
  2417. var year = date.getFullYear() + Math.round(date.getMonth() / 12);
  2418. date.setFullYear(Math.round(year / this.step) * this.step);
  2419. date.setMonth(0);
  2420. date.setDate(0);
  2421. date.setHours(0);
  2422. date.setMinutes(0);
  2423. date.setSeconds(0);
  2424. date.setMilliseconds(0);
  2425. }
  2426. else if (this.scale == TimeStep.SCALE.MONTH) {
  2427. if (date.getDate() > 15) {
  2428. date.setDate(1);
  2429. date.setMonth(date.getMonth() + 1);
  2430. // important: first set Date to 1, after that change the month.
  2431. }
  2432. else {
  2433. date.setDate(1);
  2434. }
  2435. date.setHours(0);
  2436. date.setMinutes(0);
  2437. date.setSeconds(0);
  2438. date.setMilliseconds(0);
  2439. }
  2440. else if (this.scale == TimeStep.SCALE.DAY ||
  2441. this.scale == TimeStep.SCALE.WEEKDAY) {
  2442. //noinspection FallthroughInSwitchStatementJS
  2443. switch (this.step) {
  2444. case 5:
  2445. case 2:
  2446. date.setHours(Math.round(date.getHours() / 24) * 24); break;
  2447. default:
  2448. date.setHours(Math.round(date.getHours() / 12) * 12); break;
  2449. }
  2450. date.setMinutes(0);
  2451. date.setSeconds(0);
  2452. date.setMilliseconds(0);
  2453. }
  2454. else if (this.scale == TimeStep.SCALE.HOUR) {
  2455. switch (this.step) {
  2456. case 4:
  2457. date.setMinutes(Math.round(date.getMinutes() / 60) * 60); break;
  2458. default:
  2459. date.setMinutes(Math.round(date.getMinutes() / 30) * 30); break;
  2460. }
  2461. date.setSeconds(0);
  2462. date.setMilliseconds(0);
  2463. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2464. //noinspection FallthroughInSwitchStatementJS
  2465. switch (this.step) {
  2466. case 15:
  2467. case 10:
  2468. date.setMinutes(Math.round(date.getMinutes() / 5) * 5);
  2469. date.setSeconds(0);
  2470. break;
  2471. case 5:
  2472. date.setSeconds(Math.round(date.getSeconds() / 60) * 60); break;
  2473. default:
  2474. date.setSeconds(Math.round(date.getSeconds() / 30) * 30); break;
  2475. }
  2476. date.setMilliseconds(0);
  2477. }
  2478. else if (this.scale == TimeStep.SCALE.SECOND) {
  2479. //noinspection FallthroughInSwitchStatementJS
  2480. switch (this.step) {
  2481. case 15:
  2482. case 10:
  2483. date.setSeconds(Math.round(date.getSeconds() / 5) * 5);
  2484. date.setMilliseconds(0);
  2485. break;
  2486. case 5:
  2487. date.setMilliseconds(Math.round(date.getMilliseconds() / 1000) * 1000); break;
  2488. default:
  2489. date.setMilliseconds(Math.round(date.getMilliseconds() / 500) * 500); break;
  2490. }
  2491. }
  2492. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2493. var step = this.step > 5 ? this.step / 2 : 1;
  2494. date.setMilliseconds(Math.round(date.getMilliseconds() / step) * step);
  2495. }
  2496. };
  2497. /**
  2498. * Check if the current value is a major value (for example when the step
  2499. * is DAY, a major value is each first day of the MONTH)
  2500. * @return {boolean} true if current date is major, else false.
  2501. */
  2502. TimeStep.prototype.isMajor = function() {
  2503. switch (this.scale) {
  2504. case TimeStep.SCALE.MILLISECOND:
  2505. return (this.current.getMilliseconds() == 0);
  2506. case TimeStep.SCALE.SECOND:
  2507. return (this.current.getSeconds() == 0);
  2508. case TimeStep.SCALE.MINUTE:
  2509. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2510. // Note: this is no bug. Major label is equal for both minute and hour scale
  2511. case TimeStep.SCALE.HOUR:
  2512. return (this.current.getHours() == 0);
  2513. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2514. case TimeStep.SCALE.DAY:
  2515. return (this.current.getDate() == 1);
  2516. case TimeStep.SCALE.MONTH:
  2517. return (this.current.getMonth() == 0);
  2518. case TimeStep.SCALE.YEAR:
  2519. return false;
  2520. default:
  2521. return false;
  2522. }
  2523. };
  2524. /**
  2525. * Returns formatted text for the minor axislabel, depending on the current
  2526. * date and the scale. For example when scale is MINUTE, the current time is
  2527. * formatted as "hh:mm".
  2528. * @param {Date} [date] custom date. if not provided, current date is taken
  2529. */
  2530. TimeStep.prototype.getLabelMinor = function(date) {
  2531. if (date == undefined) {
  2532. date = this.current;
  2533. }
  2534. switch (this.scale) {
  2535. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2536. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2537. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2538. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2539. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2540. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2541. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2542. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2543. default: return '';
  2544. }
  2545. };
  2546. /**
  2547. * Returns formatted text for the major axis label, depending on the current
  2548. * date and the scale. For example when scale is MINUTE, the major scale is
  2549. * hours, and the hour will be formatted as "hh".
  2550. * @param {Date} [date] custom date. if not provided, current date is taken
  2551. */
  2552. TimeStep.prototype.getLabelMajor = function(date) {
  2553. if (date == undefined) {
  2554. date = this.current;
  2555. }
  2556. //noinspection FallthroughInSwitchStatementJS
  2557. switch (this.scale) {
  2558. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2559. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2560. case TimeStep.SCALE.MINUTE:
  2561. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2562. case TimeStep.SCALE.WEEKDAY:
  2563. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2564. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2565. case TimeStep.SCALE.YEAR: return '';
  2566. default: return '';
  2567. }
  2568. };
  2569. /**
  2570. * @constructor Stack
  2571. * Stacks items on top of each other.
  2572. * @param {ItemSet} parent
  2573. * @param {Object} [options]
  2574. */
  2575. function Stack (parent, options) {
  2576. this.parent = parent;
  2577. this.options = options || {};
  2578. this.defaultOptions = {
  2579. order: function (a, b) {
  2580. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  2581. // Order: ranges over non-ranges, ranged ordered by width, and
  2582. // lastly ordered by start.
  2583. if (a instanceof ItemRange) {
  2584. if (b instanceof ItemRange) {
  2585. var aInt = (a.data.end - a.data.start);
  2586. var bInt = (b.data.end - b.data.start);
  2587. return (aInt - bInt) || (a.data.start - b.data.start);
  2588. }
  2589. else {
  2590. return -1;
  2591. }
  2592. }
  2593. else {
  2594. if (b instanceof ItemRange) {
  2595. return 1;
  2596. }
  2597. else {
  2598. return (a.data.start - b.data.start);
  2599. }
  2600. }
  2601. },
  2602. margin: {
  2603. item: 10
  2604. }
  2605. };
  2606. this.ordered = []; // ordered items
  2607. }
  2608. /**
  2609. * Set options for the stack
  2610. * @param {Object} options Available options:
  2611. * {ItemSet} parent
  2612. * {Number} margin
  2613. * {function} order Stacking order
  2614. */
  2615. Stack.prototype.setOptions = function setOptions (options) {
  2616. util.extend(this.options, options);
  2617. // TODO: register on data changes at the connected parent itemset, and update the changed part only and immediately
  2618. };
  2619. /**
  2620. * Stack the items such that they don't overlap. The items will have a minimal
  2621. * distance equal to options.margin.item.
  2622. */
  2623. Stack.prototype.update = function update() {
  2624. this._order();
  2625. this._stack();
  2626. };
  2627. /**
  2628. * Order the items. The items are ordered by width first, and by left position
  2629. * second.
  2630. * If a custom order function has been provided via the options, then this will
  2631. * be used.
  2632. * @private
  2633. */
  2634. Stack.prototype._order = function _order () {
  2635. var items = this.parent.items;
  2636. if (!items) {
  2637. throw new Error('Cannot stack items: parent does not contain items');
  2638. }
  2639. // TODO: store the sorted items, to have less work later on
  2640. var ordered = [];
  2641. var index = 0;
  2642. // items is a map (no array)
  2643. util.forEach(items, function (item) {
  2644. if (item.visible) {
  2645. ordered[index] = item;
  2646. index++;
  2647. }
  2648. });
  2649. //if a customer stack order function exists, use it.
  2650. var order = this.options.order || this.defaultOptions.order;
  2651. if (!(typeof order === 'function')) {
  2652. throw new Error('Option order must be a function');
  2653. }
  2654. ordered.sort(order);
  2655. this.ordered = ordered;
  2656. };
  2657. /**
  2658. * Adjust vertical positions of the events such that they don't overlap each
  2659. * other.
  2660. * @private
  2661. */
  2662. Stack.prototype._stack = function _stack () {
  2663. var i,
  2664. iMax,
  2665. ordered = this.ordered,
  2666. options = this.options,
  2667. orientation = options.orientation || this.defaultOptions.orientation,
  2668. axisOnTop = (orientation == 'top'),
  2669. margin;
  2670. if (options.margin && options.margin.item !== undefined) {
  2671. margin = options.margin.item;
  2672. }
  2673. else {
  2674. margin = this.defaultOptions.margin.item
  2675. }
  2676. // calculate new, non-overlapping positions
  2677. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  2678. var item = ordered[i];
  2679. var collidingItem = null;
  2680. do {
  2681. // TODO: optimize checking for overlap. when there is a gap without items,
  2682. // you only need to check for items from the next item on, not from zero
  2683. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  2684. if (collidingItem != null) {
  2685. // There is a collision. Reposition the event above the colliding element
  2686. if (axisOnTop) {
  2687. item.top = collidingItem.top + collidingItem.height + margin;
  2688. }
  2689. else {
  2690. item.top = collidingItem.top - item.height - margin;
  2691. }
  2692. }
  2693. } while (collidingItem);
  2694. }
  2695. };
  2696. /**
  2697. * Check if the destiny position of given item overlaps with any
  2698. * of the other items from index itemStart to itemEnd.
  2699. * @param {Array} items Array with items
  2700. * @param {int} itemIndex Number of the item to be checked for overlap
  2701. * @param {int} itemStart First item to be checked.
  2702. * @param {int} itemEnd Last item to be checked.
  2703. * @return {Object | null} colliding item, or undefined when no collisions
  2704. * @param {Number} margin A minimum required margin.
  2705. * If margin is provided, the two items will be
  2706. * marked colliding when they overlap or
  2707. * when the margin between the two is smaller than
  2708. * the requested margin.
  2709. */
  2710. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  2711. itemStart, itemEnd, margin) {
  2712. var collision = this.collision;
  2713. // we loop from end to start, as we suppose that the chance of a
  2714. // collision is larger for items at the end, so check these first.
  2715. var a = items[itemIndex];
  2716. for (var i = itemEnd; i >= itemStart; i--) {
  2717. var b = items[i];
  2718. if (collision(a, b, margin)) {
  2719. if (i != itemIndex) {
  2720. return b;
  2721. }
  2722. }
  2723. }
  2724. return null;
  2725. };
  2726. /**
  2727. * Test if the two provided items collide
  2728. * The items must have parameters left, width, top, and height.
  2729. * @param {Component} a The first item
  2730. * @param {Component} b The second item
  2731. * @param {Number} margin A minimum required margin.
  2732. * If margin is provided, the two items will be
  2733. * marked colliding when they overlap or
  2734. * when the margin between the two is smaller than
  2735. * the requested margin.
  2736. * @return {boolean} true if a and b collide, else false
  2737. */
  2738. Stack.prototype.collision = function collision (a, b, margin) {
  2739. return ((a.left - margin) < (b.left + b.getWidth()) &&
  2740. (a.left + a.getWidth() + margin) > b.left &&
  2741. (a.top - margin) < (b.top + b.height) &&
  2742. (a.top + a.height + margin) > b.top);
  2743. };
  2744. /**
  2745. * @constructor Range
  2746. * A Range controls a numeric range with a start and end value.
  2747. * The Range adjusts the range based on mouse events or programmatic changes,
  2748. * and triggers events when the range is changing or has been changed.
  2749. * @param {Object} [options] See description at Range.setOptions
  2750. * @extends Controller
  2751. */
  2752. function Range(options) {
  2753. this.id = util.randomUUID();
  2754. this.start = null; // Number
  2755. this.end = null; // Number
  2756. this.options = options || {};
  2757. this.setOptions(options);
  2758. }
  2759. /**
  2760. * Set options for the range controller
  2761. * @param {Object} options Available options:
  2762. * {Number} min Minimum value for start
  2763. * {Number} max Maximum value for end
  2764. * {Number} zoomMin Set a minimum value for
  2765. * (end - start).
  2766. * {Number} zoomMax Set a maximum value for
  2767. * (end - start).
  2768. */
  2769. Range.prototype.setOptions = function (options) {
  2770. util.extend(this.options, options);
  2771. // re-apply range with new limitations
  2772. if (this.start !== null && this.end !== null) {
  2773. this.setRange(this.start, this.end);
  2774. }
  2775. };
  2776. /**
  2777. * Test whether direction has a valid value
  2778. * @param {String} direction 'horizontal' or 'vertical'
  2779. */
  2780. function validateDirection (direction) {
  2781. if (direction != 'horizontal' && direction != 'vertical') {
  2782. throw new TypeError('Unknown direction "' + direction + '". ' +
  2783. 'Choose "horizontal" or "vertical".');
  2784. }
  2785. }
  2786. /**
  2787. * Add listeners for mouse and touch events to the component
  2788. * @param {Component} component
  2789. * @param {String} event Available events: 'move', 'zoom'
  2790. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2791. */
  2792. Range.prototype.subscribe = function (component, event, direction) {
  2793. var me = this;
  2794. if (event == 'move') {
  2795. // drag start listener
  2796. component.on('dragstart', function (event) {
  2797. me._onDragStart(event, component);
  2798. });
  2799. // drag listener
  2800. component.on('drag', function (event) {
  2801. me._onDrag(event, component, direction);
  2802. });
  2803. // drag end listener
  2804. component.on('dragend', function (event) {
  2805. me._onDragEnd(event, component);
  2806. });
  2807. }
  2808. else if (event == 'zoom') {
  2809. // mouse wheel
  2810. function mousewheel (event) {
  2811. me._onMouseWheel(event, component, direction);
  2812. }
  2813. component.on('mousewheel', mousewheel);
  2814. component.on('DOMMouseScroll', mousewheel); // For FF
  2815. // pinch
  2816. component.on('touch', function (event) {
  2817. me._onTouch();
  2818. });
  2819. component.on('pinch', function (event) {
  2820. me._onPinch(event, component, direction);
  2821. });
  2822. }
  2823. else {
  2824. throw new TypeError('Unknown event "' + event + '". ' +
  2825. 'Choose "move" or "zoom".');
  2826. }
  2827. };
  2828. /**
  2829. * Event handler
  2830. * @param {String} event name of the event, for example 'click', 'mousemove'
  2831. * @param {function} callback callback handler, invoked with the raw HTML Event
  2832. * as parameter.
  2833. */
  2834. Range.prototype.on = function (event, callback) {
  2835. events.addListener(this, event, callback);
  2836. };
  2837. /**
  2838. * Trigger an event
  2839. * @param {String} event name of the event, available events: 'rangechange',
  2840. * 'rangechanged'
  2841. * @private
  2842. */
  2843. Range.prototype._trigger = function (event) {
  2844. events.trigger(this, event, {
  2845. start: this.start,
  2846. end: this.end
  2847. });
  2848. };
  2849. /**
  2850. * Set a new start and end range
  2851. * @param {Number} [start]
  2852. * @param {Number} [end]
  2853. */
  2854. Range.prototype.setRange = function(start, end) {
  2855. var changed = this._applyRange(start, end);
  2856. if (changed) {
  2857. this._trigger('rangechange');
  2858. this._trigger('rangechanged');
  2859. }
  2860. };
  2861. /**
  2862. * Set a new start and end range. This method is the same as setRange, but
  2863. * does not trigger a range change and range changed event, and it returns
  2864. * true when the range is changed
  2865. * @param {Number} [start]
  2866. * @param {Number} [end]
  2867. * @return {Boolean} changed
  2868. * @private
  2869. */
  2870. Range.prototype._applyRange = function(start, end) {
  2871. var newStart = (start != null) ? util.convert(start, 'Number') : this.start,
  2872. newEnd = (end != null) ? util.convert(end, 'Number') : this.end,
  2873. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2874. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2875. diff;
  2876. // check for valid number
  2877. if (isNaN(newStart) || newStart === null) {
  2878. throw new Error('Invalid start "' + start + '"');
  2879. }
  2880. if (isNaN(newEnd) || newEnd === null) {
  2881. throw new Error('Invalid end "' + end + '"');
  2882. }
  2883. // prevent start < end
  2884. if (newEnd < newStart) {
  2885. newEnd = newStart;
  2886. }
  2887. // prevent start < min
  2888. if (min !== null) {
  2889. if (newStart < min) {
  2890. diff = (min - newStart);
  2891. newStart += diff;
  2892. newEnd += diff;
  2893. // prevent end > max
  2894. if (max != null) {
  2895. if (newEnd > max) {
  2896. newEnd = max;
  2897. }
  2898. }
  2899. }
  2900. }
  2901. // prevent end > max
  2902. if (max !== null) {
  2903. if (newEnd > max) {
  2904. diff = (newEnd - max);
  2905. newStart -= diff;
  2906. newEnd -= diff;
  2907. // prevent start < min
  2908. if (min != null) {
  2909. if (newStart < min) {
  2910. newStart = min;
  2911. }
  2912. }
  2913. }
  2914. }
  2915. // prevent (end-start) < zoomMin
  2916. if (this.options.zoomMin !== null) {
  2917. var zoomMin = parseFloat(this.options.zoomMin);
  2918. if (zoomMin < 0) {
  2919. zoomMin = 0;
  2920. }
  2921. if ((newEnd - newStart) < zoomMin) {
  2922. if ((this.end - this.start) === zoomMin) {
  2923. // ignore this action, we are already zoomed to the minimum
  2924. newStart = this.start;
  2925. newEnd = this.end;
  2926. }
  2927. else {
  2928. // zoom to the minimum
  2929. diff = (zoomMin - (newEnd - newStart));
  2930. newStart -= diff / 2;
  2931. newEnd += diff / 2;
  2932. }
  2933. }
  2934. }
  2935. // prevent (end-start) > zoomMax
  2936. if (this.options.zoomMax !== null) {
  2937. var zoomMax = parseFloat(this.options.zoomMax);
  2938. if (zoomMax < 0) {
  2939. zoomMax = 0;
  2940. }
  2941. if ((newEnd - newStart) > zoomMax) {
  2942. if ((this.end - this.start) === zoomMax) {
  2943. // ignore this action, we are already zoomed to the maximum
  2944. newStart = this.start;
  2945. newEnd = this.end;
  2946. }
  2947. else {
  2948. // zoom to the maximum
  2949. diff = ((newEnd - newStart) - zoomMax);
  2950. newStart += diff / 2;
  2951. newEnd -= diff / 2;
  2952. }
  2953. }
  2954. }
  2955. var changed = (this.start != newStart || this.end != newEnd);
  2956. this.start = newStart;
  2957. this.end = newEnd;
  2958. return changed;
  2959. };
  2960. /**
  2961. * Retrieve the current range.
  2962. * @return {Object} An object with start and end properties
  2963. */
  2964. Range.prototype.getRange = function() {
  2965. return {
  2966. start: this.start,
  2967. end: this.end
  2968. };
  2969. };
  2970. /**
  2971. * Calculate the conversion offset and scale for current range, based on
  2972. * the provided width
  2973. * @param {Number} width
  2974. * @returns {{offset: number, scale: number}} conversion
  2975. */
  2976. Range.prototype.conversion = function (width) {
  2977. return Range.conversion(this.start, this.end, width);
  2978. };
  2979. /**
  2980. * Static method to calculate the conversion offset and scale for a range,
  2981. * based on the provided start, end, and width
  2982. * @param {Number} start
  2983. * @param {Number} end
  2984. * @param {Number} width
  2985. * @returns {{offset: number, scale: number}} conversion
  2986. */
  2987. Range.conversion = function (start, end, width) {
  2988. if (width != 0 && (end - start != 0)) {
  2989. return {
  2990. offset: start,
  2991. scale: width / (end - start)
  2992. }
  2993. }
  2994. else {
  2995. return {
  2996. offset: 0,
  2997. scale: 1
  2998. };
  2999. }
  3000. };
  3001. // global (private) object to store drag params
  3002. var touchParams = {};
  3003. /**
  3004. * Start dragging horizontally or vertically
  3005. * @param {Event} event
  3006. * @param {Object} component
  3007. * @private
  3008. */
  3009. Range.prototype._onDragStart = function(event, component) {
  3010. // refuse to drag when we where pinching to prevent the timeline make a jump
  3011. // when releasing the fingers in opposite order from the touch screen
  3012. if (touchParams.pinching) return;
  3013. touchParams.start = this.start;
  3014. touchParams.end = this.end;
  3015. var frame = component.frame;
  3016. if (frame) {
  3017. frame.style.cursor = 'move';
  3018. }
  3019. };
  3020. /**
  3021. * Perform dragging operating.
  3022. * @param {Event} event
  3023. * @param {Component} component
  3024. * @param {String} direction 'horizontal' or 'vertical'
  3025. * @private
  3026. */
  3027. Range.prototype._onDrag = function (event, component, direction) {
  3028. validateDirection(direction);
  3029. // refuse to drag when we where pinching to prevent the timeline make a jump
  3030. // when releasing the fingers in opposite order from the touch screen
  3031. if (touchParams.pinching) return;
  3032. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  3033. interval = (touchParams.end - touchParams.start),
  3034. width = (direction == 'horizontal') ? component.width : component.height,
  3035. diffRange = -delta / width * interval;
  3036. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  3037. // fire a rangechange event
  3038. this._trigger('rangechange');
  3039. };
  3040. /**
  3041. * Stop dragging operating.
  3042. * @param {event} event
  3043. * @param {Component} component
  3044. * @private
  3045. */
  3046. Range.prototype._onDragEnd = function (event, component) {
  3047. // refuse to drag when we where pinching to prevent the timeline make a jump
  3048. // when releasing the fingers in opposite order from the touch screen
  3049. if (touchParams.pinching) return;
  3050. if (component.frame) {
  3051. component.frame.style.cursor = 'auto';
  3052. }
  3053. // fire a rangechanged event
  3054. this._trigger('rangechanged');
  3055. };
  3056. /**
  3057. * Event handler for mouse wheel event, used to zoom
  3058. * Code from http://adomas.org/javascript-mouse-wheel/
  3059. * @param {Event} event
  3060. * @param {Component} component
  3061. * @param {String} direction 'horizontal' or 'vertical'
  3062. * @private
  3063. */
  3064. Range.prototype._onMouseWheel = function(event, component, direction) {
  3065. validateDirection(direction);
  3066. // retrieve delta
  3067. var delta = 0;
  3068. if (event.wheelDelta) { /* IE/Opera. */
  3069. delta = event.wheelDelta / 120;
  3070. } else if (event.detail) { /* Mozilla case. */
  3071. // In Mozilla, sign of delta is different than in IE.
  3072. // Also, delta is multiple of 3.
  3073. delta = -event.detail / 3;
  3074. }
  3075. // If delta is nonzero, handle it.
  3076. // Basically, delta is now positive if wheel was scrolled up,
  3077. // and negative, if wheel was scrolled down.
  3078. if (delta) {
  3079. // perform the zoom action. Delta is normally 1 or -1
  3080. // adjust a negative delta such that zooming in with delta 0.1
  3081. // equals zooming out with a delta -0.1
  3082. var scale;
  3083. if (delta < 0) {
  3084. scale = 1 - (delta / 5);
  3085. }
  3086. else {
  3087. scale = 1 / (1 + (delta / 5)) ;
  3088. }
  3089. // calculate center, the date to zoom around
  3090. var gesture = util.fakeGesture(this, event),
  3091. pointer = getPointer(gesture.touches[0], component.frame),
  3092. pointerDate = this._pointerToDate(component, direction, pointer);
  3093. this.zoom(scale, pointerDate);
  3094. }
  3095. // Prevent default actions caused by mouse wheel
  3096. // (else the page and timeline both zoom and scroll)
  3097. util.preventDefault(event);
  3098. };
  3099. /**
  3100. * On start of a touch gesture, initialize scale to 1
  3101. * @private
  3102. */
  3103. Range.prototype._onTouch = function () {
  3104. touchParams.start = this.start;
  3105. touchParams.end = this.end;
  3106. touchParams.pinching = false;
  3107. touchParams.center = null;
  3108. };
  3109. /**
  3110. * Handle pinch event
  3111. * @param {Event} event
  3112. * @param {Component} component
  3113. * @param {String} direction 'horizontal' or 'vertical'
  3114. * @private
  3115. */
  3116. Range.prototype._onPinch = function (event, component, direction) {
  3117. touchParams.pinching = true;
  3118. if (event.gesture.touches.length > 1) {
  3119. if (!touchParams.center) {
  3120. touchParams.center = getPointer(event.gesture.center, component.frame);
  3121. }
  3122. var scale = 1 / event.gesture.scale,
  3123. initDate = this._pointerToDate(component, direction, touchParams.center),
  3124. center = getPointer(event.gesture.center, component.frame),
  3125. date = this._pointerToDate(component, direction, center),
  3126. delta = date - initDate; // TODO: utilize delta
  3127. // calculate new start and end
  3128. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3129. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3130. // apply new range
  3131. this.setRange(newStart, newEnd);
  3132. }
  3133. };
  3134. /**
  3135. * Helper function to calculate the center date for zooming
  3136. * @param {Component} component
  3137. * @param {{x: Number, y: Number}} pointer
  3138. * @param {String} direction 'horizontal' or 'vertical'
  3139. * @return {number} date
  3140. * @private
  3141. */
  3142. Range.prototype._pointerToDate = function (component, direction, pointer) {
  3143. var conversion;
  3144. if (direction == 'horizontal') {
  3145. var width = component.width;
  3146. conversion = this.conversion(width);
  3147. return pointer.x / conversion.scale + conversion.offset;
  3148. }
  3149. else {
  3150. var height = component.height;
  3151. conversion = this.conversion(height);
  3152. return pointer.y / conversion.scale + conversion.offset;
  3153. }
  3154. };
  3155. /**
  3156. * Get the pointer location relative to the location of the dom element
  3157. * @param {{pageX: Number, pageY: Number}} touch
  3158. * @param {Element} element HTML DOM element
  3159. * @return {{x: Number, y: Number}} pointer
  3160. * @private
  3161. */
  3162. function getPointer (touch, element) {
  3163. return {
  3164. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3165. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3166. };
  3167. }
  3168. /**
  3169. * Zoom the range the given scale in or out. Start and end date will
  3170. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3171. * date around which to zoom.
  3172. * For example, try scale = 0.9 or 1.1
  3173. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3174. * values below 1 will zoom in.
  3175. * @param {Number} [center] Value representing a date around which will
  3176. * be zoomed.
  3177. */
  3178. Range.prototype.zoom = function(scale, center) {
  3179. // if centerDate is not provided, take it half between start Date and end Date
  3180. if (center == null) {
  3181. center = (this.start + this.end) / 2;
  3182. }
  3183. // calculate new start and end
  3184. var newStart = center + (this.start - center) * scale;
  3185. var newEnd = center + (this.end - center) * scale;
  3186. this.setRange(newStart, newEnd);
  3187. };
  3188. /**
  3189. * Move the range with a given delta to the left or right. Start and end
  3190. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3191. * @param {Number} delta Moving amount. Positive value will move right,
  3192. * negative value will move left
  3193. */
  3194. Range.prototype.move = function(delta) {
  3195. // zoom start Date and end Date relative to the centerDate
  3196. var diff = (this.end - this.start);
  3197. // apply new values
  3198. var newStart = this.start + diff * delta;
  3199. var newEnd = this.end + diff * delta;
  3200. // TODO: reckon with min and max range
  3201. this.start = newStart;
  3202. this.end = newEnd;
  3203. };
  3204. /**
  3205. * Move the range to a new center point
  3206. * @param {Number} moveTo New center point of the range
  3207. */
  3208. Range.prototype.moveTo = function(moveTo) {
  3209. var center = (this.start + this.end) / 2;
  3210. var diff = center - moveTo;
  3211. // calculate new start and end
  3212. var newStart = this.start - diff;
  3213. var newEnd = this.end - diff;
  3214. this.setRange(newStart, newEnd);
  3215. };
  3216. /**
  3217. * @constructor Controller
  3218. *
  3219. * A Controller controls the reflows and repaints of all visual components
  3220. */
  3221. function Controller () {
  3222. this.id = util.randomUUID();
  3223. this.components = {};
  3224. this.repaintTimer = undefined;
  3225. this.reflowTimer = undefined;
  3226. }
  3227. /**
  3228. * Add a component to the controller
  3229. * @param {Component} component
  3230. */
  3231. Controller.prototype.add = function add(component) {
  3232. // validate the component
  3233. if (component.id == undefined) {
  3234. throw new Error('Component has no field id');
  3235. }
  3236. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3237. throw new TypeError('Component must be an instance of ' +
  3238. 'prototype Component or Controller');
  3239. }
  3240. // add the component
  3241. component.controller = this;
  3242. this.components[component.id] = component;
  3243. };
  3244. /**
  3245. * Remove a component from the controller
  3246. * @param {Component | String} component
  3247. */
  3248. Controller.prototype.remove = function remove(component) {
  3249. var id;
  3250. for (id in this.components) {
  3251. if (this.components.hasOwnProperty(id)) {
  3252. if (id == component || this.components[id] == component) {
  3253. break;
  3254. }
  3255. }
  3256. }
  3257. if (id) {
  3258. delete this.components[id];
  3259. }
  3260. };
  3261. /**
  3262. * Request a reflow. The controller will schedule a reflow
  3263. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3264. * is false.
  3265. */
  3266. Controller.prototype.requestReflow = function requestReflow(force) {
  3267. if (force) {
  3268. this.reflow();
  3269. }
  3270. else {
  3271. if (!this.reflowTimer) {
  3272. var me = this;
  3273. this.reflowTimer = setTimeout(function () {
  3274. me.reflowTimer = undefined;
  3275. me.reflow();
  3276. }, 0);
  3277. }
  3278. }
  3279. };
  3280. /**
  3281. * Request a repaint. The controller will schedule a repaint
  3282. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3283. * is false.
  3284. */
  3285. Controller.prototype.requestRepaint = function requestRepaint(force) {
  3286. if (force) {
  3287. this.repaint();
  3288. }
  3289. else {
  3290. if (!this.repaintTimer) {
  3291. var me = this;
  3292. this.repaintTimer = setTimeout(function () {
  3293. me.repaintTimer = undefined;
  3294. me.repaint();
  3295. }, 0);
  3296. }
  3297. }
  3298. };
  3299. /**
  3300. * Repaint all components
  3301. */
  3302. Controller.prototype.repaint = function repaint() {
  3303. var changed = false;
  3304. // cancel any running repaint request
  3305. if (this.repaintTimer) {
  3306. clearTimeout(this.repaintTimer);
  3307. this.repaintTimer = undefined;
  3308. }
  3309. var done = {};
  3310. function repaint(component, id) {
  3311. if (!(id in done)) {
  3312. // first repaint the components on which this component is dependent
  3313. if (component.depends) {
  3314. component.depends.forEach(function (dep) {
  3315. repaint(dep, dep.id);
  3316. });
  3317. }
  3318. if (component.parent) {
  3319. repaint(component.parent, component.parent.id);
  3320. }
  3321. // repaint the component itself and mark as done
  3322. changed = component.repaint() || changed;
  3323. done[id] = true;
  3324. }
  3325. }
  3326. util.forEach(this.components, repaint);
  3327. // immediately reflow when needed
  3328. if (changed) {
  3329. this.reflow();
  3330. }
  3331. // TODO: limit the number of nested reflows/repaints, prevent loop
  3332. };
  3333. /**
  3334. * Reflow all components
  3335. */
  3336. Controller.prototype.reflow = function reflow() {
  3337. var resized = false;
  3338. // cancel any running repaint request
  3339. if (this.reflowTimer) {
  3340. clearTimeout(this.reflowTimer);
  3341. this.reflowTimer = undefined;
  3342. }
  3343. var done = {};
  3344. function reflow(component, id) {
  3345. if (!(id in done)) {
  3346. // first reflow the components on which this component is dependent
  3347. if (component.depends) {
  3348. component.depends.forEach(function (dep) {
  3349. reflow(dep, dep.id);
  3350. });
  3351. }
  3352. if (component.parent) {
  3353. reflow(component.parent, component.parent.id);
  3354. }
  3355. // reflow the component itself and mark as done
  3356. resized = component.reflow() || resized;
  3357. done[id] = true;
  3358. }
  3359. }
  3360. util.forEach(this.components, reflow);
  3361. // immediately repaint when needed
  3362. if (resized) {
  3363. this.repaint();
  3364. }
  3365. // TODO: limit the number of nested reflows/repaints, prevent loop
  3366. };
  3367. /**
  3368. * Prototype for visual components
  3369. */
  3370. function Component () {
  3371. this.id = null;
  3372. this.parent = null;
  3373. this.depends = null;
  3374. this.controller = null;
  3375. this.options = null;
  3376. this.frame = null; // main DOM element
  3377. this.top = 0;
  3378. this.left = 0;
  3379. this.width = 0;
  3380. this.height = 0;
  3381. }
  3382. /**
  3383. * Set parameters for the frame. Parameters will be merged in current parameter
  3384. * set.
  3385. * @param {Object} options Available parameters:
  3386. * {String | function} [className]
  3387. * {EventBus} [eventBus]
  3388. * {String | Number | function} [left]
  3389. * {String | Number | function} [top]
  3390. * {String | Number | function} [width]
  3391. * {String | Number | function} [height]
  3392. */
  3393. Component.prototype.setOptions = function setOptions(options) {
  3394. if (options) {
  3395. util.extend(this.options, options);
  3396. if (this.controller) {
  3397. this.requestRepaint();
  3398. this.requestReflow();
  3399. }
  3400. }
  3401. };
  3402. /**
  3403. * Get an option value by name
  3404. * The function will first check this.options object, and else will check
  3405. * this.defaultOptions.
  3406. * @param {String} name
  3407. * @return {*} value
  3408. */
  3409. Component.prototype.getOption = function getOption(name) {
  3410. var value;
  3411. if (this.options) {
  3412. value = this.options[name];
  3413. }
  3414. if (value === undefined && this.defaultOptions) {
  3415. value = this.defaultOptions[name];
  3416. }
  3417. return value;
  3418. };
  3419. /**
  3420. * Get the container element of the component, which can be used by a child to
  3421. * add its own widgets. Not all components do have a container for childs, in
  3422. * that case null is returned.
  3423. * @returns {HTMLElement | null} container
  3424. */
  3425. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3426. Component.prototype.getContainer = function getContainer() {
  3427. // should be implemented by the component
  3428. return null;
  3429. };
  3430. /**
  3431. * Get the frame element of the component, the outer HTML DOM element.
  3432. * @returns {HTMLElement | null} frame
  3433. */
  3434. Component.prototype.getFrame = function getFrame() {
  3435. return this.frame;
  3436. };
  3437. /**
  3438. * Repaint the component
  3439. * @return {Boolean} changed
  3440. */
  3441. Component.prototype.repaint = function repaint() {
  3442. // should be implemented by the component
  3443. return false;
  3444. };
  3445. /**
  3446. * Reflow the component
  3447. * @return {Boolean} resized
  3448. */
  3449. Component.prototype.reflow = function reflow() {
  3450. // should be implemented by the component
  3451. return false;
  3452. };
  3453. /**
  3454. * Hide the component from the DOM
  3455. * @return {Boolean} changed
  3456. */
  3457. Component.prototype.hide = function hide() {
  3458. if (this.frame && this.frame.parentNode) {
  3459. this.frame.parentNode.removeChild(this.frame);
  3460. return true;
  3461. }
  3462. else {
  3463. return false;
  3464. }
  3465. };
  3466. /**
  3467. * Show the component in the DOM (when not already visible).
  3468. * A repaint will be executed when the component is not visible
  3469. * @return {Boolean} changed
  3470. */
  3471. Component.prototype.show = function show() {
  3472. if (!this.frame || !this.frame.parentNode) {
  3473. return this.repaint();
  3474. }
  3475. else {
  3476. return false;
  3477. }
  3478. };
  3479. /**
  3480. * Request a repaint. The controller will schedule a repaint
  3481. */
  3482. Component.prototype.requestRepaint = function requestRepaint() {
  3483. if (this.controller) {
  3484. this.controller.requestRepaint();
  3485. }
  3486. else {
  3487. throw new Error('Cannot request a repaint: no controller configured');
  3488. // TODO: just do a repaint when no parent is configured?
  3489. }
  3490. };
  3491. /**
  3492. * Request a reflow. The controller will schedule a reflow
  3493. */
  3494. Component.prototype.requestReflow = function requestReflow() {
  3495. if (this.controller) {
  3496. this.controller.requestReflow();
  3497. }
  3498. else {
  3499. throw new Error('Cannot request a reflow: no controller configured');
  3500. // TODO: just do a reflow when no parent is configured?
  3501. }
  3502. };
  3503. /**
  3504. * A panel can contain components
  3505. * @param {Component} [parent]
  3506. * @param {Component[]} [depends] Components on which this components depends
  3507. * (except for the parent)
  3508. * @param {Object} [options] Available parameters:
  3509. * {String | Number | function} [left]
  3510. * {String | Number | function} [top]
  3511. * {String | Number | function} [width]
  3512. * {String | Number | function} [height]
  3513. * {String | function} [className]
  3514. * @constructor Panel
  3515. * @extends Component
  3516. */
  3517. function Panel(parent, depends, options) {
  3518. this.id = util.randomUUID();
  3519. this.parent = parent;
  3520. this.depends = depends;
  3521. this.options = options || {};
  3522. }
  3523. Panel.prototype = new Component();
  3524. /**
  3525. * Set options. Will extend the current options.
  3526. * @param {Object} [options] Available parameters:
  3527. * {String | function} [className]
  3528. * {String | Number | function} [left]
  3529. * {String | Number | function} [top]
  3530. * {String | Number | function} [width]
  3531. * {String | Number | function} [height]
  3532. */
  3533. Panel.prototype.setOptions = Component.prototype.setOptions;
  3534. /**
  3535. * Get the container element of the panel, which can be used by a child to
  3536. * add its own widgets.
  3537. * @returns {HTMLElement} container
  3538. */
  3539. Panel.prototype.getContainer = function () {
  3540. return this.frame;
  3541. };
  3542. /**
  3543. * Repaint the component
  3544. * @return {Boolean} changed
  3545. */
  3546. Panel.prototype.repaint = function () {
  3547. var changed = 0,
  3548. update = util.updateProperty,
  3549. asSize = util.option.asSize,
  3550. options = this.options,
  3551. frame = this.frame;
  3552. if (!frame) {
  3553. frame = document.createElement('div');
  3554. frame.className = 'panel';
  3555. var className = options.className;
  3556. if (className) {
  3557. if (typeof className == 'function') {
  3558. util.addClassName(frame, String(className()));
  3559. }
  3560. else {
  3561. util.addClassName(frame, String(className));
  3562. }
  3563. }
  3564. this.frame = frame;
  3565. changed += 1;
  3566. }
  3567. if (!frame.parentNode) {
  3568. if (!this.parent) {
  3569. throw new Error('Cannot repaint panel: no parent attached');
  3570. }
  3571. var parentContainer = this.parent.getContainer();
  3572. if (!parentContainer) {
  3573. throw new Error('Cannot repaint panel: parent has no container element');
  3574. }
  3575. parentContainer.appendChild(frame);
  3576. changed += 1;
  3577. }
  3578. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3579. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3580. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3581. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3582. return (changed > 0);
  3583. };
  3584. /**
  3585. * Reflow the component
  3586. * @return {Boolean} resized
  3587. */
  3588. Panel.prototype.reflow = function () {
  3589. var changed = 0,
  3590. update = util.updateProperty,
  3591. frame = this.frame;
  3592. if (frame) {
  3593. changed += update(this, 'top', frame.offsetTop);
  3594. changed += update(this, 'left', frame.offsetLeft);
  3595. changed += update(this, 'width', frame.offsetWidth);
  3596. changed += update(this, 'height', frame.offsetHeight);
  3597. }
  3598. else {
  3599. changed += 1;
  3600. }
  3601. return (changed > 0);
  3602. };
  3603. /**
  3604. * A root panel can hold components. The root panel must be initialized with
  3605. * a DOM element as container.
  3606. * @param {HTMLElement} container
  3607. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3608. * @constructor RootPanel
  3609. * @extends Panel
  3610. */
  3611. function RootPanel(container, options) {
  3612. this.id = util.randomUUID();
  3613. this.container = container;
  3614. this.options = options || {};
  3615. this.defaultOptions = {
  3616. autoResize: true
  3617. };
  3618. this.listeners = {}; // event listeners
  3619. }
  3620. RootPanel.prototype = new Panel();
  3621. /**
  3622. * Set options. Will extend the current options.
  3623. * @param {Object} [options] Available parameters:
  3624. * {String | function} [className]
  3625. * {String | Number | function} [left]
  3626. * {String | Number | function} [top]
  3627. * {String | Number | function} [width]
  3628. * {String | Number | function} [height]
  3629. * {Boolean | function} [autoResize]
  3630. */
  3631. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3632. /**
  3633. * Repaint the component
  3634. * @return {Boolean} changed
  3635. */
  3636. RootPanel.prototype.repaint = function () {
  3637. var changed = 0,
  3638. update = util.updateProperty,
  3639. asSize = util.option.asSize,
  3640. options = this.options,
  3641. frame = this.frame;
  3642. if (!frame) {
  3643. frame = document.createElement('div');
  3644. this.frame = frame;
  3645. changed += 1;
  3646. }
  3647. if (!frame.parentNode) {
  3648. if (!this.container) {
  3649. throw new Error('Cannot repaint root panel: no container attached');
  3650. }
  3651. this.container.appendChild(frame);
  3652. changed += 1;
  3653. }
  3654. frame.className = 'vis timeline rootpanel ' + options.orientation;
  3655. var className = options.className;
  3656. if (className) {
  3657. util.addClassName(frame, util.option.asString(className));
  3658. }
  3659. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3660. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3661. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3662. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3663. this._updateEventEmitters();
  3664. this._updateWatch();
  3665. return (changed > 0);
  3666. };
  3667. /**
  3668. * Reflow the component
  3669. * @return {Boolean} resized
  3670. */
  3671. RootPanel.prototype.reflow = function () {
  3672. var changed = 0,
  3673. update = util.updateProperty,
  3674. frame = this.frame;
  3675. if (frame) {
  3676. changed += update(this, 'top', frame.offsetTop);
  3677. changed += update(this, 'left', frame.offsetLeft);
  3678. changed += update(this, 'width', frame.offsetWidth);
  3679. changed += update(this, 'height', frame.offsetHeight);
  3680. }
  3681. else {
  3682. changed += 1;
  3683. }
  3684. return (changed > 0);
  3685. };
  3686. /**
  3687. * Update watching for resize, depending on the current option
  3688. * @private
  3689. */
  3690. RootPanel.prototype._updateWatch = function () {
  3691. var autoResize = this.getOption('autoResize');
  3692. if (autoResize) {
  3693. this._watch();
  3694. }
  3695. else {
  3696. this._unwatch();
  3697. }
  3698. };
  3699. /**
  3700. * Watch for changes in the size of the frame. On resize, the Panel will
  3701. * automatically redraw itself.
  3702. * @private
  3703. */
  3704. RootPanel.prototype._watch = function () {
  3705. var me = this;
  3706. this._unwatch();
  3707. var checkSize = function () {
  3708. var autoResize = me.getOption('autoResize');
  3709. if (!autoResize) {
  3710. // stop watching when the option autoResize is changed to false
  3711. me._unwatch();
  3712. return;
  3713. }
  3714. if (me.frame) {
  3715. // check whether the frame is resized
  3716. if ((me.frame.clientWidth != me.width) ||
  3717. (me.frame.clientHeight != me.height)) {
  3718. me.requestReflow();
  3719. }
  3720. }
  3721. };
  3722. // TODO: automatically cleanup the event listener when the frame is deleted
  3723. util.addEventListener(window, 'resize', checkSize);
  3724. this.watchTimer = setInterval(checkSize, 1000);
  3725. };
  3726. /**
  3727. * Stop watching for a resize of the frame.
  3728. * @private
  3729. */
  3730. RootPanel.prototype._unwatch = function () {
  3731. if (this.watchTimer) {
  3732. clearInterval(this.watchTimer);
  3733. this.watchTimer = undefined;
  3734. }
  3735. // TODO: remove event listener on window.resize
  3736. };
  3737. /**
  3738. * Event handler
  3739. * @param {String} event name of the event, for example 'click', 'mousemove'
  3740. * @param {function} callback callback handler, invoked with the raw HTML Event
  3741. * as parameter.
  3742. */
  3743. RootPanel.prototype.on = function (event, callback) {
  3744. // register the listener at this component
  3745. var arr = this.listeners[event];
  3746. if (!arr) {
  3747. arr = [];
  3748. this.listeners[event] = arr;
  3749. }
  3750. arr.push(callback);
  3751. this._updateEventEmitters();
  3752. };
  3753. /**
  3754. * Update the event listeners for all event emitters
  3755. * @private
  3756. */
  3757. RootPanel.prototype._updateEventEmitters = function () {
  3758. if (this.listeners) {
  3759. var me = this;
  3760. util.forEach(this.listeners, function (listeners, event) {
  3761. if (!me.emitters) {
  3762. me.emitters = {};
  3763. }
  3764. if (!(event in me.emitters)) {
  3765. // create event
  3766. var frame = me.frame;
  3767. if (frame) {
  3768. //console.log('Created a listener for event ' + event + ' on component ' + me.id); // TODO: cleanup logging
  3769. var callback = function(event) {
  3770. listeners.forEach(function (listener) {
  3771. // TODO: filter on event target!
  3772. listener(event);
  3773. });
  3774. };
  3775. me.emitters[event] = callback;
  3776. if (!me.hammer) {
  3777. me.hammer = Hammer(frame, {
  3778. prevent_default: true
  3779. });
  3780. }
  3781. me.hammer.on(event, callback);
  3782. }
  3783. }
  3784. });
  3785. // TODO: be able to delete event listeners
  3786. // TODO: be able to move event listeners to a parent when available
  3787. }
  3788. };
  3789. /**
  3790. * A horizontal time axis
  3791. * @param {Component} parent
  3792. * @param {Component[]} [depends] Components on which this components depends
  3793. * (except for the parent)
  3794. * @param {Object} [options] See TimeAxis.setOptions for the available
  3795. * options.
  3796. * @constructor TimeAxis
  3797. * @extends Component
  3798. */
  3799. function TimeAxis (parent, depends, options) {
  3800. this.id = util.randomUUID();
  3801. this.parent = parent;
  3802. this.depends = depends;
  3803. this.dom = {
  3804. majorLines: [],
  3805. majorTexts: [],
  3806. minorLines: [],
  3807. minorTexts: [],
  3808. redundant: {
  3809. majorLines: [],
  3810. majorTexts: [],
  3811. minorLines: [],
  3812. minorTexts: []
  3813. }
  3814. };
  3815. this.props = {
  3816. range: {
  3817. start: 0,
  3818. end: 0,
  3819. minimumStep: 0
  3820. },
  3821. lineTop: 0
  3822. };
  3823. this.options = options || {};
  3824. this.defaultOptions = {
  3825. orientation: 'bottom', // supported: 'top', 'bottom'
  3826. // TODO: implement timeaxis orientations 'left' and 'right'
  3827. showMinorLabels: true,
  3828. showMajorLabels: true
  3829. };
  3830. this.conversion = null;
  3831. this.range = null;
  3832. }
  3833. TimeAxis.prototype = new Component();
  3834. // TODO: comment options
  3835. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3836. /**
  3837. * Set a range (start and end)
  3838. * @param {Range | Object} range A Range or an object containing start and end.
  3839. */
  3840. TimeAxis.prototype.setRange = function (range) {
  3841. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3842. throw new TypeError('Range must be an instance of Range, ' +
  3843. 'or an object containing start and end.');
  3844. }
  3845. this.range = range;
  3846. };
  3847. /**
  3848. * Convert a position on screen (pixels) to a datetime
  3849. * @param {int} x Position on the screen in pixels
  3850. * @return {Date} time The datetime the corresponds with given position x
  3851. */
  3852. TimeAxis.prototype.toTime = function(x) {
  3853. var conversion = this.conversion;
  3854. return new Date(x / conversion.scale + conversion.offset);
  3855. };
  3856. /**
  3857. * Convert a datetime (Date object) into a position on the screen
  3858. * @param {Date} time A date
  3859. * @return {int} x The position on the screen in pixels which corresponds
  3860. * with the given date.
  3861. * @private
  3862. */
  3863. TimeAxis.prototype.toScreen = function(time) {
  3864. var conversion = this.conversion;
  3865. return (time.valueOf() - conversion.offset) * conversion.scale;
  3866. };
  3867. /**
  3868. * Repaint the component
  3869. * @return {Boolean} changed
  3870. */
  3871. TimeAxis.prototype.repaint = function () {
  3872. var changed = 0,
  3873. update = util.updateProperty,
  3874. asSize = util.option.asSize,
  3875. options = this.options,
  3876. orientation = this.getOption('orientation'),
  3877. props = this.props,
  3878. step = this.step;
  3879. var frame = this.frame;
  3880. if (!frame) {
  3881. frame = document.createElement('div');
  3882. this.frame = frame;
  3883. changed += 1;
  3884. }
  3885. frame.className = 'axis';
  3886. // TODO: custom className?
  3887. if (!frame.parentNode) {
  3888. if (!this.parent) {
  3889. throw new Error('Cannot repaint time axis: no parent attached');
  3890. }
  3891. var parentContainer = this.parent.getContainer();
  3892. if (!parentContainer) {
  3893. throw new Error('Cannot repaint time axis: parent has no container element');
  3894. }
  3895. parentContainer.appendChild(frame);
  3896. changed += 1;
  3897. }
  3898. var parent = frame.parentNode;
  3899. if (parent) {
  3900. var beforeChild = frame.nextSibling;
  3901. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3902. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3903. (this.props.parentHeight - this.height) + 'px' :
  3904. '0px';
  3905. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3906. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3907. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3908. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3909. // get characters width and height
  3910. this._repaintMeasureChars();
  3911. if (this.step) {
  3912. this._repaintStart();
  3913. step.first();
  3914. var xFirstMajorLabel = undefined;
  3915. var max = 0;
  3916. while (step.hasNext() && max < 1000) {
  3917. max++;
  3918. var cur = step.getCurrent(),
  3919. x = this.toScreen(cur),
  3920. isMajor = step.isMajor();
  3921. // TODO: lines must have a width, such that we can create css backgrounds
  3922. if (this.getOption('showMinorLabels')) {
  3923. this._repaintMinorText(x, step.getLabelMinor());
  3924. }
  3925. if (isMajor && this.getOption('showMajorLabels')) {
  3926. if (x > 0) {
  3927. if (xFirstMajorLabel == undefined) {
  3928. xFirstMajorLabel = x;
  3929. }
  3930. this._repaintMajorText(x, step.getLabelMajor());
  3931. }
  3932. this._repaintMajorLine(x);
  3933. }
  3934. else {
  3935. this._repaintMinorLine(x);
  3936. }
  3937. step.next();
  3938. }
  3939. // create a major label on the left when needed
  3940. if (this.getOption('showMajorLabels')) {
  3941. var leftTime = this.toTime(0),
  3942. leftText = step.getLabelMajor(leftTime),
  3943. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3944. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3945. this._repaintMajorText(0, leftText);
  3946. }
  3947. }
  3948. this._repaintEnd();
  3949. }
  3950. this._repaintLine();
  3951. // put frame online again
  3952. if (beforeChild) {
  3953. parent.insertBefore(frame, beforeChild);
  3954. }
  3955. else {
  3956. parent.appendChild(frame)
  3957. }
  3958. }
  3959. return (changed > 0);
  3960. };
  3961. /**
  3962. * Start a repaint. Move all DOM elements to a redundant list, where they
  3963. * can be picked for re-use, or can be cleaned up in the end
  3964. * @private
  3965. */
  3966. TimeAxis.prototype._repaintStart = function () {
  3967. var dom = this.dom,
  3968. redundant = dom.redundant;
  3969. redundant.majorLines = dom.majorLines;
  3970. redundant.majorTexts = dom.majorTexts;
  3971. redundant.minorLines = dom.minorLines;
  3972. redundant.minorTexts = dom.minorTexts;
  3973. dom.majorLines = [];
  3974. dom.majorTexts = [];
  3975. dom.minorLines = [];
  3976. dom.minorTexts = [];
  3977. };
  3978. /**
  3979. * End a repaint. Cleanup leftover DOM elements in the redundant list
  3980. * @private
  3981. */
  3982. TimeAxis.prototype._repaintEnd = function () {
  3983. util.forEach(this.dom.redundant, function (arr) {
  3984. while (arr.length) {
  3985. var elem = arr.pop();
  3986. if (elem && elem.parentNode) {
  3987. elem.parentNode.removeChild(elem);
  3988. }
  3989. }
  3990. });
  3991. };
  3992. /**
  3993. * Create a minor label for the axis at position x
  3994. * @param {Number} x
  3995. * @param {String} text
  3996. * @private
  3997. */
  3998. TimeAxis.prototype._repaintMinorText = function (x, text) {
  3999. // reuse redundant label
  4000. var label = this.dom.redundant.minorTexts.shift();
  4001. if (!label) {
  4002. // create new label
  4003. var content = document.createTextNode('');
  4004. label = document.createElement('div');
  4005. label.appendChild(content);
  4006. label.className = 'text minor';
  4007. this.frame.appendChild(label);
  4008. }
  4009. this.dom.minorTexts.push(label);
  4010. label.childNodes[0].nodeValue = text;
  4011. label.style.left = x + 'px';
  4012. label.style.top = this.props.minorLabelTop + 'px';
  4013. //label.title = title; // TODO: this is a heavy operation
  4014. };
  4015. /**
  4016. * Create a Major label for the axis at position x
  4017. * @param {Number} x
  4018. * @param {String} text
  4019. * @private
  4020. */
  4021. TimeAxis.prototype._repaintMajorText = function (x, text) {
  4022. // reuse redundant label
  4023. var label = this.dom.redundant.majorTexts.shift();
  4024. if (!label) {
  4025. // create label
  4026. var content = document.createTextNode(text);
  4027. label = document.createElement('div');
  4028. label.className = 'text major';
  4029. label.appendChild(content);
  4030. this.frame.appendChild(label);
  4031. }
  4032. this.dom.majorTexts.push(label);
  4033. label.childNodes[0].nodeValue = text;
  4034. label.style.top = this.props.majorLabelTop + 'px';
  4035. label.style.left = x + 'px';
  4036. //label.title = title; // TODO: this is a heavy operation
  4037. };
  4038. /**
  4039. * Create a minor line for the axis at position x
  4040. * @param {Number} x
  4041. * @private
  4042. */
  4043. TimeAxis.prototype._repaintMinorLine = function (x) {
  4044. // reuse redundant line
  4045. var line = this.dom.redundant.minorLines.shift();
  4046. if (!line) {
  4047. // create vertical line
  4048. line = document.createElement('div');
  4049. line.className = 'grid vertical minor';
  4050. this.frame.appendChild(line);
  4051. }
  4052. this.dom.minorLines.push(line);
  4053. var props = this.props;
  4054. line.style.top = props.minorLineTop + 'px';
  4055. line.style.height = props.minorLineHeight + 'px';
  4056. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  4057. };
  4058. /**
  4059. * Create a Major line for the axis at position x
  4060. * @param {Number} x
  4061. * @private
  4062. */
  4063. TimeAxis.prototype._repaintMajorLine = function (x) {
  4064. // reuse redundant line
  4065. var line = this.dom.redundant.majorLines.shift();
  4066. if (!line) {
  4067. // create vertical line
  4068. line = document.createElement('DIV');
  4069. line.className = 'grid vertical major';
  4070. this.frame.appendChild(line);
  4071. }
  4072. this.dom.majorLines.push(line);
  4073. var props = this.props;
  4074. line.style.top = props.majorLineTop + 'px';
  4075. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4076. line.style.height = props.majorLineHeight + 'px';
  4077. };
  4078. /**
  4079. * Repaint the horizontal line for the axis
  4080. * @private
  4081. */
  4082. TimeAxis.prototype._repaintLine = function() {
  4083. var line = this.dom.line,
  4084. frame = this.frame,
  4085. options = this.options;
  4086. // line before all axis elements
  4087. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4088. if (line) {
  4089. // put this line at the end of all childs
  4090. frame.removeChild(line);
  4091. frame.appendChild(line);
  4092. }
  4093. else {
  4094. // create the axis line
  4095. line = document.createElement('div');
  4096. line.className = 'grid horizontal major';
  4097. frame.appendChild(line);
  4098. this.dom.line = line;
  4099. }
  4100. line.style.top = this.props.lineTop + 'px';
  4101. }
  4102. else {
  4103. if (line && line.parentElement) {
  4104. frame.removeChild(line.line);
  4105. delete this.dom.line;
  4106. }
  4107. }
  4108. };
  4109. /**
  4110. * Create characters used to determine the size of text on the axis
  4111. * @private
  4112. */
  4113. TimeAxis.prototype._repaintMeasureChars = function () {
  4114. // calculate the width and height of a single character
  4115. // this is used to calculate the step size, and also the positioning of the
  4116. // axis
  4117. var dom = this.dom,
  4118. text;
  4119. if (!dom.measureCharMinor) {
  4120. text = document.createTextNode('0');
  4121. var measureCharMinor = document.createElement('DIV');
  4122. measureCharMinor.className = 'text minor measure';
  4123. measureCharMinor.appendChild(text);
  4124. this.frame.appendChild(measureCharMinor);
  4125. dom.measureCharMinor = measureCharMinor;
  4126. }
  4127. if (!dom.measureCharMajor) {
  4128. text = document.createTextNode('0');
  4129. var measureCharMajor = document.createElement('DIV');
  4130. measureCharMajor.className = 'text major measure';
  4131. measureCharMajor.appendChild(text);
  4132. this.frame.appendChild(measureCharMajor);
  4133. dom.measureCharMajor = measureCharMajor;
  4134. }
  4135. };
  4136. /**
  4137. * Reflow the component
  4138. * @return {Boolean} resized
  4139. */
  4140. TimeAxis.prototype.reflow = function () {
  4141. var changed = 0,
  4142. update = util.updateProperty,
  4143. frame = this.frame,
  4144. range = this.range;
  4145. if (!range) {
  4146. throw new Error('Cannot repaint time axis: no range configured');
  4147. }
  4148. if (frame) {
  4149. changed += update(this, 'top', frame.offsetTop);
  4150. changed += update(this, 'left', frame.offsetLeft);
  4151. // calculate size of a character
  4152. var props = this.props,
  4153. showMinorLabels = this.getOption('showMinorLabels'),
  4154. showMajorLabels = this.getOption('showMajorLabels'),
  4155. measureCharMinor = this.dom.measureCharMinor,
  4156. measureCharMajor = this.dom.measureCharMajor;
  4157. if (measureCharMinor) {
  4158. props.minorCharHeight = measureCharMinor.clientHeight;
  4159. props.minorCharWidth = measureCharMinor.clientWidth;
  4160. }
  4161. if (measureCharMajor) {
  4162. props.majorCharHeight = measureCharMajor.clientHeight;
  4163. props.majorCharWidth = measureCharMajor.clientWidth;
  4164. }
  4165. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4166. if (parentHeight != props.parentHeight) {
  4167. props.parentHeight = parentHeight;
  4168. changed += 1;
  4169. }
  4170. switch (this.getOption('orientation')) {
  4171. case 'bottom':
  4172. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4173. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4174. props.minorLabelTop = 0;
  4175. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4176. props.minorLineTop = -this.top;
  4177. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4178. props.minorLineWidth = 1; // TODO: really calculate width
  4179. props.majorLineTop = -this.top;
  4180. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4181. props.majorLineWidth = 1; // TODO: really calculate width
  4182. props.lineTop = 0;
  4183. break;
  4184. case 'top':
  4185. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4186. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4187. props.majorLabelTop = 0;
  4188. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4189. props.minorLineTop = props.minorLabelTop;
  4190. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4191. props.minorLineWidth = 1; // TODO: really calculate width
  4192. props.majorLineTop = 0;
  4193. props.majorLineHeight = Math.max(parentHeight - this.top);
  4194. props.majorLineWidth = 1; // TODO: really calculate width
  4195. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4196. break;
  4197. default:
  4198. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4199. }
  4200. var height = props.minorLabelHeight + props.majorLabelHeight;
  4201. changed += update(this, 'width', frame.offsetWidth);
  4202. changed += update(this, 'height', height);
  4203. // calculate range and step
  4204. this._updateConversion();
  4205. var start = util.convert(range.start, 'Number'),
  4206. end = util.convert(range.end, 'Number'),
  4207. minimumStep = this.toTime((props.minorCharWidth || 10) * 5).valueOf()
  4208. -this.toTime(0).valueOf();
  4209. this.step = new TimeStep(new Date(start), new Date(end), minimumStep);
  4210. changed += update(props.range, 'start', start);
  4211. changed += update(props.range, 'end', end);
  4212. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4213. }
  4214. return (changed > 0);
  4215. };
  4216. /**
  4217. * Calculate the scale and offset to convert a position on screen to the
  4218. * corresponding date and vice versa.
  4219. * After the method _updateConversion is executed once, the methods toTime
  4220. * and toScreen can be used.
  4221. * @private
  4222. */
  4223. TimeAxis.prototype._updateConversion = function() {
  4224. var range = this.range;
  4225. if (!range) {
  4226. throw new Error('No range configured');
  4227. }
  4228. if (range.conversion) {
  4229. this.conversion = range.conversion(this.width);
  4230. }
  4231. else {
  4232. this.conversion = Range.conversion(range.start, range.end, this.width);
  4233. }
  4234. };
  4235. /**
  4236. * A current time bar
  4237. * @param {Component} parent
  4238. * @param {Component[]} [depends] Components on which this components depends
  4239. * (except for the parent)
  4240. * @param {Object} [options] Available parameters:
  4241. * {Boolean} [showCurrentTime]
  4242. * @constructor CurrentTime
  4243. * @extends Component
  4244. */
  4245. function CurrentTime (parent, depends, options) {
  4246. this.id = util.randomUUID();
  4247. this.parent = parent;
  4248. this.depends = depends;
  4249. this.options = options || {};
  4250. this.defaultOptions = {
  4251. showCurrentTime: false
  4252. };
  4253. }
  4254. CurrentTime.prototype = new Component();
  4255. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  4256. /**
  4257. * Get the container element of the bar, which can be used by a child to
  4258. * add its own widgets.
  4259. * @returns {HTMLElement} container
  4260. */
  4261. CurrentTime.prototype.getContainer = function () {
  4262. return this.frame;
  4263. };
  4264. /**
  4265. * Repaint the component
  4266. * @return {Boolean} changed
  4267. */
  4268. CurrentTime.prototype.repaint = function () {
  4269. var bar = this.frame,
  4270. parent = this.parent,
  4271. parentContainer = parent.parent.getContainer();
  4272. if (!parent) {
  4273. throw new Error('Cannot repaint bar: no parent attached');
  4274. }
  4275. if (!parentContainer) {
  4276. throw new Error('Cannot repaint bar: parent has no container element');
  4277. }
  4278. if (!this.getOption('showCurrentTime')) {
  4279. if (bar) {
  4280. parentContainer.removeChild(bar);
  4281. delete this.frame;
  4282. }
  4283. return;
  4284. }
  4285. if (!bar) {
  4286. bar = document.createElement('div');
  4287. bar.className = 'currenttime';
  4288. bar.style.position = 'absolute';
  4289. bar.style.top = '0px';
  4290. bar.style.height = '100%';
  4291. parentContainer.appendChild(bar);
  4292. this.frame = bar;
  4293. }
  4294. if (!parent.conversion) {
  4295. parent._updateConversion();
  4296. }
  4297. var now = new Date();
  4298. var x = parent.toScreen(now);
  4299. bar.style.left = x + 'px';
  4300. bar.title = 'Current time: ' + now;
  4301. // start a timer to adjust for the new time
  4302. if (this.currentTimeTimer !== undefined) {
  4303. clearTimeout(this.currentTimeTimer);
  4304. delete this.currentTimeTimer;
  4305. }
  4306. var timeline = this;
  4307. var interval = 1 / parent.conversion.scale / 2;
  4308. if (interval < 30) {
  4309. interval = 30;
  4310. }
  4311. this.currentTimeTimer = setTimeout(function() {
  4312. timeline.repaint();
  4313. }, interval);
  4314. return false;
  4315. };
  4316. /**
  4317. * A custom time bar
  4318. * @param {Component} parent
  4319. * @param {Component[]} [depends] Components on which this components depends
  4320. * (except for the parent)
  4321. * @param {Object} [options] Available parameters:
  4322. * {Boolean} [showCustomTime]
  4323. * @constructor CustomTime
  4324. * @extends Component
  4325. */
  4326. function CustomTime (parent, depends, options) {
  4327. this.id = util.randomUUID();
  4328. this.parent = parent;
  4329. this.depends = depends;
  4330. this.options = options || {};
  4331. this.defaultOptions = {
  4332. showCustomTime: false
  4333. };
  4334. this.listeners = [];
  4335. this.customTime = new Date();
  4336. }
  4337. CustomTime.prototype = new Component();
  4338. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4339. /**
  4340. * Get the container element of the bar, which can be used by a child to
  4341. * add its own widgets.
  4342. * @returns {HTMLElement} container
  4343. */
  4344. CustomTime.prototype.getContainer = function () {
  4345. return this.frame;
  4346. };
  4347. /**
  4348. * Repaint the component
  4349. * @return {Boolean} changed
  4350. */
  4351. CustomTime.prototype.repaint = function () {
  4352. var bar = this.frame,
  4353. parent = this.parent,
  4354. parentContainer = parent.parent.getContainer();
  4355. if (!parent) {
  4356. throw new Error('Cannot repaint bar: no parent attached');
  4357. }
  4358. if (!parentContainer) {
  4359. throw new Error('Cannot repaint bar: parent has no container element');
  4360. }
  4361. if (!this.getOption('showCustomTime')) {
  4362. if (bar) {
  4363. parentContainer.removeChild(bar);
  4364. delete this.frame;
  4365. }
  4366. return;
  4367. }
  4368. if (!bar) {
  4369. bar = document.createElement('div');
  4370. bar.className = 'customtime';
  4371. bar.style.position = 'absolute';
  4372. bar.style.top = '0px';
  4373. bar.style.height = '100%';
  4374. parentContainer.appendChild(bar);
  4375. var drag = document.createElement('div');
  4376. drag.style.position = 'relative';
  4377. drag.style.top = '0px';
  4378. drag.style.left = '-10px';
  4379. drag.style.height = '100%';
  4380. drag.style.width = '20px';
  4381. bar.appendChild(drag);
  4382. this.frame = bar;
  4383. this.subscribe(this, 'movetime');
  4384. }
  4385. if (!parent.conversion) {
  4386. parent._updateConversion();
  4387. }
  4388. var x = parent.toScreen(this.customTime);
  4389. bar.style.left = x + 'px';
  4390. bar.title = 'Time: ' + this.customTime;
  4391. return false;
  4392. };
  4393. /**
  4394. * Set custom time.
  4395. * @param {Date} time
  4396. */
  4397. CustomTime.prototype._setCustomTime = function(time) {
  4398. this.customTime = new Date(time.valueOf());
  4399. this.repaint();
  4400. };
  4401. /**
  4402. * Retrieve the current custom time.
  4403. * @return {Date} customTime
  4404. */
  4405. CustomTime.prototype._getCustomTime = function() {
  4406. return new Date(this.customTime.valueOf());
  4407. };
  4408. /**
  4409. * Add listeners for mouse and touch events to the component
  4410. * @param {Component} component
  4411. */
  4412. CustomTime.prototype.subscribe = function (component, event) {
  4413. var me = this;
  4414. var listener = {
  4415. component: component,
  4416. event: event,
  4417. callback: function (event) {
  4418. me._onMouseDown(event, listener);
  4419. },
  4420. params: {}
  4421. };
  4422. component.on('mousedown', listener.callback);
  4423. me.listeners.push(listener);
  4424. };
  4425. /**
  4426. * Event handler
  4427. * @param {String} event name of the event, for example 'click', 'mousemove'
  4428. * @param {function} callback callback handler, invoked with the raw HTML Event
  4429. * as parameter.
  4430. */
  4431. CustomTime.prototype.on = function (event, callback) {
  4432. var bar = this.frame;
  4433. if (!bar) {
  4434. throw new Error('Cannot add event listener: no parent attached');
  4435. }
  4436. events.addListener(this, event, callback);
  4437. util.addEventListener(bar, event, callback);
  4438. };
  4439. /**
  4440. * Start moving horizontally
  4441. * @param {Event} event
  4442. * @param {Object} listener Listener containing the component and params
  4443. * @private
  4444. */
  4445. CustomTime.prototype._onMouseDown = function(event, listener) {
  4446. event = event || window.event;
  4447. var params = listener.params;
  4448. // only react on left mouse button down
  4449. var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  4450. if (!leftButtonDown) {
  4451. return;
  4452. }
  4453. // get mouse position
  4454. params.mouseX = util.getPageX(event);
  4455. params.moved = false;
  4456. params.customTime = this.customTime;
  4457. // add event listeners to handle moving the custom time bar
  4458. var me = this;
  4459. if (!params.onMouseMove) {
  4460. params.onMouseMove = function (event) {
  4461. me._onMouseMove(event, listener);
  4462. };
  4463. util.addEventListener(document, 'mousemove', params.onMouseMove);
  4464. }
  4465. if (!params.onMouseUp) {
  4466. params.onMouseUp = function (event) {
  4467. me._onMouseUp(event, listener);
  4468. };
  4469. util.addEventListener(document, 'mouseup', params.onMouseUp);
  4470. }
  4471. util.stopPropagation(event);
  4472. util.preventDefault(event);
  4473. };
  4474. /**
  4475. * Perform moving operating.
  4476. * This function activated from within the funcion CustomTime._onMouseDown().
  4477. * @param {Event} event
  4478. * @param {Object} listener
  4479. * @private
  4480. */
  4481. CustomTime.prototype._onMouseMove = function (event, listener) {
  4482. event = event || window.event;
  4483. var params = listener.params;
  4484. var parent = this.parent;
  4485. // calculate change in mouse position
  4486. var mouseX = util.getPageX(event);
  4487. if (params.mouseX === undefined) {
  4488. params.mouseX = mouseX;
  4489. }
  4490. var diff = mouseX - params.mouseX;
  4491. // if mouse movement is big enough, register it as a "moved" event
  4492. if (Math.abs(diff) >= 1) {
  4493. params.moved = true;
  4494. }
  4495. var x = parent.toScreen(params.customTime);
  4496. var xnew = x + diff;
  4497. var time = parent.toTime(xnew);
  4498. this._setCustomTime(time);
  4499. // fire a timechange event
  4500. events.trigger(this, 'timechange', {customTime: this.customTime});
  4501. util.preventDefault(event);
  4502. };
  4503. /**
  4504. * Stop moving operating.
  4505. * This function activated from within the function CustomTime._onMouseDown().
  4506. * @param {event} event
  4507. * @param {Object} listener
  4508. * @private
  4509. */
  4510. CustomTime.prototype._onMouseUp = function (event, listener) {
  4511. event = event || window.event;
  4512. var params = listener.params;
  4513. // remove event listeners here, important for Safari
  4514. if (params.onMouseMove) {
  4515. util.removeEventListener(document, 'mousemove', params.onMouseMove);
  4516. params.onMouseMove = null;
  4517. }
  4518. if (params.onMouseUp) {
  4519. util.removeEventListener(document, 'mouseup', params.onMouseUp);
  4520. params.onMouseUp = null;
  4521. }
  4522. if (params.moved) {
  4523. // fire a timechanged event
  4524. events.trigger(this, 'timechanged', {customTime: this.customTime});
  4525. }
  4526. };
  4527. /**
  4528. * An ItemSet holds a set of items and ranges which can be displayed in a
  4529. * range. The width is determined by the parent of the ItemSet, and the height
  4530. * is determined by the size of the items.
  4531. * @param {Component} parent
  4532. * @param {Component[]} [depends] Components on which this components depends
  4533. * (except for the parent)
  4534. * @param {Object} [options] See ItemSet.setOptions for the available
  4535. * options.
  4536. * @constructor ItemSet
  4537. * @extends Panel
  4538. */
  4539. // TODO: improve performance by replacing all Array.forEach with a for loop
  4540. function ItemSet(parent, depends, options) {
  4541. this.id = util.randomUUID();
  4542. this.parent = parent;
  4543. this.depends = depends;
  4544. // one options object is shared by this itemset and all its items
  4545. this.options = options || {};
  4546. this.defaultOptions = {
  4547. type: 'box',
  4548. align: 'center',
  4549. orientation: 'bottom',
  4550. margin: {
  4551. axis: 20,
  4552. item: 10
  4553. },
  4554. padding: 5
  4555. };
  4556. this.dom = {};
  4557. var me = this;
  4558. this.itemsData = null; // DataSet
  4559. this.range = null; // Range or Object {start: number, end: number}
  4560. this.listeners = {
  4561. 'add': function (event, params, senderId) {
  4562. if (senderId != me.id) {
  4563. me._onAdd(params.items);
  4564. }
  4565. },
  4566. 'update': function (event, params, senderId) {
  4567. if (senderId != me.id) {
  4568. me._onUpdate(params.items);
  4569. }
  4570. },
  4571. 'remove': function (event, params, senderId) {
  4572. if (senderId != me.id) {
  4573. me._onRemove(params.items);
  4574. }
  4575. }
  4576. };
  4577. this.items = {}; // object with an Item for every data item
  4578. this.selection = []; // list with the ids of all selected nodes
  4579. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4580. this.stack = new Stack(this, Object.create(this.options));
  4581. this.conversion = null;
  4582. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4583. }
  4584. ItemSet.prototype = new Panel();
  4585. // available item types will be registered here
  4586. ItemSet.types = {
  4587. box: ItemBox,
  4588. range: ItemRange,
  4589. rangeoverflow: ItemRangeOverflow,
  4590. point: ItemPoint
  4591. };
  4592. /**
  4593. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4594. * @param {Object} [options] The following options are available:
  4595. * {String | function} [className]
  4596. * class name for the itemset
  4597. * {String} [type]
  4598. * Default type for the items. Choose from 'box'
  4599. * (default), 'point', or 'range'. The default
  4600. * Style can be overwritten by individual items.
  4601. * {String} align
  4602. * Alignment for the items, only applicable for
  4603. * ItemBox. Choose 'center' (default), 'left', or
  4604. * 'right'.
  4605. * {String} orientation
  4606. * Orientation of the item set. Choose 'top' or
  4607. * 'bottom' (default).
  4608. * {Number} margin.axis
  4609. * Margin between the axis and the items in pixels.
  4610. * Default is 20.
  4611. * {Number} margin.item
  4612. * Margin between items in pixels. Default is 10.
  4613. * {Number} padding
  4614. * Padding of the contents of an item in pixels.
  4615. * Must correspond with the items css. Default is 5.
  4616. */
  4617. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4618. /**
  4619. * Set range (start and end).
  4620. * @param {Range | Object} range A Range or an object containing start and end.
  4621. */
  4622. ItemSet.prototype.setRange = function setRange(range) {
  4623. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4624. throw new TypeError('Range must be an instance of Range, ' +
  4625. 'or an object containing start and end.');
  4626. }
  4627. this.range = range;
  4628. };
  4629. /**
  4630. * Change the item selection, and/or get currently selected items
  4631. * @param {Array} [ids] An array with zero or more ids of the items to be selected.
  4632. * @return {Array} ids The ids of the selected items
  4633. */
  4634. ItemSet.prototype.select = function select(ids) {
  4635. var i, ii, id, item, selection;
  4636. if (ids) {
  4637. if (!Array.isArray(ids)) {
  4638. throw new TypeError('Array expected');
  4639. }
  4640. // unselect currently selected items
  4641. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4642. id = this.selection[i];
  4643. item = this.items[id];
  4644. if (item) item.unselect();
  4645. }
  4646. // select items
  4647. this.selection = [];
  4648. for (i = 0, ii = ids.length; i < ii; i++) {
  4649. id = ids[i];
  4650. item = this.items[id];
  4651. if (item) {
  4652. this.selection.push(id);
  4653. item.select();
  4654. }
  4655. }
  4656. // trigger a select event
  4657. selection = this.selection.concat([]);
  4658. events.trigger(this, 'select', {
  4659. ids: selection
  4660. });
  4661. if (this.controller) {
  4662. this.requestRepaint();
  4663. }
  4664. }
  4665. else {
  4666. selection = this.selection.concat([]);
  4667. }
  4668. return selection;
  4669. };
  4670. /**
  4671. * Deselect a selected item
  4672. * @param {String | Number} id
  4673. * @private
  4674. */
  4675. ItemSet.prototype._deselect = function _deselect(id) {
  4676. var selection = this.selection;
  4677. for (var i = 0, ii = selection.length; i < ii; i++) {
  4678. if (selection[i] == id) { // non-strict comparison!
  4679. selection.splice(i, 1);
  4680. break;
  4681. }
  4682. }
  4683. };
  4684. /**
  4685. * Repaint the component
  4686. * @return {Boolean} changed
  4687. */
  4688. ItemSet.prototype.repaint = function repaint() {
  4689. var changed = 0,
  4690. update = util.updateProperty,
  4691. asSize = util.option.asSize,
  4692. options = this.options,
  4693. orientation = this.getOption('orientation'),
  4694. defaultOptions = this.defaultOptions,
  4695. frame = this.frame;
  4696. if (!frame) {
  4697. frame = document.createElement('div');
  4698. frame.className = 'itemset';
  4699. var className = options.className;
  4700. if (className) {
  4701. util.addClassName(frame, util.option.asString(className));
  4702. }
  4703. // create background panel
  4704. var background = document.createElement('div');
  4705. background.className = 'background';
  4706. frame.appendChild(background);
  4707. this.dom.background = background;
  4708. // create foreground panel
  4709. var foreground = document.createElement('div');
  4710. foreground.className = 'foreground';
  4711. frame.appendChild(foreground);
  4712. this.dom.foreground = foreground;
  4713. // create axis panel
  4714. var axis = document.createElement('div');
  4715. axis.className = 'itemset-axis';
  4716. //frame.appendChild(axis);
  4717. this.dom.axis = axis;
  4718. this.frame = frame;
  4719. changed += 1;
  4720. }
  4721. if (!this.parent) {
  4722. throw new Error('Cannot repaint itemset: no parent attached');
  4723. }
  4724. var parentContainer = this.parent.getContainer();
  4725. if (!parentContainer) {
  4726. throw new Error('Cannot repaint itemset: parent has no container element');
  4727. }
  4728. if (!frame.parentNode) {
  4729. parentContainer.appendChild(frame);
  4730. changed += 1;
  4731. }
  4732. if (!this.dom.axis.parentNode) {
  4733. parentContainer.appendChild(this.dom.axis);
  4734. changed += 1;
  4735. }
  4736. // reposition frame
  4737. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4738. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4739. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4740. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4741. // reposition axis
  4742. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4743. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4744. if (orientation == 'bottom') {
  4745. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4746. }
  4747. else { // orientation == 'top'
  4748. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4749. }
  4750. this._updateConversion();
  4751. var me = this,
  4752. queue = this.queue,
  4753. itemsData = this.itemsData,
  4754. items = this.items,
  4755. dataOptions = {
  4756. // TODO: cleanup
  4757. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  4758. };
  4759. // show/hide added/changed/removed items
  4760. Object.keys(queue).forEach(function (id) {
  4761. //var entry = queue[id];
  4762. var action = queue[id];
  4763. var item = items[id];
  4764. //var item = entry.item;
  4765. //noinspection FallthroughInSwitchStatementJS
  4766. switch (action) {
  4767. case 'add':
  4768. case 'update':
  4769. var itemData = itemsData && itemsData.get(id, dataOptions);
  4770. if (itemData) {
  4771. var type = itemData.type ||
  4772. (itemData.start && itemData.end && 'range') ||
  4773. options.type ||
  4774. 'box';
  4775. var constructor = ItemSet.types[type];
  4776. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4777. if (item) {
  4778. // update item
  4779. if (!constructor || !(item instanceof constructor)) {
  4780. // item type has changed, hide and delete the item
  4781. changed += item.hide();
  4782. item = null;
  4783. }
  4784. else {
  4785. item.data = itemData; // TODO: create a method item.setData ?
  4786. changed++;
  4787. }
  4788. }
  4789. if (!item) {
  4790. // create item
  4791. if (constructor) {
  4792. item = new constructor(me, itemData, options, defaultOptions);
  4793. item.id = id;
  4794. changed++;
  4795. }
  4796. else {
  4797. throw new TypeError('Unknown item type "' + type + '"');
  4798. }
  4799. }
  4800. // force a repaint (not only a reposition)
  4801. item.repaint();
  4802. items[id] = item;
  4803. }
  4804. // update queue
  4805. delete queue[id];
  4806. break;
  4807. case 'remove':
  4808. if (item) {
  4809. // remove the item from the set selected items
  4810. if (item.selected) {
  4811. me._deselect(id);
  4812. }
  4813. // remove DOM of the item
  4814. changed += item.hide();
  4815. }
  4816. // update lists
  4817. delete items[id];
  4818. delete queue[id];
  4819. break;
  4820. default:
  4821. console.log('Error: unknown action "' + action + '"');
  4822. }
  4823. });
  4824. // reposition all items. Show items only when in the visible area
  4825. util.forEach(this.items, function (item) {
  4826. if (item.visible) {
  4827. changed += item.show();
  4828. item.reposition();
  4829. }
  4830. else {
  4831. changed += item.hide();
  4832. }
  4833. });
  4834. return (changed > 0);
  4835. };
  4836. /**
  4837. * Get the foreground container element
  4838. * @return {HTMLElement} foreground
  4839. */
  4840. ItemSet.prototype.getForeground = function getForeground() {
  4841. return this.dom.foreground;
  4842. };
  4843. /**
  4844. * Get the background container element
  4845. * @return {HTMLElement} background
  4846. */
  4847. ItemSet.prototype.getBackground = function getBackground() {
  4848. return this.dom.background;
  4849. };
  4850. /**
  4851. * Get the axis container element
  4852. * @return {HTMLElement} axis
  4853. */
  4854. ItemSet.prototype.getAxis = function getAxis() {
  4855. return this.dom.axis;
  4856. };
  4857. /**
  4858. * Reflow the component
  4859. * @return {Boolean} resized
  4860. */
  4861. ItemSet.prototype.reflow = function reflow () {
  4862. var changed = 0,
  4863. options = this.options,
  4864. marginAxis = options.margin && options.margin.axis || this.defaultOptions.margin.axis,
  4865. marginItem = options.margin && options.margin.item || this.defaultOptions.margin.item,
  4866. update = util.updateProperty,
  4867. asNumber = util.option.asNumber,
  4868. asSize = util.option.asSize,
  4869. frame = this.frame;
  4870. if (frame) {
  4871. this._updateConversion();
  4872. util.forEach(this.items, function (item) {
  4873. changed += item.reflow();
  4874. });
  4875. // TODO: stack.update should be triggered via an event, in stack itself
  4876. // TODO: only update the stack when there are changed items
  4877. this.stack.update();
  4878. var maxHeight = asNumber(options.maxHeight);
  4879. var fixedHeight = (asSize(options.height) != null);
  4880. var height;
  4881. if (fixedHeight) {
  4882. height = frame.offsetHeight;
  4883. }
  4884. else {
  4885. // height is not specified, determine the height from the height and positioned items
  4886. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4887. if (visibleItems.length) {
  4888. var min = visibleItems[0].top;
  4889. var max = visibleItems[0].top + visibleItems[0].height;
  4890. util.forEach(visibleItems, function (item) {
  4891. min = Math.min(min, item.top);
  4892. max = Math.max(max, (item.top + item.height));
  4893. });
  4894. height = (max - min) + marginAxis + marginItem;
  4895. }
  4896. else {
  4897. height = marginAxis + marginItem;
  4898. }
  4899. }
  4900. if (maxHeight != null) {
  4901. height = Math.min(height, maxHeight);
  4902. }
  4903. changed += update(this, 'height', height);
  4904. // calculate height from items
  4905. changed += update(this, 'top', frame.offsetTop);
  4906. changed += update(this, 'left', frame.offsetLeft);
  4907. changed += update(this, 'width', frame.offsetWidth);
  4908. }
  4909. else {
  4910. changed += 1;
  4911. }
  4912. return (changed > 0);
  4913. };
  4914. /**
  4915. * Hide this component from the DOM
  4916. * @return {Boolean} changed
  4917. */
  4918. ItemSet.prototype.hide = function hide() {
  4919. var changed = false;
  4920. // remove the DOM
  4921. if (this.frame && this.frame.parentNode) {
  4922. this.frame.parentNode.removeChild(this.frame);
  4923. changed = true;
  4924. }
  4925. if (this.dom.axis && this.dom.axis.parentNode) {
  4926. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4927. changed = true;
  4928. }
  4929. return changed;
  4930. };
  4931. /**
  4932. * Set items
  4933. * @param {vis.DataSet | null} items
  4934. */
  4935. ItemSet.prototype.setItems = function setItems(items) {
  4936. var me = this,
  4937. ids,
  4938. oldItemsData = this.itemsData;
  4939. // replace the dataset
  4940. if (!items) {
  4941. this.itemsData = null;
  4942. }
  4943. else if (items instanceof DataSet || items instanceof DataView) {
  4944. this.itemsData = items;
  4945. }
  4946. else {
  4947. throw new TypeError('Data must be an instance of DataSet');
  4948. }
  4949. if (oldItemsData) {
  4950. // unsubscribe from old dataset
  4951. util.forEach(this.listeners, function (callback, event) {
  4952. oldItemsData.unsubscribe(event, callback);
  4953. });
  4954. // remove all drawn items
  4955. ids = oldItemsData.getIds();
  4956. this._onRemove(ids);
  4957. }
  4958. if (this.itemsData) {
  4959. // subscribe to new dataset
  4960. var id = this.id;
  4961. util.forEach(this.listeners, function (callback, event) {
  4962. me.itemsData.subscribe(event, callback, id);
  4963. });
  4964. // draw all new items
  4965. ids = this.itemsData.getIds();
  4966. this._onAdd(ids);
  4967. }
  4968. };
  4969. /**
  4970. * Get the current items items
  4971. * @returns {vis.DataSet | null}
  4972. */
  4973. ItemSet.prototype.getItems = function getItems() {
  4974. return this.itemsData;
  4975. };
  4976. /**
  4977. * Handle updated items
  4978. * @param {Number[]} ids
  4979. * @private
  4980. */
  4981. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4982. this._toQueue('update', ids);
  4983. };
  4984. /**
  4985. * Handle changed items
  4986. * @param {Number[]} ids
  4987. * @private
  4988. */
  4989. ItemSet.prototype._onAdd = function _onAdd(ids) {
  4990. this._toQueue('add', ids);
  4991. };
  4992. /**
  4993. * Handle removed items
  4994. * @param {Number[]} ids
  4995. * @private
  4996. */
  4997. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4998. this._toQueue('remove', ids);
  4999. };
  5000. /**
  5001. * Put items in the queue to be added/updated/remove
  5002. * @param {String} action can be 'add', 'update', 'remove'
  5003. * @param {Number[]} ids
  5004. */
  5005. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  5006. var queue = this.queue;
  5007. ids.forEach(function (id) {
  5008. queue[id] = action;
  5009. });
  5010. if (this.controller) {
  5011. //this.requestReflow();
  5012. this.requestRepaint();
  5013. }
  5014. };
  5015. /**
  5016. * Calculate the scale and offset to convert a position on screen to the
  5017. * corresponding date and vice versa.
  5018. * After the method _updateConversion is executed once, the methods toTime
  5019. * and toScreen can be used.
  5020. * @private
  5021. */
  5022. ItemSet.prototype._updateConversion = function _updateConversion() {
  5023. var range = this.range;
  5024. if (!range) {
  5025. throw new Error('No range configured');
  5026. }
  5027. if (range.conversion) {
  5028. this.conversion = range.conversion(this.width);
  5029. }
  5030. else {
  5031. this.conversion = Range.conversion(range.start, range.end, this.width);
  5032. }
  5033. };
  5034. /**
  5035. * Convert a position on screen (pixels) to a datetime
  5036. * Before this method can be used, the method _updateConversion must be
  5037. * executed once.
  5038. * @param {int} x Position on the screen in pixels
  5039. * @return {Date} time The datetime the corresponds with given position x
  5040. */
  5041. ItemSet.prototype.toTime = function toTime(x) {
  5042. var conversion = this.conversion;
  5043. return new Date(x / conversion.scale + conversion.offset);
  5044. };
  5045. /**
  5046. * Convert a datetime (Date object) into a position on the screen
  5047. * Before this method can be used, the method _updateConversion must be
  5048. * executed once.
  5049. * @param {Date} time A date
  5050. * @return {int} x The position on the screen in pixels which corresponds
  5051. * with the given date.
  5052. */
  5053. ItemSet.prototype.toScreen = function toScreen(time) {
  5054. var conversion = this.conversion;
  5055. return (time.valueOf() - conversion.offset) * conversion.scale;
  5056. };
  5057. /**
  5058. * @constructor Item
  5059. * @param {ItemSet} parent
  5060. * @param {Object} data Object containing (optional) parameters type,
  5061. * start, end, content, group, className.
  5062. * @param {Object} [options] Options to set initial property values
  5063. * @param {Object} [defaultOptions] default options
  5064. * // TODO: describe available options
  5065. */
  5066. function Item (parent, data, options, defaultOptions) {
  5067. this.parent = parent;
  5068. this.data = data;
  5069. this.dom = null;
  5070. this.options = options || {};
  5071. this.defaultOptions = defaultOptions || {};
  5072. this.selected = false;
  5073. this.visible = false;
  5074. this.top = 0;
  5075. this.left = 0;
  5076. this.width = 0;
  5077. this.height = 0;
  5078. }
  5079. /**
  5080. * Select current item
  5081. */
  5082. Item.prototype.select = function select() {
  5083. this.selected = true;
  5084. if (this.visible) this.repaint();
  5085. };
  5086. /**
  5087. * Unselect current item
  5088. */
  5089. Item.prototype.unselect = function unselect() {
  5090. this.selected = false;
  5091. if (this.visible) this.repaint();
  5092. };
  5093. /**
  5094. * Show the Item in the DOM (when not already visible)
  5095. * @return {Boolean} changed
  5096. */
  5097. Item.prototype.show = function show() {
  5098. return false;
  5099. };
  5100. /**
  5101. * Hide the Item from the DOM (when visible)
  5102. * @return {Boolean} changed
  5103. */
  5104. Item.prototype.hide = function hide() {
  5105. return false;
  5106. };
  5107. /**
  5108. * Repaint the item
  5109. * @return {Boolean} changed
  5110. */
  5111. Item.prototype.repaint = function repaint() {
  5112. // should be implemented by the item
  5113. return false;
  5114. };
  5115. /**
  5116. * Reflow the item
  5117. * @return {Boolean} resized
  5118. */
  5119. Item.prototype.reflow = function reflow() {
  5120. // should be implemented by the item
  5121. return false;
  5122. };
  5123. /**
  5124. * Return the items width
  5125. * @return {Integer} width
  5126. */
  5127. Item.prototype.getWidth = function getWidth() {
  5128. return this.width;
  5129. }
  5130. /**
  5131. * @constructor ItemBox
  5132. * @extends Item
  5133. * @param {ItemSet} parent
  5134. * @param {Object} data Object containing parameters start
  5135. * content, className.
  5136. * @param {Object} [options] Options to set initial property values
  5137. * @param {Object} [defaultOptions] default options
  5138. * // TODO: describe available options
  5139. */
  5140. function ItemBox (parent, data, options, defaultOptions) {
  5141. this.props = {
  5142. dot: {
  5143. left: 0,
  5144. top: 0,
  5145. width: 0,
  5146. height: 0
  5147. },
  5148. line: {
  5149. top: 0,
  5150. left: 0,
  5151. width: 0,
  5152. height: 0
  5153. }
  5154. };
  5155. Item.call(this, parent, data, options, defaultOptions);
  5156. }
  5157. ItemBox.prototype = new Item (null, null);
  5158. /**
  5159. * Repaint the item
  5160. * @return {Boolean} changed
  5161. */
  5162. ItemBox.prototype.repaint = function repaint() {
  5163. // TODO: make an efficient repaint
  5164. var changed = false;
  5165. var dom = this.dom;
  5166. if (!dom) {
  5167. this._create();
  5168. dom = this.dom;
  5169. changed = true;
  5170. }
  5171. if (dom) {
  5172. if (!this.parent) {
  5173. throw new Error('Cannot repaint item: no parent attached');
  5174. }
  5175. if (!dom.box.parentNode) {
  5176. var foreground = this.parent.getForeground();
  5177. if (!foreground) {
  5178. throw new Error('Cannot repaint time axis: ' +
  5179. 'parent has no foreground container element');
  5180. }
  5181. foreground.appendChild(dom.box);
  5182. changed = true;
  5183. }
  5184. if (!dom.line.parentNode) {
  5185. var background = this.parent.getBackground();
  5186. if (!background) {
  5187. throw new Error('Cannot repaint time axis: ' +
  5188. 'parent has no background container element');
  5189. }
  5190. background.appendChild(dom.line);
  5191. changed = true;
  5192. }
  5193. if (!dom.dot.parentNode) {
  5194. var axis = this.parent.getAxis();
  5195. if (!background) {
  5196. throw new Error('Cannot repaint time axis: ' +
  5197. 'parent has no axis container element');
  5198. }
  5199. axis.appendChild(dom.dot);
  5200. changed = true;
  5201. }
  5202. // update contents
  5203. if (this.data.content != this.content) {
  5204. this.content = this.data.content;
  5205. if (this.content instanceof Element) {
  5206. dom.content.innerHTML = '';
  5207. dom.content.appendChild(this.content);
  5208. }
  5209. else if (this.data.content != undefined) {
  5210. dom.content.innerHTML = this.content;
  5211. }
  5212. else {
  5213. throw new Error('Property "content" missing in item ' + this.data.id);
  5214. }
  5215. changed = true;
  5216. }
  5217. // update class
  5218. var className = (this.data.className? ' ' + this.data.className : '') +
  5219. (this.selected ? ' selected' : '');
  5220. if (this.className != className) {
  5221. this.className = className;
  5222. dom.box.className = 'item box' + className;
  5223. dom.line.className = 'item line' + className;
  5224. dom.dot.className = 'item dot' + className;
  5225. changed = true;
  5226. }
  5227. }
  5228. return changed;
  5229. };
  5230. /**
  5231. * Show the item in the DOM (when not already visible). The items DOM will
  5232. * be created when needed.
  5233. * @return {Boolean} changed
  5234. */
  5235. ItemBox.prototype.show = function show() {
  5236. if (!this.dom || !this.dom.box.parentNode) {
  5237. return this.repaint();
  5238. }
  5239. else {
  5240. return false;
  5241. }
  5242. };
  5243. /**
  5244. * Hide the item from the DOM (when visible)
  5245. * @return {Boolean} changed
  5246. */
  5247. ItemBox.prototype.hide = function hide() {
  5248. var changed = false,
  5249. dom = this.dom;
  5250. if (dom) {
  5251. if (dom.box.parentNode) {
  5252. dom.box.parentNode.removeChild(dom.box);
  5253. changed = true;
  5254. }
  5255. if (dom.line.parentNode) {
  5256. dom.line.parentNode.removeChild(dom.line);
  5257. }
  5258. if (dom.dot.parentNode) {
  5259. dom.dot.parentNode.removeChild(dom.dot);
  5260. }
  5261. }
  5262. return changed;
  5263. };
  5264. /**
  5265. * Reflow the item: calculate its actual size and position from the DOM
  5266. * @return {boolean} resized returns true if the axis is resized
  5267. * @override
  5268. */
  5269. ItemBox.prototype.reflow = function reflow() {
  5270. var changed = 0,
  5271. update,
  5272. dom,
  5273. props,
  5274. options,
  5275. margin,
  5276. start,
  5277. align,
  5278. orientation,
  5279. top,
  5280. left,
  5281. data,
  5282. range;
  5283. if (this.data.start == undefined) {
  5284. throw new Error('Property "start" missing in item ' + this.data.id);
  5285. }
  5286. data = this.data;
  5287. range = this.parent && this.parent.range;
  5288. if (data && range) {
  5289. // TODO: account for the width of the item
  5290. var interval = (range.end - range.start);
  5291. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  5292. }
  5293. else {
  5294. this.visible = false;
  5295. }
  5296. if (this.visible) {
  5297. dom = this.dom;
  5298. if (dom) {
  5299. update = util.updateProperty;
  5300. props = this.props;
  5301. options = this.options;
  5302. start = this.parent.toScreen(this.data.start);
  5303. align = options.align || this.defaultOptions.align;
  5304. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5305. orientation = options.orientation || this.defaultOptions.orientation;
  5306. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5307. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5308. changed += update(props.line, 'width', dom.line.offsetWidth);
  5309. changed += update(props.line, 'height', dom.line.offsetHeight);
  5310. changed += update(props.line, 'top', dom.line.offsetTop);
  5311. changed += update(this, 'width', dom.box.offsetWidth);
  5312. changed += update(this, 'height', dom.box.offsetHeight);
  5313. if (align == 'right') {
  5314. left = start - this.width;
  5315. }
  5316. else if (align == 'left') {
  5317. left = start;
  5318. }
  5319. else {
  5320. // default or 'center'
  5321. left = start - this.width / 2;
  5322. }
  5323. changed += update(this, 'left', left);
  5324. changed += update(props.line, 'left', start - props.line.width / 2);
  5325. changed += update(props.dot, 'left', start - props.dot.width / 2);
  5326. changed += update(props.dot, 'top', -props.dot.height / 2);
  5327. if (orientation == 'top') {
  5328. top = margin;
  5329. changed += update(this, 'top', top);
  5330. }
  5331. else {
  5332. // default or 'bottom'
  5333. var parentHeight = this.parent.height;
  5334. top = parentHeight - this.height - margin;
  5335. changed += update(this, 'top', top);
  5336. }
  5337. }
  5338. else {
  5339. changed += 1;
  5340. }
  5341. }
  5342. return (changed > 0);
  5343. };
  5344. /**
  5345. * Create an items DOM
  5346. * @private
  5347. */
  5348. ItemBox.prototype._create = function _create() {
  5349. var dom = this.dom;
  5350. if (!dom) {
  5351. this.dom = dom = {};
  5352. // create the box
  5353. dom.box = document.createElement('DIV');
  5354. // className is updated in repaint()
  5355. // contents box (inside the background box). used for making margins
  5356. dom.content = document.createElement('DIV');
  5357. dom.content.className = 'content';
  5358. dom.box.appendChild(dom.content);
  5359. // line to axis
  5360. dom.line = document.createElement('DIV');
  5361. dom.line.className = 'line';
  5362. // dot on axis
  5363. dom.dot = document.createElement('DIV');
  5364. dom.dot.className = 'dot';
  5365. }
  5366. };
  5367. /**
  5368. * Reposition the item, recalculate its left, top, and width, using the current
  5369. * range and size of the items itemset
  5370. * @override
  5371. */
  5372. ItemBox.prototype.reposition = function reposition() {
  5373. var dom = this.dom,
  5374. props = this.props,
  5375. orientation = this.options.orientation || this.defaultOptions.orientation;
  5376. if (dom) {
  5377. var box = dom.box,
  5378. line = dom.line,
  5379. dot = dom.dot;
  5380. box.style.left = this.left + 'px';
  5381. box.style.top = this.top + 'px';
  5382. line.style.left = props.line.left + 'px';
  5383. if (orientation == 'top') {
  5384. line.style.top = 0 + 'px';
  5385. line.style.height = this.top + 'px';
  5386. }
  5387. else {
  5388. // orientation 'bottom'
  5389. line.style.top = (this.top + this.height) + 'px';
  5390. line.style.height = Math.max(this.parent.height - this.top - this.height +
  5391. this.props.dot.height / 2, 0) + 'px';
  5392. }
  5393. dot.style.left = props.dot.left + 'px';
  5394. dot.style.top = props.dot.top + 'px';
  5395. }
  5396. };
  5397. /**
  5398. * @constructor ItemPoint
  5399. * @extends Item
  5400. * @param {ItemSet} parent
  5401. * @param {Object} data Object containing parameters start
  5402. * content, className.
  5403. * @param {Object} [options] Options to set initial property values
  5404. * @param {Object} [defaultOptions] default options
  5405. * // TODO: describe available options
  5406. */
  5407. function ItemPoint (parent, data, options, defaultOptions) {
  5408. this.props = {
  5409. dot: {
  5410. top: 0,
  5411. width: 0,
  5412. height: 0
  5413. },
  5414. content: {
  5415. height: 0,
  5416. marginLeft: 0
  5417. }
  5418. };
  5419. Item.call(this, parent, data, options, defaultOptions);
  5420. }
  5421. ItemPoint.prototype = new Item (null, null);
  5422. /**
  5423. * Repaint the item
  5424. * @return {Boolean} changed
  5425. */
  5426. ItemPoint.prototype.repaint = function repaint() {
  5427. // TODO: make an efficient repaint
  5428. var changed = false;
  5429. var dom = this.dom;
  5430. if (!dom) {
  5431. this._create();
  5432. dom = this.dom;
  5433. changed = true;
  5434. }
  5435. if (dom) {
  5436. if (!this.parent) {
  5437. throw new Error('Cannot repaint item: no parent attached');
  5438. }
  5439. var foreground = this.parent.getForeground();
  5440. if (!foreground) {
  5441. throw new Error('Cannot repaint time axis: ' +
  5442. 'parent has no foreground container element');
  5443. }
  5444. if (!dom.point.parentNode) {
  5445. foreground.appendChild(dom.point);
  5446. foreground.appendChild(dom.point);
  5447. changed = true;
  5448. }
  5449. // update contents
  5450. if (this.data.content != this.content) {
  5451. this.content = this.data.content;
  5452. if (this.content instanceof Element) {
  5453. dom.content.innerHTML = '';
  5454. dom.content.appendChild(this.content);
  5455. }
  5456. else if (this.data.content != undefined) {
  5457. dom.content.innerHTML = this.content;
  5458. }
  5459. else {
  5460. throw new Error('Property "content" missing in item ' + this.data.id);
  5461. }
  5462. changed = true;
  5463. }
  5464. // update class
  5465. var className = (this.data.className? ' ' + this.data.className : '') +
  5466. (this.selected ? ' selected' : '');
  5467. if (this.className != className) {
  5468. this.className = className;
  5469. dom.point.className = 'item point' + className;
  5470. changed = true;
  5471. }
  5472. }
  5473. return changed;
  5474. };
  5475. /**
  5476. * Show the item in the DOM (when not already visible). The items DOM will
  5477. * be created when needed.
  5478. * @return {Boolean} changed
  5479. */
  5480. ItemPoint.prototype.show = function show() {
  5481. if (!this.dom || !this.dom.point.parentNode) {
  5482. return this.repaint();
  5483. }
  5484. else {
  5485. return false;
  5486. }
  5487. };
  5488. /**
  5489. * Hide the item from the DOM (when visible)
  5490. * @return {Boolean} changed
  5491. */
  5492. ItemPoint.prototype.hide = function hide() {
  5493. var changed = false,
  5494. dom = this.dom;
  5495. if (dom) {
  5496. if (dom.point.parentNode) {
  5497. dom.point.parentNode.removeChild(dom.point);
  5498. changed = true;
  5499. }
  5500. }
  5501. return changed;
  5502. };
  5503. /**
  5504. * Reflow the item: calculate its actual size from the DOM
  5505. * @return {boolean} resized returns true if the axis is resized
  5506. * @override
  5507. */
  5508. ItemPoint.prototype.reflow = function reflow() {
  5509. var changed = 0,
  5510. update,
  5511. dom,
  5512. props,
  5513. options,
  5514. margin,
  5515. orientation,
  5516. start,
  5517. top,
  5518. data,
  5519. range;
  5520. if (this.data.start == undefined) {
  5521. throw new Error('Property "start" missing in item ' + this.data.id);
  5522. }
  5523. data = this.data;
  5524. range = this.parent && this.parent.range;
  5525. if (data && range) {
  5526. // TODO: account for the width of the item
  5527. var interval = (range.end - range.start);
  5528. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  5529. }
  5530. else {
  5531. this.visible = false;
  5532. }
  5533. if (this.visible) {
  5534. dom = this.dom;
  5535. if (dom) {
  5536. update = util.updateProperty;
  5537. props = this.props;
  5538. options = this.options;
  5539. orientation = options.orientation || this.defaultOptions.orientation;
  5540. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5541. start = this.parent.toScreen(this.data.start);
  5542. changed += update(this, 'width', dom.point.offsetWidth);
  5543. changed += update(this, 'height', dom.point.offsetHeight);
  5544. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5545. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5546. changed += update(props.content, 'height', dom.content.offsetHeight);
  5547. if (orientation == 'top') {
  5548. top = margin;
  5549. }
  5550. else {
  5551. // default or 'bottom'
  5552. var parentHeight = this.parent.height;
  5553. top = Math.max(parentHeight - this.height - margin, 0);
  5554. }
  5555. changed += update(this, 'top', top);
  5556. changed += update(this, 'left', start - props.dot.width / 2);
  5557. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5558. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5559. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5560. }
  5561. else {
  5562. changed += 1;
  5563. }
  5564. }
  5565. return (changed > 0);
  5566. };
  5567. /**
  5568. * Create an items DOM
  5569. * @private
  5570. */
  5571. ItemPoint.prototype._create = function _create() {
  5572. var dom = this.dom;
  5573. if (!dom) {
  5574. this.dom = dom = {};
  5575. // background box
  5576. dom.point = document.createElement('div');
  5577. // className is updated in repaint()
  5578. // contents box, right from the dot
  5579. dom.content = document.createElement('div');
  5580. dom.content.className = 'content';
  5581. dom.point.appendChild(dom.content);
  5582. // dot at start
  5583. dom.dot = document.createElement('div');
  5584. dom.dot.className = 'dot';
  5585. dom.point.appendChild(dom.dot);
  5586. }
  5587. };
  5588. /**
  5589. * Reposition the item, recalculate its left, top, and width, using the current
  5590. * range and size of the items itemset
  5591. * @override
  5592. */
  5593. ItemPoint.prototype.reposition = function reposition() {
  5594. var dom = this.dom,
  5595. props = this.props;
  5596. if (dom) {
  5597. dom.point.style.top = this.top + 'px';
  5598. dom.point.style.left = this.left + 'px';
  5599. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5600. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5601. dom.dot.style.top = props.dot.top + 'px';
  5602. }
  5603. };
  5604. /**
  5605. * @constructor ItemRange
  5606. * @extends Item
  5607. * @param {ItemSet} parent
  5608. * @param {Object} data Object containing parameters start, end
  5609. * content, className.
  5610. * @param {Object} [options] Options to set initial property values
  5611. * @param {Object} [defaultOptions] default options
  5612. * // TODO: describe available options
  5613. */
  5614. function ItemRange (parent, data, options, defaultOptions) {
  5615. this.props = {
  5616. content: {
  5617. left: 0,
  5618. width: 0
  5619. }
  5620. };
  5621. Item.call(this, parent, data, options, defaultOptions);
  5622. }
  5623. ItemRange.prototype = new Item (null, null);
  5624. /**
  5625. * Repaint the item
  5626. * @return {Boolean} changed
  5627. */
  5628. ItemRange.prototype.repaint = function repaint() {
  5629. // TODO: make an efficient repaint
  5630. var changed = false;
  5631. var dom = this.dom;
  5632. if (!dom) {
  5633. this._create();
  5634. dom = this.dom;
  5635. changed = true;
  5636. }
  5637. if (dom) {
  5638. if (!this.parent) {
  5639. throw new Error('Cannot repaint item: no parent attached');
  5640. }
  5641. var foreground = this.parent.getForeground();
  5642. if (!foreground) {
  5643. throw new Error('Cannot repaint time axis: ' +
  5644. 'parent has no foreground container element');
  5645. }
  5646. if (!dom.box.parentNode) {
  5647. foreground.appendChild(dom.box);
  5648. changed = true;
  5649. }
  5650. // update content
  5651. if (this.data.content != this.content) {
  5652. this.content = this.data.content;
  5653. if (this.content instanceof Element) {
  5654. dom.content.innerHTML = '';
  5655. dom.content.appendChild(this.content);
  5656. }
  5657. else if (this.data.content != undefined) {
  5658. dom.content.innerHTML = this.content;
  5659. }
  5660. else {
  5661. throw new Error('Property "content" missing in item ' + this.data.id);
  5662. }
  5663. changed = true;
  5664. }
  5665. // update class
  5666. var className = (this.data.className? ' ' + this.data.className : '') +
  5667. (this.selected ? ' selected' : '');
  5668. if (this.className != className) {
  5669. this.className = className;
  5670. dom.box.className = 'item range' + className;
  5671. changed = true;
  5672. }
  5673. }
  5674. return changed;
  5675. };
  5676. /**
  5677. * Show the item in the DOM (when not already visible). The items DOM will
  5678. * be created when needed.
  5679. * @return {Boolean} changed
  5680. */
  5681. ItemRange.prototype.show = function show() {
  5682. if (!this.dom || !this.dom.box.parentNode) {
  5683. return this.repaint();
  5684. }
  5685. else {
  5686. return false;
  5687. }
  5688. };
  5689. /**
  5690. * Hide the item from the DOM (when visible)
  5691. * @return {Boolean} changed
  5692. */
  5693. ItemRange.prototype.hide = function hide() {
  5694. var changed = false,
  5695. dom = this.dom;
  5696. if (dom) {
  5697. if (dom.box.parentNode) {
  5698. dom.box.parentNode.removeChild(dom.box);
  5699. changed = true;
  5700. }
  5701. }
  5702. return changed;
  5703. };
  5704. /**
  5705. * Reflow the item: calculate its actual size from the DOM
  5706. * @return {boolean} resized returns true if the axis is resized
  5707. * @override
  5708. */
  5709. ItemRange.prototype.reflow = function reflow() {
  5710. var changed = 0,
  5711. dom,
  5712. props,
  5713. options,
  5714. margin,
  5715. padding,
  5716. parent,
  5717. start,
  5718. end,
  5719. data,
  5720. range,
  5721. update,
  5722. box,
  5723. parentWidth,
  5724. contentLeft,
  5725. orientation,
  5726. top;
  5727. if (this.data.start == undefined) {
  5728. throw new Error('Property "start" missing in item ' + this.data.id);
  5729. }
  5730. if (this.data.end == undefined) {
  5731. throw new Error('Property "end" missing in item ' + this.data.id);
  5732. }
  5733. data = this.data;
  5734. range = this.parent && this.parent.range;
  5735. if (data && range) {
  5736. // TODO: account for the width of the item. Take some margin
  5737. this.visible = (data.start < range.end) && (data.end > range.start);
  5738. }
  5739. else {
  5740. this.visible = false;
  5741. }
  5742. if (this.visible) {
  5743. dom = this.dom;
  5744. if (dom) {
  5745. props = this.props;
  5746. options = this.options;
  5747. parent = this.parent;
  5748. start = parent.toScreen(this.data.start);
  5749. end = parent.toScreen(this.data.end);
  5750. update = util.updateProperty;
  5751. box = dom.box;
  5752. parentWidth = parent.width;
  5753. orientation = options.orientation || this.defaultOptions.orientation;
  5754. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5755. padding = options.padding || this.defaultOptions.padding;
  5756. changed += update(props.content, 'width', dom.content.offsetWidth);
  5757. changed += update(this, 'height', box.offsetHeight);
  5758. // limit the width of the this, as browsers cannot draw very wide divs
  5759. if (start < -parentWidth) {
  5760. start = -parentWidth;
  5761. }
  5762. if (end > 2 * parentWidth) {
  5763. end = 2 * parentWidth;
  5764. }
  5765. // when range exceeds left of the window, position the contents at the left of the visible area
  5766. if (start < 0) {
  5767. contentLeft = Math.min(-start,
  5768. (end - start - props.content.width - 2 * padding));
  5769. // TODO: remove the need for options.padding. it's terrible.
  5770. }
  5771. else {
  5772. contentLeft = 0;
  5773. }
  5774. changed += update(props.content, 'left', contentLeft);
  5775. if (orientation == 'top') {
  5776. top = margin;
  5777. changed += update(this, 'top', top);
  5778. }
  5779. else {
  5780. // default or 'bottom'
  5781. top = parent.height - this.height - margin;
  5782. changed += update(this, 'top', top);
  5783. }
  5784. changed += update(this, 'left', start);
  5785. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  5786. }
  5787. else {
  5788. changed += 1;
  5789. }
  5790. }
  5791. return (changed > 0);
  5792. };
  5793. /**
  5794. * Create an items DOM
  5795. * @private
  5796. */
  5797. ItemRange.prototype._create = function _create() {
  5798. var dom = this.dom;
  5799. if (!dom) {
  5800. this.dom = dom = {};
  5801. // background box
  5802. dom.box = document.createElement('div');
  5803. // className is updated in repaint()
  5804. // contents box
  5805. dom.content = document.createElement('div');
  5806. dom.content.className = 'content';
  5807. dom.box.appendChild(dom.content);
  5808. }
  5809. };
  5810. /**
  5811. * Reposition the item, recalculate its left, top, and width, using the current
  5812. * range and size of the items itemset
  5813. * @override
  5814. */
  5815. ItemRange.prototype.reposition = function reposition() {
  5816. var dom = this.dom,
  5817. props = this.props;
  5818. if (dom) {
  5819. dom.box.style.top = this.top + 'px';
  5820. dom.box.style.left = this.left + 'px';
  5821. dom.box.style.width = this.width + 'px';
  5822. dom.content.style.left = props.content.left + 'px';
  5823. }
  5824. };
  5825. /**
  5826. * @constructor ItemRangeOverflow
  5827. * @extends ItemRange
  5828. * @param {ItemSet} parent
  5829. * @param {Object} data Object containing parameters start, end
  5830. * content, className.
  5831. * @param {Object} [options] Options to set initial property values
  5832. * @param {Object} [defaultOptions] default options
  5833. * // TODO: describe available options
  5834. */
  5835. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  5836. this.props = {
  5837. content: {
  5838. left: 0,
  5839. width: 0
  5840. }
  5841. };
  5842. ItemRange.call(this, parent, data, options, defaultOptions);
  5843. }
  5844. ItemRangeOverflow.prototype = new ItemRange (null, null);
  5845. /**
  5846. * Repaint the item
  5847. * @return {Boolean} changed
  5848. */
  5849. ItemRangeOverflow.prototype.repaint = function repaint() {
  5850. // TODO: make an efficient repaint
  5851. var changed = false;
  5852. var dom = this.dom;
  5853. if (!dom) {
  5854. this._create();
  5855. dom = this.dom;
  5856. changed = true;
  5857. }
  5858. if (dom) {
  5859. if (!this.parent) {
  5860. throw new Error('Cannot repaint item: no parent attached');
  5861. }
  5862. var foreground = this.parent.getForeground();
  5863. if (!foreground) {
  5864. throw new Error('Cannot repaint time axis: ' +
  5865. 'parent has no foreground container element');
  5866. }
  5867. if (!dom.box.parentNode) {
  5868. foreground.appendChild(dom.box);
  5869. changed = true;
  5870. }
  5871. // update content
  5872. if (this.data.content != this.content) {
  5873. this.content = this.data.content;
  5874. if (this.content instanceof Element) {
  5875. dom.content.innerHTML = '';
  5876. dom.content.appendChild(this.content);
  5877. }
  5878. else if (this.data.content != undefined) {
  5879. dom.content.innerHTML = this.content;
  5880. }
  5881. else {
  5882. throw new Error('Property "content" missing in item ' + this.data.id);
  5883. }
  5884. changed = true;
  5885. }
  5886. // update class
  5887. var className = this.data.className ? (' ' + this.data.className) : '';
  5888. if (this.className != className) {
  5889. this.className = className;
  5890. dom.box.className = 'item rangeoverflow' + className;
  5891. changed = true;
  5892. }
  5893. }
  5894. return changed;
  5895. };
  5896. /**
  5897. * Return the items width
  5898. * @return {Number} width
  5899. */
  5900. ItemRangeOverflow.prototype.getWidth = function getWidth() {
  5901. if (this.props.content !== undefined && this.width < this.props.content.width)
  5902. return this.props.content.width;
  5903. else
  5904. return this.width;
  5905. };
  5906. /**
  5907. * @constructor Group
  5908. * @param {GroupSet} parent
  5909. * @param {Number | String} groupId
  5910. * @param {Object} [options] Options to set initial property values
  5911. * // TODO: describe available options
  5912. * @extends Component
  5913. */
  5914. function Group (parent, groupId, options) {
  5915. this.id = util.randomUUID();
  5916. this.parent = parent;
  5917. this.groupId = groupId;
  5918. this.itemset = null; // ItemSet
  5919. this.options = options || {};
  5920. this.options.top = 0;
  5921. this.props = {
  5922. label: {
  5923. width: 0,
  5924. height: 0
  5925. }
  5926. };
  5927. this.top = 0;
  5928. this.left = 0;
  5929. this.width = 0;
  5930. this.height = 0;
  5931. }
  5932. Group.prototype = new Component();
  5933. // TODO: comment
  5934. Group.prototype.setOptions = Component.prototype.setOptions;
  5935. /**
  5936. * Get the container element of the panel, which can be used by a child to
  5937. * add its own widgets.
  5938. * @returns {HTMLElement} container
  5939. */
  5940. Group.prototype.getContainer = function () {
  5941. return this.parent.getContainer();
  5942. };
  5943. /**
  5944. * Set item set for the group. The group will create a view on the itemset,
  5945. * filtered by the groups id.
  5946. * @param {DataSet | DataView} items
  5947. */
  5948. Group.prototype.setItems = function setItems(items) {
  5949. if (this.itemset) {
  5950. // remove current item set
  5951. this.itemset.hide();
  5952. this.itemset.setItems();
  5953. this.parent.controller.remove(this.itemset);
  5954. this.itemset = null;
  5955. }
  5956. if (items) {
  5957. var groupId = this.groupId;
  5958. var itemsetOptions = Object.create(this.options);
  5959. this.itemset = new ItemSet(this, null, itemsetOptions);
  5960. this.itemset.setRange(this.parent.range);
  5961. this.view = new DataView(items, {
  5962. filter: function (item) {
  5963. return item.group == groupId;
  5964. }
  5965. });
  5966. this.itemset.setItems(this.view);
  5967. this.parent.controller.add(this.itemset);
  5968. }
  5969. };
  5970. /**
  5971. * Change the item selection, and/or get currently selected items
  5972. * @param {Array} [ids] An array with zero or more ids of the items to be selected.
  5973. * @return {Array} ids The ids of the selected items
  5974. */
  5975. Group.prototype.select = function select(ids) {
  5976. return this.itemset ? this.itemset.select(ids) : [];
  5977. };
  5978. /**
  5979. * Repaint the item
  5980. * @return {Boolean} changed
  5981. */
  5982. Group.prototype.repaint = function repaint() {
  5983. return false;
  5984. };
  5985. /**
  5986. * Reflow the item
  5987. * @return {Boolean} resized
  5988. */
  5989. Group.prototype.reflow = function reflow() {
  5990. var changed = 0,
  5991. update = util.updateProperty;
  5992. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  5993. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  5994. // TODO: reckon with the height of the group label
  5995. if (this.label) {
  5996. var inner = this.label.firstChild;
  5997. changed += update(this.props.label, 'width', inner.clientWidth);
  5998. changed += update(this.props.label, 'height', inner.clientHeight);
  5999. }
  6000. else {
  6001. changed += update(this.props.label, 'width', 0);
  6002. changed += update(this.props.label, 'height', 0);
  6003. }
  6004. return (changed > 0);
  6005. };
  6006. /**
  6007. * An GroupSet holds a set of groups
  6008. * @param {Component} parent
  6009. * @param {Component[]} [depends] Components on which this components depends
  6010. * (except for the parent)
  6011. * @param {Object} [options] See GroupSet.setOptions for the available
  6012. * options.
  6013. * @constructor GroupSet
  6014. * @extends Panel
  6015. */
  6016. function GroupSet(parent, depends, options) {
  6017. this.id = util.randomUUID();
  6018. this.parent = parent;
  6019. this.depends = depends;
  6020. this.options = options || {};
  6021. this.range = null; // Range or Object {start: number, end: number}
  6022. this.itemsData = null; // DataSet with items
  6023. this.groupsData = null; // DataSet with groups
  6024. this.groups = {}; // map with groups
  6025. this.dom = {};
  6026. this.props = {
  6027. labels: {
  6028. width: 0
  6029. }
  6030. };
  6031. // TODO: implement right orientation of the labels
  6032. // changes in groups are queued key/value map containing id/action
  6033. this.queue = {};
  6034. var me = this;
  6035. this.listeners = {
  6036. 'add': function (event, params) {
  6037. me._onAdd(params.items);
  6038. },
  6039. 'update': function (event, params) {
  6040. me._onUpdate(params.items);
  6041. },
  6042. 'remove': function (event, params) {
  6043. me._onRemove(params.items);
  6044. }
  6045. };
  6046. }
  6047. GroupSet.prototype = new Panel();
  6048. /**
  6049. * Set options for the GroupSet. Existing options will be extended/overwritten.
  6050. * @param {Object} [options] The following options are available:
  6051. * {String | function} groupsOrder
  6052. * TODO: describe options
  6053. */
  6054. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  6055. GroupSet.prototype.setRange = function (range) {
  6056. // TODO: implement setRange
  6057. };
  6058. /**
  6059. * Set items
  6060. * @param {vis.DataSet | null} items
  6061. */
  6062. GroupSet.prototype.setItems = function setItems(items) {
  6063. this.itemsData = items;
  6064. for (var id in this.groups) {
  6065. if (this.groups.hasOwnProperty(id)) {
  6066. var group = this.groups[id];
  6067. group.setItems(items);
  6068. }
  6069. }
  6070. };
  6071. /**
  6072. * Get items
  6073. * @return {vis.DataSet | null} items
  6074. */
  6075. GroupSet.prototype.getItems = function getItems() {
  6076. return this.itemsData;
  6077. };
  6078. /**
  6079. * Set range (start and end).
  6080. * @param {Range | Object} range A Range or an object containing start and end.
  6081. */
  6082. GroupSet.prototype.setRange = function setRange(range) {
  6083. this.range = range;
  6084. };
  6085. /**
  6086. * Set groups
  6087. * @param {vis.DataSet} groups
  6088. */
  6089. GroupSet.prototype.setGroups = function setGroups(groups) {
  6090. var me = this,
  6091. ids;
  6092. // unsubscribe from current dataset
  6093. if (this.groupsData) {
  6094. util.forEach(this.listeners, function (callback, event) {
  6095. me.groupsData.unsubscribe(event, callback);
  6096. });
  6097. // remove all drawn groups
  6098. ids = this.groupsData.getIds();
  6099. this._onRemove(ids);
  6100. }
  6101. // replace the dataset
  6102. if (!groups) {
  6103. this.groupsData = null;
  6104. }
  6105. else if (groups instanceof DataSet) {
  6106. this.groupsData = groups;
  6107. }
  6108. else {
  6109. this.groupsData = new DataSet({
  6110. convert: {
  6111. start: 'Date',
  6112. end: 'Date'
  6113. }
  6114. });
  6115. this.groupsData.add(groups);
  6116. }
  6117. if (this.groupsData) {
  6118. // subscribe to new dataset
  6119. var id = this.id;
  6120. util.forEach(this.listeners, function (callback, event) {
  6121. me.groupsData.subscribe(event, callback, id);
  6122. });
  6123. // draw all new groups
  6124. ids = this.groupsData.getIds();
  6125. this._onAdd(ids);
  6126. }
  6127. };
  6128. /**
  6129. * Get groups
  6130. * @return {vis.DataSet | null} groups
  6131. */
  6132. GroupSet.prototype.getGroups = function getGroups() {
  6133. return this.groupsData;
  6134. };
  6135. /**
  6136. * Change the item selection, and/or get currently selected items
  6137. * @param {Array} [ids] An array with zero or more ids of the items to be selected.
  6138. * @return {Array} ids The ids of the selected items
  6139. */
  6140. GroupSet.prototype.select = function select(ids) {
  6141. var selection = [],
  6142. groups = this.groups;
  6143. // iterate over each of the groups
  6144. for (var id in groups) {
  6145. if (groups.hasOwnProperty(id)) {
  6146. var group = groups[id];
  6147. selection = selection.concat(group.select(ids));
  6148. }
  6149. }
  6150. return selection;
  6151. };
  6152. /**
  6153. * Repaint the component
  6154. * @return {Boolean} changed
  6155. */
  6156. GroupSet.prototype.repaint = function repaint() {
  6157. var changed = 0,
  6158. i, id, group, label,
  6159. update = util.updateProperty,
  6160. asSize = util.option.asSize,
  6161. asElement = util.option.asElement,
  6162. options = this.options,
  6163. frame = this.dom.frame,
  6164. labels = this.dom.labels,
  6165. labelSet = this.dom.labelSet;
  6166. // create frame
  6167. if (!this.parent) {
  6168. throw new Error('Cannot repaint groupset: no parent attached');
  6169. }
  6170. var parentContainer = this.parent.getContainer();
  6171. if (!parentContainer) {
  6172. throw new Error('Cannot repaint groupset: parent has no container element');
  6173. }
  6174. if (!frame) {
  6175. frame = document.createElement('div');
  6176. frame.className = 'groupset';
  6177. this.dom.frame = frame;
  6178. var className = options.className;
  6179. if (className) {
  6180. util.addClassName(frame, util.option.asString(className));
  6181. }
  6182. changed += 1;
  6183. }
  6184. if (!frame.parentNode) {
  6185. parentContainer.appendChild(frame);
  6186. changed += 1;
  6187. }
  6188. // create labels
  6189. var labelContainer = asElement(options.labelContainer);
  6190. if (!labelContainer) {
  6191. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  6192. }
  6193. if (!labels) {
  6194. labels = document.createElement('div');
  6195. labels.className = 'labels';
  6196. this.dom.labels = labels;
  6197. }
  6198. if (!labelSet) {
  6199. labelSet = document.createElement('div');
  6200. labelSet.className = 'label-set';
  6201. labels.appendChild(labelSet);
  6202. this.dom.labelSet = labelSet;
  6203. }
  6204. if (!labels.parentNode || labels.parentNode != labelContainer) {
  6205. if (labels.parentNode) {
  6206. labels.parentNode.removeChild(labels.parentNode);
  6207. }
  6208. labelContainer.appendChild(labels);
  6209. }
  6210. // reposition frame
  6211. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  6212. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6213. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6214. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6215. // reposition labels
  6216. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  6217. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  6218. var me = this,
  6219. queue = this.queue,
  6220. groups = this.groups,
  6221. groupsData = this.groupsData;
  6222. // show/hide added/changed/removed groups
  6223. var ids = Object.keys(queue);
  6224. if (ids.length) {
  6225. ids.forEach(function (id) {
  6226. var action = queue[id];
  6227. var group = groups[id];
  6228. //noinspection FallthroughInSwitchStatementJS
  6229. switch (action) {
  6230. case 'add':
  6231. case 'update':
  6232. if (!group) {
  6233. var groupOptions = Object.create(me.options);
  6234. util.extend(groupOptions, {
  6235. height: null,
  6236. maxHeight: null
  6237. });
  6238. group = new Group(me, id, groupOptions);
  6239. group.setItems(me.itemsData); // attach items data
  6240. groups[id] = group;
  6241. me.controller.add(group);
  6242. }
  6243. // TODO: update group data
  6244. group.data = groupsData.get(id);
  6245. delete queue[id];
  6246. break;
  6247. case 'remove':
  6248. if (group) {
  6249. group.setItems(); // detach items data
  6250. delete groups[id];
  6251. me.controller.remove(group);
  6252. }
  6253. // update lists
  6254. delete queue[id];
  6255. break;
  6256. default:
  6257. console.log('Error: unknown action "' + action + '"');
  6258. }
  6259. });
  6260. // the groupset depends on each of the groups
  6261. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  6262. // TODO: apply dependencies of the groupset
  6263. // update the top positions of the groups in the correct order
  6264. var orderedGroups = this.groupsData.getIds({
  6265. order: this.options.groupOrder
  6266. });
  6267. for (i = 0; i < orderedGroups.length; i++) {
  6268. (function (group, prevGroup) {
  6269. var top = 0;
  6270. if (prevGroup) {
  6271. top = function () {
  6272. // TODO: top must reckon with options.maxHeight
  6273. return prevGroup.top + prevGroup.height;
  6274. }
  6275. }
  6276. group.setOptions({
  6277. top: top
  6278. });
  6279. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  6280. }
  6281. // (re)create the labels
  6282. while (labelSet.firstChild) {
  6283. labelSet.removeChild(labelSet.firstChild);
  6284. }
  6285. for (i = 0; i < orderedGroups.length; i++) {
  6286. id = orderedGroups[i];
  6287. label = this._createLabel(id);
  6288. labelSet.appendChild(label);
  6289. }
  6290. changed++;
  6291. }
  6292. // reposition the labels
  6293. // TODO: labels are not displayed correctly when orientation=='top'
  6294. // TODO: width of labelPanel is not immediately updated on a change in groups
  6295. for (id in groups) {
  6296. if (groups.hasOwnProperty(id)) {
  6297. group = groups[id];
  6298. label = group.label;
  6299. if (label) {
  6300. label.style.top = group.top + 'px';
  6301. label.style.height = group.height + 'px';
  6302. }
  6303. }
  6304. }
  6305. return (changed > 0);
  6306. };
  6307. /**
  6308. * Create a label for group with given id
  6309. * @param {Number} id
  6310. * @return {Element} label
  6311. * @private
  6312. */
  6313. GroupSet.prototype._createLabel = function(id) {
  6314. var group = this.groups[id];
  6315. var label = document.createElement('div');
  6316. label.className = 'label';
  6317. var inner = document.createElement('div');
  6318. inner.className = 'inner';
  6319. label.appendChild(inner);
  6320. var content = group.data && group.data.content;
  6321. if (content instanceof Element) {
  6322. inner.appendChild(content);
  6323. }
  6324. else if (content != undefined) {
  6325. inner.innerHTML = content;
  6326. }
  6327. var className = group.data && group.data.className;
  6328. if (className) {
  6329. util.addClassName(label, className);
  6330. }
  6331. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  6332. return label;
  6333. };
  6334. /**
  6335. * Get container element
  6336. * @return {HTMLElement} container
  6337. */
  6338. GroupSet.prototype.getContainer = function getContainer() {
  6339. return this.dom.frame;
  6340. };
  6341. /**
  6342. * Get the width of the group labels
  6343. * @return {Number} width
  6344. */
  6345. GroupSet.prototype.getLabelsWidth = function getContainer() {
  6346. return this.props.labels.width;
  6347. };
  6348. /**
  6349. * Reflow the component
  6350. * @return {Boolean} resized
  6351. */
  6352. GroupSet.prototype.reflow = function reflow() {
  6353. var changed = 0,
  6354. id, group,
  6355. options = this.options,
  6356. update = util.updateProperty,
  6357. asNumber = util.option.asNumber,
  6358. asSize = util.option.asSize,
  6359. frame = this.dom.frame;
  6360. if (frame) {
  6361. var maxHeight = asNumber(options.maxHeight);
  6362. var fixedHeight = (asSize(options.height) != null);
  6363. var height;
  6364. if (fixedHeight) {
  6365. height = frame.offsetHeight;
  6366. }
  6367. else {
  6368. // height is not specified, calculate the sum of the height of all groups
  6369. height = 0;
  6370. for (id in this.groups) {
  6371. if (this.groups.hasOwnProperty(id)) {
  6372. group = this.groups[id];
  6373. height += group.height;
  6374. }
  6375. }
  6376. }
  6377. if (maxHeight != null) {
  6378. height = Math.min(height, maxHeight);
  6379. }
  6380. changed += update(this, 'height', height);
  6381. changed += update(this, 'top', frame.offsetTop);
  6382. changed += update(this, 'left', frame.offsetLeft);
  6383. changed += update(this, 'width', frame.offsetWidth);
  6384. }
  6385. // calculate the maximum width of the labels
  6386. var width = 0;
  6387. for (id in this.groups) {
  6388. if (this.groups.hasOwnProperty(id)) {
  6389. group = this.groups[id];
  6390. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  6391. width = Math.max(width, labelWidth);
  6392. }
  6393. }
  6394. changed += update(this.props.labels, 'width', width);
  6395. return (changed > 0);
  6396. };
  6397. /**
  6398. * Hide the component from the DOM
  6399. * @return {Boolean} changed
  6400. */
  6401. GroupSet.prototype.hide = function hide() {
  6402. if (this.dom.frame && this.dom.frame.parentNode) {
  6403. this.dom.frame.parentNode.removeChild(this.dom.frame);
  6404. return true;
  6405. }
  6406. else {
  6407. return false;
  6408. }
  6409. };
  6410. /**
  6411. * Show the component in the DOM (when not already visible).
  6412. * A repaint will be executed when the component is not visible
  6413. * @return {Boolean} changed
  6414. */
  6415. GroupSet.prototype.show = function show() {
  6416. if (!this.dom.frame || !this.dom.frame.parentNode) {
  6417. return this.repaint();
  6418. }
  6419. else {
  6420. return false;
  6421. }
  6422. };
  6423. /**
  6424. * Handle updated groups
  6425. * @param {Number[]} ids
  6426. * @private
  6427. */
  6428. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  6429. this._toQueue(ids, 'update');
  6430. };
  6431. /**
  6432. * Handle changed groups
  6433. * @param {Number[]} ids
  6434. * @private
  6435. */
  6436. GroupSet.prototype._onAdd = function _onAdd(ids) {
  6437. this._toQueue(ids, 'add');
  6438. };
  6439. /**
  6440. * Handle removed groups
  6441. * @param {Number[]} ids
  6442. * @private
  6443. */
  6444. GroupSet.prototype._onRemove = function _onRemove(ids) {
  6445. this._toQueue(ids, 'remove');
  6446. };
  6447. /**
  6448. * Put groups in the queue to be added/updated/remove
  6449. * @param {Number[]} ids
  6450. * @param {String} action can be 'add', 'update', 'remove'
  6451. */
  6452. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  6453. var queue = this.queue;
  6454. ids.forEach(function (id) {
  6455. queue[id] = action;
  6456. });
  6457. if (this.controller) {
  6458. //this.requestReflow();
  6459. this.requestRepaint();
  6460. }
  6461. };
  6462. /**
  6463. * Create a timeline visualization
  6464. * @param {HTMLElement} container
  6465. * @param {vis.DataSet | Array | DataTable} [items]
  6466. * @param {Object} [options] See Timeline.setOptions for the available options.
  6467. * @constructor
  6468. */
  6469. function Timeline (container, items, options) {
  6470. var me = this;
  6471. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6472. this.options = {
  6473. orientation: 'bottom',
  6474. min: null,
  6475. max: null,
  6476. zoomMin: 10, // milliseconds
  6477. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6478. // moveable: true, // TODO: option moveable
  6479. // zoomable: true, // TODO: option zoomable
  6480. showMinorLabels: true,
  6481. showMajorLabels: true,
  6482. showCurrentTime: false,
  6483. showCustomTime: false,
  6484. autoResize: false
  6485. };
  6486. // controller
  6487. this.controller = new Controller();
  6488. // root panel
  6489. if (!container) {
  6490. throw new Error('No container element provided');
  6491. }
  6492. var rootOptions = Object.create(this.options);
  6493. rootOptions.height = function () {
  6494. // TODO: change to height
  6495. if (me.options.height) {
  6496. // fixed height
  6497. return me.options.height;
  6498. }
  6499. else {
  6500. // auto height
  6501. return (me.timeaxis.height + me.content.height) + 'px';
  6502. }
  6503. };
  6504. this.rootPanel = new RootPanel(container, rootOptions);
  6505. this.controller.add(this.rootPanel);
  6506. // item panel
  6507. var itemOptions = Object.create(this.options);
  6508. itemOptions.left = function () {
  6509. return me.labelPanel.width;
  6510. };
  6511. itemOptions.width = function () {
  6512. return me.rootPanel.width - me.labelPanel.width;
  6513. };
  6514. itemOptions.top = null;
  6515. itemOptions.height = null;
  6516. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  6517. this.controller.add(this.itemPanel);
  6518. // label panel
  6519. var labelOptions = Object.create(this.options);
  6520. labelOptions.top = null;
  6521. labelOptions.left = null;
  6522. labelOptions.height = null;
  6523. labelOptions.width = function () {
  6524. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  6525. return me.content.getLabelsWidth();
  6526. }
  6527. else {
  6528. return 0;
  6529. }
  6530. };
  6531. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  6532. this.controller.add(this.labelPanel);
  6533. // range
  6534. var rangeOptions = Object.create(this.options);
  6535. this.range = new Range(rangeOptions);
  6536. this.range.setRange(
  6537. now.clone().add('days', -3).valueOf(),
  6538. now.clone().add('days', 4).valueOf()
  6539. );
  6540. // TODO: reckon with options moveable and zoomable
  6541. this.range.subscribe(this.rootPanel, 'move', 'horizontal');
  6542. this.range.subscribe(this.rootPanel, 'zoom', 'horizontal');
  6543. this.range.on('rangechange', function () {
  6544. var force = true;
  6545. me.controller.requestReflow(force);
  6546. });
  6547. this.range.on('rangechanged', function () {
  6548. var force = true;
  6549. me.controller.requestReflow(force);
  6550. });
  6551. // TODO: put the listeners in setOptions, be able to dynamically change with options moveable and zoomable
  6552. // time axis
  6553. var timeaxisOptions = Object.create(rootOptions);
  6554. timeaxisOptions.range = this.range;
  6555. timeaxisOptions.left = null;
  6556. timeaxisOptions.top = null;
  6557. timeaxisOptions.width = '100%';
  6558. timeaxisOptions.height = null;
  6559. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6560. this.timeaxis.setRange(this.range);
  6561. this.controller.add(this.timeaxis);
  6562. // current time bar
  6563. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  6564. this.controller.add(this.currenttime);
  6565. // custom time bar
  6566. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  6567. this.controller.add(this.customtime);
  6568. // create groupset
  6569. this.setGroups(null);
  6570. this.itemsData = null; // DataSet
  6571. this.groupsData = null; // DataSet
  6572. // apply options
  6573. if (options) {
  6574. this.setOptions(options);
  6575. }
  6576. // create itemset and groupset
  6577. if (items) {
  6578. this.setItems(items);
  6579. }
  6580. }
  6581. /**
  6582. * Set options
  6583. * @param {Object} options TODO: describe the available options
  6584. */
  6585. Timeline.prototype.setOptions = function (options) {
  6586. util.extend(this.options, options);
  6587. // force update of range
  6588. // options.start and options.end can be undefined
  6589. //this.range.setRange(options.start, options.end);
  6590. this.range.setRange();
  6591. this.controller.reflow();
  6592. this.controller.repaint();
  6593. };
  6594. /**
  6595. * Set a custom time bar
  6596. * @param {Date} time
  6597. */
  6598. Timeline.prototype.setCustomTime = function (time) {
  6599. this.customtime._setCustomTime(time);
  6600. };
  6601. /**
  6602. * Retrieve the current custom time.
  6603. * @return {Date} customTime
  6604. */
  6605. Timeline.prototype.getCustomTime = function() {
  6606. return new Date(this.customtime.customTime.valueOf());
  6607. };
  6608. /**
  6609. * Set items
  6610. * @param {vis.DataSet | Array | DataTable | null} items
  6611. */
  6612. Timeline.prototype.setItems = function(items) {
  6613. var initialLoad = (this.itemsData == null);
  6614. // convert to type DataSet when needed
  6615. var newItemSet;
  6616. if (!items) {
  6617. newItemSet = null;
  6618. }
  6619. else if (items instanceof DataSet) {
  6620. newItemSet = items;
  6621. }
  6622. if (!(items instanceof DataSet)) {
  6623. newItemSet = new DataSet({
  6624. convert: {
  6625. start: 'Date',
  6626. end: 'Date'
  6627. }
  6628. });
  6629. newItemSet.add(items);
  6630. }
  6631. // set items
  6632. this.itemsData = newItemSet;
  6633. this.content.setItems(newItemSet);
  6634. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6635. // apply the data range as range
  6636. var dataRange = this.getItemRange();
  6637. // add 5% space on both sides
  6638. var min = dataRange.min;
  6639. var max = dataRange.max;
  6640. if (min != null && max != null) {
  6641. var interval = (max.valueOf() - min.valueOf());
  6642. if (interval <= 0) {
  6643. // prevent an empty interval
  6644. interval = 24 * 60 * 60 * 1000; // 1 day
  6645. }
  6646. min = new Date(min.valueOf() - interval * 0.05);
  6647. max = new Date(max.valueOf() + interval * 0.05);
  6648. }
  6649. // override specified start and/or end date
  6650. if (this.options.start != undefined) {
  6651. min = util.convert(this.options.start, 'Date');
  6652. }
  6653. if (this.options.end != undefined) {
  6654. max = util.convert(this.options.end, 'Date');
  6655. }
  6656. // apply range if there is a min or max available
  6657. if (min != null || max != null) {
  6658. this.range.setRange(min, max);
  6659. }
  6660. }
  6661. };
  6662. /**
  6663. * Set groups
  6664. * @param {vis.DataSet | Array | DataTable} groups
  6665. */
  6666. Timeline.prototype.setGroups = function(groups) {
  6667. var me = this;
  6668. this.groupsData = groups;
  6669. // switch content type between ItemSet or GroupSet when needed
  6670. var Type = this.groupsData ? GroupSet : ItemSet;
  6671. if (!(this.content instanceof Type)) {
  6672. // remove old content set
  6673. if (this.content) {
  6674. this.content.hide();
  6675. if (this.content.setItems) {
  6676. this.content.setItems(); // disconnect from items
  6677. }
  6678. if (this.content.setGroups) {
  6679. this.content.setGroups(); // disconnect from groups
  6680. }
  6681. this.controller.remove(this.content);
  6682. }
  6683. // create new content set
  6684. var options = Object.create(this.options);
  6685. util.extend(options, {
  6686. top: function () {
  6687. if (me.options.orientation == 'top') {
  6688. return me.timeaxis.height;
  6689. }
  6690. else {
  6691. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  6692. }
  6693. },
  6694. left: null,
  6695. width: '100%',
  6696. height: function () {
  6697. if (me.options.height) {
  6698. // fixed height
  6699. return me.itemPanel.height - me.timeaxis.height;
  6700. }
  6701. else {
  6702. // auto height
  6703. return null;
  6704. }
  6705. },
  6706. maxHeight: function () {
  6707. // TODO: change maxHeight to be a css string like '100%' or '300px'
  6708. if (me.options.maxHeight) {
  6709. if (!util.isNumber(me.options.maxHeight)) {
  6710. throw new TypeError('Number expected for property maxHeight');
  6711. }
  6712. return me.options.maxHeight - me.timeaxis.height;
  6713. }
  6714. else {
  6715. return null;
  6716. }
  6717. },
  6718. labelContainer: function () {
  6719. return me.labelPanel.getContainer();
  6720. }
  6721. });
  6722. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  6723. if (this.content.setRange) {
  6724. this.content.setRange(this.range);
  6725. }
  6726. if (this.content.setItems) {
  6727. this.content.setItems(this.itemsData);
  6728. }
  6729. if (this.content.setGroups) {
  6730. this.content.setGroups(this.groupsData);
  6731. }
  6732. this.controller.add(this.content);
  6733. }
  6734. };
  6735. /**
  6736. * Get the data range of the item set.
  6737. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6738. * When no minimum is found, min==null
  6739. * When no maximum is found, max==null
  6740. */
  6741. Timeline.prototype.getItemRange = function getItemRange() {
  6742. // calculate min from start filed
  6743. var itemsData = this.itemsData,
  6744. min = null,
  6745. max = null;
  6746. if (itemsData) {
  6747. // calculate the minimum value of the field 'start'
  6748. var minItem = itemsData.min('start');
  6749. min = minItem ? minItem.start.valueOf() : null;
  6750. // calculate maximum value of fields 'start' and 'end'
  6751. var maxStartItem = itemsData.max('start');
  6752. if (maxStartItem) {
  6753. max = maxStartItem.start.valueOf();
  6754. }
  6755. var maxEndItem = itemsData.max('end');
  6756. if (maxEndItem) {
  6757. if (max == null) {
  6758. max = maxEndItem.end.valueOf();
  6759. }
  6760. else {
  6761. max = Math.max(max, maxEndItem.end.valueOf());
  6762. }
  6763. }
  6764. }
  6765. return {
  6766. min: (min != null) ? new Date(min) : null,
  6767. max: (max != null) ? new Date(max) : null
  6768. };
  6769. };
  6770. /**
  6771. * Change the item selection, and/or get currently selected items
  6772. * @param {Array} [ids] An array with zero or more ids of the items to be selected.
  6773. * @return {Array} ids The ids of the selected items
  6774. */
  6775. Timeline.prototype.select = function select(ids) {
  6776. return this.content ? this.content.select(ids) : [];
  6777. };
  6778. (function(exports) {
  6779. /**
  6780. * Parse a text source containing data in DOT language into a JSON object.
  6781. * The object contains two lists: one with nodes and one with edges.
  6782. *
  6783. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6784. *
  6785. * @param {String} data Text containing a graph in DOT-notation
  6786. * @return {Object} graph An object containing two parameters:
  6787. * {Object[]} nodes
  6788. * {Object[]} edges
  6789. */
  6790. function parseDOT (data) {
  6791. dot = data;
  6792. return parseGraph();
  6793. }
  6794. // token types enumeration
  6795. var TOKENTYPE = {
  6796. NULL : 0,
  6797. DELIMITER : 1,
  6798. IDENTIFIER: 2,
  6799. UNKNOWN : 3
  6800. };
  6801. // map with all delimiters
  6802. var DELIMITERS = {
  6803. '{': true,
  6804. '}': true,
  6805. '[': true,
  6806. ']': true,
  6807. ';': true,
  6808. '=': true,
  6809. ',': true,
  6810. '->': true,
  6811. '--': true
  6812. };
  6813. var dot = ''; // current dot file
  6814. var index = 0; // current index in dot file
  6815. var c = ''; // current token character in expr
  6816. var token = ''; // current token
  6817. var tokenType = TOKENTYPE.NULL; // type of the token
  6818. /**
  6819. * Get the first character from the dot file.
  6820. * The character is stored into the char c. If the end of the dot file is
  6821. * reached, the function puts an empty string in c.
  6822. */
  6823. function first() {
  6824. index = 0;
  6825. c = dot.charAt(0);
  6826. }
  6827. /**
  6828. * Get the next character from the dot file.
  6829. * The character is stored into the char c. If the end of the dot file is
  6830. * reached, the function puts an empty string in c.
  6831. */
  6832. function next() {
  6833. index++;
  6834. c = dot.charAt(index);
  6835. }
  6836. /**
  6837. * Preview the next character from the dot file.
  6838. * @return {String} cNext
  6839. */
  6840. function nextPreview() {
  6841. return dot.charAt(index + 1);
  6842. }
  6843. /**
  6844. * Test whether given character is alphabetic or numeric
  6845. * @param {String} c
  6846. * @return {Boolean} isAlphaNumeric
  6847. */
  6848. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  6849. function isAlphaNumeric(c) {
  6850. return regexAlphaNumeric.test(c);
  6851. }
  6852. /**
  6853. * Merge all properties of object b into object b
  6854. * @param {Object} a
  6855. * @param {Object} b
  6856. * @return {Object} a
  6857. */
  6858. function merge (a, b) {
  6859. if (!a) {
  6860. a = {};
  6861. }
  6862. if (b) {
  6863. for (var name in b) {
  6864. if (b.hasOwnProperty(name)) {
  6865. a[name] = b[name];
  6866. }
  6867. }
  6868. }
  6869. return a;
  6870. }
  6871. /**
  6872. * Set a value in an object, where the provided parameter name can be a
  6873. * path with nested parameters. For example:
  6874. *
  6875. * var obj = {a: 2};
  6876. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  6877. *
  6878. * @param {Object} obj
  6879. * @param {String} path A parameter name or dot-separated parameter path,
  6880. * like "color.highlight.border".
  6881. * @param {*} value
  6882. */
  6883. function setValue(obj, path, value) {
  6884. var keys = path.split('.');
  6885. var o = obj;
  6886. while (keys.length) {
  6887. var key = keys.shift();
  6888. if (keys.length) {
  6889. // this isn't the end point
  6890. if (!o[key]) {
  6891. o[key] = {};
  6892. }
  6893. o = o[key];
  6894. }
  6895. else {
  6896. // this is the end point
  6897. o[key] = value;
  6898. }
  6899. }
  6900. }
  6901. /**
  6902. * Add a node to a graph object. If there is already a node with
  6903. * the same id, their attributes will be merged.
  6904. * @param {Object} graph
  6905. * @param {Object} node
  6906. */
  6907. function addNode(graph, node) {
  6908. var i, len;
  6909. var current = null;
  6910. // find root graph (in case of subgraph)
  6911. var graphs = [graph]; // list with all graphs from current graph to root graph
  6912. var root = graph;
  6913. while (root.parent) {
  6914. graphs.push(root.parent);
  6915. root = root.parent;
  6916. }
  6917. // find existing node (at root level) by its id
  6918. if (root.nodes) {
  6919. for (i = 0, len = root.nodes.length; i < len; i++) {
  6920. if (node.id === root.nodes[i].id) {
  6921. current = root.nodes[i];
  6922. break;
  6923. }
  6924. }
  6925. }
  6926. if (!current) {
  6927. // this is a new node
  6928. current = {
  6929. id: node.id
  6930. };
  6931. if (graph.node) {
  6932. // clone default attributes
  6933. current.attr = merge(current.attr, graph.node);
  6934. }
  6935. }
  6936. // add node to this (sub)graph and all its parent graphs
  6937. for (i = graphs.length - 1; i >= 0; i--) {
  6938. var g = graphs[i];
  6939. if (!g.nodes) {
  6940. g.nodes = [];
  6941. }
  6942. if (g.nodes.indexOf(current) == -1) {
  6943. g.nodes.push(current);
  6944. }
  6945. }
  6946. // merge attributes
  6947. if (node.attr) {
  6948. current.attr = merge(current.attr, node.attr);
  6949. }
  6950. }
  6951. /**
  6952. * Add an edge to a graph object
  6953. * @param {Object} graph
  6954. * @param {Object} edge
  6955. */
  6956. function addEdge(graph, edge) {
  6957. if (!graph.edges) {
  6958. graph.edges = [];
  6959. }
  6960. graph.edges.push(edge);
  6961. if (graph.edge) {
  6962. var attr = merge({}, graph.edge); // clone default attributes
  6963. edge.attr = merge(attr, edge.attr); // merge attributes
  6964. }
  6965. }
  6966. /**
  6967. * Create an edge to a graph object
  6968. * @param {Object} graph
  6969. * @param {String | Number | Object} from
  6970. * @param {String | Number | Object} to
  6971. * @param {String} type
  6972. * @param {Object | null} attr
  6973. * @return {Object} edge
  6974. */
  6975. function createEdge(graph, from, to, type, attr) {
  6976. var edge = {
  6977. from: from,
  6978. to: to,
  6979. type: type
  6980. };
  6981. if (graph.edge) {
  6982. edge.attr = merge({}, graph.edge); // clone default attributes
  6983. }
  6984. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  6985. return edge;
  6986. }
  6987. /**
  6988. * Get next token in the current dot file.
  6989. * The token and token type are available as token and tokenType
  6990. */
  6991. function getToken() {
  6992. tokenType = TOKENTYPE.NULL;
  6993. token = '';
  6994. // skip over whitespaces
  6995. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  6996. next();
  6997. }
  6998. do {
  6999. var isComment = false;
  7000. // skip comment
  7001. if (c == '#') {
  7002. // find the previous non-space character
  7003. var i = index - 1;
  7004. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7005. i--;
  7006. }
  7007. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7008. // the # is at the start of a line, this is indeed a line comment
  7009. while (c != '' && c != '\n') {
  7010. next();
  7011. }
  7012. isComment = true;
  7013. }
  7014. }
  7015. if (c == '/' && nextPreview() == '/') {
  7016. // skip line comment
  7017. while (c != '' && c != '\n') {
  7018. next();
  7019. }
  7020. isComment = true;
  7021. }
  7022. if (c == '/' && nextPreview() == '*') {
  7023. // skip block comment
  7024. while (c != '') {
  7025. if (c == '*' && nextPreview() == '/') {
  7026. // end of block comment found. skip these last two characters
  7027. next();
  7028. next();
  7029. break;
  7030. }
  7031. else {
  7032. next();
  7033. }
  7034. }
  7035. isComment = true;
  7036. }
  7037. // skip over whitespaces
  7038. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7039. next();
  7040. }
  7041. }
  7042. while (isComment);
  7043. // check for end of dot file
  7044. if (c == '') {
  7045. // token is still empty
  7046. tokenType = TOKENTYPE.DELIMITER;
  7047. return;
  7048. }
  7049. // check for delimiters consisting of 2 characters
  7050. var c2 = c + nextPreview();
  7051. if (DELIMITERS[c2]) {
  7052. tokenType = TOKENTYPE.DELIMITER;
  7053. token = c2;
  7054. next();
  7055. next();
  7056. return;
  7057. }
  7058. // check for delimiters consisting of 1 character
  7059. if (DELIMITERS[c]) {
  7060. tokenType = TOKENTYPE.DELIMITER;
  7061. token = c;
  7062. next();
  7063. return;
  7064. }
  7065. // check for an identifier (number or string)
  7066. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7067. if (isAlphaNumeric(c) || c == '-') {
  7068. token += c;
  7069. next();
  7070. while (isAlphaNumeric(c)) {
  7071. token += c;
  7072. next();
  7073. }
  7074. if (token == 'false') {
  7075. token = false; // convert to boolean
  7076. }
  7077. else if (token == 'true') {
  7078. token = true; // convert to boolean
  7079. }
  7080. else if (!isNaN(Number(token))) {
  7081. token = Number(token); // convert to number
  7082. }
  7083. tokenType = TOKENTYPE.IDENTIFIER;
  7084. return;
  7085. }
  7086. // check for a string enclosed by double quotes
  7087. if (c == '"') {
  7088. next();
  7089. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7090. token += c;
  7091. if (c == '"') { // skip the escape character
  7092. next();
  7093. }
  7094. next();
  7095. }
  7096. if (c != '"') {
  7097. throw newSyntaxError('End of string " expected');
  7098. }
  7099. next();
  7100. tokenType = TOKENTYPE.IDENTIFIER;
  7101. return;
  7102. }
  7103. // something unknown is found, wrong characters, a syntax error
  7104. tokenType = TOKENTYPE.UNKNOWN;
  7105. while (c != '') {
  7106. token += c;
  7107. next();
  7108. }
  7109. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7110. }
  7111. /**
  7112. * Parse a graph.
  7113. * @returns {Object} graph
  7114. */
  7115. function parseGraph() {
  7116. var graph = {};
  7117. first();
  7118. getToken();
  7119. // optional strict keyword
  7120. if (token == 'strict') {
  7121. graph.strict = true;
  7122. getToken();
  7123. }
  7124. // graph or digraph keyword
  7125. if (token == 'graph' || token == 'digraph') {
  7126. graph.type = token;
  7127. getToken();
  7128. }
  7129. // optional graph id
  7130. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7131. graph.id = token;
  7132. getToken();
  7133. }
  7134. // open angle bracket
  7135. if (token != '{') {
  7136. throw newSyntaxError('Angle bracket { expected');
  7137. }
  7138. getToken();
  7139. // statements
  7140. parseStatements(graph);
  7141. // close angle bracket
  7142. if (token != '}') {
  7143. throw newSyntaxError('Angle bracket } expected');
  7144. }
  7145. getToken();
  7146. // end of file
  7147. if (token !== '') {
  7148. throw newSyntaxError('End of file expected');
  7149. }
  7150. getToken();
  7151. // remove temporary default properties
  7152. delete graph.node;
  7153. delete graph.edge;
  7154. delete graph.graph;
  7155. return graph;
  7156. }
  7157. /**
  7158. * Parse a list with statements.
  7159. * @param {Object} graph
  7160. */
  7161. function parseStatements (graph) {
  7162. while (token !== '' && token != '}') {
  7163. parseStatement(graph);
  7164. if (token == ';') {
  7165. getToken();
  7166. }
  7167. }
  7168. }
  7169. /**
  7170. * Parse a single statement. Can be a an attribute statement, node
  7171. * statement, a series of node statements and edge statements, or a
  7172. * parameter.
  7173. * @param {Object} graph
  7174. */
  7175. function parseStatement(graph) {
  7176. // parse subgraph
  7177. var subgraph = parseSubgraph(graph);
  7178. if (subgraph) {
  7179. // edge statements
  7180. parseEdge(graph, subgraph);
  7181. return;
  7182. }
  7183. // parse an attribute statement
  7184. var attr = parseAttributeStatement(graph);
  7185. if (attr) {
  7186. return;
  7187. }
  7188. // parse node
  7189. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7190. throw newSyntaxError('Identifier expected');
  7191. }
  7192. var id = token; // id can be a string or a number
  7193. getToken();
  7194. if (token == '=') {
  7195. // id statement
  7196. getToken();
  7197. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7198. throw newSyntaxError('Identifier expected');
  7199. }
  7200. graph[id] = token;
  7201. getToken();
  7202. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7203. }
  7204. else {
  7205. parseNodeStatement(graph, id);
  7206. }
  7207. }
  7208. /**
  7209. * Parse a subgraph
  7210. * @param {Object} graph parent graph object
  7211. * @return {Object | null} subgraph
  7212. */
  7213. function parseSubgraph (graph) {
  7214. var subgraph = null;
  7215. // optional subgraph keyword
  7216. if (token == 'subgraph') {
  7217. subgraph = {};
  7218. subgraph.type = 'subgraph';
  7219. getToken();
  7220. // optional graph id
  7221. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7222. subgraph.id = token;
  7223. getToken();
  7224. }
  7225. }
  7226. // open angle bracket
  7227. if (token == '{') {
  7228. getToken();
  7229. if (!subgraph) {
  7230. subgraph = {};
  7231. }
  7232. subgraph.parent = graph;
  7233. subgraph.node = graph.node;
  7234. subgraph.edge = graph.edge;
  7235. subgraph.graph = graph.graph;
  7236. // statements
  7237. parseStatements(subgraph);
  7238. // close angle bracket
  7239. if (token != '}') {
  7240. throw newSyntaxError('Angle bracket } expected');
  7241. }
  7242. getToken();
  7243. // remove temporary default properties
  7244. delete subgraph.node;
  7245. delete subgraph.edge;
  7246. delete subgraph.graph;
  7247. delete subgraph.parent;
  7248. // register at the parent graph
  7249. if (!graph.subgraphs) {
  7250. graph.subgraphs = [];
  7251. }
  7252. graph.subgraphs.push(subgraph);
  7253. }
  7254. return subgraph;
  7255. }
  7256. /**
  7257. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7258. * Available keywords are 'node', 'edge', 'graph'.
  7259. * The previous list with default attributes will be replaced
  7260. * @param {Object} graph
  7261. * @returns {String | null} keyword Returns the name of the parsed attribute
  7262. * (node, edge, graph), or null if nothing
  7263. * is parsed.
  7264. */
  7265. function parseAttributeStatement (graph) {
  7266. // attribute statements
  7267. if (token == 'node') {
  7268. getToken();
  7269. // node attributes
  7270. graph.node = parseAttributeList();
  7271. return 'node';
  7272. }
  7273. else if (token == 'edge') {
  7274. getToken();
  7275. // edge attributes
  7276. graph.edge = parseAttributeList();
  7277. return 'edge';
  7278. }
  7279. else if (token == 'graph') {
  7280. getToken();
  7281. // graph attributes
  7282. graph.graph = parseAttributeList();
  7283. return 'graph';
  7284. }
  7285. return null;
  7286. }
  7287. /**
  7288. * parse a node statement
  7289. * @param {Object} graph
  7290. * @param {String | Number} id
  7291. */
  7292. function parseNodeStatement(graph, id) {
  7293. // node statement
  7294. var node = {
  7295. id: id
  7296. };
  7297. var attr = parseAttributeList();
  7298. if (attr) {
  7299. node.attr = attr;
  7300. }
  7301. addNode(graph, node);
  7302. // edge statements
  7303. parseEdge(graph, id);
  7304. }
  7305. /**
  7306. * Parse an edge or a series of edges
  7307. * @param {Object} graph
  7308. * @param {String | Number} from Id of the from node
  7309. */
  7310. function parseEdge(graph, from) {
  7311. while (token == '->' || token == '--') {
  7312. var to;
  7313. var type = token;
  7314. getToken();
  7315. var subgraph = parseSubgraph(graph);
  7316. if (subgraph) {
  7317. to = subgraph;
  7318. }
  7319. else {
  7320. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7321. throw newSyntaxError('Identifier or subgraph expected');
  7322. }
  7323. to = token;
  7324. addNode(graph, {
  7325. id: to
  7326. });
  7327. getToken();
  7328. }
  7329. // parse edge attributes
  7330. var attr = parseAttributeList();
  7331. // create edge
  7332. var edge = createEdge(graph, from, to, type, attr);
  7333. addEdge(graph, edge);
  7334. from = to;
  7335. }
  7336. }
  7337. /**
  7338. * Parse a set with attributes,
  7339. * for example [label="1.000", shape=solid]
  7340. * @return {Object | null} attr
  7341. */
  7342. function parseAttributeList() {
  7343. var attr = null;
  7344. while (token == '[') {
  7345. getToken();
  7346. attr = {};
  7347. while (token !== '' && token != ']') {
  7348. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7349. throw newSyntaxError('Attribute name expected');
  7350. }
  7351. var name = token;
  7352. getToken();
  7353. if (token != '=') {
  7354. throw newSyntaxError('Equal sign = expected');
  7355. }
  7356. getToken();
  7357. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7358. throw newSyntaxError('Attribute value expected');
  7359. }
  7360. var value = token;
  7361. setValue(attr, name, value); // name can be a path
  7362. getToken();
  7363. if (token ==',') {
  7364. getToken();
  7365. }
  7366. }
  7367. if (token != ']') {
  7368. throw newSyntaxError('Bracket ] expected');
  7369. }
  7370. getToken();
  7371. }
  7372. return attr;
  7373. }
  7374. /**
  7375. * Create a syntax error with extra information on current token and index.
  7376. * @param {String} message
  7377. * @returns {SyntaxError} err
  7378. */
  7379. function newSyntaxError(message) {
  7380. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7381. }
  7382. /**
  7383. * Chop off text after a maximum length
  7384. * @param {String} text
  7385. * @param {Number} maxLength
  7386. * @returns {String}
  7387. */
  7388. function chop (text, maxLength) {
  7389. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7390. }
  7391. /**
  7392. * Execute a function fn for each pair of elements in two arrays
  7393. * @param {Array | *} array1
  7394. * @param {Array | *} array2
  7395. * @param {function} fn
  7396. */
  7397. function forEach2(array1, array2, fn) {
  7398. if (array1 instanceof Array) {
  7399. array1.forEach(function (elem1) {
  7400. if (array2 instanceof Array) {
  7401. array2.forEach(function (elem2) {
  7402. fn(elem1, elem2);
  7403. });
  7404. }
  7405. else {
  7406. fn(elem1, array2);
  7407. }
  7408. });
  7409. }
  7410. else {
  7411. if (array2 instanceof Array) {
  7412. array2.forEach(function (elem2) {
  7413. fn(array1, elem2);
  7414. });
  7415. }
  7416. else {
  7417. fn(array1, array2);
  7418. }
  7419. }
  7420. }
  7421. /**
  7422. * Convert a string containing a graph in DOT language into a map containing
  7423. * with nodes and edges in the format of graph.
  7424. * @param {String} data Text containing a graph in DOT-notation
  7425. * @return {Object} graphData
  7426. */
  7427. function DOTToGraph (data) {
  7428. // parse the DOT file
  7429. var dotData = parseDOT(data);
  7430. var graphData = {
  7431. nodes: [],
  7432. edges: [],
  7433. options: {}
  7434. };
  7435. // copy the nodes
  7436. if (dotData.nodes) {
  7437. dotData.nodes.forEach(function (dotNode) {
  7438. var graphNode = {
  7439. id: dotNode.id,
  7440. label: String(dotNode.label || dotNode.id)
  7441. };
  7442. merge(graphNode, dotNode.attr);
  7443. if (graphNode.image) {
  7444. graphNode.shape = 'image';
  7445. }
  7446. graphData.nodes.push(graphNode);
  7447. });
  7448. }
  7449. // copy the edges
  7450. if (dotData.edges) {
  7451. /**
  7452. * Convert an edge in DOT format to an edge with VisGraph format
  7453. * @param {Object} dotEdge
  7454. * @returns {Object} graphEdge
  7455. */
  7456. function convertEdge(dotEdge) {
  7457. var graphEdge = {
  7458. from: dotEdge.from,
  7459. to: dotEdge.to
  7460. };
  7461. merge(graphEdge, dotEdge.attr);
  7462. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  7463. return graphEdge;
  7464. }
  7465. dotData.edges.forEach(function (dotEdge) {
  7466. var from, to;
  7467. if (dotEdge.from instanceof Object) {
  7468. from = dotEdge.from.nodes;
  7469. }
  7470. else {
  7471. from = {
  7472. id: dotEdge.from
  7473. }
  7474. }
  7475. if (dotEdge.to instanceof Object) {
  7476. to = dotEdge.to.nodes;
  7477. }
  7478. else {
  7479. to = {
  7480. id: dotEdge.to
  7481. }
  7482. }
  7483. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  7484. dotEdge.from.edges.forEach(function (subEdge) {
  7485. var graphEdge = convertEdge(subEdge);
  7486. graphData.edges.push(graphEdge);
  7487. });
  7488. }
  7489. forEach2(from, to, function (from, to) {
  7490. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  7491. var graphEdge = convertEdge(subEdge);
  7492. graphData.edges.push(graphEdge);
  7493. });
  7494. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  7495. dotEdge.to.edges.forEach(function (subEdge) {
  7496. var graphEdge = convertEdge(subEdge);
  7497. graphData.edges.push(graphEdge);
  7498. });
  7499. }
  7500. });
  7501. }
  7502. // copy the options
  7503. if (dotData.attr) {
  7504. graphData.options = dotData.attr;
  7505. }
  7506. return graphData;
  7507. }
  7508. // exports
  7509. exports.parseDOT = parseDOT;
  7510. exports.DOTToGraph = DOTToGraph;
  7511. })(typeof util !== 'undefined' ? util : exports);
  7512. /**
  7513. * Canvas shapes used by the Graph
  7514. */
  7515. if (typeof CanvasRenderingContext2D !== 'undefined') {
  7516. /**
  7517. * Draw a circle shape
  7518. */
  7519. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  7520. this.beginPath();
  7521. this.arc(x, y, r, 0, 2*Math.PI, false);
  7522. };
  7523. /**
  7524. * Draw a square shape
  7525. * @param {Number} x horizontal center
  7526. * @param {Number} y vertical center
  7527. * @param {Number} r size, width and height of the square
  7528. */
  7529. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  7530. this.beginPath();
  7531. this.rect(x - r, y - r, r * 2, r * 2);
  7532. };
  7533. /**
  7534. * Draw a triangle shape
  7535. * @param {Number} x horizontal center
  7536. * @param {Number} y vertical center
  7537. * @param {Number} r radius, half the length of the sides of the triangle
  7538. */
  7539. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  7540. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7541. this.beginPath();
  7542. var s = r * 2;
  7543. var s2 = s / 2;
  7544. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7545. var h = Math.sqrt(s * s - s2 * s2); // height
  7546. this.moveTo(x, y - (h - ir));
  7547. this.lineTo(x + s2, y + ir);
  7548. this.lineTo(x - s2, y + ir);
  7549. this.lineTo(x, y - (h - ir));
  7550. this.closePath();
  7551. };
  7552. /**
  7553. * Draw a triangle shape in downward orientation
  7554. * @param {Number} x horizontal center
  7555. * @param {Number} y vertical center
  7556. * @param {Number} r radius
  7557. */
  7558. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  7559. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7560. this.beginPath();
  7561. var s = r * 2;
  7562. var s2 = s / 2;
  7563. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7564. var h = Math.sqrt(s * s - s2 * s2); // height
  7565. this.moveTo(x, y + (h - ir));
  7566. this.lineTo(x + s2, y - ir);
  7567. this.lineTo(x - s2, y - ir);
  7568. this.lineTo(x, y + (h - ir));
  7569. this.closePath();
  7570. };
  7571. /**
  7572. * Draw a star shape, a star with 5 points
  7573. * @param {Number} x horizontal center
  7574. * @param {Number} y vertical center
  7575. * @param {Number} r radius, half the length of the sides of the triangle
  7576. */
  7577. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  7578. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  7579. this.beginPath();
  7580. for (var n = 0; n < 10; n++) {
  7581. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  7582. this.lineTo(
  7583. x + radius * Math.sin(n * 2 * Math.PI / 10),
  7584. y - radius * Math.cos(n * 2 * Math.PI / 10)
  7585. );
  7586. }
  7587. this.closePath();
  7588. };
  7589. /**
  7590. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7591. */
  7592. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7593. var r2d = Math.PI/180;
  7594. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7595. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7596. this.beginPath();
  7597. this.moveTo(x+r,y);
  7598. this.lineTo(x+w-r,y);
  7599. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7600. this.lineTo(x+w,y+h-r);
  7601. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7602. this.lineTo(x+r,y+h);
  7603. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7604. this.lineTo(x,y+r);
  7605. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7606. };
  7607. /**
  7608. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7609. */
  7610. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7611. var kappa = .5522848,
  7612. ox = (w / 2) * kappa, // control point offset horizontal
  7613. oy = (h / 2) * kappa, // control point offset vertical
  7614. xe = x + w, // x-end
  7615. ye = y + h, // y-end
  7616. xm = x + w / 2, // x-middle
  7617. ym = y + h / 2; // y-middle
  7618. this.beginPath();
  7619. this.moveTo(x, ym);
  7620. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7621. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7622. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7623. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7624. };
  7625. /**
  7626. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7627. */
  7628. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7629. var f = 1/3;
  7630. var wEllipse = w;
  7631. var hEllipse = h * f;
  7632. var kappa = .5522848,
  7633. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7634. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7635. xe = x + wEllipse, // x-end
  7636. ye = y + hEllipse, // y-end
  7637. xm = x + wEllipse / 2, // x-middle
  7638. ym = y + hEllipse / 2, // y-middle
  7639. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7640. yeb = y + h; // y-end, bottom ellipse
  7641. this.beginPath();
  7642. this.moveTo(xe, ym);
  7643. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7644. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7645. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7646. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7647. this.lineTo(xe, ymb);
  7648. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7649. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7650. this.lineTo(x, ym);
  7651. };
  7652. /**
  7653. * Draw an arrow point (no line)
  7654. */
  7655. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  7656. // tail
  7657. var xt = x - length * Math.cos(angle);
  7658. var yt = y - length * Math.sin(angle);
  7659. // inner tail
  7660. // TODO: allow to customize different shapes
  7661. var xi = x - length * 0.9 * Math.cos(angle);
  7662. var yi = y - length * 0.9 * Math.sin(angle);
  7663. // left
  7664. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  7665. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  7666. // right
  7667. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  7668. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  7669. this.beginPath();
  7670. this.moveTo(x, y);
  7671. this.lineTo(xl, yl);
  7672. this.lineTo(xi, yi);
  7673. this.lineTo(xr, yr);
  7674. this.closePath();
  7675. };
  7676. /**
  7677. * Sets up the dashedLine functionality for drawing
  7678. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  7679. * @author David Jordan
  7680. * @date 2012-08-08
  7681. */
  7682. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  7683. if (!dashArray) dashArray=[10,5];
  7684. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  7685. var dashCount = dashArray.length;
  7686. this.moveTo(x, y);
  7687. var dx = (x2-x), dy = (y2-y);
  7688. var slope = dy/dx;
  7689. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  7690. var dashIndex=0, draw=true;
  7691. while (distRemaining>=0.1){
  7692. var dashLength = dashArray[dashIndex++%dashCount];
  7693. if (dashLength > distRemaining) dashLength = distRemaining;
  7694. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  7695. if (dx<0) xStep = -xStep;
  7696. x += xStep;
  7697. y += slope*xStep;
  7698. this[draw ? 'lineTo' : 'moveTo'](x,y);
  7699. distRemaining -= dashLength;
  7700. draw = !draw;
  7701. }
  7702. };
  7703. // TODO: add diamond shape
  7704. }
  7705. /**
  7706. * @class Node
  7707. * A node. A node can be connected to other nodes via one or multiple edges.
  7708. * @param {object} properties An object containing properties for the node. All
  7709. * properties are optional, except for the id.
  7710. * {number} id Id of the node. Required
  7711. * {string} label Text label for the node
  7712. * {number} x Horizontal position of the node
  7713. * {number} y Vertical position of the node
  7714. * {string} shape Node shape, available:
  7715. * "database", "circle", "ellipse",
  7716. * "box", "image", "text", "dot",
  7717. * "star", "triangle", "triangleDown",
  7718. * "square"
  7719. * {string} image An image url
  7720. * {string} title An title text, can be HTML
  7721. * {anytype} group A group name or number
  7722. * @param {Graph.Images} imagelist A list with images. Only needed
  7723. * when the node has an image
  7724. * @param {Graph.Groups} grouplist A list with groups. Needed for
  7725. * retrieving group properties
  7726. * @param {Object} constants An object with default values for
  7727. * example for the color
  7728. */
  7729. function Node(properties, imagelist, grouplist, constants) {
  7730. this.selected = false;
  7731. this.edges = []; // all edges connected to this node
  7732. this.dynamicEdges = [];
  7733. this.reroutedEdges = {};
  7734. this.group = constants.nodes.group;
  7735. this.fontSize = constants.nodes.fontSize;
  7736. this.fontFace = constants.nodes.fontFace;
  7737. this.fontColor = constants.nodes.fontColor;
  7738. this.color = constants.nodes.color;
  7739. // set defaults for the properties
  7740. this.id = undefined;
  7741. this.shape = constants.nodes.shape;
  7742. this.image = constants.nodes.image;
  7743. this.x = 0;
  7744. this.y = 0;
  7745. this.xFixed = false;
  7746. this.yFixed = false;
  7747. this.horizontalAlignLeft = true; // these are for the UI
  7748. this.verticalAlignTop = true; // these are for the UI
  7749. this.radius = constants.nodes.radius;
  7750. this.baseRadiusValue = constants.nodes.radius;
  7751. this.radiusFixed = false;
  7752. this.radiusMin = constants.nodes.radiusMin;
  7753. this.radiusMax = constants.nodes.radiusMax;
  7754. this.imagelist = imagelist;
  7755. this.grouplist = grouplist;
  7756. this.setProperties(properties, constants);
  7757. // creating the variables for clustering
  7758. this.resetCluster();
  7759. this.dynamicEdgesLength = 0;
  7760. this.clusterSession = 0;
  7761. this.clusterSizeWidthFactor = constants.clustering.clusterSizeWidthFactor;
  7762. this.clusterSizeHeightFactor = constants.clustering.clusterSizeHeightFactor;
  7763. this.clusterSizeRadiusFactor = constants.clustering.clusterSizeRadiusFactor;
  7764. // mass, force, velocity
  7765. this.mass = 50; // kg (mass is adjusted for the number of connected edges)
  7766. this.fx = 0.0; // external force x
  7767. this.fy = 0.0; // external force y
  7768. this.vx = 0.0; // velocity x
  7769. this.vy = 0.0; // velocity y
  7770. this.minForce = constants.minForce;
  7771. this.damping = 0.9; // damping factor
  7772. this.graphScaleInv = 1;
  7773. this.canvasTopLeft = {"x": -300, "y": -300};
  7774. this.canvasBottomRight = {"x": 300, "y": 300};
  7775. }
  7776. /**
  7777. * (re)setting the clustering variables and objects
  7778. */
  7779. Node.prototype.resetCluster = function() {
  7780. // clustering variables
  7781. this.formationScale = undefined; // this is used to determine when to open the cluster
  7782. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  7783. this.containedNodes = {};
  7784. this.containedEdges = {};
  7785. this.clusterSessions = [];
  7786. };
  7787. /**
  7788. * Attach a edge to the node
  7789. * @param {Edge} edge
  7790. */
  7791. Node.prototype.attachEdge = function(edge) {
  7792. if (this.edges.indexOf(edge) == -1) {
  7793. this.edges.push(edge);
  7794. }
  7795. if (this.dynamicEdges.indexOf(edge) == -1) {
  7796. this.dynamicEdges.push(edge);
  7797. }
  7798. this.dynamicEdgesLength = this.dynamicEdges.length;
  7799. this._updateMass();
  7800. };
  7801. /**
  7802. * Detach a edge from the node
  7803. * @param {Edge} edge
  7804. */
  7805. Node.prototype.detachEdge = function(edge) {
  7806. var index = this.edges.indexOf(edge);
  7807. if (index != -1) {
  7808. this.edges.splice(index, 1);
  7809. this.dynamicEdges.splice(index, 1);
  7810. }
  7811. this.dynamicEdgesLength = this.dynamicEdges.length;
  7812. this._updateMass();
  7813. };
  7814. /**
  7815. * Update the nodes mass, which is determined by the number of edges connecting
  7816. * to it (more edges -> heavier node).
  7817. * @private
  7818. */
  7819. Node.prototype._updateMass = function() {
  7820. this.mass = 50 + 20 * this.edges.length; // kg
  7821. };
  7822. /**
  7823. * Set or overwrite properties for the node
  7824. * @param {Object} properties an object with properties
  7825. * @param {Object} constants and object with default, global properties
  7826. */
  7827. Node.prototype.setProperties = function(properties, constants) {
  7828. if (!properties) {
  7829. return;
  7830. }
  7831. this.originalLabel = undefined;
  7832. // basic properties
  7833. if (properties.id !== undefined) {this.id = properties.id;}
  7834. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  7835. if (properties.title !== undefined) {this.title = properties.title;}
  7836. if (properties.group !== undefined) {this.group = properties.group;}
  7837. if (properties.x !== undefined) {this.x = properties.x;}
  7838. if (properties.y !== undefined) {this.y = properties.y;}
  7839. if (properties.value !== undefined) {this.value = properties.value;}
  7840. // UI properties
  7841. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  7842. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  7843. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  7844. if (this.id === undefined) {
  7845. throw "Node must have an id";
  7846. }
  7847. // copy group properties
  7848. if (this.group) {
  7849. var groupObj = this.grouplist.get(this.group);
  7850. for (var prop in groupObj) {
  7851. if (groupObj.hasOwnProperty(prop)) {
  7852. this[prop] = groupObj[prop];
  7853. }
  7854. }
  7855. }
  7856. // individual shape properties
  7857. if (properties.shape !== undefined) {this.shape = properties.shape;}
  7858. if (properties.image !== undefined) {this.image = properties.image;}
  7859. if (properties.radius !== undefined) {this.radius = properties.radius;}
  7860. if (properties.color !== undefined) {this.color = Node.parseColor(properties.color);}
  7861. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  7862. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  7863. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  7864. if (this.image !== undefined) {
  7865. if (this.imagelist) {
  7866. this.imageObj = this.imagelist.load(this.image);
  7867. }
  7868. else {
  7869. throw "No imagelist provided";
  7870. }
  7871. }
  7872. this.xFixed = this.xFixed || (properties.x !== undefined);
  7873. this.yFixed = this.yFixed || (properties.y !== undefined);
  7874. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  7875. if (this.shape == 'image') {
  7876. this.radiusMin = constants.nodes.widthMin;
  7877. this.radiusMax = constants.nodes.widthMax;
  7878. }
  7879. // choose draw method depending on the shape
  7880. switch (this.shape) {
  7881. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  7882. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  7883. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  7884. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7885. // TODO: add diamond shape
  7886. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  7887. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  7888. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  7889. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  7890. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  7891. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  7892. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  7893. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7894. }
  7895. // reset the size of the node, this can be changed
  7896. this._reset();
  7897. };
  7898. /**
  7899. * Parse a color property into an object with border, background, and
  7900. * hightlight colors
  7901. * @param {Object | String} color
  7902. * @return {Object} colorObject
  7903. */
  7904. Node.parseColor = function(color) {
  7905. var c;
  7906. if (util.isString(color)) {
  7907. c = {
  7908. border: color,
  7909. background: color,
  7910. highlight: {
  7911. border: color,
  7912. background: color
  7913. }
  7914. };
  7915. // TODO: automatically generate a nice highlight color
  7916. }
  7917. else {
  7918. c = {};
  7919. c.background = color.background || 'white';
  7920. c.border = color.border || c.background;
  7921. if (util.isString(color.highlight)) {
  7922. c.highlight = {
  7923. border: color.highlight,
  7924. background: color.highlight
  7925. }
  7926. }
  7927. else {
  7928. c.highlight = {};
  7929. c.highlight.background = color.highlight && color.highlight.background || c.background;
  7930. c.highlight.border = color.highlight && color.highlight.border || c.border;
  7931. }
  7932. }
  7933. return c;
  7934. };
  7935. /**
  7936. * select this node
  7937. */
  7938. Node.prototype.select = function() {
  7939. this.selected = true;
  7940. this._reset();
  7941. };
  7942. /**
  7943. * unselect this node
  7944. */
  7945. Node.prototype.unselect = function() {
  7946. this.selected = false;
  7947. this._reset();
  7948. };
  7949. /**
  7950. * Reset the calculated size of the node, forces it to recalculate its size
  7951. */
  7952. Node.prototype.clearSizeCache = function() {
  7953. this._reset();
  7954. };
  7955. /**
  7956. * Reset the calculated size of the node, forces it to recalculate its size
  7957. * @private
  7958. */
  7959. Node.prototype._reset = function() {
  7960. this.width = undefined;
  7961. this.height = undefined;
  7962. };
  7963. /**
  7964. * get the title of this node.
  7965. * @return {string} title The title of the node, or undefined when no title
  7966. * has been set.
  7967. */
  7968. Node.prototype.getTitle = function() {
  7969. return this.title;
  7970. };
  7971. /**
  7972. * Calculate the distance to the border of the Node
  7973. * @param {CanvasRenderingContext2D} ctx
  7974. * @param {Number} angle Angle in radians
  7975. * @returns {number} distance Distance to the border in pixels
  7976. */
  7977. Node.prototype.distanceToBorder = function (ctx, angle) {
  7978. var borderWidth = 1;
  7979. if (!this.width) {
  7980. this.resize(ctx);
  7981. }
  7982. //noinspection FallthroughInSwitchStatementJS
  7983. switch (this.shape) {
  7984. case 'circle':
  7985. case 'dot':
  7986. return this.radius + borderWidth;
  7987. case 'ellipse':
  7988. var a = this.width / 2;
  7989. var b = this.height / 2;
  7990. var w = (Math.sin(angle) * a);
  7991. var h = (Math.cos(angle) * b);
  7992. return a * b / Math.sqrt(w * w + h * h);
  7993. // TODO: implement distanceToBorder for database
  7994. // TODO: implement distanceToBorder for triangle
  7995. // TODO: implement distanceToBorder for triangleDown
  7996. case 'box':
  7997. case 'image':
  7998. case 'text':
  7999. default:
  8000. if (this.width) {
  8001. return Math.min(
  8002. Math.abs(this.width / 2 / Math.cos(angle)),
  8003. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8004. // TODO: reckon with border radius too in case of box
  8005. }
  8006. else {
  8007. return 0;
  8008. }
  8009. }
  8010. // TODO: implement calculation of distance to border for all shapes
  8011. };
  8012. /**
  8013. * Set forces acting on the node
  8014. * @param {number} fx Force in horizontal direction
  8015. * @param {number} fy Force in vertical direction
  8016. */
  8017. Node.prototype._setForce = function(fx, fy) {
  8018. this.fx = fx;
  8019. this.fy = fy;
  8020. };
  8021. /**
  8022. * Add forces acting on the node
  8023. * @param {number} fx Force in horizontal direction
  8024. * @param {number} fy Force in vertical direction
  8025. * @private
  8026. */
  8027. Node.prototype._addForce = function(fx, fy) {
  8028. this.fx += fx;
  8029. this.fy += fy;
  8030. };
  8031. /**
  8032. * Perform one discrete step for the node
  8033. * @param {number} interval Time interval in seconds
  8034. */
  8035. Node.prototype.discreteStep = function(interval) {
  8036. if (!this.xFixed) {
  8037. var dx = -this.damping * this.vx; // damping force
  8038. var ax = (this.fx + dx) / this.mass; // acceleration
  8039. this.vx += ax / interval; // velocity
  8040. this.x += this.vx / interval; // position
  8041. }
  8042. if (!this.yFixed) {
  8043. var dy = -this.damping * this.vy; // damping force
  8044. var ay = (this.fy + dy) / this.mass; // acceleration
  8045. this.vy += ay / interval; // velocity
  8046. this.y += this.vy / interval; // position
  8047. }
  8048. };
  8049. /**
  8050. * Check if this node has a fixed x and y position
  8051. * @return {boolean} true if fixed, false if not
  8052. */
  8053. Node.prototype.isFixed = function() {
  8054. return (this.xFixed && this.yFixed);
  8055. };
  8056. /**
  8057. * Check if this node is moving
  8058. * @param {number} vmin the minimum velocity considered as "moving"
  8059. * @return {boolean} true if moving, false if it has no velocity
  8060. */
  8061. // TODO: replace this method with calculating the kinetic energy
  8062. Node.prototype.isMoving = function(vmin) {
  8063. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin ||
  8064. (!this.xFixed && Math.abs(this.fx) > this.minForce) ||
  8065. (!this.yFixed && Math.abs(this.fy) > this.minForce));
  8066. };
  8067. /**
  8068. * check if this node is selecte
  8069. * @return {boolean} selected True if node is selected, else false
  8070. */
  8071. Node.prototype.isSelected = function() {
  8072. return this.selected;
  8073. };
  8074. /**
  8075. * Retrieve the value of the node. Can be undefined
  8076. * @return {Number} value
  8077. */
  8078. Node.prototype.getValue = function() {
  8079. return this.value;
  8080. };
  8081. /**
  8082. * Calculate the distance from the nodes location to the given location (x,y)
  8083. * @param {Number} x
  8084. * @param {Number} y
  8085. * @return {Number} value
  8086. */
  8087. Node.prototype.getDistance = function(x, y) {
  8088. var dx = this.x - x,
  8089. dy = this.y - y;
  8090. return Math.sqrt(dx * dx + dy * dy);
  8091. };
  8092. /**
  8093. * Adjust the value range of the node. The node will adjust it's radius
  8094. * based on its value.
  8095. * @param {Number} min
  8096. * @param {Number} max
  8097. */
  8098. Node.prototype.setValueRange = function(min, max) {
  8099. if (!this.radiusFixed && this.value !== undefined) {
  8100. if (max == min) {
  8101. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8102. }
  8103. else {
  8104. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8105. this.radius = (this.value - min) * scale + this.radiusMin;
  8106. }
  8107. }
  8108. this.baseRadiusValue = this.radius;
  8109. };
  8110. /**
  8111. * Draw this node in the given canvas
  8112. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8113. * @param {CanvasRenderingContext2D} ctx
  8114. */
  8115. Node.prototype.draw = function(ctx) {
  8116. throw "Draw method not initialized for node";
  8117. };
  8118. /**
  8119. * Recalculate the size of this node in the given canvas
  8120. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8121. * @param {CanvasRenderingContext2D} ctx
  8122. */
  8123. Node.prototype.resize = function(ctx) {
  8124. throw "Resize method not initialized for node";
  8125. };
  8126. /**
  8127. * Check if this object is overlapping with the provided object
  8128. * @param {Object} obj an object with parameters left, top, right, bottom
  8129. * @return {boolean} True if location is located on node
  8130. */
  8131. Node.prototype.isOverlappingWith = function(obj) {
  8132. return (this.left < obj.right &&
  8133. this.left + this.width > obj.left &&
  8134. this.top < obj.bottom &&
  8135. this.top + this.height > obj.top);
  8136. };
  8137. Node.prototype._resizeImage = function (ctx) {
  8138. // TODO: pre calculate the image size
  8139. if (!this.width || !this.height) { // undefined or 0
  8140. var width, height;
  8141. if (this.value) {
  8142. this.radius = this.baseRadiusValue;
  8143. var scale = this.imageObj.height / this.imageObj.width;
  8144. if (scale !== undefined) {
  8145. width = this.radius || this.imageObj.width;
  8146. height = this.radius * scale || this.imageObj.height;
  8147. }
  8148. else {
  8149. width = 0;
  8150. height = 0;
  8151. }
  8152. }
  8153. else {
  8154. width = this.imageObj.width;
  8155. height = this.imageObj.height;
  8156. }
  8157. this.width = width;
  8158. this.height = height;
  8159. if (this.width && this.height) {
  8160. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8161. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8162. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8163. }
  8164. }
  8165. };
  8166. Node.prototype._drawImage = function (ctx) {
  8167. this._resizeImage(ctx);
  8168. this.left = this.x - this.width / 2;
  8169. this.top = this.y - this.height / 2;
  8170. var yLabel;
  8171. if (this.imageObj.width != 0 ) {
  8172. // draw the shade
  8173. if (this.clusterSize > 1) {
  8174. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8175. lineWidth *= this.graphScaleInv;
  8176. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8177. ctx.globalAlpha = 0.5;
  8178. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8179. }
  8180. // draw the image
  8181. ctx.globalAlpha = 1.0;
  8182. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8183. yLabel = this.y + this.height / 2;
  8184. }
  8185. else {
  8186. // image still loading... just draw the label for now
  8187. yLabel = this.y;
  8188. }
  8189. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8190. };
  8191. Node.prototype._resizeBox = function (ctx) {
  8192. if (!this.width) {
  8193. var margin = 5;
  8194. var textSize = this.getTextSize(ctx);
  8195. this.width = textSize.width + 2 * margin;
  8196. this.height = textSize.height + 2 * margin;
  8197. this.width += (this.clusterSize - 1) * 0.5 * this.clusterSizeWidthFactor;
  8198. this.height += (this.clusterSize - 1) * 0.5 * this.clusterSizeHeightFactor;
  8199. // this.radius += (this.clusterSize - 1) * 0.5 * this.clusterSizeRadiusFactor;
  8200. }
  8201. };
  8202. Node.prototype._drawBox = function (ctx) {
  8203. this._resizeBox(ctx);
  8204. this.left = this.x - this.width / 2;
  8205. this.top = this.y - this.height / 2;
  8206. var clusterLineWidth = 2.5;
  8207. var selectionLineWidth = 2;
  8208. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8209. // draw the outer border
  8210. if (this.clusterSize > 1) {
  8211. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8212. ctx.lineWidth *= this.graphScaleInv;
  8213. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8214. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8215. ctx.stroke();
  8216. }
  8217. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8218. ctx.lineWidth *= this.graphScaleInv;
  8219. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8220. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8221. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8222. ctx.fill();
  8223. ctx.stroke();
  8224. this._label(ctx, this.label, this.x, this.y);
  8225. };
  8226. Node.prototype._resizeDatabase = function (ctx) {
  8227. if (!this.width) {
  8228. var margin = 5;
  8229. var textSize = this.getTextSize(ctx);
  8230. var size = textSize.width + 2 * margin;
  8231. this.width = size;
  8232. this.height = size;
  8233. // scaling used for clustering
  8234. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8235. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8236. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8237. }
  8238. };
  8239. Node.prototype._drawDatabase = function (ctx) {
  8240. this._resizeDatabase(ctx);
  8241. this.left = this.x - this.width / 2;
  8242. this.top = this.y - this.height / 2;
  8243. var clusterLineWidth = 2.5;
  8244. var selectionLineWidth = 2;
  8245. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8246. // draw the outer border
  8247. if (this.clusterSize > 1) {
  8248. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8249. ctx.lineWidth *= this.graphScaleInv;
  8250. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8251. 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);
  8252. ctx.stroke();
  8253. }
  8254. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8255. ctx.lineWidth *= this.graphScaleInv;
  8256. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8257. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8258. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8259. ctx.fill();
  8260. ctx.stroke();
  8261. this._label(ctx, this.label, this.x, this.y);
  8262. };
  8263. Node.prototype._resizeCircle = function (ctx) {
  8264. if (!this.width) {
  8265. var margin = 5;
  8266. var textSize = this.getTextSize(ctx);
  8267. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8268. this.radius = diameter / 2;
  8269. this.width = diameter;
  8270. this.height = diameter;
  8271. // scaling used for clustering
  8272. // this.width += (this.clusterSize - 1) * 0.5 * this.clusterSizeWidthFactor;
  8273. // this.height += (this.clusterSize - 1) * 0.5 * this.clusterSizeHeightFactor;
  8274. this.radius += (this.clusterSize - 1) * 0.5 * this.clusterSizeRadiusFactor;
  8275. }
  8276. };
  8277. Node.prototype._drawCircle = function (ctx) {
  8278. this._resizeCircle(ctx);
  8279. this.left = this.x - this.width / 2;
  8280. this.top = this.y - this.height / 2;
  8281. var clusterLineWidth = 2.5;
  8282. var selectionLineWidth = 2;
  8283. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8284. // draw the outer border
  8285. if (this.clusterSize > 1) {
  8286. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8287. ctx.lineWidth *= this.graphScaleInv;
  8288. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8289. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8290. ctx.stroke();
  8291. }
  8292. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8293. ctx.lineWidth *= this.graphScaleInv;
  8294. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8295. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8296. ctx.circle(this.x, this.y, this.radius);
  8297. ctx.fill();
  8298. ctx.stroke();
  8299. this._label(ctx, this.label, this.x, this.y);
  8300. };
  8301. Node.prototype._resizeEllipse = function (ctx) {
  8302. if (!this.width) {
  8303. var textSize = this.getTextSize(ctx);
  8304. this.width = textSize.width * 1.5;
  8305. this.height = textSize.height * 2;
  8306. if (this.width < this.height) {
  8307. this.width = this.height;
  8308. }
  8309. // scaling used for clustering
  8310. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8311. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8312. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8313. }
  8314. };
  8315. Node.prototype._drawEllipse = function (ctx) {
  8316. this._resizeEllipse(ctx);
  8317. this.left = this.x - this.width / 2;
  8318. this.top = this.y - this.height / 2;
  8319. var clusterLineWidth = 2.5;
  8320. var selectionLineWidth = 2;
  8321. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8322. // draw the outer border
  8323. if (this.clusterSize > 1) {
  8324. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8325. ctx.lineWidth *= this.graphScaleInv;
  8326. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8327. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8328. ctx.stroke();
  8329. }
  8330. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8331. ctx.lineWidth *= this.graphScaleInv;
  8332. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8333. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8334. ctx.ellipse(this.left, this.top, this.width, this.height);
  8335. ctx.fill();
  8336. ctx.stroke();
  8337. this._label(ctx, this.label, this.x, this.y);
  8338. };
  8339. Node.prototype._drawDot = function (ctx) {
  8340. this._drawShape(ctx, 'circle');
  8341. };
  8342. Node.prototype._drawTriangle = function (ctx) {
  8343. this._drawShape(ctx, 'triangle');
  8344. };
  8345. Node.prototype._drawTriangleDown = function (ctx) {
  8346. this._drawShape(ctx, 'triangleDown');
  8347. };
  8348. Node.prototype._drawSquare = function (ctx) {
  8349. this._drawShape(ctx, 'square');
  8350. };
  8351. Node.prototype._drawStar = function (ctx) {
  8352. this._drawShape(ctx, 'star');
  8353. };
  8354. Node.prototype._resizeShape = function (ctx) {
  8355. if (!this.width) {
  8356. this.radius = this.baseRadiusValue;
  8357. var size = 2 * this.radius;
  8358. this.width = size;
  8359. this.height = size;
  8360. // scaling used for clustering
  8361. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8362. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8363. this.radius += (this.clusterSize - 1) * 0.5 * this.clusterSizeRadiusFactor;
  8364. }
  8365. };
  8366. Node.prototype._drawShape = function (ctx, shape) {
  8367. this._resizeShape(ctx);
  8368. this.left = this.x - this.width / 2;
  8369. this.top = this.y - this.height / 2;
  8370. var clusterLineWidth = 2.5;
  8371. var selectionLineWidth = 2;
  8372. var radiusMultiplier = 2;
  8373. // choose draw method depending on the shape
  8374. switch (shape) {
  8375. case 'dot': radiusMultiplier = 2; break;
  8376. case 'square': radiusMultiplier = 2; break;
  8377. case 'triangle': radiusMultiplier = 3; break;
  8378. case 'triangleDown': radiusMultiplier = 3; break;
  8379. case 'star': radiusMultiplier = 4; break;
  8380. }
  8381. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8382. // draw the outer border
  8383. if (this.clusterSize > 1) {
  8384. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8385. ctx.lineWidth *= this.graphScaleInv;
  8386. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8387. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8388. ctx.stroke();
  8389. }
  8390. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8391. ctx.lineWidth *= this.graphScaleInv;
  8392. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8393. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8394. ctx[shape](this.x, this.y, this.radius);
  8395. ctx.fill();
  8396. ctx.stroke();
  8397. if (this.label) {
  8398. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8399. }
  8400. };
  8401. Node.prototype._resizeText = function (ctx) {
  8402. if (!this.width) {
  8403. var margin = 5;
  8404. var textSize = this.getTextSize(ctx);
  8405. this.width = textSize.width + 2 * margin;
  8406. this.height = textSize.height + 2 * margin;
  8407. // scaling used for clustering
  8408. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8409. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8410. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8411. }
  8412. };
  8413. Node.prototype._drawText = function (ctx) {
  8414. this._resizeText(ctx);
  8415. this.left = this.x - this.width / 2;
  8416. this.top = this.y - this.height / 2;
  8417. this._label(ctx, this.label, this.x, this.y);
  8418. };
  8419. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  8420. if (text) {
  8421. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8422. ctx.fillStyle = this.fontColor || "black";
  8423. ctx.textAlign = align || "center";
  8424. ctx.textBaseline = baseline || "middle";
  8425. var lines = text.split('\n'),
  8426. lineCount = lines.length,
  8427. fontSize = (this.fontSize + 4),
  8428. yLine = y + (1 - lineCount) / 2 * fontSize;
  8429. for (var i = 0; i < lineCount; i++) {
  8430. ctx.fillText(lines[i], x, yLine);
  8431. yLine += fontSize;
  8432. }
  8433. }
  8434. };
  8435. Node.prototype.getTextSize = function(ctx) {
  8436. if (this.label !== undefined) {
  8437. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8438. var lines = this.label.split('\n'),
  8439. height = (this.fontSize + 4) * lines.length,
  8440. width = 0;
  8441. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  8442. width = Math.max(width, ctx.measureText(lines[i]).width);
  8443. }
  8444. return {"width": width, "height": height};
  8445. }
  8446. else {
  8447. return {"width": 0, "height": 0};
  8448. }
  8449. };
  8450. /**
  8451. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  8452. * there is a safety margin of 0.3 * width;
  8453. *
  8454. * @returns {boolean}
  8455. */
  8456. Node.prototype.inArea = function() {
  8457. if (this.width !== undefined) {
  8458. return (this.x + this.width*0.8 >= this.canvasTopLeft.x &&
  8459. this.x - this.width*0.8 < this.canvasBottomRight.x &&
  8460. this.y + this.height*0.8 >= this.canvasTopLeft.y &&
  8461. this.y - this.height*0.8 < this.canvasBottomRight.y);
  8462. }
  8463. else {
  8464. return true;
  8465. }
  8466. }
  8467. /**
  8468. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  8469. * @returns {boolean}
  8470. */
  8471. Node.prototype.inView = function() {
  8472. return (this.x >= this.canvasTopLeft.x &&
  8473. this.x < this.canvasBottomRight.x &&
  8474. this.y >= this.canvasTopLeft.y &&
  8475. this.y < this.canvasBottomRight.y);
  8476. }
  8477. /**
  8478. * This allows the zoom level of the graph to influence the rendering
  8479. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  8480. *
  8481. * @param scale
  8482. * @param canvasTopLeft
  8483. * @param canvasBottomRight
  8484. */
  8485. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  8486. this.graphScaleInv = 1.0/scale;
  8487. this.canvasTopLeft = canvasTopLeft;
  8488. this.canvasBottomRight = canvasBottomRight;
  8489. };
  8490. /**
  8491. * This allows the zoom level of the graph to influence the rendering
  8492. *
  8493. * @param scale
  8494. */
  8495. Node.prototype.setScale = function(scale) {
  8496. this.graphScaleInv = 1.0/scale;
  8497. };
  8498. /**
  8499. * This function updates the damping parameter for clusters, based ont he
  8500. *
  8501. * @param {Number} numberOfNodes
  8502. */
  8503. Node.prototype.updateDamping = function(numberOfNodes) {
  8504. this.damping = 0.8 + 0.1*this.clusterSize * (1 + 2/Math.pow(numberOfNodes,2));
  8505. };
  8506. /**
  8507. * set the velocity at 0. Is called when this node is contained in another during clustering
  8508. */
  8509. Node.prototype.clearVelocity = function() {
  8510. this.vx = 0;
  8511. this.vy = 0;
  8512. };
  8513. /**
  8514. * Basic preservation of (kinectic) energy
  8515. *
  8516. * @param massBeforeClustering
  8517. */
  8518. Node.prototype.updateVelocity = function(massBeforeClustering) {
  8519. var energyBefore = this.vx * this.vx * massBeforeClustering;
  8520. this.vx = Math.sqrt(energyBefore/this.mass);
  8521. energyBefore = this.vy * this.vy * massBeforeClustering;
  8522. this.vy = Math.sqrt(energyBefore/this.mass);
  8523. };
  8524. /**
  8525. * @class Edge
  8526. *
  8527. * A edge connects two nodes
  8528. * @param {Object} properties Object with properties. Must contain
  8529. * At least properties from and to.
  8530. * Available properties: from (number),
  8531. * to (number), label (string, color (string),
  8532. * width (number), style (string),
  8533. * length (number), title (string)
  8534. * @param {Graph} graph A graph object, used to find and edge to
  8535. * nodes.
  8536. * @param {Object} constants An object with default values for
  8537. * example for the color
  8538. */
  8539. function Edge (properties, graph, constants) {
  8540. if (!graph) {
  8541. throw "No graph provided";
  8542. }
  8543. this.graph = graph;
  8544. // initialize constants
  8545. this.widthMin = constants.edges.widthMin;
  8546. this.widthMax = constants.edges.widthMax;
  8547. // initialize variables
  8548. this.id = undefined;
  8549. this.fromId = undefined;
  8550. this.toId = undefined;
  8551. this.style = constants.edges.style;
  8552. this.title = undefined;
  8553. this.width = constants.edges.width;
  8554. this.value = undefined;
  8555. this.length = constants.edges.length;
  8556. this.from = null; // a node
  8557. this.to = null; // a node
  8558. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  8559. // by storing the original information we can revert to the original connection when the cluser is opened.
  8560. this.originalFromId = [];
  8561. this.originalToId = [];
  8562. this.connected = false;
  8563. // Added to support dashed lines
  8564. // David Jordan
  8565. // 2012-08-08
  8566. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  8567. this.stiffness = undefined; // depends on the length of the edge
  8568. this.color = constants.edges.color;
  8569. this.widthFixed = false;
  8570. this.lengthFixed = false;
  8571. this.setProperties(properties, constants);
  8572. }
  8573. /**
  8574. * Set or overwrite properties for the edge
  8575. * @param {Object} properties an object with properties
  8576. * @param {Object} constants and object with default, global properties
  8577. */
  8578. Edge.prototype.setProperties = function(properties, constants) {
  8579. if (!properties) {
  8580. return;
  8581. }
  8582. if (properties.from !== undefined) {this.fromId = properties.from;}
  8583. if (properties.to !== undefined) {this.toId = properties.to;}
  8584. if (properties.id !== undefined) {this.id = properties.id;}
  8585. if (properties.style !== undefined) {this.style = properties.style;}
  8586. if (properties.label !== undefined) {this.label = properties.label;}
  8587. if (this.label) {
  8588. this.fontSize = constants.edges.fontSize;
  8589. this.fontFace = constants.edges.fontFace;
  8590. this.fontColor = constants.edges.fontColor;
  8591. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8592. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8593. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8594. }
  8595. if (properties.title !== undefined) {this.title = properties.title;}
  8596. if (properties.width !== undefined) {this.width = properties.width;}
  8597. if (properties.value !== undefined) {this.value = properties.value;}
  8598. if (properties.length !== undefined) {this.length = properties.length;}
  8599. // Added to support dashed lines
  8600. // David Jordan
  8601. // 2012-08-08
  8602. if (properties.dash) {
  8603. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  8604. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  8605. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  8606. }
  8607. if (properties.color !== undefined) {this.color = properties.color;}
  8608. // A node is connected when it has a from and to node.
  8609. this.connect();
  8610. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  8611. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  8612. this.stiffness = 1 / this.length;
  8613. // set draw method based on style
  8614. switch (this.style) {
  8615. case 'line': this.draw = this._drawLine; break;
  8616. case 'arrow': this.draw = this._drawArrow; break;
  8617. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  8618. case 'dash-line': this.draw = this._drawDashLine; break;
  8619. default: this.draw = this._drawLine; break;
  8620. }
  8621. };
  8622. /**
  8623. * Connect an edge to its nodes
  8624. */
  8625. Edge.prototype.connect = function () {
  8626. this.disconnect();
  8627. this.from = this.graph.nodes[this.fromId] || null;
  8628. this.to = this.graph.nodes[this.toId] || null;
  8629. this.connected = (this.from && this.to);
  8630. if (this.connected) {
  8631. this.from.attachEdge(this);
  8632. this.to.attachEdge(this);
  8633. }
  8634. else {
  8635. if (this.from) {
  8636. this.from.detachEdge(this);
  8637. }
  8638. if (this.to) {
  8639. this.to.detachEdge(this);
  8640. }
  8641. }
  8642. };
  8643. /**
  8644. * Disconnect an edge from its nodes
  8645. */
  8646. Edge.prototype.disconnect = function () {
  8647. if (this.from) {
  8648. this.from.detachEdge(this);
  8649. this.from = null;
  8650. }
  8651. if (this.to) {
  8652. this.to.detachEdge(this);
  8653. this.to = null;
  8654. }
  8655. this.connected = false;
  8656. };
  8657. /**
  8658. * get the title of this edge.
  8659. * @return {string} title The title of the edge, or undefined when no title
  8660. * has been set.
  8661. */
  8662. Edge.prototype.getTitle = function() {
  8663. return this.title;
  8664. };
  8665. /**
  8666. * Retrieve the value of the edge. Can be undefined
  8667. * @return {Number} value
  8668. */
  8669. Edge.prototype.getValue = function() {
  8670. return this.value;
  8671. };
  8672. /**
  8673. * Adjust the value range of the edge. The edge will adjust it's width
  8674. * based on its value.
  8675. * @param {Number} min
  8676. * @param {Number} max
  8677. */
  8678. Edge.prototype.setValueRange = function(min, max) {
  8679. if (!this.widthFixed && this.value !== undefined) {
  8680. var scale = (this.widthMax - this.widthMin) / (max - min);
  8681. this.width = (this.value - min) * scale + this.widthMin;
  8682. }
  8683. };
  8684. /**
  8685. * Redraw a edge
  8686. * Draw this edge in the given canvas
  8687. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8688. * @param {CanvasRenderingContext2D} ctx
  8689. */
  8690. Edge.prototype.draw = function(ctx) {
  8691. throw "Method draw not initialized in edge";
  8692. };
  8693. /**
  8694. * Check if this object is overlapping with the provided object
  8695. * @param {Object} obj an object with parameters left, top
  8696. * @return {boolean} True if location is located on the edge
  8697. */
  8698. Edge.prototype.isOverlappingWith = function(obj) {
  8699. var distMax = 10;
  8700. var xFrom = this.from.x;
  8701. var yFrom = this.from.y;
  8702. var xTo = this.to.x;
  8703. var yTo = this.to.y;
  8704. var xObj = obj.left;
  8705. var yObj = obj.top;
  8706. var dist = Edge._dist(xFrom, yFrom, xTo, yTo, xObj, yObj);
  8707. return (dist < distMax);
  8708. };
  8709. /**
  8710. * Redraw a edge as a line
  8711. * Draw this edge in the given canvas
  8712. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8713. * @param {CanvasRenderingContext2D} ctx
  8714. * @private
  8715. */
  8716. Edge.prototype._drawLine = function(ctx) {
  8717. // set style
  8718. ctx.strokeStyle = this.color;
  8719. ctx.lineWidth = this._getLineWidth();
  8720. var point;
  8721. if (this.from != this.to) {
  8722. // draw line
  8723. this._line(ctx);
  8724. // draw label
  8725. if (this.label) {
  8726. point = this._pointOnLine(0.5);
  8727. this._label(ctx, this.label, point.x, point.y);
  8728. }
  8729. }
  8730. else {
  8731. var x, y;
  8732. var radius = this.length / 4;
  8733. var node = this.from;
  8734. if (!node.width) {
  8735. node.resize(ctx);
  8736. }
  8737. if (node.width > node.height) {
  8738. x = node.x + node.width / 2;
  8739. y = node.y - radius;
  8740. }
  8741. else {
  8742. x = node.x + radius;
  8743. y = node.y - node.height / 2;
  8744. }
  8745. this._circle(ctx, x, y, radius);
  8746. point = this._pointOnCircle(x, y, radius, 0.5);
  8747. this._label(ctx, this.label, point.x, point.y);
  8748. }
  8749. };
  8750. /**
  8751. * Get the line width of the edge. Depends on width and whether one of the
  8752. * connected nodes is selected.
  8753. * @return {Number} width
  8754. * @private
  8755. */
  8756. Edge.prototype._getLineWidth = function() {
  8757. if (this.from.selected || this.to.selected) {
  8758. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  8759. }
  8760. else {
  8761. return this.width*this.graphScaleInv;
  8762. }
  8763. };
  8764. /**
  8765. * Draw a line between two nodes
  8766. * @param {CanvasRenderingContext2D} ctx
  8767. * @private
  8768. */
  8769. Edge.prototype._line = function (ctx) {
  8770. // draw a straight line
  8771. ctx.beginPath();
  8772. ctx.moveTo(this.from.x, this.from.y);
  8773. ctx.lineTo(this.to.x, this.to.y);
  8774. ctx.stroke();
  8775. };
  8776. /**
  8777. * Draw a line from a node to itself, a circle
  8778. * @param {CanvasRenderingContext2D} ctx
  8779. * @param {Number} x
  8780. * @param {Number} y
  8781. * @param {Number} radius
  8782. * @private
  8783. */
  8784. Edge.prototype._circle = function (ctx, x, y, radius) {
  8785. // draw a circle
  8786. ctx.beginPath();
  8787. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  8788. ctx.stroke();
  8789. };
  8790. /**
  8791. * Draw label with white background and with the middle at (x, y)
  8792. * @param {CanvasRenderingContext2D} ctx
  8793. * @param {String} text
  8794. * @param {Number} x
  8795. * @param {Number} y
  8796. * @private
  8797. */
  8798. Edge.prototype._label = function (ctx, text, x, y) {
  8799. if (text) {
  8800. // TODO: cache the calculated size
  8801. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  8802. this.fontSize + "px " + this.fontFace;
  8803. ctx.fillStyle = 'white';
  8804. var width = ctx.measureText(text).width;
  8805. var height = this.fontSize;
  8806. var left = x - width / 2;
  8807. var top = y - height / 2;
  8808. ctx.fillRect(left, top, width, height);
  8809. // draw text
  8810. ctx.fillStyle = this.fontColor || "black";
  8811. ctx.textAlign = "left";
  8812. ctx.textBaseline = "top";
  8813. ctx.fillText(text, left, top);
  8814. }
  8815. };
  8816. /**
  8817. * Redraw a edge as a dashed line
  8818. * Draw this edge in the given canvas
  8819. * @author David Jordan
  8820. * @date 2012-08-08
  8821. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8822. * @param {CanvasRenderingContext2D} ctx
  8823. * @private
  8824. */
  8825. Edge.prototype._drawDashLine = function(ctx) {
  8826. // set style
  8827. ctx.strokeStyle = this.color;
  8828. ctx.lineWidth = this._getLineWidth();
  8829. // draw dashed line
  8830. ctx.beginPath();
  8831. ctx.lineCap = 'round';
  8832. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  8833. {
  8834. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8835. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  8836. }
  8837. 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
  8838. {
  8839. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8840. [this.dash.length,this.dash.gap]);
  8841. }
  8842. else //If all else fails draw a line
  8843. {
  8844. ctx.moveTo(this.from.x, this.from.y);
  8845. ctx.lineTo(this.to.x, this.to.y);
  8846. }
  8847. ctx.stroke();
  8848. // draw label
  8849. if (this.label) {
  8850. var point = this._pointOnLine(0.5);
  8851. this._label(ctx, this.label, point.x, point.y);
  8852. }
  8853. };
  8854. /**
  8855. * Get a point on a line
  8856. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8857. * @return {Object} point
  8858. * @private
  8859. */
  8860. Edge.prototype._pointOnLine = function (percentage) {
  8861. return {
  8862. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  8863. y: (1 - percentage) * this.from.y + percentage * this.to.y
  8864. }
  8865. };
  8866. /**
  8867. * Get a point on a circle
  8868. * @param {Number} x
  8869. * @param {Number} y
  8870. * @param {Number} radius
  8871. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8872. * @return {Object} point
  8873. * @private
  8874. */
  8875. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  8876. var angle = (percentage - 3/8) * 2 * Math.PI;
  8877. return {
  8878. x: x + radius * Math.cos(angle),
  8879. y: y - radius * Math.sin(angle)
  8880. }
  8881. };
  8882. /**
  8883. * Redraw a edge as a line with an arrow halfway the line
  8884. * Draw this edge in the given canvas
  8885. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8886. * @param {CanvasRenderingContext2D} ctx
  8887. * @private
  8888. */
  8889. Edge.prototype._drawArrowCenter = function(ctx) {
  8890. var point;
  8891. // set style
  8892. ctx.strokeStyle = this.color;
  8893. ctx.fillStyle = this.color;
  8894. ctx.lineWidth = this._getLineWidth();
  8895. if (this.from != this.to) {
  8896. // draw line
  8897. this._line(ctx);
  8898. // draw an arrow halfway the line
  8899. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8900. var length = 10 + 5 * this.width; // TODO: make customizable?
  8901. point = this._pointOnLine(0.5);
  8902. ctx.arrow(point.x, point.y, angle, length);
  8903. ctx.fill();
  8904. ctx.stroke();
  8905. // draw label
  8906. if (this.label) {
  8907. point = this._pointOnLine(0.5);
  8908. this._label(ctx, this.label, point.x, point.y);
  8909. }
  8910. }
  8911. else {
  8912. // draw circle
  8913. var x, y;
  8914. var radius = this.length / 4;
  8915. var node = this.from;
  8916. if (!node.width) {
  8917. node.resize(ctx);
  8918. }
  8919. if (node.width > node.height) {
  8920. x = node.x + node.width / 2;
  8921. y = node.y - radius;
  8922. }
  8923. else {
  8924. x = node.x + radius;
  8925. y = node.y - node.height / 2;
  8926. }
  8927. this._circle(ctx, x, y, radius);
  8928. // draw all arrows
  8929. var angle = 0.2 * Math.PI;
  8930. var length = 10 + 5 * this.width; // TODO: make customizable?
  8931. point = this._pointOnCircle(x, y, radius, 0.5);
  8932. ctx.arrow(point.x, point.y, angle, length);
  8933. ctx.fill();
  8934. ctx.stroke();
  8935. // draw label
  8936. if (this.label) {
  8937. point = this._pointOnCircle(x, y, radius, 0.5);
  8938. this._label(ctx, this.label, point.x, point.y);
  8939. }
  8940. }
  8941. };
  8942. /**
  8943. * Redraw a edge as a line with an arrow
  8944. * Draw this edge in the given canvas
  8945. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8946. * @param {CanvasRenderingContext2D} ctx
  8947. * @private
  8948. */
  8949. Edge.prototype._drawArrow = function(ctx) {
  8950. // set style
  8951. ctx.strokeStyle = this.color;
  8952. ctx.fillStyle = this.color;
  8953. ctx.lineWidth = this._getLineWidth();
  8954. // draw line
  8955. var angle, length;
  8956. if (this.from != this.to) {
  8957. // calculate length and angle of the line
  8958. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8959. var dx = (this.to.x - this.from.x);
  8960. var dy = (this.to.y - this.from.y);
  8961. var lEdge = Math.sqrt(dx * dx + dy * dy);
  8962. var lFrom = this.from.distanceToBorder(ctx, angle + Math.PI);
  8963. var pFrom = (lEdge - lFrom) / lEdge;
  8964. var xFrom = (pFrom) * this.from.x + (1 - pFrom) * this.to.x;
  8965. var yFrom = (pFrom) * this.from.y + (1 - pFrom) * this.to.y;
  8966. var lTo = this.to.distanceToBorder(ctx, angle);
  8967. var pTo = (lEdge - lTo) / lEdge;
  8968. var xTo = (1 - pTo) * this.from.x + pTo * this.to.x;
  8969. var yTo = (1 - pTo) * this.from.y + pTo * this.to.y;
  8970. ctx.beginPath();
  8971. ctx.moveTo(xFrom, yFrom);
  8972. ctx.lineTo(xTo, yTo);
  8973. ctx.stroke();
  8974. // draw arrow at the end of the line
  8975. length = 10 + 5 * this.width; // TODO: make customizable?
  8976. ctx.arrow(xTo, yTo, angle, length);
  8977. ctx.fill();
  8978. ctx.stroke();
  8979. // draw label
  8980. if (this.label) {
  8981. var point = this._pointOnLine(0.5);
  8982. this._label(ctx, this.label, point.x, point.y);
  8983. }
  8984. }
  8985. else {
  8986. // draw circle
  8987. var node = this.from;
  8988. var x, y, arrow;
  8989. var radius = this.length / 4;
  8990. if (!node.width) {
  8991. node.resize(ctx);
  8992. }
  8993. if (node.width > node.height) {
  8994. x = node.x + node.width / 2;
  8995. y = node.y - radius;
  8996. arrow = {
  8997. x: x,
  8998. y: node.y,
  8999. angle: 0.9 * Math.PI
  9000. };
  9001. }
  9002. else {
  9003. x = node.x + radius;
  9004. y = node.y - node.height / 2;
  9005. arrow = {
  9006. x: node.x,
  9007. y: y,
  9008. angle: 0.6 * Math.PI
  9009. };
  9010. }
  9011. ctx.beginPath();
  9012. // TODO: do not draw a circle, but an arc
  9013. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9014. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9015. ctx.stroke();
  9016. // draw all arrows
  9017. length = 10 + 5 * this.width; // TODO: make customizable?
  9018. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9019. ctx.fill();
  9020. ctx.stroke();
  9021. // draw label
  9022. if (this.label) {
  9023. point = this._pointOnCircle(x, y, radius, 0.5);
  9024. this._label(ctx, this.label, point.x, point.y);
  9025. }
  9026. }
  9027. };
  9028. /**
  9029. * Calculate the distance between a point (x3,y3) and a line segment from
  9030. * (x1,y1) to (x2,y2).
  9031. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9032. * @param {number} x1
  9033. * @param {number} y1
  9034. * @param {number} x2
  9035. * @param {number} y2
  9036. * @param {number} x3
  9037. * @param {number} y3
  9038. * @private
  9039. */
  9040. Edge._dist = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9041. var px = x2-x1,
  9042. py = y2-y1,
  9043. something = px*px + py*py,
  9044. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9045. if (u > 1) {
  9046. u = 1;
  9047. }
  9048. else if (u < 0) {
  9049. u = 0;
  9050. }
  9051. var x = x1 + u * px,
  9052. y = y1 + u * py,
  9053. dx = x - x3,
  9054. dy = y - y3;
  9055. //# Note: If the actual distance does not matter,
  9056. //# if you only want to compare what this function
  9057. //# returns to other results of this function, you
  9058. //# can just return the squared distance instead
  9059. //# (i.e. remove the sqrt) to gain a little performance
  9060. return Math.sqrt(dx*dx + dy*dy);
  9061. };
  9062. /**
  9063. * This allows the zoom level of the graph to influence the rendering
  9064. *
  9065. * @param scale
  9066. */
  9067. Edge.prototype.setScale = function(scale) {
  9068. this.graphScaleInv = 1.0/scale;
  9069. };
  9070. /**
  9071. * Popup is a class to create a popup window with some text
  9072. * @param {Element} container The container object.
  9073. * @param {Number} [x]
  9074. * @param {Number} [y]
  9075. * @param {String} [text]
  9076. */
  9077. function Popup(container, x, y, text) {
  9078. if (container) {
  9079. this.container = container;
  9080. }
  9081. else {
  9082. this.container = document.body;
  9083. }
  9084. this.x = 0;
  9085. this.y = 0;
  9086. this.padding = 5;
  9087. if (x !== undefined && y !== undefined ) {
  9088. this.setPosition(x, y);
  9089. }
  9090. if (text !== undefined) {
  9091. this.setText(text);
  9092. }
  9093. // create the frame
  9094. this.frame = document.createElement("div");
  9095. var style = this.frame.style;
  9096. style.position = "absolute";
  9097. style.visibility = "hidden";
  9098. style.border = "1px solid #666";
  9099. style.color = "black";
  9100. style.padding = this.padding + "px";
  9101. style.backgroundColor = "#FFFFC6";
  9102. style.borderRadius = "3px";
  9103. style.MozBorderRadius = "3px";
  9104. style.WebkitBorderRadius = "3px";
  9105. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9106. style.whiteSpace = "nowrap";
  9107. this.container.appendChild(this.frame);
  9108. }
  9109. /**
  9110. * @param {number} x Horizontal position of the popup window
  9111. * @param {number} y Vertical position of the popup window
  9112. */
  9113. Popup.prototype.setPosition = function(x, y) {
  9114. this.x = parseInt(x);
  9115. this.y = parseInt(y);
  9116. };
  9117. /**
  9118. * Set the text for the popup window. This can be HTML code
  9119. * @param {string} text
  9120. */
  9121. Popup.prototype.setText = function(text) {
  9122. this.frame.innerHTML = text;
  9123. };
  9124. /**
  9125. * Show the popup window
  9126. * @param {boolean} show Optional. Show or hide the window
  9127. */
  9128. Popup.prototype.show = function (show) {
  9129. if (show === undefined) {
  9130. show = true;
  9131. }
  9132. if (show) {
  9133. var height = this.frame.clientHeight;
  9134. var width = this.frame.clientWidth;
  9135. var maxHeight = this.frame.parentNode.clientHeight;
  9136. var maxWidth = this.frame.parentNode.clientWidth;
  9137. var top = (this.y - height);
  9138. if (top + height + this.padding > maxHeight) {
  9139. top = maxHeight - height - this.padding;
  9140. }
  9141. if (top < this.padding) {
  9142. top = this.padding;
  9143. }
  9144. var left = this.x;
  9145. if (left + width + this.padding > maxWidth) {
  9146. left = maxWidth - width - this.padding;
  9147. }
  9148. if (left < this.padding) {
  9149. left = this.padding;
  9150. }
  9151. this.frame.style.left = left + "px";
  9152. this.frame.style.top = top + "px";
  9153. this.frame.style.visibility = "visible";
  9154. }
  9155. else {
  9156. this.hide();
  9157. }
  9158. };
  9159. /**
  9160. * Hide the popup window
  9161. */
  9162. Popup.prototype.hide = function () {
  9163. this.frame.style.visibility = "hidden";
  9164. };
  9165. /**
  9166. * @class Groups
  9167. * This class can store groups and properties specific for groups.
  9168. */
  9169. Groups = function () {
  9170. this.clear();
  9171. this.defaultIndex = 0;
  9172. };
  9173. /**
  9174. * default constants for group colors
  9175. */
  9176. Groups.DEFAULT = [
  9177. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9178. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9179. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9180. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9181. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9182. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9183. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9184. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9185. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9186. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9187. ];
  9188. /**
  9189. * Clear all groups
  9190. */
  9191. Groups.prototype.clear = function () {
  9192. this.groups = {};
  9193. this.groups.length = function()
  9194. {
  9195. var i = 0;
  9196. for ( var p in this ) {
  9197. if (this.hasOwnProperty(p)) {
  9198. i++;
  9199. }
  9200. }
  9201. return i;
  9202. }
  9203. };
  9204. /**
  9205. * get group properties of a groupname. If groupname is not found, a new group
  9206. * is added.
  9207. * @param {*} groupname Can be a number, string, Date, etc.
  9208. * @return {Object} group The created group, containing all group properties
  9209. */
  9210. Groups.prototype.get = function (groupname) {
  9211. var group = this.groups[groupname];
  9212. if (group == undefined) {
  9213. // create new group
  9214. var index = this.defaultIndex % Groups.DEFAULT.length;
  9215. this.defaultIndex++;
  9216. group = {};
  9217. group.color = Groups.DEFAULT[index];
  9218. this.groups[groupname] = group;
  9219. }
  9220. return group;
  9221. };
  9222. /**
  9223. * Add a custom group style
  9224. * @param {String} groupname
  9225. * @param {Object} style An object containing borderColor,
  9226. * backgroundColor, etc.
  9227. * @return {Object} group The created group object
  9228. */
  9229. Groups.prototype.add = function (groupname, style) {
  9230. this.groups[groupname] = style;
  9231. if (style.color) {
  9232. style.color = Node.parseColor(style.color);
  9233. }
  9234. return style;
  9235. };
  9236. /**
  9237. * @class Images
  9238. * This class loads images and keeps them stored.
  9239. */
  9240. Images = function () {
  9241. this.images = {};
  9242. this.callback = undefined;
  9243. };
  9244. /**
  9245. * Set an onload callback function. This will be called each time an image
  9246. * is loaded
  9247. * @param {function} callback
  9248. */
  9249. Images.prototype.setOnloadCallback = function(callback) {
  9250. this.callback = callback;
  9251. };
  9252. /**
  9253. *
  9254. * @param {string} url Url of the image
  9255. * @return {Image} img The image object
  9256. */
  9257. Images.prototype.load = function(url) {
  9258. var img = this.images[url];
  9259. if (img == undefined) {
  9260. // create the image
  9261. var images = this;
  9262. img = new Image();
  9263. this.images[url] = img;
  9264. img.onload = function() {
  9265. if (images.callback) {
  9266. images.callback(this);
  9267. }
  9268. };
  9269. img.src = url;
  9270. }
  9271. return img;
  9272. };
  9273. /**
  9274. * Creation of the SectorMixin var.
  9275. *
  9276. * This contains all the functions the Graph object can use to employ the sector system.
  9277. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  9278. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  9279. *
  9280. * Alex de Mulder
  9281. * 21-01-2013
  9282. */
  9283. var SectorMixin = {
  9284. /**
  9285. * This function is only called by the setData function of the Graph object.
  9286. * This loads the global references into the active sector. This initializes the sector.
  9287. *
  9288. * @private
  9289. */
  9290. _putDataInSector : function() {
  9291. this.sectors["active"][this._sector()].nodes = this.nodes;
  9292. this.sectors["active"][this._sector()].edges = this.edges;
  9293. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  9294. },
  9295. /**
  9296. * /**
  9297. * This function sets the global references to nodes, edges and nodeIndices back to
  9298. * those of the supplied (active) sector. If a type is defined, do the specific type
  9299. *
  9300. * @param {String} sectorId
  9301. * @param {String} [sectorType] | "active" or "frozen"
  9302. * @private
  9303. */
  9304. _switchToSector : function(sectorId, sectorType) {
  9305. if (sectorType === undefined || sectorType == "active") {
  9306. this._switchToActiveSector(sectorId);
  9307. }
  9308. else {
  9309. this._switchToFrozenSector(sectorId);
  9310. }
  9311. },
  9312. /**
  9313. * This function sets the global references to nodes, edges and nodeIndices back to
  9314. * those of the supplied active sector.
  9315. *
  9316. * @param sectorId
  9317. * @private
  9318. */
  9319. _switchToActiveSector : function(sectorId) {
  9320. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  9321. this.nodes = this.sectors["active"][sectorId]["nodes"];
  9322. this.edges = this.sectors["active"][sectorId]["edges"];
  9323. },
  9324. /**
  9325. * This function sets the global references to nodes, edges and nodeIndices back to
  9326. * those of the supplied frozen sector.
  9327. *
  9328. * @param sectorId
  9329. * @private
  9330. */
  9331. _switchToFrozenSector : function(sectorId) {
  9332. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  9333. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  9334. this.edges = this.sectors["frozen"][sectorId]["edges"];
  9335. },
  9336. /**
  9337. * This function sets the global references to nodes, edges and nodeIndices to
  9338. * those of the UI sector.
  9339. *
  9340. * @private
  9341. */
  9342. _switchToUISector : function() {
  9343. this.nodeIndices = this.sectors["UI"]["nodeIndices"];
  9344. this.nodes = this.sectors["UI"]["nodes"];
  9345. this.edges = this.sectors["UI"]["edges"];
  9346. },
  9347. /**
  9348. * This function sets the global references to nodes, edges and nodeIndices back to
  9349. * those of the currently active sector.
  9350. *
  9351. * @private
  9352. */
  9353. _loadLatestSector : function() {
  9354. this._switchToSector(this._sector());
  9355. },
  9356. /**
  9357. * This function returns the currently active sector Id
  9358. *
  9359. * @returns {String}
  9360. * @private
  9361. */
  9362. _sector : function() {
  9363. return this.activeSector[this.activeSector.length-1];
  9364. },
  9365. /**
  9366. * This function returns the previously active sector Id
  9367. *
  9368. * @returns {String}
  9369. * @private
  9370. */
  9371. _previousSector : function() {
  9372. if (this.activeSector.length > 1) {
  9373. return this.activeSector[this.activeSector.length-2];
  9374. }
  9375. else {
  9376. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  9377. }
  9378. },
  9379. /**
  9380. * We add the active sector at the end of the this.activeSector array
  9381. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  9382. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  9383. *
  9384. * @param newId
  9385. * @private
  9386. */
  9387. _setActiveSector : function(newId) {
  9388. this.activeSector.push(newId);
  9389. },
  9390. /**
  9391. * We remove the currently active sector id from the active sector stack. This happens when
  9392. * we reactivate the previously active sector
  9393. *
  9394. * @private
  9395. */
  9396. _forgetLastSector : function() {
  9397. this.activeSector.pop();
  9398. },
  9399. /**
  9400. * This function creates a new active sector with the supplied newId. This newId
  9401. * is the expanding node id.
  9402. *
  9403. * @param {String} newId | Id of the new active sector
  9404. * @private
  9405. */
  9406. _createNewSector : function(newId) {
  9407. // create the new sector
  9408. this.sectors["active"][newId] = {"nodes":{},
  9409. "edges":{},
  9410. "nodeIndices":[],
  9411. "formationScale": this.scale,
  9412. "drawingNode": undefined};
  9413. // create the new sector render node. This gives visual feedback that you are in a new sector.
  9414. this.sectors["active"][newId]['drawingNode'] = new Node(
  9415. {id:newId,
  9416. color: {
  9417. background: "#eaefef",
  9418. border: "495c5e"
  9419. }
  9420. },{},{},this.constants);
  9421. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  9422. },
  9423. /**
  9424. * This function removes the currently active sector. This is called when we create a new
  9425. * active sector.
  9426. *
  9427. * @param {String} sectorId | Id of the active sector that will be removed
  9428. * @private
  9429. */
  9430. _deleteActiveSector : function(sectorId) {
  9431. delete this.sectors["active"][sectorId];
  9432. },
  9433. /**
  9434. * This function removes the currently active sector. This is called when we reactivate
  9435. * the previously active sector.
  9436. *
  9437. * @param {String} sectorId | Id of the active sector that will be removed
  9438. * @private
  9439. */
  9440. _deleteFrozenSector : function(sectorId) {
  9441. delete this.sectors["frozen"][sectorId];
  9442. },
  9443. /**
  9444. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  9445. * We copy the references, then delete the active entree.
  9446. *
  9447. * @param sectorId
  9448. * @private
  9449. */
  9450. _freezeSector : function(sectorId) {
  9451. // we move the set references from the active to the frozen stack.
  9452. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  9453. // we have moved the sector data into the frozen set, we now remove it from the active set
  9454. this._deleteActiveSector(sectorId);
  9455. },
  9456. /**
  9457. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  9458. * object to the "active" object.
  9459. *
  9460. * @param sectorId
  9461. * @private
  9462. */
  9463. _activateSector : function(sectorId) {
  9464. // we move the set references from the frozen to the active stack.
  9465. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  9466. // we have moved the sector data into the active set, we now remove it from the frozen stack
  9467. this._deleteFrozenSector(sectorId);
  9468. },
  9469. /**
  9470. * This function merges the data from the currently active sector with a frozen sector. This is used
  9471. * in the process of reverting back to the previously active sector.
  9472. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  9473. * upon the creation of a new active sector.
  9474. *
  9475. * @param sectorId
  9476. * @private
  9477. */
  9478. _mergeThisWithFrozen : function(sectorId) {
  9479. // copy all nodes
  9480. for (var nodeId in this.nodes) {
  9481. if (this.nodes.hasOwnProperty(nodeId)) {
  9482. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  9483. }
  9484. }
  9485. // copy all edges (if not fully clustered, else there are no edges)
  9486. for (var edgeId in this.edges) {
  9487. if (this.edges.hasOwnProperty(edgeId)) {
  9488. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  9489. }
  9490. }
  9491. // merge the nodeIndices
  9492. for (var i = 0; i < this.nodeIndices.length; i++) {
  9493. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  9494. }
  9495. },
  9496. /**
  9497. * This clusters the sector to one cluster. It was a single cluster before this process started so
  9498. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  9499. *
  9500. * @private
  9501. */
  9502. _collapseThisToSingleCluster : function() {
  9503. this.clusterToFit(1,false);
  9504. },
  9505. /**
  9506. * We create a new active sector from the node that we want to open.
  9507. *
  9508. * @param node
  9509. * @private
  9510. */
  9511. _addSector : function(node) {
  9512. // this is the currently active sector
  9513. var sector = this._sector();
  9514. // // this should allow me to select nodes from a frozen set.
  9515. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  9516. // console.log("the node is part of the active sector");
  9517. // }
  9518. // else {
  9519. // console.log("I dont know what the fuck happened!!");
  9520. // }
  9521. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  9522. delete this.nodes[node.id];
  9523. var unqiueIdentifier = util.randomUUID();
  9524. // we fully freeze the currently active sector
  9525. this._freezeSector(sector);
  9526. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  9527. this._createNewSector(unqiueIdentifier);
  9528. // we add the active sector to the sectors array to be able to revert these steps later on
  9529. this._setActiveSector(unqiueIdentifier);
  9530. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  9531. this._switchToSector(this._sector());
  9532. // finally we add the node we removed from our previous active sector to the new active sector
  9533. this.nodes[node.id] = node;
  9534. },
  9535. /**
  9536. * We close the sector that is currently open and revert back to the one before.
  9537. * If the active sector is the "default" sector, nothing happens.
  9538. *
  9539. * @private
  9540. */
  9541. _collapseSector : function() {
  9542. // the currently active sector
  9543. var sector = this._sector();
  9544. // we cannot collapse the default sector
  9545. if (sector != "default") {
  9546. if ((this.nodeIndices.length == 1) ||
  9547. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  9548. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  9549. var previousSector = this._previousSector();
  9550. // we collapse the sector back to a single cluster
  9551. this._collapseThisToSingleCluster();
  9552. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  9553. // This previous sector is the one we will reactivate
  9554. this._mergeThisWithFrozen(previousSector);
  9555. // the previously active (frozen) sector now has all the data from the currently active sector.
  9556. // we can now delete the active sector.
  9557. this._deleteActiveSector(sector);
  9558. // we activate the previously active (and currently frozen) sector.
  9559. this._activateSector(previousSector);
  9560. // we load the references from the newly active sector into the global references
  9561. this._switchToSector(previousSector);
  9562. // we forget the previously active sector because we reverted to the one before
  9563. this._forgetLastSector();
  9564. // finally, we update the node index list.
  9565. this._updateNodeIndexList();
  9566. }
  9567. }
  9568. },
  9569. /**
  9570. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  9571. *
  9572. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9573. * | we dont pass the function itself because then the "this" is the window object
  9574. * | instead of the Graph object
  9575. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9576. * @private
  9577. */
  9578. _doInAllActiveSectors : function(runFunction,argument) {
  9579. if (argument === undefined) {
  9580. for (var sector in this.sectors["active"]) {
  9581. if (this.sectors["active"].hasOwnProperty(sector)) {
  9582. // switch the global references to those of this sector
  9583. this._switchToActiveSector(sector);
  9584. this[runFunction]();
  9585. }
  9586. }
  9587. }
  9588. else {
  9589. for (var sector in this.sectors["active"]) {
  9590. if (this.sectors["active"].hasOwnProperty(sector)) {
  9591. // switch the global references to those of this sector
  9592. this._switchToActiveSector(sector);
  9593. var args = Array.prototype.splice.call(arguments, 1);
  9594. if (args.length > 1) {
  9595. this[runFunction](args[0],args[1]);
  9596. }
  9597. else {
  9598. this[runFunction](argument);
  9599. }
  9600. }
  9601. }
  9602. }
  9603. // we revert the global references back to our active sector
  9604. this._loadLatestSector();
  9605. },
  9606. /**
  9607. * This runs a function in all frozen sectors. This is used in the _redraw().
  9608. *
  9609. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9610. * | we don't pass the function itself because then the "this" is the window object
  9611. * | instead of the Graph object
  9612. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9613. * @private
  9614. */
  9615. _doInAllFrozenSectors : function(runFunction,argument) {
  9616. if (argument === undefined) {
  9617. for (var sector in this.sectors["frozen"]) {
  9618. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  9619. // switch the global references to those of this sector
  9620. this._switchToFrozenSector(sector);
  9621. this[runFunction]();
  9622. }
  9623. }
  9624. }
  9625. else {
  9626. for (var sector in this.sectors["frozen"]) {
  9627. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  9628. // switch the global references to those of this sector
  9629. this._switchToFrozenSector(sector);
  9630. var args = Array.prototype.splice.call(arguments, 1);
  9631. if (args.length > 1) {
  9632. this[runFunction](args[0],args[1]);
  9633. }
  9634. else {
  9635. this[runFunction](argument);
  9636. }
  9637. }
  9638. }
  9639. }
  9640. this._loadLatestSector();
  9641. },
  9642. /**
  9643. * This runs a function in all frozen sectors. This is used in the _redraw().
  9644. *
  9645. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9646. * | we don't pass the function itself because then the "this" is the window object
  9647. * | instead of the Graph object
  9648. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9649. * @private
  9650. */
  9651. _doInUISector : function(runFunction,argument) {
  9652. this._switchToUISector();
  9653. if (argument === undefined) {
  9654. this[runFunction]();
  9655. }
  9656. else {
  9657. var args = Array.prototype.splice.call(arguments, 1);
  9658. if (args.length > 1) {
  9659. this[runFunction](args[0],args[1]);
  9660. }
  9661. else {
  9662. this[runFunction](argument);
  9663. }
  9664. }
  9665. this._loadLatestSector();
  9666. },
  9667. /**
  9668. * This runs a function in all sectors. This is used in the _redraw().
  9669. *
  9670. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9671. * | we don't pass the function itself because then the "this" is the window object
  9672. * | instead of the Graph object
  9673. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9674. * @private
  9675. */
  9676. _doInAllSectors : function(runFunction,argument) {
  9677. var args = Array.prototype.splice.call(arguments, 1);
  9678. if (argument === undefined) {
  9679. this._doInAllActiveSectors(runFunction);
  9680. this._doInAllFrozenSectors(runFunction);
  9681. }
  9682. else {
  9683. if (args.length > 1) {
  9684. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  9685. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  9686. }
  9687. else {
  9688. this._doInAllActiveSectors(runFunction,argument);
  9689. this._doInAllFrozenSectors(runFunction,argument);
  9690. }
  9691. }
  9692. },
  9693. /**
  9694. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  9695. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  9696. *
  9697. * @private
  9698. */
  9699. _clearNodeIndexList : function() {
  9700. var sector = this._sector();
  9701. this.sectors["active"][sector]["nodeIndices"] = [];
  9702. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  9703. },
  9704. /**
  9705. * Draw the encompassing sector node
  9706. *
  9707. * @param ctx
  9708. * @param sectorType
  9709. * @private
  9710. */
  9711. _drawSectorNodes : function(ctx,sectorType) {
  9712. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  9713. for (var sector in this.sectors[sectorType]) {
  9714. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  9715. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  9716. this._switchToSector(sector,sectorType);
  9717. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  9718. for (var nodeId in this.nodes) {
  9719. if (this.nodes.hasOwnProperty(nodeId)) {
  9720. node = this.nodes[nodeId];
  9721. node.resize(ctx);
  9722. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  9723. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  9724. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  9725. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  9726. }
  9727. }
  9728. node = this.sectors[sectorType][sector]["drawingNode"];
  9729. node.x = 0.5 * (maxX + minX);
  9730. node.y = 0.5 * (maxY + minY);
  9731. node.width = 2 * (node.x - minX);
  9732. node.height = 2 * (node.y - minY);
  9733. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  9734. node.setScale(this.scale);
  9735. node._drawCircle(ctx);
  9736. }
  9737. }
  9738. }
  9739. },
  9740. _drawAllSectorNodes : function(ctx) {
  9741. this._drawSectorNodes(ctx,"frozen");
  9742. this._drawSectorNodes(ctx,"active");
  9743. this._loadLatestSector();
  9744. }
  9745. };
  9746. /**
  9747. * Creation of the ClusterMixin var.
  9748. *
  9749. * This contains all the functions the Graph object can use to employ clustering
  9750. *
  9751. * Alex de Mulder
  9752. * 21-01-2013
  9753. */
  9754. var ClusterMixin = {
  9755. /**
  9756. * This is only called in the constructor of the graph object
  9757. * */
  9758. startWithClustering : function() {
  9759. // cluster if the data set is big
  9760. this.clusterToFit(this.constants.clustering.initialMaxNumberOfNodes, true);
  9761. // updates the lables after clustering
  9762. this.updateLabels();
  9763. // this is called here because if clusterin is disabled, the start and stabilize are called in
  9764. // the setData function.
  9765. if (this.stabilize) {
  9766. this._doStabilize();
  9767. }
  9768. this.start();
  9769. },
  9770. /**
  9771. * This function clusters until the initialMaxNumberOfNodes has been reached
  9772. *
  9773. * @param {Number} maxNumberOfNodes
  9774. * @param {Boolean} reposition
  9775. */
  9776. clusterToFit : function(maxNumberOfNodes, reposition) {
  9777. var numberOfNodes = this.nodeIndices.length;
  9778. var maxLevels = 50;
  9779. var level = 0;
  9780. // we first cluster the hubs, then we pull in the outliers, repeat
  9781. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  9782. if (level % 3 == 0) {
  9783. this.forceAggregateHubs();
  9784. }
  9785. else {
  9786. this.increaseClusterLevel();
  9787. }
  9788. numberOfNodes = this.nodeIndices.length;
  9789. level += 1;
  9790. }
  9791. // after the clustering we reposition the nodes to reduce the initial chaos
  9792. if (level > 1 && reposition == true) {
  9793. this.repositionNodes();
  9794. }
  9795. },
  9796. /**
  9797. * This function can be called to open up a specific cluster. It is only called by
  9798. * It will unpack the cluster back one level.
  9799. *
  9800. * @param node | Node object: cluster to open.
  9801. */
  9802. openCluster : function(node) {
  9803. var isMovingBeforeClustering = this.moving;
  9804. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  9805. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  9806. this._addSector(node);
  9807. var level = 0;
  9808. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNumberOfNodes) && (level < 10)) {
  9809. this.decreaseClusterLevel();
  9810. level += 1;
  9811. }
  9812. }
  9813. else {
  9814. this._expandClusterNode(node,false,true);
  9815. // update the index list, dynamic edges and labels
  9816. this._updateNodeIndexList();
  9817. this._updateDynamicEdges();
  9818. this.updateLabels();
  9819. }
  9820. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  9821. if (this.moving != isMovingBeforeClustering) {
  9822. this.start();
  9823. }
  9824. },
  9825. /**
  9826. * This calls the updateClustes with default arguments
  9827. */
  9828. updateClustersDefault : function() {
  9829. if (this.constants.clustering.enabled == true) {
  9830. this.updateClusters(0,false,false);
  9831. }
  9832. },
  9833. /**
  9834. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  9835. * be clustered with their connected node. This can be repeated as many times as needed.
  9836. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  9837. */
  9838. increaseClusterLevel : function() {
  9839. this.updateClusters(-1,false,true);
  9840. },
  9841. /**
  9842. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  9843. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  9844. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  9845. */
  9846. decreaseClusterLevel : function() {
  9847. this.updateClusters(1,false,true);
  9848. },
  9849. /**
  9850. * This is the main clustering function. It clusters and declusters on zoom or forced
  9851. * This function clusters on zoom, it can be called with a predefined zoom direction
  9852. * If out, check if we can form clusters, if in, check if we can open clusters.
  9853. * This function is only called from _zoom()
  9854. *
  9855. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  9856. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  9857. * @param {Boolean} force | enabled or disable forcing
  9858. *
  9859. */
  9860. updateClusters : function(zoomDirection,recursive,force) {
  9861. var isMovingBeforeClustering = this.moving;
  9862. var amountOfNodes = this.nodeIndices.length;
  9863. // on zoom out collapse the sector if the scale is at the level the sector was made
  9864. if (this.previousScale > this.scale && zoomDirection == 0) {
  9865. this._collapseSector();
  9866. }
  9867. // check if we zoom in or out
  9868. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  9869. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  9870. // outer nodes determines if it is being clustered
  9871. this._formClusters(force);
  9872. }
  9873. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  9874. if (force == true) {
  9875. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  9876. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  9877. this._openClusters(recursive,force);
  9878. }
  9879. else {
  9880. // if a cluster takes up a set percentage of the active window
  9881. this._openClustersBySize();
  9882. }
  9883. }
  9884. this._updateNodeIndexList();
  9885. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  9886. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  9887. this._aggregateHubs(force);
  9888. this._updateNodeIndexList();
  9889. }
  9890. // we now reduce chains.
  9891. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  9892. this.handleChains();
  9893. this._updateNodeIndexList();
  9894. }
  9895. this.previousScale = this.scale;
  9896. // rest of the update the index list, dynamic edges and labels
  9897. this._updateDynamicEdges();
  9898. this.updateLabels();
  9899. // if a cluster was formed, we increase the clusterSession
  9900. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  9901. this.clusterSession += 1;
  9902. }
  9903. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  9904. if (this.moving != isMovingBeforeClustering) {
  9905. this.start();
  9906. }
  9907. },
  9908. /**
  9909. * This function handles the chains. It is called on every updateClusters().
  9910. */
  9911. handleChains : function() {
  9912. // after clustering we check how many chains there are
  9913. var chainPercentage = this._getChainFraction();
  9914. if (chainPercentage > this.constants.clustering.chainThreshold) {
  9915. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  9916. }
  9917. },
  9918. /**
  9919. * this functions starts clustering by hubs
  9920. * The minimum hub threshold is set globally
  9921. *
  9922. * @private
  9923. */
  9924. _aggregateHubs : function(force) {
  9925. this._getHubSize();
  9926. this._formClustersByHub(force,false);
  9927. },
  9928. /**
  9929. * This function is fired by keypress. It forces hubs to form.
  9930. *
  9931. */
  9932. forceAggregateHubs : function() {
  9933. var isMovingBeforeClustering = this.moving;
  9934. var amountOfNodes = this.nodeIndices.length;
  9935. this._aggregateHubs(true);
  9936. // update the index list, dynamic edges and labels
  9937. this._updateNodeIndexList();
  9938. this._updateDynamicEdges();
  9939. this.updateLabels();
  9940. // if a cluster was formed, we increase the clusterSession
  9941. if (this.nodeIndices.length != amountOfNodes) {
  9942. this.clusterSession += 1;
  9943. }
  9944. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  9945. if (this.moving != isMovingBeforeClustering) {
  9946. this.start();
  9947. }
  9948. },
  9949. /**
  9950. * If a cluster takes up more than a set percentage of the screen, open the cluster
  9951. *
  9952. * @private
  9953. */
  9954. _openClustersBySize : function() {
  9955. for (var nodeId in this.nodes) {
  9956. if (this.nodes.hasOwnProperty(nodeId)) {
  9957. var node = this.nodes[nodeId];
  9958. if (node.inView() == true) {
  9959. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  9960. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  9961. this.openCluster(node);
  9962. }
  9963. }
  9964. }
  9965. }
  9966. },
  9967. /**
  9968. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  9969. * has to be opened based on the current zoom level.
  9970. *
  9971. * @private
  9972. */
  9973. _openClusters : function(recursive,force) {
  9974. for (var i = 0; i < this.nodeIndices.length; i++) {
  9975. var node = this.nodes[this.nodeIndices[i]];
  9976. this._expandClusterNode(node,recursive,force);
  9977. }
  9978. },
  9979. /**
  9980. * This function checks if a node has to be opened. This is done by checking the zoom level.
  9981. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  9982. * This recursive behaviour is optional and can be set by the recursive argument.
  9983. *
  9984. * @param {Node} parentNode | to check for cluster and expand
  9985. * @param {Boolean} recursive | enabled or disable recursive calling
  9986. * @param {Boolean} force | enabled or disable forcing
  9987. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  9988. * @private
  9989. */
  9990. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  9991. // first check if node is a cluster
  9992. if (parentNode.clusterSize > 1) {
  9993. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  9994. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  9995. openAll = true;
  9996. }
  9997. recursive = openAll ? true : recursive;
  9998. // if the last child has been added on a smaller scale than current scale decluster
  9999. if (parentNode.formationScale < this.scale || force == true) {
  10000. // we will check if any of the contained child nodes should be removed from the cluster
  10001. for (var containedNodeId in parentNode.containedNodes) {
  10002. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  10003. var childNode = parentNode.containedNodes[containedNodeId];
  10004. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  10005. // the largest cluster is the one that comes from outside
  10006. if (force == true) {
  10007. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  10008. || openAll) {
  10009. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  10010. }
  10011. }
  10012. else {
  10013. if (this._nodeInActiveArea(parentNode)) {
  10014. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  10015. }
  10016. }
  10017. }
  10018. }
  10019. }
  10020. }
  10021. },
  10022. /**
  10023. * ONLY CALLED FROM _expandClusterNode
  10024. *
  10025. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  10026. * the child node from the parent contained_node object and put it back into the global nodes object.
  10027. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  10028. *
  10029. * @param {Node} parentNode | the parent node
  10030. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  10031. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  10032. * With force and recursive both true, the entire cluster is unpacked
  10033. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  10034. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  10035. * @private
  10036. */
  10037. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  10038. var childNode = parentNode.containedNodes[containedNodeId];
  10039. // if child node has been added on smaller scale than current, kick out
  10040. if (childNode.formationScale < this.scale || force == true) {
  10041. // put the child node back in the global nodes object
  10042. this.nodes[containedNodeId] = childNode;
  10043. // release the contained edges from this childNode back into the global edges
  10044. this._releaseContainedEdges(parentNode,childNode);
  10045. // reconnect rerouted edges to the childNode
  10046. this._connectEdgeBackToChild(parentNode,childNode);
  10047. // validate all edges in dynamicEdges
  10048. this._validateEdges(parentNode);
  10049. // undo the changes from the clustering operation on the parent node
  10050. parentNode.mass -= this.constants.clustering.massTransferCoefficient * childNode.mass;
  10051. parentNode.fontSize -= this.constants.clustering.fontSizeMultiplier * childNode.clusterSize;
  10052. parentNode.clusterSize -= childNode.clusterSize;
  10053. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  10054. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  10055. childNode.x = parentNode.x + this.constants.edges.length * 0.3 * (0.5 - Math.random()) * parentNode.clusterSize;
  10056. childNode.y = parentNode.y + this.constants.edges.length * 0.3 * (0.5 - Math.random()) * parentNode.clusterSize;
  10057. // remove node from the list
  10058. delete parentNode.containedNodes[containedNodeId];
  10059. // check if there are other childs with this clusterSession in the parent.
  10060. var othersPresent = false;
  10061. for (var childNodeId in parentNode.containedNodes) {
  10062. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  10063. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  10064. othersPresent = true;
  10065. break;
  10066. }
  10067. }
  10068. }
  10069. // if there are no others, remove the cluster session from the list
  10070. if (othersPresent == false) {
  10071. parentNode.clusterSessions.pop();
  10072. }
  10073. // remove the clusterSession from the child node
  10074. childNode.clusterSession = 0;
  10075. // restart the simulation to reorganise all nodes
  10076. this.moving = true;
  10077. // recalculate the size of the node on the next time the node is rendered
  10078. parentNode.clearSizeCache();
  10079. }
  10080. // check if a further expansion step is possible if recursivity is enabled
  10081. if (recursive == true) {
  10082. this._expandClusterNode(childNode,recursive,force,openAll);
  10083. }
  10084. },
  10085. /**
  10086. * This function checks if any nodes at the end of their trees have edges below a threshold length
  10087. * This function is called only from updateClusters()
  10088. * forceLevelCollapse ignores the length of the edge and collapses one level
  10089. * This means that a node with only one edge will be clustered with its connected node
  10090. *
  10091. * @private
  10092. * @param {Boolean} force
  10093. */
  10094. _formClusters : function(force) {
  10095. if (force == false) {
  10096. this._formClustersByZoom();
  10097. }
  10098. else {
  10099. this._forceClustersByZoom();
  10100. }
  10101. },
  10102. /**
  10103. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  10104. *
  10105. * @private
  10106. */
  10107. _formClustersByZoom : function() {
  10108. var dx,dy,length,
  10109. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  10110. // check if any edges are shorter than minLength and start the clustering
  10111. // the clustering favours the node with the larger mass
  10112. for (var edgeId in this.edges) {
  10113. if (this.edges.hasOwnProperty(edgeId)) {
  10114. var edge = this.edges[edgeId];
  10115. if (edge.connected) {
  10116. if (edge.toId != edge.fromId) {
  10117. dx = (edge.to.x - edge.from.x);
  10118. dy = (edge.to.y - edge.from.y);
  10119. length = Math.sqrt(dx * dx + dy * dy);
  10120. if (length < minLength) {
  10121. // first check which node is larger
  10122. var parentNode = edge.from;
  10123. var childNode = edge.to;
  10124. if (edge.to.mass > edge.from.mass) {
  10125. parentNode = edge.to;
  10126. childNode = edge.from;
  10127. }
  10128. if (childNode.dynamicEdgesLength == 1) {
  10129. this._addToCluster(parentNode,childNode,false);
  10130. }
  10131. else if (parentNode.dynamicEdgesLength == 1) {
  10132. this._addToCluster(childNode,parentNode,false);
  10133. }
  10134. }
  10135. }
  10136. }
  10137. }
  10138. }
  10139. },
  10140. /**
  10141. * This function forces the graph to cluster all nodes with only one connecting edge to their
  10142. * connected node.
  10143. *
  10144. * @private
  10145. */
  10146. _forceClustersByZoom : function() {
  10147. for (var nodeId in this.nodes) {
  10148. // another node could have absorbed this child.
  10149. if (this.nodes.hasOwnProperty(nodeId)) {
  10150. var childNode = this.nodes[nodeId];
  10151. // the edges can be swallowed by another decrease
  10152. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  10153. var edge = childNode.dynamicEdges[0];
  10154. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  10155. // group to the largest node
  10156. if (childNode.id != parentNode.id) {
  10157. if (parentNode.mass > childNode.mass) {
  10158. this._addToCluster(parentNode,childNode,true);
  10159. }
  10160. else {
  10161. this._addToCluster(childNode,parentNode,true);
  10162. }
  10163. }
  10164. }
  10165. }
  10166. }
  10167. },
  10168. /**
  10169. * This function forms clusters from hubs, it loops over all nodes
  10170. *
  10171. * @param {Boolean} force | Disregard zoom level
  10172. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  10173. * @private
  10174. */
  10175. _formClustersByHub : function(force, onlyEqual) {
  10176. // we loop over all nodes in the list
  10177. for (var nodeId in this.nodes) {
  10178. // we check if it is still available since it can be used by the clustering in this loop
  10179. if (this.nodes.hasOwnProperty(nodeId)) {
  10180. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  10181. }
  10182. }
  10183. },
  10184. /**
  10185. * This function forms a cluster from a specific preselected hub node
  10186. *
  10187. * @param {Node} hubNode | the node we will cluster as a hub
  10188. * @param {Boolean} force | Disregard zoom level
  10189. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  10190. * @param {Number} [absorptionSizeOffset] |
  10191. * @private
  10192. */
  10193. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  10194. if (absorptionSizeOffset === undefined) {
  10195. absorptionSizeOffset = 0;
  10196. }
  10197. // we decide if the node is a hub
  10198. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  10199. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  10200. // initialize variables
  10201. var dx,dy,length;
  10202. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  10203. var allowCluster = false;
  10204. // we create a list of edges because the dynamicEdges change over the course of this loop
  10205. var edgesIdarray = [];
  10206. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  10207. for (var j = 0; j < amountOfInitialEdges; j++) {
  10208. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  10209. }
  10210. // if the hub clustering is not forces, we check if one of the edges connected
  10211. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  10212. if (force == false) {
  10213. allowCluster = false;
  10214. for (j = 0; j < amountOfInitialEdges; j++) {
  10215. var edge = this.edges[edgesIdarray[j]];
  10216. if (edge !== undefined) {
  10217. if (edge.connected) {
  10218. if (edge.toId != edge.fromId) {
  10219. dx = (edge.to.x - edge.from.x);
  10220. dy = (edge.to.y - edge.from.y);
  10221. length = Math.sqrt(dx * dx + dy * dy);
  10222. if (length < minLength) {
  10223. allowCluster = true;
  10224. break;
  10225. }
  10226. }
  10227. }
  10228. }
  10229. }
  10230. }
  10231. // start the clustering if allowed
  10232. if ((!force && allowCluster) || force) {
  10233. // we loop over all edges INITIALLY connected to this hub
  10234. for (j = 0; j < amountOfInitialEdges; j++) {
  10235. edge = this.edges[edgesIdarray[j]];
  10236. // the edge can be clustered by this function in a previous loop
  10237. if (edge !== undefined) {
  10238. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  10239. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  10240. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  10241. (childNode.id != hubNode.id)) {
  10242. this._addToCluster(hubNode,childNode,force);
  10243. }
  10244. }
  10245. }
  10246. }
  10247. }
  10248. },
  10249. /**
  10250. * This function adds the child node to the parent node, creating a cluster if it is not already.
  10251. *
  10252. * @param {Node} parentNode | this is the node that will house the child node
  10253. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  10254. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  10255. * @private
  10256. */
  10257. _addToCluster : function(parentNode, childNode, force) {
  10258. // join child node in the parent node
  10259. parentNode.containedNodes[childNode.id] = childNode;
  10260. // manage all the edges connected to the child and parent nodes
  10261. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  10262. var edge = childNode.dynamicEdges[i];
  10263. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  10264. this._addToContainedEdges(parentNode,childNode,edge);
  10265. }
  10266. else {
  10267. this._connectEdgeToCluster(parentNode,childNode,edge);
  10268. }
  10269. }
  10270. // a contained node has no dynamic edges.
  10271. childNode.dynamicEdges = [];
  10272. // remove circular edges from clusters
  10273. this._containCircularEdgesFromNode(parentNode,childNode);
  10274. // remove the childNode from the global nodes object
  10275. delete this.nodes[childNode.id];
  10276. // update the properties of the child and parent
  10277. var massBefore = parentNode.mass;
  10278. childNode.clusterSession = this.clusterSession;
  10279. parentNode.mass += this.constants.clustering.massTransferCoefficient * childNode.mass;
  10280. parentNode.clusterSize += childNode.clusterSize;
  10281. parentNode.fontSize += this.constants.clustering.fontSizeMultiplier * childNode.clusterSize;
  10282. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  10283. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  10284. parentNode.clusterSessions.push(this.clusterSession);
  10285. }
  10286. // forced clusters only open from screen size and double tap
  10287. if (force == true) {
  10288. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  10289. parentNode.formationScale = 0;
  10290. }
  10291. else {
  10292. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  10293. }
  10294. // recalculate the size of the node on the next time the node is rendered
  10295. parentNode.clearSizeCache();
  10296. // set the pop-out scale for the childnode
  10297. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  10298. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  10299. childNode.clearVelocity();
  10300. // the mass has altered, preservation of energy dictates the velocity to be updated
  10301. parentNode.updateVelocity(massBefore);
  10302. // restart the simulation to reorganise all nodes
  10303. this.moving = true;
  10304. },
  10305. /**
  10306. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  10307. * This is a seperate function to allow for level-wise collapsing of the node tree.
  10308. * It has to be called if a level is collapsed. It is called by _formClusters().
  10309. * @private
  10310. */
  10311. _updateDynamicEdges : function() {
  10312. for (var i = 0; i < this.nodeIndices.length; i++) {
  10313. var node = this.nodes[this.nodeIndices[i]];
  10314. node.dynamicEdgesLength = node.dynamicEdges.length;
  10315. // this corrects for multiple edges pointing at the same other node
  10316. var correction = 0;
  10317. if (node.dynamicEdgesLength > 1) {
  10318. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  10319. var edgeToId = node.dynamicEdges[j].toId;
  10320. var edgeFromId = node.dynamicEdges[j].fromId;
  10321. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  10322. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  10323. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  10324. correction += 1;
  10325. }
  10326. }
  10327. }
  10328. }
  10329. node.dynamicEdgesLength -= correction;
  10330. }
  10331. },
  10332. /**
  10333. * This adds an edge from the childNode to the contained edges of the parent node
  10334. *
  10335. * @param parentNode | Node object
  10336. * @param childNode | Node object
  10337. * @param edge | Edge object
  10338. * @private
  10339. */
  10340. _addToContainedEdges : function(parentNode, childNode, edge) {
  10341. // create an array object if it does not yet exist for this childNode
  10342. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  10343. parentNode.containedEdges[childNode.id] = []
  10344. }
  10345. // add this edge to the list
  10346. parentNode.containedEdges[childNode.id].push(edge);
  10347. // remove the edge from the global edges object
  10348. delete this.edges[edge.id];
  10349. // remove the edge from the parent object
  10350. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  10351. if (parentNode.dynamicEdges[i].id == edge.id) {
  10352. parentNode.dynamicEdges.splice(i,1);
  10353. break;
  10354. }
  10355. }
  10356. },
  10357. /**
  10358. * This function connects an edge that was connected to a child node to the parent node.
  10359. * It keeps track of which nodes it has been connected to with the originalId array.
  10360. *
  10361. * @param {Node} parentNode | Node object
  10362. * @param {Node} childNode | Node object
  10363. * @param {Edge} edge | Edge object
  10364. * @private
  10365. */
  10366. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  10367. // handle circular edges
  10368. if (edge.toId == edge.fromId) {
  10369. this._addToContainedEdges(parentNode, childNode, edge);
  10370. }
  10371. else {
  10372. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  10373. edge.originalToId.push(childNode.id);
  10374. edge.to = parentNode;
  10375. edge.toId = parentNode.id;
  10376. }
  10377. else { // edge connected to other node with the "from" side
  10378. edge.originalFromId.push(childNode.id);
  10379. edge.from = parentNode;
  10380. edge.fromId = parentNode.id;
  10381. }
  10382. this._addToReroutedEdges(parentNode,childNode,edge);
  10383. }
  10384. },
  10385. _containCircularEdgesFromNode : function(parentNode, childNode) {
  10386. // manage all the edges connected to the child and parent nodes
  10387. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  10388. var edge = parentNode.dynamicEdges[i];
  10389. // handle circular edges
  10390. if (edge.toId == edge.fromId) {
  10391. this._addToContainedEdges(parentNode, childNode, edge);
  10392. }
  10393. }
  10394. },
  10395. /**
  10396. * This adds an edge from the childNode to the rerouted edges of the parent node
  10397. *
  10398. * @param parentNode | Node object
  10399. * @param childNode | Node object
  10400. * @param edge | Edge object
  10401. * @private
  10402. */
  10403. _addToReroutedEdges : function(parentNode, childNode, edge) {
  10404. // create an array object if it does not yet exist for this childNode
  10405. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  10406. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  10407. parentNode.reroutedEdges[childNode.id] = [];
  10408. }
  10409. parentNode.reroutedEdges[childNode.id].push(edge);
  10410. // this edge becomes part of the dynamicEdges of the cluster node
  10411. parentNode.dynamicEdges.push(edge);
  10412. },
  10413. /**
  10414. * This function connects an edge that was connected to a cluster node back to the child node.
  10415. *
  10416. * @param parentNode | Node object
  10417. * @param childNode | Node object
  10418. * @private
  10419. */
  10420. _connectEdgeBackToChild : function(parentNode, childNode) {
  10421. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  10422. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  10423. var edge = parentNode.reroutedEdges[childNode.id][i];
  10424. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  10425. edge.originalFromId.pop();
  10426. edge.fromId = childNode.id;
  10427. edge.from = childNode;
  10428. }
  10429. else {
  10430. edge.originalToId.pop();
  10431. edge.toId = childNode.id;
  10432. edge.to = childNode;
  10433. }
  10434. // append this edge to the list of edges connecting to the childnode
  10435. childNode.dynamicEdges.push(edge);
  10436. // remove the edge from the parent object
  10437. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  10438. if (parentNode.dynamicEdges[j].id == edge.id) {
  10439. parentNode.dynamicEdges.splice(j,1);
  10440. break;
  10441. }
  10442. }
  10443. }
  10444. // remove the entry from the rerouted edges
  10445. delete parentNode.reroutedEdges[childNode.id];
  10446. }
  10447. },
  10448. /**
  10449. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  10450. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  10451. * parentNode
  10452. *
  10453. * @param parentNode | Node object
  10454. * @private
  10455. */
  10456. _validateEdges : function(parentNode) {
  10457. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  10458. var edge = parentNode.dynamicEdges[i];
  10459. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  10460. parentNode.dynamicEdges.splice(i,1);
  10461. }
  10462. }
  10463. },
  10464. /**
  10465. * This function released the contained edges back into the global domain and puts them back into the
  10466. * dynamic edges of both parent and child.
  10467. *
  10468. * @param {Node} parentNode |
  10469. * @param {Node} childNode |
  10470. * @private
  10471. */
  10472. _releaseContainedEdges : function(parentNode, childNode) {
  10473. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  10474. var edge = parentNode.containedEdges[childNode.id][i];
  10475. // put the edge back in the global edges object
  10476. this.edges[edge.id] = edge;
  10477. // put the edge back in the dynamic edges of the child and parent
  10478. childNode.dynamicEdges.push(edge);
  10479. parentNode.dynamicEdges.push(edge);
  10480. }
  10481. // remove the entry from the contained edges
  10482. delete parentNode.containedEdges[childNode.id];
  10483. },
  10484. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  10485. /**
  10486. * This updates the node labels for all nodes (for debugging purposes)
  10487. */
  10488. updateLabels : function() {
  10489. var nodeId;
  10490. // update node labels
  10491. for (nodeId in this.nodes) {
  10492. if (this.nodes.hasOwnProperty(nodeId)) {
  10493. var node = this.nodes[nodeId];
  10494. if (node.clusterSize > 1) {
  10495. node.label = "[".concat(String(node.clusterSize),"]");
  10496. }
  10497. }
  10498. }
  10499. // update node labels
  10500. for (nodeId in this.nodes) {
  10501. if (this.nodes.hasOwnProperty(nodeId)) {
  10502. node = this.nodes[nodeId];
  10503. if (node.clusterSize == 1) {
  10504. if (node.originalLabel !== undefined) {
  10505. node.label = node.originalLabel;
  10506. }
  10507. else {
  10508. node.label = String(node.id);
  10509. }
  10510. }
  10511. }
  10512. }
  10513. /* Debug Override */
  10514. // for (nodeId in this.nodes) {
  10515. // if (this.nodes.hasOwnProperty(nodeId)) {
  10516. // node = this.nodes[nodeId];
  10517. // node.label = String(Math.round(node.width)).concat(":",Math.round(node.width*this.scale));
  10518. // }
  10519. // }
  10520. },
  10521. /**
  10522. * This function determines if the cluster we want to decluster is in the active area
  10523. * this means around the zoom center
  10524. *
  10525. * @param {Node} node
  10526. * @returns {boolean}
  10527. * @private
  10528. */
  10529. _nodeInActiveArea : function(node) {
  10530. return (
  10531. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  10532. &&
  10533. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  10534. )
  10535. },
  10536. /**
  10537. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  10538. * It puts large clusters away from the center and randomizes the order.
  10539. *
  10540. */
  10541. repositionNodes : function() {
  10542. for (var i = 0; i < this.nodeIndices.length; i++) {
  10543. var node = this.nodes[this.nodeIndices[i]];
  10544. if (!node.isFixed()) {
  10545. var radius = this.constants.edges.length * (1 + 0.6*node.clusterSize);
  10546. var angle = 2 * Math.PI * Math.random();
  10547. node.x = radius * Math.cos(angle);
  10548. node.y = radius * Math.sin(angle);
  10549. }
  10550. }
  10551. },
  10552. /**
  10553. * We determine how many connections denote an important hub.
  10554. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  10555. *
  10556. * @private
  10557. */
  10558. _getHubSize : function() {
  10559. var average = 0;
  10560. var averageSquared = 0;
  10561. var hubCounter = 0;
  10562. var largestHub = 0;
  10563. for (var i = 0; i < this.nodeIndices.length; i++) {
  10564. var node = this.nodes[this.nodeIndices[i]];
  10565. if (node.dynamicEdgesLength > largestHub) {
  10566. largestHub = node.dynamicEdgesLength;
  10567. }
  10568. average += node.dynamicEdgesLength;
  10569. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  10570. hubCounter += 1;
  10571. }
  10572. average = average / hubCounter;
  10573. averageSquared = averageSquared / hubCounter;
  10574. var variance = averageSquared - Math.pow(average,2);
  10575. var standardDeviation = Math.sqrt(variance);
  10576. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  10577. // always have at least one to cluster
  10578. if (this.hubThreshold > largestHub) {
  10579. this.hubThreshold = largestHub;
  10580. }
  10581. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  10582. // console.log("hubThreshold:",this.hubThreshold);
  10583. },
  10584. /**
  10585. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  10586. * with this amount we can cluster specifically on these chains.
  10587. *
  10588. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  10589. * @private
  10590. */
  10591. _reduceAmountOfChains : function(fraction) {
  10592. this.hubThreshold = 2;
  10593. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  10594. for (var nodeId in this.nodes) {
  10595. if (this.nodes.hasOwnProperty(nodeId)) {
  10596. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  10597. if (reduceAmount > 0) {
  10598. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  10599. reduceAmount -= 1;
  10600. }
  10601. }
  10602. }
  10603. }
  10604. },
  10605. /**
  10606. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  10607. * with this amount we can cluster specifically on these chains.
  10608. *
  10609. * @private
  10610. */
  10611. _getChainFraction : function() {
  10612. var chains = 0;
  10613. var total = 0;
  10614. for (var nodeId in this.nodes) {
  10615. if (this.nodes.hasOwnProperty(nodeId)) {
  10616. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  10617. chains += 1;
  10618. }
  10619. total += 1;
  10620. }
  10621. }
  10622. return chains/total;
  10623. }
  10624. };
  10625. var SelectionMixin = {
  10626. /**
  10627. * This function can be called from the _doInAllSectors function
  10628. *
  10629. * @param object
  10630. * @param overlappingNodes
  10631. * @private
  10632. */
  10633. _getNodesOverlappingWith : function(object, overlappingNodes) {
  10634. var nodes = this.nodes;
  10635. for (var nodeId in nodes) {
  10636. if (nodes.hasOwnProperty(nodeId)) {
  10637. if (nodes[nodeId].isOverlappingWith(object)) {
  10638. overlappingNodes.push(nodeId);
  10639. }
  10640. }
  10641. }
  10642. },
  10643. /**
  10644. * retrieve all nodes overlapping with given object
  10645. * @param {Object} object An object with parameters left, top, right, bottom
  10646. * @return {Number[]} An array with id's of the overlapping nodes
  10647. * @private
  10648. */
  10649. _getAllNodesOverlappingWith : function (object) {
  10650. var overlappingNodes = [];
  10651. this._doInAllSectors("_getNodesOverlappingWith",object,overlappingNodes);
  10652. return overlappingNodes;
  10653. },
  10654. /**
  10655. * retrieve all nodes in the UI overlapping with given object
  10656. * @param {Object} object An object with parameters left, top, right, bottom
  10657. * @return {Number[]} An array with id's of the overlapping nodes
  10658. * @private
  10659. */
  10660. _getAllUINodesOverlappingWith : function (object) {
  10661. var overlappingNodes = [];
  10662. this._doInUISector("_getNodesOverlappingWith",object,overlappingNodes);
  10663. return overlappingNodes;
  10664. },
  10665. /**
  10666. * Return a position object in canvasspace from a single point in screenspace
  10667. *
  10668. * @param pointer
  10669. * @returns {{left: number, top: number, right: number, bottom: number}}
  10670. * @private
  10671. */
  10672. _pointerToPositionObject : function(pointer) {
  10673. var x = this._canvasToX(pointer.x);
  10674. var y = this._canvasToY(pointer.y);
  10675. return {left: x,
  10676. top: y,
  10677. right: x,
  10678. bottom: y};
  10679. },
  10680. /**
  10681. * Return a position object in canvasspace from a single point in screenspace
  10682. *
  10683. * @param pointer
  10684. * @returns {{left: number, top: number, right: number, bottom: number}}
  10685. * @private
  10686. */
  10687. _pointerToScreenPositionObject : function(pointer) {
  10688. var x = pointer.x;
  10689. var y = pointer.y;
  10690. return {left: x,
  10691. top: y,
  10692. right: x,
  10693. bottom: y};
  10694. },
  10695. /**
  10696. * Get the top UI node at the a specific point (like a click)
  10697. *
  10698. * @param {{x: Number, y: Number}} pointer
  10699. * @return {Node | null} node
  10700. * @private
  10701. */
  10702. _getUINodeAt : function (pointer) {
  10703. var screenPositionObject = this._pointerToScreenPositionObject(pointer);
  10704. var overlappingNodes = this._getAllUINodesOverlappingWith(screenPositionObject);
  10705. if (this.UIvisible && overlappingNodes.length > 0) {
  10706. return this.sectors["UI"]["nodes"][overlappingNodes[overlappingNodes.length - 1]];
  10707. }
  10708. else {
  10709. return null;
  10710. }
  10711. },
  10712. /**
  10713. * Get the top node at the a specific point (like a click)
  10714. *
  10715. * @param {{x: Number, y: Number}} pointer
  10716. * @return {Node | null} node
  10717. * @private
  10718. */
  10719. _getNodeAt : function (pointer) {
  10720. // we first check if this is an UI element
  10721. var positionObject = this._pointerToPositionObject(pointer);
  10722. overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  10723. // if there are overlapping nodes, select the last one, this is the
  10724. // one which is drawn on top of the others
  10725. if (overlappingNodes.length > 0) {
  10726. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  10727. }
  10728. else {
  10729. return null;
  10730. }
  10731. },
  10732. _getEdgeAt : function(pointer) {
  10733. },
  10734. _addToSelection : function(obj) {
  10735. this.selection.push(obj.id);
  10736. this.selectionObj[obj.id] = obj;
  10737. },
  10738. _removeFromSelection : function(obj) {
  10739. for (var i = 0; i < this.selection.length; i++) {
  10740. if (obj.id == this.selection[i]) {
  10741. this.selection.splice(i,1);
  10742. break;
  10743. }
  10744. }
  10745. delete this.selectionObj[obj.id];
  10746. },
  10747. _unselectAll : function() {
  10748. this.selection = [];
  10749. for (var objId in this.selectionObj) {
  10750. if (this.selectionObj.hasOwnProperty(objId)) {
  10751. this.selectionObj[objId].unselect();
  10752. }
  10753. }
  10754. this.selectionObj = {};
  10755. },
  10756. _selectionIsEmpty : function() {
  10757. if (this.selection.length == 0) {
  10758. return true;
  10759. }
  10760. else {
  10761. return false;
  10762. }
  10763. },
  10764. /**
  10765. * This is called when someone clicks on a node. either select or deselect it.
  10766. * If there is an existing selection and we don't want to append to it, clear the existing selection
  10767. *
  10768. * @param {Node} node
  10769. * @param {Boolean} append
  10770. * @private
  10771. */
  10772. _selectNode : function(node, append) {
  10773. // TODO: triggers?
  10774. if (this._selectionIsEmpty() == false && append == false) {
  10775. this._unselectAll();
  10776. }
  10777. if (node.selected == false) {
  10778. node.select();
  10779. this._addToSelection(node);
  10780. }
  10781. else {
  10782. node.unselect();
  10783. this._removeFromSelection(node);
  10784. }
  10785. },
  10786. /**
  10787. * handles the selection part of the touch, only for UI elements;
  10788. *
  10789. * @param {Object} pointer
  10790. * @private
  10791. */
  10792. _handleTouch : function(pointer) {
  10793. var node = this._getUINodeAt(pointer);
  10794. if (node != null) {
  10795. if (this[node.triggerFunction] !== undefined) {
  10796. this[node.triggerFunction]();
  10797. }
  10798. }
  10799. },
  10800. /**
  10801. * handles the selection part of the tap;
  10802. *
  10803. * @param {Object} pointer
  10804. * @private
  10805. */
  10806. _handleTap : function(pointer) {
  10807. var node = this._getNodeAt(pointer);
  10808. if (node != null) {
  10809. this._selectNode(node,false);
  10810. }
  10811. else {
  10812. this._unselectAll();
  10813. }
  10814. this._redraw();
  10815. },
  10816. /**
  10817. * handles the selection part of the double tap and opens a cluster if needed
  10818. *
  10819. * @param {Object} pointer
  10820. * @private
  10821. */
  10822. _handleDoubleTap : function(pointer) {
  10823. var node = this._getNodeAt(pointer);
  10824. if (node != null && node !== undefined) {
  10825. // we reset the areaCenter here so the opening of the node will occur
  10826. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  10827. "y" : this._canvasToY(pointer.y)};
  10828. this.openCluster(node);
  10829. }
  10830. },
  10831. _handleOnHold : function(pointer) {
  10832. var node = this._getNodeAt(pointer);
  10833. if (node != null) {
  10834. this._selectNode(node,true);
  10835. }
  10836. this._redraw();
  10837. },
  10838. _handleOnRelease : function() {
  10839. this.xIncrement = 0;
  10840. this.yIncrement = 0;
  10841. this.zoomIncrement = 0;
  10842. this._unHighlightAll();
  10843. },
  10844. /**
  10845. * Unselect selected nodes. If no selection array is provided, all nodes
  10846. * are unselected
  10847. * @param {Object[]} selection Array with selection objects, each selection
  10848. * object has a parameter row. Optional
  10849. * @param {Boolean} triggerSelect If true (default), the select event
  10850. * is triggered when nodes are unselected
  10851. * @return {Boolean} changed True if the selection is changed
  10852. * @private
  10853. */
  10854. /* _unselectNodes : function(selection, triggerSelect) {
  10855. var changed = false;
  10856. var i, iMax, id;
  10857. if (selection) {
  10858. // remove provided selections
  10859. for (i = 0, iMax = selection.length; i < iMax; i++) {
  10860. id = selection[i];
  10861. if (this.nodes.hasOwnProperty(id)) {
  10862. this.nodes[id].unselect();
  10863. }
  10864. var j = 0;
  10865. while (j < this.selection.length) {
  10866. if (this.selection[j] == id) {
  10867. this.selection.splice(j, 1);
  10868. changed = true;
  10869. }
  10870. else {
  10871. j++;
  10872. }
  10873. }
  10874. }
  10875. }
  10876. else if (this.selection && this.selection.length) {
  10877. // remove all selections
  10878. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  10879. id = this.selection[i];
  10880. if (this.nodes.hasOwnProperty(id)) {
  10881. this.nodes[id].unselect();
  10882. }
  10883. changed = true;
  10884. }
  10885. this.selection = [];
  10886. }
  10887. if (changed && (triggerSelect == true || triggerSelect == undefined)) {
  10888. // fire the select event
  10889. this._trigger('select');
  10890. }
  10891. return changed;
  10892. },
  10893. */
  10894. /**
  10895. * select all nodes on given location x, y
  10896. * @param {Array} selection an array with node ids
  10897. * @param {boolean} append If true, the new selection will be appended to the
  10898. * current selection (except for duplicate entries)
  10899. * @return {Boolean} changed True if the selection is changed
  10900. * @private
  10901. */
  10902. /* _selectNodes : function(selection, append) {
  10903. var changed = false;
  10904. var i, iMax;
  10905. // TODO: the selectNodes method is a little messy, rework this
  10906. // check if the current selection equals the desired selection
  10907. var selectionAlreadyThere = true;
  10908. if (selection.length != this.selection.length) {
  10909. selectionAlreadyThere = false;
  10910. }
  10911. else {
  10912. for (i = 0, iMax = Math.min(selection.length, this.selection.length); i < iMax; i++) {
  10913. if (selection[i] != this.selection[i]) {
  10914. selectionAlreadyThere = false;
  10915. break;
  10916. }
  10917. }
  10918. }
  10919. if (selectionAlreadyThere) {
  10920. return changed;
  10921. }
  10922. if (append == undefined || append == false) {
  10923. // first deselect any selected node
  10924. var triggerSelect = false;
  10925. changed = this._unselectNodes(undefined, triggerSelect);
  10926. }
  10927. for (i = 0, iMax = selection.length; i < iMax; i++) {
  10928. // add each of the new selections, but only when they are not duplicate
  10929. var id = selection[i];
  10930. var isDuplicate = (this.selection.indexOf(id) != -1);
  10931. if (!isDuplicate) {
  10932. this.nodes[id].select();
  10933. this.selection.push(id);
  10934. changed = true;
  10935. }
  10936. }
  10937. if (changed) {
  10938. // fire the select event
  10939. this._trigger('select');
  10940. }
  10941. return changed;
  10942. },
  10943. */
  10944. /**
  10945. * retrieve the currently selected nodes
  10946. * @return {Number[] | String[]} selection An array with the ids of the
  10947. * selected nodes.
  10948. */
  10949. getSelection : function() {
  10950. return this.selection.concat([]);
  10951. },
  10952. /**
  10953. * select zero or more nodes
  10954. * @param {Number[] | String[]} selection An array with the ids of the
  10955. * selected nodes.
  10956. */
  10957. setSelection : function(selection) {
  10958. var i, iMax, id;
  10959. if (!selection || (selection.length == undefined))
  10960. throw 'Selection must be an array with ids';
  10961. // first unselect any selected node
  10962. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  10963. id = this.selection[i];
  10964. this.nodes[id].unselect();
  10965. }
  10966. this.selection = [];
  10967. for (i = 0, iMax = selection.length; i < iMax; i++) {
  10968. id = selection[i];
  10969. var node = this.nodes[id];
  10970. if (!node) {
  10971. throw new RangeError('Node with id "' + id + '" not found');
  10972. }
  10973. node.select();
  10974. this.selection.push(id);
  10975. }
  10976. this.redraw();
  10977. },
  10978. /**
  10979. * Validate the selection: remove ids of nodes which no longer exist
  10980. * @private
  10981. */
  10982. _updateSelection : function () {
  10983. var i = 0;
  10984. while (i < this.selection.length) {
  10985. var nodeId = this.selection[i];
  10986. if (!this.nodes.hasOwnProperty(nodeId)) {
  10987. this.selection.splice(i, 1);
  10988. delete this.selectionObj[nodeId];
  10989. }
  10990. else {
  10991. i++;
  10992. }
  10993. }
  10994. }
  10995. };
  10996. /**
  10997. * Created by Alex on 1/22/14.
  10998. */
  10999. var UIMixin = {
  11000. _relocateUI : function() {
  11001. if (this.sectors !== undefined) {
  11002. var xOffset = this.UIclientWidth - this.frame.canvas.clientWidth;
  11003. var yOffset = this.UIclientHeight - this.frame.canvas.clientHeight;
  11004. this.UIclientWidth = this.frame.canvas.clientWidth;
  11005. this.UIclientHeight = this.frame.canvas.clientHeight;
  11006. var node = null;
  11007. for (var nodeId in this.sectors["UI"]["nodes"]) {
  11008. if (this.sectors["UI"]["nodes"].hasOwnProperty(nodeId)) {
  11009. node = this.sectors["UI"]["nodes"][nodeId];
  11010. if (!node.horizontalAlignLeft) {
  11011. node.x -= xOffset;
  11012. }
  11013. if (!node.verticalAlignTop) {
  11014. node.y -= yOffset;
  11015. }
  11016. }
  11017. }
  11018. }
  11019. },
  11020. _loadUIElements : function() {
  11021. var DIR = 'img/UI/';
  11022. this.UIclientWidth = this.frame.canvas.clientWidth;
  11023. this.UIclientHeight = this.frame.canvas.clientHeight;
  11024. if (this.UIclientWidth === undefined) {
  11025. this.UIclientWidth = 0;
  11026. this.UIclientHeight = 0;
  11027. }
  11028. var UINodes = [
  11029. {id: 'UI_up', shape: 'image', image: DIR + 'uparrow.png', triggerFunction: "_moveUp",
  11030. verticalAlignTop: false, x: 52, y: this.UIclientHeight - 52},
  11031. {id: 'UI_down', shape: 'image', image: DIR + 'downarrow.png', triggerFunction: "_moveDown",
  11032. verticalAlignTop: false, x: 52, y: this.UIclientHeight - 20},
  11033. {id: 'UI_left', shape: 'image', image: DIR + 'leftarrow.png', triggerFunction: "_moveLeft",
  11034. verticalAlignTop: false, x: 20, y: this.UIclientHeight - 20},
  11035. {id: 'UI_right', shape: 'image', image: DIR + 'rightarrow.png',triggerFunction: "_moveRight",
  11036. verticalAlignTop: false, x: 84, y: this.UIclientHeight - 20},
  11037. {id: 'UI_plus', shape: 'image', image: DIR + 'plus.png', triggerFunction: "_zoomIn",
  11038. verticalAlignTop: false, x: 140, y: this.UIclientHeight - 20},
  11039. {id: 'UI_min', shape: 'image', image: DIR + 'minus.png', triggerFunction: "_zoomOut",
  11040. verticalAlignTop: false, x: 172, y: this.UIclientHeight - 20}
  11041. ];
  11042. var nodeObj = null;
  11043. for (var i = 0; i < UINodes.length; i++) {
  11044. nodeObj = this.sectors["UI"]['nodes'];
  11045. nodeObj[UINodes[i]['id']] = new Node(UINodes[i], this.images, this.groups, this.constants);
  11046. }
  11047. },
  11048. _highlightUIElement : function(elementId) {
  11049. if (this.sectors["UI"]["nodes"].hasOwnProperty(elementId)) {
  11050. this.sectors["UI"]["nodes"][elementId].clusterSize = 2;
  11051. }
  11052. },
  11053. _unHighlightUIElement : function(elementId) {
  11054. if (this.sectors["UI"]["nodes"].hasOwnProperty(elementId)) {
  11055. this.sectors["UI"]["nodes"][elementId].clusterSize = 1;
  11056. }
  11057. },
  11058. _toggleUI : function() {
  11059. this.UIvisible = !this.UIvisible;
  11060. this._redraw();
  11061. },
  11062. _unHighlightAll : function() {
  11063. for (var nodeId in this.sectors['UI']['nodes']) {
  11064. this._unHighlightUIElement(nodeId);
  11065. }
  11066. },
  11067. _moveUp : function() {
  11068. this._highlightUIElement("UI_up");
  11069. this.yIncrement = this.constants.UI.yMovementSpeed;
  11070. this.start(); // if there is no node movement, the calculation wont be done
  11071. },
  11072. _moveDown : function() {
  11073. this._highlightUIElement("UI_down");
  11074. this.yIncrement = -this.constants.UI.yMovementSpeed;
  11075. this.start(); // if there is no node movement, the calculation wont be done
  11076. },
  11077. _moveLeft : function() {
  11078. this._highlightUIElement("UI_left");
  11079. this.xIncrement = this.constants.UI.xMovementSpeed;
  11080. this.start(); // if there is no node movement, the calculation wont be done
  11081. },
  11082. _moveRight : function() {
  11083. this._highlightUIElement("UI_right");
  11084. this.xIncrement = -this.constants.UI.xMovementSpeed;
  11085. this.start(); // if there is no node movement, the calculation wont be done
  11086. },
  11087. _zoomIn : function() {
  11088. this._highlightUIElement("UI_plus");
  11089. this.zoomIncrement = this.constants.UI.zoomMovementSpeed;
  11090. this.start(); // if there is no node movement, the calculation wont be done
  11091. },
  11092. _zoomOut : function() {
  11093. this._highlightUIElement("UI_min");
  11094. this.zoomIncrement = -this.constants.UI.zoomMovementSpeed;
  11095. this.start(); // if there is no node movement, the calculation wont be done
  11096. },
  11097. _stopZoom : function() {
  11098. if (this.zoomIncrement > 0) { // plus (zoomin)
  11099. this._unHighlightUIElement("UI_plus");
  11100. }
  11101. else if (this.zoomIncrement < 0) { // min (zoomout)
  11102. this._unHighlightUIElement("UI_min");
  11103. }
  11104. this.zoomIncrement = 0;
  11105. },
  11106. _yStopMoving : function() {
  11107. if (this.yIncrement > 0) { // up
  11108. this._unHighlightUIElement("UI_up");
  11109. }
  11110. else if (this.yIncrement < 0) { // down
  11111. this._unHighlightUIElement("UI_down");
  11112. }
  11113. this.yIncrement = 0;
  11114. },
  11115. _xStopMoving : function() {
  11116. if (this.xIncrement > 0) { // left
  11117. this._unHighlightUIElement("UI_left");
  11118. }
  11119. else if (this.xIncrement < 0) { // right
  11120. this._unHighlightUIElement("UI_right");
  11121. }
  11122. this.xIncrement = 0;
  11123. }
  11124. };
  11125. /**
  11126. * @constructor Graph
  11127. * Create a graph visualization, displaying nodes and edges.
  11128. *
  11129. * @param {Element} container The DOM element in which the Graph will
  11130. * be created. Normally a div element.
  11131. * @param {Object} data An object containing parameters
  11132. * {Array} nodes
  11133. * {Array} edges
  11134. * @param {Object} options Options
  11135. */
  11136. function Graph (container, data, options) {
  11137. // create variables and set default values
  11138. this.containerElement = container;
  11139. this.width = '100%';
  11140. this.height = '100%';
  11141. // to give everything a nice fluidity, we seperate the rendering and calculating of the forces
  11142. this.calculationRefreshRate = 40; // milliseconds
  11143. this.calculationStartTime = 0;
  11144. this.renderRefreshRate = 10; // milliseconds
  11145. this.stabilize = true; // stabilize before displaying the graph
  11146. this.selectable = true;
  11147. // set constant values
  11148. this.constants = {
  11149. nodes: {
  11150. radiusMin: 5,
  11151. radiusMax: 20,
  11152. radius: 5,
  11153. distance: 100, // px
  11154. shape: 'ellipse',
  11155. image: undefined,
  11156. widthMin: 16, // px
  11157. widthMax: 64, // px
  11158. fontColor: 'black',
  11159. fontSize: 14, // px
  11160. //fontFace: verdana,
  11161. fontFace: 'arial',
  11162. color: {
  11163. border: '#2B7CE9',
  11164. background: '#97C2FC',
  11165. highlight: {
  11166. border: '#2B7CE9',
  11167. background: '#D2E5FF'
  11168. }
  11169. },
  11170. borderColor: '#2B7CE9',
  11171. backgroundColor: '#97C2FC',
  11172. highlightColor: '#D2E5FF',
  11173. group: undefined
  11174. },
  11175. edges: {
  11176. widthMin: 1,
  11177. widthMax: 15,
  11178. width: 1,
  11179. style: 'line',
  11180. color: '#343434',
  11181. fontColor: '#343434',
  11182. fontSize: 14, // px
  11183. fontFace: 'arial',
  11184. //distance: 100, //px
  11185. length: 100, // px
  11186. dash: {
  11187. length: 10,
  11188. gap: 5,
  11189. altLength: undefined
  11190. }
  11191. },
  11192. clustering: { // Per Node in Cluster = PNiC
  11193. enabled: false, // (Boolean) | global on/off switch for clustering.
  11194. initialMaxNumberOfNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  11195. absoluteMaxNumberOfNodes:500, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than this. If it is, cluster until reduced to reduceToMaxNumberOfNodes
  11196. reduceToMaxNumberOfNodes:300, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than absoluteMaxNumberOfNodes. If it is, cluster until reduced to this
  11197. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  11198. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  11199. sectorThreshold: 50, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  11200. 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.
  11201. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  11202. forceAmplification: 0.6, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  11203. distanceAmplification: 0.2, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  11204. edgeGrowth: 11, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  11205. clusterSizeWidthFactor: 10, // (px PNiC) | growth of the width per node in cluster.
  11206. clusterSizeHeightFactor: 10, // (px PNiC) | growth of the height per node in cluster.
  11207. clusterSizeRadiusFactor: 10, // (px PNiC) | growth of the radius per node in cluster.
  11208. activeAreaBoxSize: 100, // (px) | box area around the curser where clusters are popped open.
  11209. massTransferCoefficient: 1 // (multiplier) | parent.mass += massTransferCoefficient * child.mass
  11210. },
  11211. UI: {
  11212. enabled: true,
  11213. xMovementSpeed: 10,
  11214. yMovementSpeed: 10,
  11215. zoomMovementSpeed: 0.02
  11216. },
  11217. minForce: 0.05,
  11218. minVelocity: 0.02, // px/s
  11219. maxIterations: 1000 // maximum number of iteration to stabilize
  11220. };
  11221. // Node variables
  11222. this.groups = new Groups(); // object with groups
  11223. this.images = new Images(); // object with images
  11224. this.images.setOnloadCallback(function () {
  11225. graph._redraw();
  11226. });
  11227. // UI variables
  11228. this.UIvisible = true;
  11229. this.xIncrement = 0;
  11230. this.yIncrement = 0;
  11231. this.zoomIncrement = 0;
  11232. // create a frame and canvas
  11233. this._create();
  11234. // apply options
  11235. this.setOptions(options);
  11236. // load the cluster system. (mandatory)
  11237. this._loadClusterSystem();
  11238. // load the sector system. (mandatory)
  11239. this._loadSectorSystem();
  11240. // load the selection system. (mandatory)
  11241. this._loadSelectionSystem();
  11242. // load the UI system. (mandatory)
  11243. this._loadUISystem();
  11244. // other vars
  11245. var graph = this;
  11246. this.freezeSimulation = false;// freeze the simulation
  11247. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  11248. this.nodes = {}; // object with Node objects
  11249. this.edges = {}; // object with Edge objects
  11250. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  11251. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  11252. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  11253. this.scale = 1; // defining the global scale variable in the constructor
  11254. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  11255. // TODO: create a counter to keep track on the number of nodes having values
  11256. // TODO: create a counter to keep track on the number of nodes currently moving
  11257. // TODO: create a counter to keep track on the number of edges having values
  11258. this.nodesData = null; // A DataSet or DataView
  11259. this.edgesData = null; // A DataSet or DataView
  11260. // create event listeners used to subscribe on the DataSets of the nodes and edges
  11261. var me = this;
  11262. this.nodesListeners = {
  11263. 'add': function (event, params) {
  11264. me._addNodes(params.items);
  11265. me.start();
  11266. },
  11267. 'update': function (event, params) {
  11268. me._updateNodes(params.items);
  11269. me.start();
  11270. },
  11271. 'remove': function (event, params) {
  11272. me._removeNodes(params.items);
  11273. me.start();
  11274. }
  11275. };
  11276. this.edgesListeners = {
  11277. 'add': function (event, params) {
  11278. me._addEdges(params.items);
  11279. me.start();
  11280. },
  11281. 'update': function (event, params) {
  11282. me._updateEdges(params.items);
  11283. me.start();
  11284. },
  11285. 'remove': function (event, params) {
  11286. me._removeEdges(params.items);
  11287. me.start();
  11288. }
  11289. };
  11290. // properties of the data
  11291. this.moving = false; // True if any of the nodes have an undefined position
  11292. this.timer = undefined;
  11293. // load data (the disable start variable will be the same as the enabled clustering)
  11294. this.setData(data,this.constants.clustering.enabled);
  11295. // zoom so all data will fit on the screen
  11296. this.zoomToFit();
  11297. // if clustering is disabled, the simulation will have started in the setData function
  11298. if (this.constants.clustering.enabled) {
  11299. this.startWithClustering();
  11300. }
  11301. }
  11302. /**
  11303. * This function zooms out to fit all data on screen based on amount of nodes
  11304. */
  11305. Graph.prototype.zoomToFit = function() {
  11306. var numberOfNodes = this.nodeIndices.length;
  11307. var zoomLevel = 46.5 / (numberOfNodes + 20.622); // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  11308. if (zoomLevel > 1.0) {
  11309. zoomLevel = 1.0;
  11310. }
  11311. if (!('mousewheelScale' in this.pinch)) {
  11312. this.pinch.mousewheelScale = zoomLevel;
  11313. }
  11314. this._setScale(zoomLevel);
  11315. };
  11316. /**
  11317. * Update the this.nodeIndices with the most recent node index list
  11318. * @private
  11319. */
  11320. Graph.prototype._updateNodeIndexList = function() {
  11321. this._clearNodeIndexList();
  11322. for (var idx in this.nodes) {
  11323. if (this.nodes.hasOwnProperty(idx)) {
  11324. this.nodeIndices.push(idx);
  11325. }
  11326. }
  11327. };
  11328. /**
  11329. * Set nodes and edges, and optionally options as well.
  11330. *
  11331. * @param {Object} data Object containing parameters:
  11332. * {Array | DataSet | DataView} [nodes] Array with nodes
  11333. * {Array | DataSet | DataView} [edges] Array with edges
  11334. * {String} [dot] String containing data in DOT format
  11335. * {Options} [options] Object with options
  11336. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  11337. */
  11338. Graph.prototype.setData = function(data, disableStart) {
  11339. if (disableStart === undefined) {
  11340. disableStart = false;
  11341. }
  11342. if (data && data.dot && (data.nodes || data.edges)) {
  11343. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  11344. ' parameter pair "nodes" and "edges", but not both.');
  11345. }
  11346. // set options
  11347. this.setOptions(data && data.options);
  11348. // set all data
  11349. if (data && data.dot) {
  11350. // parse DOT file
  11351. if(data && data.dot) {
  11352. var dotData = vis.util.DOTToGraph(data.dot);
  11353. this.setData(dotData);
  11354. return;
  11355. }
  11356. }
  11357. else {
  11358. this._setNodes(data && data.nodes);
  11359. this._setEdges(data && data.edges);
  11360. }
  11361. this._putDataInSector();
  11362. if (!disableStart) {
  11363. // find a stable position or start animating to a stable position
  11364. if (this.stabilize) {
  11365. this._doStabilize();
  11366. }
  11367. this.start();
  11368. }
  11369. };
  11370. /**
  11371. * Set options
  11372. * @param {Object} options
  11373. */
  11374. Graph.prototype.setOptions = function (options) {
  11375. if (options) {
  11376. // retrieve parameter values
  11377. if (options.width !== undefined) {this.width = options.width;}
  11378. if (options.height !== undefined) {this.height = options.height;}
  11379. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  11380. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  11381. if (options.clustering) {
  11382. for (var prop in options.clustering) {
  11383. if (options.clustering.hasOwnProperty(prop)) {
  11384. this.constants.clustering[prop] = options.clustering[prop];
  11385. }
  11386. }
  11387. }
  11388. if (options.UI) {
  11389. for (var prop in options.UI) {
  11390. if (options.UI.hasOwnProperty(prop)) {
  11391. this.constants.UI[prop] = options.UI[prop];
  11392. }
  11393. }
  11394. }
  11395. // TODO: work out these options and document them
  11396. if (options.edges) {
  11397. for (prop in options.edges) {
  11398. if (options.edges.hasOwnProperty(prop)) {
  11399. this.constants.edges[prop] = options.edges[prop];
  11400. }
  11401. }
  11402. if (options.edges.length !== undefined &&
  11403. options.nodes && options.nodes.distance === undefined) {
  11404. this.constants.edges.length = options.edges.length;
  11405. this.constants.nodes.distance = options.edges.length * 1.25;
  11406. }
  11407. if (!options.edges.fontColor) {
  11408. this.constants.edges.fontColor = options.edges.color;
  11409. }
  11410. // Added to support dashed lines
  11411. // David Jordan
  11412. // 2012-08-08
  11413. if (options.edges.dash) {
  11414. if (options.edges.dash.length !== undefined) {
  11415. this.constants.edges.dash.length = options.edges.dash.length;
  11416. }
  11417. if (options.edges.dash.gap !== undefined) {
  11418. this.constants.edges.dash.gap = options.edges.dash.gap;
  11419. }
  11420. if (options.edges.dash.altLength !== undefined) {
  11421. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  11422. }
  11423. }
  11424. }
  11425. if (options.nodes) {
  11426. for (prop in options.nodes) {
  11427. if (options.nodes.hasOwnProperty(prop)) {
  11428. this.constants.nodes[prop] = options.nodes[prop];
  11429. }
  11430. }
  11431. if (options.nodes.color) {
  11432. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  11433. }
  11434. /*
  11435. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  11436. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  11437. */
  11438. }
  11439. if (options.groups) {
  11440. for (var groupname in options.groups) {
  11441. if (options.groups.hasOwnProperty(groupname)) {
  11442. var group = options.groups[groupname];
  11443. this.groups.add(groupname, group);
  11444. }
  11445. }
  11446. }
  11447. }
  11448. this.setSize(this.width, this.height);
  11449. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  11450. this._setScale(1);
  11451. };
  11452. /**
  11453. * fire an event
  11454. * @param {String} event The name of an event, for example 'select'
  11455. * @param {Object} params Optional object with event parameters
  11456. * @private
  11457. */
  11458. Graph.prototype._trigger = function (event, params) {
  11459. events.trigger(this, event, params);
  11460. };
  11461. /**
  11462. * Create the main frame for the Graph.
  11463. * This function is executed once when a Graph object is created. The frame
  11464. * contains a canvas, and this canvas contains all objects like the axis and
  11465. * nodes.
  11466. * @private
  11467. */
  11468. Graph.prototype._create = function () {
  11469. // remove all elements from the container element.
  11470. while (this.containerElement.hasChildNodes()) {
  11471. this.containerElement.removeChild(this.containerElement.firstChild);
  11472. }
  11473. this.frame = document.createElement('div');
  11474. this.frame.className = 'graph-frame';
  11475. this.frame.style.position = 'relative';
  11476. this.frame.style.overflow = 'hidden';
  11477. // create the graph canvas (HTML canvas element)
  11478. this.frame.canvas = document.createElement( 'canvas' );
  11479. this.frame.canvas.style.position = 'relative';
  11480. this.frame.appendChild(this.frame.canvas);
  11481. if (!this.frame.canvas.getContext) {
  11482. var noCanvas = document.createElement( 'DIV' );
  11483. noCanvas.style.color = 'red';
  11484. noCanvas.style.fontWeight = 'bold' ;
  11485. noCanvas.style.padding = '10px';
  11486. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  11487. this.frame.canvas.appendChild(noCanvas);
  11488. }
  11489. var me = this;
  11490. this.drag = {};
  11491. this.pinch = {};
  11492. this.hammer = Hammer(this.frame.canvas, {
  11493. prevent_default: true
  11494. });
  11495. this.hammer.on('tap', me._onTap.bind(me) );
  11496. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  11497. this.hammer.on('hold', me._onHold.bind(me) );
  11498. this.hammer.on('pinch', me._onPinch.bind(me) );
  11499. this.hammer.on('touch', me._onTouch.bind(me) );
  11500. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  11501. this.hammer.on('drag', me._onDrag.bind(me) );
  11502. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  11503. this.hammer.on('release', me._onRelease.bind(me) );
  11504. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  11505. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  11506. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  11507. // add the frame to the container element
  11508. this.containerElement.appendChild(this.frame);
  11509. };
  11510. Graph.prototype._createKeyBinds = function() {
  11511. var me = this;
  11512. this.mouseTrap = mouseTrap;
  11513. this.mouseTrap.bind("up", this._moveUp.bind(me) , "keydown");
  11514. this.mouseTrap.bind("up", this._yStopMoving.bind(me), "keyup");
  11515. this.mouseTrap.bind("down", this._moveDown.bind(me) , "keydown");
  11516. this.mouseTrap.bind("down", this._yStopMoving.bind(me), "keyup");
  11517. this.mouseTrap.bind("left", this._moveLeft.bind(me) , "keydown");
  11518. this.mouseTrap.bind("left", this._xStopMoving.bind(me), "keyup");
  11519. this.mouseTrap.bind("right",this._moveRight.bind(me), "keydown");
  11520. this.mouseTrap.bind("right",this._xStopMoving.bind(me), "keyup");
  11521. this.mouseTrap.bind("=",this._zoomIn.bind(me), "keydown");
  11522. this.mouseTrap.bind("=",this._stopZoom.bind(me), "keyup");
  11523. this.mouseTrap.bind("-",this._zoomOut.bind(me), "keydown");
  11524. this.mouseTrap.bind("-",this._stopZoom.bind(me), "keyup");
  11525. this.mouseTrap.bind("[",this._zoomIn.bind(me), "keydown");
  11526. this.mouseTrap.bind("[",this._stopZoom.bind(me), "keyup");
  11527. this.mouseTrap.bind("]",this._zoomOut.bind(me), "keydown");
  11528. this.mouseTrap.bind("]",this._stopZoom.bind(me), "keyup");
  11529. this.mouseTrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  11530. this.mouseTrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  11531. this.mouseTrap.bind("pagedown",this._zoomOut.bind(me), "keydown");
  11532. this.mouseTrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  11533. this.mouseTrap.bind("u",this._toggleUI.bind(me) , "keydown");
  11534. /*=
  11535. this.mouseTrap.bind("=",this.decreaseClusterLevel.bind(me));
  11536. this.mouseTrap.bind("-",this.increaseClusterLevel.bind(me));
  11537. this.mouseTrap.bind("s",this.singleStep.bind(me));
  11538. this.mouseTrap.bind("h",this.updateClustersDefault.bind(me));
  11539. this.mouseTrap.bind("c",this._collapseSector.bind(me));
  11540. this.mouseTrap.bind("f",this.toggleFreeze.bind(me));
  11541. */
  11542. }
  11543. /**
  11544. * Get the pointer location from a touch location
  11545. * @param {{pageX: Number, pageY: Number}} touch
  11546. * @return {{x: Number, y: Number}} pointer
  11547. * @private
  11548. */
  11549. Graph.prototype._getPointer = function (touch) {
  11550. return {
  11551. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  11552. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  11553. };
  11554. };
  11555. /**
  11556. * On start of a touch gesture, store the pointer
  11557. * @param event
  11558. * @private
  11559. */
  11560. Graph.prototype._onTouch = function (event) {
  11561. this.drag.pointer = this._getPointer(event.gesture.touches[0]);
  11562. this.drag.pinched = false;
  11563. this.pinch.scale = this._getScale();
  11564. this._handleTouch(this.drag.pointer);
  11565. };
  11566. /**
  11567. * handle drag start event
  11568. * @private
  11569. */
  11570. Graph.prototype._onDragStart = function () {
  11571. var drag = this.drag;
  11572. var node = this._getNodeAt(drag.pointer);
  11573. // note: drag.pointer is set in _onTouch to get the initial touch location
  11574. drag.selection = [];
  11575. drag.translation = this._getTranslation();
  11576. drag.nodeId = null;
  11577. if (node != null) {
  11578. drag.nodeId = node.id;
  11579. // select the clicked node if not yet selected
  11580. if (!node.isSelected()) {
  11581. this._selectNode(node,false);
  11582. }
  11583. // create an array with the selected nodes and their original location and status
  11584. var me = this;
  11585. this.selection.forEach(function (id) {
  11586. var node = me.nodes[id];
  11587. if (node) {
  11588. var s = {
  11589. id: id,
  11590. node: node,
  11591. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  11592. x: node.x,
  11593. y: node.y,
  11594. xFixed: node.xFixed,
  11595. yFixed: node.yFixed
  11596. };
  11597. node.xFixed = true;
  11598. node.yFixed = true;
  11599. drag.selection.push(s);
  11600. }
  11601. });
  11602. }
  11603. };
  11604. /**
  11605. * handle drag event
  11606. * @private
  11607. */
  11608. Graph.prototype._onDrag = function (event) {
  11609. if (this.drag.pinched) {
  11610. return;
  11611. }
  11612. var pointer = this._getPointer(event.gesture.touches[0]);
  11613. var me = this,
  11614. drag = this.drag,
  11615. selection = drag.selection;
  11616. if (selection && selection.length) {
  11617. // calculate delta's and new location
  11618. var deltaX = pointer.x - drag.pointer.x,
  11619. deltaY = pointer.y - drag.pointer.y;
  11620. // update position of all selected nodes
  11621. selection.forEach(function (s) {
  11622. var node = s.node;
  11623. if (!s.xFixed) {
  11624. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  11625. }
  11626. if (!s.yFixed) {
  11627. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  11628. }
  11629. });
  11630. // start animation if not yet running
  11631. if (!this.moving) {
  11632. this.moving = true;
  11633. this.start();
  11634. }
  11635. }
  11636. else {
  11637. // move the graph
  11638. var diffX = pointer.x - this.drag.pointer.x;
  11639. var diffY = pointer.y - this.drag.pointer.y;
  11640. this._setTranslation(
  11641. this.drag.translation.x + diffX,
  11642. this.drag.translation.y + diffY);
  11643. this._redraw();
  11644. this.moved = true;
  11645. }
  11646. };
  11647. /**
  11648. * handle drag start event
  11649. * @private
  11650. */
  11651. Graph.prototype._onDragEnd = function () {
  11652. var selection = this.drag.selection;
  11653. if (selection) {
  11654. selection.forEach(function (s) {
  11655. // restore original xFixed and yFixed
  11656. s.node.xFixed = s.xFixed;
  11657. s.node.yFixed = s.yFixed;
  11658. });
  11659. }
  11660. };
  11661. /**
  11662. * handle tap/click event: select/unselect a node
  11663. * @private
  11664. */
  11665. Graph.prototype._onTap = function (event) {
  11666. var pointer = this._getPointer(event.gesture.touches[0]);
  11667. this._handleTap(pointer);
  11668. };
  11669. /**
  11670. * handle doubletap event
  11671. * @private
  11672. */
  11673. Graph.prototype._onDoubleTap = function (event) {
  11674. var pointer = this._getPointer(event.gesture.touches[0]);
  11675. this._handleDoubleTap(pointer);
  11676. };
  11677. /**
  11678. * handle long tap event: multi select nodes
  11679. * @private
  11680. */
  11681. Graph.prototype._onHold = function (event) {
  11682. var pointer = this._getPointer(event.gesture.touches[0]);
  11683. this._handleOnHold(pointer);
  11684. };
  11685. /**
  11686. * handle the release of the screen
  11687. *
  11688. * @param event
  11689. * @private
  11690. */
  11691. Graph.prototype._onRelease = function (event) {
  11692. this._handleOnRelease();
  11693. };
  11694. /**
  11695. * Handle pinch event
  11696. * @param event
  11697. * @private
  11698. */
  11699. Graph.prototype._onPinch = function (event) {
  11700. var pointer = this._getPointer(event.gesture.center);
  11701. this.drag.pinched = true;
  11702. if (!('scale' in this.pinch)) {
  11703. this.pinch.scale = 1;
  11704. }
  11705. // TODO: enabled moving while pinching?
  11706. var scale = this.pinch.scale * event.gesture.scale;
  11707. this._zoom(scale, pointer)
  11708. };
  11709. /**
  11710. * Zoom the graph in or out
  11711. * @param {Number} scale a number around 1, and between 0.01 and 10
  11712. * @param {{x: Number, y: Number}} pointer
  11713. * @return {Number} appliedScale scale is limited within the boundaries
  11714. * @private
  11715. */
  11716. Graph.prototype._zoom = function(scale, pointer) {
  11717. var scaleOld = this._getScale();
  11718. if (scale < 0.00001) {
  11719. scale = 0.00001;
  11720. }
  11721. if (scale > 10) {
  11722. scale = 10;
  11723. }
  11724. // + this.frame.canvas.clientHeight / 2
  11725. var translation = this._getTranslation();
  11726. var scaleFrac = scale / scaleOld;
  11727. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  11728. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  11729. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  11730. "y" : this._canvasToY(pointer.y)};
  11731. // this.areaCenter = {"x" : pointer.x,"y" : pointer.y };
  11732. this.pinch.mousewheelScale = scale;
  11733. this._setScale(scale);
  11734. this._setTranslation(tx, ty);
  11735. this.updateClustersDefault();
  11736. this._redraw();
  11737. // console.log("current zoomscale:",this.scale);
  11738. return scale;
  11739. };
  11740. /**
  11741. * Event handler for mouse wheel event, used to zoom the timeline
  11742. * See http://adomas.org/javascript-mouse-wheel/
  11743. * https://github.com/EightMedia/hammer.js/issues/256
  11744. * @param {MouseEvent} event
  11745. * @private
  11746. */
  11747. Graph.prototype._onMouseWheel = function(event) {
  11748. // retrieve delta
  11749. var delta = 0;
  11750. if (event.wheelDelta) { /* IE/Opera. */
  11751. delta = event.wheelDelta/120;
  11752. } else if (event.detail) { /* Mozilla case. */
  11753. // In Mozilla, sign of delta is different than in IE.
  11754. // Also, delta is multiple of 3.
  11755. delta = -event.detail/3;
  11756. }
  11757. // If delta is nonzero, handle it.
  11758. // Basically, delta is now positive if wheel was scrolled up,
  11759. // and negative, if wheel was scrolled down.
  11760. if (delta) {
  11761. if (!('mousewheelScale' in this.pinch)) {
  11762. this.pinch.mousewheelScale = 1;
  11763. }
  11764. // calculate the new scale
  11765. var scale = this.pinch.mousewheelScale;
  11766. var zoom = delta / 10;
  11767. if (delta < 0) {
  11768. zoom = zoom / (1 - zoom);
  11769. }
  11770. scale *= (1 + zoom);
  11771. // calculate the pointer location
  11772. var gesture = util.fakeGesture(this, event);
  11773. var pointer = this._getPointer(gesture.center);
  11774. // apply the new scale
  11775. scale = this._zoom(scale, pointer);
  11776. // store the new, applied scale -- this is now done in _zoom
  11777. // this.pinch.mousewheelScale = scale;
  11778. }
  11779. // Prevent default actions caused by mouse wheel.
  11780. event.preventDefault();
  11781. };
  11782. /**
  11783. * Mouse move handler for checking whether the title moves over a node with a title.
  11784. * @param {Event} event
  11785. * @private
  11786. */
  11787. Graph.prototype._onMouseMoveTitle = function (event) {
  11788. var gesture = util.fakeGesture(this, event);
  11789. var pointer = this._getPointer(gesture.center);
  11790. this.lastPointerPosition = pointer;
  11791. // check if the previously selected node is still selected
  11792. if (this.popupNode) {
  11793. this._checkHidePopup(pointer);
  11794. }
  11795. // start a timeout that will check if the mouse is positioned above
  11796. // an element
  11797. var me = this;
  11798. var checkShow = function() {
  11799. me._checkShowPopup(pointer);
  11800. };
  11801. if (this.popupTimer) {
  11802. clearInterval(this.popupTimer); // stop any running calculationTimer
  11803. }
  11804. if (!this.leftButtonDown) {
  11805. this.popupTimer = setTimeout(checkShow, 300);
  11806. }
  11807. };
  11808. /**
  11809. * Check if there is an element on the given position in the graph
  11810. * (a node or edge). If so, and if this element has a title,
  11811. * show a popup window with its title.
  11812. *
  11813. * @param {{x:Number, y:Number}} pointer
  11814. * @private
  11815. */
  11816. Graph.prototype._checkShowPopup = function (pointer) {
  11817. var obj = {
  11818. left: this._canvasToX(pointer.x),
  11819. top: this._canvasToY(pointer.y),
  11820. right: this._canvasToX(pointer.x),
  11821. bottom: this._canvasToY(pointer.y)
  11822. };
  11823. var id;
  11824. var lastPopupNode = this.popupNode;
  11825. if (this.popupNode == undefined) {
  11826. // search the nodes for overlap, select the top one in case of multiple nodes
  11827. var nodes = this.nodes;
  11828. for (id in nodes) {
  11829. if (nodes.hasOwnProperty(id)) {
  11830. var node = nodes[id];
  11831. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  11832. this.popupNode = node;
  11833. break;
  11834. }
  11835. }
  11836. }
  11837. }
  11838. if (this.popupNode === undefined) {
  11839. // search the edges for overlap
  11840. var edges = this.edges;
  11841. for (id in edges) {
  11842. if (edges.hasOwnProperty(id)) {
  11843. var edge = edges[id];
  11844. if (edge.connected && (edge.getTitle() !== undefined) &&
  11845. edge.isOverlappingWith(obj)) {
  11846. this.popupNode = edge;
  11847. break;
  11848. }
  11849. }
  11850. }
  11851. }
  11852. if (this.popupNode) {
  11853. // show popup message window
  11854. if (this.popupNode != lastPopupNode) {
  11855. var me = this;
  11856. if (!me.popup) {
  11857. me.popup = new Popup(me.frame);
  11858. }
  11859. // adjust a small offset such that the mouse cursor is located in the
  11860. // bottom left location of the popup, and you can easily move over the
  11861. // popup area
  11862. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  11863. me.popup.setText(me.popupNode.getTitle());
  11864. me.popup.show();
  11865. }
  11866. }
  11867. else {
  11868. if (this.popup) {
  11869. this.popup.hide();
  11870. }
  11871. }
  11872. };
  11873. /**
  11874. * Check if the popup must be hided, which is the case when the mouse is no
  11875. * longer hovering on the object
  11876. * @param {{x:Number, y:Number}} pointer
  11877. * @private
  11878. */
  11879. Graph.prototype._checkHidePopup = function (pointer) {
  11880. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  11881. this.popupNode = undefined;
  11882. if (this.popup) {
  11883. this.popup.hide();
  11884. }
  11885. }
  11886. };
  11887. /**
  11888. * Temporary method to test calculating a hub value for the nodes
  11889. * @param {number} level Maximum number edges between two nodes in order
  11890. * to call them connected. Optional, 1 by default
  11891. * @return {Number[]} connectioncount array with the connection count
  11892. * for each node
  11893. * @private
  11894. */
  11895. Graph.prototype._getConnectionCount = function(level) {
  11896. if (level == undefined) {
  11897. level = 1;
  11898. }
  11899. // get the nodes connected to given nodes
  11900. function getConnectedNodes(nodes) {
  11901. var connectedNodes = [];
  11902. for (var j = 0, jMax = nodes.length; j < jMax; j++) {
  11903. var node = nodes[j];
  11904. // find all nodes connected to this node
  11905. var edges = node.edges;
  11906. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  11907. var edge = edges[i];
  11908. var other = null;
  11909. // check if connected
  11910. if (edge.from == node)
  11911. other = edge.to;
  11912. else if (edge.to == node)
  11913. other = edge.from;
  11914. // check if the other node is not already in the list with nodes
  11915. var k, kMax;
  11916. if (other) {
  11917. for (k = 0, kMax = nodes.length; k < kMax; k++) {
  11918. if (nodes[k] == other) {
  11919. other = null;
  11920. break;
  11921. }
  11922. }
  11923. }
  11924. if (other) {
  11925. for (k = 0, kMax = connectedNodes.length; k < kMax; k++) {
  11926. if (connectedNodes[k] == other) {
  11927. other = null;
  11928. break;
  11929. }
  11930. }
  11931. }
  11932. if (other)
  11933. connectedNodes.push(other);
  11934. }
  11935. }
  11936. return connectedNodes;
  11937. }
  11938. var connections = [];
  11939. var nodes = this.nodes;
  11940. for (var id in nodes) {
  11941. if (nodes.hasOwnProperty(id)) {
  11942. var c = [nodes[id]];
  11943. for (var l = 0; l < level; l++) {
  11944. c = c.concat(getConnectedNodes(c));
  11945. }
  11946. connections.push(c);
  11947. }
  11948. }
  11949. var hubs = [];
  11950. for (var i = 0, len = connections.length; i < len; i++) {
  11951. hubs.push(connections[i].length);
  11952. }
  11953. return hubs;
  11954. };
  11955. /**
  11956. * Set a new size for the graph
  11957. * @param {string} width Width in pixels or percentage (for example '800px'
  11958. * or '50%')
  11959. * @param {string} height Height in pixels or percentage (for example '400px'
  11960. * or '30%')
  11961. */
  11962. Graph.prototype.setSize = function(width, height) {
  11963. this.frame.style.width = width;
  11964. this.frame.style.height = height;
  11965. this.frame.canvas.style.width = '100%';
  11966. this.frame.canvas.style.height = '100%';
  11967. this.frame.canvas.width = this.frame.canvas.clientWidth;
  11968. this.frame.canvas.height = this.frame.canvas.clientHeight;
  11969. if (this.constants.UI.enabled == true) {
  11970. this._relocateUI();
  11971. }
  11972. };
  11973. /**
  11974. * Set a data set with nodes for the graph
  11975. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  11976. * @private
  11977. */
  11978. Graph.prototype._setNodes = function(nodes) {
  11979. var oldNodesData = this.nodesData;
  11980. if (nodes instanceof DataSet || nodes instanceof DataView) {
  11981. this.nodesData = nodes;
  11982. }
  11983. else if (nodes instanceof Array) {
  11984. this.nodesData = new DataSet();
  11985. this.nodesData.add(nodes);
  11986. }
  11987. else if (!nodes) {
  11988. this.nodesData = new DataSet();
  11989. }
  11990. else {
  11991. throw new TypeError('Array or DataSet expected');
  11992. }
  11993. if (oldNodesData) {
  11994. // unsubscribe from old dataset
  11995. util.forEach(this.nodesListeners, function (callback, event) {
  11996. oldNodesData.unsubscribe(event, callback);
  11997. });
  11998. }
  11999. // remove drawn nodes
  12000. this.nodes = {};
  12001. if (this.nodesData) {
  12002. // subscribe to new dataset
  12003. var me = this;
  12004. util.forEach(this.nodesListeners, function (callback, event) {
  12005. me.nodesData.subscribe(event, callback);
  12006. });
  12007. // draw all new nodes
  12008. var ids = this.nodesData.getIds();
  12009. this._addNodes(ids);
  12010. }
  12011. this._updateSelection();
  12012. };
  12013. /**
  12014. * Add nodes
  12015. * @param {Number[] | String[]} ids
  12016. * @private
  12017. */
  12018. Graph.prototype._addNodes = function(ids) {
  12019. var id;
  12020. for (var i = 0, len = ids.length; i < len; i++) {
  12021. id = ids[i];
  12022. var data = this.nodesData.get(id);
  12023. var node = new Node(data, this.images, this.groups, this.constants);
  12024. this.nodes[id] = node; // note: this may replace an existing node
  12025. if (!node.isFixed()) {
  12026. // TODO: position new nodes in a smarter way!
  12027. var radius = this.constants.edges.length * 2;
  12028. var count = ids.length;
  12029. var angle = 2 * Math.PI * (i / count);
  12030. node.x = radius * Math.cos(angle);
  12031. node.y = radius * Math.sin(angle);
  12032. // note: no not use node.isMoving() here, as that gives the current
  12033. // velocity of the node, which is zero after creation of the node.
  12034. this.moving = true;
  12035. }
  12036. }
  12037. this._updateNodeIndexList();
  12038. this._reconnectEdges();
  12039. this._updateValueRange(this.nodes);
  12040. };
  12041. /**
  12042. * Update existing nodes, or create them when not yet existing
  12043. * @param {Number[] | String[]} ids
  12044. * @private
  12045. */
  12046. Graph.prototype._updateNodes = function(ids) {
  12047. var nodes = this.nodes,
  12048. nodesData = this.nodesData;
  12049. for (var i = 0, len = ids.length; i < len; i++) {
  12050. var id = ids[i];
  12051. var node = nodes[id];
  12052. var data = nodesData.get(id);
  12053. if (node) {
  12054. // update node
  12055. node.setProperties(data, this.constants);
  12056. }
  12057. else {
  12058. // create node
  12059. node = new Node(properties, this.images, this.groups, this.constants);
  12060. nodes[id] = node;
  12061. if (!node.isFixed()) {
  12062. this.moving = true;
  12063. }
  12064. }
  12065. }
  12066. this._updateNodeIndexList();
  12067. this._reconnectEdges();
  12068. this._updateValueRange(nodes);
  12069. };
  12070. /**
  12071. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  12072. * @param {Number[] | String[]} ids
  12073. * @private
  12074. */
  12075. Graph.prototype._removeNodes = function(ids) {
  12076. var nodes = this.nodes;
  12077. for (var i = 0, len = ids.length; i < len; i++) {
  12078. var id = ids[i];
  12079. delete nodes[id];
  12080. }
  12081. this._updateNodeIndexList();
  12082. this._reconnectEdges();
  12083. this._updateSelection();
  12084. this._updateValueRange(nodes);
  12085. };
  12086. /**
  12087. * Load edges by reading the data table
  12088. * @param {Array | DataSet | DataView} edges The data containing the edges.
  12089. * @private
  12090. * @private
  12091. */
  12092. Graph.prototype._setEdges = function(edges) {
  12093. var oldEdgesData = this.edgesData;
  12094. if (edges instanceof DataSet || edges instanceof DataView) {
  12095. this.edgesData = edges;
  12096. }
  12097. else if (edges instanceof Array) {
  12098. this.edgesData = new DataSet();
  12099. this.edgesData.add(edges);
  12100. }
  12101. else if (!edges) {
  12102. this.edgesData = new DataSet();
  12103. }
  12104. else {
  12105. throw new TypeError('Array or DataSet expected');
  12106. }
  12107. if (oldEdgesData) {
  12108. // unsubscribe from old dataset
  12109. util.forEach(this.edgesListeners, function (callback, event) {
  12110. oldEdgesData.unsubscribe(event, callback);
  12111. });
  12112. }
  12113. // remove drawn edges
  12114. this.edges = {};
  12115. if (this.edgesData) {
  12116. // subscribe to new dataset
  12117. var me = this;
  12118. util.forEach(this.edgesListeners, function (callback, event) {
  12119. me.edgesData.subscribe(event, callback);
  12120. });
  12121. // draw all new nodes
  12122. var ids = this.edgesData.getIds();
  12123. this._addEdges(ids);
  12124. }
  12125. this._reconnectEdges();
  12126. };
  12127. /**
  12128. * Add edges
  12129. * @param {Number[] | String[]} ids
  12130. * @private
  12131. */
  12132. Graph.prototype._addEdges = function (ids) {
  12133. var edges = this.edges,
  12134. edgesData = this.edgesData;
  12135. for (var i = 0, len = ids.length; i < len; i++) {
  12136. var id = ids[i];
  12137. var oldEdge = edges[id];
  12138. if (oldEdge) {
  12139. oldEdge.disconnect();
  12140. }
  12141. var data = edgesData.get(id, {"showInternalIds" : true});
  12142. edges[id] = new Edge(data, this, this.constants);
  12143. }
  12144. this.moving = true;
  12145. this._updateValueRange(edges);
  12146. };
  12147. /**
  12148. * Update existing edges, or create them when not yet existing
  12149. * @param {Number[] | String[]} ids
  12150. * @private
  12151. */
  12152. Graph.prototype._updateEdges = function (ids) {
  12153. var edges = this.edges,
  12154. edgesData = this.edgesData;
  12155. for (var i = 0, len = ids.length; i < len; i++) {
  12156. var id = ids[i];
  12157. var data = edgesData.get(id);
  12158. var edge = edges[id];
  12159. if (edge) {
  12160. // update edge
  12161. edge.disconnect();
  12162. edge.setProperties(data, this.constants);
  12163. edge.connect();
  12164. }
  12165. else {
  12166. // create edge
  12167. edge = new Edge(data, this, this.constants);
  12168. this.edges[id] = edge;
  12169. }
  12170. }
  12171. this.moving = true;
  12172. this._updateValueRange(edges);
  12173. };
  12174. /**
  12175. * Remove existing edges. Non existing ids will be ignored
  12176. * @param {Number[] | String[]} ids
  12177. * @private
  12178. */
  12179. Graph.prototype._removeEdges = function (ids) {
  12180. var edges = this.edges;
  12181. for (var i = 0, len = ids.length; i < len; i++) {
  12182. var id = ids[i];
  12183. var edge = edges[id];
  12184. if (edge) {
  12185. edge.disconnect();
  12186. delete edges[id];
  12187. }
  12188. }
  12189. this.moving = true;
  12190. this._updateValueRange(edges);
  12191. };
  12192. /**
  12193. * Reconnect all edges
  12194. * @private
  12195. */
  12196. Graph.prototype._reconnectEdges = function() {
  12197. var id,
  12198. nodes = this.nodes,
  12199. edges = this.edges;
  12200. for (id in nodes) {
  12201. if (nodes.hasOwnProperty(id)) {
  12202. nodes[id].edges = [];
  12203. }
  12204. }
  12205. for (id in edges) {
  12206. if (edges.hasOwnProperty(id)) {
  12207. var edge = edges[id];
  12208. edge.from = null;
  12209. edge.to = null;
  12210. edge.connect();
  12211. }
  12212. }
  12213. };
  12214. /**
  12215. * Update the values of all object in the given array according to the current
  12216. * value range of the objects in the array.
  12217. * @param {Object} obj An object containing a set of Edges or Nodes
  12218. * The objects must have a method getValue() and
  12219. * setValueRange(min, max).
  12220. * @private
  12221. */
  12222. Graph.prototype._updateValueRange = function(obj) {
  12223. var id;
  12224. // determine the range of the objects
  12225. var valueMin = undefined;
  12226. var valueMax = undefined;
  12227. for (id in obj) {
  12228. if (obj.hasOwnProperty(id)) {
  12229. var value = obj[id].getValue();
  12230. if (value !== undefined) {
  12231. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  12232. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  12233. }
  12234. }
  12235. }
  12236. // adjust the range of all objects
  12237. if (valueMin !== undefined && valueMax !== undefined) {
  12238. for (id in obj) {
  12239. if (obj.hasOwnProperty(id)) {
  12240. obj[id].setValueRange(valueMin, valueMax);
  12241. }
  12242. }
  12243. }
  12244. };
  12245. /**
  12246. * Redraw the graph with the current data
  12247. * chart will be resized too.
  12248. */
  12249. Graph.prototype.redraw = function() {
  12250. this.setSize(this.width, this.height);
  12251. this._redraw();
  12252. };
  12253. /**
  12254. * Redraw the graph with the current data
  12255. * @private
  12256. */
  12257. Graph.prototype._redraw = function() {
  12258. var ctx = this.frame.canvas.getContext('2d');
  12259. // clear the canvas
  12260. var w = this.frame.canvas.width;
  12261. var h = this.frame.canvas.height;
  12262. ctx.clearRect(0, 0, w, h);
  12263. // set scaling and translation
  12264. ctx.save();
  12265. ctx.translate(this.translation.x, this.translation.y);
  12266. ctx.scale(this.scale, this.scale);
  12267. this.canvasTopLeft = {"x": (0-this.translation.x)/this.scale,
  12268. "y": (0-this.translation.y)/this.scale};
  12269. this.canvasBottomRight = {"x": (this.frame.canvas.clientWidth -this.translation.x)/this.scale,
  12270. "y": (this.frame.canvas.clientHeight-this.translation.y)/this.scale};
  12271. this._doInAllSectors("_drawAllSectorNodes",ctx);
  12272. this._doInAllSectors("_drawEdges",ctx);
  12273. this._doInAllSectors("_drawNodes",ctx);
  12274. // restore original scaling and translation
  12275. ctx.restore();
  12276. if (this.UIvisible == true) {
  12277. this._doInUISector("_drawNodes",ctx,true);
  12278. }
  12279. };
  12280. /**
  12281. * Set the translation of the graph
  12282. * @param {Number} offsetX Horizontal offset
  12283. * @param {Number} offsetY Vertical offset
  12284. * @private
  12285. */
  12286. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  12287. if (this.translation === undefined) {
  12288. this.translation = {
  12289. x: 0,
  12290. y: 0
  12291. };
  12292. }
  12293. if (offsetX !== undefined) {
  12294. this.translation.x = offsetX;
  12295. }
  12296. if (offsetY !== undefined) {
  12297. this.translation.y = offsetY;
  12298. }
  12299. };
  12300. /**
  12301. * Get the translation of the graph
  12302. * @return {Object} translation An object with parameters x and y, both a number
  12303. * @private
  12304. */
  12305. Graph.prototype._getTranslation = function() {
  12306. return {
  12307. x: this.translation.x,
  12308. y: this.translation.y
  12309. };
  12310. };
  12311. /**
  12312. * Scale the graph
  12313. * @param {Number} scale Scaling factor 1.0 is unscaled
  12314. * @private
  12315. */
  12316. Graph.prototype._setScale = function(scale) {
  12317. this.scale = scale;
  12318. };
  12319. /**
  12320. * Get the current scale of the graph
  12321. * @return {Number} scale Scaling factor 1.0 is unscaled
  12322. * @private
  12323. */
  12324. Graph.prototype._getScale = function() {
  12325. return this.scale;
  12326. };
  12327. /**
  12328. * Convert a horizontal point on the HTML canvas to the x-value of the model
  12329. * @param {number} x
  12330. * @returns {number}
  12331. * @private
  12332. */
  12333. Graph.prototype._canvasToX = function(x) {
  12334. return (x - this.translation.x) / this.scale;
  12335. };
  12336. /**
  12337. * Convert an x-value in the model to a horizontal point on the HTML canvas
  12338. * @param {number} x
  12339. * @returns {number}
  12340. * @private
  12341. */
  12342. Graph.prototype._xToCanvas = function(x) {
  12343. return x * this.scale + this.translation.x;
  12344. };
  12345. /**
  12346. * Convert a vertical point on the HTML canvas to the y-value of the model
  12347. * @param {number} y
  12348. * @returns {number}
  12349. * @private
  12350. */
  12351. Graph.prototype._canvasToY = function(y) {
  12352. return (y - this.translation.y) / this.scale;
  12353. };
  12354. /**
  12355. * Convert an y-value in the model to a vertical point on the HTML canvas
  12356. * @param {number} y
  12357. * @returns {number}
  12358. * @private
  12359. */
  12360. Graph.prototype._yToCanvas = function(y) {
  12361. return y * this.scale + this.translation.y ;
  12362. };
  12363. /**
  12364. * Redraw all nodes
  12365. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  12366. * @param {CanvasRenderingContext2D} ctx
  12367. * @param {Boolean} [alwaysShow]
  12368. * @private
  12369. */
  12370. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  12371. if (alwaysShow === undefined) {
  12372. alwaysShow = false;
  12373. }
  12374. // first draw the unselected nodes
  12375. var nodes = this.nodes;
  12376. var selected = [];
  12377. for (var id in nodes) {
  12378. if (nodes.hasOwnProperty(id)) {
  12379. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  12380. if (nodes[id].isSelected()) {
  12381. selected.push(id);
  12382. }
  12383. else {
  12384. if (nodes[id].inArea() || alwaysShow) {
  12385. nodes[id].draw(ctx);
  12386. }
  12387. }
  12388. }
  12389. }
  12390. // draw the selected nodes on top
  12391. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  12392. if (nodes[selected[s]].inArea() || alwaysShow) {
  12393. nodes[selected[s]].draw(ctx);
  12394. }
  12395. }
  12396. };
  12397. /**
  12398. * Redraw all edges
  12399. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  12400. * @param {CanvasRenderingContext2D} ctx
  12401. * @private
  12402. */
  12403. Graph.prototype._drawEdges = function(ctx) {
  12404. var edges = this.edges;
  12405. for (var id in edges) {
  12406. if (edges.hasOwnProperty(id)) {
  12407. var edge = edges[id];
  12408. edge.setScale(this.scale);
  12409. if (edge.connected) {
  12410. edges[id].draw(ctx);
  12411. }
  12412. }
  12413. }
  12414. };
  12415. /**
  12416. * Find a stable position for all nodes
  12417. * @private
  12418. */
  12419. Graph.prototype._doStabilize = function() {
  12420. //var start = new Date();
  12421. // find stable position
  12422. var count = 0;
  12423. var vmin = this.constants.minVelocity;
  12424. var stable = false;
  12425. while (!stable && count < this.constants.maxIterations) {
  12426. this._initializeForceCalculation();
  12427. this._discreteStepNodes();
  12428. stable = !this._isMoving(vmin);
  12429. count++;
  12430. }
  12431. // var end = new Date();
  12432. // console.log('Stabilized in ' + (end-start) + ' ms, ' + count + ' iterations' ); // TODO: cleanup
  12433. };
  12434. /**
  12435. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  12436. * if there is more than one node. If it is just one node, we dont calculate anything.
  12437. *
  12438. * @private
  12439. */
  12440. Graph.prototype._initializeForceCalculation = function() {
  12441. // stop calculation if there is only one node
  12442. if (this.nodeIndices.length == 1) {
  12443. this.nodes[this.nodeIndices[0]]._setForce(0,0);
  12444. }
  12445. else {
  12446. // if there are too many nodes on screen, we cluster without repositioning
  12447. if (this.nodeIndices.length > this.constants.clustering.absoluteMaxNumberOfNodes && this.constants.clustering.enabled == true) {
  12448. this.clusterToFit(this.constants.clustering.reduceToMaxNumberOfNodes, false);
  12449. }
  12450. // we now start the force calculation
  12451. this._calculateForces();
  12452. }
  12453. };
  12454. /**
  12455. * Calculate the external forces acting on the nodes
  12456. * Forces are caused by: edges, repulsing forces between nodes, gravity
  12457. * @private
  12458. */
  12459. Graph.prototype._calculateForces = function() {
  12460. var centerPos = {"x":0.5*(this.canvasTopLeft.x + this.canvasBottomRight.x),
  12461. "y":0.5*(this.canvasTopLeft.y + this.canvasBottomRight.y)}
  12462. // create a local edge to the nodes and edges, that is faster
  12463. var dx, dy, angle, distance, fx, fy,
  12464. repulsingForce, springForce, length, edgeLength,
  12465. node, node1, node2, edge, edgeId, i, j, nodeId, xCenter, yCenter;
  12466. var clusterSize;
  12467. var nodes = this.nodes;
  12468. var edges = this.edges;
  12469. // Gravity is required to keep separated groups from floating off
  12470. // the forces are reset to zero in this loop by using _setForce instead
  12471. // of _addForce
  12472. var gravity = 0.08;
  12473. for (i = 0; i < this.nodeIndices.length; i++) {
  12474. node = nodes[this.nodeIndices[i]];
  12475. // gravity does not apply when we are in a pocket sector
  12476. if (this._sector() == "default") {
  12477. dx = -node.x + centerPos.x;
  12478. dy = -node.y + centerPos.y;
  12479. angle = Math.atan2(dy, dx);
  12480. fx = Math.cos(angle) * gravity;
  12481. fy = Math.sin(angle) * gravity;
  12482. }
  12483. else {
  12484. fx = 0;
  12485. fy = 0;
  12486. }
  12487. node._setForce(fx, fy);
  12488. node.updateDamping(this.nodeIndices.length);
  12489. }
  12490. // repulsing forces between nodes
  12491. var minimumDistance = this.constants.nodes.distance,
  12492. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  12493. // we loop from i over all but the last entree in the array
  12494. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  12495. for (i = 0; i < this.nodeIndices.length-1; i++) {
  12496. node1 = nodes[this.nodeIndices[i]];
  12497. for (j = i+1; j < this.nodeIndices.length; j++) {
  12498. node2 = nodes[this.nodeIndices[j]];
  12499. clusterSize = (node1.clusterSize + node2.clusterSize - 2);
  12500. dx = node2.x - node1.x;
  12501. dy = node2.y - node1.y;
  12502. distance = Math.sqrt(dx * dx + dy * dy);
  12503. // clusters have a larger region of influence
  12504. minimumDistance = (clusterSize == 0) ? this.constants.nodes.distance : (this.constants.nodes.distance * (1 + clusterSize * this.constants.clustering.distanceAmplification));
  12505. if (distance < 2*minimumDistance) { // at 2.0 * the minimum distance, the force is 0.000045
  12506. angle = Math.atan2(dy, dx);
  12507. if (distance < 0.5*minimumDistance) { // at 0.5 * the minimum distance, the force is 0.993307
  12508. repulsingForce = 1.0;
  12509. }
  12510. else {
  12511. // TODO: correct factor for repulsing force
  12512. //repulsingForce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12513. //repulsingForce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12514. repulsingForce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)); // TODO: customize the repulsing force
  12515. }
  12516. // amplify the repulsion for clusters.
  12517. repulsingForce *= (clusterSize == 0) ? 1 : 1 + clusterSize * this.constants.clustering.forceAmplification;
  12518. fx = Math.cos(angle) * repulsingForce;
  12519. fy = Math.sin(angle) * repulsingForce;
  12520. node1._addForce(-fx, -fy);
  12521. node2._addForce(fx, fy);
  12522. }
  12523. }
  12524. }
  12525. /*
  12526. // repulsion of the edges on the nodes and
  12527. for (var nodeId in nodes) {
  12528. if (nodes.hasOwnProperty(nodeId)) {
  12529. node = nodes[nodeId];
  12530. for(var edgeId in edges) {
  12531. if (edges.hasOwnProperty(edgeId)) {
  12532. edge = edges[edgeId];
  12533. // get the center of the edge
  12534. xCenter = edge.from.x+(edge.to.x - edge.from.x)/2;
  12535. yCenter = edge.from.y+(edge.to.y - edge.from.y)/2;
  12536. // calculate normally distributed force
  12537. dx = node.x - xCenter;
  12538. dy = node.y - yCenter;
  12539. distance = Math.sqrt(dx * dx + dy * dy);
  12540. if (distance < 2*minimumDistance) { // at 2.0 * the minimum distance, the force is 0.000045
  12541. angle = Math.atan2(dy, dx);
  12542. if (distance < 0.5*minimumDistance) { // at 0.5 * the minimum distance, the force is 0.993307
  12543. repulsingForce = 1.0;
  12544. }
  12545. else {
  12546. // TODO: correct factor for repulsing force
  12547. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12548. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  12549. repulsingForce = 1 / (1 + Math.exp((distance / (minimumDistance / 2) - 1) * steepness)); // TODO: customize the repulsing force
  12550. }
  12551. fx = Math.cos(angle) * repulsingForce;
  12552. fy = Math.sin(angle) * repulsingForce;
  12553. node._addForce(fx, fy);
  12554. edge.from._addForce(-fx/2,-fy/2);
  12555. edge.to._addForce(-fx/2,-fy/2);
  12556. }
  12557. }
  12558. }
  12559. }
  12560. }
  12561. */
  12562. // forces caused by the edges, modelled as springs
  12563. for (edgeId in edges) {
  12564. if (edges.hasOwnProperty(edgeId)) {
  12565. edge = edges[edgeId];
  12566. if (edge.connected) {
  12567. // only calculate forces if nodes are in the same sector
  12568. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  12569. clusterSize = (edge.to.clusterSize + edge.from.clusterSize - 2);
  12570. dx = (edge.to.x - edge.from.x);
  12571. dy = (edge.to.y - edge.from.y);
  12572. //edgeLength = (edge.from.width + edge.from.height + edge.to.width + edge.to.height)/2 || edge.length; // TODO: dmin
  12573. //edgeLength = (edge.from.width + edge.to.width)/2 || edge.length; // TODO: dmin
  12574. //edgeLength = 20 + ((edge.from.width + edge.to.width) || 0) / 2;
  12575. edgeLength = edge.length;
  12576. // this implies that the edges between big clusters are longer
  12577. edgeLength += clusterSize * this.constants.clustering.edgeGrowth;
  12578. length = Math.sqrt(dx * dx + dy * dy);
  12579. angle = Math.atan2(dy, dx);
  12580. springForce = edge.stiffness * (edgeLength - length);
  12581. fx = Math.cos(angle) * springForce;
  12582. fy = Math.sin(angle) * springForce;
  12583. edge.from._addForce(-fx, -fy);
  12584. edge.to._addForce(fx, fy);
  12585. }
  12586. }
  12587. }
  12588. }
  12589. /*
  12590. // TODO: re-implement repulsion of edges
  12591. // repulsing forces between edges
  12592. var minimumDistance = this.constants.edges.distance,
  12593. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  12594. for (var l = 0; l < edges.length; l++) {
  12595. //Keep distance from other edge centers
  12596. for (var l2 = l + 1; l2 < this.edges.length; l2++) {
  12597. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  12598. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  12599. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  12600. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  12601. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  12602. l2x = edges[l2].from.x+(edges[l2].to.x - edges[l2].from.x)/2,
  12603. l2y = edges[l2].from.y+(edges[l2].to.y - edges[l2].from.y)/2,
  12604. // calculate normally distributed force
  12605. dx = l2x - lx,
  12606. dy = l2y - ly,
  12607. distance = Math.sqrt(dx * dx + dy * dy),
  12608. angle = Math.atan2(dy, dx),
  12609. // TODO: correct factor for repulsing force
  12610. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12611. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  12612. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  12613. fx = Math.cos(angle) * repulsingforce,
  12614. fy = Math.sin(angle) * repulsingforce;
  12615. edges[l].from._addForce(-fx, -fy);
  12616. edges[l].to._addForce(-fx, -fy);
  12617. edges[l2].from._addForce(fx, fy);
  12618. edges[l2].to._addForce(fx, fy);
  12619. }
  12620. }
  12621. */
  12622. };
  12623. /**
  12624. * Check if any of the nodes is still moving
  12625. * @param {number} vmin the minimum velocity considered as 'moving'
  12626. * @return {boolean} true if moving, false if non of the nodes is moving
  12627. * @private
  12628. */
  12629. Graph.prototype._isMoving = function(vmin) {
  12630. // TODO: ismoving does not work well: should check the kinetic energy, not its velocity
  12631. var nodes = this.nodes;
  12632. for (var id in nodes) {
  12633. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  12634. return true;
  12635. }
  12636. }
  12637. return false;
  12638. };
  12639. /**
  12640. * Perform one discrete step for all nodes
  12641. * @private
  12642. */
  12643. Graph.prototype._discreteStepNodes = function() {
  12644. var interval = this.calculationRefreshRate / 1000.0; // in seconds
  12645. var nodes = this.nodes;
  12646. for (var id in nodes) {
  12647. if (nodes.hasOwnProperty(id)) {
  12648. nodes[id].discreteStep(interval);
  12649. }
  12650. }
  12651. var vmin = this.constants.minVelocity;
  12652. this.moving = this._isMoving(vmin);
  12653. };
  12654. /**
  12655. * Start animating nodes and edges
  12656. *
  12657. * @poram {Boolean} runCalculationStep
  12658. */
  12659. Graph.prototype.start = function(runCalculationStep) {
  12660. if (runCalculationStep === undefined) {
  12661. runCalculationStep = true;
  12662. }
  12663. if (!this.freezeSimulation) {
  12664. if (this.moving && runCalculationStep) {
  12665. this._doInAllActiveSectors("_initializeForceCalculation");
  12666. this._doInAllActiveSectors("_discreteStepNodes");
  12667. }
  12668. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  12669. // start animation. only start calculationTimer if it is not already running
  12670. if (!this.timer) {
  12671. var graph = this;
  12672. this.timer = window.setTimeout(function () {
  12673. graph.timer = undefined;
  12674. // keyboad movement
  12675. if (graph.xIncrement != 0 || graph.yIncrement != 0) {
  12676. var translation = graph._getTranslation();
  12677. graph._setTranslation(translation.x+graph.xIncrement,translation.y+graph.yIncrement);
  12678. }
  12679. if (graph.zoomIncrement != 0) {
  12680. graph._zoom(graph.scale*(1 + graph.zoomIncrement),graph.lastPointerPosition);
  12681. }
  12682. var calculateNextStep = false;
  12683. var time = window.performance.now();
  12684. if (time - graph.calculationStartTime > graph.calculationRefreshRate && graph.moving) {
  12685. calculateNextStep = true;
  12686. graph.calculationStartTime = window.performance.now();
  12687. }
  12688. graph.start(calculateNextStep);
  12689. //var startTime = window.performance.now();
  12690. graph._redraw();
  12691. //var end = window.performance.now();
  12692. //time = end - startTime;
  12693. //console.log('Drawing time: ' + time);
  12694. //this.end = window.performance.now();
  12695. //this.time = this.end - this.startTime;
  12696. //console.log('refresh time: ' + this.time);
  12697. //this.startTime = window.performance.now();
  12698. }, this.renderRefreshRate);
  12699. }
  12700. }
  12701. else {
  12702. this._redraw();
  12703. }
  12704. }
  12705. };
  12706. Graph.prototype.singleStep = function() {
  12707. if (this.moving) {
  12708. this._initializeForceCalculation();
  12709. this._discreteStepNodes();
  12710. var vmin = this.constants.minVelocity;
  12711. this.moving = this._isMoving(vmin);
  12712. this._redraw();
  12713. }
  12714. };
  12715. /**
  12716. * Freeze the animation
  12717. */
  12718. Graph.prototype.toggleFreeze = function() {
  12719. if (this.freezeSimulation == false) {
  12720. this.freezeSimulation = true;
  12721. }
  12722. else {
  12723. this.freezeSimulation = false;
  12724. this.start();
  12725. }
  12726. };
  12727. /**
  12728. * Mixin the cluster system and initialize the parameters required.
  12729. *
  12730. * @private
  12731. */
  12732. Graph.prototype._loadClusterSystem = function() {
  12733. this.clusterSession = 0;
  12734. this.hubThreshold = 5;
  12735. for (var mixinFunction in ClusterMixin) {
  12736. if (ClusterMixin.hasOwnProperty(mixinFunction)) {
  12737. Graph.prototype[mixinFunction] = ClusterMixin[mixinFunction];
  12738. }
  12739. }
  12740. }
  12741. /**
  12742. * Mixin the sector system and initialize the parameters required
  12743. *
  12744. * @private
  12745. */
  12746. Graph.prototype._loadSectorSystem = function() {
  12747. this.sectors = {};
  12748. this.activeSector = ["default"];
  12749. this.sectors["active"] = {};
  12750. this.sectors["active"]["default"] = {"nodes":{},
  12751. "edges":{},
  12752. "nodeIndices":[],
  12753. "formationScale": 1.0,
  12754. "drawingNode": undefined};
  12755. this.sectors["frozen"] = {};
  12756. this.sectors["UI"] = {"nodes":{},
  12757. "edges":{},
  12758. "nodeIndices":[],
  12759. "formationScale": 1.0,
  12760. "drawingNode": undefined};
  12761. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  12762. for (var mixinFunction in SectorMixin) {
  12763. if (SectorMixin.hasOwnProperty(mixinFunction)) {
  12764. Graph.prototype[mixinFunction] = SectorMixin[mixinFunction];
  12765. }
  12766. }
  12767. };
  12768. /**
  12769. * Mixin the selection system and initialize the parameters required
  12770. *
  12771. * @private
  12772. */
  12773. Graph.prototype._loadSelectionSystem = function() {
  12774. this.selection = [];
  12775. this.selectionObj = {};
  12776. for (var mixinFunction in SelectionMixin) {
  12777. if (SelectionMixin.hasOwnProperty(mixinFunction)) {
  12778. Graph.prototype[mixinFunction] = SelectionMixin[mixinFunction];
  12779. }
  12780. }
  12781. }
  12782. Graph.prototype._relocateUI = function() {
  12783. // empty, will be overloaded when loading the UI system
  12784. }
  12785. /**
  12786. * Mixin the UI (User Interface) system and initialize the parameters required
  12787. *
  12788. * @private
  12789. */
  12790. Graph.prototype._loadUISystem = function() {
  12791. for (var mixinFunction in UIMixin) {
  12792. if (UIMixin.hasOwnProperty(mixinFunction)) {
  12793. Graph.prototype[mixinFunction] = UIMixin[mixinFunction];
  12794. }
  12795. }
  12796. this._loadUIElements();
  12797. if (this.constants.UI.enabled == true) {
  12798. this._createKeyBinds();
  12799. }
  12800. }
  12801. /**
  12802. * vis.js module exports
  12803. */
  12804. var vis = {
  12805. util: util,
  12806. events: events,
  12807. Controller: Controller,
  12808. DataSet: DataSet,
  12809. DataView: DataView,
  12810. Range: Range,
  12811. Stack: Stack,
  12812. TimeStep: TimeStep,
  12813. EventBus: EventBus,
  12814. components: {
  12815. items: {
  12816. Item: Item,
  12817. ItemBox: ItemBox,
  12818. ItemPoint: ItemPoint,
  12819. ItemRange: ItemRange
  12820. },
  12821. Component: Component,
  12822. Panel: Panel,
  12823. RootPanel: RootPanel,
  12824. ItemSet: ItemSet,
  12825. TimeAxis: TimeAxis
  12826. },
  12827. graph: {
  12828. Node: Node,
  12829. Edge: Edge,
  12830. Popup: Popup,
  12831. Groups: Groups,
  12832. Images: Images
  12833. },
  12834. Timeline: Timeline,
  12835. Graph: Graph
  12836. };
  12837. /**
  12838. * CommonJS module exports
  12839. */
  12840. if (typeof exports !== 'undefined') {
  12841. exports = vis;
  12842. }
  12843. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  12844. module.exports = vis;
  12845. }
  12846. /**
  12847. * AMD module exports
  12848. */
  12849. if (typeof(define) === 'function') {
  12850. define(function () {
  12851. return vis;
  12852. });
  12853. }
  12854. /**
  12855. * Window exports
  12856. */
  12857. if (typeof window !== 'undefined') {
  12858. // attach the module to the window, load as a regular javascript file
  12859. window['vis'] = vis;
  12860. }
  12861. },{"hammerjs":2,"moment":3,"mouseTrap":4}],2:[function(require,module,exports){
  12862. /*! Hammer.JS - v1.0.5 - 2013-04-07
  12863. * http://eightmedia.github.com/hammer.js
  12864. *
  12865. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  12866. * Licensed under the MIT license */
  12867. (function(window, undefined) {
  12868. 'use strict';
  12869. /**
  12870. * Hammer
  12871. * use this to create instances
  12872. * @param {HTMLElement} element
  12873. * @param {Object} options
  12874. * @returns {Hammer.Instance}
  12875. * @constructor
  12876. */
  12877. var Hammer = function(element, options) {
  12878. return new Hammer.Instance(element, options || {});
  12879. };
  12880. // default settings
  12881. Hammer.defaults = {
  12882. // add styles and attributes to the element to prevent the browser from doing
  12883. // its native behavior. this doesnt prevent the scrolling, but cancels
  12884. // the contextmenu, tap highlighting etc
  12885. // set to false to disable this
  12886. stop_browser_behavior: {
  12887. // this also triggers onselectstart=false for IE
  12888. userSelect: 'none',
  12889. // this makes the element blocking in IE10 >, you could experiment with the value
  12890. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  12891. touchAction: 'none',
  12892. touchCallout: 'none',
  12893. contentZooming: 'none',
  12894. userDrag: 'none',
  12895. tapHighlightColor: 'rgba(0,0,0,0)'
  12896. }
  12897. // more settings are defined per gesture at gestures.js
  12898. };
  12899. // detect touchevents
  12900. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  12901. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  12902. // dont use mouseevents on mobile devices
  12903. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  12904. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  12905. // eventtypes per touchevent (start, move, end)
  12906. // are filled by Hammer.event.determineEventTypes on setup
  12907. Hammer.EVENT_TYPES = {};
  12908. // direction defines
  12909. Hammer.DIRECTION_DOWN = 'down';
  12910. Hammer.DIRECTION_LEFT = 'left';
  12911. Hammer.DIRECTION_UP = 'up';
  12912. Hammer.DIRECTION_RIGHT = 'right';
  12913. // pointer type
  12914. Hammer.POINTER_MOUSE = 'mouse';
  12915. Hammer.POINTER_TOUCH = 'touch';
  12916. Hammer.POINTER_PEN = 'pen';
  12917. // touch event defines
  12918. Hammer.EVENT_START = 'start';
  12919. Hammer.EVENT_MOVE = 'move';
  12920. Hammer.EVENT_END = 'end';
  12921. // hammer document where the base events are added at
  12922. Hammer.DOCUMENT = document;
  12923. // plugins namespace
  12924. Hammer.plugins = {};
  12925. // if the window events are set...
  12926. Hammer.READY = false;
  12927. /**
  12928. * setup events to detect gestures on the document
  12929. */
  12930. function setup() {
  12931. if(Hammer.READY) {
  12932. return;
  12933. }
  12934. // find what eventtypes we add listeners to
  12935. Hammer.event.determineEventTypes();
  12936. // Register all gestures inside Hammer.gestures
  12937. for(var name in Hammer.gestures) {
  12938. if(Hammer.gestures.hasOwnProperty(name)) {
  12939. Hammer.detection.register(Hammer.gestures[name]);
  12940. }
  12941. }
  12942. // Add touch events on the document
  12943. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  12944. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  12945. // Hammer is ready...!
  12946. Hammer.READY = true;
  12947. }
  12948. /**
  12949. * create new hammer instance
  12950. * all methods should return the instance itself, so it is chainable.
  12951. * @param {HTMLElement} element
  12952. * @param {Object} [options={}]
  12953. * @returns {Hammer.Instance}
  12954. * @constructor
  12955. */
  12956. Hammer.Instance = function(element, options) {
  12957. var self = this;
  12958. // setup HammerJS window events and register all gestures
  12959. // this also sets up the default options
  12960. setup();
  12961. this.element = element;
  12962. // start/stop detection option
  12963. this.enabled = true;
  12964. // merge options
  12965. this.options = Hammer.utils.extend(
  12966. Hammer.utils.extend({}, Hammer.defaults),
  12967. options || {});
  12968. // add some css to the element to prevent the browser from doing its native behavoir
  12969. if(this.options.stop_browser_behavior) {
  12970. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  12971. }
  12972. // start detection on touchstart
  12973. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  12974. if(self.enabled) {
  12975. Hammer.detection.startDetect(self, ev);
  12976. }
  12977. });
  12978. // return instance
  12979. return this;
  12980. };
  12981. Hammer.Instance.prototype = {
  12982. /**
  12983. * bind events to the instance
  12984. * @param {String} gesture
  12985. * @param {Function} handler
  12986. * @returns {Hammer.Instance}
  12987. */
  12988. on: function onEvent(gesture, handler){
  12989. var gestures = gesture.split(' ');
  12990. for(var t=0; t<gestures.length; t++) {
  12991. this.element.addEventListener(gestures[t], handler, false);
  12992. }
  12993. return this;
  12994. },
  12995. /**
  12996. * unbind events to the instance
  12997. * @param {String} gesture
  12998. * @param {Function} handler
  12999. * @returns {Hammer.Instance}
  13000. */
  13001. off: function offEvent(gesture, handler){
  13002. var gestures = gesture.split(' ');
  13003. for(var t=0; t<gestures.length; t++) {
  13004. this.element.removeEventListener(gestures[t], handler, false);
  13005. }
  13006. return this;
  13007. },
  13008. /**
  13009. * trigger gesture event
  13010. * @param {String} gesture
  13011. * @param {Object} eventData
  13012. * @returns {Hammer.Instance}
  13013. */
  13014. trigger: function triggerEvent(gesture, eventData){
  13015. // create DOM event
  13016. var event = Hammer.DOCUMENT.createEvent('Event');
  13017. event.initEvent(gesture, true, true);
  13018. event.gesture = eventData;
  13019. // trigger on the target if it is in the instance element,
  13020. // this is for event delegation tricks
  13021. var element = this.element;
  13022. if(Hammer.utils.hasParent(eventData.target, element)) {
  13023. element = eventData.target;
  13024. }
  13025. element.dispatchEvent(event);
  13026. return this;
  13027. },
  13028. /**
  13029. * enable of disable hammer.js detection
  13030. * @param {Boolean} state
  13031. * @returns {Hammer.Instance}
  13032. */
  13033. enable: function enable(state) {
  13034. this.enabled = state;
  13035. return this;
  13036. }
  13037. };
  13038. /**
  13039. * this holds the last move event,
  13040. * used to fix empty touchend issue
  13041. * see the onTouch event for an explanation
  13042. * @type {Object}
  13043. */
  13044. var last_move_event = null;
  13045. /**
  13046. * when the mouse is hold down, this is true
  13047. * @type {Boolean}
  13048. */
  13049. var enable_detect = false;
  13050. /**
  13051. * when touch events have been fired, this is true
  13052. * @type {Boolean}
  13053. */
  13054. var touch_triggered = false;
  13055. Hammer.event = {
  13056. /**
  13057. * simple addEventListener
  13058. * @param {HTMLElement} element
  13059. * @param {String} type
  13060. * @param {Function} handler
  13061. */
  13062. bindDom: function(element, type, handler) {
  13063. var types = type.split(' ');
  13064. for(var t=0; t<types.length; t++) {
  13065. element.addEventListener(types[t], handler, false);
  13066. }
  13067. },
  13068. /**
  13069. * touch events with mouse fallback
  13070. * @param {HTMLElement} element
  13071. * @param {String} eventType like Hammer.EVENT_MOVE
  13072. * @param {Function} handler
  13073. */
  13074. onTouch: function onTouch(element, eventType, handler) {
  13075. var self = this;
  13076. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  13077. var sourceEventType = ev.type.toLowerCase();
  13078. // onmouseup, but when touchend has been fired we do nothing.
  13079. // this is for touchdevices which also fire a mouseup on touchend
  13080. if(sourceEventType.match(/mouse/) && touch_triggered) {
  13081. return;
  13082. }
  13083. // mousebutton must be down or a touch event
  13084. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  13085. sourceEventType.match(/pointerdown/) || // pointerevents touch
  13086. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  13087. ){
  13088. enable_detect = true;
  13089. }
  13090. // we are in a touch event, set the touch triggered bool to true,
  13091. // this for the conflicts that may occur on ios and android
  13092. if(sourceEventType.match(/touch|pointer/)) {
  13093. touch_triggered = true;
  13094. }
  13095. // count the total touches on the screen
  13096. var count_touches = 0;
  13097. // when touch has been triggered in this detection session
  13098. // and we are now handling a mouse event, we stop that to prevent conflicts
  13099. if(enable_detect) {
  13100. // update pointerevent
  13101. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  13102. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  13103. }
  13104. // touch
  13105. else if(sourceEventType.match(/touch/)) {
  13106. count_touches = ev.touches.length;
  13107. }
  13108. // mouse
  13109. else if(!touch_triggered) {
  13110. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  13111. }
  13112. // if we are in a end event, but when we remove one touch and
  13113. // we still have enough, set eventType to move
  13114. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  13115. eventType = Hammer.EVENT_MOVE;
  13116. }
  13117. // no touches, force the end event
  13118. else if(!count_touches) {
  13119. eventType = Hammer.EVENT_END;
  13120. }
  13121. // because touchend has no touches, and we often want to use these in our gestures,
  13122. // we send the last move event as our eventData in touchend
  13123. if(!count_touches && last_move_event !== null) {
  13124. ev = last_move_event;
  13125. }
  13126. // store the last move event
  13127. else {
  13128. last_move_event = ev;
  13129. }
  13130. // trigger the handler
  13131. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  13132. // remove pointerevent from list
  13133. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  13134. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  13135. }
  13136. }
  13137. //debug(sourceEventType +" "+ eventType);
  13138. // on the end we reset everything
  13139. if(!count_touches) {
  13140. last_move_event = null;
  13141. enable_detect = false;
  13142. touch_triggered = false;
  13143. Hammer.PointerEvent.reset();
  13144. }
  13145. });
  13146. },
  13147. /**
  13148. * we have different events for each device/browser
  13149. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  13150. */
  13151. determineEventTypes: function determineEventTypes() {
  13152. // determine the eventtype we want to set
  13153. var types;
  13154. // pointerEvents magic
  13155. if(Hammer.HAS_POINTEREVENTS) {
  13156. types = Hammer.PointerEvent.getEvents();
  13157. }
  13158. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  13159. else if(Hammer.NO_MOUSEEVENTS) {
  13160. types = [
  13161. 'touchstart',
  13162. 'touchmove',
  13163. 'touchend touchcancel'];
  13164. }
  13165. // for non pointer events browsers and mixed browsers,
  13166. // like chrome on windows8 touch laptop
  13167. else {
  13168. types = [
  13169. 'touchstart mousedown',
  13170. 'touchmove mousemove',
  13171. 'touchend touchcancel mouseup'];
  13172. }
  13173. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  13174. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  13175. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  13176. },
  13177. /**
  13178. * create touchlist depending on the event
  13179. * @param {Object} ev
  13180. * @param {String} eventType used by the fakemultitouch plugin
  13181. */
  13182. getTouchList: function getTouchList(ev/*, eventType*/) {
  13183. // get the fake pointerEvent touchlist
  13184. if(Hammer.HAS_POINTEREVENTS) {
  13185. return Hammer.PointerEvent.getTouchList();
  13186. }
  13187. // get the touchlist
  13188. else if(ev.touches) {
  13189. return ev.touches;
  13190. }
  13191. // make fake touchlist from mouse position
  13192. else {
  13193. return [{
  13194. identifier: 1,
  13195. pageX: ev.pageX,
  13196. pageY: ev.pageY,
  13197. target: ev.target
  13198. }];
  13199. }
  13200. },
  13201. /**
  13202. * collect event data for Hammer js
  13203. * @param {HTMLElement} element
  13204. * @param {String} eventType like Hammer.EVENT_MOVE
  13205. * @param {Object} eventData
  13206. */
  13207. collectEventData: function collectEventData(element, eventType, ev) {
  13208. var touches = this.getTouchList(ev, eventType);
  13209. // find out pointerType
  13210. var pointerType = Hammer.POINTER_TOUCH;
  13211. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  13212. pointerType = Hammer.POINTER_MOUSE;
  13213. }
  13214. return {
  13215. center : Hammer.utils.getCenter(touches),
  13216. timeStamp : new Date().getTime(),
  13217. target : ev.target,
  13218. touches : touches,
  13219. eventType : eventType,
  13220. pointerType : pointerType,
  13221. srcEvent : ev,
  13222. /**
  13223. * prevent the browser default actions
  13224. * mostly used to disable scrolling of the browser
  13225. */
  13226. preventDefault: function() {
  13227. if(this.srcEvent.preventManipulation) {
  13228. this.srcEvent.preventManipulation();
  13229. }
  13230. if(this.srcEvent.preventDefault) {
  13231. this.srcEvent.preventDefault();
  13232. }
  13233. },
  13234. /**
  13235. * stop bubbling the event up to its parents
  13236. */
  13237. stopPropagation: function() {
  13238. this.srcEvent.stopPropagation();
  13239. },
  13240. /**
  13241. * immediately stop gesture detection
  13242. * might be useful after a swipe was detected
  13243. * @return {*}
  13244. */
  13245. stopDetect: function() {
  13246. return Hammer.detection.stopDetect();
  13247. }
  13248. };
  13249. }
  13250. };
  13251. Hammer.PointerEvent = {
  13252. /**
  13253. * holds all pointers
  13254. * @type {Object}
  13255. */
  13256. pointers: {},
  13257. /**
  13258. * get a list of pointers
  13259. * @returns {Array} touchlist
  13260. */
  13261. getTouchList: function() {
  13262. var self = this;
  13263. var touchlist = [];
  13264. // we can use forEach since pointerEvents only is in IE10
  13265. Object.keys(self.pointers).sort().forEach(function(id) {
  13266. touchlist.push(self.pointers[id]);
  13267. });
  13268. return touchlist;
  13269. },
  13270. /**
  13271. * update the position of a pointer
  13272. * @param {String} type Hammer.EVENT_END
  13273. * @param {Object} pointerEvent
  13274. */
  13275. updatePointer: function(type, pointerEvent) {
  13276. if(type == Hammer.EVENT_END) {
  13277. this.pointers = {};
  13278. }
  13279. else {
  13280. pointerEvent.identifier = pointerEvent.pointerId;
  13281. this.pointers[pointerEvent.pointerId] = pointerEvent;
  13282. }
  13283. return Object.keys(this.pointers).length;
  13284. },
  13285. /**
  13286. * check if ev matches pointertype
  13287. * @param {String} pointerType Hammer.POINTER_MOUSE
  13288. * @param {PointerEvent} ev
  13289. */
  13290. matchType: function(pointerType, ev) {
  13291. if(!ev.pointerType) {
  13292. return false;
  13293. }
  13294. var types = {};
  13295. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  13296. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  13297. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  13298. return types[pointerType];
  13299. },
  13300. /**
  13301. * get events
  13302. */
  13303. getEvents: function() {
  13304. return [
  13305. 'pointerdown MSPointerDown',
  13306. 'pointermove MSPointerMove',
  13307. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  13308. ];
  13309. },
  13310. /**
  13311. * reset the list
  13312. */
  13313. reset: function() {
  13314. this.pointers = {};
  13315. }
  13316. };
  13317. Hammer.utils = {
  13318. /**
  13319. * extend method,
  13320. * also used for cloning when dest is an empty object
  13321. * @param {Object} dest
  13322. * @param {Object} src
  13323. * @parm {Boolean} merge do a merge
  13324. * @returns {Object} dest
  13325. */
  13326. extend: function extend(dest, src, merge) {
  13327. for (var key in src) {
  13328. if(dest[key] !== undefined && merge) {
  13329. continue;
  13330. }
  13331. dest[key] = src[key];
  13332. }
  13333. return dest;
  13334. },
  13335. /**
  13336. * find if a node is in the given parent
  13337. * used for event delegation tricks
  13338. * @param {HTMLElement} node
  13339. * @param {HTMLElement} parent
  13340. * @returns {boolean} has_parent
  13341. */
  13342. hasParent: function(node, parent) {
  13343. while(node){
  13344. if(node == parent) {
  13345. return true;
  13346. }
  13347. node = node.parentNode;
  13348. }
  13349. return false;
  13350. },
  13351. /**
  13352. * get the center of all the touches
  13353. * @param {Array} touches
  13354. * @returns {Object} center
  13355. */
  13356. getCenter: function getCenter(touches) {
  13357. var valuesX = [], valuesY = [];
  13358. for(var t= 0,len=touches.length; t<len; t++) {
  13359. valuesX.push(touches[t].pageX);
  13360. valuesY.push(touches[t].pageY);
  13361. }
  13362. return {
  13363. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  13364. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  13365. };
  13366. },
  13367. /**
  13368. * calculate the velocity between two points
  13369. * @param {Number} delta_time
  13370. * @param {Number} delta_x
  13371. * @param {Number} delta_y
  13372. * @returns {Object} velocity
  13373. */
  13374. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  13375. return {
  13376. x: Math.abs(delta_x / delta_time) || 0,
  13377. y: Math.abs(delta_y / delta_time) || 0
  13378. };
  13379. },
  13380. /**
  13381. * calculate the angle between two coordinates
  13382. * @param {Touch} touch1
  13383. * @param {Touch} touch2
  13384. * @returns {Number} angle
  13385. */
  13386. getAngle: function getAngle(touch1, touch2) {
  13387. var y = touch2.pageY - touch1.pageY,
  13388. x = touch2.pageX - touch1.pageX;
  13389. return Math.atan2(y, x) * 180 / Math.PI;
  13390. },
  13391. /**
  13392. * angle to direction define
  13393. * @param {Touch} touch1
  13394. * @param {Touch} touch2
  13395. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  13396. */
  13397. getDirection: function getDirection(touch1, touch2) {
  13398. var x = Math.abs(touch1.pageX - touch2.pageX),
  13399. y = Math.abs(touch1.pageY - touch2.pageY);
  13400. if(x >= y) {
  13401. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  13402. }
  13403. else {
  13404. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  13405. }
  13406. },
  13407. /**
  13408. * calculate the distance between two touches
  13409. * @param {Touch} touch1
  13410. * @param {Touch} touch2
  13411. * @returns {Number} distance
  13412. */
  13413. getDistance: function getDistance(touch1, touch2) {
  13414. var x = touch2.pageX - touch1.pageX,
  13415. y = touch2.pageY - touch1.pageY;
  13416. return Math.sqrt((x*x) + (y*y));
  13417. },
  13418. /**
  13419. * calculate the scale factor between two touchLists (fingers)
  13420. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  13421. * @param {Array} start
  13422. * @param {Array} end
  13423. * @returns {Number} scale
  13424. */
  13425. getScale: function getScale(start, end) {
  13426. // need two fingers...
  13427. if(start.length >= 2 && end.length >= 2) {
  13428. return this.getDistance(end[0], end[1]) /
  13429. this.getDistance(start[0], start[1]);
  13430. }
  13431. return 1;
  13432. },
  13433. /**
  13434. * calculate the rotation degrees between two touchLists (fingers)
  13435. * @param {Array} start
  13436. * @param {Array} end
  13437. * @returns {Number} rotation
  13438. */
  13439. getRotation: function getRotation(start, end) {
  13440. // need two fingers
  13441. if(start.length >= 2 && end.length >= 2) {
  13442. return this.getAngle(end[1], end[0]) -
  13443. this.getAngle(start[1], start[0]);
  13444. }
  13445. return 0;
  13446. },
  13447. /**
  13448. * boolean if the direction is vertical
  13449. * @param {String} direction
  13450. * @returns {Boolean} is_vertical
  13451. */
  13452. isVertical: function isVertical(direction) {
  13453. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  13454. },
  13455. /**
  13456. * stop browser default behavior with css props
  13457. * @param {HtmlElement} element
  13458. * @param {Object} css_props
  13459. */
  13460. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  13461. var prop,
  13462. vendors = ['webkit','khtml','moz','ms','o',''];
  13463. if(!css_props || !element.style) {
  13464. return;
  13465. }
  13466. // with css properties for modern browsers
  13467. for(var i = 0; i < vendors.length; i++) {
  13468. for(var p in css_props) {
  13469. if(css_props.hasOwnProperty(p)) {
  13470. prop = p;
  13471. // vender prefix at the property
  13472. if(vendors[i]) {
  13473. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  13474. }
  13475. // set the style
  13476. element.style[prop] = css_props[p];
  13477. }
  13478. }
  13479. }
  13480. // also the disable onselectstart
  13481. if(css_props.userSelect == 'none') {
  13482. element.onselectstart = function() {
  13483. return false;
  13484. };
  13485. }
  13486. }
  13487. };
  13488. Hammer.detection = {
  13489. // contains all registred Hammer.gestures in the correct order
  13490. gestures: [],
  13491. // data of the current Hammer.gesture detection session
  13492. current: null,
  13493. // the previous Hammer.gesture session data
  13494. // is a full clone of the previous gesture.current object
  13495. previous: null,
  13496. // when this becomes true, no gestures are fired
  13497. stopped: false,
  13498. /**
  13499. * start Hammer.gesture detection
  13500. * @param {Hammer.Instance} inst
  13501. * @param {Object} eventData
  13502. */
  13503. startDetect: function startDetect(inst, eventData) {
  13504. // already busy with a Hammer.gesture detection on an element
  13505. if(this.current) {
  13506. return;
  13507. }
  13508. this.stopped = false;
  13509. this.current = {
  13510. inst : inst, // reference to HammerInstance we're working for
  13511. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  13512. lastEvent : false, // last eventData
  13513. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  13514. };
  13515. this.detect(eventData);
  13516. },
  13517. /**
  13518. * Hammer.gesture detection
  13519. * @param {Object} eventData
  13520. * @param {Object} eventData
  13521. */
  13522. detect: function detect(eventData) {
  13523. if(!this.current || this.stopped) {
  13524. return;
  13525. }
  13526. // extend event data with calculations about scale, distance etc
  13527. eventData = this.extendEventData(eventData);
  13528. // instance options
  13529. var inst_options = this.current.inst.options;
  13530. // call Hammer.gesture handlers
  13531. for(var g=0,len=this.gestures.length; g<len; g++) {
  13532. var gesture = this.gestures[g];
  13533. // only when the instance options have enabled this gesture
  13534. if(!this.stopped && inst_options[gesture.name] !== false) {
  13535. // if a handler returns false, we stop with the detection
  13536. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  13537. this.stopDetect();
  13538. break;
  13539. }
  13540. }
  13541. }
  13542. // store as previous event event
  13543. if(this.current) {
  13544. this.current.lastEvent = eventData;
  13545. }
  13546. // endevent, but not the last touch, so dont stop
  13547. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  13548. this.stopDetect();
  13549. }
  13550. return eventData;
  13551. },
  13552. /**
  13553. * clear the Hammer.gesture vars
  13554. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  13555. * to stop other Hammer.gestures from being fired
  13556. */
  13557. stopDetect: function stopDetect() {
  13558. // clone current data to the store as the previous gesture
  13559. // used for the double tap gesture, since this is an other gesture detect session
  13560. this.previous = Hammer.utils.extend({}, this.current);
  13561. // reset the current
  13562. this.current = null;
  13563. // stopped!
  13564. this.stopped = true;
  13565. },
  13566. /**
  13567. * extend eventData for Hammer.gestures
  13568. * @param {Object} ev
  13569. * @returns {Object} ev
  13570. */
  13571. extendEventData: function extendEventData(ev) {
  13572. var startEv = this.current.startEvent;
  13573. // if the touches change, set the new touches over the startEvent touches
  13574. // this because touchevents don't have all the touches on touchstart, or the
  13575. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  13576. // but, sometimes it happens that both fingers are touching at the EXACT same time
  13577. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  13578. // extend 1 level deep to get the touchlist with the touch objects
  13579. startEv.touches = [];
  13580. for(var i=0,len=ev.touches.length; i<len; i++) {
  13581. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  13582. }
  13583. }
  13584. var delta_time = ev.timeStamp - startEv.timeStamp,
  13585. delta_x = ev.center.pageX - startEv.center.pageX,
  13586. delta_y = ev.center.pageY - startEv.center.pageY,
  13587. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  13588. Hammer.utils.extend(ev, {
  13589. deltaTime : delta_time,
  13590. deltaX : delta_x,
  13591. deltaY : delta_y,
  13592. velocityX : velocity.x,
  13593. velocityY : velocity.y,
  13594. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  13595. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  13596. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  13597. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  13598. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  13599. startEvent : startEv
  13600. });
  13601. return ev;
  13602. },
  13603. /**
  13604. * register new gesture
  13605. * @param {Object} gesture object, see gestures.js for documentation
  13606. * @returns {Array} gestures
  13607. */
  13608. register: function register(gesture) {
  13609. // add an enable gesture options if there is no given
  13610. var options = gesture.defaults || {};
  13611. if(options[gesture.name] === undefined) {
  13612. options[gesture.name] = true;
  13613. }
  13614. // extend Hammer default options with the Hammer.gesture options
  13615. Hammer.utils.extend(Hammer.defaults, options, true);
  13616. // set its index
  13617. gesture.index = gesture.index || 1000;
  13618. // add Hammer.gesture to the list
  13619. this.gestures.push(gesture);
  13620. // sort the list by index
  13621. this.gestures.sort(function(a, b) {
  13622. if (a.index < b.index) {
  13623. return -1;
  13624. }
  13625. if (a.index > b.index) {
  13626. return 1;
  13627. }
  13628. return 0;
  13629. });
  13630. return this.gestures;
  13631. }
  13632. };
  13633. Hammer.gestures = Hammer.gestures || {};
  13634. /**
  13635. * Custom gestures
  13636. * ==============================
  13637. *
  13638. * Gesture object
  13639. * --------------------
  13640. * The object structure of a gesture:
  13641. *
  13642. * { name: 'mygesture',
  13643. * index: 1337,
  13644. * defaults: {
  13645. * mygesture_option: true
  13646. * }
  13647. * handler: function(type, ev, inst) {
  13648. * // trigger gesture event
  13649. * inst.trigger(this.name, ev);
  13650. * }
  13651. * }
  13652. * @param {String} name
  13653. * this should be the name of the gesture, lowercase
  13654. * it is also being used to disable/enable the gesture per instance config.
  13655. *
  13656. * @param {Number} [index=1000]
  13657. * the index of the gesture, where it is going to be in the stack of gestures detection
  13658. * like when you build an gesture that depends on the drag gesture, it is a good
  13659. * idea to place it after the index of the drag gesture.
  13660. *
  13661. * @param {Object} [defaults={}]
  13662. * the default settings of the gesture. these are added to the instance settings,
  13663. * and can be overruled per instance. you can also add the name of the gesture,
  13664. * but this is also added by default (and set to true).
  13665. *
  13666. * @param {Function} handler
  13667. * this handles the gesture detection of your custom gesture and receives the
  13668. * following arguments:
  13669. *
  13670. * @param {Object} eventData
  13671. * event data containing the following properties:
  13672. * timeStamp {Number} time the event occurred
  13673. * target {HTMLElement} target element
  13674. * touches {Array} touches (fingers, pointers, mouse) on the screen
  13675. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  13676. * center {Object} center position of the touches. contains pageX and pageY
  13677. * deltaTime {Number} the total time of the touches in the screen
  13678. * deltaX {Number} the delta on x axis we haved moved
  13679. * deltaY {Number} the delta on y axis we haved moved
  13680. * velocityX {Number} the velocity on the x
  13681. * velocityY {Number} the velocity on y
  13682. * angle {Number} the angle we are moving
  13683. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  13684. * distance {Number} the distance we haved moved
  13685. * scale {Number} scaling of the touches, needs 2 touches
  13686. * rotation {Number} rotation of the touches, needs 2 touches *
  13687. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  13688. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  13689. * startEvent {Object} contains the same properties as above,
  13690. * but from the first touch. this is used to calculate
  13691. * distances, deltaTime, scaling etc
  13692. *
  13693. * @param {Hammer.Instance} inst
  13694. * the instance we are doing the detection for. you can get the options from
  13695. * the inst.options object and trigger the gesture event by calling inst.trigger
  13696. *
  13697. *
  13698. * Handle gestures
  13699. * --------------------
  13700. * inside the handler you can get/set Hammer.detection.current. This is the current
  13701. * detection session. It has the following properties
  13702. * @param {String} name
  13703. * contains the name of the gesture we have detected. it has not a real function,
  13704. * only to check in other gestures if something is detected.
  13705. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  13706. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  13707. *
  13708. * @readonly
  13709. * @param {Hammer.Instance} inst
  13710. * the instance we do the detection for
  13711. *
  13712. * @readonly
  13713. * @param {Object} startEvent
  13714. * contains the properties of the first gesture detection in this session.
  13715. * Used for calculations about timing, distance, etc.
  13716. *
  13717. * @readonly
  13718. * @param {Object} lastEvent
  13719. * contains all the properties of the last gesture detect in this session.
  13720. *
  13721. * after the gesture detection session has been completed (user has released the screen)
  13722. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  13723. * this is usefull for gestures like doubletap, where you need to know if the
  13724. * previous gesture was a tap
  13725. *
  13726. * options that have been set by the instance can be received by calling inst.options
  13727. *
  13728. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  13729. * The first param is the name of your gesture, the second the event argument
  13730. *
  13731. *
  13732. * Register gestures
  13733. * --------------------
  13734. * When an gesture is added to the Hammer.gestures object, it is auto registered
  13735. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  13736. * manually and pass your gesture object as a param
  13737. *
  13738. */
  13739. /**
  13740. * Hold
  13741. * Touch stays at the same place for x time
  13742. * @events hold
  13743. */
  13744. Hammer.gestures.Hold = {
  13745. name: 'hold',
  13746. index: 10,
  13747. defaults: {
  13748. hold_timeout : 500,
  13749. hold_threshold : 1
  13750. },
  13751. timer: null,
  13752. handler: function holdGesture(ev, inst) {
  13753. switch(ev.eventType) {
  13754. case Hammer.EVENT_START:
  13755. // clear any running timers
  13756. clearTimeout(this.timer);
  13757. // set the gesture so we can check in the timeout if it still is
  13758. Hammer.detection.current.name = this.name;
  13759. // set timer and if after the timeout it still is hold,
  13760. // we trigger the hold event
  13761. this.timer = setTimeout(function() {
  13762. if(Hammer.detection.current.name == 'hold') {
  13763. inst.trigger('hold', ev);
  13764. }
  13765. }, inst.options.hold_timeout);
  13766. break;
  13767. // when you move or end we clear the timer
  13768. case Hammer.EVENT_MOVE:
  13769. if(ev.distance > inst.options.hold_threshold) {
  13770. clearTimeout(this.timer);
  13771. }
  13772. break;
  13773. case Hammer.EVENT_END:
  13774. clearTimeout(this.timer);
  13775. break;
  13776. }
  13777. }
  13778. };
  13779. /**
  13780. * Tap/DoubleTap
  13781. * Quick touch at a place or double at the same place
  13782. * @events tap, doubletap
  13783. */
  13784. Hammer.gestures.Tap = {
  13785. name: 'tap',
  13786. index: 100,
  13787. defaults: {
  13788. tap_max_touchtime : 250,
  13789. tap_max_distance : 10,
  13790. tap_always : true,
  13791. doubletap_distance : 20,
  13792. doubletap_interval : 300
  13793. },
  13794. handler: function tapGesture(ev, inst) {
  13795. if(ev.eventType == Hammer.EVENT_END) {
  13796. // previous gesture, for the double tap since these are two different gesture detections
  13797. var prev = Hammer.detection.previous,
  13798. did_doubletap = false;
  13799. // when the touchtime is higher then the max touch time
  13800. // or when the moving distance is too much
  13801. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  13802. ev.distance > inst.options.tap_max_distance) {
  13803. return;
  13804. }
  13805. // check if double tap
  13806. if(prev && prev.name == 'tap' &&
  13807. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  13808. ev.distance < inst.options.doubletap_distance) {
  13809. inst.trigger('doubletap', ev);
  13810. did_doubletap = true;
  13811. }
  13812. // do a single tap
  13813. if(!did_doubletap || inst.options.tap_always) {
  13814. Hammer.detection.current.name = 'tap';
  13815. inst.trigger(Hammer.detection.current.name, ev);
  13816. }
  13817. }
  13818. }
  13819. };
  13820. /**
  13821. * Swipe
  13822. * triggers swipe events when the end velocity is above the threshold
  13823. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  13824. */
  13825. Hammer.gestures.Swipe = {
  13826. name: 'swipe',
  13827. index: 40,
  13828. defaults: {
  13829. // set 0 for unlimited, but this can conflict with transform
  13830. swipe_max_touches : 1,
  13831. swipe_velocity : 0.7
  13832. },
  13833. handler: function swipeGesture(ev, inst) {
  13834. if(ev.eventType == Hammer.EVENT_END) {
  13835. // max touches
  13836. if(inst.options.swipe_max_touches > 0 &&
  13837. ev.touches.length > inst.options.swipe_max_touches) {
  13838. return;
  13839. }
  13840. // when the distance we moved is too small we skip this gesture
  13841. // or we can be already in dragging
  13842. if(ev.velocityX > inst.options.swipe_velocity ||
  13843. ev.velocityY > inst.options.swipe_velocity) {
  13844. // trigger swipe events
  13845. inst.trigger(this.name, ev);
  13846. inst.trigger(this.name + ev.direction, ev);
  13847. }
  13848. }
  13849. }
  13850. };
  13851. /**
  13852. * Drag
  13853. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  13854. * moving left and right is a good practice. When all the drag events are blocking
  13855. * you disable scrolling on that area.
  13856. * @events drag, drapleft, dragright, dragup, dragdown
  13857. */
  13858. Hammer.gestures.Drag = {
  13859. name: 'drag',
  13860. index: 50,
  13861. defaults: {
  13862. drag_min_distance : 10,
  13863. // set 0 for unlimited, but this can conflict with transform
  13864. drag_max_touches : 1,
  13865. // prevent default browser behavior when dragging occurs
  13866. // be careful with it, it makes the element a blocking element
  13867. // when you are using the drag gesture, it is a good practice to set this true
  13868. drag_block_horizontal : false,
  13869. drag_block_vertical : false,
  13870. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  13871. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  13872. drag_lock_to_axis : false,
  13873. // drag lock only kicks in when distance > drag_lock_min_distance
  13874. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  13875. drag_lock_min_distance : 25
  13876. },
  13877. triggered: false,
  13878. handler: function dragGesture(ev, inst) {
  13879. // current gesture isnt drag, but dragged is true
  13880. // this means an other gesture is busy. now call dragend
  13881. if(Hammer.detection.current.name != this.name && this.triggered) {
  13882. inst.trigger(this.name +'end', ev);
  13883. this.triggered = false;
  13884. return;
  13885. }
  13886. // max touches
  13887. if(inst.options.drag_max_touches > 0 &&
  13888. ev.touches.length > inst.options.drag_max_touches) {
  13889. return;
  13890. }
  13891. switch(ev.eventType) {
  13892. case Hammer.EVENT_START:
  13893. this.triggered = false;
  13894. break;
  13895. case Hammer.EVENT_MOVE:
  13896. // when the distance we moved is too small we skip this gesture
  13897. // or we can be already in dragging
  13898. if(ev.distance < inst.options.drag_min_distance &&
  13899. Hammer.detection.current.name != this.name) {
  13900. return;
  13901. }
  13902. // we are dragging!
  13903. Hammer.detection.current.name = this.name;
  13904. // lock drag to axis?
  13905. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  13906. ev.drag_locked_to_axis = true;
  13907. }
  13908. var last_direction = Hammer.detection.current.lastEvent.direction;
  13909. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  13910. // keep direction on the axis that the drag gesture started on
  13911. if(Hammer.utils.isVertical(last_direction)) {
  13912. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  13913. }
  13914. else {
  13915. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  13916. }
  13917. }
  13918. // first time, trigger dragstart event
  13919. if(!this.triggered) {
  13920. inst.trigger(this.name +'start', ev);
  13921. this.triggered = true;
  13922. }
  13923. // trigger normal event
  13924. inst.trigger(this.name, ev);
  13925. // direction event, like dragdown
  13926. inst.trigger(this.name + ev.direction, ev);
  13927. // block the browser events
  13928. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  13929. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  13930. ev.preventDefault();
  13931. }
  13932. break;
  13933. case Hammer.EVENT_END:
  13934. // trigger dragend
  13935. if(this.triggered) {
  13936. inst.trigger(this.name +'end', ev);
  13937. }
  13938. this.triggered = false;
  13939. break;
  13940. }
  13941. }
  13942. };
  13943. /**
  13944. * Transform
  13945. * User want to scale or rotate with 2 fingers
  13946. * @events transform, pinch, pinchin, pinchout, rotate
  13947. */
  13948. Hammer.gestures.Transform = {
  13949. name: 'transform',
  13950. index: 45,
  13951. defaults: {
  13952. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  13953. transform_min_scale : 0.01,
  13954. // rotation in degrees
  13955. transform_min_rotation : 1,
  13956. // prevent default browser behavior when two touches are on the screen
  13957. // but it makes the element a blocking element
  13958. // when you are using the transform gesture, it is a good practice to set this true
  13959. transform_always_block : false
  13960. },
  13961. triggered: false,
  13962. handler: function transformGesture(ev, inst) {
  13963. // current gesture isnt drag, but dragged is true
  13964. // this means an other gesture is busy. now call dragend
  13965. if(Hammer.detection.current.name != this.name && this.triggered) {
  13966. inst.trigger(this.name +'end', ev);
  13967. this.triggered = false;
  13968. return;
  13969. }
  13970. // atleast multitouch
  13971. if(ev.touches.length < 2) {
  13972. return;
  13973. }
  13974. // prevent default when two fingers are on the screen
  13975. if(inst.options.transform_always_block) {
  13976. ev.preventDefault();
  13977. }
  13978. switch(ev.eventType) {
  13979. case Hammer.EVENT_START:
  13980. this.triggered = false;
  13981. break;
  13982. case Hammer.EVENT_MOVE:
  13983. var scale_threshold = Math.abs(1-ev.scale);
  13984. var rotation_threshold = Math.abs(ev.rotation);
  13985. // when the distance we moved is too small we skip this gesture
  13986. // or we can be already in dragging
  13987. if(scale_threshold < inst.options.transform_min_scale &&
  13988. rotation_threshold < inst.options.transform_min_rotation) {
  13989. return;
  13990. }
  13991. // we are transforming!
  13992. Hammer.detection.current.name = this.name;
  13993. // first time, trigger dragstart event
  13994. if(!this.triggered) {
  13995. inst.trigger(this.name +'start', ev);
  13996. this.triggered = true;
  13997. }
  13998. inst.trigger(this.name, ev); // basic transform event
  13999. // trigger rotate event
  14000. if(rotation_threshold > inst.options.transform_min_rotation) {
  14001. inst.trigger('rotate', ev);
  14002. }
  14003. // trigger pinch event
  14004. if(scale_threshold > inst.options.transform_min_scale) {
  14005. inst.trigger('pinch', ev);
  14006. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  14007. }
  14008. break;
  14009. case Hammer.EVENT_END:
  14010. // trigger dragend
  14011. if(this.triggered) {
  14012. inst.trigger(this.name +'end', ev);
  14013. }
  14014. this.triggered = false;
  14015. break;
  14016. }
  14017. }
  14018. };
  14019. /**
  14020. * Touch
  14021. * Called as first, tells the user has touched the screen
  14022. * @events touch
  14023. */
  14024. Hammer.gestures.Touch = {
  14025. name: 'touch',
  14026. index: -Infinity,
  14027. defaults: {
  14028. // call preventDefault at touchstart, and makes the element blocking by
  14029. // disabling the scrolling of the page, but it improves gestures like
  14030. // transforming and dragging.
  14031. // be careful with using this, it can be very annoying for users to be stuck
  14032. // on the page
  14033. prevent_default: false,
  14034. // disable mouse events, so only touch (or pen!) input triggers events
  14035. prevent_mouseevents: false
  14036. },
  14037. handler: function touchGesture(ev, inst) {
  14038. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  14039. ev.stopDetect();
  14040. return;
  14041. }
  14042. if(inst.options.prevent_default) {
  14043. ev.preventDefault();
  14044. }
  14045. if(ev.eventType == Hammer.EVENT_START) {
  14046. inst.trigger(this.name, ev);
  14047. }
  14048. }
  14049. };
  14050. /**
  14051. * Release
  14052. * Called as last, tells the user has released the screen
  14053. * @events release
  14054. */
  14055. Hammer.gestures.Release = {
  14056. name: 'release',
  14057. index: Infinity,
  14058. handler: function releaseGesture(ev, inst) {
  14059. if(ev.eventType == Hammer.EVENT_END) {
  14060. inst.trigger(this.name, ev);
  14061. }
  14062. }
  14063. };
  14064. // node export
  14065. if(typeof module === 'object' && typeof module.exports === 'object'){
  14066. module.exports = Hammer;
  14067. }
  14068. // just window export
  14069. else {
  14070. window.Hammer = Hammer;
  14071. // requireJS module definition
  14072. if(typeof window.define === 'function' && window.define.amd) {
  14073. window.define('hammer', [], function() {
  14074. return Hammer;
  14075. });
  14076. }
  14077. }
  14078. })(this);
  14079. },{}],3:[function(require,module,exports){
  14080. //! moment.js
  14081. //! version : 2.5.0
  14082. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  14083. //! license : MIT
  14084. //! momentjs.com
  14085. (function (undefined) {
  14086. /************************************
  14087. Constants
  14088. ************************************/
  14089. var moment,
  14090. VERSION = "2.5.0",
  14091. global = this,
  14092. round = Math.round,
  14093. i,
  14094. YEAR = 0,
  14095. MONTH = 1,
  14096. DATE = 2,
  14097. HOUR = 3,
  14098. MINUTE = 4,
  14099. SECOND = 5,
  14100. MILLISECOND = 6,
  14101. // internal storage for language config files
  14102. languages = {},
  14103. // check for nodeJS
  14104. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  14105. // ASP.NET json date format regex
  14106. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  14107. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  14108. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  14109. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  14110. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  14111. // format tokens
  14112. formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,
  14113. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  14114. // parsing token regexes
  14115. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  14116. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  14117. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  14118. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  14119. parseTokenDigits = /\d+/, // nonzero number of digits
  14120. 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.
  14121. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  14122. parseTokenT = /T/i, // T (ISO separator)
  14123. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  14124. //strict parsing regexes
  14125. parseTokenOneDigit = /\d/, // 0 - 9
  14126. parseTokenTwoDigits = /\d\d/, // 00 - 99
  14127. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  14128. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  14129. parseTokenSixDigits = /[+\-]?\d{6}/, // -999,999 - 999,999
  14130. // iso 8601 regex
  14131. // 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)
  14132. isoRegex = /^\s*\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)?)?$/,
  14133. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  14134. isoDates = [
  14135. 'YYYY-MM-DD',
  14136. 'GGGG-[W]WW',
  14137. 'GGGG-[W]WW-E',
  14138. 'YYYY-DDD'
  14139. ],
  14140. // iso time formats and regexes
  14141. isoTimes = [
  14142. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  14143. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  14144. ['HH:mm', /(T| )\d\d:\d\d/],
  14145. ['HH', /(T| )\d\d/]
  14146. ],
  14147. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  14148. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  14149. // getter and setter names
  14150. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  14151. unitMillisecondFactors = {
  14152. 'Milliseconds' : 1,
  14153. 'Seconds' : 1e3,
  14154. 'Minutes' : 6e4,
  14155. 'Hours' : 36e5,
  14156. 'Days' : 864e5,
  14157. 'Months' : 2592e6,
  14158. 'Years' : 31536e6
  14159. },
  14160. unitAliases = {
  14161. ms : 'millisecond',
  14162. s : 'second',
  14163. m : 'minute',
  14164. h : 'hour',
  14165. d : 'day',
  14166. D : 'date',
  14167. w : 'week',
  14168. W : 'isoWeek',
  14169. M : 'month',
  14170. y : 'year',
  14171. DDD : 'dayOfYear',
  14172. e : 'weekday',
  14173. E : 'isoWeekday',
  14174. gg: 'weekYear',
  14175. GG: 'isoWeekYear'
  14176. },
  14177. camelFunctions = {
  14178. dayofyear : 'dayOfYear',
  14179. isoweekday : 'isoWeekday',
  14180. isoweek : 'isoWeek',
  14181. weekyear : 'weekYear',
  14182. isoweekyear : 'isoWeekYear'
  14183. },
  14184. // format function strings
  14185. formatFunctions = {},
  14186. // tokens to ordinalize and pad
  14187. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  14188. paddedTokens = 'M D H h m s w W'.split(' '),
  14189. formatTokenFunctions = {
  14190. M : function () {
  14191. return this.month() + 1;
  14192. },
  14193. MMM : function (format) {
  14194. return this.lang().monthsShort(this, format);
  14195. },
  14196. MMMM : function (format) {
  14197. return this.lang().months(this, format);
  14198. },
  14199. D : function () {
  14200. return this.date();
  14201. },
  14202. DDD : function () {
  14203. return this.dayOfYear();
  14204. },
  14205. d : function () {
  14206. return this.day();
  14207. },
  14208. dd : function (format) {
  14209. return this.lang().weekdaysMin(this, format);
  14210. },
  14211. ddd : function (format) {
  14212. return this.lang().weekdaysShort(this, format);
  14213. },
  14214. dddd : function (format) {
  14215. return this.lang().weekdays(this, format);
  14216. },
  14217. w : function () {
  14218. return this.week();
  14219. },
  14220. W : function () {
  14221. return this.isoWeek();
  14222. },
  14223. YY : function () {
  14224. return leftZeroFill(this.year() % 100, 2);
  14225. },
  14226. YYYY : function () {
  14227. return leftZeroFill(this.year(), 4);
  14228. },
  14229. YYYYY : function () {
  14230. return leftZeroFill(this.year(), 5);
  14231. },
  14232. YYYYYY : function () {
  14233. var y = this.year(), sign = y >= 0 ? '+' : '-';
  14234. return sign + leftZeroFill(Math.abs(y), 6);
  14235. },
  14236. gg : function () {
  14237. return leftZeroFill(this.weekYear() % 100, 2);
  14238. },
  14239. gggg : function () {
  14240. return this.weekYear();
  14241. },
  14242. ggggg : function () {
  14243. return leftZeroFill(this.weekYear(), 5);
  14244. },
  14245. GG : function () {
  14246. return leftZeroFill(this.isoWeekYear() % 100, 2);
  14247. },
  14248. GGGG : function () {
  14249. return this.isoWeekYear();
  14250. },
  14251. GGGGG : function () {
  14252. return leftZeroFill(this.isoWeekYear(), 5);
  14253. },
  14254. e : function () {
  14255. return this.weekday();
  14256. },
  14257. E : function () {
  14258. return this.isoWeekday();
  14259. },
  14260. a : function () {
  14261. return this.lang().meridiem(this.hours(), this.minutes(), true);
  14262. },
  14263. A : function () {
  14264. return this.lang().meridiem(this.hours(), this.minutes(), false);
  14265. },
  14266. H : function () {
  14267. return this.hours();
  14268. },
  14269. h : function () {
  14270. return this.hours() % 12 || 12;
  14271. },
  14272. m : function () {
  14273. return this.minutes();
  14274. },
  14275. s : function () {
  14276. return this.seconds();
  14277. },
  14278. S : function () {
  14279. return toInt(this.milliseconds() / 100);
  14280. },
  14281. SS : function () {
  14282. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  14283. },
  14284. SSS : function () {
  14285. return leftZeroFill(this.milliseconds(), 3);
  14286. },
  14287. SSSS : function () {
  14288. return leftZeroFill(this.milliseconds(), 3);
  14289. },
  14290. Z : function () {
  14291. var a = -this.zone(),
  14292. b = "+";
  14293. if (a < 0) {
  14294. a = -a;
  14295. b = "-";
  14296. }
  14297. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  14298. },
  14299. ZZ : function () {
  14300. var a = -this.zone(),
  14301. b = "+";
  14302. if (a < 0) {
  14303. a = -a;
  14304. b = "-";
  14305. }
  14306. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  14307. },
  14308. z : function () {
  14309. return this.zoneAbbr();
  14310. },
  14311. zz : function () {
  14312. return this.zoneName();
  14313. },
  14314. X : function () {
  14315. return this.unix();
  14316. },
  14317. Q : function () {
  14318. return this.quarter();
  14319. }
  14320. },
  14321. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  14322. function padToken(func, count) {
  14323. return function (a) {
  14324. return leftZeroFill(func.call(this, a), count);
  14325. };
  14326. }
  14327. function ordinalizeToken(func, period) {
  14328. return function (a) {
  14329. return this.lang().ordinal(func.call(this, a), period);
  14330. };
  14331. }
  14332. while (ordinalizeTokens.length) {
  14333. i = ordinalizeTokens.pop();
  14334. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  14335. }
  14336. while (paddedTokens.length) {
  14337. i = paddedTokens.pop();
  14338. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  14339. }
  14340. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  14341. /************************************
  14342. Constructors
  14343. ************************************/
  14344. function Language() {
  14345. }
  14346. // Moment prototype object
  14347. function Moment(config) {
  14348. checkOverflow(config);
  14349. extend(this, config);
  14350. }
  14351. // Duration Constructor
  14352. function Duration(duration) {
  14353. var normalizedInput = normalizeObjectUnits(duration),
  14354. years = normalizedInput.year || 0,
  14355. months = normalizedInput.month || 0,
  14356. weeks = normalizedInput.week || 0,
  14357. days = normalizedInput.day || 0,
  14358. hours = normalizedInput.hour || 0,
  14359. minutes = normalizedInput.minute || 0,
  14360. seconds = normalizedInput.second || 0,
  14361. milliseconds = normalizedInput.millisecond || 0;
  14362. // representation for dateAddRemove
  14363. this._milliseconds = +milliseconds +
  14364. seconds * 1e3 + // 1000
  14365. minutes * 6e4 + // 1000 * 60
  14366. hours * 36e5; // 1000 * 60 * 60
  14367. // Because of dateAddRemove treats 24 hours as different from a
  14368. // day when working around DST, we need to store them separately
  14369. this._days = +days +
  14370. weeks * 7;
  14371. // It is impossible translate months into days without knowing
  14372. // which months you are are talking about, so we have to store
  14373. // it separately.
  14374. this._months = +months +
  14375. years * 12;
  14376. this._data = {};
  14377. this._bubble();
  14378. }
  14379. /************************************
  14380. Helpers
  14381. ************************************/
  14382. function extend(a, b) {
  14383. for (var i in b) {
  14384. if (b.hasOwnProperty(i)) {
  14385. a[i] = b[i];
  14386. }
  14387. }
  14388. if (b.hasOwnProperty("toString")) {
  14389. a.toString = b.toString;
  14390. }
  14391. if (b.hasOwnProperty("valueOf")) {
  14392. a.valueOf = b.valueOf;
  14393. }
  14394. return a;
  14395. }
  14396. function absRound(number) {
  14397. if (number < 0) {
  14398. return Math.ceil(number);
  14399. } else {
  14400. return Math.floor(number);
  14401. }
  14402. }
  14403. // left zero fill a number
  14404. // see http://jsperf.com/left-zero-filling for performance comparison
  14405. function leftZeroFill(number, targetLength, forceSign) {
  14406. var output = Math.abs(number) + '',
  14407. sign = number >= 0;
  14408. while (output.length < targetLength) {
  14409. output = '0' + output;
  14410. }
  14411. return (sign ? (forceSign ? '+' : '') : '-') + output;
  14412. }
  14413. // helper function for _.addTime and _.subtractTime
  14414. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  14415. var milliseconds = duration._milliseconds,
  14416. days = duration._days,
  14417. months = duration._months,
  14418. minutes,
  14419. hours;
  14420. if (milliseconds) {
  14421. mom._d.setTime(+mom._d + milliseconds * isAdding);
  14422. }
  14423. // store the minutes and hours so we can restore them
  14424. if (days || months) {
  14425. minutes = mom.minute();
  14426. hours = mom.hour();
  14427. }
  14428. if (days) {
  14429. mom.date(mom.date() + days * isAdding);
  14430. }
  14431. if (months) {
  14432. mom.month(mom.month() + months * isAdding);
  14433. }
  14434. if (milliseconds && !ignoreUpdateOffset) {
  14435. moment.updateOffset(mom);
  14436. }
  14437. // restore the minutes and hours after possibly changing dst
  14438. if (days || months) {
  14439. mom.minute(minutes);
  14440. mom.hour(hours);
  14441. }
  14442. }
  14443. // check if is an array
  14444. function isArray(input) {
  14445. return Object.prototype.toString.call(input) === '[object Array]';
  14446. }
  14447. function isDate(input) {
  14448. return Object.prototype.toString.call(input) === '[object Date]' ||
  14449. input instanceof Date;
  14450. }
  14451. // compare two arrays, return the number of differences
  14452. function compareArrays(array1, array2, dontConvert) {
  14453. var len = Math.min(array1.length, array2.length),
  14454. lengthDiff = Math.abs(array1.length - array2.length),
  14455. diffs = 0,
  14456. i;
  14457. for (i = 0; i < len; i++) {
  14458. if ((dontConvert && array1[i] !== array2[i]) ||
  14459. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  14460. diffs++;
  14461. }
  14462. }
  14463. return diffs + lengthDiff;
  14464. }
  14465. function normalizeUnits(units) {
  14466. if (units) {
  14467. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  14468. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  14469. }
  14470. return units;
  14471. }
  14472. function normalizeObjectUnits(inputObject) {
  14473. var normalizedInput = {},
  14474. normalizedProp,
  14475. prop;
  14476. for (prop in inputObject) {
  14477. if (inputObject.hasOwnProperty(prop)) {
  14478. normalizedProp = normalizeUnits(prop);
  14479. if (normalizedProp) {
  14480. normalizedInput[normalizedProp] = inputObject[prop];
  14481. }
  14482. }
  14483. }
  14484. return normalizedInput;
  14485. }
  14486. function makeList(field) {
  14487. var count, setter;
  14488. if (field.indexOf('week') === 0) {
  14489. count = 7;
  14490. setter = 'day';
  14491. }
  14492. else if (field.indexOf('month') === 0) {
  14493. count = 12;
  14494. setter = 'month';
  14495. }
  14496. else {
  14497. return;
  14498. }
  14499. moment[field] = function (format, index) {
  14500. var i, getter,
  14501. method = moment.fn._lang[field],
  14502. results = [];
  14503. if (typeof format === 'number') {
  14504. index = format;
  14505. format = undefined;
  14506. }
  14507. getter = function (i) {
  14508. var m = moment().utc().set(setter, i);
  14509. return method.call(moment.fn._lang, m, format || '');
  14510. };
  14511. if (index != null) {
  14512. return getter(index);
  14513. }
  14514. else {
  14515. for (i = 0; i < count; i++) {
  14516. results.push(getter(i));
  14517. }
  14518. return results;
  14519. }
  14520. };
  14521. }
  14522. function toInt(argumentForCoercion) {
  14523. var coercedNumber = +argumentForCoercion,
  14524. value = 0;
  14525. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  14526. if (coercedNumber >= 0) {
  14527. value = Math.floor(coercedNumber);
  14528. } else {
  14529. value = Math.ceil(coercedNumber);
  14530. }
  14531. }
  14532. return value;
  14533. }
  14534. function daysInMonth(year, month) {
  14535. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  14536. }
  14537. function daysInYear(year) {
  14538. return isLeapYear(year) ? 366 : 365;
  14539. }
  14540. function isLeapYear(year) {
  14541. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  14542. }
  14543. function checkOverflow(m) {
  14544. var overflow;
  14545. if (m._a && m._pf.overflow === -2) {
  14546. overflow =
  14547. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  14548. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  14549. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  14550. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  14551. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  14552. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  14553. -1;
  14554. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  14555. overflow = DATE;
  14556. }
  14557. m._pf.overflow = overflow;
  14558. }
  14559. }
  14560. function initializeParsingFlags(config) {
  14561. config._pf = {
  14562. empty : false,
  14563. unusedTokens : [],
  14564. unusedInput : [],
  14565. overflow : -2,
  14566. charsLeftOver : 0,
  14567. nullInput : false,
  14568. invalidMonth : null,
  14569. invalidFormat : false,
  14570. userInvalidated : false,
  14571. iso: false
  14572. };
  14573. }
  14574. function isValid(m) {
  14575. if (m._isValid == null) {
  14576. m._isValid = !isNaN(m._d.getTime()) &&
  14577. m._pf.overflow < 0 &&
  14578. !m._pf.empty &&
  14579. !m._pf.invalidMonth &&
  14580. !m._pf.nullInput &&
  14581. !m._pf.invalidFormat &&
  14582. !m._pf.userInvalidated;
  14583. if (m._strict) {
  14584. m._isValid = m._isValid &&
  14585. m._pf.charsLeftOver === 0 &&
  14586. m._pf.unusedTokens.length === 0;
  14587. }
  14588. }
  14589. return m._isValid;
  14590. }
  14591. function normalizeLanguage(key) {
  14592. return key ? key.toLowerCase().replace('_', '-') : key;
  14593. }
  14594. // Return a moment from input, that is local/utc/zone equivalent to model.
  14595. function makeAs(input, model) {
  14596. return model._isUTC ? moment(input).zone(model._offset || 0) :
  14597. moment(input).local();
  14598. }
  14599. /************************************
  14600. Languages
  14601. ************************************/
  14602. extend(Language.prototype, {
  14603. set : function (config) {
  14604. var prop, i;
  14605. for (i in config) {
  14606. prop = config[i];
  14607. if (typeof prop === 'function') {
  14608. this[i] = prop;
  14609. } else {
  14610. this['_' + i] = prop;
  14611. }
  14612. }
  14613. },
  14614. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  14615. months : function (m) {
  14616. return this._months[m.month()];
  14617. },
  14618. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  14619. monthsShort : function (m) {
  14620. return this._monthsShort[m.month()];
  14621. },
  14622. monthsParse : function (monthName) {
  14623. var i, mom, regex;
  14624. if (!this._monthsParse) {
  14625. this._monthsParse = [];
  14626. }
  14627. for (i = 0; i < 12; i++) {
  14628. // make the regex if we don't have it already
  14629. if (!this._monthsParse[i]) {
  14630. mom = moment.utc([2000, i]);
  14631. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  14632. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  14633. }
  14634. // test the regex
  14635. if (this._monthsParse[i].test(monthName)) {
  14636. return i;
  14637. }
  14638. }
  14639. },
  14640. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  14641. weekdays : function (m) {
  14642. return this._weekdays[m.day()];
  14643. },
  14644. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  14645. weekdaysShort : function (m) {
  14646. return this._weekdaysShort[m.day()];
  14647. },
  14648. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  14649. weekdaysMin : function (m) {
  14650. return this._weekdaysMin[m.day()];
  14651. },
  14652. weekdaysParse : function (weekdayName) {
  14653. var i, mom, regex;
  14654. if (!this._weekdaysParse) {
  14655. this._weekdaysParse = [];
  14656. }
  14657. for (i = 0; i < 7; i++) {
  14658. // make the regex if we don't have it already
  14659. if (!this._weekdaysParse[i]) {
  14660. mom = moment([2000, 1]).day(i);
  14661. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  14662. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  14663. }
  14664. // test the regex
  14665. if (this._weekdaysParse[i].test(weekdayName)) {
  14666. return i;
  14667. }
  14668. }
  14669. },
  14670. _longDateFormat : {
  14671. LT : "h:mm A",
  14672. L : "MM/DD/YYYY",
  14673. LL : "MMMM D YYYY",
  14674. LLL : "MMMM D YYYY LT",
  14675. LLLL : "dddd, MMMM D YYYY LT"
  14676. },
  14677. longDateFormat : function (key) {
  14678. var output = this._longDateFormat[key];
  14679. if (!output && this._longDateFormat[key.toUpperCase()]) {
  14680. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  14681. return val.slice(1);
  14682. });
  14683. this._longDateFormat[key] = output;
  14684. }
  14685. return output;
  14686. },
  14687. isPM : function (input) {
  14688. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  14689. // Using charAt should be more compatible.
  14690. return ((input + '').toLowerCase().charAt(0) === 'p');
  14691. },
  14692. _meridiemParse : /[ap]\.?m?\.?/i,
  14693. meridiem : function (hours, minutes, isLower) {
  14694. if (hours > 11) {
  14695. return isLower ? 'pm' : 'PM';
  14696. } else {
  14697. return isLower ? 'am' : 'AM';
  14698. }
  14699. },
  14700. _calendar : {
  14701. sameDay : '[Today at] LT',
  14702. nextDay : '[Tomorrow at] LT',
  14703. nextWeek : 'dddd [at] LT',
  14704. lastDay : '[Yesterday at] LT',
  14705. lastWeek : '[Last] dddd [at] LT',
  14706. sameElse : 'L'
  14707. },
  14708. calendar : function (key, mom) {
  14709. var output = this._calendar[key];
  14710. return typeof output === 'function' ? output.apply(mom) : output;
  14711. },
  14712. _relativeTime : {
  14713. future : "in %s",
  14714. past : "%s ago",
  14715. s : "a few seconds",
  14716. m : "a minute",
  14717. mm : "%d minutes",
  14718. h : "an hour",
  14719. hh : "%d hours",
  14720. d : "a day",
  14721. dd : "%d days",
  14722. M : "a month",
  14723. MM : "%d months",
  14724. y : "a year",
  14725. yy : "%d years"
  14726. },
  14727. relativeTime : function (number, withoutSuffix, string, isFuture) {
  14728. var output = this._relativeTime[string];
  14729. return (typeof output === 'function') ?
  14730. output(number, withoutSuffix, string, isFuture) :
  14731. output.replace(/%d/i, number);
  14732. },
  14733. pastFuture : function (diff, output) {
  14734. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  14735. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  14736. },
  14737. ordinal : function (number) {
  14738. return this._ordinal.replace("%d", number);
  14739. },
  14740. _ordinal : "%d",
  14741. preparse : function (string) {
  14742. return string;
  14743. },
  14744. postformat : function (string) {
  14745. return string;
  14746. },
  14747. week : function (mom) {
  14748. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  14749. },
  14750. _week : {
  14751. dow : 0, // Sunday is the first day of the week.
  14752. doy : 6 // The week that contains Jan 1st is the first week of the year.
  14753. },
  14754. _invalidDate: 'Invalid date',
  14755. invalidDate: function () {
  14756. return this._invalidDate;
  14757. }
  14758. });
  14759. // Loads a language definition into the `languages` cache. The function
  14760. // takes a key and optionally values. If not in the browser and no values
  14761. // are provided, it will load the language file module. As a convenience,
  14762. // this function also returns the language values.
  14763. function loadLang(key, values) {
  14764. values.abbr = key;
  14765. if (!languages[key]) {
  14766. languages[key] = new Language();
  14767. }
  14768. languages[key].set(values);
  14769. return languages[key];
  14770. }
  14771. // Remove a language from the `languages` cache. Mostly useful in tests.
  14772. function unloadLang(key) {
  14773. delete languages[key];
  14774. }
  14775. // Determines which language definition to use and returns it.
  14776. //
  14777. // With no parameters, it will return the global language. If you
  14778. // pass in a language key, such as 'en', it will return the
  14779. // definition for 'en', so long as 'en' has already been loaded using
  14780. // moment.lang.
  14781. function getLangDefinition(key) {
  14782. var i = 0, j, lang, next, split,
  14783. get = function (k) {
  14784. if (!languages[k] && hasModule) {
  14785. try {
  14786. require('./lang/' + k);
  14787. } catch (e) { }
  14788. }
  14789. return languages[k];
  14790. };
  14791. if (!key) {
  14792. return moment.fn._lang;
  14793. }
  14794. if (!isArray(key)) {
  14795. //short-circuit everything else
  14796. lang = get(key);
  14797. if (lang) {
  14798. return lang;
  14799. }
  14800. key = [key];
  14801. }
  14802. //pick the language from the array
  14803. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  14804. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  14805. while (i < key.length) {
  14806. split = normalizeLanguage(key[i]).split('-');
  14807. j = split.length;
  14808. next = normalizeLanguage(key[i + 1]);
  14809. next = next ? next.split('-') : null;
  14810. while (j > 0) {
  14811. lang = get(split.slice(0, j).join('-'));
  14812. if (lang) {
  14813. return lang;
  14814. }
  14815. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  14816. //the next array item is better than a shallower substring of this one
  14817. break;
  14818. }
  14819. j--;
  14820. }
  14821. i++;
  14822. }
  14823. return moment.fn._lang;
  14824. }
  14825. /************************************
  14826. Formatting
  14827. ************************************/
  14828. function removeFormattingTokens(input) {
  14829. if (input.match(/\[[\s\S]/)) {
  14830. return input.replace(/^\[|\]$/g, "");
  14831. }
  14832. return input.replace(/\\/g, "");
  14833. }
  14834. function makeFormatFunction(format) {
  14835. var array = format.match(formattingTokens), i, length;
  14836. for (i = 0, length = array.length; i < length; i++) {
  14837. if (formatTokenFunctions[array[i]]) {
  14838. array[i] = formatTokenFunctions[array[i]];
  14839. } else {
  14840. array[i] = removeFormattingTokens(array[i]);
  14841. }
  14842. }
  14843. return function (mom) {
  14844. var output = "";
  14845. for (i = 0; i < length; i++) {
  14846. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  14847. }
  14848. return output;
  14849. };
  14850. }
  14851. // format date using native date object
  14852. function formatMoment(m, format) {
  14853. if (!m.isValid()) {
  14854. return m.lang().invalidDate();
  14855. }
  14856. format = expandFormat(format, m.lang());
  14857. if (!formatFunctions[format]) {
  14858. formatFunctions[format] = makeFormatFunction(format);
  14859. }
  14860. return formatFunctions[format](m);
  14861. }
  14862. function expandFormat(format, lang) {
  14863. var i = 5;
  14864. function replaceLongDateFormatTokens(input) {
  14865. return lang.longDateFormat(input) || input;
  14866. }
  14867. localFormattingTokens.lastIndex = 0;
  14868. while (i >= 0 && localFormattingTokens.test(format)) {
  14869. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  14870. localFormattingTokens.lastIndex = 0;
  14871. i -= 1;
  14872. }
  14873. return format;
  14874. }
  14875. /************************************
  14876. Parsing
  14877. ************************************/
  14878. // get the regex to find the next token
  14879. function getParseRegexForToken(token, config) {
  14880. var a, strict = config._strict;
  14881. switch (token) {
  14882. case 'DDDD':
  14883. return parseTokenThreeDigits;
  14884. case 'YYYY':
  14885. case 'GGGG':
  14886. case 'gggg':
  14887. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  14888. case 'YYYYYY':
  14889. case 'YYYYY':
  14890. case 'GGGGG':
  14891. case 'ggggg':
  14892. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  14893. case 'S':
  14894. if (strict) { return parseTokenOneDigit; }
  14895. /* falls through */
  14896. case 'SS':
  14897. if (strict) { return parseTokenTwoDigits; }
  14898. /* falls through */
  14899. case 'SSS':
  14900. case 'DDD':
  14901. return strict ? parseTokenThreeDigits : parseTokenOneToThreeDigits;
  14902. case 'MMM':
  14903. case 'MMMM':
  14904. case 'dd':
  14905. case 'ddd':
  14906. case 'dddd':
  14907. return parseTokenWord;
  14908. case 'a':
  14909. case 'A':
  14910. return getLangDefinition(config._l)._meridiemParse;
  14911. case 'X':
  14912. return parseTokenTimestampMs;
  14913. case 'Z':
  14914. case 'ZZ':
  14915. return parseTokenTimezone;
  14916. case 'T':
  14917. return parseTokenT;
  14918. case 'SSSS':
  14919. return parseTokenDigits;
  14920. case 'MM':
  14921. case 'DD':
  14922. case 'YY':
  14923. case 'GG':
  14924. case 'gg':
  14925. case 'HH':
  14926. case 'hh':
  14927. case 'mm':
  14928. case 'ss':
  14929. case 'ww':
  14930. case 'WW':
  14931. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  14932. case 'M':
  14933. case 'D':
  14934. case 'd':
  14935. case 'H':
  14936. case 'h':
  14937. case 'm':
  14938. case 's':
  14939. case 'w':
  14940. case 'W':
  14941. case 'e':
  14942. case 'E':
  14943. return strict ? parseTokenOneDigit : parseTokenOneOrTwoDigits;
  14944. default :
  14945. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  14946. return a;
  14947. }
  14948. }
  14949. function timezoneMinutesFromString(string) {
  14950. string = string || "";
  14951. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  14952. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  14953. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  14954. minutes = +(parts[1] * 60) + toInt(parts[2]);
  14955. return parts[0] === '+' ? -minutes : minutes;
  14956. }
  14957. // function to convert string input to date
  14958. function addTimeToArrayFromToken(token, input, config) {
  14959. var a, datePartArray = config._a;
  14960. switch (token) {
  14961. // MONTH
  14962. case 'M' : // fall through to MM
  14963. case 'MM' :
  14964. if (input != null) {
  14965. datePartArray[MONTH] = toInt(input) - 1;
  14966. }
  14967. break;
  14968. case 'MMM' : // fall through to MMMM
  14969. case 'MMMM' :
  14970. a = getLangDefinition(config._l).monthsParse(input);
  14971. // if we didn't find a month name, mark the date as invalid.
  14972. if (a != null) {
  14973. datePartArray[MONTH] = a;
  14974. } else {
  14975. config._pf.invalidMonth = input;
  14976. }
  14977. break;
  14978. // DAY OF MONTH
  14979. case 'D' : // fall through to DD
  14980. case 'DD' :
  14981. if (input != null) {
  14982. datePartArray[DATE] = toInt(input);
  14983. }
  14984. break;
  14985. // DAY OF YEAR
  14986. case 'DDD' : // fall through to DDDD
  14987. case 'DDDD' :
  14988. if (input != null) {
  14989. config._dayOfYear = toInt(input);
  14990. }
  14991. break;
  14992. // YEAR
  14993. case 'YY' :
  14994. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  14995. break;
  14996. case 'YYYY' :
  14997. case 'YYYYY' :
  14998. case 'YYYYYY' :
  14999. datePartArray[YEAR] = toInt(input);
  15000. break;
  15001. // AM / PM
  15002. case 'a' : // fall through to A
  15003. case 'A' :
  15004. config._isPm = getLangDefinition(config._l).isPM(input);
  15005. break;
  15006. // 24 HOUR
  15007. case 'H' : // fall through to hh
  15008. case 'HH' : // fall through to hh
  15009. case 'h' : // fall through to hh
  15010. case 'hh' :
  15011. datePartArray[HOUR] = toInt(input);
  15012. break;
  15013. // MINUTE
  15014. case 'm' : // fall through to mm
  15015. case 'mm' :
  15016. datePartArray[MINUTE] = toInt(input);
  15017. break;
  15018. // SECOND
  15019. case 's' : // fall through to ss
  15020. case 'ss' :
  15021. datePartArray[SECOND] = toInt(input);
  15022. break;
  15023. // MILLISECOND
  15024. case 'S' :
  15025. case 'SS' :
  15026. case 'SSS' :
  15027. case 'SSSS' :
  15028. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  15029. break;
  15030. // UNIX TIMESTAMP WITH MS
  15031. case 'X':
  15032. config._d = new Date(parseFloat(input) * 1000);
  15033. break;
  15034. // TIMEZONE
  15035. case 'Z' : // fall through to ZZ
  15036. case 'ZZ' :
  15037. config._useUTC = true;
  15038. config._tzm = timezoneMinutesFromString(input);
  15039. break;
  15040. case 'w':
  15041. case 'ww':
  15042. case 'W':
  15043. case 'WW':
  15044. case 'd':
  15045. case 'dd':
  15046. case 'ddd':
  15047. case 'dddd':
  15048. case 'e':
  15049. case 'E':
  15050. token = token.substr(0, 1);
  15051. /* falls through */
  15052. case 'gg':
  15053. case 'gggg':
  15054. case 'GG':
  15055. case 'GGGG':
  15056. case 'GGGGG':
  15057. token = token.substr(0, 2);
  15058. if (input) {
  15059. config._w = config._w || {};
  15060. config._w[token] = input;
  15061. }
  15062. break;
  15063. }
  15064. }
  15065. // convert an array to a date.
  15066. // the array should mirror the parameters below
  15067. // note: all values past the year are optional and will default to the lowest possible value.
  15068. // [year, month, day , hour, minute, second, millisecond]
  15069. function dateFromConfig(config) {
  15070. var i, date, input = [], currentDate,
  15071. yearToUse, fixYear, w, temp, lang, weekday, week;
  15072. if (config._d) {
  15073. return;
  15074. }
  15075. currentDate = currentDateArray(config);
  15076. //compute day of the year from weeks and weekdays
  15077. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  15078. fixYear = function (val) {
  15079. var int_val = parseInt(val, 10);
  15080. return val ?
  15081. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  15082. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  15083. };
  15084. w = config._w;
  15085. if (w.GG != null || w.W != null || w.E != null) {
  15086. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  15087. }
  15088. else {
  15089. lang = getLangDefinition(config._l);
  15090. weekday = w.d != null ? parseWeekday(w.d, lang) :
  15091. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  15092. week = parseInt(w.w, 10) || 1;
  15093. //if we're parsing 'd', then the low day numbers may be next week
  15094. if (w.d != null && weekday < lang._week.dow) {
  15095. week++;
  15096. }
  15097. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  15098. }
  15099. config._a[YEAR] = temp.year;
  15100. config._dayOfYear = temp.dayOfYear;
  15101. }
  15102. //if the day of the year is set, figure out what it is
  15103. if (config._dayOfYear) {
  15104. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  15105. if (config._dayOfYear > daysInYear(yearToUse)) {
  15106. config._pf._overflowDayOfYear = true;
  15107. }
  15108. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  15109. config._a[MONTH] = date.getUTCMonth();
  15110. config._a[DATE] = date.getUTCDate();
  15111. }
  15112. // Default to current date.
  15113. // * if no year, month, day of month are given, default to today
  15114. // * if day of month is given, default month and year
  15115. // * if month is given, default only year
  15116. // * if year is given, don't default anything
  15117. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  15118. config._a[i] = input[i] = currentDate[i];
  15119. }
  15120. // Zero out whatever was not defaulted, including time
  15121. for (; i < 7; i++) {
  15122. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  15123. }
  15124. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  15125. input[HOUR] += toInt((config._tzm || 0) / 60);
  15126. input[MINUTE] += toInt((config._tzm || 0) % 60);
  15127. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  15128. }
  15129. function dateFromObject(config) {
  15130. var normalizedInput;
  15131. if (config._d) {
  15132. return;
  15133. }
  15134. normalizedInput = normalizeObjectUnits(config._i);
  15135. config._a = [
  15136. normalizedInput.year,
  15137. normalizedInput.month,
  15138. normalizedInput.day,
  15139. normalizedInput.hour,
  15140. normalizedInput.minute,
  15141. normalizedInput.second,
  15142. normalizedInput.millisecond
  15143. ];
  15144. dateFromConfig(config);
  15145. }
  15146. function currentDateArray(config) {
  15147. var now = new Date();
  15148. if (config._useUTC) {
  15149. return [
  15150. now.getUTCFullYear(),
  15151. now.getUTCMonth(),
  15152. now.getUTCDate()
  15153. ];
  15154. } else {
  15155. return [now.getFullYear(), now.getMonth(), now.getDate()];
  15156. }
  15157. }
  15158. // date from string and format string
  15159. function makeDateFromStringAndFormat(config) {
  15160. config._a = [];
  15161. config._pf.empty = true;
  15162. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  15163. var lang = getLangDefinition(config._l),
  15164. string = '' + config._i,
  15165. i, parsedInput, tokens, token, skipped,
  15166. stringLength = string.length,
  15167. totalParsedInputLength = 0;
  15168. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  15169. for (i = 0; i < tokens.length; i++) {
  15170. token = tokens[i];
  15171. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  15172. if (parsedInput) {
  15173. skipped = string.substr(0, string.indexOf(parsedInput));
  15174. if (skipped.length > 0) {
  15175. config._pf.unusedInput.push(skipped);
  15176. }
  15177. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  15178. totalParsedInputLength += parsedInput.length;
  15179. }
  15180. // don't parse if it's not a known token
  15181. if (formatTokenFunctions[token]) {
  15182. if (parsedInput) {
  15183. config._pf.empty = false;
  15184. }
  15185. else {
  15186. config._pf.unusedTokens.push(token);
  15187. }
  15188. addTimeToArrayFromToken(token, parsedInput, config);
  15189. }
  15190. else if (config._strict && !parsedInput) {
  15191. config._pf.unusedTokens.push(token);
  15192. }
  15193. }
  15194. // add remaining unparsed input length to the string
  15195. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  15196. if (string.length > 0) {
  15197. config._pf.unusedInput.push(string);
  15198. }
  15199. // handle am pm
  15200. if (config._isPm && config._a[HOUR] < 12) {
  15201. config._a[HOUR] += 12;
  15202. }
  15203. // if is 12 am, change hours to 0
  15204. if (config._isPm === false && config._a[HOUR] === 12) {
  15205. config._a[HOUR] = 0;
  15206. }
  15207. dateFromConfig(config);
  15208. checkOverflow(config);
  15209. }
  15210. function unescapeFormat(s) {
  15211. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  15212. return p1 || p2 || p3 || p4;
  15213. });
  15214. }
  15215. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  15216. function regexpEscape(s) {
  15217. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  15218. }
  15219. // date from string and array of format strings
  15220. function makeDateFromStringAndArray(config) {
  15221. var tempConfig,
  15222. bestMoment,
  15223. scoreToBeat,
  15224. i,
  15225. currentScore;
  15226. if (config._f.length === 0) {
  15227. config._pf.invalidFormat = true;
  15228. config._d = new Date(NaN);
  15229. return;
  15230. }
  15231. for (i = 0; i < config._f.length; i++) {
  15232. currentScore = 0;
  15233. tempConfig = extend({}, config);
  15234. initializeParsingFlags(tempConfig);
  15235. tempConfig._f = config._f[i];
  15236. makeDateFromStringAndFormat(tempConfig);
  15237. if (!isValid(tempConfig)) {
  15238. continue;
  15239. }
  15240. // if there is any input that was not parsed add a penalty for that format
  15241. currentScore += tempConfig._pf.charsLeftOver;
  15242. //or tokens
  15243. currentScore += tempConfig._pf.unusedTokens.length * 10;
  15244. tempConfig._pf.score = currentScore;
  15245. if (scoreToBeat == null || currentScore < scoreToBeat) {
  15246. scoreToBeat = currentScore;
  15247. bestMoment = tempConfig;
  15248. }
  15249. }
  15250. extend(config, bestMoment || tempConfig);
  15251. }
  15252. // date from iso format
  15253. function makeDateFromString(config) {
  15254. var i,
  15255. string = config._i,
  15256. match = isoRegex.exec(string);
  15257. if (match) {
  15258. config._pf.iso = true;
  15259. for (i = 4; i > 0; i--) {
  15260. if (match[i]) {
  15261. // match[5] should be "T" or undefined
  15262. config._f = isoDates[i - 1] + (match[6] || " ");
  15263. break;
  15264. }
  15265. }
  15266. for (i = 0; i < 4; i++) {
  15267. if (isoTimes[i][1].exec(string)) {
  15268. config._f += isoTimes[i][0];
  15269. break;
  15270. }
  15271. }
  15272. if (string.match(parseTokenTimezone)) {
  15273. config._f += "Z";
  15274. }
  15275. makeDateFromStringAndFormat(config);
  15276. }
  15277. else {
  15278. config._d = new Date(string);
  15279. }
  15280. }
  15281. function makeDateFromInput(config) {
  15282. var input = config._i,
  15283. matched = aspNetJsonRegex.exec(input);
  15284. if (input === undefined) {
  15285. config._d = new Date();
  15286. } else if (matched) {
  15287. config._d = new Date(+matched[1]);
  15288. } else if (typeof input === 'string') {
  15289. makeDateFromString(config);
  15290. } else if (isArray(input)) {
  15291. config._a = input.slice(0);
  15292. dateFromConfig(config);
  15293. } else if (isDate(input)) {
  15294. config._d = new Date(+input);
  15295. } else if (typeof(input) === 'object') {
  15296. dateFromObject(config);
  15297. } else {
  15298. config._d = new Date(input);
  15299. }
  15300. }
  15301. function makeDate(y, m, d, h, M, s, ms) {
  15302. //can't just apply() to create a date:
  15303. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  15304. var date = new Date(y, m, d, h, M, s, ms);
  15305. //the date constructor doesn't accept years < 1970
  15306. if (y < 1970) {
  15307. date.setFullYear(y);
  15308. }
  15309. return date;
  15310. }
  15311. function makeUTCDate(y) {
  15312. var date = new Date(Date.UTC.apply(null, arguments));
  15313. if (y < 1970) {
  15314. date.setUTCFullYear(y);
  15315. }
  15316. return date;
  15317. }
  15318. function parseWeekday(input, language) {
  15319. if (typeof input === 'string') {
  15320. if (!isNaN(input)) {
  15321. input = parseInt(input, 10);
  15322. }
  15323. else {
  15324. input = language.weekdaysParse(input);
  15325. if (typeof input !== 'number') {
  15326. return null;
  15327. }
  15328. }
  15329. }
  15330. return input;
  15331. }
  15332. /************************************
  15333. Relative Time
  15334. ************************************/
  15335. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  15336. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  15337. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  15338. }
  15339. function relativeTime(milliseconds, withoutSuffix, lang) {
  15340. var seconds = round(Math.abs(milliseconds) / 1000),
  15341. minutes = round(seconds / 60),
  15342. hours = round(minutes / 60),
  15343. days = round(hours / 24),
  15344. years = round(days / 365),
  15345. args = seconds < 45 && ['s', seconds] ||
  15346. minutes === 1 && ['m'] ||
  15347. minutes < 45 && ['mm', minutes] ||
  15348. hours === 1 && ['h'] ||
  15349. hours < 22 && ['hh', hours] ||
  15350. days === 1 && ['d'] ||
  15351. days <= 25 && ['dd', days] ||
  15352. days <= 45 && ['M'] ||
  15353. days < 345 && ['MM', round(days / 30)] ||
  15354. years === 1 && ['y'] || ['yy', years];
  15355. args[2] = withoutSuffix;
  15356. args[3] = milliseconds > 0;
  15357. args[4] = lang;
  15358. return substituteTimeAgo.apply({}, args);
  15359. }
  15360. /************************************
  15361. Week of Year
  15362. ************************************/
  15363. // firstDayOfWeek 0 = sun, 6 = sat
  15364. // the day of the week that starts the week
  15365. // (usually sunday or monday)
  15366. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  15367. // the first week is the week that contains the first
  15368. // of this day of the week
  15369. // (eg. ISO weeks use thursday (4))
  15370. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  15371. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  15372. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  15373. adjustedMoment;
  15374. if (daysToDayOfWeek > end) {
  15375. daysToDayOfWeek -= 7;
  15376. }
  15377. if (daysToDayOfWeek < end - 7) {
  15378. daysToDayOfWeek += 7;
  15379. }
  15380. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  15381. return {
  15382. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  15383. year: adjustedMoment.year()
  15384. };
  15385. }
  15386. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  15387. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  15388. // The only solid way to create an iso date from year is to use
  15389. // a string format (Date.UTC handles only years > 1900). Don't ask why
  15390. // it doesn't need Z at the end.
  15391. var d = new Date(leftZeroFill(year, 6, true) + '-01-01').getUTCDay(),
  15392. daysToAdd, dayOfYear;
  15393. weekday = weekday != null ? weekday : firstDayOfWeek;
  15394. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0);
  15395. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  15396. return {
  15397. year: dayOfYear > 0 ? year : year - 1,
  15398. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  15399. };
  15400. }
  15401. /************************************
  15402. Top Level Functions
  15403. ************************************/
  15404. function makeMoment(config) {
  15405. var input = config._i,
  15406. format = config._f;
  15407. if (typeof config._pf === 'undefined') {
  15408. initializeParsingFlags(config);
  15409. }
  15410. if (input === null) {
  15411. return moment.invalid({nullInput: true});
  15412. }
  15413. if (typeof input === 'string') {
  15414. config._i = input = getLangDefinition().preparse(input);
  15415. }
  15416. if (moment.isMoment(input)) {
  15417. config = extend({}, input);
  15418. config._d = new Date(+input._d);
  15419. } else if (format) {
  15420. if (isArray(format)) {
  15421. makeDateFromStringAndArray(config);
  15422. } else {
  15423. makeDateFromStringAndFormat(config);
  15424. }
  15425. } else {
  15426. makeDateFromInput(config);
  15427. }
  15428. return new Moment(config);
  15429. }
  15430. moment = function (input, format, lang, strict) {
  15431. if (typeof(lang) === "boolean") {
  15432. strict = lang;
  15433. lang = undefined;
  15434. }
  15435. return makeMoment({
  15436. _i : input,
  15437. _f : format,
  15438. _l : lang,
  15439. _strict : strict,
  15440. _isUTC : false
  15441. });
  15442. };
  15443. // creating with utc
  15444. moment.utc = function (input, format, lang, strict) {
  15445. var m;
  15446. if (typeof(lang) === "boolean") {
  15447. strict = lang;
  15448. lang = undefined;
  15449. }
  15450. m = makeMoment({
  15451. _useUTC : true,
  15452. _isUTC : true,
  15453. _l : lang,
  15454. _i : input,
  15455. _f : format,
  15456. _strict : strict
  15457. }).utc();
  15458. return m;
  15459. };
  15460. // creating with unix timestamp (in seconds)
  15461. moment.unix = function (input) {
  15462. return moment(input * 1000);
  15463. };
  15464. // duration
  15465. moment.duration = function (input, key) {
  15466. var duration = input,
  15467. // matching against regexp is expensive, do it on demand
  15468. match = null,
  15469. sign,
  15470. ret,
  15471. parseIso;
  15472. if (moment.isDuration(input)) {
  15473. duration = {
  15474. ms: input._milliseconds,
  15475. d: input._days,
  15476. M: input._months
  15477. };
  15478. } else if (typeof input === 'number') {
  15479. duration = {};
  15480. if (key) {
  15481. duration[key] = input;
  15482. } else {
  15483. duration.milliseconds = input;
  15484. }
  15485. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  15486. sign = (match[1] === "-") ? -1 : 1;
  15487. duration = {
  15488. y: 0,
  15489. d: toInt(match[DATE]) * sign,
  15490. h: toInt(match[HOUR]) * sign,
  15491. m: toInt(match[MINUTE]) * sign,
  15492. s: toInt(match[SECOND]) * sign,
  15493. ms: toInt(match[MILLISECOND]) * sign
  15494. };
  15495. } else if (!!(match = isoDurationRegex.exec(input))) {
  15496. sign = (match[1] === "-") ? -1 : 1;
  15497. parseIso = function (inp) {
  15498. // We'd normally use ~~inp for this, but unfortunately it also
  15499. // converts floats to ints.
  15500. // inp may be undefined, so careful calling replace on it.
  15501. var res = inp && parseFloat(inp.replace(',', '.'));
  15502. // apply sign while we're at it
  15503. return (isNaN(res) ? 0 : res) * sign;
  15504. };
  15505. duration = {
  15506. y: parseIso(match[2]),
  15507. M: parseIso(match[3]),
  15508. d: parseIso(match[4]),
  15509. h: parseIso(match[5]),
  15510. m: parseIso(match[6]),
  15511. s: parseIso(match[7]),
  15512. w: parseIso(match[8])
  15513. };
  15514. }
  15515. ret = new Duration(duration);
  15516. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  15517. ret._lang = input._lang;
  15518. }
  15519. return ret;
  15520. };
  15521. // version number
  15522. moment.version = VERSION;
  15523. // default format
  15524. moment.defaultFormat = isoFormat;
  15525. // This function will be called whenever a moment is mutated.
  15526. // It is intended to keep the offset in sync with the timezone.
  15527. moment.updateOffset = function () {};
  15528. // This function will load languages and then set the global language. If
  15529. // no arguments are passed in, it will simply return the current global
  15530. // language key.
  15531. moment.lang = function (key, values) {
  15532. var r;
  15533. if (!key) {
  15534. return moment.fn._lang._abbr;
  15535. }
  15536. if (values) {
  15537. loadLang(normalizeLanguage(key), values);
  15538. } else if (values === null) {
  15539. unloadLang(key);
  15540. key = 'en';
  15541. } else if (!languages[key]) {
  15542. getLangDefinition(key);
  15543. }
  15544. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  15545. return r._abbr;
  15546. };
  15547. // returns language data
  15548. moment.langData = function (key) {
  15549. if (key && key._lang && key._lang._abbr) {
  15550. key = key._lang._abbr;
  15551. }
  15552. return getLangDefinition(key);
  15553. };
  15554. // compare moment object
  15555. moment.isMoment = function (obj) {
  15556. return obj instanceof Moment;
  15557. };
  15558. // for typechecking Duration objects
  15559. moment.isDuration = function (obj) {
  15560. return obj instanceof Duration;
  15561. };
  15562. for (i = lists.length - 1; i >= 0; --i) {
  15563. makeList(lists[i]);
  15564. }
  15565. moment.normalizeUnits = function (units) {
  15566. return normalizeUnits(units);
  15567. };
  15568. moment.invalid = function (flags) {
  15569. var m = moment.utc(NaN);
  15570. if (flags != null) {
  15571. extend(m._pf, flags);
  15572. }
  15573. else {
  15574. m._pf.userInvalidated = true;
  15575. }
  15576. return m;
  15577. };
  15578. moment.parseZone = function (input) {
  15579. return moment(input).parseZone();
  15580. };
  15581. /************************************
  15582. Moment Prototype
  15583. ************************************/
  15584. extend(moment.fn = Moment.prototype, {
  15585. clone : function () {
  15586. return moment(this);
  15587. },
  15588. valueOf : function () {
  15589. return +this._d + ((this._offset || 0) * 60000);
  15590. },
  15591. unix : function () {
  15592. return Math.floor(+this / 1000);
  15593. },
  15594. toString : function () {
  15595. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  15596. },
  15597. toDate : function () {
  15598. return this._offset ? new Date(+this) : this._d;
  15599. },
  15600. toISOString : function () {
  15601. var m = moment(this).utc();
  15602. if (0 < m.year() && m.year() <= 9999) {
  15603. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  15604. } else {
  15605. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  15606. }
  15607. },
  15608. toArray : function () {
  15609. var m = this;
  15610. return [
  15611. m.year(),
  15612. m.month(),
  15613. m.date(),
  15614. m.hours(),
  15615. m.minutes(),
  15616. m.seconds(),
  15617. m.milliseconds()
  15618. ];
  15619. },
  15620. isValid : function () {
  15621. return isValid(this);
  15622. },
  15623. isDSTShifted : function () {
  15624. if (this._a) {
  15625. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  15626. }
  15627. return false;
  15628. },
  15629. parsingFlags : function () {
  15630. return extend({}, this._pf);
  15631. },
  15632. invalidAt: function () {
  15633. return this._pf.overflow;
  15634. },
  15635. utc : function () {
  15636. return this.zone(0);
  15637. },
  15638. local : function () {
  15639. this.zone(0);
  15640. this._isUTC = false;
  15641. return this;
  15642. },
  15643. format : function (inputString) {
  15644. var output = formatMoment(this, inputString || moment.defaultFormat);
  15645. return this.lang().postformat(output);
  15646. },
  15647. add : function (input, val) {
  15648. var dur;
  15649. // switch args to support add('s', 1) and add(1, 's')
  15650. if (typeof input === 'string') {
  15651. dur = moment.duration(+val, input);
  15652. } else {
  15653. dur = moment.duration(input, val);
  15654. }
  15655. addOrSubtractDurationFromMoment(this, dur, 1);
  15656. return this;
  15657. },
  15658. subtract : function (input, val) {
  15659. var dur;
  15660. // switch args to support subtract('s', 1) and subtract(1, 's')
  15661. if (typeof input === 'string') {
  15662. dur = moment.duration(+val, input);
  15663. } else {
  15664. dur = moment.duration(input, val);
  15665. }
  15666. addOrSubtractDurationFromMoment(this, dur, -1);
  15667. return this;
  15668. },
  15669. diff : function (input, units, asFloat) {
  15670. var that = makeAs(input, this),
  15671. zoneDiff = (this.zone() - that.zone()) * 6e4,
  15672. diff, output;
  15673. units = normalizeUnits(units);
  15674. if (units === 'year' || units === 'month') {
  15675. // average number of days in the months in the given dates
  15676. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  15677. // difference in months
  15678. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  15679. // adjust by taking difference in days, average number of days
  15680. // and dst in the given months.
  15681. output += ((this - moment(this).startOf('month')) -
  15682. (that - moment(that).startOf('month'))) / diff;
  15683. // same as above but with zones, to negate all dst
  15684. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  15685. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  15686. if (units === 'year') {
  15687. output = output / 12;
  15688. }
  15689. } else {
  15690. diff = (this - that);
  15691. output = units === 'second' ? diff / 1e3 : // 1000
  15692. units === 'minute' ? diff / 6e4 : // 1000 * 60
  15693. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  15694. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  15695. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  15696. diff;
  15697. }
  15698. return asFloat ? output : absRound(output);
  15699. },
  15700. from : function (time, withoutSuffix) {
  15701. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  15702. },
  15703. fromNow : function (withoutSuffix) {
  15704. return this.from(moment(), withoutSuffix);
  15705. },
  15706. calendar : function () {
  15707. // We want to compare the start of today, vs this.
  15708. // Getting start-of-today depends on whether we're zone'd or not.
  15709. var sod = makeAs(moment(), this).startOf('day'),
  15710. diff = this.diff(sod, 'days', true),
  15711. format = diff < -6 ? 'sameElse' :
  15712. diff < -1 ? 'lastWeek' :
  15713. diff < 0 ? 'lastDay' :
  15714. diff < 1 ? 'sameDay' :
  15715. diff < 2 ? 'nextDay' :
  15716. diff < 7 ? 'nextWeek' : 'sameElse';
  15717. return this.format(this.lang().calendar(format, this));
  15718. },
  15719. isLeapYear : function () {
  15720. return isLeapYear(this.year());
  15721. },
  15722. isDST : function () {
  15723. return (this.zone() < this.clone().month(0).zone() ||
  15724. this.zone() < this.clone().month(5).zone());
  15725. },
  15726. day : function (input) {
  15727. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  15728. if (input != null) {
  15729. input = parseWeekday(input, this.lang());
  15730. return this.add({ d : input - day });
  15731. } else {
  15732. return day;
  15733. }
  15734. },
  15735. month : function (input) {
  15736. var utc = this._isUTC ? 'UTC' : '',
  15737. dayOfMonth;
  15738. if (input != null) {
  15739. if (typeof input === 'string') {
  15740. input = this.lang().monthsParse(input);
  15741. if (typeof input !== 'number') {
  15742. return this;
  15743. }
  15744. }
  15745. dayOfMonth = this.date();
  15746. this.date(1);
  15747. this._d['set' + utc + 'Month'](input);
  15748. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  15749. moment.updateOffset(this);
  15750. return this;
  15751. } else {
  15752. return this._d['get' + utc + 'Month']();
  15753. }
  15754. },
  15755. startOf: function (units) {
  15756. units = normalizeUnits(units);
  15757. // the following switch intentionally omits break keywords
  15758. // to utilize falling through the cases.
  15759. switch (units) {
  15760. case 'year':
  15761. this.month(0);
  15762. /* falls through */
  15763. case 'month':
  15764. this.date(1);
  15765. /* falls through */
  15766. case 'week':
  15767. case 'isoWeek':
  15768. case 'day':
  15769. this.hours(0);
  15770. /* falls through */
  15771. case 'hour':
  15772. this.minutes(0);
  15773. /* falls through */
  15774. case 'minute':
  15775. this.seconds(0);
  15776. /* falls through */
  15777. case 'second':
  15778. this.milliseconds(0);
  15779. /* falls through */
  15780. }
  15781. // weeks are a special case
  15782. if (units === 'week') {
  15783. this.weekday(0);
  15784. } else if (units === 'isoWeek') {
  15785. this.isoWeekday(1);
  15786. }
  15787. return this;
  15788. },
  15789. endOf: function (units) {
  15790. units = normalizeUnits(units);
  15791. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  15792. },
  15793. isAfter: function (input, units) {
  15794. units = typeof units !== 'undefined' ? units : 'millisecond';
  15795. return +this.clone().startOf(units) > +moment(input).startOf(units);
  15796. },
  15797. isBefore: function (input, units) {
  15798. units = typeof units !== 'undefined' ? units : 'millisecond';
  15799. return +this.clone().startOf(units) < +moment(input).startOf(units);
  15800. },
  15801. isSame: function (input, units) {
  15802. units = units || 'ms';
  15803. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  15804. },
  15805. min: function (other) {
  15806. other = moment.apply(null, arguments);
  15807. return other < this ? this : other;
  15808. },
  15809. max: function (other) {
  15810. other = moment.apply(null, arguments);
  15811. return other > this ? this : other;
  15812. },
  15813. zone : function (input) {
  15814. var offset = this._offset || 0;
  15815. if (input != null) {
  15816. if (typeof input === "string") {
  15817. input = timezoneMinutesFromString(input);
  15818. }
  15819. if (Math.abs(input) < 16) {
  15820. input = input * 60;
  15821. }
  15822. this._offset = input;
  15823. this._isUTC = true;
  15824. if (offset !== input) {
  15825. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  15826. }
  15827. } else {
  15828. return this._isUTC ? offset : this._d.getTimezoneOffset();
  15829. }
  15830. return this;
  15831. },
  15832. zoneAbbr : function () {
  15833. return this._isUTC ? "UTC" : "";
  15834. },
  15835. zoneName : function () {
  15836. return this._isUTC ? "Coordinated Universal Time" : "";
  15837. },
  15838. parseZone : function () {
  15839. if (this._tzm) {
  15840. this.zone(this._tzm);
  15841. } else if (typeof this._i === 'string') {
  15842. this.zone(this._i);
  15843. }
  15844. return this;
  15845. },
  15846. hasAlignedHourOffset : function (input) {
  15847. if (!input) {
  15848. input = 0;
  15849. }
  15850. else {
  15851. input = moment(input).zone();
  15852. }
  15853. return (this.zone() - input) % 60 === 0;
  15854. },
  15855. daysInMonth : function () {
  15856. return daysInMonth(this.year(), this.month());
  15857. },
  15858. dayOfYear : function (input) {
  15859. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  15860. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  15861. },
  15862. quarter : function () {
  15863. return Math.ceil((this.month() + 1.0) / 3.0);
  15864. },
  15865. weekYear : function (input) {
  15866. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  15867. return input == null ? year : this.add("y", (input - year));
  15868. },
  15869. isoWeekYear : function (input) {
  15870. var year = weekOfYear(this, 1, 4).year;
  15871. return input == null ? year : this.add("y", (input - year));
  15872. },
  15873. week : function (input) {
  15874. var week = this.lang().week(this);
  15875. return input == null ? week : this.add("d", (input - week) * 7);
  15876. },
  15877. isoWeek : function (input) {
  15878. var week = weekOfYear(this, 1, 4).week;
  15879. return input == null ? week : this.add("d", (input - week) * 7);
  15880. },
  15881. weekday : function (input) {
  15882. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  15883. return input == null ? weekday : this.add("d", input - weekday);
  15884. },
  15885. isoWeekday : function (input) {
  15886. // behaves the same as moment#day except
  15887. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  15888. // as a setter, sunday should belong to the previous week.
  15889. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  15890. },
  15891. get : function (units) {
  15892. units = normalizeUnits(units);
  15893. return this[units]();
  15894. },
  15895. set : function (units, value) {
  15896. units = normalizeUnits(units);
  15897. if (typeof this[units] === 'function') {
  15898. this[units](value);
  15899. }
  15900. return this;
  15901. },
  15902. // If passed a language key, it will set the language for this
  15903. // instance. Otherwise, it will return the language configuration
  15904. // variables for this instance.
  15905. lang : function (key) {
  15906. if (key === undefined) {
  15907. return this._lang;
  15908. } else {
  15909. this._lang = getLangDefinition(key);
  15910. return this;
  15911. }
  15912. }
  15913. });
  15914. // helper for adding shortcuts
  15915. function makeGetterAndSetter(name, key) {
  15916. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  15917. var utc = this._isUTC ? 'UTC' : '';
  15918. if (input != null) {
  15919. this._d['set' + utc + key](input);
  15920. moment.updateOffset(this);
  15921. return this;
  15922. } else {
  15923. return this._d['get' + utc + key]();
  15924. }
  15925. };
  15926. }
  15927. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  15928. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  15929. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  15930. }
  15931. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  15932. makeGetterAndSetter('year', 'FullYear');
  15933. // add plural methods
  15934. moment.fn.days = moment.fn.day;
  15935. moment.fn.months = moment.fn.month;
  15936. moment.fn.weeks = moment.fn.week;
  15937. moment.fn.isoWeeks = moment.fn.isoWeek;
  15938. // add aliased format methods
  15939. moment.fn.toJSON = moment.fn.toISOString;
  15940. /************************************
  15941. Duration Prototype
  15942. ************************************/
  15943. extend(moment.duration.fn = Duration.prototype, {
  15944. _bubble : function () {
  15945. var milliseconds = this._milliseconds,
  15946. days = this._days,
  15947. months = this._months,
  15948. data = this._data,
  15949. seconds, minutes, hours, years;
  15950. // The following code bubbles up values, see the tests for
  15951. // examples of what that means.
  15952. data.milliseconds = milliseconds % 1000;
  15953. seconds = absRound(milliseconds / 1000);
  15954. data.seconds = seconds % 60;
  15955. minutes = absRound(seconds / 60);
  15956. data.minutes = minutes % 60;
  15957. hours = absRound(minutes / 60);
  15958. data.hours = hours % 24;
  15959. days += absRound(hours / 24);
  15960. data.days = days % 30;
  15961. months += absRound(days / 30);
  15962. data.months = months % 12;
  15963. years = absRound(months / 12);
  15964. data.years = years;
  15965. },
  15966. weeks : function () {
  15967. return absRound(this.days() / 7);
  15968. },
  15969. valueOf : function () {
  15970. return this._milliseconds +
  15971. this._days * 864e5 +
  15972. (this._months % 12) * 2592e6 +
  15973. toInt(this._months / 12) * 31536e6;
  15974. },
  15975. humanize : function (withSuffix) {
  15976. var difference = +this,
  15977. output = relativeTime(difference, !withSuffix, this.lang());
  15978. if (withSuffix) {
  15979. output = this.lang().pastFuture(difference, output);
  15980. }
  15981. return this.lang().postformat(output);
  15982. },
  15983. add : function (input, val) {
  15984. // supports only 2.0-style add(1, 's') or add(moment)
  15985. var dur = moment.duration(input, val);
  15986. this._milliseconds += dur._milliseconds;
  15987. this._days += dur._days;
  15988. this._months += dur._months;
  15989. this._bubble();
  15990. return this;
  15991. },
  15992. subtract : function (input, val) {
  15993. var dur = moment.duration(input, val);
  15994. this._milliseconds -= dur._milliseconds;
  15995. this._days -= dur._days;
  15996. this._months -= dur._months;
  15997. this._bubble();
  15998. return this;
  15999. },
  16000. get : function (units) {
  16001. units = normalizeUnits(units);
  16002. return this[units.toLowerCase() + 's']();
  16003. },
  16004. as : function (units) {
  16005. units = normalizeUnits(units);
  16006. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  16007. },
  16008. lang : moment.fn.lang,
  16009. toIsoString : function () {
  16010. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  16011. var years = Math.abs(this.years()),
  16012. months = Math.abs(this.months()),
  16013. days = Math.abs(this.days()),
  16014. hours = Math.abs(this.hours()),
  16015. minutes = Math.abs(this.minutes()),
  16016. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  16017. if (!this.asSeconds()) {
  16018. // this is the same as C#'s (Noda) and python (isodate)...
  16019. // but not other JS (goog.date)
  16020. return 'P0D';
  16021. }
  16022. return (this.asSeconds() < 0 ? '-' : '') +
  16023. 'P' +
  16024. (years ? years + 'Y' : '') +
  16025. (months ? months + 'M' : '') +
  16026. (days ? days + 'D' : '') +
  16027. ((hours || minutes || seconds) ? 'T' : '') +
  16028. (hours ? hours + 'H' : '') +
  16029. (minutes ? minutes + 'M' : '') +
  16030. (seconds ? seconds + 'S' : '');
  16031. }
  16032. });
  16033. function makeDurationGetter(name) {
  16034. moment.duration.fn[name] = function () {
  16035. return this._data[name];
  16036. };
  16037. }
  16038. function makeDurationAsGetter(name, factor) {
  16039. moment.duration.fn['as' + name] = function () {
  16040. return +this / factor;
  16041. };
  16042. }
  16043. for (i in unitMillisecondFactors) {
  16044. if (unitMillisecondFactors.hasOwnProperty(i)) {
  16045. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  16046. makeDurationGetter(i.toLowerCase());
  16047. }
  16048. }
  16049. makeDurationAsGetter('Weeks', 6048e5);
  16050. moment.duration.fn.asMonths = function () {
  16051. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  16052. };
  16053. /************************************
  16054. Default Lang
  16055. ************************************/
  16056. // Set default language, other languages will inherit from English.
  16057. moment.lang('en', {
  16058. ordinal : function (number) {
  16059. var b = number % 10,
  16060. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  16061. (b === 1) ? 'st' :
  16062. (b === 2) ? 'nd' :
  16063. (b === 3) ? 'rd' : 'th';
  16064. return number + output;
  16065. }
  16066. });
  16067. /* EMBED_LANGUAGES */
  16068. /************************************
  16069. Exposing Moment
  16070. ************************************/
  16071. function makeGlobal(deprecate) {
  16072. var warned = false, local_moment = moment;
  16073. /*global ender:false */
  16074. if (typeof ender !== 'undefined') {
  16075. return;
  16076. }
  16077. // here, `this` means `window` in the browser, or `global` on the server
  16078. // add `moment` as a global object via a string identifier,
  16079. // for Closure Compiler "advanced" mode
  16080. if (deprecate) {
  16081. global.moment = function () {
  16082. if (!warned && console && console.warn) {
  16083. warned = true;
  16084. console.warn(
  16085. "Accessing Moment through the global scope is " +
  16086. "deprecated, and will be removed in an upcoming " +
  16087. "release.");
  16088. }
  16089. return local_moment.apply(null, arguments);
  16090. };
  16091. extend(global.moment, local_moment);
  16092. } else {
  16093. global['moment'] = moment;
  16094. }
  16095. }
  16096. // CommonJS module is defined
  16097. if (hasModule) {
  16098. module.exports = moment;
  16099. makeGlobal(true);
  16100. } else if (typeof define === "function" && define.amd) {
  16101. define("moment", function (require, exports, module) {
  16102. if (module.config && module.config() && module.config().noGlobal !== true) {
  16103. // If user provided noGlobal, he is aware of global
  16104. makeGlobal(module.config().noGlobal === undefined);
  16105. }
  16106. return moment;
  16107. });
  16108. } else {
  16109. makeGlobal();
  16110. }
  16111. }).call(this);
  16112. },{}],4:[function(require,module,exports){
  16113. /**
  16114. * Copyright 2012 Craig Campbell
  16115. *
  16116. * Licensed under the Apache License, Version 2.0 (the "License");
  16117. * you may not use this file except in compliance with the License.
  16118. * You may obtain a copy of the License at
  16119. *
  16120. * http://www.apache.org/licenses/LICENSE-2.0
  16121. *
  16122. * Unless required by applicable law or agreed to in writing, software
  16123. * distributed under the License is distributed on an "AS IS" BASIS,
  16124. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16125. * See the License for the specific language governing permissions and
  16126. * limitations under the License.
  16127. *
  16128. * Mousetrap is a simple keyboard shortcut library for Javascript with
  16129. * no external dependencies
  16130. *
  16131. * @version 1.1.2
  16132. * @url craig.is/killing/mice
  16133. */
  16134. /**
  16135. * mapping of special keycodes to their corresponding keys
  16136. *
  16137. * everything in this dictionary cannot use keypress events
  16138. * so it has to be here to map to the correct keycodes for
  16139. * keyup/keydown events
  16140. *
  16141. * @type {Object}
  16142. */
  16143. var _MAP = {
  16144. 8: 'backspace',
  16145. 9: 'tab',
  16146. 13: 'enter',
  16147. 16: 'shift',
  16148. 17: 'ctrl',
  16149. 18: 'alt',
  16150. 20: 'capslock',
  16151. 27: 'esc',
  16152. 32: 'space',
  16153. 33: 'pageup',
  16154. 34: 'pagedown',
  16155. 35: 'end',
  16156. 36: 'home',
  16157. 37: 'left',
  16158. 38: 'up',
  16159. 39: 'right',
  16160. 40: 'down',
  16161. 45: 'ins',
  16162. 46: 'del',
  16163. 91: 'meta',
  16164. 93: 'meta',
  16165. 224: 'meta'
  16166. },
  16167. /**
  16168. * mapping for special characters so they can support
  16169. *
  16170. * this dictionary is only used incase you want to bind a
  16171. * keyup or keydown event to one of these keys
  16172. *
  16173. * @type {Object}
  16174. */
  16175. _KEYCODE_MAP = {
  16176. 106: '*',
  16177. 107: '+',
  16178. 109: '-',
  16179. 110: '.',
  16180. 111 : '/',
  16181. 186: ';',
  16182. 187: '=',
  16183. 188: ',',
  16184. 189: '-',
  16185. 190: '.',
  16186. 191: '/',
  16187. 192: '`',
  16188. 219: '[',
  16189. 220: '\\',
  16190. 221: ']',
  16191. 222: '\''
  16192. },
  16193. /**
  16194. * this is a mapping of keys that require shift on a US keypad
  16195. * back to the non shift equivelents
  16196. *
  16197. * this is so you can use keyup events with these keys
  16198. *
  16199. * note that this will only work reliably on US keyboards
  16200. *
  16201. * @type {Object}
  16202. */
  16203. _SHIFT_MAP = {
  16204. '~': '`',
  16205. '!': '1',
  16206. '@': '2',
  16207. '#': '3',
  16208. '$': '4',
  16209. '%': '5',
  16210. '^': '6',
  16211. '&': '7',
  16212. '*': '8',
  16213. '(': '9',
  16214. ')': '0',
  16215. '_': '-',
  16216. '+': '=',
  16217. ':': ';',
  16218. '\"': '\'',
  16219. '<': ',',
  16220. '>': '.',
  16221. '?': '/',
  16222. '|': '\\'
  16223. },
  16224. /**
  16225. * this is a list of special strings you can use to map
  16226. * to modifier keys when you specify your keyboard shortcuts
  16227. *
  16228. * @type {Object}
  16229. */
  16230. _SPECIAL_ALIASES = {
  16231. 'option': 'alt',
  16232. 'command': 'meta',
  16233. 'return': 'enter',
  16234. 'escape': 'esc'
  16235. },
  16236. /**
  16237. * variable to store the flipped version of _MAP from above
  16238. * needed to check if we should use keypress or not when no action
  16239. * is specified
  16240. *
  16241. * @type {Object|undefined}
  16242. */
  16243. _REVERSE_MAP,
  16244. /**
  16245. * a list of all the callbacks setup via Mousetrap.bind()
  16246. *
  16247. * @type {Object}
  16248. */
  16249. _callbacks = {},
  16250. /**
  16251. * direct map of string combinations to callbacks used for trigger()
  16252. *
  16253. * @type {Object}
  16254. */
  16255. _direct_map = {},
  16256. /**
  16257. * keeps track of what level each sequence is at since multiple
  16258. * sequences can start out with the same sequence
  16259. *
  16260. * @type {Object}
  16261. */
  16262. _sequence_levels = {},
  16263. /**
  16264. * variable to store the setTimeout call
  16265. *
  16266. * @type {null|number}
  16267. */
  16268. _reset_timer,
  16269. /**
  16270. * temporary state where we will ignore the next keyup
  16271. *
  16272. * @type {boolean|string}
  16273. */
  16274. _ignore_next_keyup = false,
  16275. /**
  16276. * are we currently inside of a sequence?
  16277. * type of action ("keyup" or "keydown" or "keypress") or false
  16278. *
  16279. * @type {boolean|string}
  16280. */
  16281. _inside_sequence = false;
  16282. /**
  16283. * loop through the f keys, f1 to f19 and add them to the map
  16284. * programatically
  16285. */
  16286. for (var i = 1; i < 20; ++i) {
  16287. _MAP[111 + i] = 'f' + i;
  16288. }
  16289. /**
  16290. * loop through to map numbers on the numeric keypad
  16291. */
  16292. for (i = 0; i <= 9; ++i) {
  16293. _MAP[i + 96] = i;
  16294. }
  16295. /**
  16296. * cross browser add event method
  16297. *
  16298. * @param {Element|HTMLDocument} object
  16299. * @param {string} type
  16300. * @param {Function} callback
  16301. * @returns void
  16302. */
  16303. function _addEvent(object, type, callback) {
  16304. if (object.addEventListener) {
  16305. return object.addEventListener(type, callback, false);
  16306. }
  16307. object.attachEvent('on' + type, callback);
  16308. }
  16309. /**
  16310. * takes the event and returns the key character
  16311. *
  16312. * @param {Event} e
  16313. * @return {string}
  16314. */
  16315. function _characterFromEvent(e) {
  16316. // for keypress events we should return the character as is
  16317. if (e.type == 'keypress') {
  16318. return String.fromCharCode(e.which);
  16319. }
  16320. // for non keypress events the special maps are needed
  16321. if (_MAP[e.which]) {
  16322. return _MAP[e.which];
  16323. }
  16324. if (_KEYCODE_MAP[e.which]) {
  16325. return _KEYCODE_MAP[e.which];
  16326. }
  16327. // if it is not in the special map
  16328. return String.fromCharCode(e.which).toLowerCase();
  16329. }
  16330. /**
  16331. * should we stop this event before firing off callbacks
  16332. *
  16333. * @param {Event} e
  16334. * @return {boolean}
  16335. */
  16336. function _stop(e) {
  16337. var element = e.target || e.srcElement,
  16338. tag_name = element.tagName;
  16339. // if the element has the class "mousetrap" then no need to stop
  16340. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  16341. return false;
  16342. }
  16343. // stop for input, select, and textarea
  16344. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  16345. }
  16346. /**
  16347. * checks if two arrays are equal
  16348. *
  16349. * @param {Array} modifiers1
  16350. * @param {Array} modifiers2
  16351. * @returns {boolean}
  16352. */
  16353. function _modifiersMatch(modifiers1, modifiers2) {
  16354. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  16355. }
  16356. /**
  16357. * resets all sequence counters except for the ones passed in
  16358. *
  16359. * @param {Object} do_not_reset
  16360. * @returns void
  16361. */
  16362. function _resetSequences(do_not_reset) {
  16363. do_not_reset = do_not_reset || {};
  16364. var active_sequences = false,
  16365. key;
  16366. for (key in _sequence_levels) {
  16367. if (do_not_reset[key]) {
  16368. active_sequences = true;
  16369. continue;
  16370. }
  16371. _sequence_levels[key] = 0;
  16372. }
  16373. if (!active_sequences) {
  16374. _inside_sequence = false;
  16375. }
  16376. }
  16377. /**
  16378. * finds all callbacks that match based on the keycode, modifiers,
  16379. * and action
  16380. *
  16381. * @param {string} character
  16382. * @param {Array} modifiers
  16383. * @param {string} action
  16384. * @param {boolean=} remove - should we remove any matches
  16385. * @param {string=} combination
  16386. * @returns {Array}
  16387. */
  16388. function _getMatches(character, modifiers, action, remove, combination) {
  16389. var i,
  16390. callback,
  16391. matches = [];
  16392. // if there are no events related to this keycode
  16393. if (!_callbacks[character]) {
  16394. return [];
  16395. }
  16396. // if a modifier key is coming up on its own we should allow it
  16397. if (action == 'keyup' && _isModifier(character)) {
  16398. modifiers = [character];
  16399. }
  16400. // loop through all callbacks for the key that was pressed
  16401. // and see if any of them match
  16402. for (i = 0; i < _callbacks[character].length; ++i) {
  16403. callback = _callbacks[character][i];
  16404. // if this is a sequence but it is not at the right level
  16405. // then move onto the next match
  16406. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  16407. continue;
  16408. }
  16409. // if the action we are looking for doesn't match the action we got
  16410. // then we should keep going
  16411. if (action != callback.action) {
  16412. continue;
  16413. }
  16414. // if this is a keypress event that means that we need to only
  16415. // look at the character, otherwise check the modifiers as
  16416. // well
  16417. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  16418. // remove is used so if you change your mind and call bind a
  16419. // second time with a new function the first one is overwritten
  16420. if (remove && callback.combo == combination) {
  16421. _callbacks[character].splice(i, 1);
  16422. }
  16423. matches.push(callback);
  16424. }
  16425. }
  16426. return matches;
  16427. }
  16428. /**
  16429. * takes a key event and figures out what the modifiers are
  16430. *
  16431. * @param {Event} e
  16432. * @returns {Array}
  16433. */
  16434. function _eventModifiers(e) {
  16435. var modifiers = [];
  16436. if (e.shiftKey) {
  16437. modifiers.push('shift');
  16438. }
  16439. if (e.altKey) {
  16440. modifiers.push('alt');
  16441. }
  16442. if (e.ctrlKey) {
  16443. modifiers.push('ctrl');
  16444. }
  16445. if (e.metaKey) {
  16446. modifiers.push('meta');
  16447. }
  16448. return modifiers;
  16449. }
  16450. /**
  16451. * actually calls the callback function
  16452. *
  16453. * if your callback function returns false this will use the jquery
  16454. * convention - prevent default and stop propogation on the event
  16455. *
  16456. * @param {Function} callback
  16457. * @param {Event} e
  16458. * @returns void
  16459. */
  16460. function _fireCallback(callback, e) {
  16461. if (callback(e) === false) {
  16462. if (e.preventDefault) {
  16463. e.preventDefault();
  16464. }
  16465. if (e.stopPropagation) {
  16466. e.stopPropagation();
  16467. }
  16468. e.returnValue = false;
  16469. e.cancelBubble = true;
  16470. }
  16471. }
  16472. /**
  16473. * handles a character key event
  16474. *
  16475. * @param {string} character
  16476. * @param {Event} e
  16477. * @returns void
  16478. */
  16479. function _handleCharacter(character, e) {
  16480. // if this event should not happen stop here
  16481. if (_stop(e)) {
  16482. return;
  16483. }
  16484. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  16485. i,
  16486. do_not_reset = {},
  16487. processed_sequence_callback = false;
  16488. // loop through matching callbacks for this key event
  16489. for (i = 0; i < callbacks.length; ++i) {
  16490. // fire for all sequence callbacks
  16491. // this is because if for example you have multiple sequences
  16492. // bound such as "g i" and "g t" they both need to fire the
  16493. // callback for matching g cause otherwise you can only ever
  16494. // match the first one
  16495. if (callbacks[i].seq) {
  16496. processed_sequence_callback = true;
  16497. // keep a list of which sequences were matches for later
  16498. do_not_reset[callbacks[i].seq] = 1;
  16499. _fireCallback(callbacks[i].callback, e);
  16500. continue;
  16501. }
  16502. // if there were no sequence matches but we are still here
  16503. // that means this is a regular match so we should fire that
  16504. if (!processed_sequence_callback && !_inside_sequence) {
  16505. _fireCallback(callbacks[i].callback, e);
  16506. }
  16507. }
  16508. // if you are inside of a sequence and the key you are pressing
  16509. // is not a modifier key then we should reset all sequences
  16510. // that were not matched by this key event
  16511. if (e.type == _inside_sequence && !_isModifier(character)) {
  16512. _resetSequences(do_not_reset);
  16513. }
  16514. }
  16515. /**
  16516. * handles a keydown event
  16517. *
  16518. * @param {Event} e
  16519. * @returns void
  16520. */
  16521. function _handleKey(e) {
  16522. // normalize e.which for key events
  16523. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  16524. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  16525. var character = _characterFromEvent(e);
  16526. // no character found then stop
  16527. if (!character) {
  16528. return;
  16529. }
  16530. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  16531. _ignore_next_keyup = false;
  16532. return;
  16533. }
  16534. _handleCharacter(character, e);
  16535. }
  16536. /**
  16537. * determines if the keycode specified is a modifier key or not
  16538. *
  16539. * @param {string} key
  16540. * @returns {boolean}
  16541. */
  16542. function _isModifier(key) {
  16543. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  16544. }
  16545. /**
  16546. * called to set a 1 second timeout on the specified sequence
  16547. *
  16548. * this is so after each key press in the sequence you have 1 second
  16549. * to press the next key before you have to start over
  16550. *
  16551. * @returns void
  16552. */
  16553. function _resetSequenceTimer() {
  16554. clearTimeout(_reset_timer);
  16555. _reset_timer = setTimeout(_resetSequences, 1000);
  16556. }
  16557. /**
  16558. * reverses the map lookup so that we can look for specific keys
  16559. * to see what can and can't use keypress
  16560. *
  16561. * @return {Object}
  16562. */
  16563. function _getReverseMap() {
  16564. if (!_REVERSE_MAP) {
  16565. _REVERSE_MAP = {};
  16566. for (var key in _MAP) {
  16567. // pull out the numeric keypad from here cause keypress should
  16568. // be able to detect the keys from the character
  16569. if (key > 95 && key < 112) {
  16570. continue;
  16571. }
  16572. if (_MAP.hasOwnProperty(key)) {
  16573. _REVERSE_MAP[_MAP[key]] = key;
  16574. }
  16575. }
  16576. }
  16577. return _REVERSE_MAP;
  16578. }
  16579. /**
  16580. * picks the best action based on the key combination
  16581. *
  16582. * @param {string} key - character for key
  16583. * @param {Array} modifiers
  16584. * @param {string=} action passed in
  16585. */
  16586. function _pickBestAction(key, modifiers, action) {
  16587. // if no action was picked in we should try to pick the one
  16588. // that we think would work best for this key
  16589. if (!action) {
  16590. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  16591. }
  16592. // modifier keys don't work as expected with keypress,
  16593. // switch to keydown
  16594. if (action == 'keypress' && modifiers.length) {
  16595. action = 'keydown';
  16596. }
  16597. return action;
  16598. }
  16599. /**
  16600. * binds a key sequence to an event
  16601. *
  16602. * @param {string} combo - combo specified in bind call
  16603. * @param {Array} keys
  16604. * @param {Function} callback
  16605. * @param {string=} action
  16606. * @returns void
  16607. */
  16608. function _bindSequence(combo, keys, callback, action) {
  16609. // start off by adding a sequence level record for this combination
  16610. // and setting the level to 0
  16611. _sequence_levels[combo] = 0;
  16612. // if there is no action pick the best one for the first key
  16613. // in the sequence
  16614. if (!action) {
  16615. action = _pickBestAction(keys[0], []);
  16616. }
  16617. /**
  16618. * callback to increase the sequence level for this sequence and reset
  16619. * all other sequences that were active
  16620. *
  16621. * @param {Event} e
  16622. * @returns void
  16623. */
  16624. var _increaseSequence = function(e) {
  16625. _inside_sequence = action;
  16626. ++_sequence_levels[combo];
  16627. _resetSequenceTimer();
  16628. },
  16629. /**
  16630. * wraps the specified callback inside of another function in order
  16631. * to reset all sequence counters as soon as this sequence is done
  16632. *
  16633. * @param {Event} e
  16634. * @returns void
  16635. */
  16636. _callbackAndReset = function(e) {
  16637. _fireCallback(callback, e);
  16638. // we should ignore the next key up if the action is key down
  16639. // or keypress. this is so if you finish a sequence and
  16640. // release the key the final key will not trigger a keyup
  16641. if (action !== 'keyup') {
  16642. _ignore_next_keyup = _characterFromEvent(e);
  16643. }
  16644. // weird race condition if a sequence ends with the key
  16645. // another sequence begins with
  16646. setTimeout(_resetSequences, 10);
  16647. },
  16648. i;
  16649. // loop through keys one at a time and bind the appropriate callback
  16650. // function. for any key leading up to the final one it should
  16651. // increase the sequence. after the final, it should reset all sequences
  16652. for (i = 0; i < keys.length; ++i) {
  16653. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  16654. }
  16655. }
  16656. /**
  16657. * binds a single keyboard combination
  16658. *
  16659. * @param {string} combination
  16660. * @param {Function} callback
  16661. * @param {string=} action
  16662. * @param {string=} sequence_name - name of sequence if part of sequence
  16663. * @param {number=} level - what part of the sequence the command is
  16664. * @returns void
  16665. */
  16666. function _bindSingle(combination, callback, action, sequence_name, level) {
  16667. // make sure multiple spaces in a row become a single space
  16668. combination = combination.replace(/\s+/g, ' ');
  16669. var sequence = combination.split(' '),
  16670. i,
  16671. key,
  16672. keys,
  16673. modifiers = [];
  16674. // if this pattern is a sequence of keys then run through this method
  16675. // to reprocess each pattern one key at a time
  16676. if (sequence.length > 1) {
  16677. return _bindSequence(combination, sequence, callback, action);
  16678. }
  16679. // take the keys from this pattern and figure out what the actual
  16680. // pattern is all about
  16681. keys = combination === '+' ? ['+'] : combination.split('+');
  16682. for (i = 0; i < keys.length; ++i) {
  16683. key = keys[i];
  16684. // normalize key names
  16685. if (_SPECIAL_ALIASES[key]) {
  16686. key = _SPECIAL_ALIASES[key];
  16687. }
  16688. // if this is not a keypress event then we should
  16689. // be smart about using shift keys
  16690. // this will only work for US keyboards however
  16691. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  16692. key = _SHIFT_MAP[key];
  16693. modifiers.push('shift');
  16694. }
  16695. // if this key is a modifier then add it to the list of modifiers
  16696. if (_isModifier(key)) {
  16697. modifiers.push(key);
  16698. }
  16699. }
  16700. // depending on what the key combination is
  16701. // we will try to pick the best event for it
  16702. action = _pickBestAction(key, modifiers, action);
  16703. // make sure to initialize array if this is the first time
  16704. // a callback is added for this key
  16705. if (!_callbacks[key]) {
  16706. _callbacks[key] = [];
  16707. }
  16708. // remove an existing match if there is one
  16709. _getMatches(key, modifiers, action, !sequence_name, combination);
  16710. // add this call back to the array
  16711. // if it is a sequence put it at the beginning
  16712. // if not put it at the end
  16713. //
  16714. // this is important because the way these are processed expects
  16715. // the sequence ones to come first
  16716. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  16717. callback: callback,
  16718. modifiers: modifiers,
  16719. action: action,
  16720. seq: sequence_name,
  16721. level: level,
  16722. combo: combination
  16723. });
  16724. }
  16725. /**
  16726. * binds multiple combinations to the same callback
  16727. *
  16728. * @param {Array} combinations
  16729. * @param {Function} callback
  16730. * @param {string|undefined} action
  16731. * @returns void
  16732. */
  16733. function _bindMultiple(combinations, callback, action) {
  16734. for (var i = 0; i < combinations.length; ++i) {
  16735. _bindSingle(combinations[i], callback, action);
  16736. }
  16737. }
  16738. // start!
  16739. _addEvent(document, 'keypress', _handleKey);
  16740. _addEvent(document, 'keydown', _handleKey);
  16741. _addEvent(document, 'keyup', _handleKey);
  16742. var mousetrap = {
  16743. /**
  16744. * binds an event to mousetrap
  16745. *
  16746. * can be a single key, a combination of keys separated with +,
  16747. * a comma separated list of keys, an array of keys, or
  16748. * a sequence of keys separated by spaces
  16749. *
  16750. * be sure to list the modifier keys first to make sure that the
  16751. * correct key ends up getting bound (the last key in the pattern)
  16752. *
  16753. * @param {string|Array} keys
  16754. * @param {Function} callback
  16755. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  16756. * @returns void
  16757. */
  16758. bind: function(keys, callback, action) {
  16759. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  16760. _direct_map[keys + ':' + action] = callback;
  16761. return this;
  16762. },
  16763. /**
  16764. * unbinds an event to mousetrap
  16765. *
  16766. * the unbinding sets the callback function of the specified key combo
  16767. * to an empty function and deletes the corresponding key in the
  16768. * _direct_map dict.
  16769. *
  16770. * the keycombo+action has to be exactly the same as
  16771. * it was defined in the bind method
  16772. *
  16773. * TODO: actually remove this from the _callbacks dictionary instead
  16774. * of binding an empty function
  16775. *
  16776. * @param {string|Array} keys
  16777. * @param {string} action
  16778. * @returns void
  16779. */
  16780. unbind: function(keys, action) {
  16781. if (_direct_map[keys + ':' + action]) {
  16782. delete _direct_map[keys + ':' + action];
  16783. this.bind(keys, function() {}, action);
  16784. }
  16785. return this;
  16786. },
  16787. /**
  16788. * triggers an event that has already been bound
  16789. *
  16790. * @param {string} keys
  16791. * @param {string=} action
  16792. * @returns void
  16793. */
  16794. trigger: function(keys, action) {
  16795. _direct_map[keys + ':' + action]();
  16796. return this;
  16797. },
  16798. /**
  16799. * resets the library back to its initial state. this is useful
  16800. * if you want to clear out the current keyboard shortcuts and bind
  16801. * new ones - for example if you switch to another page
  16802. *
  16803. * @returns void
  16804. */
  16805. reset: function() {
  16806. _callbacks = {};
  16807. _direct_map = {};
  16808. return this;
  16809. }
  16810. };
  16811. module.exports = mousetrap;
  16812. },{}]},{},[1])
  16813. (1)
  16814. });