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.

19505 lines
559 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-23
  9. *
  10. * @license
  11. * Copyright (C) 2011-2014 Almende B.V, http://almende.com
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  14. * use this file except in compliance with the License. You may obtain a copy
  15. * of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  22. * License for the specific language governing permissions and limitations under
  23. * the License.
  24. */
  25. !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.vis=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  26. /**
  27. * vis.js module imports
  28. */
  29. // Try to load dependencies from the global window object.
  30. // If not available there, load via require.
  31. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment');
  32. var 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 > 0 && this.height > 0) {
  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. /**
  10733. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  10734. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  10735. *
  10736. * @param pointer
  10737. * @returns {null}
  10738. * @private
  10739. */
  10740. _getEdgeAt : function(pointer) {
  10741. return null;
  10742. },
  10743. /**
  10744. * Add object to the selection array. The this.selection id array may not be needed.
  10745. *
  10746. * @param obj
  10747. * @private
  10748. */
  10749. _addToSelection : function(obj) {
  10750. this.selection.push(obj.id);
  10751. this.selectionObj[obj.id] = obj;
  10752. },
  10753. /**
  10754. * Remove a single option from selection.
  10755. *
  10756. * @param obj
  10757. * @private
  10758. */
  10759. _removeFromSelection : function(obj) {
  10760. for (var i = 0; i < this.selection.length; i++) {
  10761. if (obj.id == this.selection[i]) {
  10762. this.selection.splice(i,1);
  10763. break;
  10764. }
  10765. }
  10766. delete this.selectionObj[obj.id];
  10767. },
  10768. /**
  10769. * Unselect all. The selectionObj is useful for this.
  10770. *
  10771. * @private
  10772. */
  10773. _unselectAll : function() {
  10774. this.selection = [];
  10775. for (var objId in this.selectionObj) {
  10776. if (this.selectionObj.hasOwnProperty(objId)) {
  10777. this.selectionObj[objId].unselect();
  10778. }
  10779. }
  10780. this.selectionObj = {};
  10781. },
  10782. /**
  10783. * Check if anything is selected
  10784. *
  10785. * @returns {boolean}
  10786. * @private
  10787. */
  10788. _selectionIsEmpty : function() {
  10789. if (this.selection.length == 0) {
  10790. return true;
  10791. }
  10792. else {
  10793. return false;
  10794. }
  10795. },
  10796. /**
  10797. * This is called when someone clicks on a node. either select or deselect it.
  10798. * If there is an existing selection and we don't want to append to it, clear the existing selection
  10799. *
  10800. * @param {Node} node
  10801. * @param {Boolean} append
  10802. * @private
  10803. */
  10804. _selectNode : function(node, append) {
  10805. // TODO: triggers?
  10806. if (this._selectionIsEmpty() == false && append == false) {
  10807. this._unselectAll();
  10808. }
  10809. if (node.selected == false) {
  10810. node.select();
  10811. this._addToSelection(node);
  10812. }
  10813. else {
  10814. node.unselect();
  10815. this._removeFromSelection(node);
  10816. }
  10817. },
  10818. /**
  10819. * handles the selection part of the touch, only for UI elements;
  10820. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  10821. * This is the most responsive solution
  10822. *
  10823. * @param {Object} pointer
  10824. * @private
  10825. */
  10826. _handleTouch : function(pointer) {
  10827. var node = this._getUINodeAt(pointer);
  10828. if (node != null) {
  10829. if (this[node.triggerFunction] !== undefined) {
  10830. this[node.triggerFunction]();
  10831. }
  10832. }
  10833. },
  10834. /**
  10835. * handles the selection part of the tap;
  10836. *
  10837. * @param {Object} pointer
  10838. * @private
  10839. */
  10840. _handleTap : function(pointer) {
  10841. var node = this._getNodeAt(pointer);
  10842. if (node != null) {
  10843. this._selectNode(node,false);
  10844. }
  10845. else {
  10846. this._unselectAll();
  10847. }
  10848. this._redraw();
  10849. },
  10850. /**
  10851. * handles the selection part of the double tap and opens a cluster if needed
  10852. *
  10853. * @param {Object} pointer
  10854. * @private
  10855. */
  10856. _handleDoubleTap : function(pointer) {
  10857. var node = this._getNodeAt(pointer);
  10858. if (node != null && node !== undefined) {
  10859. // we reset the areaCenter here so the opening of the node will occur
  10860. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  10861. "y" : this._canvasToY(pointer.y)};
  10862. this.openCluster(node);
  10863. }
  10864. },
  10865. /**
  10866. * Handle the onHold selection part
  10867. *
  10868. * @param pointer
  10869. * @private
  10870. */
  10871. _handleOnHold : function(pointer) {
  10872. var node = this._getNodeAt(pointer);
  10873. if (node != null) {
  10874. this._selectNode(node,true);
  10875. }
  10876. this._redraw();
  10877. },
  10878. /**
  10879. * handle the onRelease event. These functions are here for the UI module.
  10880. *
  10881. * @private
  10882. */
  10883. _handleOnRelease : function() {
  10884. this.xIncrement = 0;
  10885. this.yIncrement = 0;
  10886. this.zoomIncrement = 0;
  10887. this._unHighlightAll();
  10888. },
  10889. /**
  10890. * * // TODO: rework this function, it is from the old system
  10891. *
  10892. * retrieve the currently selected nodes
  10893. * @return {Number[] | String[]} selection An array with the ids of the
  10894. * selected nodes.
  10895. */
  10896. getSelection : function() {
  10897. return this.selection.concat([]);
  10898. },
  10899. /**
  10900. * // TODO: rework this function, it is from the old system
  10901. *
  10902. * select zero or more nodes
  10903. * @param {Number[] | String[]} selection An array with the ids of the
  10904. * selected nodes.
  10905. */
  10906. setSelection : function(selection) {
  10907. var i, iMax, id;
  10908. if (!selection || (selection.length == undefined))
  10909. throw 'Selection must be an array with ids';
  10910. // first unselect any selected node
  10911. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  10912. id = this.selection[i];
  10913. this.nodes[id].unselect();
  10914. }
  10915. this.selection = [];
  10916. for (i = 0, iMax = selection.length; i < iMax; i++) {
  10917. id = selection[i];
  10918. var node = this.nodes[id];
  10919. if (!node) {
  10920. throw new RangeError('Node with id "' + id + '" not found');
  10921. }
  10922. node.select();
  10923. this.selection.push(id);
  10924. }
  10925. this.redraw();
  10926. },
  10927. /**
  10928. * TODO: rework this function, it is from the old system
  10929. *
  10930. * Validate the selection: remove ids of nodes which no longer exist
  10931. * @private
  10932. */
  10933. _updateSelection : function () {
  10934. var i = 0;
  10935. while (i < this.selection.length) {
  10936. var nodeId = this.selection[i];
  10937. if (!this.nodes.hasOwnProperty(nodeId)) {
  10938. this.selection.splice(i, 1);
  10939. delete this.selectionObj[nodeId];
  10940. }
  10941. else {
  10942. i++;
  10943. }
  10944. }
  10945. }
  10946. /**
  10947. * Unselect selected nodes. If no selection array is provided, all nodes
  10948. * are unselected
  10949. * @param {Object[]} selection Array with selection objects, each selection
  10950. * object has a parameter row. Optional
  10951. * @param {Boolean} triggerSelect If true (default), the select event
  10952. * is triggered when nodes are unselected
  10953. * @return {Boolean} changed True if the selection is changed
  10954. * @private
  10955. */
  10956. /* _unselectNodes : function(selection, triggerSelect) {
  10957. var changed = false;
  10958. var i, iMax, id;
  10959. if (selection) {
  10960. // remove provided selections
  10961. for (i = 0, iMax = selection.length; i < iMax; i++) {
  10962. id = selection[i];
  10963. if (this.nodes.hasOwnProperty(id)) {
  10964. this.nodes[id].unselect();
  10965. }
  10966. var j = 0;
  10967. while (j < this.selection.length) {
  10968. if (this.selection[j] == id) {
  10969. this.selection.splice(j, 1);
  10970. changed = true;
  10971. }
  10972. else {
  10973. j++;
  10974. }
  10975. }
  10976. }
  10977. }
  10978. else if (this.selection && this.selection.length) {
  10979. // remove all selections
  10980. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  10981. id = this.selection[i];
  10982. if (this.nodes.hasOwnProperty(id)) {
  10983. this.nodes[id].unselect();
  10984. }
  10985. changed = true;
  10986. }
  10987. this.selection = [];
  10988. }
  10989. if (changed && (triggerSelect == true || triggerSelect == undefined)) {
  10990. // fire the select event
  10991. this._trigger('select');
  10992. }
  10993. return changed;
  10994. },
  10995. */
  10996. /**
  10997. * select all nodes on given location x, y
  10998. * @param {Array} selection an array with node ids
  10999. * @param {boolean} append If true, the new selection will be appended to the
  11000. * current selection (except for duplicate entries)
  11001. * @return {Boolean} changed True if the selection is changed
  11002. * @private
  11003. */
  11004. /* _selectNodes : function(selection, append) {
  11005. var changed = false;
  11006. var i, iMax;
  11007. // TODO: the selectNodes method is a little messy, rework this
  11008. // check if the current selection equals the desired selection
  11009. var selectionAlreadyThere = true;
  11010. if (selection.length != this.selection.length) {
  11011. selectionAlreadyThere = false;
  11012. }
  11013. else {
  11014. for (i = 0, iMax = Math.min(selection.length, this.selection.length); i < iMax; i++) {
  11015. if (selection[i] != this.selection[i]) {
  11016. selectionAlreadyThere = false;
  11017. break;
  11018. }
  11019. }
  11020. }
  11021. if (selectionAlreadyThere) {
  11022. return changed;
  11023. }
  11024. if (append == undefined || append == false) {
  11025. // first deselect any selected node
  11026. var triggerSelect = false;
  11027. changed = this._unselectNodes(undefined, triggerSelect);
  11028. }
  11029. for (i = 0, iMax = selection.length; i < iMax; i++) {
  11030. // add each of the new selections, but only when they are not duplicate
  11031. var id = selection[i];
  11032. var isDuplicate = (this.selection.indexOf(id) != -1);
  11033. if (!isDuplicate) {
  11034. this.nodes[id].select();
  11035. this.selection.push(id);
  11036. changed = true;
  11037. }
  11038. }
  11039. if (changed) {
  11040. // fire the select event
  11041. this._trigger('select');
  11042. }
  11043. return changed;
  11044. },
  11045. */
  11046. };
  11047. /**
  11048. * Created by Alex on 1/22/14.
  11049. */
  11050. var UIMixin = {
  11051. /**
  11052. * This function moves the UI if the canvas size has been changed. If the arugments
  11053. * verticaAlignTop and horizontalAlignLeft are false, the correction will be made
  11054. *
  11055. * @private
  11056. */
  11057. _relocateUI : function() {
  11058. if (this.sectors !== undefined) {
  11059. var xOffset = this.UIclientWidth - this.frame.canvas.clientWidth;
  11060. var yOffset = this.UIclientHeight - this.frame.canvas.clientHeight;
  11061. this.UIclientWidth = this.frame.canvas.clientWidth;
  11062. this.UIclientHeight = this.frame.canvas.clientHeight;
  11063. var node = null;
  11064. for (var nodeId in this.sectors["UI"]["nodes"]) {
  11065. if (this.sectors["UI"]["nodes"].hasOwnProperty(nodeId)) {
  11066. node = this.sectors["UI"]["nodes"][nodeId];
  11067. if (!node.horizontalAlignLeft) {
  11068. node.x -= xOffset;
  11069. }
  11070. if (!node.verticalAlignTop) {
  11071. node.y -= yOffset;
  11072. }
  11073. }
  11074. }
  11075. }
  11076. },
  11077. /**
  11078. * Creation of the UI nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  11079. * they have a triggerFunction which is called on click. If the position of the UI is dependent
  11080. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  11081. * This means that the location will be corrected by the _relocateUI function on a size change of the canvas.
  11082. *
  11083. * @private
  11084. */
  11085. _loadUIElements : function() {
  11086. var DIR = 'img/UI/';
  11087. this.UIclientWidth = this.frame.canvas.clientWidth;
  11088. this.UIclientHeight = this.frame.canvas.clientHeight;
  11089. if (this.UIclientWidth === undefined) {
  11090. this.UIclientWidth = 0;
  11091. this.UIclientHeight = 0;
  11092. }
  11093. var UINodes = [
  11094. {id: 'UI_up', shape: 'image', image: DIR + 'uparrow.png', triggerFunction: "_moveUp",
  11095. verticalAlignTop: false, x: 52, y: this.UIclientHeight - 52},
  11096. {id: 'UI_down', shape: 'image', image: DIR + 'downarrow.png', triggerFunction: "_moveDown",
  11097. verticalAlignTop: false, x: 52, y: this.UIclientHeight - 20},
  11098. {id: 'UI_left', shape: 'image', image: DIR + 'leftarrow.png', triggerFunction: "_moveLeft",
  11099. verticalAlignTop: false, x: 20, y: this.UIclientHeight - 20},
  11100. {id: 'UI_right', shape: 'image', image: DIR + 'rightarrow.png',triggerFunction: "_moveRight",
  11101. verticalAlignTop: false, x: 84, y: this.UIclientHeight - 20},
  11102. {id: 'UI_plus', shape: 'image', image: DIR + 'plus.png', triggerFunction: "_zoomIn",
  11103. verticalAlignTop: false, horizontalAlignLeft: false,
  11104. x: this.UIclientWidth - 52, y: this.UIclientHeight - 20},
  11105. {id: 'UI_min', shape: 'image', image: DIR + 'minus.png', triggerFunction: "_zoomOut",
  11106. verticalAlignTop: false, horizontalAlignLeft: false,
  11107. x: this.UIclientWidth - 20, y: this.UIclientHeight - 20},
  11108. {id: 'UI_zoomExtends', shape: 'image', image: DIR + 'zoomExtends.png', triggerFunction: "zoomToFit",
  11109. verticalAlignTop: false, horizontalAlignLeft: false,
  11110. x: this.UIclientWidth - 20, y: this.UIclientHeight - 52}
  11111. ];
  11112. var nodeObj = null;
  11113. for (var i = 0; i < UINodes.length; i++) {
  11114. nodeObj = this.sectors["UI"]['nodes'];
  11115. nodeObj[UINodes[i]['id']] = new Node(UINodes[i], this.images, this.groups, this.constants);
  11116. }
  11117. },
  11118. /**
  11119. * By setting the clustersize to be larger than 1, we use the clustering drawing method
  11120. * to illustrate the buttons are presed. We call this highlighting.
  11121. *
  11122. * @param {String} elementId
  11123. * @private
  11124. */
  11125. _highlightUIElement : function(elementId) {
  11126. if (this.sectors["UI"]["nodes"].hasOwnProperty(elementId)) {
  11127. this.sectors["UI"]["nodes"][elementId].clusterSize = 2;
  11128. }
  11129. },
  11130. /**
  11131. * Reverting back to a normal button
  11132. *
  11133. * @param {String} elementId
  11134. * @private
  11135. */
  11136. _unHighlightUIElement : function(elementId) {
  11137. if (this.sectors["UI"]["nodes"].hasOwnProperty(elementId)) {
  11138. this.sectors["UI"]["nodes"][elementId].clusterSize = 1;
  11139. }
  11140. },
  11141. /**
  11142. * toggle the visibility of the UI
  11143. *
  11144. * @private
  11145. */
  11146. _toggleUI : function() {
  11147. if (this.UIvisible === undefined) {
  11148. this.UIvisible = false;
  11149. }
  11150. this.UIvisible = !this.UIvisible;
  11151. this._redraw();
  11152. },
  11153. /**
  11154. * un-highlight (for lack of a better term) all UI elements
  11155. * @private
  11156. */
  11157. _unHighlightAll : function() {
  11158. for (var nodeId in this.sectors['UI']['nodes']) {
  11159. this._unHighlightUIElement(nodeId);
  11160. }
  11161. },
  11162. /**
  11163. * move the screen up
  11164. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  11165. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  11166. * To avoid this behaviour, we do the translation in the start loop.
  11167. *
  11168. * @private
  11169. */
  11170. _moveUp : function() {
  11171. this._highlightUIElement("UI_up");
  11172. this.yIncrement = this.constants.UI.yMovementSpeed;
  11173. this.start(); // if there is no node movement, the calculation wont be done
  11174. },
  11175. /**
  11176. * move the screen down
  11177. * @private
  11178. */
  11179. _moveDown : function() {
  11180. this._highlightUIElement("UI_down");
  11181. this.yIncrement = -this.constants.UI.yMovementSpeed;
  11182. this.start(); // if there is no node movement, the calculation wont be done
  11183. },
  11184. /**
  11185. * move the screen left
  11186. * @private
  11187. */
  11188. _moveLeft : function() {
  11189. this._highlightUIElement("UI_left");
  11190. this.xIncrement = this.constants.UI.xMovementSpeed;
  11191. this.start(); // if there is no node movement, the calculation wont be done
  11192. },
  11193. /**
  11194. * move the screen right
  11195. * @private
  11196. */
  11197. _moveRight : function() {
  11198. this._highlightUIElement("UI_right");
  11199. this.xIncrement = -this.constants.UI.xMovementSpeed;
  11200. this.start(); // if there is no node movement, the calculation wont be done
  11201. },
  11202. /**
  11203. * Zoom in, using the same method as the movement.
  11204. * @private
  11205. */
  11206. _zoomIn : function() {
  11207. this._highlightUIElement("UI_plus");
  11208. this.zoomIncrement = this.constants.UI.zoomMovementSpeed;
  11209. this.start(); // if there is no node movement, the calculation wont be done
  11210. },
  11211. /**
  11212. * Zoom out
  11213. * @private
  11214. */
  11215. _zoomOut : function() {
  11216. this._highlightUIElement("UI_min");
  11217. this.zoomIncrement = -this.constants.UI.zoomMovementSpeed;
  11218. this.start(); // if there is no node movement, the calculation wont be done
  11219. },
  11220. /**
  11221. * Stop zooming and unhighlight the zoom controls
  11222. * @private
  11223. */
  11224. _stopZoom : function() {
  11225. this._unHighlightUIElement("UI_plus");
  11226. this._unHighlightUIElement("UI_min");
  11227. },
  11228. /**
  11229. * Stop moving in the Y direction and unHighlight the up and down
  11230. * @private
  11231. */
  11232. _yStopMoving : function() {
  11233. this._unHighlightUIElement("UI_up");
  11234. this._unHighlightUIElement("UI_down");
  11235. this.yIncrement = 0;
  11236. },
  11237. /**
  11238. * Stop moving in the X direction and unHighlight left and right.
  11239. * @private
  11240. */
  11241. _xStopMoving : function() {
  11242. this._unHighlightUIElement("UI_left");
  11243. this._unHighlightUIElement("UI_right");
  11244. this.xIncrement = 0;
  11245. }
  11246. };
  11247. /**
  11248. * @constructor Graph
  11249. * Create a graph visualization, displaying nodes and edges.
  11250. *
  11251. * @param {Element} container The DOM element in which the Graph will
  11252. * be created. Normally a div element.
  11253. * @param {Object} data An object containing parameters
  11254. * {Array} nodes
  11255. * {Array} edges
  11256. * @param {Object} options Options
  11257. */
  11258. function Graph (container, data, options) {
  11259. // create variables and set default values
  11260. this.containerElement = container;
  11261. this.width = '100%';
  11262. this.height = '100%';
  11263. // to give everything a nice fluidity, we seperate the rendering and calculating of the forces
  11264. this.calculationRefreshRate = 40; // milliseconds
  11265. this.calculationStartTime = 0;
  11266. this.renderRefreshRate = 15; // milliseconds
  11267. this.stabilize = true; // stabilize before displaying the graph
  11268. this.selectable = true;
  11269. // set constant values
  11270. this.constants = {
  11271. nodes: {
  11272. radiusMin: 5,
  11273. radiusMax: 20,
  11274. radius: 5,
  11275. distance: 100, // px
  11276. shape: 'ellipse',
  11277. image: undefined,
  11278. widthMin: 16, // px
  11279. widthMax: 64, // px
  11280. fontColor: 'black',
  11281. fontSize: 14, // px
  11282. //fontFace: verdana,
  11283. fontFace: 'arial',
  11284. color: {
  11285. border: '#2B7CE9',
  11286. background: '#97C2FC',
  11287. highlight: {
  11288. border: '#2B7CE9',
  11289. background: '#D2E5FF'
  11290. }
  11291. },
  11292. borderColor: '#2B7CE9',
  11293. backgroundColor: '#97C2FC',
  11294. highlightColor: '#D2E5FF',
  11295. group: undefined
  11296. },
  11297. edges: {
  11298. widthMin: 1,
  11299. widthMax: 15,
  11300. width: 1,
  11301. style: 'line',
  11302. color: '#343434',
  11303. fontColor: '#343434',
  11304. fontSize: 14, // px
  11305. fontFace: 'arial',
  11306. //distance: 100, //px
  11307. length: 100, // px
  11308. dash: {
  11309. length: 10,
  11310. gap: 5,
  11311. altLength: undefined
  11312. }
  11313. },
  11314. clustering: { // Per Node in Cluster = PNiC
  11315. enabled: false, // (Boolean) | global on/off switch for clustering.
  11316. initialMaxNumberOfNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  11317. 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
  11318. 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
  11319. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  11320. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  11321. sectorThreshold: 50, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  11322. 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.
  11323. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  11324. forceAmplification: 0.6, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  11325. distanceAmplification: 0.2, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  11326. edgeGrowth: 11, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  11327. clusterSizeWidthFactor: 10, // (px PNiC) | growth of the width per node in cluster.
  11328. clusterSizeHeightFactor: 10, // (px PNiC) | growth of the height per node in cluster.
  11329. clusterSizeRadiusFactor: 10, // (px PNiC) | growth of the radius per node in cluster.
  11330. activeAreaBoxSize: 100, // (px) | box area around the curser where clusters are popped open.
  11331. massTransferCoefficient: 1 // (multiplier) | parent.mass += massTransferCoefficient * child.mass
  11332. },
  11333. UI: {
  11334. enabled: true,
  11335. initiallyVisible: true,
  11336. xMovementSpeed: 10,
  11337. yMovementSpeed: 10,
  11338. zoomMovementSpeed: 0.02
  11339. },
  11340. minForce: 0.05,
  11341. minVelocity: 0.02, // px/s
  11342. maxIterations: 1000 // maximum number of iteration to stabilize
  11343. };
  11344. // Node variables
  11345. this.groups = new Groups(); // object with groups
  11346. this.images = new Images(); // object with images
  11347. this.images.setOnloadCallback(function () {
  11348. graph._redraw();
  11349. });
  11350. // UI variables
  11351. this.UIvisible = this.constants.UI.initiallyVisible;
  11352. this.xIncrement = 0;
  11353. this.yIncrement = 0;
  11354. this.zoomIncrement = 0;
  11355. // create a frame and canvas
  11356. this._create();
  11357. // apply options
  11358. this.setOptions(options);
  11359. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  11360. this._loadClusterSystem();
  11361. // load the sector system. (mandatory, fully integrated with Graph)
  11362. this._loadSectorSystem();
  11363. // load the selection system. (mandatory, required by Graph)
  11364. this._loadSelectionSystem();
  11365. // load the UI system. (mandatory, few function calls even when UI is disabled (in this.setSize)
  11366. this._loadUISystem();
  11367. // other vars
  11368. var graph = this;
  11369. this.freezeSimulation = false;// freeze the simulation
  11370. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  11371. this.nodes = {}; // object with Node objects
  11372. this.edges = {}; // object with Edge objects
  11373. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  11374. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  11375. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  11376. this.scale = 1; // defining the global scale variable in the constructor
  11377. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  11378. // TODO: create a counter to keep track on the number of nodes having values
  11379. // TODO: create a counter to keep track on the number of nodes currently moving
  11380. // TODO: create a counter to keep track on the number of edges having values
  11381. this.nodesData = null; // A DataSet or DataView
  11382. this.edgesData = null; // A DataSet or DataView
  11383. // create event listeners used to subscribe on the DataSets of the nodes and edges
  11384. var me = this;
  11385. this.nodesListeners = {
  11386. 'add': function (event, params) {
  11387. me._addNodes(params.items);
  11388. me.start();
  11389. },
  11390. 'update': function (event, params) {
  11391. me._updateNodes(params.items);
  11392. me.start();
  11393. },
  11394. 'remove': function (event, params) {
  11395. me._removeNodes(params.items);
  11396. me.start();
  11397. }
  11398. };
  11399. this.edgesListeners = {
  11400. 'add': function (event, params) {
  11401. me._addEdges(params.items);
  11402. me.start();
  11403. },
  11404. 'update': function (event, params) {
  11405. me._updateEdges(params.items);
  11406. me.start();
  11407. },
  11408. 'remove': function (event, params) {
  11409. me._removeEdges(params.items);
  11410. me.start();
  11411. }
  11412. };
  11413. // properties of the data
  11414. this.moving = false; // True if any of the nodes have an undefined position
  11415. this.timer = undefined;
  11416. // load data (the disable start variable will be the same as the enabled clustering)
  11417. this.setData(data,this.constants.clustering.enabled);
  11418. // zoom so all data will fit on the screen
  11419. this.zoomToFit();
  11420. // if clustering is disabled, the simulation will have started in the setData function
  11421. if (this.constants.clustering.enabled) {
  11422. this.startWithClustering();
  11423. }
  11424. }
  11425. /**
  11426. * Find the center position of the graph
  11427. * @private
  11428. */
  11429. Graph.prototype._findCenter = function() {
  11430. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11431. for (var i = 0; i < this.nodeIndices.length; i++) {
  11432. node = this.nodes[this.nodeIndices[i]];
  11433. if (minX > node.x) {minX = node.x;}
  11434. if (maxX < node.x) {maxX = node.x;}
  11435. if (minY > node.y) {minY = node.y;}
  11436. if (maxY < node.y) {maxY = node.y;}
  11437. }
  11438. return {x: (0.5 * (maxX + minX)),
  11439. y: (0.5 * (maxY + minY))};
  11440. };
  11441. /**
  11442. * center the graph
  11443. */
  11444. Graph.prototype._centerGraph = function() {
  11445. var center = this._findCenter();
  11446. center.x -= 0.5 * this.frame.canvas.clientWidth;
  11447. center.y -= 0.5 * this.frame.canvas.clientHeight;
  11448. this._setTranslation(-center.x,-center.y);
  11449. };
  11450. /**
  11451. * This function zooms out to fit all data on screen based on amount of nodes
  11452. */
  11453. Graph.prototype.zoomToFit = function() {
  11454. var numberOfNodes = this.nodeIndices.length;
  11455. var zoomLevel = 46.5 / (numberOfNodes + 20.622); // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  11456. if (zoomLevel > 1.0) {
  11457. zoomLevel = 1.0;
  11458. }
  11459. this.pinch.mousewheelScale = zoomLevel;
  11460. this._setScale(zoomLevel);
  11461. this._centerGraph();
  11462. };
  11463. /**
  11464. * Update the this.nodeIndices with the most recent node index list
  11465. * @private
  11466. */
  11467. Graph.prototype._updateNodeIndexList = function() {
  11468. this._clearNodeIndexList();
  11469. for (var idx in this.nodes) {
  11470. if (this.nodes.hasOwnProperty(idx)) {
  11471. this.nodeIndices.push(idx);
  11472. }
  11473. }
  11474. };
  11475. /**
  11476. * Set nodes and edges, and optionally options as well.
  11477. *
  11478. * @param {Object} data Object containing parameters:
  11479. * {Array | DataSet | DataView} [nodes] Array with nodes
  11480. * {Array | DataSet | DataView} [edges] Array with edges
  11481. * {String} [dot] String containing data in DOT format
  11482. * {Options} [options] Object with options
  11483. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  11484. */
  11485. Graph.prototype.setData = function(data, disableStart) {
  11486. if (disableStart === undefined) {
  11487. disableStart = false;
  11488. }
  11489. if (data && data.dot && (data.nodes || data.edges)) {
  11490. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  11491. ' parameter pair "nodes" and "edges", but not both.');
  11492. }
  11493. // set options
  11494. this.setOptions(data && data.options);
  11495. // set all data
  11496. if (data && data.dot) {
  11497. // parse DOT file
  11498. if(data && data.dot) {
  11499. var dotData = vis.util.DOTToGraph(data.dot);
  11500. this.setData(dotData);
  11501. return;
  11502. }
  11503. }
  11504. else {
  11505. this._setNodes(data && data.nodes);
  11506. this._setEdges(data && data.edges);
  11507. }
  11508. this._putDataInSector();
  11509. if (!disableStart) {
  11510. // find a stable position or start animating to a stable position
  11511. if (this.stabilize) {
  11512. this._doStabilize();
  11513. }
  11514. this.start();
  11515. }
  11516. };
  11517. /**
  11518. * Set options
  11519. * @param {Object} options
  11520. */
  11521. Graph.prototype.setOptions = function (options) {
  11522. if (options) {
  11523. // retrieve parameter values
  11524. if (options.width !== undefined) {this.width = options.width;}
  11525. if (options.height !== undefined) {this.height = options.height;}
  11526. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  11527. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  11528. if (options.clustering) {
  11529. for (var prop in options.clustering) {
  11530. if (options.clustering.hasOwnProperty(prop)) {
  11531. this.constants.clustering[prop] = options.clustering[prop];
  11532. }
  11533. }
  11534. }
  11535. if (options.UI) {
  11536. for (var prop in options.UI) {
  11537. if (options.UI.hasOwnProperty(prop)) {
  11538. this.constants.UI[prop] = options.UI[prop];
  11539. }
  11540. }
  11541. }
  11542. // TODO: work out these options and document them
  11543. if (options.edges) {
  11544. for (prop in options.edges) {
  11545. if (options.edges.hasOwnProperty(prop)) {
  11546. this.constants.edges[prop] = options.edges[prop];
  11547. }
  11548. }
  11549. if (options.edges.length !== undefined &&
  11550. options.nodes && options.nodes.distance === undefined) {
  11551. this.constants.edges.length = options.edges.length;
  11552. this.constants.nodes.distance = options.edges.length * 1.25;
  11553. }
  11554. if (!options.edges.fontColor) {
  11555. this.constants.edges.fontColor = options.edges.color;
  11556. }
  11557. // Added to support dashed lines
  11558. // David Jordan
  11559. // 2012-08-08
  11560. if (options.edges.dash) {
  11561. if (options.edges.dash.length !== undefined) {
  11562. this.constants.edges.dash.length = options.edges.dash.length;
  11563. }
  11564. if (options.edges.dash.gap !== undefined) {
  11565. this.constants.edges.dash.gap = options.edges.dash.gap;
  11566. }
  11567. if (options.edges.dash.altLength !== undefined) {
  11568. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  11569. }
  11570. }
  11571. }
  11572. if (options.nodes) {
  11573. for (prop in options.nodes) {
  11574. if (options.nodes.hasOwnProperty(prop)) {
  11575. this.constants.nodes[prop] = options.nodes[prop];
  11576. }
  11577. }
  11578. if (options.nodes.color) {
  11579. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  11580. }
  11581. /*
  11582. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  11583. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  11584. */
  11585. }
  11586. if (options.groups) {
  11587. for (var groupname in options.groups) {
  11588. if (options.groups.hasOwnProperty(groupname)) {
  11589. var group = options.groups[groupname];
  11590. this.groups.add(groupname, group);
  11591. }
  11592. }
  11593. }
  11594. }
  11595. this.setSize(this.width, this.height);
  11596. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  11597. this._setScale(1);
  11598. };
  11599. /**
  11600. * fire an event
  11601. * @param {String} event The name of an event, for example 'select'
  11602. * @param {Object} params Optional object with event parameters
  11603. * @private
  11604. */
  11605. Graph.prototype._trigger = function (event, params) {
  11606. events.trigger(this, event, params);
  11607. };
  11608. /**
  11609. * Create the main frame for the Graph.
  11610. * This function is executed once when a Graph object is created. The frame
  11611. * contains a canvas, and this canvas contains all objects like the axis and
  11612. * nodes.
  11613. * @private
  11614. */
  11615. Graph.prototype._create = function () {
  11616. // remove all elements from the container element.
  11617. while (this.containerElement.hasChildNodes()) {
  11618. this.containerElement.removeChild(this.containerElement.firstChild);
  11619. }
  11620. this.frame = document.createElement('div');
  11621. this.frame.className = 'graph-frame';
  11622. this.frame.style.position = 'relative';
  11623. this.frame.style.overflow = 'hidden';
  11624. // create the graph canvas (HTML canvas element)
  11625. this.frame.canvas = document.createElement( 'canvas' );
  11626. this.frame.canvas.style.position = 'relative';
  11627. this.frame.appendChild(this.frame.canvas);
  11628. if (!this.frame.canvas.getContext) {
  11629. var noCanvas = document.createElement( 'DIV' );
  11630. noCanvas.style.color = 'red';
  11631. noCanvas.style.fontWeight = 'bold' ;
  11632. noCanvas.style.padding = '10px';
  11633. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  11634. this.frame.canvas.appendChild(noCanvas);
  11635. }
  11636. var me = this;
  11637. this.drag = {};
  11638. this.pinch = {};
  11639. this.hammer = Hammer(this.frame.canvas, {
  11640. prevent_default: true
  11641. });
  11642. this.hammer.on('tap', me._onTap.bind(me) );
  11643. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  11644. this.hammer.on('hold', me._onHold.bind(me) );
  11645. this.hammer.on('pinch', me._onPinch.bind(me) );
  11646. this.hammer.on('touch', me._onTouch.bind(me) );
  11647. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  11648. this.hammer.on('drag', me._onDrag.bind(me) );
  11649. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  11650. this.hammer.on('release', me._onRelease.bind(me) );
  11651. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  11652. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  11653. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  11654. // add the frame to the container element
  11655. this.containerElement.appendChild(this.frame);
  11656. };
  11657. /**
  11658. * Binding the keys for keyboard navigation. These functions are defined in the UIMixin
  11659. * @private
  11660. */
  11661. Graph.prototype._createKeyBinds = function() {
  11662. var me = this;
  11663. this.mouseTrap = mouseTrap;
  11664. this.mouseTrap.bind("up", this._moveUp.bind(me) , "keydown");
  11665. this.mouseTrap.bind("up", this._yStopMoving.bind(me), "keyup");
  11666. this.mouseTrap.bind("down", this._moveDown.bind(me) , "keydown");
  11667. this.mouseTrap.bind("down", this._yStopMoving.bind(me), "keyup");
  11668. this.mouseTrap.bind("left", this._moveLeft.bind(me) , "keydown");
  11669. this.mouseTrap.bind("left", this._xStopMoving.bind(me), "keyup");
  11670. this.mouseTrap.bind("right",this._moveRight.bind(me), "keydown");
  11671. this.mouseTrap.bind("right",this._xStopMoving.bind(me), "keyup");
  11672. this.mouseTrap.bind("=",this._zoomIn.bind(me), "keydown");
  11673. this.mouseTrap.bind("=",this._stopZoom.bind(me), "keyup");
  11674. this.mouseTrap.bind("-",this._zoomOut.bind(me), "keydown");
  11675. this.mouseTrap.bind("-",this._stopZoom.bind(me), "keyup");
  11676. this.mouseTrap.bind("[",this._zoomIn.bind(me), "keydown");
  11677. this.mouseTrap.bind("[",this._stopZoom.bind(me), "keyup");
  11678. this.mouseTrap.bind("]",this._zoomOut.bind(me), "keydown");
  11679. this.mouseTrap.bind("]",this._stopZoom.bind(me), "keyup");
  11680. this.mouseTrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  11681. this.mouseTrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  11682. this.mouseTrap.bind("pagedown",this._zoomOut.bind(me), "keydown");
  11683. this.mouseTrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  11684. this.mouseTrap.bind("u",this._toggleUI.bind(me) , "keydown");
  11685. /*
  11686. this.mouseTrap.bind("=",this.decreaseClusterLevel.bind(me));
  11687. this.mouseTrap.bind("-",this.increaseClusterLevel.bind(me));
  11688. this.mouseTrap.bind("s",this.singleStep.bind(me));
  11689. this.mouseTrap.bind("h",this.updateClustersDefault.bind(me));
  11690. this.mouseTrap.bind("c",this._collapseSector.bind(me));
  11691. this.mouseTrap.bind("f",this.toggleFreeze.bind(me));
  11692. */
  11693. }
  11694. /**
  11695. * Get the pointer location from a touch location
  11696. * @param {{pageX: Number, pageY: Number}} touch
  11697. * @return {{x: Number, y: Number}} pointer
  11698. * @private
  11699. */
  11700. Graph.prototype._getPointer = function (touch) {
  11701. return {
  11702. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  11703. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  11704. };
  11705. };
  11706. /**
  11707. * On start of a touch gesture, store the pointer
  11708. * @param event
  11709. * @private
  11710. */
  11711. Graph.prototype._onTouch = function (event) {
  11712. this.drag.pointer = this._getPointer(event.gesture.touches[0]);
  11713. this.drag.pinched = false;
  11714. this.pinch.scale = this._getScale();
  11715. this._handleTouch(this.drag.pointer);
  11716. };
  11717. /**
  11718. * handle drag start event
  11719. * @private
  11720. */
  11721. Graph.prototype._onDragStart = function () {
  11722. var drag = this.drag;
  11723. var node = this._getNodeAt(drag.pointer);
  11724. // note: drag.pointer is set in _onTouch to get the initial touch location
  11725. drag.selection = [];
  11726. drag.translation = this._getTranslation();
  11727. drag.nodeId = null;
  11728. if (node != null) {
  11729. drag.nodeId = node.id;
  11730. // select the clicked node if not yet selected
  11731. if (!node.isSelected()) {
  11732. this._selectNode(node,false);
  11733. }
  11734. // create an array with the selected nodes and their original location and status
  11735. var me = this;
  11736. this.selection.forEach(function (id) {
  11737. var node = me.nodes[id];
  11738. if (node) {
  11739. var s = {
  11740. id: id,
  11741. node: node,
  11742. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  11743. x: node.x,
  11744. y: node.y,
  11745. xFixed: node.xFixed,
  11746. yFixed: node.yFixed
  11747. };
  11748. node.xFixed = true;
  11749. node.yFixed = true;
  11750. drag.selection.push(s);
  11751. }
  11752. });
  11753. }
  11754. };
  11755. /**
  11756. * handle drag event
  11757. * @private
  11758. */
  11759. Graph.prototype._onDrag = function (event) {
  11760. if (this.drag.pinched) {
  11761. return;
  11762. }
  11763. var pointer = this._getPointer(event.gesture.touches[0]);
  11764. var me = this,
  11765. drag = this.drag,
  11766. selection = drag.selection;
  11767. if (selection && selection.length) {
  11768. // calculate delta's and new location
  11769. var deltaX = pointer.x - drag.pointer.x,
  11770. deltaY = pointer.y - drag.pointer.y;
  11771. // update position of all selected nodes
  11772. selection.forEach(function (s) {
  11773. var node = s.node;
  11774. if (!s.xFixed) {
  11775. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  11776. }
  11777. if (!s.yFixed) {
  11778. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  11779. }
  11780. });
  11781. // start animation if not yet running
  11782. if (!this.moving) {
  11783. this.moving = true;
  11784. this.start();
  11785. }
  11786. }
  11787. else {
  11788. // move the graph
  11789. var diffX = pointer.x - this.drag.pointer.x;
  11790. var diffY = pointer.y - this.drag.pointer.y;
  11791. this._setTranslation(
  11792. this.drag.translation.x + diffX,
  11793. this.drag.translation.y + diffY);
  11794. this._redraw();
  11795. this.moved = true;
  11796. }
  11797. };
  11798. /**
  11799. * handle drag start event
  11800. * @private
  11801. */
  11802. Graph.prototype._onDragEnd = function () {
  11803. var selection = this.drag.selection;
  11804. if (selection) {
  11805. selection.forEach(function (s) {
  11806. // restore original xFixed and yFixed
  11807. s.node.xFixed = s.xFixed;
  11808. s.node.yFixed = s.yFixed;
  11809. });
  11810. }
  11811. };
  11812. /**
  11813. * handle tap/click event: select/unselect a node
  11814. * @private
  11815. */
  11816. Graph.prototype._onTap = function (event) {
  11817. var pointer = this._getPointer(event.gesture.touches[0]);
  11818. this._handleTap(pointer);
  11819. };
  11820. /**
  11821. * handle doubletap event
  11822. * @private
  11823. */
  11824. Graph.prototype._onDoubleTap = function (event) {
  11825. var pointer = this._getPointer(event.gesture.touches[0]);
  11826. this._handleDoubleTap(pointer);
  11827. };
  11828. /**
  11829. * handle long tap event: multi select nodes
  11830. * @private
  11831. */
  11832. Graph.prototype._onHold = function (event) {
  11833. var pointer = this._getPointer(event.gesture.touches[0]);
  11834. this._handleOnHold(pointer);
  11835. };
  11836. /**
  11837. * handle the release of the screen
  11838. *
  11839. * @param event
  11840. * @private
  11841. */
  11842. Graph.prototype._onRelease = function (event) {
  11843. this._handleOnRelease();
  11844. };
  11845. /**
  11846. * Handle pinch event
  11847. * @param event
  11848. * @private
  11849. */
  11850. Graph.prototype._onPinch = function (event) {
  11851. var pointer = this._getPointer(event.gesture.center);
  11852. this.drag.pinched = true;
  11853. if (!('scale' in this.pinch)) {
  11854. this.pinch.scale = 1;
  11855. }
  11856. // TODO: enabled moving while pinching?
  11857. var scale = this.pinch.scale * event.gesture.scale;
  11858. this._zoom(scale, pointer)
  11859. };
  11860. /**
  11861. * Zoom the graph in or out
  11862. * @param {Number} scale a number around 1, and between 0.01 and 10
  11863. * @param {{x: Number, y: Number}} pointer
  11864. * @return {Number} appliedScale scale is limited within the boundaries
  11865. * @private
  11866. */
  11867. Graph.prototype._zoom = function(scale, pointer) {
  11868. var scaleOld = this._getScale();
  11869. if (scale < 0.00001) {
  11870. scale = 0.00001;
  11871. }
  11872. if (scale > 10) {
  11873. scale = 10;
  11874. }
  11875. // + this.frame.canvas.clientHeight / 2
  11876. var translation = this._getTranslation();
  11877. var scaleFrac = scale / scaleOld;
  11878. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  11879. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  11880. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  11881. "y" : this._canvasToY(pointer.y)};
  11882. // this.areaCenter = {"x" : pointer.x,"y" : pointer.y };
  11883. // console.log(translation.x,translation.y,pointer.x,pointer.y,scale);
  11884. this.pinch.mousewheelScale = scale;
  11885. this._setScale(scale);
  11886. this._setTranslation(tx, ty);
  11887. this.updateClustersDefault();
  11888. this._redraw();
  11889. // console.log("current zoomscale:",this.scale);
  11890. return scale;
  11891. };
  11892. /**
  11893. * Event handler for mouse wheel event, used to zoom the timeline
  11894. * See http://adomas.org/javascript-mouse-wheel/
  11895. * https://github.com/EightMedia/hammer.js/issues/256
  11896. * @param {MouseEvent} event
  11897. * @private
  11898. */
  11899. Graph.prototype._onMouseWheel = function(event) {
  11900. // retrieve delta
  11901. var delta = 0;
  11902. if (event.wheelDelta) { /* IE/Opera. */
  11903. delta = event.wheelDelta/120;
  11904. } else if (event.detail) { /* Mozilla case. */
  11905. // In Mozilla, sign of delta is different than in IE.
  11906. // Also, delta is multiple of 3.
  11907. delta = -event.detail/3;
  11908. }
  11909. // If delta is nonzero, handle it.
  11910. // Basically, delta is now positive if wheel was scrolled up,
  11911. // and negative, if wheel was scrolled down.
  11912. if (delta) {
  11913. if (!('mousewheelScale' in this.pinch)) {
  11914. this.pinch.mousewheelScale = 1;
  11915. }
  11916. // calculate the new scale
  11917. var scale = this.pinch.mousewheelScale;
  11918. var zoom = delta / 10;
  11919. if (delta < 0) {
  11920. zoom = zoom / (1 - zoom);
  11921. }
  11922. scale *= (1 + zoom);
  11923. // calculate the pointer location
  11924. var gesture = util.fakeGesture(this, event);
  11925. var pointer = this._getPointer(gesture.center);
  11926. // apply the new scale
  11927. scale = this._zoom(scale, pointer);
  11928. // store the new, applied scale -- this is now done in _zoom
  11929. // this.pinch.mousewheelScale = scale;
  11930. }
  11931. // Prevent default actions caused by mouse wheel.
  11932. event.preventDefault();
  11933. };
  11934. /**
  11935. * Mouse move handler for checking whether the title moves over a node with a title.
  11936. * @param {Event} event
  11937. * @private
  11938. */
  11939. Graph.prototype._onMouseMoveTitle = function (event) {
  11940. var gesture = util.fakeGesture(this, event);
  11941. var pointer = this._getPointer(gesture.center);
  11942. this.lastPointerPosition = pointer;
  11943. // check if the previously selected node is still selected
  11944. if (this.popupNode) {
  11945. this._checkHidePopup(pointer);
  11946. }
  11947. // start a timeout that will check if the mouse is positioned above
  11948. // an element
  11949. var me = this;
  11950. var checkShow = function() {
  11951. me._checkShowPopup(pointer);
  11952. };
  11953. if (this.popupTimer) {
  11954. clearInterval(this.popupTimer); // stop any running calculationTimer
  11955. }
  11956. if (!this.leftButtonDown) {
  11957. this.popupTimer = setTimeout(checkShow, 300);
  11958. }
  11959. };
  11960. /**
  11961. * Check if there is an element on the given position in the graph
  11962. * (a node or edge). If so, and if this element has a title,
  11963. * show a popup window with its title.
  11964. *
  11965. * @param {{x:Number, y:Number}} pointer
  11966. * @private
  11967. */
  11968. Graph.prototype._checkShowPopup = function (pointer) {
  11969. var obj = {
  11970. left: this._canvasToX(pointer.x),
  11971. top: this._canvasToY(pointer.y),
  11972. right: this._canvasToX(pointer.x),
  11973. bottom: this._canvasToY(pointer.y)
  11974. };
  11975. var id;
  11976. var lastPopupNode = this.popupNode;
  11977. if (this.popupNode == undefined) {
  11978. // search the nodes for overlap, select the top one in case of multiple nodes
  11979. var nodes = this.nodes;
  11980. for (id in nodes) {
  11981. if (nodes.hasOwnProperty(id)) {
  11982. var node = nodes[id];
  11983. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  11984. this.popupNode = node;
  11985. break;
  11986. }
  11987. }
  11988. }
  11989. }
  11990. if (this.popupNode === undefined) {
  11991. // search the edges for overlap
  11992. var edges = this.edges;
  11993. for (id in edges) {
  11994. if (edges.hasOwnProperty(id)) {
  11995. var edge = edges[id];
  11996. if (edge.connected && (edge.getTitle() !== undefined) &&
  11997. edge.isOverlappingWith(obj)) {
  11998. this.popupNode = edge;
  11999. break;
  12000. }
  12001. }
  12002. }
  12003. }
  12004. if (this.popupNode) {
  12005. // show popup message window
  12006. if (this.popupNode != lastPopupNode) {
  12007. var me = this;
  12008. if (!me.popup) {
  12009. me.popup = new Popup(me.frame);
  12010. }
  12011. // adjust a small offset such that the mouse cursor is located in the
  12012. // bottom left location of the popup, and you can easily move over the
  12013. // popup area
  12014. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  12015. me.popup.setText(me.popupNode.getTitle());
  12016. me.popup.show();
  12017. }
  12018. }
  12019. else {
  12020. if (this.popup) {
  12021. this.popup.hide();
  12022. }
  12023. }
  12024. };
  12025. /**
  12026. * Check if the popup must be hided, which is the case when the mouse is no
  12027. * longer hovering on the object
  12028. * @param {{x:Number, y:Number}} pointer
  12029. * @private
  12030. */
  12031. Graph.prototype._checkHidePopup = function (pointer) {
  12032. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  12033. this.popupNode = undefined;
  12034. if (this.popup) {
  12035. this.popup.hide();
  12036. }
  12037. }
  12038. };
  12039. /**
  12040. * Temporary method to test calculating a hub value for the nodes
  12041. * @param {number} level Maximum number edges between two nodes in order
  12042. * to call them connected. Optional, 1 by default
  12043. * @return {Number[]} connectioncount array with the connection count
  12044. * for each node
  12045. * @private
  12046. */
  12047. Graph.prototype._getConnectionCount = function(level) {
  12048. if (level == undefined) {
  12049. level = 1;
  12050. }
  12051. // get the nodes connected to given nodes
  12052. function getConnectedNodes(nodes) {
  12053. var connectedNodes = [];
  12054. for (var j = 0, jMax = nodes.length; j < jMax; j++) {
  12055. var node = nodes[j];
  12056. // find all nodes connected to this node
  12057. var edges = node.edges;
  12058. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  12059. var edge = edges[i];
  12060. var other = null;
  12061. // check if connected
  12062. if (edge.from == node)
  12063. other = edge.to;
  12064. else if (edge.to == node)
  12065. other = edge.from;
  12066. // check if the other node is not already in the list with nodes
  12067. var k, kMax;
  12068. if (other) {
  12069. for (k = 0, kMax = nodes.length; k < kMax; k++) {
  12070. if (nodes[k] == other) {
  12071. other = null;
  12072. break;
  12073. }
  12074. }
  12075. }
  12076. if (other) {
  12077. for (k = 0, kMax = connectedNodes.length; k < kMax; k++) {
  12078. if (connectedNodes[k] == other) {
  12079. other = null;
  12080. break;
  12081. }
  12082. }
  12083. }
  12084. if (other)
  12085. connectedNodes.push(other);
  12086. }
  12087. }
  12088. return connectedNodes;
  12089. }
  12090. var connections = [];
  12091. var nodes = this.nodes;
  12092. for (var id in nodes) {
  12093. if (nodes.hasOwnProperty(id)) {
  12094. var c = [nodes[id]];
  12095. for (var l = 0; l < level; l++) {
  12096. c = c.concat(getConnectedNodes(c));
  12097. }
  12098. connections.push(c);
  12099. }
  12100. }
  12101. var hubs = [];
  12102. for (var i = 0, len = connections.length; i < len; i++) {
  12103. hubs.push(connections[i].length);
  12104. }
  12105. return hubs;
  12106. };
  12107. /**
  12108. * Set a new size for the graph
  12109. * @param {string} width Width in pixels or percentage (for example '800px'
  12110. * or '50%')
  12111. * @param {string} height Height in pixels or percentage (for example '400px'
  12112. * or '30%')
  12113. */
  12114. Graph.prototype.setSize = function(width, height) {
  12115. this.frame.style.width = width;
  12116. this.frame.style.height = height;
  12117. this.frame.canvas.style.width = '100%';
  12118. this.frame.canvas.style.height = '100%';
  12119. this.frame.canvas.width = this.frame.canvas.clientWidth;
  12120. this.frame.canvas.height = this.frame.canvas.clientHeight;
  12121. if (this.constants.UI.enabled == true) {
  12122. this._relocateUI();
  12123. }
  12124. };
  12125. /**
  12126. * Set a data set with nodes for the graph
  12127. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  12128. * @private
  12129. */
  12130. Graph.prototype._setNodes = function(nodes) {
  12131. var oldNodesData = this.nodesData;
  12132. if (nodes instanceof DataSet || nodes instanceof DataView) {
  12133. this.nodesData = nodes;
  12134. }
  12135. else if (nodes instanceof Array) {
  12136. this.nodesData = new DataSet();
  12137. this.nodesData.add(nodes);
  12138. }
  12139. else if (!nodes) {
  12140. this.nodesData = new DataSet();
  12141. }
  12142. else {
  12143. throw new TypeError('Array or DataSet expected');
  12144. }
  12145. if (oldNodesData) {
  12146. // unsubscribe from old dataset
  12147. util.forEach(this.nodesListeners, function (callback, event) {
  12148. oldNodesData.unsubscribe(event, callback);
  12149. });
  12150. }
  12151. // remove drawn nodes
  12152. this.nodes = {};
  12153. if (this.nodesData) {
  12154. // subscribe to new dataset
  12155. var me = this;
  12156. util.forEach(this.nodesListeners, function (callback, event) {
  12157. me.nodesData.subscribe(event, callback);
  12158. });
  12159. // draw all new nodes
  12160. var ids = this.nodesData.getIds();
  12161. this._addNodes(ids);
  12162. }
  12163. this._updateSelection();
  12164. };
  12165. /**
  12166. * Add nodes
  12167. * @param {Number[] | String[]} ids
  12168. * @private
  12169. */
  12170. Graph.prototype._addNodes = function(ids) {
  12171. var id;
  12172. for (var i = 0, len = ids.length; i < len; i++) {
  12173. id = ids[i];
  12174. var data = this.nodesData.get(id);
  12175. var node = new Node(data, this.images, this.groups, this.constants);
  12176. this.nodes[id] = node; // note: this may replace an existing node
  12177. if (!node.isFixed()) {
  12178. // TODO: position new nodes in a smarter way!
  12179. var radius = this.constants.edges.length * 2;
  12180. var count = ids.length;
  12181. var angle = 2 * Math.PI * (i / count);
  12182. node.x = radius * Math.cos(angle);
  12183. node.y = radius * Math.sin(angle);
  12184. // note: no not use node.isMoving() here, as that gives the current
  12185. // velocity of the node, which is zero after creation of the node.
  12186. this.moving = true;
  12187. }
  12188. }
  12189. this._updateNodeIndexList();
  12190. this._reconnectEdges();
  12191. this._updateValueRange(this.nodes);
  12192. };
  12193. /**
  12194. * Update existing nodes, or create them when not yet existing
  12195. * @param {Number[] | String[]} ids
  12196. * @private
  12197. */
  12198. Graph.prototype._updateNodes = function(ids) {
  12199. var nodes = this.nodes,
  12200. nodesData = this.nodesData;
  12201. for (var i = 0, len = ids.length; i < len; i++) {
  12202. var id = ids[i];
  12203. var node = nodes[id];
  12204. var data = nodesData.get(id);
  12205. if (node) {
  12206. // update node
  12207. node.setProperties(data, this.constants);
  12208. }
  12209. else {
  12210. // create node
  12211. node = new Node(properties, this.images, this.groups, this.constants);
  12212. nodes[id] = node;
  12213. if (!node.isFixed()) {
  12214. this.moving = true;
  12215. }
  12216. }
  12217. }
  12218. this._updateNodeIndexList();
  12219. this._reconnectEdges();
  12220. this._updateValueRange(nodes);
  12221. };
  12222. /**
  12223. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  12224. * @param {Number[] | String[]} ids
  12225. * @private
  12226. */
  12227. Graph.prototype._removeNodes = function(ids) {
  12228. var nodes = this.nodes;
  12229. for (var i = 0, len = ids.length; i < len; i++) {
  12230. var id = ids[i];
  12231. delete nodes[id];
  12232. }
  12233. this._updateNodeIndexList();
  12234. this._reconnectEdges();
  12235. this._updateSelection();
  12236. this._updateValueRange(nodes);
  12237. };
  12238. /**
  12239. * Load edges by reading the data table
  12240. * @param {Array | DataSet | DataView} edges The data containing the edges.
  12241. * @private
  12242. * @private
  12243. */
  12244. Graph.prototype._setEdges = function(edges) {
  12245. var oldEdgesData = this.edgesData;
  12246. if (edges instanceof DataSet || edges instanceof DataView) {
  12247. this.edgesData = edges;
  12248. }
  12249. else if (edges instanceof Array) {
  12250. this.edgesData = new DataSet();
  12251. this.edgesData.add(edges);
  12252. }
  12253. else if (!edges) {
  12254. this.edgesData = new DataSet();
  12255. }
  12256. else {
  12257. throw new TypeError('Array or DataSet expected');
  12258. }
  12259. if (oldEdgesData) {
  12260. // unsubscribe from old dataset
  12261. util.forEach(this.edgesListeners, function (callback, event) {
  12262. oldEdgesData.unsubscribe(event, callback);
  12263. });
  12264. }
  12265. // remove drawn edges
  12266. this.edges = {};
  12267. if (this.edgesData) {
  12268. // subscribe to new dataset
  12269. var me = this;
  12270. util.forEach(this.edgesListeners, function (callback, event) {
  12271. me.edgesData.subscribe(event, callback);
  12272. });
  12273. // draw all new nodes
  12274. var ids = this.edgesData.getIds();
  12275. this._addEdges(ids);
  12276. }
  12277. this._reconnectEdges();
  12278. };
  12279. /**
  12280. * Add edges
  12281. * @param {Number[] | String[]} ids
  12282. * @private
  12283. */
  12284. Graph.prototype._addEdges = function (ids) {
  12285. var edges = this.edges,
  12286. edgesData = this.edgesData;
  12287. for (var i = 0, len = ids.length; i < len; i++) {
  12288. var id = ids[i];
  12289. var oldEdge = edges[id];
  12290. if (oldEdge) {
  12291. oldEdge.disconnect();
  12292. }
  12293. var data = edgesData.get(id, {"showInternalIds" : true});
  12294. edges[id] = new Edge(data, this, this.constants);
  12295. }
  12296. this.moving = true;
  12297. this._updateValueRange(edges);
  12298. };
  12299. /**
  12300. * Update existing edges, or create them when not yet existing
  12301. * @param {Number[] | String[]} ids
  12302. * @private
  12303. */
  12304. Graph.prototype._updateEdges = function (ids) {
  12305. var edges = this.edges,
  12306. edgesData = this.edgesData;
  12307. for (var i = 0, len = ids.length; i < len; i++) {
  12308. var id = ids[i];
  12309. var data = edgesData.get(id);
  12310. var edge = edges[id];
  12311. if (edge) {
  12312. // update edge
  12313. edge.disconnect();
  12314. edge.setProperties(data, this.constants);
  12315. edge.connect();
  12316. }
  12317. else {
  12318. // create edge
  12319. edge = new Edge(data, this, this.constants);
  12320. this.edges[id] = edge;
  12321. }
  12322. }
  12323. this.moving = true;
  12324. this._updateValueRange(edges);
  12325. };
  12326. /**
  12327. * Remove existing edges. Non existing ids will be ignored
  12328. * @param {Number[] | String[]} ids
  12329. * @private
  12330. */
  12331. Graph.prototype._removeEdges = function (ids) {
  12332. var edges = this.edges;
  12333. for (var i = 0, len = ids.length; i < len; i++) {
  12334. var id = ids[i];
  12335. var edge = edges[id];
  12336. if (edge) {
  12337. edge.disconnect();
  12338. delete edges[id];
  12339. }
  12340. }
  12341. this.moving = true;
  12342. this._updateValueRange(edges);
  12343. };
  12344. /**
  12345. * Reconnect all edges
  12346. * @private
  12347. */
  12348. Graph.prototype._reconnectEdges = function() {
  12349. var id,
  12350. nodes = this.nodes,
  12351. edges = this.edges;
  12352. for (id in nodes) {
  12353. if (nodes.hasOwnProperty(id)) {
  12354. nodes[id].edges = [];
  12355. }
  12356. }
  12357. for (id in edges) {
  12358. if (edges.hasOwnProperty(id)) {
  12359. var edge = edges[id];
  12360. edge.from = null;
  12361. edge.to = null;
  12362. edge.connect();
  12363. }
  12364. }
  12365. };
  12366. /**
  12367. * Update the values of all object in the given array according to the current
  12368. * value range of the objects in the array.
  12369. * @param {Object} obj An object containing a set of Edges or Nodes
  12370. * The objects must have a method getValue() and
  12371. * setValueRange(min, max).
  12372. * @private
  12373. */
  12374. Graph.prototype._updateValueRange = function(obj) {
  12375. var id;
  12376. // determine the range of the objects
  12377. var valueMin = undefined;
  12378. var valueMax = undefined;
  12379. for (id in obj) {
  12380. if (obj.hasOwnProperty(id)) {
  12381. var value = obj[id].getValue();
  12382. if (value !== undefined) {
  12383. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  12384. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  12385. }
  12386. }
  12387. }
  12388. // adjust the range of all objects
  12389. if (valueMin !== undefined && valueMax !== undefined) {
  12390. for (id in obj) {
  12391. if (obj.hasOwnProperty(id)) {
  12392. obj[id].setValueRange(valueMin, valueMax);
  12393. }
  12394. }
  12395. }
  12396. };
  12397. /**
  12398. * Redraw the graph with the current data
  12399. * chart will be resized too.
  12400. */
  12401. Graph.prototype.redraw = function() {
  12402. this.setSize(this.width, this.height);
  12403. this._redraw();
  12404. };
  12405. /**
  12406. * Redraw the graph with the current data
  12407. * @private
  12408. */
  12409. Graph.prototype._redraw = function() {
  12410. var ctx = this.frame.canvas.getContext('2d');
  12411. // clear the canvas
  12412. var w = this.frame.canvas.width;
  12413. var h = this.frame.canvas.height;
  12414. ctx.clearRect(0, 0, w, h);
  12415. // set scaling and translation
  12416. ctx.save();
  12417. ctx.translate(this.translation.x, this.translation.y);
  12418. ctx.scale(this.scale, this.scale);
  12419. this.canvasTopLeft = {"x": (0-this.translation.x)/this.scale,
  12420. "y": (0-this.translation.y)/this.scale};
  12421. this.canvasBottomRight = {"x": (this.frame.canvas.clientWidth -this.translation.x)/this.scale,
  12422. "y": (this.frame.canvas.clientHeight-this.translation.y)/this.scale};
  12423. this._doInAllSectors("_drawAllSectorNodes",ctx);
  12424. this._doInAllSectors("_drawEdges",ctx);
  12425. this._doInAllSectors("_drawNodes",ctx);
  12426. // restore original scaling and translation
  12427. ctx.restore();
  12428. if (this.UIvisible == true) {
  12429. this._doInUISector("_drawNodes",ctx,true);
  12430. }
  12431. };
  12432. /**
  12433. * Set the translation of the graph
  12434. * @param {Number} offsetX Horizontal offset
  12435. * @param {Number} offsetY Vertical offset
  12436. * @private
  12437. */
  12438. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  12439. if (this.translation === undefined) {
  12440. this.translation = {
  12441. x: 0,
  12442. y: 0
  12443. };
  12444. }
  12445. if (offsetX !== undefined) {
  12446. this.translation.x = offsetX;
  12447. }
  12448. if (offsetY !== undefined) {
  12449. this.translation.y = offsetY;
  12450. }
  12451. };
  12452. /**
  12453. * Get the translation of the graph
  12454. * @return {Object} translation An object with parameters x and y, both a number
  12455. * @private
  12456. */
  12457. Graph.prototype._getTranslation = function() {
  12458. return {
  12459. x: this.translation.x,
  12460. y: this.translation.y
  12461. };
  12462. };
  12463. /**
  12464. * Scale the graph
  12465. * @param {Number} scale Scaling factor 1.0 is unscaled
  12466. * @private
  12467. */
  12468. Graph.prototype._setScale = function(scale) {
  12469. this.scale = scale;
  12470. };
  12471. /**
  12472. * Get the current scale of the graph
  12473. * @return {Number} scale Scaling factor 1.0 is unscaled
  12474. * @private
  12475. */
  12476. Graph.prototype._getScale = function() {
  12477. return this.scale;
  12478. };
  12479. /**
  12480. * Convert a horizontal point on the HTML canvas to the x-value of the model
  12481. * @param {number} x
  12482. * @returns {number}
  12483. * @private
  12484. */
  12485. Graph.prototype._canvasToX = function(x) {
  12486. return (x - this.translation.x) / this.scale;
  12487. };
  12488. /**
  12489. * Convert an x-value in the model to a horizontal point on the HTML canvas
  12490. * @param {number} x
  12491. * @returns {number}
  12492. * @private
  12493. */
  12494. Graph.prototype._xToCanvas = function(x) {
  12495. return x * this.scale + this.translation.x;
  12496. };
  12497. /**
  12498. * Convert a vertical point on the HTML canvas to the y-value of the model
  12499. * @param {number} y
  12500. * @returns {number}
  12501. * @private
  12502. */
  12503. Graph.prototype._canvasToY = function(y) {
  12504. return (y - this.translation.y) / this.scale;
  12505. };
  12506. /**
  12507. * Convert an y-value in the model to a vertical point on the HTML canvas
  12508. * @param {number} y
  12509. * @returns {number}
  12510. * @private
  12511. */
  12512. Graph.prototype._yToCanvas = function(y) {
  12513. return y * this.scale + this.translation.y ;
  12514. };
  12515. /**
  12516. * Redraw all nodes
  12517. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  12518. * @param {CanvasRenderingContext2D} ctx
  12519. * @param {Boolean} [alwaysShow]
  12520. * @private
  12521. */
  12522. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  12523. if (alwaysShow === undefined) {
  12524. alwaysShow = false;
  12525. }
  12526. // first draw the unselected nodes
  12527. var nodes = this.nodes;
  12528. var selected = [];
  12529. for (var id in nodes) {
  12530. if (nodes.hasOwnProperty(id)) {
  12531. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  12532. if (nodes[id].isSelected()) {
  12533. selected.push(id);
  12534. }
  12535. else {
  12536. if (nodes[id].inArea() || alwaysShow) {
  12537. nodes[id].draw(ctx);
  12538. }
  12539. }
  12540. }
  12541. }
  12542. // draw the selected nodes on top
  12543. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  12544. if (nodes[selected[s]].inArea() || alwaysShow) {
  12545. nodes[selected[s]].draw(ctx);
  12546. }
  12547. }
  12548. };
  12549. /**
  12550. * Redraw all edges
  12551. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  12552. * @param {CanvasRenderingContext2D} ctx
  12553. * @private
  12554. */
  12555. Graph.prototype._drawEdges = function(ctx) {
  12556. var edges = this.edges;
  12557. for (var id in edges) {
  12558. if (edges.hasOwnProperty(id)) {
  12559. var edge = edges[id];
  12560. edge.setScale(this.scale);
  12561. if (edge.connected) {
  12562. edges[id].draw(ctx);
  12563. }
  12564. }
  12565. }
  12566. };
  12567. /**
  12568. * Find a stable position for all nodes
  12569. * @private
  12570. */
  12571. Graph.prototype._doStabilize = function() {
  12572. //var start = new Date();
  12573. // find stable position
  12574. var count = 0;
  12575. var vmin = this.constants.minVelocity;
  12576. var stable = false;
  12577. while (!stable && count < this.constants.maxIterations) {
  12578. this._initializeForceCalculation();
  12579. this._discreteStepNodes();
  12580. stable = !this._isMoving(vmin);
  12581. count++;
  12582. }
  12583. // var end = new Date();
  12584. // console.log('Stabilized in ' + (end-start) + ' ms, ' + count + ' iterations' ); // TODO: cleanup
  12585. };
  12586. /**
  12587. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  12588. * if there is more than one node. If it is just one node, we dont calculate anything.
  12589. *
  12590. * @private
  12591. */
  12592. Graph.prototype._initializeForceCalculation = function() {
  12593. // stop calculation if there is only one node
  12594. if (this.nodeIndices.length == 1) {
  12595. this.nodes[this.nodeIndices[0]]._setForce(0,0);
  12596. }
  12597. else {
  12598. // if there are too many nodes on screen, we cluster without repositioning
  12599. if (this.nodeIndices.length > this.constants.clustering.absoluteMaxNumberOfNodes && this.constants.clustering.enabled == true) {
  12600. this.clusterToFit(this.constants.clustering.reduceToMaxNumberOfNodes, false);
  12601. }
  12602. // we now start the force calculation
  12603. this._calculateForces();
  12604. }
  12605. };
  12606. /**
  12607. * Calculate the external forces acting on the nodes
  12608. * Forces are caused by: edges, repulsing forces between nodes, gravity
  12609. * @private
  12610. */
  12611. Graph.prototype._calculateForces = function() {
  12612. var screenCenterPos = {"x":0.5*(this.canvasTopLeft.x + this.canvasBottomRight.x),
  12613. "y":0.5*(this.canvasTopLeft.y + this.canvasBottomRight.y)}
  12614. // create a local edge to the nodes and edges, that is faster
  12615. var dx, dy, angle, distance, fx, fy,
  12616. repulsingForce, springForce, length, edgeLength,
  12617. node, node1, node2, edge, edgeId, i, j, nodeId, xCenter, yCenter;
  12618. var clusterSize;
  12619. var nodes = this.nodes;
  12620. var edges = this.edges;
  12621. // Gravity is required to keep separated groups from floating off
  12622. // the forces are reset to zero in this loop by using _setForce instead
  12623. // of _addForce
  12624. var gravity = 0.08;
  12625. for (i = 0; i < this.nodeIndices.length; i++) {
  12626. node = nodes[this.nodeIndices[i]];
  12627. // gravity does not apply when we are in a pocket sector
  12628. if (this._sector() == "default") {
  12629. dx = -node.x + screenCenterPos.x;
  12630. dy = -node.y + screenCenterPos.y;
  12631. angle = Math.atan2(dy, dx);
  12632. fx = Math.cos(angle) * gravity;
  12633. fy = Math.sin(angle) * gravity;
  12634. }
  12635. else {
  12636. fx = 0;
  12637. fy = 0;
  12638. }
  12639. node._setForce(fx, fy);
  12640. node.updateDamping(this.nodeIndices.length);
  12641. }
  12642. // repulsing forces between nodes
  12643. var minimumDistance = this.constants.nodes.distance,
  12644. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  12645. // we loop from i over all but the last entree in the array
  12646. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  12647. for (i = 0; i < this.nodeIndices.length-1; i++) {
  12648. node1 = nodes[this.nodeIndices[i]];
  12649. for (j = i+1; j < this.nodeIndices.length; j++) {
  12650. node2 = nodes[this.nodeIndices[j]];
  12651. clusterSize = (node1.clusterSize + node2.clusterSize - 2);
  12652. dx = node2.x - node1.x;
  12653. dy = node2.y - node1.y;
  12654. distance = Math.sqrt(dx * dx + dy * dy);
  12655. // clusters have a larger region of influence
  12656. minimumDistance = (clusterSize == 0) ? this.constants.nodes.distance : (this.constants.nodes.distance * (1 + clusterSize * this.constants.clustering.distanceAmplification));
  12657. if (distance < 2*minimumDistance) { // at 2.0 * the minimum distance, the force is 0.000045
  12658. angle = Math.atan2(dy, dx);
  12659. if (distance < 0.5*minimumDistance) { // at 0.5 * the minimum distance, the force is 0.993307
  12660. repulsingForce = 1.0;
  12661. }
  12662. else {
  12663. // TODO: correct factor for repulsing force
  12664. //repulsingForce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12665. //repulsingForce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12666. repulsingForce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)); // TODO: customize the repulsing force
  12667. }
  12668. // amplify the repulsion for clusters.
  12669. repulsingForce *= (clusterSize == 0) ? 1 : 1 + clusterSize * this.constants.clustering.forceAmplification;
  12670. fx = Math.cos(angle) * repulsingForce;
  12671. fy = Math.sin(angle) * repulsingForce;
  12672. node1._addForce(-fx, -fy);
  12673. node2._addForce(fx, fy);
  12674. }
  12675. }
  12676. }
  12677. /*
  12678. // repulsion of the edges on the nodes and
  12679. for (var nodeId in nodes) {
  12680. if (nodes.hasOwnProperty(nodeId)) {
  12681. node = nodes[nodeId];
  12682. for(var edgeId in edges) {
  12683. if (edges.hasOwnProperty(edgeId)) {
  12684. edge = edges[edgeId];
  12685. // get the center of the edge
  12686. xCenter = edge.from.x+(edge.to.x - edge.from.x)/2;
  12687. yCenter = edge.from.y+(edge.to.y - edge.from.y)/2;
  12688. // calculate normally distributed force
  12689. dx = node.x - xCenter;
  12690. dy = node.y - yCenter;
  12691. distance = Math.sqrt(dx * dx + dy * dy);
  12692. if (distance < 2*minimumDistance) { // at 2.0 * the minimum distance, the force is 0.000045
  12693. angle = Math.atan2(dy, dx);
  12694. if (distance < 0.5*minimumDistance) { // at 0.5 * the minimum distance, the force is 0.993307
  12695. repulsingForce = 1.0;
  12696. }
  12697. else {
  12698. // TODO: correct factor for repulsing force
  12699. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12700. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  12701. repulsingForce = 1 / (1 + Math.exp((distance / (minimumDistance / 2) - 1) * steepness)); // TODO: customize the repulsing force
  12702. }
  12703. fx = Math.cos(angle) * repulsingForce;
  12704. fy = Math.sin(angle) * repulsingForce;
  12705. node._addForce(fx, fy);
  12706. edge.from._addForce(-fx/2,-fy/2);
  12707. edge.to._addForce(-fx/2,-fy/2);
  12708. }
  12709. }
  12710. }
  12711. }
  12712. }
  12713. */
  12714. // forces caused by the edges, modelled as springs
  12715. for (edgeId in edges) {
  12716. if (edges.hasOwnProperty(edgeId)) {
  12717. edge = edges[edgeId];
  12718. if (edge.connected) {
  12719. // only calculate forces if nodes are in the same sector
  12720. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  12721. clusterSize = (edge.to.clusterSize + edge.from.clusterSize - 2);
  12722. dx = (edge.to.x - edge.from.x);
  12723. dy = (edge.to.y - edge.from.y);
  12724. //edgeLength = (edge.from.width + edge.from.height + edge.to.width + edge.to.height)/2 || edge.length; // TODO: dmin
  12725. //edgeLength = (edge.from.width + edge.to.width)/2 || edge.length; // TODO: dmin
  12726. //edgeLength = 20 + ((edge.from.width + edge.to.width) || 0) / 2;
  12727. edgeLength = edge.length;
  12728. // this implies that the edges between big clusters are longer
  12729. edgeLength += clusterSize * this.constants.clustering.edgeGrowth;
  12730. length = Math.sqrt(dx * dx + dy * dy);
  12731. angle = Math.atan2(dy, dx);
  12732. springForce = edge.stiffness * (edgeLength - length);
  12733. fx = Math.cos(angle) * springForce;
  12734. fy = Math.sin(angle) * springForce;
  12735. edge.from._addForce(-fx, -fy);
  12736. edge.to._addForce(fx, fy);
  12737. }
  12738. }
  12739. }
  12740. }
  12741. /*
  12742. // TODO: re-implement repulsion of edges
  12743. // repulsing forces between edges
  12744. var minimumDistance = this.constants.edges.distance,
  12745. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  12746. for (var l = 0; l < edges.length; l++) {
  12747. //Keep distance from other edge centers
  12748. for (var l2 = l + 1; l2 < this.edges.length; l2++) {
  12749. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  12750. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  12751. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  12752. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  12753. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  12754. l2x = edges[l2].from.x+(edges[l2].to.x - edges[l2].from.x)/2,
  12755. l2y = edges[l2].from.y+(edges[l2].to.y - edges[l2].from.y)/2,
  12756. // calculate normally distributed force
  12757. dx = l2x - lx,
  12758. dy = l2y - ly,
  12759. distance = Math.sqrt(dx * dx + dy * dy),
  12760. angle = Math.atan2(dy, dx),
  12761. // TODO: correct factor for repulsing force
  12762. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12763. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  12764. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  12765. fx = Math.cos(angle) * repulsingforce,
  12766. fy = Math.sin(angle) * repulsingforce;
  12767. edges[l].from._addForce(-fx, -fy);
  12768. edges[l].to._addForce(-fx, -fy);
  12769. edges[l2].from._addForce(fx, fy);
  12770. edges[l2].to._addForce(fx, fy);
  12771. }
  12772. }
  12773. */
  12774. };
  12775. /**
  12776. * Check if any of the nodes is still moving
  12777. * @param {number} vmin the minimum velocity considered as 'moving'
  12778. * @return {boolean} true if moving, false if non of the nodes is moving
  12779. * @private
  12780. */
  12781. Graph.prototype._isMoving = function(vmin) {
  12782. // TODO: ismoving does not work well: should check the kinetic energy, not its velocity
  12783. var nodes = this.nodes;
  12784. for (var id in nodes) {
  12785. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  12786. return true;
  12787. }
  12788. }
  12789. return false;
  12790. };
  12791. /**
  12792. * Perform one discrete step for all nodes
  12793. * @private
  12794. */
  12795. Graph.prototype._discreteStepNodes = function() {
  12796. var interval = this.calculationRefreshRate / 1000.0; // in seconds
  12797. var nodes = this.nodes;
  12798. for (var id in nodes) {
  12799. if (nodes.hasOwnProperty(id)) {
  12800. nodes[id].discreteStep(interval);
  12801. }
  12802. }
  12803. var vmin = this.constants.minVelocity;
  12804. this.moving = this._isMoving(vmin);
  12805. };
  12806. /**
  12807. * Start animating nodes and edges
  12808. *
  12809. * @poram {Boolean} runCalculationStep
  12810. */
  12811. Graph.prototype.start = function(runCalculationStep) {
  12812. if (runCalculationStep === undefined) {
  12813. runCalculationStep = true;
  12814. }
  12815. if (!this.freezeSimulation) {
  12816. if (this.moving && runCalculationStep) {
  12817. this._doInAllActiveSectors("_initializeForceCalculation");
  12818. this._doInAllActiveSectors("_discreteStepNodes");
  12819. }
  12820. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  12821. // start animation. only start calculationTimer if it is not already running
  12822. if (!this.timer) {
  12823. var graph = this;
  12824. this.timer = window.setTimeout(function () {
  12825. graph.timer = undefined;
  12826. // keyboad movement
  12827. if (graph.xIncrement != 0 || graph.yIncrement != 0) {
  12828. var translation = graph._getTranslation();
  12829. graph._setTranslation(translation.x+graph.xIncrement,translation.y+graph.yIncrement);
  12830. }
  12831. if (graph.zoomIncrement != 0) {
  12832. graph._zoom(graph.scale*(1 + graph.zoomIncrement),graph.lastPointerPosition);
  12833. }
  12834. var calculateNextStep = false;
  12835. var time = window.performance.now();
  12836. if (time - graph.calculationStartTime > graph.calculationRefreshRate && graph.moving) {
  12837. calculateNextStep = true;
  12838. graph.calculationStartTime = window.performance.now();
  12839. }
  12840. graph.start(calculateNextStep);
  12841. //var startTime = window.performance.now();
  12842. graph._redraw();
  12843. //var end = window.performance.now();
  12844. //time = end - startTime;
  12845. //console.log('Drawing time: ' + time);
  12846. //this.end = window.performance.now();
  12847. //this.time = this.end - this.startTime;
  12848. //console.log('refresh time: ' + this.time);
  12849. //this.startTime = window.performance.now();
  12850. }, this.renderRefreshRate);
  12851. }
  12852. }
  12853. else {
  12854. this._redraw();
  12855. }
  12856. }
  12857. };
  12858. Graph.prototype.singleStep = function() {
  12859. if (this.moving) {
  12860. this._initializeForceCalculation();
  12861. this._discreteStepNodes();
  12862. var vmin = this.constants.minVelocity;
  12863. this.moving = this._isMoving(vmin);
  12864. this._redraw();
  12865. }
  12866. };
  12867. /**
  12868. * Freeze the animation
  12869. */
  12870. Graph.prototype.toggleFreeze = function() {
  12871. if (this.freezeSimulation == false) {
  12872. this.freezeSimulation = true;
  12873. }
  12874. else {
  12875. this.freezeSimulation = false;
  12876. this.start();
  12877. }
  12878. };
  12879. /**
  12880. * Mixin the cluster system and initialize the parameters required.
  12881. *
  12882. * @private
  12883. */
  12884. Graph.prototype._loadClusterSystem = function() {
  12885. this.clusterSession = 0;
  12886. this.hubThreshold = 5;
  12887. for (var mixinFunction in ClusterMixin) {
  12888. if (ClusterMixin.hasOwnProperty(mixinFunction)) {
  12889. Graph.prototype[mixinFunction] = ClusterMixin[mixinFunction];
  12890. }
  12891. }
  12892. }
  12893. /**
  12894. * Mixin the sector system and initialize the parameters required
  12895. *
  12896. * @private
  12897. */
  12898. Graph.prototype._loadSectorSystem = function() {
  12899. this.sectors = {};
  12900. this.activeSector = ["default"];
  12901. this.sectors["active"] = {};
  12902. this.sectors["active"]["default"] = {"nodes":{},
  12903. "edges":{},
  12904. "nodeIndices":[],
  12905. "formationScale": 1.0,
  12906. "drawingNode": undefined};
  12907. this.sectors["frozen"] = {};
  12908. this.sectors["UI"] = {"nodes":{},
  12909. "edges":{},
  12910. "nodeIndices":[],
  12911. "formationScale": 1.0,
  12912. "drawingNode": undefined};
  12913. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  12914. for (var mixinFunction in SectorMixin) {
  12915. if (SectorMixin.hasOwnProperty(mixinFunction)) {
  12916. Graph.prototype[mixinFunction] = SectorMixin[mixinFunction];
  12917. }
  12918. }
  12919. };
  12920. /**
  12921. * Mixin the selection system and initialize the parameters required
  12922. *
  12923. * @private
  12924. */
  12925. Graph.prototype._loadSelectionSystem = function() {
  12926. this.selection = [];
  12927. this.selectionObj = {};
  12928. for (var mixinFunction in SelectionMixin) {
  12929. if (SelectionMixin.hasOwnProperty(mixinFunction)) {
  12930. Graph.prototype[mixinFunction] = SelectionMixin[mixinFunction];
  12931. }
  12932. }
  12933. }
  12934. /**
  12935. * Mixin the UI (User Interface) system and initialize the parameters required
  12936. *
  12937. * @private
  12938. */
  12939. Graph.prototype._loadUISystem = function() {
  12940. for (var mixinFunction in UIMixin) {
  12941. if (UIMixin.hasOwnProperty(mixinFunction)) {
  12942. Graph.prototype[mixinFunction] = UIMixin[mixinFunction];
  12943. }
  12944. }
  12945. if (this.constants.UI.enabled == true) {
  12946. this._loadUIElements();
  12947. this._createKeyBinds();
  12948. }
  12949. }
  12950. /**
  12951. * this function exists to avoid errors when not loading the UI system
  12952. */
  12953. Graph.prototype._relocateUI = function() {
  12954. // empty, is overloaded by UI system
  12955. }
  12956. /**
  12957. * * this function exists to avoid errors when not loading the UI system
  12958. */
  12959. Graph.prototype._unHighlightAll = function() {
  12960. // empty, is overloaded by the UI system
  12961. }
  12962. /**
  12963. * vis.js module exports
  12964. */
  12965. var vis = {
  12966. util: util,
  12967. events: events,
  12968. Controller: Controller,
  12969. DataSet: DataSet,
  12970. DataView: DataView,
  12971. Range: Range,
  12972. Stack: Stack,
  12973. TimeStep: TimeStep,
  12974. EventBus: EventBus,
  12975. components: {
  12976. items: {
  12977. Item: Item,
  12978. ItemBox: ItemBox,
  12979. ItemPoint: ItemPoint,
  12980. ItemRange: ItemRange
  12981. },
  12982. Component: Component,
  12983. Panel: Panel,
  12984. RootPanel: RootPanel,
  12985. ItemSet: ItemSet,
  12986. TimeAxis: TimeAxis
  12987. },
  12988. graph: {
  12989. Node: Node,
  12990. Edge: Edge,
  12991. Popup: Popup,
  12992. Groups: Groups,
  12993. Images: Images
  12994. },
  12995. Timeline: Timeline,
  12996. Graph: Graph
  12997. };
  12998. /**
  12999. * CommonJS module exports
  13000. */
  13001. if (typeof exports !== 'undefined') {
  13002. exports = vis;
  13003. }
  13004. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  13005. module.exports = vis;
  13006. }
  13007. /**
  13008. * AMD module exports
  13009. */
  13010. if (typeof(define) === 'function') {
  13011. define(function () {
  13012. return vis;
  13013. });
  13014. }
  13015. /**
  13016. * Window exports
  13017. */
  13018. if (typeof window !== 'undefined') {
  13019. // attach the module to the window, load as a regular javascript file
  13020. window['vis'] = vis;
  13021. }
  13022. },{"hammerjs":2,"moment":3,"mouseTrap":4}],2:[function(require,module,exports){
  13023. /*! Hammer.JS - v1.0.5 - 2013-04-07
  13024. * http://eightmedia.github.com/hammer.js
  13025. *
  13026. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  13027. * Licensed under the MIT license */
  13028. (function(window, undefined) {
  13029. 'use strict';
  13030. /**
  13031. * Hammer
  13032. * use this to create instances
  13033. * @param {HTMLElement} element
  13034. * @param {Object} options
  13035. * @returns {Hammer.Instance}
  13036. * @constructor
  13037. */
  13038. var Hammer = function(element, options) {
  13039. return new Hammer.Instance(element, options || {});
  13040. };
  13041. // default settings
  13042. Hammer.defaults = {
  13043. // add styles and attributes to the element to prevent the browser from doing
  13044. // its native behavior. this doesnt prevent the scrolling, but cancels
  13045. // the contextmenu, tap highlighting etc
  13046. // set to false to disable this
  13047. stop_browser_behavior: {
  13048. // this also triggers onselectstart=false for IE
  13049. userSelect: 'none',
  13050. // this makes the element blocking in IE10 >, you could experiment with the value
  13051. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  13052. touchAction: 'none',
  13053. touchCallout: 'none',
  13054. contentZooming: 'none',
  13055. userDrag: 'none',
  13056. tapHighlightColor: 'rgba(0,0,0,0)'
  13057. }
  13058. // more settings are defined per gesture at gestures.js
  13059. };
  13060. // detect touchevents
  13061. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  13062. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  13063. // dont use mouseevents on mobile devices
  13064. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  13065. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  13066. // eventtypes per touchevent (start, move, end)
  13067. // are filled by Hammer.event.determineEventTypes on setup
  13068. Hammer.EVENT_TYPES = {};
  13069. // direction defines
  13070. Hammer.DIRECTION_DOWN = 'down';
  13071. Hammer.DIRECTION_LEFT = 'left';
  13072. Hammer.DIRECTION_UP = 'up';
  13073. Hammer.DIRECTION_RIGHT = 'right';
  13074. // pointer type
  13075. Hammer.POINTER_MOUSE = 'mouse';
  13076. Hammer.POINTER_TOUCH = 'touch';
  13077. Hammer.POINTER_PEN = 'pen';
  13078. // touch event defines
  13079. Hammer.EVENT_START = 'start';
  13080. Hammer.EVENT_MOVE = 'move';
  13081. Hammer.EVENT_END = 'end';
  13082. // hammer document where the base events are added at
  13083. Hammer.DOCUMENT = document;
  13084. // plugins namespace
  13085. Hammer.plugins = {};
  13086. // if the window events are set...
  13087. Hammer.READY = false;
  13088. /**
  13089. * setup events to detect gestures on the document
  13090. */
  13091. function setup() {
  13092. if(Hammer.READY) {
  13093. return;
  13094. }
  13095. // find what eventtypes we add listeners to
  13096. Hammer.event.determineEventTypes();
  13097. // Register all gestures inside Hammer.gestures
  13098. for(var name in Hammer.gestures) {
  13099. if(Hammer.gestures.hasOwnProperty(name)) {
  13100. Hammer.detection.register(Hammer.gestures[name]);
  13101. }
  13102. }
  13103. // Add touch events on the document
  13104. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  13105. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  13106. // Hammer is ready...!
  13107. Hammer.READY = true;
  13108. }
  13109. /**
  13110. * create new hammer instance
  13111. * all methods should return the instance itself, so it is chainable.
  13112. * @param {HTMLElement} element
  13113. * @param {Object} [options={}]
  13114. * @returns {Hammer.Instance}
  13115. * @constructor
  13116. */
  13117. Hammer.Instance = function(element, options) {
  13118. var self = this;
  13119. // setup HammerJS window events and register all gestures
  13120. // this also sets up the default options
  13121. setup();
  13122. this.element = element;
  13123. // start/stop detection option
  13124. this.enabled = true;
  13125. // merge options
  13126. this.options = Hammer.utils.extend(
  13127. Hammer.utils.extend({}, Hammer.defaults),
  13128. options || {});
  13129. // add some css to the element to prevent the browser from doing its native behavoir
  13130. if(this.options.stop_browser_behavior) {
  13131. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  13132. }
  13133. // start detection on touchstart
  13134. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  13135. if(self.enabled) {
  13136. Hammer.detection.startDetect(self, ev);
  13137. }
  13138. });
  13139. // return instance
  13140. return this;
  13141. };
  13142. Hammer.Instance.prototype = {
  13143. /**
  13144. * bind events to the instance
  13145. * @param {String} gesture
  13146. * @param {Function} handler
  13147. * @returns {Hammer.Instance}
  13148. */
  13149. on: function onEvent(gesture, handler){
  13150. var gestures = gesture.split(' ');
  13151. for(var t=0; t<gestures.length; t++) {
  13152. this.element.addEventListener(gestures[t], handler, false);
  13153. }
  13154. return this;
  13155. },
  13156. /**
  13157. * unbind events to the instance
  13158. * @param {String} gesture
  13159. * @param {Function} handler
  13160. * @returns {Hammer.Instance}
  13161. */
  13162. off: function offEvent(gesture, handler){
  13163. var gestures = gesture.split(' ');
  13164. for(var t=0; t<gestures.length; t++) {
  13165. this.element.removeEventListener(gestures[t], handler, false);
  13166. }
  13167. return this;
  13168. },
  13169. /**
  13170. * trigger gesture event
  13171. * @param {String} gesture
  13172. * @param {Object} eventData
  13173. * @returns {Hammer.Instance}
  13174. */
  13175. trigger: function triggerEvent(gesture, eventData){
  13176. // create DOM event
  13177. var event = Hammer.DOCUMENT.createEvent('Event');
  13178. event.initEvent(gesture, true, true);
  13179. event.gesture = eventData;
  13180. // trigger on the target if it is in the instance element,
  13181. // this is for event delegation tricks
  13182. var element = this.element;
  13183. if(Hammer.utils.hasParent(eventData.target, element)) {
  13184. element = eventData.target;
  13185. }
  13186. element.dispatchEvent(event);
  13187. return this;
  13188. },
  13189. /**
  13190. * enable of disable hammer.js detection
  13191. * @param {Boolean} state
  13192. * @returns {Hammer.Instance}
  13193. */
  13194. enable: function enable(state) {
  13195. this.enabled = state;
  13196. return this;
  13197. }
  13198. };
  13199. /**
  13200. * this holds the last move event,
  13201. * used to fix empty touchend issue
  13202. * see the onTouch event for an explanation
  13203. * @type {Object}
  13204. */
  13205. var last_move_event = null;
  13206. /**
  13207. * when the mouse is hold down, this is true
  13208. * @type {Boolean}
  13209. */
  13210. var enable_detect = false;
  13211. /**
  13212. * when touch events have been fired, this is true
  13213. * @type {Boolean}
  13214. */
  13215. var touch_triggered = false;
  13216. Hammer.event = {
  13217. /**
  13218. * simple addEventListener
  13219. * @param {HTMLElement} element
  13220. * @param {String} type
  13221. * @param {Function} handler
  13222. */
  13223. bindDom: function(element, type, handler) {
  13224. var types = type.split(' ');
  13225. for(var t=0; t<types.length; t++) {
  13226. element.addEventListener(types[t], handler, false);
  13227. }
  13228. },
  13229. /**
  13230. * touch events with mouse fallback
  13231. * @param {HTMLElement} element
  13232. * @param {String} eventType like Hammer.EVENT_MOVE
  13233. * @param {Function} handler
  13234. */
  13235. onTouch: function onTouch(element, eventType, handler) {
  13236. var self = this;
  13237. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  13238. var sourceEventType = ev.type.toLowerCase();
  13239. // onmouseup, but when touchend has been fired we do nothing.
  13240. // this is for touchdevices which also fire a mouseup on touchend
  13241. if(sourceEventType.match(/mouse/) && touch_triggered) {
  13242. return;
  13243. }
  13244. // mousebutton must be down or a touch event
  13245. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  13246. sourceEventType.match(/pointerdown/) || // pointerevents touch
  13247. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  13248. ){
  13249. enable_detect = true;
  13250. }
  13251. // we are in a touch event, set the touch triggered bool to true,
  13252. // this for the conflicts that may occur on ios and android
  13253. if(sourceEventType.match(/touch|pointer/)) {
  13254. touch_triggered = true;
  13255. }
  13256. // count the total touches on the screen
  13257. var count_touches = 0;
  13258. // when touch has been triggered in this detection session
  13259. // and we are now handling a mouse event, we stop that to prevent conflicts
  13260. if(enable_detect) {
  13261. // update pointerevent
  13262. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  13263. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  13264. }
  13265. // touch
  13266. else if(sourceEventType.match(/touch/)) {
  13267. count_touches = ev.touches.length;
  13268. }
  13269. // mouse
  13270. else if(!touch_triggered) {
  13271. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  13272. }
  13273. // if we are in a end event, but when we remove one touch and
  13274. // we still have enough, set eventType to move
  13275. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  13276. eventType = Hammer.EVENT_MOVE;
  13277. }
  13278. // no touches, force the end event
  13279. else if(!count_touches) {
  13280. eventType = Hammer.EVENT_END;
  13281. }
  13282. // because touchend has no touches, and we often want to use these in our gestures,
  13283. // we send the last move event as our eventData in touchend
  13284. if(!count_touches && last_move_event !== null) {
  13285. ev = last_move_event;
  13286. }
  13287. // store the last move event
  13288. else {
  13289. last_move_event = ev;
  13290. }
  13291. // trigger the handler
  13292. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  13293. // remove pointerevent from list
  13294. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  13295. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  13296. }
  13297. }
  13298. //debug(sourceEventType +" "+ eventType);
  13299. // on the end we reset everything
  13300. if(!count_touches) {
  13301. last_move_event = null;
  13302. enable_detect = false;
  13303. touch_triggered = false;
  13304. Hammer.PointerEvent.reset();
  13305. }
  13306. });
  13307. },
  13308. /**
  13309. * we have different events for each device/browser
  13310. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  13311. */
  13312. determineEventTypes: function determineEventTypes() {
  13313. // determine the eventtype we want to set
  13314. var types;
  13315. // pointerEvents magic
  13316. if(Hammer.HAS_POINTEREVENTS) {
  13317. types = Hammer.PointerEvent.getEvents();
  13318. }
  13319. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  13320. else if(Hammer.NO_MOUSEEVENTS) {
  13321. types = [
  13322. 'touchstart',
  13323. 'touchmove',
  13324. 'touchend touchcancel'];
  13325. }
  13326. // for non pointer events browsers and mixed browsers,
  13327. // like chrome on windows8 touch laptop
  13328. else {
  13329. types = [
  13330. 'touchstart mousedown',
  13331. 'touchmove mousemove',
  13332. 'touchend touchcancel mouseup'];
  13333. }
  13334. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  13335. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  13336. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  13337. },
  13338. /**
  13339. * create touchlist depending on the event
  13340. * @param {Object} ev
  13341. * @param {String} eventType used by the fakemultitouch plugin
  13342. */
  13343. getTouchList: function getTouchList(ev/*, eventType*/) {
  13344. // get the fake pointerEvent touchlist
  13345. if(Hammer.HAS_POINTEREVENTS) {
  13346. return Hammer.PointerEvent.getTouchList();
  13347. }
  13348. // get the touchlist
  13349. else if(ev.touches) {
  13350. return ev.touches;
  13351. }
  13352. // make fake touchlist from mouse position
  13353. else {
  13354. return [{
  13355. identifier: 1,
  13356. pageX: ev.pageX,
  13357. pageY: ev.pageY,
  13358. target: ev.target
  13359. }];
  13360. }
  13361. },
  13362. /**
  13363. * collect event data for Hammer js
  13364. * @param {HTMLElement} element
  13365. * @param {String} eventType like Hammer.EVENT_MOVE
  13366. * @param {Object} eventData
  13367. */
  13368. collectEventData: function collectEventData(element, eventType, ev) {
  13369. var touches = this.getTouchList(ev, eventType);
  13370. // find out pointerType
  13371. var pointerType = Hammer.POINTER_TOUCH;
  13372. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  13373. pointerType = Hammer.POINTER_MOUSE;
  13374. }
  13375. return {
  13376. center : Hammer.utils.getCenter(touches),
  13377. timeStamp : new Date().getTime(),
  13378. target : ev.target,
  13379. touches : touches,
  13380. eventType : eventType,
  13381. pointerType : pointerType,
  13382. srcEvent : ev,
  13383. /**
  13384. * prevent the browser default actions
  13385. * mostly used to disable scrolling of the browser
  13386. */
  13387. preventDefault: function() {
  13388. if(this.srcEvent.preventManipulation) {
  13389. this.srcEvent.preventManipulation();
  13390. }
  13391. if(this.srcEvent.preventDefault) {
  13392. this.srcEvent.preventDefault();
  13393. }
  13394. },
  13395. /**
  13396. * stop bubbling the event up to its parents
  13397. */
  13398. stopPropagation: function() {
  13399. this.srcEvent.stopPropagation();
  13400. },
  13401. /**
  13402. * immediately stop gesture detection
  13403. * might be useful after a swipe was detected
  13404. * @return {*}
  13405. */
  13406. stopDetect: function() {
  13407. return Hammer.detection.stopDetect();
  13408. }
  13409. };
  13410. }
  13411. };
  13412. Hammer.PointerEvent = {
  13413. /**
  13414. * holds all pointers
  13415. * @type {Object}
  13416. */
  13417. pointers: {},
  13418. /**
  13419. * get a list of pointers
  13420. * @returns {Array} touchlist
  13421. */
  13422. getTouchList: function() {
  13423. var self = this;
  13424. var touchlist = [];
  13425. // we can use forEach since pointerEvents only is in IE10
  13426. Object.keys(self.pointers).sort().forEach(function(id) {
  13427. touchlist.push(self.pointers[id]);
  13428. });
  13429. return touchlist;
  13430. },
  13431. /**
  13432. * update the position of a pointer
  13433. * @param {String} type Hammer.EVENT_END
  13434. * @param {Object} pointerEvent
  13435. */
  13436. updatePointer: function(type, pointerEvent) {
  13437. if(type == Hammer.EVENT_END) {
  13438. this.pointers = {};
  13439. }
  13440. else {
  13441. pointerEvent.identifier = pointerEvent.pointerId;
  13442. this.pointers[pointerEvent.pointerId] = pointerEvent;
  13443. }
  13444. return Object.keys(this.pointers).length;
  13445. },
  13446. /**
  13447. * check if ev matches pointertype
  13448. * @param {String} pointerType Hammer.POINTER_MOUSE
  13449. * @param {PointerEvent} ev
  13450. */
  13451. matchType: function(pointerType, ev) {
  13452. if(!ev.pointerType) {
  13453. return false;
  13454. }
  13455. var types = {};
  13456. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  13457. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  13458. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  13459. return types[pointerType];
  13460. },
  13461. /**
  13462. * get events
  13463. */
  13464. getEvents: function() {
  13465. return [
  13466. 'pointerdown MSPointerDown',
  13467. 'pointermove MSPointerMove',
  13468. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  13469. ];
  13470. },
  13471. /**
  13472. * reset the list
  13473. */
  13474. reset: function() {
  13475. this.pointers = {};
  13476. }
  13477. };
  13478. Hammer.utils = {
  13479. /**
  13480. * extend method,
  13481. * also used for cloning when dest is an empty object
  13482. * @param {Object} dest
  13483. * @param {Object} src
  13484. * @parm {Boolean} merge do a merge
  13485. * @returns {Object} dest
  13486. */
  13487. extend: function extend(dest, src, merge) {
  13488. for (var key in src) {
  13489. if(dest[key] !== undefined && merge) {
  13490. continue;
  13491. }
  13492. dest[key] = src[key];
  13493. }
  13494. return dest;
  13495. },
  13496. /**
  13497. * find if a node is in the given parent
  13498. * used for event delegation tricks
  13499. * @param {HTMLElement} node
  13500. * @param {HTMLElement} parent
  13501. * @returns {boolean} has_parent
  13502. */
  13503. hasParent: function(node, parent) {
  13504. while(node){
  13505. if(node == parent) {
  13506. return true;
  13507. }
  13508. node = node.parentNode;
  13509. }
  13510. return false;
  13511. },
  13512. /**
  13513. * get the center of all the touches
  13514. * @param {Array} touches
  13515. * @returns {Object} center
  13516. */
  13517. getCenter: function getCenter(touches) {
  13518. var valuesX = [], valuesY = [];
  13519. for(var t= 0,len=touches.length; t<len; t++) {
  13520. valuesX.push(touches[t].pageX);
  13521. valuesY.push(touches[t].pageY);
  13522. }
  13523. return {
  13524. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  13525. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  13526. };
  13527. },
  13528. /**
  13529. * calculate the velocity between two points
  13530. * @param {Number} delta_time
  13531. * @param {Number} delta_x
  13532. * @param {Number} delta_y
  13533. * @returns {Object} velocity
  13534. */
  13535. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  13536. return {
  13537. x: Math.abs(delta_x / delta_time) || 0,
  13538. y: Math.abs(delta_y / delta_time) || 0
  13539. };
  13540. },
  13541. /**
  13542. * calculate the angle between two coordinates
  13543. * @param {Touch} touch1
  13544. * @param {Touch} touch2
  13545. * @returns {Number} angle
  13546. */
  13547. getAngle: function getAngle(touch1, touch2) {
  13548. var y = touch2.pageY - touch1.pageY,
  13549. x = touch2.pageX - touch1.pageX;
  13550. return Math.atan2(y, x) * 180 / Math.PI;
  13551. },
  13552. /**
  13553. * angle to direction define
  13554. * @param {Touch} touch1
  13555. * @param {Touch} touch2
  13556. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  13557. */
  13558. getDirection: function getDirection(touch1, touch2) {
  13559. var x = Math.abs(touch1.pageX - touch2.pageX),
  13560. y = Math.abs(touch1.pageY - touch2.pageY);
  13561. if(x >= y) {
  13562. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  13563. }
  13564. else {
  13565. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  13566. }
  13567. },
  13568. /**
  13569. * calculate the distance between two touches
  13570. * @param {Touch} touch1
  13571. * @param {Touch} touch2
  13572. * @returns {Number} distance
  13573. */
  13574. getDistance: function getDistance(touch1, touch2) {
  13575. var x = touch2.pageX - touch1.pageX,
  13576. y = touch2.pageY - touch1.pageY;
  13577. return Math.sqrt((x*x) + (y*y));
  13578. },
  13579. /**
  13580. * calculate the scale factor between two touchLists (fingers)
  13581. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  13582. * @param {Array} start
  13583. * @param {Array} end
  13584. * @returns {Number} scale
  13585. */
  13586. getScale: function getScale(start, end) {
  13587. // need two fingers...
  13588. if(start.length >= 2 && end.length >= 2) {
  13589. return this.getDistance(end[0], end[1]) /
  13590. this.getDistance(start[0], start[1]);
  13591. }
  13592. return 1;
  13593. },
  13594. /**
  13595. * calculate the rotation degrees between two touchLists (fingers)
  13596. * @param {Array} start
  13597. * @param {Array} end
  13598. * @returns {Number} rotation
  13599. */
  13600. getRotation: function getRotation(start, end) {
  13601. // need two fingers
  13602. if(start.length >= 2 && end.length >= 2) {
  13603. return this.getAngle(end[1], end[0]) -
  13604. this.getAngle(start[1], start[0]);
  13605. }
  13606. return 0;
  13607. },
  13608. /**
  13609. * boolean if the direction is vertical
  13610. * @param {String} direction
  13611. * @returns {Boolean} is_vertical
  13612. */
  13613. isVertical: function isVertical(direction) {
  13614. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  13615. },
  13616. /**
  13617. * stop browser default behavior with css props
  13618. * @param {HtmlElement} element
  13619. * @param {Object} css_props
  13620. */
  13621. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  13622. var prop,
  13623. vendors = ['webkit','khtml','moz','ms','o',''];
  13624. if(!css_props || !element.style) {
  13625. return;
  13626. }
  13627. // with css properties for modern browsers
  13628. for(var i = 0; i < vendors.length; i++) {
  13629. for(var p in css_props) {
  13630. if(css_props.hasOwnProperty(p)) {
  13631. prop = p;
  13632. // vender prefix at the property
  13633. if(vendors[i]) {
  13634. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  13635. }
  13636. // set the style
  13637. element.style[prop] = css_props[p];
  13638. }
  13639. }
  13640. }
  13641. // also the disable onselectstart
  13642. if(css_props.userSelect == 'none') {
  13643. element.onselectstart = function() {
  13644. return false;
  13645. };
  13646. }
  13647. }
  13648. };
  13649. Hammer.detection = {
  13650. // contains all registred Hammer.gestures in the correct order
  13651. gestures: [],
  13652. // data of the current Hammer.gesture detection session
  13653. current: null,
  13654. // the previous Hammer.gesture session data
  13655. // is a full clone of the previous gesture.current object
  13656. previous: null,
  13657. // when this becomes true, no gestures are fired
  13658. stopped: false,
  13659. /**
  13660. * start Hammer.gesture detection
  13661. * @param {Hammer.Instance} inst
  13662. * @param {Object} eventData
  13663. */
  13664. startDetect: function startDetect(inst, eventData) {
  13665. // already busy with a Hammer.gesture detection on an element
  13666. if(this.current) {
  13667. return;
  13668. }
  13669. this.stopped = false;
  13670. this.current = {
  13671. inst : inst, // reference to HammerInstance we're working for
  13672. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  13673. lastEvent : false, // last eventData
  13674. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  13675. };
  13676. this.detect(eventData);
  13677. },
  13678. /**
  13679. * Hammer.gesture detection
  13680. * @param {Object} eventData
  13681. * @param {Object} eventData
  13682. */
  13683. detect: function detect(eventData) {
  13684. if(!this.current || this.stopped) {
  13685. return;
  13686. }
  13687. // extend event data with calculations about scale, distance etc
  13688. eventData = this.extendEventData(eventData);
  13689. // instance options
  13690. var inst_options = this.current.inst.options;
  13691. // call Hammer.gesture handlers
  13692. for(var g=0,len=this.gestures.length; g<len; g++) {
  13693. var gesture = this.gestures[g];
  13694. // only when the instance options have enabled this gesture
  13695. if(!this.stopped && inst_options[gesture.name] !== false) {
  13696. // if a handler returns false, we stop with the detection
  13697. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  13698. this.stopDetect();
  13699. break;
  13700. }
  13701. }
  13702. }
  13703. // store as previous event event
  13704. if(this.current) {
  13705. this.current.lastEvent = eventData;
  13706. }
  13707. // endevent, but not the last touch, so dont stop
  13708. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  13709. this.stopDetect();
  13710. }
  13711. return eventData;
  13712. },
  13713. /**
  13714. * clear the Hammer.gesture vars
  13715. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  13716. * to stop other Hammer.gestures from being fired
  13717. */
  13718. stopDetect: function stopDetect() {
  13719. // clone current data to the store as the previous gesture
  13720. // used for the double tap gesture, since this is an other gesture detect session
  13721. this.previous = Hammer.utils.extend({}, this.current);
  13722. // reset the current
  13723. this.current = null;
  13724. // stopped!
  13725. this.stopped = true;
  13726. },
  13727. /**
  13728. * extend eventData for Hammer.gestures
  13729. * @param {Object} ev
  13730. * @returns {Object} ev
  13731. */
  13732. extendEventData: function extendEventData(ev) {
  13733. var startEv = this.current.startEvent;
  13734. // if the touches change, set the new touches over the startEvent touches
  13735. // this because touchevents don't have all the touches on touchstart, or the
  13736. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  13737. // but, sometimes it happens that both fingers are touching at the EXACT same time
  13738. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  13739. // extend 1 level deep to get the touchlist with the touch objects
  13740. startEv.touches = [];
  13741. for(var i=0,len=ev.touches.length; i<len; i++) {
  13742. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  13743. }
  13744. }
  13745. var delta_time = ev.timeStamp - startEv.timeStamp,
  13746. delta_x = ev.center.pageX - startEv.center.pageX,
  13747. delta_y = ev.center.pageY - startEv.center.pageY,
  13748. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  13749. Hammer.utils.extend(ev, {
  13750. deltaTime : delta_time,
  13751. deltaX : delta_x,
  13752. deltaY : delta_y,
  13753. velocityX : velocity.x,
  13754. velocityY : velocity.y,
  13755. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  13756. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  13757. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  13758. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  13759. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  13760. startEvent : startEv
  13761. });
  13762. return ev;
  13763. },
  13764. /**
  13765. * register new gesture
  13766. * @param {Object} gesture object, see gestures.js for documentation
  13767. * @returns {Array} gestures
  13768. */
  13769. register: function register(gesture) {
  13770. // add an enable gesture options if there is no given
  13771. var options = gesture.defaults || {};
  13772. if(options[gesture.name] === undefined) {
  13773. options[gesture.name] = true;
  13774. }
  13775. // extend Hammer default options with the Hammer.gesture options
  13776. Hammer.utils.extend(Hammer.defaults, options, true);
  13777. // set its index
  13778. gesture.index = gesture.index || 1000;
  13779. // add Hammer.gesture to the list
  13780. this.gestures.push(gesture);
  13781. // sort the list by index
  13782. this.gestures.sort(function(a, b) {
  13783. if (a.index < b.index) {
  13784. return -1;
  13785. }
  13786. if (a.index > b.index) {
  13787. return 1;
  13788. }
  13789. return 0;
  13790. });
  13791. return this.gestures;
  13792. }
  13793. };
  13794. Hammer.gestures = Hammer.gestures || {};
  13795. /**
  13796. * Custom gestures
  13797. * ==============================
  13798. *
  13799. * Gesture object
  13800. * --------------------
  13801. * The object structure of a gesture:
  13802. *
  13803. * { name: 'mygesture',
  13804. * index: 1337,
  13805. * defaults: {
  13806. * mygesture_option: true
  13807. * }
  13808. * handler: function(type, ev, inst) {
  13809. * // trigger gesture event
  13810. * inst.trigger(this.name, ev);
  13811. * }
  13812. * }
  13813. * @param {String} name
  13814. * this should be the name of the gesture, lowercase
  13815. * it is also being used to disable/enable the gesture per instance config.
  13816. *
  13817. * @param {Number} [index=1000]
  13818. * the index of the gesture, where it is going to be in the stack of gestures detection
  13819. * like when you build an gesture that depends on the drag gesture, it is a good
  13820. * idea to place it after the index of the drag gesture.
  13821. *
  13822. * @param {Object} [defaults={}]
  13823. * the default settings of the gesture. these are added to the instance settings,
  13824. * and can be overruled per instance. you can also add the name of the gesture,
  13825. * but this is also added by default (and set to true).
  13826. *
  13827. * @param {Function} handler
  13828. * this handles the gesture detection of your custom gesture and receives the
  13829. * following arguments:
  13830. *
  13831. * @param {Object} eventData
  13832. * event data containing the following properties:
  13833. * timeStamp {Number} time the event occurred
  13834. * target {HTMLElement} target element
  13835. * touches {Array} touches (fingers, pointers, mouse) on the screen
  13836. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  13837. * center {Object} center position of the touches. contains pageX and pageY
  13838. * deltaTime {Number} the total time of the touches in the screen
  13839. * deltaX {Number} the delta on x axis we haved moved
  13840. * deltaY {Number} the delta on y axis we haved moved
  13841. * velocityX {Number} the velocity on the x
  13842. * velocityY {Number} the velocity on y
  13843. * angle {Number} the angle we are moving
  13844. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  13845. * distance {Number} the distance we haved moved
  13846. * scale {Number} scaling of the touches, needs 2 touches
  13847. * rotation {Number} rotation of the touches, needs 2 touches *
  13848. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  13849. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  13850. * startEvent {Object} contains the same properties as above,
  13851. * but from the first touch. this is used to calculate
  13852. * distances, deltaTime, scaling etc
  13853. *
  13854. * @param {Hammer.Instance} inst
  13855. * the instance we are doing the detection for. you can get the options from
  13856. * the inst.options object and trigger the gesture event by calling inst.trigger
  13857. *
  13858. *
  13859. * Handle gestures
  13860. * --------------------
  13861. * inside the handler you can get/set Hammer.detection.current. This is the current
  13862. * detection session. It has the following properties
  13863. * @param {String} name
  13864. * contains the name of the gesture we have detected. it has not a real function,
  13865. * only to check in other gestures if something is detected.
  13866. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  13867. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  13868. *
  13869. * @readonly
  13870. * @param {Hammer.Instance} inst
  13871. * the instance we do the detection for
  13872. *
  13873. * @readonly
  13874. * @param {Object} startEvent
  13875. * contains the properties of the first gesture detection in this session.
  13876. * Used for calculations about timing, distance, etc.
  13877. *
  13878. * @readonly
  13879. * @param {Object} lastEvent
  13880. * contains all the properties of the last gesture detect in this session.
  13881. *
  13882. * after the gesture detection session has been completed (user has released the screen)
  13883. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  13884. * this is usefull for gestures like doubletap, where you need to know if the
  13885. * previous gesture was a tap
  13886. *
  13887. * options that have been set by the instance can be received by calling inst.options
  13888. *
  13889. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  13890. * The first param is the name of your gesture, the second the event argument
  13891. *
  13892. *
  13893. * Register gestures
  13894. * --------------------
  13895. * When an gesture is added to the Hammer.gestures object, it is auto registered
  13896. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  13897. * manually and pass your gesture object as a param
  13898. *
  13899. */
  13900. /**
  13901. * Hold
  13902. * Touch stays at the same place for x time
  13903. * @events hold
  13904. */
  13905. Hammer.gestures.Hold = {
  13906. name: 'hold',
  13907. index: 10,
  13908. defaults: {
  13909. hold_timeout : 500,
  13910. hold_threshold : 1
  13911. },
  13912. timer: null,
  13913. handler: function holdGesture(ev, inst) {
  13914. switch(ev.eventType) {
  13915. case Hammer.EVENT_START:
  13916. // clear any running timers
  13917. clearTimeout(this.timer);
  13918. // set the gesture so we can check in the timeout if it still is
  13919. Hammer.detection.current.name = this.name;
  13920. // set timer and if after the timeout it still is hold,
  13921. // we trigger the hold event
  13922. this.timer = setTimeout(function() {
  13923. if(Hammer.detection.current.name == 'hold') {
  13924. inst.trigger('hold', ev);
  13925. }
  13926. }, inst.options.hold_timeout);
  13927. break;
  13928. // when you move or end we clear the timer
  13929. case Hammer.EVENT_MOVE:
  13930. if(ev.distance > inst.options.hold_threshold) {
  13931. clearTimeout(this.timer);
  13932. }
  13933. break;
  13934. case Hammer.EVENT_END:
  13935. clearTimeout(this.timer);
  13936. break;
  13937. }
  13938. }
  13939. };
  13940. /**
  13941. * Tap/DoubleTap
  13942. * Quick touch at a place or double at the same place
  13943. * @events tap, doubletap
  13944. */
  13945. Hammer.gestures.Tap = {
  13946. name: 'tap',
  13947. index: 100,
  13948. defaults: {
  13949. tap_max_touchtime : 250,
  13950. tap_max_distance : 10,
  13951. tap_always : true,
  13952. doubletap_distance : 20,
  13953. doubletap_interval : 300
  13954. },
  13955. handler: function tapGesture(ev, inst) {
  13956. if(ev.eventType == Hammer.EVENT_END) {
  13957. // previous gesture, for the double tap since these are two different gesture detections
  13958. var prev = Hammer.detection.previous,
  13959. did_doubletap = false;
  13960. // when the touchtime is higher then the max touch time
  13961. // or when the moving distance is too much
  13962. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  13963. ev.distance > inst.options.tap_max_distance) {
  13964. return;
  13965. }
  13966. // check if double tap
  13967. if(prev && prev.name == 'tap' &&
  13968. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  13969. ev.distance < inst.options.doubletap_distance) {
  13970. inst.trigger('doubletap', ev);
  13971. did_doubletap = true;
  13972. }
  13973. // do a single tap
  13974. if(!did_doubletap || inst.options.tap_always) {
  13975. Hammer.detection.current.name = 'tap';
  13976. inst.trigger(Hammer.detection.current.name, ev);
  13977. }
  13978. }
  13979. }
  13980. };
  13981. /**
  13982. * Swipe
  13983. * triggers swipe events when the end velocity is above the threshold
  13984. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  13985. */
  13986. Hammer.gestures.Swipe = {
  13987. name: 'swipe',
  13988. index: 40,
  13989. defaults: {
  13990. // set 0 for unlimited, but this can conflict with transform
  13991. swipe_max_touches : 1,
  13992. swipe_velocity : 0.7
  13993. },
  13994. handler: function swipeGesture(ev, inst) {
  13995. if(ev.eventType == Hammer.EVENT_END) {
  13996. // max touches
  13997. if(inst.options.swipe_max_touches > 0 &&
  13998. ev.touches.length > inst.options.swipe_max_touches) {
  13999. return;
  14000. }
  14001. // when the distance we moved is too small we skip this gesture
  14002. // or we can be already in dragging
  14003. if(ev.velocityX > inst.options.swipe_velocity ||
  14004. ev.velocityY > inst.options.swipe_velocity) {
  14005. // trigger swipe events
  14006. inst.trigger(this.name, ev);
  14007. inst.trigger(this.name + ev.direction, ev);
  14008. }
  14009. }
  14010. }
  14011. };
  14012. /**
  14013. * Drag
  14014. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  14015. * moving left and right is a good practice. When all the drag events are blocking
  14016. * you disable scrolling on that area.
  14017. * @events drag, drapleft, dragright, dragup, dragdown
  14018. */
  14019. Hammer.gestures.Drag = {
  14020. name: 'drag',
  14021. index: 50,
  14022. defaults: {
  14023. drag_min_distance : 10,
  14024. // set 0 for unlimited, but this can conflict with transform
  14025. drag_max_touches : 1,
  14026. // prevent default browser behavior when dragging occurs
  14027. // be careful with it, it makes the element a blocking element
  14028. // when you are using the drag gesture, it is a good practice to set this true
  14029. drag_block_horizontal : false,
  14030. drag_block_vertical : false,
  14031. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  14032. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  14033. drag_lock_to_axis : false,
  14034. // drag lock only kicks in when distance > drag_lock_min_distance
  14035. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  14036. drag_lock_min_distance : 25
  14037. },
  14038. triggered: false,
  14039. handler: function dragGesture(ev, inst) {
  14040. // current gesture isnt drag, but dragged is true
  14041. // this means an other gesture is busy. now call dragend
  14042. if(Hammer.detection.current.name != this.name && this.triggered) {
  14043. inst.trigger(this.name +'end', ev);
  14044. this.triggered = false;
  14045. return;
  14046. }
  14047. // max touches
  14048. if(inst.options.drag_max_touches > 0 &&
  14049. ev.touches.length > inst.options.drag_max_touches) {
  14050. return;
  14051. }
  14052. switch(ev.eventType) {
  14053. case Hammer.EVENT_START:
  14054. this.triggered = false;
  14055. break;
  14056. case Hammer.EVENT_MOVE:
  14057. // when the distance we moved is too small we skip this gesture
  14058. // or we can be already in dragging
  14059. if(ev.distance < inst.options.drag_min_distance &&
  14060. Hammer.detection.current.name != this.name) {
  14061. return;
  14062. }
  14063. // we are dragging!
  14064. Hammer.detection.current.name = this.name;
  14065. // lock drag to axis?
  14066. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  14067. ev.drag_locked_to_axis = true;
  14068. }
  14069. var last_direction = Hammer.detection.current.lastEvent.direction;
  14070. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  14071. // keep direction on the axis that the drag gesture started on
  14072. if(Hammer.utils.isVertical(last_direction)) {
  14073. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  14074. }
  14075. else {
  14076. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  14077. }
  14078. }
  14079. // first time, trigger dragstart event
  14080. if(!this.triggered) {
  14081. inst.trigger(this.name +'start', ev);
  14082. this.triggered = true;
  14083. }
  14084. // trigger normal event
  14085. inst.trigger(this.name, ev);
  14086. // direction event, like dragdown
  14087. inst.trigger(this.name + ev.direction, ev);
  14088. // block the browser events
  14089. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  14090. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  14091. ev.preventDefault();
  14092. }
  14093. break;
  14094. case Hammer.EVENT_END:
  14095. // trigger dragend
  14096. if(this.triggered) {
  14097. inst.trigger(this.name +'end', ev);
  14098. }
  14099. this.triggered = false;
  14100. break;
  14101. }
  14102. }
  14103. };
  14104. /**
  14105. * Transform
  14106. * User want to scale or rotate with 2 fingers
  14107. * @events transform, pinch, pinchin, pinchout, rotate
  14108. */
  14109. Hammer.gestures.Transform = {
  14110. name: 'transform',
  14111. index: 45,
  14112. defaults: {
  14113. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  14114. transform_min_scale : 0.01,
  14115. // rotation in degrees
  14116. transform_min_rotation : 1,
  14117. // prevent default browser behavior when two touches are on the screen
  14118. // but it makes the element a blocking element
  14119. // when you are using the transform gesture, it is a good practice to set this true
  14120. transform_always_block : false
  14121. },
  14122. triggered: false,
  14123. handler: function transformGesture(ev, inst) {
  14124. // current gesture isnt drag, but dragged is true
  14125. // this means an other gesture is busy. now call dragend
  14126. if(Hammer.detection.current.name != this.name && this.triggered) {
  14127. inst.trigger(this.name +'end', ev);
  14128. this.triggered = false;
  14129. return;
  14130. }
  14131. // atleast multitouch
  14132. if(ev.touches.length < 2) {
  14133. return;
  14134. }
  14135. // prevent default when two fingers are on the screen
  14136. if(inst.options.transform_always_block) {
  14137. ev.preventDefault();
  14138. }
  14139. switch(ev.eventType) {
  14140. case Hammer.EVENT_START:
  14141. this.triggered = false;
  14142. break;
  14143. case Hammer.EVENT_MOVE:
  14144. var scale_threshold = Math.abs(1-ev.scale);
  14145. var rotation_threshold = Math.abs(ev.rotation);
  14146. // when the distance we moved is too small we skip this gesture
  14147. // or we can be already in dragging
  14148. if(scale_threshold < inst.options.transform_min_scale &&
  14149. rotation_threshold < inst.options.transform_min_rotation) {
  14150. return;
  14151. }
  14152. // we are transforming!
  14153. Hammer.detection.current.name = this.name;
  14154. // first time, trigger dragstart event
  14155. if(!this.triggered) {
  14156. inst.trigger(this.name +'start', ev);
  14157. this.triggered = true;
  14158. }
  14159. inst.trigger(this.name, ev); // basic transform event
  14160. // trigger rotate event
  14161. if(rotation_threshold > inst.options.transform_min_rotation) {
  14162. inst.trigger('rotate', ev);
  14163. }
  14164. // trigger pinch event
  14165. if(scale_threshold > inst.options.transform_min_scale) {
  14166. inst.trigger('pinch', ev);
  14167. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  14168. }
  14169. break;
  14170. case Hammer.EVENT_END:
  14171. // trigger dragend
  14172. if(this.triggered) {
  14173. inst.trigger(this.name +'end', ev);
  14174. }
  14175. this.triggered = false;
  14176. break;
  14177. }
  14178. }
  14179. };
  14180. /**
  14181. * Touch
  14182. * Called as first, tells the user has touched the screen
  14183. * @events touch
  14184. */
  14185. Hammer.gestures.Touch = {
  14186. name: 'touch',
  14187. index: -Infinity,
  14188. defaults: {
  14189. // call preventDefault at touchstart, and makes the element blocking by
  14190. // disabling the scrolling of the page, but it improves gestures like
  14191. // transforming and dragging.
  14192. // be careful with using this, it can be very annoying for users to be stuck
  14193. // on the page
  14194. prevent_default: false,
  14195. // disable mouse events, so only touch (or pen!) input triggers events
  14196. prevent_mouseevents: false
  14197. },
  14198. handler: function touchGesture(ev, inst) {
  14199. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  14200. ev.stopDetect();
  14201. return;
  14202. }
  14203. if(inst.options.prevent_default) {
  14204. ev.preventDefault();
  14205. }
  14206. if(ev.eventType == Hammer.EVENT_START) {
  14207. inst.trigger(this.name, ev);
  14208. }
  14209. }
  14210. };
  14211. /**
  14212. * Release
  14213. * Called as last, tells the user has released the screen
  14214. * @events release
  14215. */
  14216. Hammer.gestures.Release = {
  14217. name: 'release',
  14218. index: Infinity,
  14219. handler: function releaseGesture(ev, inst) {
  14220. if(ev.eventType == Hammer.EVENT_END) {
  14221. inst.trigger(this.name, ev);
  14222. }
  14223. }
  14224. };
  14225. // node export
  14226. if(typeof module === 'object' && typeof module.exports === 'object'){
  14227. module.exports = Hammer;
  14228. }
  14229. // just window export
  14230. else {
  14231. window.Hammer = Hammer;
  14232. // requireJS module definition
  14233. if(typeof window.define === 'function' && window.define.amd) {
  14234. window.define('hammer', [], function() {
  14235. return Hammer;
  14236. });
  14237. }
  14238. }
  14239. })(this);
  14240. },{}],3:[function(require,module,exports){
  14241. //! moment.js
  14242. //! version : 2.5.0
  14243. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  14244. //! license : MIT
  14245. //! momentjs.com
  14246. (function (undefined) {
  14247. /************************************
  14248. Constants
  14249. ************************************/
  14250. var moment,
  14251. VERSION = "2.5.0",
  14252. global = this,
  14253. round = Math.round,
  14254. i,
  14255. YEAR = 0,
  14256. MONTH = 1,
  14257. DATE = 2,
  14258. HOUR = 3,
  14259. MINUTE = 4,
  14260. SECOND = 5,
  14261. MILLISECOND = 6,
  14262. // internal storage for language config files
  14263. languages = {},
  14264. // check for nodeJS
  14265. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  14266. // ASP.NET json date format regex
  14267. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  14268. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  14269. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  14270. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  14271. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  14272. // format tokens
  14273. 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,
  14274. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  14275. // parsing token regexes
  14276. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  14277. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  14278. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  14279. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  14280. parseTokenDigits = /\d+/, // nonzero number of digits
  14281. 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.
  14282. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  14283. parseTokenT = /T/i, // T (ISO separator)
  14284. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  14285. //strict parsing regexes
  14286. parseTokenOneDigit = /\d/, // 0 - 9
  14287. parseTokenTwoDigits = /\d\d/, // 00 - 99
  14288. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  14289. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  14290. parseTokenSixDigits = /[+\-]?\d{6}/, // -999,999 - 999,999
  14291. // iso 8601 regex
  14292. // 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)
  14293. 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)?)?$/,
  14294. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  14295. isoDates = [
  14296. 'YYYY-MM-DD',
  14297. 'GGGG-[W]WW',
  14298. 'GGGG-[W]WW-E',
  14299. 'YYYY-DDD'
  14300. ],
  14301. // iso time formats and regexes
  14302. isoTimes = [
  14303. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  14304. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  14305. ['HH:mm', /(T| )\d\d:\d\d/],
  14306. ['HH', /(T| )\d\d/]
  14307. ],
  14308. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  14309. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  14310. // getter and setter names
  14311. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  14312. unitMillisecondFactors = {
  14313. 'Milliseconds' : 1,
  14314. 'Seconds' : 1e3,
  14315. 'Minutes' : 6e4,
  14316. 'Hours' : 36e5,
  14317. 'Days' : 864e5,
  14318. 'Months' : 2592e6,
  14319. 'Years' : 31536e6
  14320. },
  14321. unitAliases = {
  14322. ms : 'millisecond',
  14323. s : 'second',
  14324. m : 'minute',
  14325. h : 'hour',
  14326. d : 'day',
  14327. D : 'date',
  14328. w : 'week',
  14329. W : 'isoWeek',
  14330. M : 'month',
  14331. y : 'year',
  14332. DDD : 'dayOfYear',
  14333. e : 'weekday',
  14334. E : 'isoWeekday',
  14335. gg: 'weekYear',
  14336. GG: 'isoWeekYear'
  14337. },
  14338. camelFunctions = {
  14339. dayofyear : 'dayOfYear',
  14340. isoweekday : 'isoWeekday',
  14341. isoweek : 'isoWeek',
  14342. weekyear : 'weekYear',
  14343. isoweekyear : 'isoWeekYear'
  14344. },
  14345. // format function strings
  14346. formatFunctions = {},
  14347. // tokens to ordinalize and pad
  14348. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  14349. paddedTokens = 'M D H h m s w W'.split(' '),
  14350. formatTokenFunctions = {
  14351. M : function () {
  14352. return this.month() + 1;
  14353. },
  14354. MMM : function (format) {
  14355. return this.lang().monthsShort(this, format);
  14356. },
  14357. MMMM : function (format) {
  14358. return this.lang().months(this, format);
  14359. },
  14360. D : function () {
  14361. return this.date();
  14362. },
  14363. DDD : function () {
  14364. return this.dayOfYear();
  14365. },
  14366. d : function () {
  14367. return this.day();
  14368. },
  14369. dd : function (format) {
  14370. return this.lang().weekdaysMin(this, format);
  14371. },
  14372. ddd : function (format) {
  14373. return this.lang().weekdaysShort(this, format);
  14374. },
  14375. dddd : function (format) {
  14376. return this.lang().weekdays(this, format);
  14377. },
  14378. w : function () {
  14379. return this.week();
  14380. },
  14381. W : function () {
  14382. return this.isoWeek();
  14383. },
  14384. YY : function () {
  14385. return leftZeroFill(this.year() % 100, 2);
  14386. },
  14387. YYYY : function () {
  14388. return leftZeroFill(this.year(), 4);
  14389. },
  14390. YYYYY : function () {
  14391. return leftZeroFill(this.year(), 5);
  14392. },
  14393. YYYYYY : function () {
  14394. var y = this.year(), sign = y >= 0 ? '+' : '-';
  14395. return sign + leftZeroFill(Math.abs(y), 6);
  14396. },
  14397. gg : function () {
  14398. return leftZeroFill(this.weekYear() % 100, 2);
  14399. },
  14400. gggg : function () {
  14401. return this.weekYear();
  14402. },
  14403. ggggg : function () {
  14404. return leftZeroFill(this.weekYear(), 5);
  14405. },
  14406. GG : function () {
  14407. return leftZeroFill(this.isoWeekYear() % 100, 2);
  14408. },
  14409. GGGG : function () {
  14410. return this.isoWeekYear();
  14411. },
  14412. GGGGG : function () {
  14413. return leftZeroFill(this.isoWeekYear(), 5);
  14414. },
  14415. e : function () {
  14416. return this.weekday();
  14417. },
  14418. E : function () {
  14419. return this.isoWeekday();
  14420. },
  14421. a : function () {
  14422. return this.lang().meridiem(this.hours(), this.minutes(), true);
  14423. },
  14424. A : function () {
  14425. return this.lang().meridiem(this.hours(), this.minutes(), false);
  14426. },
  14427. H : function () {
  14428. return this.hours();
  14429. },
  14430. h : function () {
  14431. return this.hours() % 12 || 12;
  14432. },
  14433. m : function () {
  14434. return this.minutes();
  14435. },
  14436. s : function () {
  14437. return this.seconds();
  14438. },
  14439. S : function () {
  14440. return toInt(this.milliseconds() / 100);
  14441. },
  14442. SS : function () {
  14443. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  14444. },
  14445. SSS : function () {
  14446. return leftZeroFill(this.milliseconds(), 3);
  14447. },
  14448. SSSS : function () {
  14449. return leftZeroFill(this.milliseconds(), 3);
  14450. },
  14451. Z : function () {
  14452. var a = -this.zone(),
  14453. b = "+";
  14454. if (a < 0) {
  14455. a = -a;
  14456. b = "-";
  14457. }
  14458. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  14459. },
  14460. ZZ : function () {
  14461. var a = -this.zone(),
  14462. b = "+";
  14463. if (a < 0) {
  14464. a = -a;
  14465. b = "-";
  14466. }
  14467. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  14468. },
  14469. z : function () {
  14470. return this.zoneAbbr();
  14471. },
  14472. zz : function () {
  14473. return this.zoneName();
  14474. },
  14475. X : function () {
  14476. return this.unix();
  14477. },
  14478. Q : function () {
  14479. return this.quarter();
  14480. }
  14481. },
  14482. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  14483. function padToken(func, count) {
  14484. return function (a) {
  14485. return leftZeroFill(func.call(this, a), count);
  14486. };
  14487. }
  14488. function ordinalizeToken(func, period) {
  14489. return function (a) {
  14490. return this.lang().ordinal(func.call(this, a), period);
  14491. };
  14492. }
  14493. while (ordinalizeTokens.length) {
  14494. i = ordinalizeTokens.pop();
  14495. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  14496. }
  14497. while (paddedTokens.length) {
  14498. i = paddedTokens.pop();
  14499. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  14500. }
  14501. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  14502. /************************************
  14503. Constructors
  14504. ************************************/
  14505. function Language() {
  14506. }
  14507. // Moment prototype object
  14508. function Moment(config) {
  14509. checkOverflow(config);
  14510. extend(this, config);
  14511. }
  14512. // Duration Constructor
  14513. function Duration(duration) {
  14514. var normalizedInput = normalizeObjectUnits(duration),
  14515. years = normalizedInput.year || 0,
  14516. months = normalizedInput.month || 0,
  14517. weeks = normalizedInput.week || 0,
  14518. days = normalizedInput.day || 0,
  14519. hours = normalizedInput.hour || 0,
  14520. minutes = normalizedInput.minute || 0,
  14521. seconds = normalizedInput.second || 0,
  14522. milliseconds = normalizedInput.millisecond || 0;
  14523. // representation for dateAddRemove
  14524. this._milliseconds = +milliseconds +
  14525. seconds * 1e3 + // 1000
  14526. minutes * 6e4 + // 1000 * 60
  14527. hours * 36e5; // 1000 * 60 * 60
  14528. // Because of dateAddRemove treats 24 hours as different from a
  14529. // day when working around DST, we need to store them separately
  14530. this._days = +days +
  14531. weeks * 7;
  14532. // It is impossible translate months into days without knowing
  14533. // which months you are are talking about, so we have to store
  14534. // it separately.
  14535. this._months = +months +
  14536. years * 12;
  14537. this._data = {};
  14538. this._bubble();
  14539. }
  14540. /************************************
  14541. Helpers
  14542. ************************************/
  14543. function extend(a, b) {
  14544. for (var i in b) {
  14545. if (b.hasOwnProperty(i)) {
  14546. a[i] = b[i];
  14547. }
  14548. }
  14549. if (b.hasOwnProperty("toString")) {
  14550. a.toString = b.toString;
  14551. }
  14552. if (b.hasOwnProperty("valueOf")) {
  14553. a.valueOf = b.valueOf;
  14554. }
  14555. return a;
  14556. }
  14557. function absRound(number) {
  14558. if (number < 0) {
  14559. return Math.ceil(number);
  14560. } else {
  14561. return Math.floor(number);
  14562. }
  14563. }
  14564. // left zero fill a number
  14565. // see http://jsperf.com/left-zero-filling for performance comparison
  14566. function leftZeroFill(number, targetLength, forceSign) {
  14567. var output = Math.abs(number) + '',
  14568. sign = number >= 0;
  14569. while (output.length < targetLength) {
  14570. output = '0' + output;
  14571. }
  14572. return (sign ? (forceSign ? '+' : '') : '-') + output;
  14573. }
  14574. // helper function for _.addTime and _.subtractTime
  14575. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  14576. var milliseconds = duration._milliseconds,
  14577. days = duration._days,
  14578. months = duration._months,
  14579. minutes,
  14580. hours;
  14581. if (milliseconds) {
  14582. mom._d.setTime(+mom._d + milliseconds * isAdding);
  14583. }
  14584. // store the minutes and hours so we can restore them
  14585. if (days || months) {
  14586. minutes = mom.minute();
  14587. hours = mom.hour();
  14588. }
  14589. if (days) {
  14590. mom.date(mom.date() + days * isAdding);
  14591. }
  14592. if (months) {
  14593. mom.month(mom.month() + months * isAdding);
  14594. }
  14595. if (milliseconds && !ignoreUpdateOffset) {
  14596. moment.updateOffset(mom);
  14597. }
  14598. // restore the minutes and hours after possibly changing dst
  14599. if (days || months) {
  14600. mom.minute(minutes);
  14601. mom.hour(hours);
  14602. }
  14603. }
  14604. // check if is an array
  14605. function isArray(input) {
  14606. return Object.prototype.toString.call(input) === '[object Array]';
  14607. }
  14608. function isDate(input) {
  14609. return Object.prototype.toString.call(input) === '[object Date]' ||
  14610. input instanceof Date;
  14611. }
  14612. // compare two arrays, return the number of differences
  14613. function compareArrays(array1, array2, dontConvert) {
  14614. var len = Math.min(array1.length, array2.length),
  14615. lengthDiff = Math.abs(array1.length - array2.length),
  14616. diffs = 0,
  14617. i;
  14618. for (i = 0; i < len; i++) {
  14619. if ((dontConvert && array1[i] !== array2[i]) ||
  14620. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  14621. diffs++;
  14622. }
  14623. }
  14624. return diffs + lengthDiff;
  14625. }
  14626. function normalizeUnits(units) {
  14627. if (units) {
  14628. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  14629. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  14630. }
  14631. return units;
  14632. }
  14633. function normalizeObjectUnits(inputObject) {
  14634. var normalizedInput = {},
  14635. normalizedProp,
  14636. prop;
  14637. for (prop in inputObject) {
  14638. if (inputObject.hasOwnProperty(prop)) {
  14639. normalizedProp = normalizeUnits(prop);
  14640. if (normalizedProp) {
  14641. normalizedInput[normalizedProp] = inputObject[prop];
  14642. }
  14643. }
  14644. }
  14645. return normalizedInput;
  14646. }
  14647. function makeList(field) {
  14648. var count, setter;
  14649. if (field.indexOf('week') === 0) {
  14650. count = 7;
  14651. setter = 'day';
  14652. }
  14653. else if (field.indexOf('month') === 0) {
  14654. count = 12;
  14655. setter = 'month';
  14656. }
  14657. else {
  14658. return;
  14659. }
  14660. moment[field] = function (format, index) {
  14661. var i, getter,
  14662. method = moment.fn._lang[field],
  14663. results = [];
  14664. if (typeof format === 'number') {
  14665. index = format;
  14666. format = undefined;
  14667. }
  14668. getter = function (i) {
  14669. var m = moment().utc().set(setter, i);
  14670. return method.call(moment.fn._lang, m, format || '');
  14671. };
  14672. if (index != null) {
  14673. return getter(index);
  14674. }
  14675. else {
  14676. for (i = 0; i < count; i++) {
  14677. results.push(getter(i));
  14678. }
  14679. return results;
  14680. }
  14681. };
  14682. }
  14683. function toInt(argumentForCoercion) {
  14684. var coercedNumber = +argumentForCoercion,
  14685. value = 0;
  14686. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  14687. if (coercedNumber >= 0) {
  14688. value = Math.floor(coercedNumber);
  14689. } else {
  14690. value = Math.ceil(coercedNumber);
  14691. }
  14692. }
  14693. return value;
  14694. }
  14695. function daysInMonth(year, month) {
  14696. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  14697. }
  14698. function daysInYear(year) {
  14699. return isLeapYear(year) ? 366 : 365;
  14700. }
  14701. function isLeapYear(year) {
  14702. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  14703. }
  14704. function checkOverflow(m) {
  14705. var overflow;
  14706. if (m._a && m._pf.overflow === -2) {
  14707. overflow =
  14708. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  14709. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  14710. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  14711. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  14712. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  14713. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  14714. -1;
  14715. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  14716. overflow = DATE;
  14717. }
  14718. m._pf.overflow = overflow;
  14719. }
  14720. }
  14721. function initializeParsingFlags(config) {
  14722. config._pf = {
  14723. empty : false,
  14724. unusedTokens : [],
  14725. unusedInput : [],
  14726. overflow : -2,
  14727. charsLeftOver : 0,
  14728. nullInput : false,
  14729. invalidMonth : null,
  14730. invalidFormat : false,
  14731. userInvalidated : false,
  14732. iso: false
  14733. };
  14734. }
  14735. function isValid(m) {
  14736. if (m._isValid == null) {
  14737. m._isValid = !isNaN(m._d.getTime()) &&
  14738. m._pf.overflow < 0 &&
  14739. !m._pf.empty &&
  14740. !m._pf.invalidMonth &&
  14741. !m._pf.nullInput &&
  14742. !m._pf.invalidFormat &&
  14743. !m._pf.userInvalidated;
  14744. if (m._strict) {
  14745. m._isValid = m._isValid &&
  14746. m._pf.charsLeftOver === 0 &&
  14747. m._pf.unusedTokens.length === 0;
  14748. }
  14749. }
  14750. return m._isValid;
  14751. }
  14752. function normalizeLanguage(key) {
  14753. return key ? key.toLowerCase().replace('_', '-') : key;
  14754. }
  14755. // Return a moment from input, that is local/utc/zone equivalent to model.
  14756. function makeAs(input, model) {
  14757. return model._isUTC ? moment(input).zone(model._offset || 0) :
  14758. moment(input).local();
  14759. }
  14760. /************************************
  14761. Languages
  14762. ************************************/
  14763. extend(Language.prototype, {
  14764. set : function (config) {
  14765. var prop, i;
  14766. for (i in config) {
  14767. prop = config[i];
  14768. if (typeof prop === 'function') {
  14769. this[i] = prop;
  14770. } else {
  14771. this['_' + i] = prop;
  14772. }
  14773. }
  14774. },
  14775. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  14776. months : function (m) {
  14777. return this._months[m.month()];
  14778. },
  14779. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  14780. monthsShort : function (m) {
  14781. return this._monthsShort[m.month()];
  14782. },
  14783. monthsParse : function (monthName) {
  14784. var i, mom, regex;
  14785. if (!this._monthsParse) {
  14786. this._monthsParse = [];
  14787. }
  14788. for (i = 0; i < 12; i++) {
  14789. // make the regex if we don't have it already
  14790. if (!this._monthsParse[i]) {
  14791. mom = moment.utc([2000, i]);
  14792. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  14793. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  14794. }
  14795. // test the regex
  14796. if (this._monthsParse[i].test(monthName)) {
  14797. return i;
  14798. }
  14799. }
  14800. },
  14801. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  14802. weekdays : function (m) {
  14803. return this._weekdays[m.day()];
  14804. },
  14805. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  14806. weekdaysShort : function (m) {
  14807. return this._weekdaysShort[m.day()];
  14808. },
  14809. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  14810. weekdaysMin : function (m) {
  14811. return this._weekdaysMin[m.day()];
  14812. },
  14813. weekdaysParse : function (weekdayName) {
  14814. var i, mom, regex;
  14815. if (!this._weekdaysParse) {
  14816. this._weekdaysParse = [];
  14817. }
  14818. for (i = 0; i < 7; i++) {
  14819. // make the regex if we don't have it already
  14820. if (!this._weekdaysParse[i]) {
  14821. mom = moment([2000, 1]).day(i);
  14822. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  14823. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  14824. }
  14825. // test the regex
  14826. if (this._weekdaysParse[i].test(weekdayName)) {
  14827. return i;
  14828. }
  14829. }
  14830. },
  14831. _longDateFormat : {
  14832. LT : "h:mm A",
  14833. L : "MM/DD/YYYY",
  14834. LL : "MMMM D YYYY",
  14835. LLL : "MMMM D YYYY LT",
  14836. LLLL : "dddd, MMMM D YYYY LT"
  14837. },
  14838. longDateFormat : function (key) {
  14839. var output = this._longDateFormat[key];
  14840. if (!output && this._longDateFormat[key.toUpperCase()]) {
  14841. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  14842. return val.slice(1);
  14843. });
  14844. this._longDateFormat[key] = output;
  14845. }
  14846. return output;
  14847. },
  14848. isPM : function (input) {
  14849. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  14850. // Using charAt should be more compatible.
  14851. return ((input + '').toLowerCase().charAt(0) === 'p');
  14852. },
  14853. _meridiemParse : /[ap]\.?m?\.?/i,
  14854. meridiem : function (hours, minutes, isLower) {
  14855. if (hours > 11) {
  14856. return isLower ? 'pm' : 'PM';
  14857. } else {
  14858. return isLower ? 'am' : 'AM';
  14859. }
  14860. },
  14861. _calendar : {
  14862. sameDay : '[Today at] LT',
  14863. nextDay : '[Tomorrow at] LT',
  14864. nextWeek : 'dddd [at] LT',
  14865. lastDay : '[Yesterday at] LT',
  14866. lastWeek : '[Last] dddd [at] LT',
  14867. sameElse : 'L'
  14868. },
  14869. calendar : function (key, mom) {
  14870. var output = this._calendar[key];
  14871. return typeof output === 'function' ? output.apply(mom) : output;
  14872. },
  14873. _relativeTime : {
  14874. future : "in %s",
  14875. past : "%s ago",
  14876. s : "a few seconds",
  14877. m : "a minute",
  14878. mm : "%d minutes",
  14879. h : "an hour",
  14880. hh : "%d hours",
  14881. d : "a day",
  14882. dd : "%d days",
  14883. M : "a month",
  14884. MM : "%d months",
  14885. y : "a year",
  14886. yy : "%d years"
  14887. },
  14888. relativeTime : function (number, withoutSuffix, string, isFuture) {
  14889. var output = this._relativeTime[string];
  14890. return (typeof output === 'function') ?
  14891. output(number, withoutSuffix, string, isFuture) :
  14892. output.replace(/%d/i, number);
  14893. },
  14894. pastFuture : function (diff, output) {
  14895. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  14896. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  14897. },
  14898. ordinal : function (number) {
  14899. return this._ordinal.replace("%d", number);
  14900. },
  14901. _ordinal : "%d",
  14902. preparse : function (string) {
  14903. return string;
  14904. },
  14905. postformat : function (string) {
  14906. return string;
  14907. },
  14908. week : function (mom) {
  14909. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  14910. },
  14911. _week : {
  14912. dow : 0, // Sunday is the first day of the week.
  14913. doy : 6 // The week that contains Jan 1st is the first week of the year.
  14914. },
  14915. _invalidDate: 'Invalid date',
  14916. invalidDate: function () {
  14917. return this._invalidDate;
  14918. }
  14919. });
  14920. // Loads a language definition into the `languages` cache. The function
  14921. // takes a key and optionally values. If not in the browser and no values
  14922. // are provided, it will load the language file module. As a convenience,
  14923. // this function also returns the language values.
  14924. function loadLang(key, values) {
  14925. values.abbr = key;
  14926. if (!languages[key]) {
  14927. languages[key] = new Language();
  14928. }
  14929. languages[key].set(values);
  14930. return languages[key];
  14931. }
  14932. // Remove a language from the `languages` cache. Mostly useful in tests.
  14933. function unloadLang(key) {
  14934. delete languages[key];
  14935. }
  14936. // Determines which language definition to use and returns it.
  14937. //
  14938. // With no parameters, it will return the global language. If you
  14939. // pass in a language key, such as 'en', it will return the
  14940. // definition for 'en', so long as 'en' has already been loaded using
  14941. // moment.lang.
  14942. function getLangDefinition(key) {
  14943. var i = 0, j, lang, next, split,
  14944. get = function (k) {
  14945. if (!languages[k] && hasModule) {
  14946. try {
  14947. require('./lang/' + k);
  14948. } catch (e) { }
  14949. }
  14950. return languages[k];
  14951. };
  14952. if (!key) {
  14953. return moment.fn._lang;
  14954. }
  14955. if (!isArray(key)) {
  14956. //short-circuit everything else
  14957. lang = get(key);
  14958. if (lang) {
  14959. return lang;
  14960. }
  14961. key = [key];
  14962. }
  14963. //pick the language from the array
  14964. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  14965. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  14966. while (i < key.length) {
  14967. split = normalizeLanguage(key[i]).split('-');
  14968. j = split.length;
  14969. next = normalizeLanguage(key[i + 1]);
  14970. next = next ? next.split('-') : null;
  14971. while (j > 0) {
  14972. lang = get(split.slice(0, j).join('-'));
  14973. if (lang) {
  14974. return lang;
  14975. }
  14976. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  14977. //the next array item is better than a shallower substring of this one
  14978. break;
  14979. }
  14980. j--;
  14981. }
  14982. i++;
  14983. }
  14984. return moment.fn._lang;
  14985. }
  14986. /************************************
  14987. Formatting
  14988. ************************************/
  14989. function removeFormattingTokens(input) {
  14990. if (input.match(/\[[\s\S]/)) {
  14991. return input.replace(/^\[|\]$/g, "");
  14992. }
  14993. return input.replace(/\\/g, "");
  14994. }
  14995. function makeFormatFunction(format) {
  14996. var array = format.match(formattingTokens), i, length;
  14997. for (i = 0, length = array.length; i < length; i++) {
  14998. if (formatTokenFunctions[array[i]]) {
  14999. array[i] = formatTokenFunctions[array[i]];
  15000. } else {
  15001. array[i] = removeFormattingTokens(array[i]);
  15002. }
  15003. }
  15004. return function (mom) {
  15005. var output = "";
  15006. for (i = 0; i < length; i++) {
  15007. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  15008. }
  15009. return output;
  15010. };
  15011. }
  15012. // format date using native date object
  15013. function formatMoment(m, format) {
  15014. if (!m.isValid()) {
  15015. return m.lang().invalidDate();
  15016. }
  15017. format = expandFormat(format, m.lang());
  15018. if (!formatFunctions[format]) {
  15019. formatFunctions[format] = makeFormatFunction(format);
  15020. }
  15021. return formatFunctions[format](m);
  15022. }
  15023. function expandFormat(format, lang) {
  15024. var i = 5;
  15025. function replaceLongDateFormatTokens(input) {
  15026. return lang.longDateFormat(input) || input;
  15027. }
  15028. localFormattingTokens.lastIndex = 0;
  15029. while (i >= 0 && localFormattingTokens.test(format)) {
  15030. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  15031. localFormattingTokens.lastIndex = 0;
  15032. i -= 1;
  15033. }
  15034. return format;
  15035. }
  15036. /************************************
  15037. Parsing
  15038. ************************************/
  15039. // get the regex to find the next token
  15040. function getParseRegexForToken(token, config) {
  15041. var a, strict = config._strict;
  15042. switch (token) {
  15043. case 'DDDD':
  15044. return parseTokenThreeDigits;
  15045. case 'YYYY':
  15046. case 'GGGG':
  15047. case 'gggg':
  15048. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  15049. case 'YYYYYY':
  15050. case 'YYYYY':
  15051. case 'GGGGG':
  15052. case 'ggggg':
  15053. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  15054. case 'S':
  15055. if (strict) { return parseTokenOneDigit; }
  15056. /* falls through */
  15057. case 'SS':
  15058. if (strict) { return parseTokenTwoDigits; }
  15059. /* falls through */
  15060. case 'SSS':
  15061. case 'DDD':
  15062. return strict ? parseTokenThreeDigits : parseTokenOneToThreeDigits;
  15063. case 'MMM':
  15064. case 'MMMM':
  15065. case 'dd':
  15066. case 'ddd':
  15067. case 'dddd':
  15068. return parseTokenWord;
  15069. case 'a':
  15070. case 'A':
  15071. return getLangDefinition(config._l)._meridiemParse;
  15072. case 'X':
  15073. return parseTokenTimestampMs;
  15074. case 'Z':
  15075. case 'ZZ':
  15076. return parseTokenTimezone;
  15077. case 'T':
  15078. return parseTokenT;
  15079. case 'SSSS':
  15080. return parseTokenDigits;
  15081. case 'MM':
  15082. case 'DD':
  15083. case 'YY':
  15084. case 'GG':
  15085. case 'gg':
  15086. case 'HH':
  15087. case 'hh':
  15088. case 'mm':
  15089. case 'ss':
  15090. case 'ww':
  15091. case 'WW':
  15092. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  15093. case 'M':
  15094. case 'D':
  15095. case 'd':
  15096. case 'H':
  15097. case 'h':
  15098. case 'm':
  15099. case 's':
  15100. case 'w':
  15101. case 'W':
  15102. case 'e':
  15103. case 'E':
  15104. return strict ? parseTokenOneDigit : parseTokenOneOrTwoDigits;
  15105. default :
  15106. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  15107. return a;
  15108. }
  15109. }
  15110. function timezoneMinutesFromString(string) {
  15111. string = string || "";
  15112. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  15113. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  15114. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  15115. minutes = +(parts[1] * 60) + toInt(parts[2]);
  15116. return parts[0] === '+' ? -minutes : minutes;
  15117. }
  15118. // function to convert string input to date
  15119. function addTimeToArrayFromToken(token, input, config) {
  15120. var a, datePartArray = config._a;
  15121. switch (token) {
  15122. // MONTH
  15123. case 'M' : // fall through to MM
  15124. case 'MM' :
  15125. if (input != null) {
  15126. datePartArray[MONTH] = toInt(input) - 1;
  15127. }
  15128. break;
  15129. case 'MMM' : // fall through to MMMM
  15130. case 'MMMM' :
  15131. a = getLangDefinition(config._l).monthsParse(input);
  15132. // if we didn't find a month name, mark the date as invalid.
  15133. if (a != null) {
  15134. datePartArray[MONTH] = a;
  15135. } else {
  15136. config._pf.invalidMonth = input;
  15137. }
  15138. break;
  15139. // DAY OF MONTH
  15140. case 'D' : // fall through to DD
  15141. case 'DD' :
  15142. if (input != null) {
  15143. datePartArray[DATE] = toInt(input);
  15144. }
  15145. break;
  15146. // DAY OF YEAR
  15147. case 'DDD' : // fall through to DDDD
  15148. case 'DDDD' :
  15149. if (input != null) {
  15150. config._dayOfYear = toInt(input);
  15151. }
  15152. break;
  15153. // YEAR
  15154. case 'YY' :
  15155. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  15156. break;
  15157. case 'YYYY' :
  15158. case 'YYYYY' :
  15159. case 'YYYYYY' :
  15160. datePartArray[YEAR] = toInt(input);
  15161. break;
  15162. // AM / PM
  15163. case 'a' : // fall through to A
  15164. case 'A' :
  15165. config._isPm = getLangDefinition(config._l).isPM(input);
  15166. break;
  15167. // 24 HOUR
  15168. case 'H' : // fall through to hh
  15169. case 'HH' : // fall through to hh
  15170. case 'h' : // fall through to hh
  15171. case 'hh' :
  15172. datePartArray[HOUR] = toInt(input);
  15173. break;
  15174. // MINUTE
  15175. case 'm' : // fall through to mm
  15176. case 'mm' :
  15177. datePartArray[MINUTE] = toInt(input);
  15178. break;
  15179. // SECOND
  15180. case 's' : // fall through to ss
  15181. case 'ss' :
  15182. datePartArray[SECOND] = toInt(input);
  15183. break;
  15184. // MILLISECOND
  15185. case 'S' :
  15186. case 'SS' :
  15187. case 'SSS' :
  15188. case 'SSSS' :
  15189. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  15190. break;
  15191. // UNIX TIMESTAMP WITH MS
  15192. case 'X':
  15193. config._d = new Date(parseFloat(input) * 1000);
  15194. break;
  15195. // TIMEZONE
  15196. case 'Z' : // fall through to ZZ
  15197. case 'ZZ' :
  15198. config._useUTC = true;
  15199. config._tzm = timezoneMinutesFromString(input);
  15200. break;
  15201. case 'w':
  15202. case 'ww':
  15203. case 'W':
  15204. case 'WW':
  15205. case 'd':
  15206. case 'dd':
  15207. case 'ddd':
  15208. case 'dddd':
  15209. case 'e':
  15210. case 'E':
  15211. token = token.substr(0, 1);
  15212. /* falls through */
  15213. case 'gg':
  15214. case 'gggg':
  15215. case 'GG':
  15216. case 'GGGG':
  15217. case 'GGGGG':
  15218. token = token.substr(0, 2);
  15219. if (input) {
  15220. config._w = config._w || {};
  15221. config._w[token] = input;
  15222. }
  15223. break;
  15224. }
  15225. }
  15226. // convert an array to a date.
  15227. // the array should mirror the parameters below
  15228. // note: all values past the year are optional and will default to the lowest possible value.
  15229. // [year, month, day , hour, minute, second, millisecond]
  15230. function dateFromConfig(config) {
  15231. var i, date, input = [], currentDate,
  15232. yearToUse, fixYear, w, temp, lang, weekday, week;
  15233. if (config._d) {
  15234. return;
  15235. }
  15236. currentDate = currentDateArray(config);
  15237. //compute day of the year from weeks and weekdays
  15238. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  15239. fixYear = function (val) {
  15240. var int_val = parseInt(val, 10);
  15241. return val ?
  15242. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  15243. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  15244. };
  15245. w = config._w;
  15246. if (w.GG != null || w.W != null || w.E != null) {
  15247. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  15248. }
  15249. else {
  15250. lang = getLangDefinition(config._l);
  15251. weekday = w.d != null ? parseWeekday(w.d, lang) :
  15252. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  15253. week = parseInt(w.w, 10) || 1;
  15254. //if we're parsing 'd', then the low day numbers may be next week
  15255. if (w.d != null && weekday < lang._week.dow) {
  15256. week++;
  15257. }
  15258. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  15259. }
  15260. config._a[YEAR] = temp.year;
  15261. config._dayOfYear = temp.dayOfYear;
  15262. }
  15263. //if the day of the year is set, figure out what it is
  15264. if (config._dayOfYear) {
  15265. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  15266. if (config._dayOfYear > daysInYear(yearToUse)) {
  15267. config._pf._overflowDayOfYear = true;
  15268. }
  15269. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  15270. config._a[MONTH] = date.getUTCMonth();
  15271. config._a[DATE] = date.getUTCDate();
  15272. }
  15273. // Default to current date.
  15274. // * if no year, month, day of month are given, default to today
  15275. // * if day of month is given, default month and year
  15276. // * if month is given, default only year
  15277. // * if year is given, don't default anything
  15278. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  15279. config._a[i] = input[i] = currentDate[i];
  15280. }
  15281. // Zero out whatever was not defaulted, including time
  15282. for (; i < 7; i++) {
  15283. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  15284. }
  15285. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  15286. input[HOUR] += toInt((config._tzm || 0) / 60);
  15287. input[MINUTE] += toInt((config._tzm || 0) % 60);
  15288. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  15289. }
  15290. function dateFromObject(config) {
  15291. var normalizedInput;
  15292. if (config._d) {
  15293. return;
  15294. }
  15295. normalizedInput = normalizeObjectUnits(config._i);
  15296. config._a = [
  15297. normalizedInput.year,
  15298. normalizedInput.month,
  15299. normalizedInput.day,
  15300. normalizedInput.hour,
  15301. normalizedInput.minute,
  15302. normalizedInput.second,
  15303. normalizedInput.millisecond
  15304. ];
  15305. dateFromConfig(config);
  15306. }
  15307. function currentDateArray(config) {
  15308. var now = new Date();
  15309. if (config._useUTC) {
  15310. return [
  15311. now.getUTCFullYear(),
  15312. now.getUTCMonth(),
  15313. now.getUTCDate()
  15314. ];
  15315. } else {
  15316. return [now.getFullYear(), now.getMonth(), now.getDate()];
  15317. }
  15318. }
  15319. // date from string and format string
  15320. function makeDateFromStringAndFormat(config) {
  15321. config._a = [];
  15322. config._pf.empty = true;
  15323. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  15324. var lang = getLangDefinition(config._l),
  15325. string = '' + config._i,
  15326. i, parsedInput, tokens, token, skipped,
  15327. stringLength = string.length,
  15328. totalParsedInputLength = 0;
  15329. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  15330. for (i = 0; i < tokens.length; i++) {
  15331. token = tokens[i];
  15332. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  15333. if (parsedInput) {
  15334. skipped = string.substr(0, string.indexOf(parsedInput));
  15335. if (skipped.length > 0) {
  15336. config._pf.unusedInput.push(skipped);
  15337. }
  15338. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  15339. totalParsedInputLength += parsedInput.length;
  15340. }
  15341. // don't parse if it's not a known token
  15342. if (formatTokenFunctions[token]) {
  15343. if (parsedInput) {
  15344. config._pf.empty = false;
  15345. }
  15346. else {
  15347. config._pf.unusedTokens.push(token);
  15348. }
  15349. addTimeToArrayFromToken(token, parsedInput, config);
  15350. }
  15351. else if (config._strict && !parsedInput) {
  15352. config._pf.unusedTokens.push(token);
  15353. }
  15354. }
  15355. // add remaining unparsed input length to the string
  15356. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  15357. if (string.length > 0) {
  15358. config._pf.unusedInput.push(string);
  15359. }
  15360. // handle am pm
  15361. if (config._isPm && config._a[HOUR] < 12) {
  15362. config._a[HOUR] += 12;
  15363. }
  15364. // if is 12 am, change hours to 0
  15365. if (config._isPm === false && config._a[HOUR] === 12) {
  15366. config._a[HOUR] = 0;
  15367. }
  15368. dateFromConfig(config);
  15369. checkOverflow(config);
  15370. }
  15371. function unescapeFormat(s) {
  15372. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  15373. return p1 || p2 || p3 || p4;
  15374. });
  15375. }
  15376. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  15377. function regexpEscape(s) {
  15378. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  15379. }
  15380. // date from string and array of format strings
  15381. function makeDateFromStringAndArray(config) {
  15382. var tempConfig,
  15383. bestMoment,
  15384. scoreToBeat,
  15385. i,
  15386. currentScore;
  15387. if (config._f.length === 0) {
  15388. config._pf.invalidFormat = true;
  15389. config._d = new Date(NaN);
  15390. return;
  15391. }
  15392. for (i = 0; i < config._f.length; i++) {
  15393. currentScore = 0;
  15394. tempConfig = extend({}, config);
  15395. initializeParsingFlags(tempConfig);
  15396. tempConfig._f = config._f[i];
  15397. makeDateFromStringAndFormat(tempConfig);
  15398. if (!isValid(tempConfig)) {
  15399. continue;
  15400. }
  15401. // if there is any input that was not parsed add a penalty for that format
  15402. currentScore += tempConfig._pf.charsLeftOver;
  15403. //or tokens
  15404. currentScore += tempConfig._pf.unusedTokens.length * 10;
  15405. tempConfig._pf.score = currentScore;
  15406. if (scoreToBeat == null || currentScore < scoreToBeat) {
  15407. scoreToBeat = currentScore;
  15408. bestMoment = tempConfig;
  15409. }
  15410. }
  15411. extend(config, bestMoment || tempConfig);
  15412. }
  15413. // date from iso format
  15414. function makeDateFromString(config) {
  15415. var i,
  15416. string = config._i,
  15417. match = isoRegex.exec(string);
  15418. if (match) {
  15419. config._pf.iso = true;
  15420. for (i = 4; i > 0; i--) {
  15421. if (match[i]) {
  15422. // match[5] should be "T" or undefined
  15423. config._f = isoDates[i - 1] + (match[6] || " ");
  15424. break;
  15425. }
  15426. }
  15427. for (i = 0; i < 4; i++) {
  15428. if (isoTimes[i][1].exec(string)) {
  15429. config._f += isoTimes[i][0];
  15430. break;
  15431. }
  15432. }
  15433. if (string.match(parseTokenTimezone)) {
  15434. config._f += "Z";
  15435. }
  15436. makeDateFromStringAndFormat(config);
  15437. }
  15438. else {
  15439. config._d = new Date(string);
  15440. }
  15441. }
  15442. function makeDateFromInput(config) {
  15443. var input = config._i,
  15444. matched = aspNetJsonRegex.exec(input);
  15445. if (input === undefined) {
  15446. config._d = new Date();
  15447. } else if (matched) {
  15448. config._d = new Date(+matched[1]);
  15449. } else if (typeof input === 'string') {
  15450. makeDateFromString(config);
  15451. } else if (isArray(input)) {
  15452. config._a = input.slice(0);
  15453. dateFromConfig(config);
  15454. } else if (isDate(input)) {
  15455. config._d = new Date(+input);
  15456. } else if (typeof(input) === 'object') {
  15457. dateFromObject(config);
  15458. } else {
  15459. config._d = new Date(input);
  15460. }
  15461. }
  15462. function makeDate(y, m, d, h, M, s, ms) {
  15463. //can't just apply() to create a date:
  15464. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  15465. var date = new Date(y, m, d, h, M, s, ms);
  15466. //the date constructor doesn't accept years < 1970
  15467. if (y < 1970) {
  15468. date.setFullYear(y);
  15469. }
  15470. return date;
  15471. }
  15472. function makeUTCDate(y) {
  15473. var date = new Date(Date.UTC.apply(null, arguments));
  15474. if (y < 1970) {
  15475. date.setUTCFullYear(y);
  15476. }
  15477. return date;
  15478. }
  15479. function parseWeekday(input, language) {
  15480. if (typeof input === 'string') {
  15481. if (!isNaN(input)) {
  15482. input = parseInt(input, 10);
  15483. }
  15484. else {
  15485. input = language.weekdaysParse(input);
  15486. if (typeof input !== 'number') {
  15487. return null;
  15488. }
  15489. }
  15490. }
  15491. return input;
  15492. }
  15493. /************************************
  15494. Relative Time
  15495. ************************************/
  15496. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  15497. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  15498. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  15499. }
  15500. function relativeTime(milliseconds, withoutSuffix, lang) {
  15501. var seconds = round(Math.abs(milliseconds) / 1000),
  15502. minutes = round(seconds / 60),
  15503. hours = round(minutes / 60),
  15504. days = round(hours / 24),
  15505. years = round(days / 365),
  15506. args = seconds < 45 && ['s', seconds] ||
  15507. minutes === 1 && ['m'] ||
  15508. minutes < 45 && ['mm', minutes] ||
  15509. hours === 1 && ['h'] ||
  15510. hours < 22 && ['hh', hours] ||
  15511. days === 1 && ['d'] ||
  15512. days <= 25 && ['dd', days] ||
  15513. days <= 45 && ['M'] ||
  15514. days < 345 && ['MM', round(days / 30)] ||
  15515. years === 1 && ['y'] || ['yy', years];
  15516. args[2] = withoutSuffix;
  15517. args[3] = milliseconds > 0;
  15518. args[4] = lang;
  15519. return substituteTimeAgo.apply({}, args);
  15520. }
  15521. /************************************
  15522. Week of Year
  15523. ************************************/
  15524. // firstDayOfWeek 0 = sun, 6 = sat
  15525. // the day of the week that starts the week
  15526. // (usually sunday or monday)
  15527. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  15528. // the first week is the week that contains the first
  15529. // of this day of the week
  15530. // (eg. ISO weeks use thursday (4))
  15531. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  15532. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  15533. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  15534. adjustedMoment;
  15535. if (daysToDayOfWeek > end) {
  15536. daysToDayOfWeek -= 7;
  15537. }
  15538. if (daysToDayOfWeek < end - 7) {
  15539. daysToDayOfWeek += 7;
  15540. }
  15541. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  15542. return {
  15543. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  15544. year: adjustedMoment.year()
  15545. };
  15546. }
  15547. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  15548. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  15549. // The only solid way to create an iso date from year is to use
  15550. // a string format (Date.UTC handles only years > 1900). Don't ask why
  15551. // it doesn't need Z at the end.
  15552. var d = new Date(leftZeroFill(year, 6, true) + '-01-01').getUTCDay(),
  15553. daysToAdd, dayOfYear;
  15554. weekday = weekday != null ? weekday : firstDayOfWeek;
  15555. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0);
  15556. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  15557. return {
  15558. year: dayOfYear > 0 ? year : year - 1,
  15559. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  15560. };
  15561. }
  15562. /************************************
  15563. Top Level Functions
  15564. ************************************/
  15565. function makeMoment(config) {
  15566. var input = config._i,
  15567. format = config._f;
  15568. if (typeof config._pf === 'undefined') {
  15569. initializeParsingFlags(config);
  15570. }
  15571. if (input === null) {
  15572. return moment.invalid({nullInput: true});
  15573. }
  15574. if (typeof input === 'string') {
  15575. config._i = input = getLangDefinition().preparse(input);
  15576. }
  15577. if (moment.isMoment(input)) {
  15578. config = extend({}, input);
  15579. config._d = new Date(+input._d);
  15580. } else if (format) {
  15581. if (isArray(format)) {
  15582. makeDateFromStringAndArray(config);
  15583. } else {
  15584. makeDateFromStringAndFormat(config);
  15585. }
  15586. } else {
  15587. makeDateFromInput(config);
  15588. }
  15589. return new Moment(config);
  15590. }
  15591. moment = function (input, format, lang, strict) {
  15592. if (typeof(lang) === "boolean") {
  15593. strict = lang;
  15594. lang = undefined;
  15595. }
  15596. return makeMoment({
  15597. _i : input,
  15598. _f : format,
  15599. _l : lang,
  15600. _strict : strict,
  15601. _isUTC : false
  15602. });
  15603. };
  15604. // creating with utc
  15605. moment.utc = function (input, format, lang, strict) {
  15606. var m;
  15607. if (typeof(lang) === "boolean") {
  15608. strict = lang;
  15609. lang = undefined;
  15610. }
  15611. m = makeMoment({
  15612. _useUTC : true,
  15613. _isUTC : true,
  15614. _l : lang,
  15615. _i : input,
  15616. _f : format,
  15617. _strict : strict
  15618. }).utc();
  15619. return m;
  15620. };
  15621. // creating with unix timestamp (in seconds)
  15622. moment.unix = function (input) {
  15623. return moment(input * 1000);
  15624. };
  15625. // duration
  15626. moment.duration = function (input, key) {
  15627. var duration = input,
  15628. // matching against regexp is expensive, do it on demand
  15629. match = null,
  15630. sign,
  15631. ret,
  15632. parseIso;
  15633. if (moment.isDuration(input)) {
  15634. duration = {
  15635. ms: input._milliseconds,
  15636. d: input._days,
  15637. M: input._months
  15638. };
  15639. } else if (typeof input === 'number') {
  15640. duration = {};
  15641. if (key) {
  15642. duration[key] = input;
  15643. } else {
  15644. duration.milliseconds = input;
  15645. }
  15646. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  15647. sign = (match[1] === "-") ? -1 : 1;
  15648. duration = {
  15649. y: 0,
  15650. d: toInt(match[DATE]) * sign,
  15651. h: toInt(match[HOUR]) * sign,
  15652. m: toInt(match[MINUTE]) * sign,
  15653. s: toInt(match[SECOND]) * sign,
  15654. ms: toInt(match[MILLISECOND]) * sign
  15655. };
  15656. } else if (!!(match = isoDurationRegex.exec(input))) {
  15657. sign = (match[1] === "-") ? -1 : 1;
  15658. parseIso = function (inp) {
  15659. // We'd normally use ~~inp for this, but unfortunately it also
  15660. // converts floats to ints.
  15661. // inp may be undefined, so careful calling replace on it.
  15662. var res = inp && parseFloat(inp.replace(',', '.'));
  15663. // apply sign while we're at it
  15664. return (isNaN(res) ? 0 : res) * sign;
  15665. };
  15666. duration = {
  15667. y: parseIso(match[2]),
  15668. M: parseIso(match[3]),
  15669. d: parseIso(match[4]),
  15670. h: parseIso(match[5]),
  15671. m: parseIso(match[6]),
  15672. s: parseIso(match[7]),
  15673. w: parseIso(match[8])
  15674. };
  15675. }
  15676. ret = new Duration(duration);
  15677. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  15678. ret._lang = input._lang;
  15679. }
  15680. return ret;
  15681. };
  15682. // version number
  15683. moment.version = VERSION;
  15684. // default format
  15685. moment.defaultFormat = isoFormat;
  15686. // This function will be called whenever a moment is mutated.
  15687. // It is intended to keep the offset in sync with the timezone.
  15688. moment.updateOffset = function () {};
  15689. // This function will load languages and then set the global language. If
  15690. // no arguments are passed in, it will simply return the current global
  15691. // language key.
  15692. moment.lang = function (key, values) {
  15693. var r;
  15694. if (!key) {
  15695. return moment.fn._lang._abbr;
  15696. }
  15697. if (values) {
  15698. loadLang(normalizeLanguage(key), values);
  15699. } else if (values === null) {
  15700. unloadLang(key);
  15701. key = 'en';
  15702. } else if (!languages[key]) {
  15703. getLangDefinition(key);
  15704. }
  15705. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  15706. return r._abbr;
  15707. };
  15708. // returns language data
  15709. moment.langData = function (key) {
  15710. if (key && key._lang && key._lang._abbr) {
  15711. key = key._lang._abbr;
  15712. }
  15713. return getLangDefinition(key);
  15714. };
  15715. // compare moment object
  15716. moment.isMoment = function (obj) {
  15717. return obj instanceof Moment;
  15718. };
  15719. // for typechecking Duration objects
  15720. moment.isDuration = function (obj) {
  15721. return obj instanceof Duration;
  15722. };
  15723. for (i = lists.length - 1; i >= 0; --i) {
  15724. makeList(lists[i]);
  15725. }
  15726. moment.normalizeUnits = function (units) {
  15727. return normalizeUnits(units);
  15728. };
  15729. moment.invalid = function (flags) {
  15730. var m = moment.utc(NaN);
  15731. if (flags != null) {
  15732. extend(m._pf, flags);
  15733. }
  15734. else {
  15735. m._pf.userInvalidated = true;
  15736. }
  15737. return m;
  15738. };
  15739. moment.parseZone = function (input) {
  15740. return moment(input).parseZone();
  15741. };
  15742. /************************************
  15743. Moment Prototype
  15744. ************************************/
  15745. extend(moment.fn = Moment.prototype, {
  15746. clone : function () {
  15747. return moment(this);
  15748. },
  15749. valueOf : function () {
  15750. return +this._d + ((this._offset || 0) * 60000);
  15751. },
  15752. unix : function () {
  15753. return Math.floor(+this / 1000);
  15754. },
  15755. toString : function () {
  15756. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  15757. },
  15758. toDate : function () {
  15759. return this._offset ? new Date(+this) : this._d;
  15760. },
  15761. toISOString : function () {
  15762. var m = moment(this).utc();
  15763. if (0 < m.year() && m.year() <= 9999) {
  15764. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  15765. } else {
  15766. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  15767. }
  15768. },
  15769. toArray : function () {
  15770. var m = this;
  15771. return [
  15772. m.year(),
  15773. m.month(),
  15774. m.date(),
  15775. m.hours(),
  15776. m.minutes(),
  15777. m.seconds(),
  15778. m.milliseconds()
  15779. ];
  15780. },
  15781. isValid : function () {
  15782. return isValid(this);
  15783. },
  15784. isDSTShifted : function () {
  15785. if (this._a) {
  15786. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  15787. }
  15788. return false;
  15789. },
  15790. parsingFlags : function () {
  15791. return extend({}, this._pf);
  15792. },
  15793. invalidAt: function () {
  15794. return this._pf.overflow;
  15795. },
  15796. utc : function () {
  15797. return this.zone(0);
  15798. },
  15799. local : function () {
  15800. this.zone(0);
  15801. this._isUTC = false;
  15802. return this;
  15803. },
  15804. format : function (inputString) {
  15805. var output = formatMoment(this, inputString || moment.defaultFormat);
  15806. return this.lang().postformat(output);
  15807. },
  15808. add : function (input, val) {
  15809. var dur;
  15810. // switch args to support add('s', 1) and add(1, 's')
  15811. if (typeof input === 'string') {
  15812. dur = moment.duration(+val, input);
  15813. } else {
  15814. dur = moment.duration(input, val);
  15815. }
  15816. addOrSubtractDurationFromMoment(this, dur, 1);
  15817. return this;
  15818. },
  15819. subtract : function (input, val) {
  15820. var dur;
  15821. // switch args to support subtract('s', 1) and subtract(1, 's')
  15822. if (typeof input === 'string') {
  15823. dur = moment.duration(+val, input);
  15824. } else {
  15825. dur = moment.duration(input, val);
  15826. }
  15827. addOrSubtractDurationFromMoment(this, dur, -1);
  15828. return this;
  15829. },
  15830. diff : function (input, units, asFloat) {
  15831. var that = makeAs(input, this),
  15832. zoneDiff = (this.zone() - that.zone()) * 6e4,
  15833. diff, output;
  15834. units = normalizeUnits(units);
  15835. if (units === 'year' || units === 'month') {
  15836. // average number of days in the months in the given dates
  15837. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  15838. // difference in months
  15839. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  15840. // adjust by taking difference in days, average number of days
  15841. // and dst in the given months.
  15842. output += ((this - moment(this).startOf('month')) -
  15843. (that - moment(that).startOf('month'))) / diff;
  15844. // same as above but with zones, to negate all dst
  15845. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  15846. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  15847. if (units === 'year') {
  15848. output = output / 12;
  15849. }
  15850. } else {
  15851. diff = (this - that);
  15852. output = units === 'second' ? diff / 1e3 : // 1000
  15853. units === 'minute' ? diff / 6e4 : // 1000 * 60
  15854. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  15855. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  15856. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  15857. diff;
  15858. }
  15859. return asFloat ? output : absRound(output);
  15860. },
  15861. from : function (time, withoutSuffix) {
  15862. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  15863. },
  15864. fromNow : function (withoutSuffix) {
  15865. return this.from(moment(), withoutSuffix);
  15866. },
  15867. calendar : function () {
  15868. // We want to compare the start of today, vs this.
  15869. // Getting start-of-today depends on whether we're zone'd or not.
  15870. var sod = makeAs(moment(), this).startOf('day'),
  15871. diff = this.diff(sod, 'days', true),
  15872. format = diff < -6 ? 'sameElse' :
  15873. diff < -1 ? 'lastWeek' :
  15874. diff < 0 ? 'lastDay' :
  15875. diff < 1 ? 'sameDay' :
  15876. diff < 2 ? 'nextDay' :
  15877. diff < 7 ? 'nextWeek' : 'sameElse';
  15878. return this.format(this.lang().calendar(format, this));
  15879. },
  15880. isLeapYear : function () {
  15881. return isLeapYear(this.year());
  15882. },
  15883. isDST : function () {
  15884. return (this.zone() < this.clone().month(0).zone() ||
  15885. this.zone() < this.clone().month(5).zone());
  15886. },
  15887. day : function (input) {
  15888. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  15889. if (input != null) {
  15890. input = parseWeekday(input, this.lang());
  15891. return this.add({ d : input - day });
  15892. } else {
  15893. return day;
  15894. }
  15895. },
  15896. month : function (input) {
  15897. var utc = this._isUTC ? 'UTC' : '',
  15898. dayOfMonth;
  15899. if (input != null) {
  15900. if (typeof input === 'string') {
  15901. input = this.lang().monthsParse(input);
  15902. if (typeof input !== 'number') {
  15903. return this;
  15904. }
  15905. }
  15906. dayOfMonth = this.date();
  15907. this.date(1);
  15908. this._d['set' + utc + 'Month'](input);
  15909. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  15910. moment.updateOffset(this);
  15911. return this;
  15912. } else {
  15913. return this._d['get' + utc + 'Month']();
  15914. }
  15915. },
  15916. startOf: function (units) {
  15917. units = normalizeUnits(units);
  15918. // the following switch intentionally omits break keywords
  15919. // to utilize falling through the cases.
  15920. switch (units) {
  15921. case 'year':
  15922. this.month(0);
  15923. /* falls through */
  15924. case 'month':
  15925. this.date(1);
  15926. /* falls through */
  15927. case 'week':
  15928. case 'isoWeek':
  15929. case 'day':
  15930. this.hours(0);
  15931. /* falls through */
  15932. case 'hour':
  15933. this.minutes(0);
  15934. /* falls through */
  15935. case 'minute':
  15936. this.seconds(0);
  15937. /* falls through */
  15938. case 'second':
  15939. this.milliseconds(0);
  15940. /* falls through */
  15941. }
  15942. // weeks are a special case
  15943. if (units === 'week') {
  15944. this.weekday(0);
  15945. } else if (units === 'isoWeek') {
  15946. this.isoWeekday(1);
  15947. }
  15948. return this;
  15949. },
  15950. endOf: function (units) {
  15951. units = normalizeUnits(units);
  15952. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  15953. },
  15954. isAfter: function (input, units) {
  15955. units = typeof units !== 'undefined' ? units : 'millisecond';
  15956. return +this.clone().startOf(units) > +moment(input).startOf(units);
  15957. },
  15958. isBefore: function (input, units) {
  15959. units = typeof units !== 'undefined' ? units : 'millisecond';
  15960. return +this.clone().startOf(units) < +moment(input).startOf(units);
  15961. },
  15962. isSame: function (input, units) {
  15963. units = units || 'ms';
  15964. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  15965. },
  15966. min: function (other) {
  15967. other = moment.apply(null, arguments);
  15968. return other < this ? this : other;
  15969. },
  15970. max: function (other) {
  15971. other = moment.apply(null, arguments);
  15972. return other > this ? this : other;
  15973. },
  15974. zone : function (input) {
  15975. var offset = this._offset || 0;
  15976. if (input != null) {
  15977. if (typeof input === "string") {
  15978. input = timezoneMinutesFromString(input);
  15979. }
  15980. if (Math.abs(input) < 16) {
  15981. input = input * 60;
  15982. }
  15983. this._offset = input;
  15984. this._isUTC = true;
  15985. if (offset !== input) {
  15986. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  15987. }
  15988. } else {
  15989. return this._isUTC ? offset : this._d.getTimezoneOffset();
  15990. }
  15991. return this;
  15992. },
  15993. zoneAbbr : function () {
  15994. return this._isUTC ? "UTC" : "";
  15995. },
  15996. zoneName : function () {
  15997. return this._isUTC ? "Coordinated Universal Time" : "";
  15998. },
  15999. parseZone : function () {
  16000. if (this._tzm) {
  16001. this.zone(this._tzm);
  16002. } else if (typeof this._i === 'string') {
  16003. this.zone(this._i);
  16004. }
  16005. return this;
  16006. },
  16007. hasAlignedHourOffset : function (input) {
  16008. if (!input) {
  16009. input = 0;
  16010. }
  16011. else {
  16012. input = moment(input).zone();
  16013. }
  16014. return (this.zone() - input) % 60 === 0;
  16015. },
  16016. daysInMonth : function () {
  16017. return daysInMonth(this.year(), this.month());
  16018. },
  16019. dayOfYear : function (input) {
  16020. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  16021. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  16022. },
  16023. quarter : function () {
  16024. return Math.ceil((this.month() + 1.0) / 3.0);
  16025. },
  16026. weekYear : function (input) {
  16027. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  16028. return input == null ? year : this.add("y", (input - year));
  16029. },
  16030. isoWeekYear : function (input) {
  16031. var year = weekOfYear(this, 1, 4).year;
  16032. return input == null ? year : this.add("y", (input - year));
  16033. },
  16034. week : function (input) {
  16035. var week = this.lang().week(this);
  16036. return input == null ? week : this.add("d", (input - week) * 7);
  16037. },
  16038. isoWeek : function (input) {
  16039. var week = weekOfYear(this, 1, 4).week;
  16040. return input == null ? week : this.add("d", (input - week) * 7);
  16041. },
  16042. weekday : function (input) {
  16043. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  16044. return input == null ? weekday : this.add("d", input - weekday);
  16045. },
  16046. isoWeekday : function (input) {
  16047. // behaves the same as moment#day except
  16048. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  16049. // as a setter, sunday should belong to the previous week.
  16050. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  16051. },
  16052. get : function (units) {
  16053. units = normalizeUnits(units);
  16054. return this[units]();
  16055. },
  16056. set : function (units, value) {
  16057. units = normalizeUnits(units);
  16058. if (typeof this[units] === 'function') {
  16059. this[units](value);
  16060. }
  16061. return this;
  16062. },
  16063. // If passed a language key, it will set the language for this
  16064. // instance. Otherwise, it will return the language configuration
  16065. // variables for this instance.
  16066. lang : function (key) {
  16067. if (key === undefined) {
  16068. return this._lang;
  16069. } else {
  16070. this._lang = getLangDefinition(key);
  16071. return this;
  16072. }
  16073. }
  16074. });
  16075. // helper for adding shortcuts
  16076. function makeGetterAndSetter(name, key) {
  16077. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  16078. var utc = this._isUTC ? 'UTC' : '';
  16079. if (input != null) {
  16080. this._d['set' + utc + key](input);
  16081. moment.updateOffset(this);
  16082. return this;
  16083. } else {
  16084. return this._d['get' + utc + key]();
  16085. }
  16086. };
  16087. }
  16088. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  16089. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  16090. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  16091. }
  16092. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  16093. makeGetterAndSetter('year', 'FullYear');
  16094. // add plural methods
  16095. moment.fn.days = moment.fn.day;
  16096. moment.fn.months = moment.fn.month;
  16097. moment.fn.weeks = moment.fn.week;
  16098. moment.fn.isoWeeks = moment.fn.isoWeek;
  16099. // add aliased format methods
  16100. moment.fn.toJSON = moment.fn.toISOString;
  16101. /************************************
  16102. Duration Prototype
  16103. ************************************/
  16104. extend(moment.duration.fn = Duration.prototype, {
  16105. _bubble : function () {
  16106. var milliseconds = this._milliseconds,
  16107. days = this._days,
  16108. months = this._months,
  16109. data = this._data,
  16110. seconds, minutes, hours, years;
  16111. // The following code bubbles up values, see the tests for
  16112. // examples of what that means.
  16113. data.milliseconds = milliseconds % 1000;
  16114. seconds = absRound(milliseconds / 1000);
  16115. data.seconds = seconds % 60;
  16116. minutes = absRound(seconds / 60);
  16117. data.minutes = minutes % 60;
  16118. hours = absRound(minutes / 60);
  16119. data.hours = hours % 24;
  16120. days += absRound(hours / 24);
  16121. data.days = days % 30;
  16122. months += absRound(days / 30);
  16123. data.months = months % 12;
  16124. years = absRound(months / 12);
  16125. data.years = years;
  16126. },
  16127. weeks : function () {
  16128. return absRound(this.days() / 7);
  16129. },
  16130. valueOf : function () {
  16131. return this._milliseconds +
  16132. this._days * 864e5 +
  16133. (this._months % 12) * 2592e6 +
  16134. toInt(this._months / 12) * 31536e6;
  16135. },
  16136. humanize : function (withSuffix) {
  16137. var difference = +this,
  16138. output = relativeTime(difference, !withSuffix, this.lang());
  16139. if (withSuffix) {
  16140. output = this.lang().pastFuture(difference, output);
  16141. }
  16142. return this.lang().postformat(output);
  16143. },
  16144. add : function (input, val) {
  16145. // supports only 2.0-style add(1, 's') or add(moment)
  16146. var dur = moment.duration(input, val);
  16147. this._milliseconds += dur._milliseconds;
  16148. this._days += dur._days;
  16149. this._months += dur._months;
  16150. this._bubble();
  16151. return this;
  16152. },
  16153. subtract : function (input, val) {
  16154. var dur = moment.duration(input, val);
  16155. this._milliseconds -= dur._milliseconds;
  16156. this._days -= dur._days;
  16157. this._months -= dur._months;
  16158. this._bubble();
  16159. return this;
  16160. },
  16161. get : function (units) {
  16162. units = normalizeUnits(units);
  16163. return this[units.toLowerCase() + 's']();
  16164. },
  16165. as : function (units) {
  16166. units = normalizeUnits(units);
  16167. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  16168. },
  16169. lang : moment.fn.lang,
  16170. toIsoString : function () {
  16171. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  16172. var years = Math.abs(this.years()),
  16173. months = Math.abs(this.months()),
  16174. days = Math.abs(this.days()),
  16175. hours = Math.abs(this.hours()),
  16176. minutes = Math.abs(this.minutes()),
  16177. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  16178. if (!this.asSeconds()) {
  16179. // this is the same as C#'s (Noda) and python (isodate)...
  16180. // but not other JS (goog.date)
  16181. return 'P0D';
  16182. }
  16183. return (this.asSeconds() < 0 ? '-' : '') +
  16184. 'P' +
  16185. (years ? years + 'Y' : '') +
  16186. (months ? months + 'M' : '') +
  16187. (days ? days + 'D' : '') +
  16188. ((hours || minutes || seconds) ? 'T' : '') +
  16189. (hours ? hours + 'H' : '') +
  16190. (minutes ? minutes + 'M' : '') +
  16191. (seconds ? seconds + 'S' : '');
  16192. }
  16193. });
  16194. function makeDurationGetter(name) {
  16195. moment.duration.fn[name] = function () {
  16196. return this._data[name];
  16197. };
  16198. }
  16199. function makeDurationAsGetter(name, factor) {
  16200. moment.duration.fn['as' + name] = function () {
  16201. return +this / factor;
  16202. };
  16203. }
  16204. for (i in unitMillisecondFactors) {
  16205. if (unitMillisecondFactors.hasOwnProperty(i)) {
  16206. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  16207. makeDurationGetter(i.toLowerCase());
  16208. }
  16209. }
  16210. makeDurationAsGetter('Weeks', 6048e5);
  16211. moment.duration.fn.asMonths = function () {
  16212. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  16213. };
  16214. /************************************
  16215. Default Lang
  16216. ************************************/
  16217. // Set default language, other languages will inherit from English.
  16218. moment.lang('en', {
  16219. ordinal : function (number) {
  16220. var b = number % 10,
  16221. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  16222. (b === 1) ? 'st' :
  16223. (b === 2) ? 'nd' :
  16224. (b === 3) ? 'rd' : 'th';
  16225. return number + output;
  16226. }
  16227. });
  16228. /* EMBED_LANGUAGES */
  16229. /************************************
  16230. Exposing Moment
  16231. ************************************/
  16232. function makeGlobal(deprecate) {
  16233. var warned = false, local_moment = moment;
  16234. /*global ender:false */
  16235. if (typeof ender !== 'undefined') {
  16236. return;
  16237. }
  16238. // here, `this` means `window` in the browser, or `global` on the server
  16239. // add `moment` as a global object via a string identifier,
  16240. // for Closure Compiler "advanced" mode
  16241. if (deprecate) {
  16242. global.moment = function () {
  16243. if (!warned && console && console.warn) {
  16244. warned = true;
  16245. console.warn(
  16246. "Accessing Moment through the global scope is " +
  16247. "deprecated, and will be removed in an upcoming " +
  16248. "release.");
  16249. }
  16250. return local_moment.apply(null, arguments);
  16251. };
  16252. extend(global.moment, local_moment);
  16253. } else {
  16254. global['moment'] = moment;
  16255. }
  16256. }
  16257. // CommonJS module is defined
  16258. if (hasModule) {
  16259. module.exports = moment;
  16260. makeGlobal(true);
  16261. } else if (typeof define === "function" && define.amd) {
  16262. define("moment", function (require, exports, module) {
  16263. if (module.config && module.config() && module.config().noGlobal !== true) {
  16264. // If user provided noGlobal, he is aware of global
  16265. makeGlobal(module.config().noGlobal === undefined);
  16266. }
  16267. return moment;
  16268. });
  16269. } else {
  16270. makeGlobal();
  16271. }
  16272. }).call(this);
  16273. },{}],4:[function(require,module,exports){
  16274. /**
  16275. * Copyright 2012 Craig Campbell
  16276. *
  16277. * Licensed under the Apache License, Version 2.0 (the "License");
  16278. * you may not use this file except in compliance with the License.
  16279. * You may obtain a copy of the License at
  16280. *
  16281. * http://www.apache.org/licenses/LICENSE-2.0
  16282. *
  16283. * Unless required by applicable law or agreed to in writing, software
  16284. * distributed under the License is distributed on an "AS IS" BASIS,
  16285. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16286. * See the License for the specific language governing permissions and
  16287. * limitations under the License.
  16288. *
  16289. * Mousetrap is a simple keyboard shortcut library for Javascript with
  16290. * no external dependencies
  16291. *
  16292. * @version 1.1.2
  16293. * @url craig.is/killing/mice
  16294. */
  16295. /**
  16296. * mapping of special keycodes to their corresponding keys
  16297. *
  16298. * everything in this dictionary cannot use keypress events
  16299. * so it has to be here to map to the correct keycodes for
  16300. * keyup/keydown events
  16301. *
  16302. * @type {Object}
  16303. */
  16304. var _MAP = {
  16305. 8: 'backspace',
  16306. 9: 'tab',
  16307. 13: 'enter',
  16308. 16: 'shift',
  16309. 17: 'ctrl',
  16310. 18: 'alt',
  16311. 20: 'capslock',
  16312. 27: 'esc',
  16313. 32: 'space',
  16314. 33: 'pageup',
  16315. 34: 'pagedown',
  16316. 35: 'end',
  16317. 36: 'home',
  16318. 37: 'left',
  16319. 38: 'up',
  16320. 39: 'right',
  16321. 40: 'down',
  16322. 45: 'ins',
  16323. 46: 'del',
  16324. 91: 'meta',
  16325. 93: 'meta',
  16326. 224: 'meta'
  16327. },
  16328. /**
  16329. * mapping for special characters so they can support
  16330. *
  16331. * this dictionary is only used incase you want to bind a
  16332. * keyup or keydown event to one of these keys
  16333. *
  16334. * @type {Object}
  16335. */
  16336. _KEYCODE_MAP = {
  16337. 106: '*',
  16338. 107: '+',
  16339. 109: '-',
  16340. 110: '.',
  16341. 111 : '/',
  16342. 186: ';',
  16343. 187: '=',
  16344. 188: ',',
  16345. 189: '-',
  16346. 190: '.',
  16347. 191: '/',
  16348. 192: '`',
  16349. 219: '[',
  16350. 220: '\\',
  16351. 221: ']',
  16352. 222: '\''
  16353. },
  16354. /**
  16355. * this is a mapping of keys that require shift on a US keypad
  16356. * back to the non shift equivelents
  16357. *
  16358. * this is so you can use keyup events with these keys
  16359. *
  16360. * note that this will only work reliably on US keyboards
  16361. *
  16362. * @type {Object}
  16363. */
  16364. _SHIFT_MAP = {
  16365. '~': '`',
  16366. '!': '1',
  16367. '@': '2',
  16368. '#': '3',
  16369. '$': '4',
  16370. '%': '5',
  16371. '^': '6',
  16372. '&': '7',
  16373. '*': '8',
  16374. '(': '9',
  16375. ')': '0',
  16376. '_': '-',
  16377. '+': '=',
  16378. ':': ';',
  16379. '\"': '\'',
  16380. '<': ',',
  16381. '>': '.',
  16382. '?': '/',
  16383. '|': '\\'
  16384. },
  16385. /**
  16386. * this is a list of special strings you can use to map
  16387. * to modifier keys when you specify your keyboard shortcuts
  16388. *
  16389. * @type {Object}
  16390. */
  16391. _SPECIAL_ALIASES = {
  16392. 'option': 'alt',
  16393. 'command': 'meta',
  16394. 'return': 'enter',
  16395. 'escape': 'esc'
  16396. },
  16397. /**
  16398. * variable to store the flipped version of _MAP from above
  16399. * needed to check if we should use keypress or not when no action
  16400. * is specified
  16401. *
  16402. * @type {Object|undefined}
  16403. */
  16404. _REVERSE_MAP,
  16405. /**
  16406. * a list of all the callbacks setup via Mousetrap.bind()
  16407. *
  16408. * @type {Object}
  16409. */
  16410. _callbacks = {},
  16411. /**
  16412. * direct map of string combinations to callbacks used for trigger()
  16413. *
  16414. * @type {Object}
  16415. */
  16416. _direct_map = {},
  16417. /**
  16418. * keeps track of what level each sequence is at since multiple
  16419. * sequences can start out with the same sequence
  16420. *
  16421. * @type {Object}
  16422. */
  16423. _sequence_levels = {},
  16424. /**
  16425. * variable to store the setTimeout call
  16426. *
  16427. * @type {null|number}
  16428. */
  16429. _reset_timer,
  16430. /**
  16431. * temporary state where we will ignore the next keyup
  16432. *
  16433. * @type {boolean|string}
  16434. */
  16435. _ignore_next_keyup = false,
  16436. /**
  16437. * are we currently inside of a sequence?
  16438. * type of action ("keyup" or "keydown" or "keypress") or false
  16439. *
  16440. * @type {boolean|string}
  16441. */
  16442. _inside_sequence = false;
  16443. /**
  16444. * loop through the f keys, f1 to f19 and add them to the map
  16445. * programatically
  16446. */
  16447. for (var i = 1; i < 20; ++i) {
  16448. _MAP[111 + i] = 'f' + i;
  16449. }
  16450. /**
  16451. * loop through to map numbers on the numeric keypad
  16452. */
  16453. for (i = 0; i <= 9; ++i) {
  16454. _MAP[i + 96] = i;
  16455. }
  16456. /**
  16457. * cross browser add event method
  16458. *
  16459. * @param {Element|HTMLDocument} object
  16460. * @param {string} type
  16461. * @param {Function} callback
  16462. * @returns void
  16463. */
  16464. function _addEvent(object, type, callback) {
  16465. if (object.addEventListener) {
  16466. return object.addEventListener(type, callback, false);
  16467. }
  16468. object.attachEvent('on' + type, callback);
  16469. }
  16470. /**
  16471. * takes the event and returns the key character
  16472. *
  16473. * @param {Event} e
  16474. * @return {string}
  16475. */
  16476. function _characterFromEvent(e) {
  16477. // for keypress events we should return the character as is
  16478. if (e.type == 'keypress') {
  16479. return String.fromCharCode(e.which);
  16480. }
  16481. // for non keypress events the special maps are needed
  16482. if (_MAP[e.which]) {
  16483. return _MAP[e.which];
  16484. }
  16485. if (_KEYCODE_MAP[e.which]) {
  16486. return _KEYCODE_MAP[e.which];
  16487. }
  16488. // if it is not in the special map
  16489. return String.fromCharCode(e.which).toLowerCase();
  16490. }
  16491. /**
  16492. * should we stop this event before firing off callbacks
  16493. *
  16494. * @param {Event} e
  16495. * @return {boolean}
  16496. */
  16497. function _stop(e) {
  16498. var element = e.target || e.srcElement,
  16499. tag_name = element.tagName;
  16500. // if the element has the class "mousetrap" then no need to stop
  16501. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  16502. return false;
  16503. }
  16504. // stop for input, select, and textarea
  16505. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  16506. }
  16507. /**
  16508. * checks if two arrays are equal
  16509. *
  16510. * @param {Array} modifiers1
  16511. * @param {Array} modifiers2
  16512. * @returns {boolean}
  16513. */
  16514. function _modifiersMatch(modifiers1, modifiers2) {
  16515. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  16516. }
  16517. /**
  16518. * resets all sequence counters except for the ones passed in
  16519. *
  16520. * @param {Object} do_not_reset
  16521. * @returns void
  16522. */
  16523. function _resetSequences(do_not_reset) {
  16524. do_not_reset = do_not_reset || {};
  16525. var active_sequences = false,
  16526. key;
  16527. for (key in _sequence_levels) {
  16528. if (do_not_reset[key]) {
  16529. active_sequences = true;
  16530. continue;
  16531. }
  16532. _sequence_levels[key] = 0;
  16533. }
  16534. if (!active_sequences) {
  16535. _inside_sequence = false;
  16536. }
  16537. }
  16538. /**
  16539. * finds all callbacks that match based on the keycode, modifiers,
  16540. * and action
  16541. *
  16542. * @param {string} character
  16543. * @param {Array} modifiers
  16544. * @param {string} action
  16545. * @param {boolean=} remove - should we remove any matches
  16546. * @param {string=} combination
  16547. * @returns {Array}
  16548. */
  16549. function _getMatches(character, modifiers, action, remove, combination) {
  16550. var i,
  16551. callback,
  16552. matches = [];
  16553. // if there are no events related to this keycode
  16554. if (!_callbacks[character]) {
  16555. return [];
  16556. }
  16557. // if a modifier key is coming up on its own we should allow it
  16558. if (action == 'keyup' && _isModifier(character)) {
  16559. modifiers = [character];
  16560. }
  16561. // loop through all callbacks for the key that was pressed
  16562. // and see if any of them match
  16563. for (i = 0; i < _callbacks[character].length; ++i) {
  16564. callback = _callbacks[character][i];
  16565. // if this is a sequence but it is not at the right level
  16566. // then move onto the next match
  16567. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  16568. continue;
  16569. }
  16570. // if the action we are looking for doesn't match the action we got
  16571. // then we should keep going
  16572. if (action != callback.action) {
  16573. continue;
  16574. }
  16575. // if this is a keypress event that means that we need to only
  16576. // look at the character, otherwise check the modifiers as
  16577. // well
  16578. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  16579. // remove is used so if you change your mind and call bind a
  16580. // second time with a new function the first one is overwritten
  16581. if (remove && callback.combo == combination) {
  16582. _callbacks[character].splice(i, 1);
  16583. }
  16584. matches.push(callback);
  16585. }
  16586. }
  16587. return matches;
  16588. }
  16589. /**
  16590. * takes a key event and figures out what the modifiers are
  16591. *
  16592. * @param {Event} e
  16593. * @returns {Array}
  16594. */
  16595. function _eventModifiers(e) {
  16596. var modifiers = [];
  16597. if (e.shiftKey) {
  16598. modifiers.push('shift');
  16599. }
  16600. if (e.altKey) {
  16601. modifiers.push('alt');
  16602. }
  16603. if (e.ctrlKey) {
  16604. modifiers.push('ctrl');
  16605. }
  16606. if (e.metaKey) {
  16607. modifiers.push('meta');
  16608. }
  16609. return modifiers;
  16610. }
  16611. /**
  16612. * actually calls the callback function
  16613. *
  16614. * if your callback function returns false this will use the jquery
  16615. * convention - prevent default and stop propogation on the event
  16616. *
  16617. * @param {Function} callback
  16618. * @param {Event} e
  16619. * @returns void
  16620. */
  16621. function _fireCallback(callback, e) {
  16622. if (callback(e) === false) {
  16623. if (e.preventDefault) {
  16624. e.preventDefault();
  16625. }
  16626. if (e.stopPropagation) {
  16627. e.stopPropagation();
  16628. }
  16629. e.returnValue = false;
  16630. e.cancelBubble = true;
  16631. }
  16632. }
  16633. /**
  16634. * handles a character key event
  16635. *
  16636. * @param {string} character
  16637. * @param {Event} e
  16638. * @returns void
  16639. */
  16640. function _handleCharacter(character, e) {
  16641. // if this event should not happen stop here
  16642. if (_stop(e)) {
  16643. return;
  16644. }
  16645. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  16646. i,
  16647. do_not_reset = {},
  16648. processed_sequence_callback = false;
  16649. // loop through matching callbacks for this key event
  16650. for (i = 0; i < callbacks.length; ++i) {
  16651. // fire for all sequence callbacks
  16652. // this is because if for example you have multiple sequences
  16653. // bound such as "g i" and "g t" they both need to fire the
  16654. // callback for matching g cause otherwise you can only ever
  16655. // match the first one
  16656. if (callbacks[i].seq) {
  16657. processed_sequence_callback = true;
  16658. // keep a list of which sequences were matches for later
  16659. do_not_reset[callbacks[i].seq] = 1;
  16660. _fireCallback(callbacks[i].callback, e);
  16661. continue;
  16662. }
  16663. // if there were no sequence matches but we are still here
  16664. // that means this is a regular match so we should fire that
  16665. if (!processed_sequence_callback && !_inside_sequence) {
  16666. _fireCallback(callbacks[i].callback, e);
  16667. }
  16668. }
  16669. // if you are inside of a sequence and the key you are pressing
  16670. // is not a modifier key then we should reset all sequences
  16671. // that were not matched by this key event
  16672. if (e.type == _inside_sequence && !_isModifier(character)) {
  16673. _resetSequences(do_not_reset);
  16674. }
  16675. }
  16676. /**
  16677. * handles a keydown event
  16678. *
  16679. * @param {Event} e
  16680. * @returns void
  16681. */
  16682. function _handleKey(e) {
  16683. // normalize e.which for key events
  16684. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  16685. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  16686. var character = _characterFromEvent(e);
  16687. // no character found then stop
  16688. if (!character) {
  16689. return;
  16690. }
  16691. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  16692. _ignore_next_keyup = false;
  16693. return;
  16694. }
  16695. _handleCharacter(character, e);
  16696. }
  16697. /**
  16698. * determines if the keycode specified is a modifier key or not
  16699. *
  16700. * @param {string} key
  16701. * @returns {boolean}
  16702. */
  16703. function _isModifier(key) {
  16704. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  16705. }
  16706. /**
  16707. * called to set a 1 second timeout on the specified sequence
  16708. *
  16709. * this is so after each key press in the sequence you have 1 second
  16710. * to press the next key before you have to start over
  16711. *
  16712. * @returns void
  16713. */
  16714. function _resetSequenceTimer() {
  16715. clearTimeout(_reset_timer);
  16716. _reset_timer = setTimeout(_resetSequences, 1000);
  16717. }
  16718. /**
  16719. * reverses the map lookup so that we can look for specific keys
  16720. * to see what can and can't use keypress
  16721. *
  16722. * @return {Object}
  16723. */
  16724. function _getReverseMap() {
  16725. if (!_REVERSE_MAP) {
  16726. _REVERSE_MAP = {};
  16727. for (var key in _MAP) {
  16728. // pull out the numeric keypad from here cause keypress should
  16729. // be able to detect the keys from the character
  16730. if (key > 95 && key < 112) {
  16731. continue;
  16732. }
  16733. if (_MAP.hasOwnProperty(key)) {
  16734. _REVERSE_MAP[_MAP[key]] = key;
  16735. }
  16736. }
  16737. }
  16738. return _REVERSE_MAP;
  16739. }
  16740. /**
  16741. * picks the best action based on the key combination
  16742. *
  16743. * @param {string} key - character for key
  16744. * @param {Array} modifiers
  16745. * @param {string=} action passed in
  16746. */
  16747. function _pickBestAction(key, modifiers, action) {
  16748. // if no action was picked in we should try to pick the one
  16749. // that we think would work best for this key
  16750. if (!action) {
  16751. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  16752. }
  16753. // modifier keys don't work as expected with keypress,
  16754. // switch to keydown
  16755. if (action == 'keypress' && modifiers.length) {
  16756. action = 'keydown';
  16757. }
  16758. return action;
  16759. }
  16760. /**
  16761. * binds a key sequence to an event
  16762. *
  16763. * @param {string} combo - combo specified in bind call
  16764. * @param {Array} keys
  16765. * @param {Function} callback
  16766. * @param {string=} action
  16767. * @returns void
  16768. */
  16769. function _bindSequence(combo, keys, callback, action) {
  16770. // start off by adding a sequence level record for this combination
  16771. // and setting the level to 0
  16772. _sequence_levels[combo] = 0;
  16773. // if there is no action pick the best one for the first key
  16774. // in the sequence
  16775. if (!action) {
  16776. action = _pickBestAction(keys[0], []);
  16777. }
  16778. /**
  16779. * callback to increase the sequence level for this sequence and reset
  16780. * all other sequences that were active
  16781. *
  16782. * @param {Event} e
  16783. * @returns void
  16784. */
  16785. var _increaseSequence = function(e) {
  16786. _inside_sequence = action;
  16787. ++_sequence_levels[combo];
  16788. _resetSequenceTimer();
  16789. },
  16790. /**
  16791. * wraps the specified callback inside of another function in order
  16792. * to reset all sequence counters as soon as this sequence is done
  16793. *
  16794. * @param {Event} e
  16795. * @returns void
  16796. */
  16797. _callbackAndReset = function(e) {
  16798. _fireCallback(callback, e);
  16799. // we should ignore the next key up if the action is key down
  16800. // or keypress. this is so if you finish a sequence and
  16801. // release the key the final key will not trigger a keyup
  16802. if (action !== 'keyup') {
  16803. _ignore_next_keyup = _characterFromEvent(e);
  16804. }
  16805. // weird race condition if a sequence ends with the key
  16806. // another sequence begins with
  16807. setTimeout(_resetSequences, 10);
  16808. },
  16809. i;
  16810. // loop through keys one at a time and bind the appropriate callback
  16811. // function. for any key leading up to the final one it should
  16812. // increase the sequence. after the final, it should reset all sequences
  16813. for (i = 0; i < keys.length; ++i) {
  16814. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  16815. }
  16816. }
  16817. /**
  16818. * binds a single keyboard combination
  16819. *
  16820. * @param {string} combination
  16821. * @param {Function} callback
  16822. * @param {string=} action
  16823. * @param {string=} sequence_name - name of sequence if part of sequence
  16824. * @param {number=} level - what part of the sequence the command is
  16825. * @returns void
  16826. */
  16827. function _bindSingle(combination, callback, action, sequence_name, level) {
  16828. // make sure multiple spaces in a row become a single space
  16829. combination = combination.replace(/\s+/g, ' ');
  16830. var sequence = combination.split(' '),
  16831. i,
  16832. key,
  16833. keys,
  16834. modifiers = [];
  16835. // if this pattern is a sequence of keys then run through this method
  16836. // to reprocess each pattern one key at a time
  16837. if (sequence.length > 1) {
  16838. return _bindSequence(combination, sequence, callback, action);
  16839. }
  16840. // take the keys from this pattern and figure out what the actual
  16841. // pattern is all about
  16842. keys = combination === '+' ? ['+'] : combination.split('+');
  16843. for (i = 0; i < keys.length; ++i) {
  16844. key = keys[i];
  16845. // normalize key names
  16846. if (_SPECIAL_ALIASES[key]) {
  16847. key = _SPECIAL_ALIASES[key];
  16848. }
  16849. // if this is not a keypress event then we should
  16850. // be smart about using shift keys
  16851. // this will only work for US keyboards however
  16852. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  16853. key = _SHIFT_MAP[key];
  16854. modifiers.push('shift');
  16855. }
  16856. // if this key is a modifier then add it to the list of modifiers
  16857. if (_isModifier(key)) {
  16858. modifiers.push(key);
  16859. }
  16860. }
  16861. // depending on what the key combination is
  16862. // we will try to pick the best event for it
  16863. action = _pickBestAction(key, modifiers, action);
  16864. // make sure to initialize array if this is the first time
  16865. // a callback is added for this key
  16866. if (!_callbacks[key]) {
  16867. _callbacks[key] = [];
  16868. }
  16869. // remove an existing match if there is one
  16870. _getMatches(key, modifiers, action, !sequence_name, combination);
  16871. // add this call back to the array
  16872. // if it is a sequence put it at the beginning
  16873. // if not put it at the end
  16874. //
  16875. // this is important because the way these are processed expects
  16876. // the sequence ones to come first
  16877. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  16878. callback: callback,
  16879. modifiers: modifiers,
  16880. action: action,
  16881. seq: sequence_name,
  16882. level: level,
  16883. combo: combination
  16884. });
  16885. }
  16886. /**
  16887. * binds multiple combinations to the same callback
  16888. *
  16889. * @param {Array} combinations
  16890. * @param {Function} callback
  16891. * @param {string|undefined} action
  16892. * @returns void
  16893. */
  16894. function _bindMultiple(combinations, callback, action) {
  16895. for (var i = 0; i < combinations.length; ++i) {
  16896. _bindSingle(combinations[i], callback, action);
  16897. }
  16898. }
  16899. // start!
  16900. _addEvent(document, 'keypress', _handleKey);
  16901. _addEvent(document, 'keydown', _handleKey);
  16902. _addEvent(document, 'keyup', _handleKey);
  16903. var mousetrap = {
  16904. /**
  16905. * binds an event to mousetrap
  16906. *
  16907. * can be a single key, a combination of keys separated with +,
  16908. * a comma separated list of keys, an array of keys, or
  16909. * a sequence of keys separated by spaces
  16910. *
  16911. * be sure to list the modifier keys first to make sure that the
  16912. * correct key ends up getting bound (the last key in the pattern)
  16913. *
  16914. * @param {string|Array} keys
  16915. * @param {Function} callback
  16916. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  16917. * @returns void
  16918. */
  16919. bind: function(keys, callback, action) {
  16920. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  16921. _direct_map[keys + ':' + action] = callback;
  16922. return this;
  16923. },
  16924. /**
  16925. * unbinds an event to mousetrap
  16926. *
  16927. * the unbinding sets the callback function of the specified key combo
  16928. * to an empty function and deletes the corresponding key in the
  16929. * _direct_map dict.
  16930. *
  16931. * the keycombo+action has to be exactly the same as
  16932. * it was defined in the bind method
  16933. *
  16934. * TODO: actually remove this from the _callbacks dictionary instead
  16935. * of binding an empty function
  16936. *
  16937. * @param {string|Array} keys
  16938. * @param {string} action
  16939. * @returns void
  16940. */
  16941. unbind: function(keys, action) {
  16942. if (_direct_map[keys + ':' + action]) {
  16943. delete _direct_map[keys + ':' + action];
  16944. this.bind(keys, function() {}, action);
  16945. }
  16946. return this;
  16947. },
  16948. /**
  16949. * triggers an event that has already been bound
  16950. *
  16951. * @param {string} keys
  16952. * @param {string=} action
  16953. * @returns void
  16954. */
  16955. trigger: function(keys, action) {
  16956. _direct_map[keys + ':' + action]();
  16957. return this;
  16958. },
  16959. /**
  16960. * resets the library back to its initial state. this is useful
  16961. * if you want to clear out the current keyboard shortcuts and bind
  16962. * new ones - for example if you switch to another page
  16963. *
  16964. * @returns void
  16965. */
  16966. reset: function() {
  16967. _callbacks = {};
  16968. _direct_map = {};
  16969. return this;
  16970. }
  16971. };
  16972. module.exports = mousetrap;
  16973. },{}]},{},[1])
  16974. (1)
  16975. });