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.

19659 lines
564 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 @@version
  8. * @date @@date
  9. *
  10. * @license
  11. * Copyright (C) 2011-2014 Almende B.V, http://almende.com
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  14. * use this file except in compliance with the License. You may obtain a copy
  15. * of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  22. * License for the specific language governing permissions and limitations under
  23. * the License.
  24. */
  25. !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.vis=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  26. /**
  27. * vis.js module imports
  28. */
  29. // Try to load dependencies from the global window object.
  30. // If not available there, load via require.
  31. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment');
  32. var 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. * Compare two numbers and return the lowest, non-negative number.
  867. *
  868. * @param {number} number1
  869. * @param {number} number2
  870. * @returns {number} | number1 or number2, the lowest positive number. If both negative, return -1
  871. * @private
  872. */
  873. util._getLowestPositiveNumber = function(number1,number2) {
  874. if (number1 >= 0) {
  875. if (number2 >= 0) {
  876. return (number1 < number2) ? number1 : number2;
  877. }
  878. else {
  879. return number1;
  880. }
  881. }
  882. else {
  883. if (number2 >= 0) {
  884. return number2;
  885. }
  886. else {
  887. return -1;
  888. }
  889. }
  890. }
  891. /**
  892. * Event listener (singleton)
  893. */
  894. // TODO: replace usage of the event listener for the EventBus
  895. var events = {
  896. 'listeners': [],
  897. /**
  898. * Find a single listener by its object
  899. * @param {Object} object
  900. * @return {Number} index -1 when not found
  901. */
  902. 'indexOf': function (object) {
  903. var listeners = this.listeners;
  904. for (var i = 0, iMax = this.listeners.length; i < iMax; i++) {
  905. var listener = listeners[i];
  906. if (listener && listener.object == object) {
  907. return i;
  908. }
  909. }
  910. return -1;
  911. },
  912. /**
  913. * Add an event listener
  914. * @param {Object} object
  915. * @param {String} event The name of an event, for example 'select'
  916. * @param {function} callback The callback method, called when the
  917. * event takes place
  918. */
  919. 'addListener': function (object, event, callback) {
  920. var index = this.indexOf(object);
  921. var listener = this.listeners[index];
  922. if (!listener) {
  923. listener = {
  924. 'object': object,
  925. 'events': {}
  926. };
  927. this.listeners.push(listener);
  928. }
  929. var callbacks = listener.events[event];
  930. if (!callbacks) {
  931. callbacks = [];
  932. listener.events[event] = callbacks;
  933. }
  934. // add the callback if it does not yet exist
  935. if (callbacks.indexOf(callback) == -1) {
  936. callbacks.push(callback);
  937. }
  938. },
  939. /**
  940. * Remove an event listener
  941. * @param {Object} object
  942. * @param {String} event The name of an event, for example 'select'
  943. * @param {function} callback The registered callback method
  944. */
  945. 'removeListener': function (object, event, callback) {
  946. var index = this.indexOf(object);
  947. var listener = this.listeners[index];
  948. if (listener) {
  949. var callbacks = listener.events[event];
  950. if (callbacks) {
  951. index = callbacks.indexOf(callback);
  952. if (index != -1) {
  953. callbacks.splice(index, 1);
  954. }
  955. // remove the array when empty
  956. if (callbacks.length == 0) {
  957. delete listener.events[event];
  958. }
  959. }
  960. // count the number of registered events. remove listener when empty
  961. var count = 0;
  962. var events = listener.events;
  963. for (var e in events) {
  964. if (events.hasOwnProperty(e)) {
  965. count++;
  966. }
  967. }
  968. if (count == 0) {
  969. delete this.listeners[index];
  970. }
  971. }
  972. },
  973. /**
  974. * Remove all registered event listeners
  975. */
  976. 'removeAllListeners': function () {
  977. this.listeners = [];
  978. },
  979. /**
  980. * Trigger an event. All registered event handlers will be called
  981. * @param {Object} object
  982. * @param {String} event
  983. * @param {Object} properties (optional)
  984. */
  985. 'trigger': function (object, event, properties) {
  986. var index = this.indexOf(object);
  987. var listener = this.listeners[index];
  988. if (listener) {
  989. var callbacks = listener.events[event];
  990. if (callbacks) {
  991. for (var i = 0, iMax = callbacks.length; i < iMax; i++) {
  992. callbacks[i](properties);
  993. }
  994. }
  995. }
  996. }
  997. };
  998. /**
  999. * An event bus can be used to emit events, and to subscribe to events
  1000. * @constructor EventBus
  1001. */
  1002. function EventBus() {
  1003. this.subscriptions = [];
  1004. }
  1005. /**
  1006. * Subscribe to an event
  1007. * @param {String | RegExp} event The event can be a regular expression, or
  1008. * a string with wildcards, like 'server.*'.
  1009. * @param {function} callback. Callback are called with three parameters:
  1010. * {String} event, {*} [data], {*} [source]
  1011. * @param {*} [target]
  1012. * @returns {String} id A subscription id
  1013. */
  1014. EventBus.prototype.on = function (event, callback, target) {
  1015. var regexp = (event instanceof RegExp) ?
  1016. event :
  1017. new RegExp(event.replace('*', '\\w+'));
  1018. var subscription = {
  1019. id: util.randomUUID(),
  1020. event: event,
  1021. regexp: regexp,
  1022. callback: (typeof callback === 'function') ? callback : null,
  1023. target: target
  1024. };
  1025. this.subscriptions.push(subscription);
  1026. return subscription.id;
  1027. };
  1028. /**
  1029. * Unsubscribe from an event
  1030. * @param {String | Object} filter Filter for subscriptions to be removed
  1031. * Filter can be a string containing a
  1032. * subscription id, or an object containing
  1033. * one or more of the fields id, event,
  1034. * callback, and target.
  1035. */
  1036. EventBus.prototype.off = function (filter) {
  1037. var i = 0;
  1038. while (i < this.subscriptions.length) {
  1039. var subscription = this.subscriptions[i];
  1040. var match = true;
  1041. if (filter instanceof Object) {
  1042. // filter is an object. All fields must match
  1043. for (var prop in filter) {
  1044. if (filter.hasOwnProperty(prop)) {
  1045. if (filter[prop] !== subscription[prop]) {
  1046. match = false;
  1047. }
  1048. }
  1049. }
  1050. }
  1051. else {
  1052. // filter is a string, filter on id
  1053. match = (subscription.id == filter);
  1054. }
  1055. if (match) {
  1056. this.subscriptions.splice(i, 1);
  1057. }
  1058. else {
  1059. i++;
  1060. }
  1061. }
  1062. };
  1063. /**
  1064. * Emit an event
  1065. * @param {String} event
  1066. * @param {*} [data]
  1067. * @param {*} [source]
  1068. */
  1069. EventBus.prototype.emit = function (event, data, source) {
  1070. for (var i =0; i < this.subscriptions.length; i++) {
  1071. var subscription = this.subscriptions[i];
  1072. if (subscription.regexp.test(event)) {
  1073. if (subscription.callback) {
  1074. subscription.callback(event, data, source);
  1075. }
  1076. }
  1077. }
  1078. };
  1079. /**
  1080. * DataSet
  1081. *
  1082. * Usage:
  1083. * var dataSet = new DataSet({
  1084. * fieldId: '_id',
  1085. * convert: {
  1086. * // ...
  1087. * }
  1088. * });
  1089. *
  1090. * dataSet.add(item);
  1091. * dataSet.add(data);
  1092. * dataSet.update(item);
  1093. * dataSet.update(data);
  1094. * dataSet.remove(id);
  1095. * dataSet.remove(ids);
  1096. * var data = dataSet.get();
  1097. * var data = dataSet.get(id);
  1098. * var data = dataSet.get(ids);
  1099. * var data = dataSet.get(ids, options, data);
  1100. * dataSet.clear();
  1101. *
  1102. * A data set can:
  1103. * - add/remove/update data
  1104. * - gives triggers upon changes in the data
  1105. * - can import/export data in various data formats
  1106. *
  1107. * @param {Object} [options] Available options:
  1108. * {String} fieldId Field name of the id in the
  1109. * items, 'id' by default.
  1110. * {Object.<String, String} convert
  1111. * A map with field names as key,
  1112. * and the field type as value.
  1113. * @constructor DataSet
  1114. */
  1115. // TODO: add a DataSet constructor DataSet(data, options)
  1116. function DataSet (options) {
  1117. this.id = util.randomUUID();
  1118. this.options = options || {};
  1119. this.data = {}; // map with data indexed by id
  1120. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1121. this.convert = {}; // field types by field name
  1122. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1123. if (this.options.convert) {
  1124. for (var field in this.options.convert) {
  1125. if (this.options.convert.hasOwnProperty(field)) {
  1126. var value = this.options.convert[field];
  1127. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1128. this.convert[field] = 'Date';
  1129. }
  1130. else {
  1131. this.convert[field] = value;
  1132. }
  1133. }
  1134. }
  1135. }
  1136. // event subscribers
  1137. this.subscribers = {};
  1138. this.internalIds = {}; // internally generated id's
  1139. }
  1140. /**
  1141. * Subscribe to an event, add an event listener
  1142. * @param {String} event Event name. Available events: 'put', 'update',
  1143. * 'remove'
  1144. * @param {function} callback Callback method. Called with three parameters:
  1145. * {String} event
  1146. * {Object | null} params
  1147. * {String | Number} senderId
  1148. */
  1149. DataSet.prototype.subscribe = function (event, callback) {
  1150. var subscribers = this.subscribers[event];
  1151. if (!subscribers) {
  1152. subscribers = [];
  1153. this.subscribers[event] = subscribers;
  1154. }
  1155. subscribers.push({
  1156. callback: callback
  1157. });
  1158. };
  1159. /**
  1160. * Unsubscribe from an event, remove an event listener
  1161. * @param {String} event
  1162. * @param {function} callback
  1163. */
  1164. DataSet.prototype.unsubscribe = function (event, callback) {
  1165. var subscribers = this.subscribers[event];
  1166. if (subscribers) {
  1167. this.subscribers[event] = subscribers.filter(function (listener) {
  1168. return (listener.callback != callback);
  1169. });
  1170. }
  1171. };
  1172. /**
  1173. * Trigger an event
  1174. * @param {String} event
  1175. * @param {Object | null} params
  1176. * @param {String} [senderId] Optional id of the sender.
  1177. * @private
  1178. */
  1179. DataSet.prototype._trigger = function (event, params, senderId) {
  1180. if (event == '*') {
  1181. throw new Error('Cannot trigger event *');
  1182. }
  1183. var subscribers = [];
  1184. if (event in this.subscribers) {
  1185. subscribers = subscribers.concat(this.subscribers[event]);
  1186. }
  1187. if ('*' in this.subscribers) {
  1188. subscribers = subscribers.concat(this.subscribers['*']);
  1189. }
  1190. for (var i = 0; i < subscribers.length; i++) {
  1191. var subscriber = subscribers[i];
  1192. if (subscriber.callback) {
  1193. subscriber.callback(event, params, senderId || null);
  1194. }
  1195. }
  1196. };
  1197. /**
  1198. * Add data.
  1199. * Adding an item will fail when there already is an item with the same id.
  1200. * @param {Object | Array | DataTable} data
  1201. * @param {String} [senderId] Optional sender id
  1202. * @return {Array} addedIds Array with the ids of the added items
  1203. */
  1204. DataSet.prototype.add = function (data, senderId) {
  1205. var addedIds = [],
  1206. id,
  1207. me = this;
  1208. if (data instanceof Array) {
  1209. // Array
  1210. for (var i = 0, len = data.length; i < len; i++) {
  1211. id = me._addItem(data[i]);
  1212. addedIds.push(id);
  1213. }
  1214. }
  1215. else if (util.isDataTable(data)) {
  1216. // Google DataTable
  1217. var columns = this._getColumnNames(data);
  1218. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1219. var item = {};
  1220. for (var col = 0, cols = columns.length; col < cols; col++) {
  1221. var field = columns[col];
  1222. item[field] = data.getValue(row, col);
  1223. }
  1224. id = me._addItem(item);
  1225. addedIds.push(id);
  1226. }
  1227. }
  1228. else if (data instanceof Object) {
  1229. // Single item
  1230. id = me._addItem(data);
  1231. addedIds.push(id);
  1232. }
  1233. else {
  1234. throw new Error('Unknown dataType');
  1235. }
  1236. if (addedIds.length) {
  1237. this._trigger('add', {items: addedIds}, senderId);
  1238. }
  1239. return addedIds;
  1240. };
  1241. /**
  1242. * Update existing items. When an item does not exist, it will be created
  1243. * @param {Object | Array | DataTable} data
  1244. * @param {String} [senderId] Optional sender id
  1245. * @return {Array} updatedIds The ids of the added or updated items
  1246. */
  1247. DataSet.prototype.update = function (data, senderId) {
  1248. var addedIds = [],
  1249. updatedIds = [],
  1250. me = this,
  1251. fieldId = me.fieldId;
  1252. var addOrUpdate = function (item) {
  1253. var id = item[fieldId];
  1254. if (me.data[id]) {
  1255. // update item
  1256. id = me._updateItem(item);
  1257. updatedIds.push(id);
  1258. }
  1259. else {
  1260. // add new item
  1261. id = me._addItem(item);
  1262. addedIds.push(id);
  1263. }
  1264. };
  1265. if (data instanceof Array) {
  1266. // Array
  1267. for (var i = 0, len = data.length; i < len; i++) {
  1268. addOrUpdate(data[i]);
  1269. }
  1270. }
  1271. else if (util.isDataTable(data)) {
  1272. // Google DataTable
  1273. var columns = this._getColumnNames(data);
  1274. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1275. var item = {};
  1276. for (var col = 0, cols = columns.length; col < cols; col++) {
  1277. var field = columns[col];
  1278. item[field] = data.getValue(row, col);
  1279. }
  1280. addOrUpdate(item);
  1281. }
  1282. }
  1283. else if (data instanceof Object) {
  1284. // Single item
  1285. addOrUpdate(data);
  1286. }
  1287. else {
  1288. throw new Error('Unknown dataType');
  1289. }
  1290. if (addedIds.length) {
  1291. this._trigger('add', {items: addedIds}, senderId);
  1292. }
  1293. if (updatedIds.length) {
  1294. this._trigger('update', {items: updatedIds}, senderId);
  1295. }
  1296. return addedIds.concat(updatedIds);
  1297. };
  1298. /**
  1299. * Get a data item or multiple items.
  1300. *
  1301. * Usage:
  1302. *
  1303. * get()
  1304. * get(options: Object)
  1305. * get(options: Object, data: Array | DataTable)
  1306. *
  1307. * get(id: Number | String)
  1308. * get(id: Number | String, options: Object)
  1309. * get(id: Number | String, options: Object, data: Array | DataTable)
  1310. *
  1311. * get(ids: Number[] | String[])
  1312. * get(ids: Number[] | String[], options: Object)
  1313. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1314. *
  1315. * Where:
  1316. *
  1317. * {Number | String} id The id of an item
  1318. * {Number[] | String{}} ids An array with ids of items
  1319. * {Object} options An Object with options. Available options:
  1320. * {String} [type] Type of data to be returned. Can
  1321. * be 'DataTable' or 'Array' (default)
  1322. * {Object.<String, String>} [convert]
  1323. * {String[]} [fields] field names to be returned
  1324. * {function} [filter] filter items
  1325. * {String | function} [order] Order the items by
  1326. * a field name or custom sort function.
  1327. * {Array | DataTable} [data] If provided, items will be appended to this
  1328. * array or table. Required in case of Google
  1329. * DataTable.
  1330. *
  1331. * @throws Error
  1332. */
  1333. DataSet.prototype.get = function (args) {
  1334. var me = this;
  1335. var globalShowInternalIds = this.showInternalIds;
  1336. // parse the arguments
  1337. var id, ids, options, data;
  1338. var firstType = util.getType(arguments[0]);
  1339. if (firstType == 'String' || firstType == 'Number') {
  1340. // get(id [, options] [, data])
  1341. id = arguments[0];
  1342. options = arguments[1];
  1343. data = arguments[2];
  1344. }
  1345. else if (firstType == 'Array') {
  1346. // get(ids [, options] [, data])
  1347. ids = arguments[0];
  1348. options = arguments[1];
  1349. data = arguments[2];
  1350. }
  1351. else {
  1352. // get([, options] [, data])
  1353. options = arguments[0];
  1354. data = arguments[1];
  1355. }
  1356. // determine the return type
  1357. var type;
  1358. if (options && options.type) {
  1359. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1360. if (data && (type != util.getType(data))) {
  1361. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1362. 'does not correspond with specified options.type (' + options.type + ')');
  1363. }
  1364. if (type == 'DataTable' && !util.isDataTable(data)) {
  1365. throw new Error('Parameter "data" must be a DataTable ' +
  1366. 'when options.type is "DataTable"');
  1367. }
  1368. }
  1369. else if (data) {
  1370. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1371. }
  1372. else {
  1373. type = 'Array';
  1374. }
  1375. // we allow the setting of this value for a single get request.
  1376. if (options != undefined) {
  1377. if (options.showInternalIds != undefined) {
  1378. this.showInternalIds = options.showInternalIds;
  1379. }
  1380. }
  1381. // build options
  1382. var convert = options && options.convert || this.options.convert;
  1383. var filter = options && options.filter;
  1384. var items = [], item, itemId, i, len;
  1385. // convert items
  1386. if (id != undefined) {
  1387. // return a single item
  1388. item = me._getItem(id, convert);
  1389. if (filter && !filter(item)) {
  1390. item = null;
  1391. }
  1392. }
  1393. else if (ids != undefined) {
  1394. // return a subset of items
  1395. for (i = 0, len = ids.length; i < len; i++) {
  1396. item = me._getItem(ids[i], convert);
  1397. if (!filter || filter(item)) {
  1398. items.push(item);
  1399. }
  1400. }
  1401. }
  1402. else {
  1403. // return all items
  1404. for (itemId in this.data) {
  1405. if (this.data.hasOwnProperty(itemId)) {
  1406. item = me._getItem(itemId, convert);
  1407. if (!filter || filter(item)) {
  1408. items.push(item);
  1409. }
  1410. }
  1411. }
  1412. }
  1413. // restore the global value of showInternalIds
  1414. this.showInternalIds = globalShowInternalIds;
  1415. // order the results
  1416. if (options && options.order && id == undefined) {
  1417. this._sort(items, options.order);
  1418. }
  1419. // filter fields of the items
  1420. if (options && options.fields) {
  1421. var fields = options.fields;
  1422. if (id != undefined) {
  1423. item = this._filterFields(item, fields);
  1424. }
  1425. else {
  1426. for (i = 0, len = items.length; i < len; i++) {
  1427. items[i] = this._filterFields(items[i], fields);
  1428. }
  1429. }
  1430. }
  1431. // return the results
  1432. if (type == 'DataTable') {
  1433. var columns = this._getColumnNames(data);
  1434. if (id != undefined) {
  1435. // append a single item to the data table
  1436. me._appendRow(data, columns, item);
  1437. }
  1438. else {
  1439. // copy the items to the provided data table
  1440. for (i = 0, len = items.length; i < len; i++) {
  1441. me._appendRow(data, columns, items[i]);
  1442. }
  1443. }
  1444. return data;
  1445. }
  1446. else {
  1447. // return an array
  1448. if (id != undefined) {
  1449. // a single item
  1450. return item;
  1451. }
  1452. else {
  1453. // multiple items
  1454. if (data) {
  1455. // copy the items to the provided array
  1456. for (i = 0, len = items.length; i < len; i++) {
  1457. data.push(items[i]);
  1458. }
  1459. return data;
  1460. }
  1461. else {
  1462. // just return our array
  1463. return items;
  1464. }
  1465. }
  1466. }
  1467. };
  1468. /**
  1469. * Get ids of all items or from a filtered set of items.
  1470. * @param {Object} [options] An Object with options. Available options:
  1471. * {function} [filter] filter items
  1472. * {String | function} [order] Order the items by
  1473. * a field name or custom sort function.
  1474. * @return {Array} ids
  1475. */
  1476. DataSet.prototype.getIds = function (options) {
  1477. var data = this.data,
  1478. filter = options && options.filter,
  1479. order = options && options.order,
  1480. convert = options && options.convert || this.options.convert,
  1481. i,
  1482. len,
  1483. id,
  1484. item,
  1485. items,
  1486. ids = [];
  1487. if (filter) {
  1488. // get filtered items
  1489. if (order) {
  1490. // create ordered list
  1491. items = [];
  1492. for (id in data) {
  1493. if (data.hasOwnProperty(id)) {
  1494. item = this._getItem(id, convert);
  1495. if (filter(item)) {
  1496. items.push(item);
  1497. }
  1498. }
  1499. }
  1500. this._sort(items, order);
  1501. for (i = 0, len = items.length; i < len; i++) {
  1502. ids[i] = items[i][this.fieldId];
  1503. }
  1504. }
  1505. else {
  1506. // create unordered list
  1507. for (id in data) {
  1508. if (data.hasOwnProperty(id)) {
  1509. item = this._getItem(id, convert);
  1510. if (filter(item)) {
  1511. ids.push(item[this.fieldId]);
  1512. }
  1513. }
  1514. }
  1515. }
  1516. }
  1517. else {
  1518. // get all items
  1519. if (order) {
  1520. // create an ordered list
  1521. items = [];
  1522. for (id in data) {
  1523. if (data.hasOwnProperty(id)) {
  1524. items.push(data[id]);
  1525. }
  1526. }
  1527. this._sort(items, order);
  1528. for (i = 0, len = items.length; i < len; i++) {
  1529. ids[i] = items[i][this.fieldId];
  1530. }
  1531. }
  1532. else {
  1533. // create unordered list
  1534. for (id in data) {
  1535. if (data.hasOwnProperty(id)) {
  1536. item = data[id];
  1537. ids.push(item[this.fieldId]);
  1538. }
  1539. }
  1540. }
  1541. }
  1542. return ids;
  1543. };
  1544. /**
  1545. * Execute a callback function for every item in the dataset.
  1546. * The order of the items is not determined.
  1547. * @param {function} callback
  1548. * @param {Object} [options] Available options:
  1549. * {Object.<String, String>} [convert]
  1550. * {String[]} [fields] filter fields
  1551. * {function} [filter] filter items
  1552. * {String | function} [order] Order the items by
  1553. * a field name or custom sort function.
  1554. */
  1555. DataSet.prototype.forEach = function (callback, options) {
  1556. var filter = options && options.filter,
  1557. convert = options && options.convert || this.options.convert,
  1558. data = this.data,
  1559. item,
  1560. id;
  1561. if (options && options.order) {
  1562. // execute forEach on ordered list
  1563. var items = this.get(options);
  1564. for (var i = 0, len = items.length; i < len; i++) {
  1565. item = items[i];
  1566. id = item[this.fieldId];
  1567. callback(item, id);
  1568. }
  1569. }
  1570. else {
  1571. // unordered
  1572. for (id in data) {
  1573. if (data.hasOwnProperty(id)) {
  1574. item = this._getItem(id, convert);
  1575. if (!filter || filter(item)) {
  1576. callback(item, id);
  1577. }
  1578. }
  1579. }
  1580. }
  1581. };
  1582. /**
  1583. * Map every item in the dataset.
  1584. * @param {function} callback
  1585. * @param {Object} [options] Available options:
  1586. * {Object.<String, String>} [convert]
  1587. * {String[]} [fields] filter fields
  1588. * {function} [filter] filter items
  1589. * {String | function} [order] Order the items by
  1590. * a field name or custom sort function.
  1591. * @return {Object[]} mappedItems
  1592. */
  1593. DataSet.prototype.map = function (callback, options) {
  1594. var filter = options && options.filter,
  1595. convert = options && options.convert || this.options.convert,
  1596. mappedItems = [],
  1597. data = this.data,
  1598. item;
  1599. // convert and filter items
  1600. for (var id in data) {
  1601. if (data.hasOwnProperty(id)) {
  1602. item = this._getItem(id, convert);
  1603. if (!filter || filter(item)) {
  1604. mappedItems.push(callback(item, id));
  1605. }
  1606. }
  1607. }
  1608. // order items
  1609. if (options && options.order) {
  1610. this._sort(mappedItems, options.order);
  1611. }
  1612. return mappedItems;
  1613. };
  1614. /**
  1615. * Filter the fields of an item
  1616. * @param {Object} item
  1617. * @param {String[]} fields Field names
  1618. * @return {Object} filteredItem
  1619. * @private
  1620. */
  1621. DataSet.prototype._filterFields = function (item, fields) {
  1622. var filteredItem = {};
  1623. for (var field in item) {
  1624. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1625. filteredItem[field] = item[field];
  1626. }
  1627. }
  1628. return filteredItem;
  1629. };
  1630. /**
  1631. * Sort the provided array with items
  1632. * @param {Object[]} items
  1633. * @param {String | function} order A field name or custom sort function.
  1634. * @private
  1635. */
  1636. DataSet.prototype._sort = function (items, order) {
  1637. if (util.isString(order)) {
  1638. // order by provided field name
  1639. var name = order; // field name
  1640. items.sort(function (a, b) {
  1641. var av = a[name];
  1642. var bv = b[name];
  1643. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1644. });
  1645. }
  1646. else if (typeof order === 'function') {
  1647. // order by sort function
  1648. items.sort(order);
  1649. }
  1650. // TODO: extend order by an Object {field:String, direction:String}
  1651. // where direction can be 'asc' or 'desc'
  1652. else {
  1653. throw new TypeError('Order must be a function or a string');
  1654. }
  1655. };
  1656. /**
  1657. * Remove an object by pointer or by id
  1658. * @param {String | Number | Object | Array} id Object or id, or an array with
  1659. * objects or ids to be removed
  1660. * @param {String} [senderId] Optional sender id
  1661. * @return {Array} removedIds
  1662. */
  1663. DataSet.prototype.remove = function (id, senderId) {
  1664. var removedIds = [],
  1665. i, len, removedId;
  1666. if (id instanceof Array) {
  1667. for (i = 0, len = id.length; i < len; i++) {
  1668. removedId = this._remove(id[i]);
  1669. if (removedId != null) {
  1670. removedIds.push(removedId);
  1671. }
  1672. }
  1673. }
  1674. else {
  1675. removedId = this._remove(id);
  1676. if (removedId != null) {
  1677. removedIds.push(removedId);
  1678. }
  1679. }
  1680. if (removedIds.length) {
  1681. this._trigger('remove', {items: removedIds}, senderId);
  1682. }
  1683. return removedIds;
  1684. };
  1685. /**
  1686. * Remove an item by its id
  1687. * @param {Number | String | Object} id id or item
  1688. * @returns {Number | String | null} id
  1689. * @private
  1690. */
  1691. DataSet.prototype._remove = function (id) {
  1692. if (util.isNumber(id) || util.isString(id)) {
  1693. if (this.data[id]) {
  1694. delete this.data[id];
  1695. delete this.internalIds[id];
  1696. return id;
  1697. }
  1698. }
  1699. else if (id instanceof Object) {
  1700. var itemId = id[this.fieldId];
  1701. if (itemId && this.data[itemId]) {
  1702. delete this.data[itemId];
  1703. delete this.internalIds[itemId];
  1704. return itemId;
  1705. }
  1706. }
  1707. return null;
  1708. };
  1709. /**
  1710. * Clear the data
  1711. * @param {String} [senderId] Optional sender id
  1712. * @return {Array} removedIds The ids of all removed items
  1713. */
  1714. DataSet.prototype.clear = function (senderId) {
  1715. var ids = Object.keys(this.data);
  1716. this.data = {};
  1717. this.internalIds = {};
  1718. this._trigger('remove', {items: ids}, senderId);
  1719. return ids;
  1720. };
  1721. /**
  1722. * Find the item with maximum value of a specified field
  1723. * @param {String} field
  1724. * @return {Object | null} item Item containing max value, or null if no items
  1725. */
  1726. DataSet.prototype.max = function (field) {
  1727. var data = this.data,
  1728. max = null,
  1729. maxField = null;
  1730. for (var id in data) {
  1731. if (data.hasOwnProperty(id)) {
  1732. var item = data[id];
  1733. var itemField = item[field];
  1734. if (itemField != null && (!max || itemField > maxField)) {
  1735. max = item;
  1736. maxField = itemField;
  1737. }
  1738. }
  1739. }
  1740. return max;
  1741. };
  1742. /**
  1743. * Find the item with minimum value of a specified field
  1744. * @param {String} field
  1745. * @return {Object | null} item Item containing max value, or null if no items
  1746. */
  1747. DataSet.prototype.min = function (field) {
  1748. var data = this.data,
  1749. min = null,
  1750. minField = null;
  1751. for (var id in data) {
  1752. if (data.hasOwnProperty(id)) {
  1753. var item = data[id];
  1754. var itemField = item[field];
  1755. if (itemField != null && (!min || itemField < minField)) {
  1756. min = item;
  1757. minField = itemField;
  1758. }
  1759. }
  1760. }
  1761. return min;
  1762. };
  1763. /**
  1764. * Find all distinct values of a specified field
  1765. * @param {String} field
  1766. * @return {Array} values Array containing all distinct values. If the data
  1767. * items do not contain the specified field, an array
  1768. * containing a single value undefined is returned.
  1769. * The returned array is unordered.
  1770. */
  1771. DataSet.prototype.distinct = function (field) {
  1772. var data = this.data,
  1773. values = [],
  1774. fieldType = this.options.convert[field],
  1775. count = 0;
  1776. for (var prop in data) {
  1777. if (data.hasOwnProperty(prop)) {
  1778. var item = data[prop];
  1779. var value = util.convert(item[field], fieldType);
  1780. var exists = false;
  1781. for (var i = 0; i < count; i++) {
  1782. if (values[i] == value) {
  1783. exists = true;
  1784. break;
  1785. }
  1786. }
  1787. if (!exists) {
  1788. values[count] = value;
  1789. count++;
  1790. }
  1791. }
  1792. }
  1793. return values;
  1794. };
  1795. /**
  1796. * Add a single item. Will fail when an item with the same id already exists.
  1797. * @param {Object} item
  1798. * @return {String} id
  1799. * @private
  1800. */
  1801. DataSet.prototype._addItem = function (item) {
  1802. var id = item[this.fieldId];
  1803. if (id != undefined) {
  1804. // check whether this id is already taken
  1805. if (this.data[id]) {
  1806. // item already exists
  1807. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1808. }
  1809. }
  1810. else {
  1811. // generate an id
  1812. id = util.randomUUID();
  1813. item[this.fieldId] = id;
  1814. this.internalIds[id] = item;
  1815. }
  1816. var d = {};
  1817. for (var field in item) {
  1818. if (item.hasOwnProperty(field)) {
  1819. var fieldType = this.convert[field]; // type may be undefined
  1820. d[field] = util.convert(item[field], fieldType);
  1821. }
  1822. }
  1823. this.data[id] = d;
  1824. return id;
  1825. };
  1826. /**
  1827. * Get an item. Fields can be converted to a specific type
  1828. * @param {String} id
  1829. * @param {Object.<String, String>} [convert] field types to convert
  1830. * @return {Object | null} item
  1831. * @private
  1832. */
  1833. DataSet.prototype._getItem = function (id, convert) {
  1834. var field, value;
  1835. // get the item from the dataset
  1836. var raw = this.data[id];
  1837. if (!raw) {
  1838. return null;
  1839. }
  1840. // convert the items field types
  1841. var converted = {},
  1842. fieldId = this.fieldId,
  1843. internalIds = this.internalIds;
  1844. if (convert) {
  1845. for (field in raw) {
  1846. if (raw.hasOwnProperty(field)) {
  1847. value = raw[field];
  1848. // output all fields, except internal ids
  1849. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1850. converted[field] = util.convert(value, convert[field]);
  1851. }
  1852. }
  1853. }
  1854. }
  1855. else {
  1856. // no field types specified, no converting needed
  1857. for (field in raw) {
  1858. if (raw.hasOwnProperty(field)) {
  1859. value = raw[field];
  1860. // output all fields, except internal ids
  1861. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1862. converted[field] = value;
  1863. }
  1864. }
  1865. }
  1866. }
  1867. return converted;
  1868. };
  1869. /**
  1870. * Update a single item: merge with existing item.
  1871. * Will fail when the item has no id, or when there does not exist an item
  1872. * with the same id.
  1873. * @param {Object} item
  1874. * @return {String} id
  1875. * @private
  1876. */
  1877. DataSet.prototype._updateItem = function (item) {
  1878. var id = item[this.fieldId];
  1879. if (id == undefined) {
  1880. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1881. }
  1882. var d = this.data[id];
  1883. if (!d) {
  1884. // item doesn't exist
  1885. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1886. }
  1887. // merge with current item
  1888. for (var field in item) {
  1889. if (item.hasOwnProperty(field)) {
  1890. var fieldType = this.convert[field]; // type may be undefined
  1891. d[field] = util.convert(item[field], fieldType);
  1892. }
  1893. }
  1894. return id;
  1895. };
  1896. /**
  1897. * check if an id is an internal or external id
  1898. * @param id
  1899. * @returns {boolean}
  1900. * @private
  1901. */
  1902. DataSet.prototype.isInternalId = function(id) {
  1903. return (id in this.internalIds);
  1904. };
  1905. /**
  1906. * Get an array with the column names of a Google DataTable
  1907. * @param {DataTable} dataTable
  1908. * @return {String[]} columnNames
  1909. * @private
  1910. */
  1911. DataSet.prototype._getColumnNames = function (dataTable) {
  1912. var columns = [];
  1913. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1914. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1915. }
  1916. return columns;
  1917. };
  1918. /**
  1919. * Append an item as a row to the dataTable
  1920. * @param dataTable
  1921. * @param columns
  1922. * @param item
  1923. * @private
  1924. */
  1925. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1926. var row = dataTable.addRow();
  1927. for (var col = 0, cols = columns.length; col < cols; col++) {
  1928. var field = columns[col];
  1929. dataTable.setValue(row, col, item[field]);
  1930. }
  1931. };
  1932. /**
  1933. * DataView
  1934. *
  1935. * a dataview offers a filtered view on a dataset or an other dataview.
  1936. *
  1937. * @param {DataSet | DataView} data
  1938. * @param {Object} [options] Available options: see method get
  1939. *
  1940. * @constructor DataView
  1941. */
  1942. function DataView (data, options) {
  1943. this.id = util.randomUUID();
  1944. this.data = null;
  1945. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1946. this.options = options || {};
  1947. this.fieldId = 'id'; // name of the field containing id
  1948. this.subscribers = {}; // event subscribers
  1949. var me = this;
  1950. this.listener = function () {
  1951. me._onEvent.apply(me, arguments);
  1952. };
  1953. this.setData(data);
  1954. }
  1955. // TODO: implement a function .config() to dynamically update things like configured filter
  1956. // and trigger changes accordingly
  1957. /**
  1958. * Set a data source for the view
  1959. * @param {DataSet | DataView} data
  1960. */
  1961. DataView.prototype.setData = function (data) {
  1962. var ids, dataItems, i, len;
  1963. if (this.data) {
  1964. // unsubscribe from current dataset
  1965. if (this.data.unsubscribe) {
  1966. this.data.unsubscribe('*', this.listener);
  1967. }
  1968. // trigger a remove of all items in memory
  1969. ids = [];
  1970. for (var id in this.ids) {
  1971. if (this.ids.hasOwnProperty(id)) {
  1972. ids.push(id);
  1973. }
  1974. }
  1975. this.ids = {};
  1976. this._trigger('remove', {items: ids});
  1977. }
  1978. this.data = data;
  1979. if (this.data) {
  1980. // update fieldId
  1981. this.fieldId = this.options.fieldId ||
  1982. (this.data && this.data.options && this.data.options.fieldId) ||
  1983. 'id';
  1984. // trigger an add of all added items
  1985. ids = this.data.getIds({filter: this.options && this.options.filter});
  1986. for (i = 0, len = ids.length; i < len; i++) {
  1987. id = ids[i];
  1988. this.ids[id] = true;
  1989. }
  1990. this._trigger('add', {items: ids});
  1991. // subscribe to new dataset
  1992. if (this.data.subscribe) {
  1993. this.data.subscribe('*', this.listener);
  1994. }
  1995. }
  1996. };
  1997. /**
  1998. * Get data from the data view
  1999. *
  2000. * Usage:
  2001. *
  2002. * get()
  2003. * get(options: Object)
  2004. * get(options: Object, data: Array | DataTable)
  2005. *
  2006. * get(id: Number)
  2007. * get(id: Number, options: Object)
  2008. * get(id: Number, options: Object, data: Array | DataTable)
  2009. *
  2010. * get(ids: Number[])
  2011. * get(ids: Number[], options: Object)
  2012. * get(ids: Number[], options: Object, data: Array | DataTable)
  2013. *
  2014. * Where:
  2015. *
  2016. * {Number | String} id The id of an item
  2017. * {Number[] | String{}} ids An array with ids of items
  2018. * {Object} options An Object with options. Available options:
  2019. * {String} [type] Type of data to be returned. Can
  2020. * be 'DataTable' or 'Array' (default)
  2021. * {Object.<String, String>} [convert]
  2022. * {String[]} [fields] field names to be returned
  2023. * {function} [filter] filter items
  2024. * {String | function} [order] Order the items by
  2025. * a field name or custom sort function.
  2026. * {Array | DataTable} [data] If provided, items will be appended to this
  2027. * array or table. Required in case of Google
  2028. * DataTable.
  2029. * @param args
  2030. */
  2031. DataView.prototype.get = function (args) {
  2032. var me = this;
  2033. // parse the arguments
  2034. var ids, options, data;
  2035. var firstType = util.getType(arguments[0]);
  2036. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2037. // get(id(s) [, options] [, data])
  2038. ids = arguments[0]; // can be a single id or an array with ids
  2039. options = arguments[1];
  2040. data = arguments[2];
  2041. }
  2042. else {
  2043. // get([, options] [, data])
  2044. options = arguments[0];
  2045. data = arguments[1];
  2046. }
  2047. // extend the options with the default options and provided options
  2048. var viewOptions = util.extend({}, this.options, options);
  2049. // create a combined filter method when needed
  2050. if (this.options.filter && options && options.filter) {
  2051. viewOptions.filter = function (item) {
  2052. return me.options.filter(item) && options.filter(item);
  2053. }
  2054. }
  2055. // build up the call to the linked data set
  2056. var getArguments = [];
  2057. if (ids != undefined) {
  2058. getArguments.push(ids);
  2059. }
  2060. getArguments.push(viewOptions);
  2061. getArguments.push(data);
  2062. return this.data && this.data.get.apply(this.data, getArguments);
  2063. };
  2064. /**
  2065. * Get ids of all items or from a filtered set of items.
  2066. * @param {Object} [options] An Object with options. Available options:
  2067. * {function} [filter] filter items
  2068. * {String | function} [order] Order the items by
  2069. * a field name or custom sort function.
  2070. * @return {Array} ids
  2071. */
  2072. DataView.prototype.getIds = function (options) {
  2073. var ids;
  2074. if (this.data) {
  2075. var defaultFilter = this.options.filter;
  2076. var filter;
  2077. if (options && options.filter) {
  2078. if (defaultFilter) {
  2079. filter = function (item) {
  2080. return defaultFilter(item) && options.filter(item);
  2081. }
  2082. }
  2083. else {
  2084. filter = options.filter;
  2085. }
  2086. }
  2087. else {
  2088. filter = defaultFilter;
  2089. }
  2090. ids = this.data.getIds({
  2091. filter: filter,
  2092. order: options && options.order
  2093. });
  2094. }
  2095. else {
  2096. ids = [];
  2097. }
  2098. return ids;
  2099. };
  2100. /**
  2101. * Event listener. Will propagate all events from the connected data set to
  2102. * the subscribers of the DataView, but will filter the items and only trigger
  2103. * when there are changes in the filtered data set.
  2104. * @param {String} event
  2105. * @param {Object | null} params
  2106. * @param {String} senderId
  2107. * @private
  2108. */
  2109. DataView.prototype._onEvent = function (event, params, senderId) {
  2110. var i, len, id, item,
  2111. ids = params && params.items,
  2112. data = this.data,
  2113. added = [],
  2114. updated = [],
  2115. removed = [];
  2116. if (ids && data) {
  2117. switch (event) {
  2118. case 'add':
  2119. // filter the ids of the added items
  2120. for (i = 0, len = ids.length; i < len; i++) {
  2121. id = ids[i];
  2122. item = this.get(id);
  2123. if (item) {
  2124. this.ids[id] = true;
  2125. added.push(id);
  2126. }
  2127. }
  2128. break;
  2129. case 'update':
  2130. // determine the event from the views viewpoint: an updated
  2131. // item can be added, updated, or removed from this view.
  2132. for (i = 0, len = ids.length; i < len; i++) {
  2133. id = ids[i];
  2134. item = this.get(id);
  2135. if (item) {
  2136. if (this.ids[id]) {
  2137. updated.push(id);
  2138. }
  2139. else {
  2140. this.ids[id] = true;
  2141. added.push(id);
  2142. }
  2143. }
  2144. else {
  2145. if (this.ids[id]) {
  2146. delete this.ids[id];
  2147. removed.push(id);
  2148. }
  2149. else {
  2150. // nothing interesting for me :-(
  2151. }
  2152. }
  2153. }
  2154. break;
  2155. case 'remove':
  2156. // filter the ids of the removed items
  2157. for (i = 0, len = ids.length; i < len; i++) {
  2158. id = ids[i];
  2159. if (this.ids[id]) {
  2160. delete this.ids[id];
  2161. removed.push(id);
  2162. }
  2163. }
  2164. break;
  2165. }
  2166. if (added.length) {
  2167. this._trigger('add', {items: added}, senderId);
  2168. }
  2169. if (updated.length) {
  2170. this._trigger('update', {items: updated}, senderId);
  2171. }
  2172. if (removed.length) {
  2173. this._trigger('remove', {items: removed}, senderId);
  2174. }
  2175. }
  2176. };
  2177. // copy subscription functionality from DataSet
  2178. DataView.prototype.subscribe = DataSet.prototype.subscribe;
  2179. DataView.prototype.unsubscribe = DataSet.prototype.unsubscribe;
  2180. DataView.prototype._trigger = DataSet.prototype._trigger;
  2181. /**
  2182. * @constructor TimeStep
  2183. * The class TimeStep is an iterator for dates. You provide a start date and an
  2184. * end date. The class itself determines the best scale (step size) based on the
  2185. * provided start Date, end Date, and minimumStep.
  2186. *
  2187. * If minimumStep is provided, the step size is chosen as close as possible
  2188. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2189. * provided, the scale is set to 1 DAY.
  2190. * The minimumStep should correspond with the onscreen size of about 6 characters
  2191. *
  2192. * Alternatively, you can set a scale by hand.
  2193. * After creation, you can initialize the class by executing first(). Then you
  2194. * can iterate from the start date to the end date via next(). You can check if
  2195. * the end date is reached with the function hasNext(). After each step, you can
  2196. * retrieve the current date via getCurrent().
  2197. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2198. * days, to years.
  2199. *
  2200. * Version: 1.2
  2201. *
  2202. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2203. * or new Date(2010, 9, 21, 23, 45, 00)
  2204. * @param {Date} [end] The end date
  2205. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2206. */
  2207. TimeStep = function(start, end, minimumStep) {
  2208. // variables
  2209. this.current = new Date();
  2210. this._start = new Date();
  2211. this._end = new Date();
  2212. this.autoScale = true;
  2213. this.scale = TimeStep.SCALE.DAY;
  2214. this.step = 1;
  2215. // initialize the range
  2216. this.setRange(start, end, minimumStep);
  2217. };
  2218. /// enum scale
  2219. TimeStep.SCALE = {
  2220. MILLISECOND: 1,
  2221. SECOND: 2,
  2222. MINUTE: 3,
  2223. HOUR: 4,
  2224. DAY: 5,
  2225. WEEKDAY: 6,
  2226. MONTH: 7,
  2227. YEAR: 8
  2228. };
  2229. /**
  2230. * Set a new range
  2231. * If minimumStep is provided, the step size is chosen as close as possible
  2232. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2233. * provided, the scale is set to 1 DAY.
  2234. * The minimumStep should correspond with the onscreen size of about 6 characters
  2235. * @param {Date} [start] The start date and time.
  2236. * @param {Date} [end] The end date and time.
  2237. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2238. */
  2239. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2240. if (!(start instanceof Date) || !(end instanceof Date)) {
  2241. throw "No legal start or end date in method setRange";
  2242. }
  2243. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2244. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2245. if (this.autoScale) {
  2246. this.setMinimumStep(minimumStep);
  2247. }
  2248. };
  2249. /**
  2250. * Set the range iterator to the start date.
  2251. */
  2252. TimeStep.prototype.first = function() {
  2253. this.current = new Date(this._start.valueOf());
  2254. this.roundToMinor();
  2255. };
  2256. /**
  2257. * Round the current date to the first minor date value
  2258. * This must be executed once when the current date is set to start Date
  2259. */
  2260. TimeStep.prototype.roundToMinor = function() {
  2261. // round to floor
  2262. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2263. //noinspection FallthroughInSwitchStatementJS
  2264. switch (this.scale) {
  2265. case TimeStep.SCALE.YEAR:
  2266. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2267. this.current.setMonth(0);
  2268. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2269. case TimeStep.SCALE.DAY: // intentional fall through
  2270. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2271. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2272. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2273. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2274. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2275. }
  2276. if (this.step != 1) {
  2277. // round down to the first minor value that is a multiple of the current step size
  2278. switch (this.scale) {
  2279. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2280. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2281. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2282. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2283. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2284. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2285. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2286. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2287. default: break;
  2288. }
  2289. }
  2290. };
  2291. /**
  2292. * Check if the there is a next step
  2293. * @return {boolean} true if the current date has not passed the end date
  2294. */
  2295. TimeStep.prototype.hasNext = function () {
  2296. return (this.current.valueOf() <= this._end.valueOf());
  2297. };
  2298. /**
  2299. * Do the next step
  2300. */
  2301. TimeStep.prototype.next = function() {
  2302. var prev = this.current.valueOf();
  2303. // Two cases, needed to prevent issues with switching daylight savings
  2304. // (end of March and end of October)
  2305. if (this.current.getMonth() < 6) {
  2306. switch (this.scale) {
  2307. case TimeStep.SCALE.MILLISECOND:
  2308. this.current = new Date(this.current.valueOf() + this.step); break;
  2309. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2310. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2311. case TimeStep.SCALE.HOUR:
  2312. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2313. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2314. var h = this.current.getHours();
  2315. this.current.setHours(h - (h % this.step));
  2316. break;
  2317. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2318. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2319. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2320. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2321. default: break;
  2322. }
  2323. }
  2324. else {
  2325. switch (this.scale) {
  2326. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2327. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2328. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2329. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2330. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2331. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2332. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2333. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2334. default: break;
  2335. }
  2336. }
  2337. if (this.step != 1) {
  2338. // round down to the correct major value
  2339. switch (this.scale) {
  2340. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2341. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2342. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2343. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2344. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2345. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2346. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2347. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2348. default: break;
  2349. }
  2350. }
  2351. // safety mechanism: if current time is still unchanged, move to the end
  2352. if (this.current.valueOf() == prev) {
  2353. this.current = new Date(this._end.valueOf());
  2354. }
  2355. };
  2356. /**
  2357. * Get the current datetime
  2358. * @return {Date} current The current date
  2359. */
  2360. TimeStep.prototype.getCurrent = function() {
  2361. return this.current;
  2362. };
  2363. /**
  2364. * Set a custom scale. Autoscaling will be disabled.
  2365. * For example setScale(SCALE.MINUTES, 5) will result
  2366. * in minor steps of 5 minutes, and major steps of an hour.
  2367. *
  2368. * @param {TimeStep.SCALE} newScale
  2369. * A scale. Choose from SCALE.MILLISECOND,
  2370. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2371. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2372. * SCALE.YEAR.
  2373. * @param {Number} newStep A step size, by default 1. Choose for
  2374. * example 1, 2, 5, or 10.
  2375. */
  2376. TimeStep.prototype.setScale = function(newScale, newStep) {
  2377. this.scale = newScale;
  2378. if (newStep > 0) {
  2379. this.step = newStep;
  2380. }
  2381. this.autoScale = false;
  2382. };
  2383. /**
  2384. * Enable or disable autoscaling
  2385. * @param {boolean} enable If true, autoascaling is set true
  2386. */
  2387. TimeStep.prototype.setAutoScale = function (enable) {
  2388. this.autoScale = enable;
  2389. };
  2390. /**
  2391. * Automatically determine the scale that bests fits the provided minimum step
  2392. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2393. */
  2394. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2395. if (minimumStep == undefined) {
  2396. return;
  2397. }
  2398. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2399. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2400. var stepDay = (1000 * 60 * 60 * 24);
  2401. var stepHour = (1000 * 60 * 60);
  2402. var stepMinute = (1000 * 60);
  2403. var stepSecond = (1000);
  2404. var stepMillisecond= (1);
  2405. // find the smallest step that is larger than the provided minimumStep
  2406. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2407. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2408. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2409. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2410. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2411. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2412. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2413. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2414. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2415. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2416. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2417. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2418. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2419. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2420. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2421. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2422. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2423. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2424. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2425. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2426. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2427. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2428. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2429. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2430. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2431. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2432. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2433. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2434. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2435. };
  2436. /**
  2437. * Snap a date to a rounded value. The snap intervals are dependent on the
  2438. * current scale and step.
  2439. * @param {Date} date the date to be snapped
  2440. */
  2441. TimeStep.prototype.snap = function(date) {
  2442. if (this.scale == TimeStep.SCALE.YEAR) {
  2443. var year = date.getFullYear() + Math.round(date.getMonth() / 12);
  2444. date.setFullYear(Math.round(year / this.step) * this.step);
  2445. date.setMonth(0);
  2446. date.setDate(0);
  2447. date.setHours(0);
  2448. date.setMinutes(0);
  2449. date.setSeconds(0);
  2450. date.setMilliseconds(0);
  2451. }
  2452. else if (this.scale == TimeStep.SCALE.MONTH) {
  2453. if (date.getDate() > 15) {
  2454. date.setDate(1);
  2455. date.setMonth(date.getMonth() + 1);
  2456. // important: first set Date to 1, after that change the month.
  2457. }
  2458. else {
  2459. date.setDate(1);
  2460. }
  2461. date.setHours(0);
  2462. date.setMinutes(0);
  2463. date.setSeconds(0);
  2464. date.setMilliseconds(0);
  2465. }
  2466. else if (this.scale == TimeStep.SCALE.DAY ||
  2467. this.scale == TimeStep.SCALE.WEEKDAY) {
  2468. //noinspection FallthroughInSwitchStatementJS
  2469. switch (this.step) {
  2470. case 5:
  2471. case 2:
  2472. date.setHours(Math.round(date.getHours() / 24) * 24); break;
  2473. default:
  2474. date.setHours(Math.round(date.getHours() / 12) * 12); break;
  2475. }
  2476. date.setMinutes(0);
  2477. date.setSeconds(0);
  2478. date.setMilliseconds(0);
  2479. }
  2480. else if (this.scale == TimeStep.SCALE.HOUR) {
  2481. switch (this.step) {
  2482. case 4:
  2483. date.setMinutes(Math.round(date.getMinutes() / 60) * 60); break;
  2484. default:
  2485. date.setMinutes(Math.round(date.getMinutes() / 30) * 30); break;
  2486. }
  2487. date.setSeconds(0);
  2488. date.setMilliseconds(0);
  2489. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2490. //noinspection FallthroughInSwitchStatementJS
  2491. switch (this.step) {
  2492. case 15:
  2493. case 10:
  2494. date.setMinutes(Math.round(date.getMinutes() / 5) * 5);
  2495. date.setSeconds(0);
  2496. break;
  2497. case 5:
  2498. date.setSeconds(Math.round(date.getSeconds() / 60) * 60); break;
  2499. default:
  2500. date.setSeconds(Math.round(date.getSeconds() / 30) * 30); break;
  2501. }
  2502. date.setMilliseconds(0);
  2503. }
  2504. else if (this.scale == TimeStep.SCALE.SECOND) {
  2505. //noinspection FallthroughInSwitchStatementJS
  2506. switch (this.step) {
  2507. case 15:
  2508. case 10:
  2509. date.setSeconds(Math.round(date.getSeconds() / 5) * 5);
  2510. date.setMilliseconds(0);
  2511. break;
  2512. case 5:
  2513. date.setMilliseconds(Math.round(date.getMilliseconds() / 1000) * 1000); break;
  2514. default:
  2515. date.setMilliseconds(Math.round(date.getMilliseconds() / 500) * 500); break;
  2516. }
  2517. }
  2518. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2519. var step = this.step > 5 ? this.step / 2 : 1;
  2520. date.setMilliseconds(Math.round(date.getMilliseconds() / step) * step);
  2521. }
  2522. };
  2523. /**
  2524. * Check if the current value is a major value (for example when the step
  2525. * is DAY, a major value is each first day of the MONTH)
  2526. * @return {boolean} true if current date is major, else false.
  2527. */
  2528. TimeStep.prototype.isMajor = function() {
  2529. switch (this.scale) {
  2530. case TimeStep.SCALE.MILLISECOND:
  2531. return (this.current.getMilliseconds() == 0);
  2532. case TimeStep.SCALE.SECOND:
  2533. return (this.current.getSeconds() == 0);
  2534. case TimeStep.SCALE.MINUTE:
  2535. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2536. // Note: this is no bug. Major label is equal for both minute and hour scale
  2537. case TimeStep.SCALE.HOUR:
  2538. return (this.current.getHours() == 0);
  2539. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2540. case TimeStep.SCALE.DAY:
  2541. return (this.current.getDate() == 1);
  2542. case TimeStep.SCALE.MONTH:
  2543. return (this.current.getMonth() == 0);
  2544. case TimeStep.SCALE.YEAR:
  2545. return false;
  2546. default:
  2547. return false;
  2548. }
  2549. };
  2550. /**
  2551. * Returns formatted text for the minor axislabel, depending on the current
  2552. * date and the scale. For example when scale is MINUTE, the current time is
  2553. * formatted as "hh:mm".
  2554. * @param {Date} [date] custom date. if not provided, current date is taken
  2555. */
  2556. TimeStep.prototype.getLabelMinor = function(date) {
  2557. if (date == undefined) {
  2558. date = this.current;
  2559. }
  2560. switch (this.scale) {
  2561. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2562. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2563. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2564. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2565. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2566. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2567. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2568. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2569. default: return '';
  2570. }
  2571. };
  2572. /**
  2573. * Returns formatted text for the major axis label, depending on the current
  2574. * date and the scale. For example when scale is MINUTE, the major scale is
  2575. * hours, and the hour will be formatted as "hh".
  2576. * @param {Date} [date] custom date. if not provided, current date is taken
  2577. */
  2578. TimeStep.prototype.getLabelMajor = function(date) {
  2579. if (date == undefined) {
  2580. date = this.current;
  2581. }
  2582. //noinspection FallthroughInSwitchStatementJS
  2583. switch (this.scale) {
  2584. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2585. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2586. case TimeStep.SCALE.MINUTE:
  2587. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2588. case TimeStep.SCALE.WEEKDAY:
  2589. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2590. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2591. case TimeStep.SCALE.YEAR: return '';
  2592. default: return '';
  2593. }
  2594. };
  2595. /**
  2596. * @constructor Stack
  2597. * Stacks items on top of each other.
  2598. * @param {ItemSet} parent
  2599. * @param {Object} [options]
  2600. */
  2601. function Stack (parent, options) {
  2602. this.parent = parent;
  2603. this.options = options || {};
  2604. this.defaultOptions = {
  2605. order: function (a, b) {
  2606. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  2607. // Order: ranges over non-ranges, ranged ordered by width, and
  2608. // lastly ordered by start.
  2609. if (a instanceof ItemRange) {
  2610. if (b instanceof ItemRange) {
  2611. var aInt = (a.data.end - a.data.start);
  2612. var bInt = (b.data.end - b.data.start);
  2613. return (aInt - bInt) || (a.data.start - b.data.start);
  2614. }
  2615. else {
  2616. return -1;
  2617. }
  2618. }
  2619. else {
  2620. if (b instanceof ItemRange) {
  2621. return 1;
  2622. }
  2623. else {
  2624. return (a.data.start - b.data.start);
  2625. }
  2626. }
  2627. },
  2628. margin: {
  2629. item: 10
  2630. }
  2631. };
  2632. this.ordered = []; // ordered items
  2633. }
  2634. /**
  2635. * Set options for the stack
  2636. * @param {Object} options Available options:
  2637. * {ItemSet} parent
  2638. * {Number} margin
  2639. * {function} order Stacking order
  2640. */
  2641. Stack.prototype.setOptions = function setOptions (options) {
  2642. util.extend(this.options, options);
  2643. // TODO: register on data changes at the connected parent itemset, and update the changed part only and immediately
  2644. };
  2645. /**
  2646. * Stack the items such that they don't overlap. The items will have a minimal
  2647. * distance equal to options.margin.item.
  2648. */
  2649. Stack.prototype.update = function update() {
  2650. this._order();
  2651. this._stack();
  2652. };
  2653. /**
  2654. * Order the items. The items are ordered by width first, and by left position
  2655. * second.
  2656. * If a custom order function has been provided via the options, then this will
  2657. * be used.
  2658. * @private
  2659. */
  2660. Stack.prototype._order = function _order () {
  2661. var items = this.parent.items;
  2662. if (!items) {
  2663. throw new Error('Cannot stack items: parent does not contain items');
  2664. }
  2665. // TODO: store the sorted items, to have less work later on
  2666. var ordered = [];
  2667. var index = 0;
  2668. // items is a map (no array)
  2669. util.forEach(items, function (item) {
  2670. if (item.visible) {
  2671. ordered[index] = item;
  2672. index++;
  2673. }
  2674. });
  2675. //if a customer stack order function exists, use it.
  2676. var order = this.options.order || this.defaultOptions.order;
  2677. if (!(typeof order === 'function')) {
  2678. throw new Error('Option order must be a function');
  2679. }
  2680. ordered.sort(order);
  2681. this.ordered = ordered;
  2682. };
  2683. /**
  2684. * Adjust vertical positions of the events such that they don't overlap each
  2685. * other.
  2686. * @private
  2687. */
  2688. Stack.prototype._stack = function _stack () {
  2689. var i,
  2690. iMax,
  2691. ordered = this.ordered,
  2692. options = this.options,
  2693. orientation = options.orientation || this.defaultOptions.orientation,
  2694. axisOnTop = (orientation == 'top'),
  2695. margin;
  2696. if (options.margin && options.margin.item !== undefined) {
  2697. margin = options.margin.item;
  2698. }
  2699. else {
  2700. margin = this.defaultOptions.margin.item
  2701. }
  2702. // calculate new, non-overlapping positions
  2703. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  2704. var item = ordered[i];
  2705. var collidingItem = null;
  2706. do {
  2707. // TODO: optimize checking for overlap. when there is a gap without items,
  2708. // you only need to check for items from the next item on, not from zero
  2709. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  2710. if (collidingItem != null) {
  2711. // There is a collision. Reposition the event above the colliding element
  2712. if (axisOnTop) {
  2713. item.top = collidingItem.top + collidingItem.height + margin;
  2714. }
  2715. else {
  2716. item.top = collidingItem.top - item.height - margin;
  2717. }
  2718. }
  2719. } while (collidingItem);
  2720. }
  2721. };
  2722. /**
  2723. * Check if the destiny position of given item overlaps with any
  2724. * of the other items from index itemStart to itemEnd.
  2725. * @param {Array} items Array with items
  2726. * @param {int} itemIndex Number of the item to be checked for overlap
  2727. * @param {int} itemStart First item to be checked.
  2728. * @param {int} itemEnd Last item to be checked.
  2729. * @return {Object | null} colliding item, or undefined when no collisions
  2730. * @param {Number} margin A minimum required margin.
  2731. * If margin is provided, the two items will be
  2732. * marked colliding when they overlap or
  2733. * when the margin between the two is smaller than
  2734. * the requested margin.
  2735. */
  2736. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  2737. itemStart, itemEnd, margin) {
  2738. var collision = this.collision;
  2739. // we loop from end to start, as we suppose that the chance of a
  2740. // collision is larger for items at the end, so check these first.
  2741. var a = items[itemIndex];
  2742. for (var i = itemEnd; i >= itemStart; i--) {
  2743. var b = items[i];
  2744. if (collision(a, b, margin)) {
  2745. if (i != itemIndex) {
  2746. return b;
  2747. }
  2748. }
  2749. }
  2750. return null;
  2751. };
  2752. /**
  2753. * Test if the two provided items collide
  2754. * The items must have parameters left, width, top, and height.
  2755. * @param {Component} a The first item
  2756. * @param {Component} b The second item
  2757. * @param {Number} margin A minimum required margin.
  2758. * If margin is provided, the two items will be
  2759. * marked colliding when they overlap or
  2760. * when the margin between the two is smaller than
  2761. * the requested margin.
  2762. * @return {boolean} true if a and b collide, else false
  2763. */
  2764. Stack.prototype.collision = function collision (a, b, margin) {
  2765. return ((a.left - margin) < (b.left + b.getWidth()) &&
  2766. (a.left + a.getWidth() + margin) > b.left &&
  2767. (a.top - margin) < (b.top + b.height) &&
  2768. (a.top + a.height + margin) > b.top);
  2769. };
  2770. /**
  2771. * @constructor Range
  2772. * A Range controls a numeric range with a start and end value.
  2773. * The Range adjusts the range based on mouse events or programmatic changes,
  2774. * and triggers events when the range is changing or has been changed.
  2775. * @param {Object} [options] See description at Range.setOptions
  2776. * @extends Controller
  2777. */
  2778. function Range(options) {
  2779. this.id = util.randomUUID();
  2780. this.start = null; // Number
  2781. this.end = null; // Number
  2782. this.options = options || {};
  2783. this.setOptions(options);
  2784. }
  2785. /**
  2786. * Set options for the range controller
  2787. * @param {Object} options Available options:
  2788. * {Number} min Minimum value for start
  2789. * {Number} max Maximum value for end
  2790. * {Number} zoomMin Set a minimum value for
  2791. * (end - start).
  2792. * {Number} zoomMax Set a maximum value for
  2793. * (end - start).
  2794. */
  2795. Range.prototype.setOptions = function (options) {
  2796. util.extend(this.options, options);
  2797. // re-apply range with new limitations
  2798. if (this.start !== null && this.end !== null) {
  2799. this.setRange(this.start, this.end);
  2800. }
  2801. };
  2802. /**
  2803. * Test whether direction has a valid value
  2804. * @param {String} direction 'horizontal' or 'vertical'
  2805. */
  2806. function validateDirection (direction) {
  2807. if (direction != 'horizontal' && direction != 'vertical') {
  2808. throw new TypeError('Unknown direction "' + direction + '". ' +
  2809. 'Choose "horizontal" or "vertical".');
  2810. }
  2811. }
  2812. /**
  2813. * Add listeners for mouse and touch events to the component
  2814. * @param {Component} component
  2815. * @param {String} event Available events: 'move', 'zoom'
  2816. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2817. */
  2818. Range.prototype.subscribe = function (component, event, direction) {
  2819. var me = this;
  2820. if (event == 'move') {
  2821. // drag start listener
  2822. component.on('dragstart', function (event) {
  2823. me._onDragStart(event, component);
  2824. });
  2825. // drag listener
  2826. component.on('drag', function (event) {
  2827. me._onDrag(event, component, direction);
  2828. });
  2829. // drag end listener
  2830. component.on('dragend', function (event) {
  2831. me._onDragEnd(event, component);
  2832. });
  2833. }
  2834. else if (event == 'zoom') {
  2835. // mouse wheel
  2836. function mousewheel (event) {
  2837. me._onMouseWheel(event, component, direction);
  2838. }
  2839. component.on('mousewheel', mousewheel);
  2840. component.on('DOMMouseScroll', mousewheel); // For FF
  2841. // pinch
  2842. component.on('touch', function (event) {
  2843. me._onTouch();
  2844. });
  2845. component.on('pinch', function (event) {
  2846. me._onPinch(event, component, direction);
  2847. });
  2848. }
  2849. else {
  2850. throw new TypeError('Unknown event "' + event + '". ' +
  2851. 'Choose "move" or "zoom".');
  2852. }
  2853. };
  2854. /**
  2855. * Event handler
  2856. * @param {String} event name of the event, for example 'click', 'mousemove'
  2857. * @param {function} callback callback handler, invoked with the raw HTML Event
  2858. * as parameter.
  2859. */
  2860. Range.prototype.on = function (event, callback) {
  2861. events.addListener(this, event, callback);
  2862. };
  2863. /**
  2864. * Trigger an event
  2865. * @param {String} event name of the event, available events: 'rangechange',
  2866. * 'rangechanged'
  2867. * @private
  2868. */
  2869. Range.prototype._trigger = function (event) {
  2870. events.trigger(this, event, {
  2871. start: this.start,
  2872. end: this.end
  2873. });
  2874. };
  2875. /**
  2876. * Set a new start and end range
  2877. * @param {Number} [start]
  2878. * @param {Number} [end]
  2879. */
  2880. Range.prototype.setRange = function(start, end) {
  2881. var changed = this._applyRange(start, end);
  2882. if (changed) {
  2883. this._trigger('rangechange');
  2884. this._trigger('rangechanged');
  2885. }
  2886. };
  2887. /**
  2888. * Set a new start and end range. This method is the same as setRange, but
  2889. * does not trigger a range change and range changed event, and it returns
  2890. * true when the range is changed
  2891. * @param {Number} [start]
  2892. * @param {Number} [end]
  2893. * @return {Boolean} changed
  2894. * @private
  2895. */
  2896. Range.prototype._applyRange = function(start, end) {
  2897. var newStart = (start != null) ? util.convert(start, 'Number') : this.start,
  2898. newEnd = (end != null) ? util.convert(end, 'Number') : this.end,
  2899. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2900. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2901. diff;
  2902. // check for valid number
  2903. if (isNaN(newStart) || newStart === null) {
  2904. throw new Error('Invalid start "' + start + '"');
  2905. }
  2906. if (isNaN(newEnd) || newEnd === null) {
  2907. throw new Error('Invalid end "' + end + '"');
  2908. }
  2909. // prevent start < end
  2910. if (newEnd < newStart) {
  2911. newEnd = newStart;
  2912. }
  2913. // prevent start < min
  2914. if (min !== null) {
  2915. if (newStart < min) {
  2916. diff = (min - newStart);
  2917. newStart += diff;
  2918. newEnd += diff;
  2919. // prevent end > max
  2920. if (max != null) {
  2921. if (newEnd > max) {
  2922. newEnd = max;
  2923. }
  2924. }
  2925. }
  2926. }
  2927. // prevent end > max
  2928. if (max !== null) {
  2929. if (newEnd > max) {
  2930. diff = (newEnd - max);
  2931. newStart -= diff;
  2932. newEnd -= diff;
  2933. // prevent start < min
  2934. if (min != null) {
  2935. if (newStart < min) {
  2936. newStart = min;
  2937. }
  2938. }
  2939. }
  2940. }
  2941. // prevent (end-start) < zoomMin
  2942. if (this.options.zoomMin !== null) {
  2943. var zoomMin = parseFloat(this.options.zoomMin);
  2944. if (zoomMin < 0) {
  2945. zoomMin = 0;
  2946. }
  2947. if ((newEnd - newStart) < zoomMin) {
  2948. if ((this.end - this.start) === zoomMin) {
  2949. // ignore this action, we are already zoomed to the minimum
  2950. newStart = this.start;
  2951. newEnd = this.end;
  2952. }
  2953. else {
  2954. // zoom to the minimum
  2955. diff = (zoomMin - (newEnd - newStart));
  2956. newStart -= diff / 2;
  2957. newEnd += diff / 2;
  2958. }
  2959. }
  2960. }
  2961. // prevent (end-start) > zoomMax
  2962. if (this.options.zoomMax !== null) {
  2963. var zoomMax = parseFloat(this.options.zoomMax);
  2964. if (zoomMax < 0) {
  2965. zoomMax = 0;
  2966. }
  2967. if ((newEnd - newStart) > zoomMax) {
  2968. if ((this.end - this.start) === zoomMax) {
  2969. // ignore this action, we are already zoomed to the maximum
  2970. newStart = this.start;
  2971. newEnd = this.end;
  2972. }
  2973. else {
  2974. // zoom to the maximum
  2975. diff = ((newEnd - newStart) - zoomMax);
  2976. newStart += diff / 2;
  2977. newEnd -= diff / 2;
  2978. }
  2979. }
  2980. }
  2981. var changed = (this.start != newStart || this.end != newEnd);
  2982. this.start = newStart;
  2983. this.end = newEnd;
  2984. return changed;
  2985. };
  2986. /**
  2987. * Retrieve the current range.
  2988. * @return {Object} An object with start and end properties
  2989. */
  2990. Range.prototype.getRange = function() {
  2991. return {
  2992. start: this.start,
  2993. end: this.end
  2994. };
  2995. };
  2996. /**
  2997. * Calculate the conversion offset and scale for current range, based on
  2998. * the provided width
  2999. * @param {Number} width
  3000. * @returns {{offset: number, scale: number}} conversion
  3001. */
  3002. Range.prototype.conversion = function (width) {
  3003. return Range.conversion(this.start, this.end, width);
  3004. };
  3005. /**
  3006. * Static method to calculate the conversion offset and scale for a range,
  3007. * based on the provided start, end, and width
  3008. * @param {Number} start
  3009. * @param {Number} end
  3010. * @param {Number} width
  3011. * @returns {{offset: number, scale: number}} conversion
  3012. */
  3013. Range.conversion = function (start, end, width) {
  3014. if (width != 0 && (end - start != 0)) {
  3015. return {
  3016. offset: start,
  3017. scale: width / (end - start)
  3018. }
  3019. }
  3020. else {
  3021. return {
  3022. offset: 0,
  3023. scale: 1
  3024. };
  3025. }
  3026. };
  3027. // global (private) object to store drag params
  3028. var touchParams = {};
  3029. /**
  3030. * Start dragging horizontally or vertically
  3031. * @param {Event} event
  3032. * @param {Object} component
  3033. * @private
  3034. */
  3035. Range.prototype._onDragStart = function(event, component) {
  3036. // refuse to drag when we where pinching to prevent the timeline make a jump
  3037. // when releasing the fingers in opposite order from the touch screen
  3038. if (touchParams.pinching) return;
  3039. touchParams.start = this.start;
  3040. touchParams.end = this.end;
  3041. var frame = component.frame;
  3042. if (frame) {
  3043. frame.style.cursor = 'move';
  3044. }
  3045. };
  3046. /**
  3047. * Perform dragging operating.
  3048. * @param {Event} event
  3049. * @param {Component} component
  3050. * @param {String} direction 'horizontal' or 'vertical'
  3051. * @private
  3052. */
  3053. Range.prototype._onDrag = function (event, component, direction) {
  3054. validateDirection(direction);
  3055. // refuse to drag when we where pinching to prevent the timeline make a jump
  3056. // when releasing the fingers in opposite order from the touch screen
  3057. if (touchParams.pinching) return;
  3058. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  3059. interval = (touchParams.end - touchParams.start),
  3060. width = (direction == 'horizontal') ? component.width : component.height,
  3061. diffRange = -delta / width * interval;
  3062. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  3063. // fire a rangechange event
  3064. this._trigger('rangechange');
  3065. };
  3066. /**
  3067. * Stop dragging operating.
  3068. * @param {event} event
  3069. * @param {Component} component
  3070. * @private
  3071. */
  3072. Range.prototype._onDragEnd = function (event, component) {
  3073. // refuse to drag when we where pinching to prevent the timeline make a jump
  3074. // when releasing the fingers in opposite order from the touch screen
  3075. if (touchParams.pinching) return;
  3076. if (component.frame) {
  3077. component.frame.style.cursor = 'auto';
  3078. }
  3079. // fire a rangechanged event
  3080. this._trigger('rangechanged');
  3081. };
  3082. /**
  3083. * Event handler for mouse wheel event, used to zoom
  3084. * Code from http://adomas.org/javascript-mouse-wheel/
  3085. * @param {Event} event
  3086. * @param {Component} component
  3087. * @param {String} direction 'horizontal' or 'vertical'
  3088. * @private
  3089. */
  3090. Range.prototype._onMouseWheel = function(event, component, direction) {
  3091. validateDirection(direction);
  3092. // retrieve delta
  3093. var delta = 0;
  3094. if (event.wheelDelta) { /* IE/Opera. */
  3095. delta = event.wheelDelta / 120;
  3096. } else if (event.detail) { /* Mozilla case. */
  3097. // In Mozilla, sign of delta is different than in IE.
  3098. // Also, delta is multiple of 3.
  3099. delta = -event.detail / 3;
  3100. }
  3101. // If delta is nonzero, handle it.
  3102. // Basically, delta is now positive if wheel was scrolled up,
  3103. // and negative, if wheel was scrolled down.
  3104. if (delta) {
  3105. // perform the zoom action. Delta is normally 1 or -1
  3106. // adjust a negative delta such that zooming in with delta 0.1
  3107. // equals zooming out with a delta -0.1
  3108. var scale;
  3109. if (delta < 0) {
  3110. scale = 1 - (delta / 5);
  3111. }
  3112. else {
  3113. scale = 1 / (1 + (delta / 5)) ;
  3114. }
  3115. // calculate center, the date to zoom around
  3116. var gesture = util.fakeGesture(this, event),
  3117. pointer = getPointer(gesture.touches[0], component.frame),
  3118. pointerDate = this._pointerToDate(component, direction, pointer);
  3119. this.zoom(scale, pointerDate);
  3120. }
  3121. // Prevent default actions caused by mouse wheel
  3122. // (else the page and timeline both zoom and scroll)
  3123. util.preventDefault(event);
  3124. };
  3125. /**
  3126. * On start of a touch gesture, initialize scale to 1
  3127. * @private
  3128. */
  3129. Range.prototype._onTouch = function () {
  3130. touchParams.start = this.start;
  3131. touchParams.end = this.end;
  3132. touchParams.pinching = false;
  3133. touchParams.center = null;
  3134. };
  3135. /**
  3136. * Handle pinch event
  3137. * @param {Event} event
  3138. * @param {Component} component
  3139. * @param {String} direction 'horizontal' or 'vertical'
  3140. * @private
  3141. */
  3142. Range.prototype._onPinch = function (event, component, direction) {
  3143. touchParams.pinching = true;
  3144. if (event.gesture.touches.length > 1) {
  3145. if (!touchParams.center) {
  3146. touchParams.center = getPointer(event.gesture.center, component.frame);
  3147. }
  3148. var scale = 1 / event.gesture.scale,
  3149. initDate = this._pointerToDate(component, direction, touchParams.center),
  3150. center = getPointer(event.gesture.center, component.frame),
  3151. date = this._pointerToDate(component, direction, center),
  3152. delta = date - initDate; // TODO: utilize delta
  3153. // calculate new start and end
  3154. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3155. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3156. // apply new range
  3157. this.setRange(newStart, newEnd);
  3158. }
  3159. };
  3160. /**
  3161. * Helper function to calculate the center date for zooming
  3162. * @param {Component} component
  3163. * @param {{x: Number, y: Number}} pointer
  3164. * @param {String} direction 'horizontal' or 'vertical'
  3165. * @return {number} date
  3166. * @private
  3167. */
  3168. Range.prototype._pointerToDate = function (component, direction, pointer) {
  3169. var conversion;
  3170. if (direction == 'horizontal') {
  3171. var width = component.width;
  3172. conversion = this.conversion(width);
  3173. return pointer.x / conversion.scale + conversion.offset;
  3174. }
  3175. else {
  3176. var height = component.height;
  3177. conversion = this.conversion(height);
  3178. return pointer.y / conversion.scale + conversion.offset;
  3179. }
  3180. };
  3181. /**
  3182. * Get the pointer location relative to the location of the dom element
  3183. * @param {{pageX: Number, pageY: Number}} touch
  3184. * @param {Element} element HTML DOM element
  3185. * @return {{x: Number, y: Number}} pointer
  3186. * @private
  3187. */
  3188. function getPointer (touch, element) {
  3189. return {
  3190. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3191. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3192. };
  3193. }
  3194. /**
  3195. * Zoom the range the given scale in or out. Start and end date will
  3196. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3197. * date around which to zoom.
  3198. * For example, try scale = 0.9 or 1.1
  3199. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3200. * values below 1 will zoom in.
  3201. * @param {Number} [center] Value representing a date around which will
  3202. * be zoomed.
  3203. */
  3204. Range.prototype.zoom = function(scale, center) {
  3205. // if centerDate is not provided, take it half between start Date and end Date
  3206. if (center == null) {
  3207. center = (this.start + this.end) / 2;
  3208. }
  3209. // calculate new start and end
  3210. var newStart = center + (this.start - center) * scale;
  3211. var newEnd = center + (this.end - center) * scale;
  3212. this.setRange(newStart, newEnd);
  3213. };
  3214. /**
  3215. * Move the range with a given delta to the left or right. Start and end
  3216. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3217. * @param {Number} delta Moving amount. Positive value will move right,
  3218. * negative value will move left
  3219. */
  3220. Range.prototype.move = function(delta) {
  3221. // zoom start Date and end Date relative to the centerDate
  3222. var diff = (this.end - this.start);
  3223. // apply new values
  3224. var newStart = this.start + diff * delta;
  3225. var newEnd = this.end + diff * delta;
  3226. // TODO: reckon with min and max range
  3227. this.start = newStart;
  3228. this.end = newEnd;
  3229. };
  3230. /**
  3231. * Move the range to a new center point
  3232. * @param {Number} moveTo New center point of the range
  3233. */
  3234. Range.prototype.moveTo = function(moveTo) {
  3235. var center = (this.start + this.end) / 2;
  3236. var diff = center - moveTo;
  3237. // calculate new start and end
  3238. var newStart = this.start - diff;
  3239. var newEnd = this.end - diff;
  3240. this.setRange(newStart, newEnd);
  3241. };
  3242. /**
  3243. * @constructor Controller
  3244. *
  3245. * A Controller controls the reflows and repaints of all visual components
  3246. */
  3247. function Controller () {
  3248. this.id = util.randomUUID();
  3249. this.components = {};
  3250. this.repaintTimer = undefined;
  3251. this.reflowTimer = undefined;
  3252. }
  3253. /**
  3254. * Add a component to the controller
  3255. * @param {Component} component
  3256. */
  3257. Controller.prototype.add = function add(component) {
  3258. // validate the component
  3259. if (component.id == undefined) {
  3260. throw new Error('Component has no field id');
  3261. }
  3262. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3263. throw new TypeError('Component must be an instance of ' +
  3264. 'prototype Component or Controller');
  3265. }
  3266. // add the component
  3267. component.controller = this;
  3268. this.components[component.id] = component;
  3269. };
  3270. /**
  3271. * Remove a component from the controller
  3272. * @param {Component | String} component
  3273. */
  3274. Controller.prototype.remove = function remove(component) {
  3275. var id;
  3276. for (id in this.components) {
  3277. if (this.components.hasOwnProperty(id)) {
  3278. if (id == component || this.components[id] == component) {
  3279. break;
  3280. }
  3281. }
  3282. }
  3283. if (id) {
  3284. delete this.components[id];
  3285. }
  3286. };
  3287. /**
  3288. * Request a reflow. The controller will schedule a reflow
  3289. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3290. * is false.
  3291. */
  3292. Controller.prototype.requestReflow = function requestReflow(force) {
  3293. if (force) {
  3294. this.reflow();
  3295. }
  3296. else {
  3297. if (!this.reflowTimer) {
  3298. var me = this;
  3299. this.reflowTimer = setTimeout(function () {
  3300. me.reflowTimer = undefined;
  3301. me.reflow();
  3302. }, 0);
  3303. }
  3304. }
  3305. };
  3306. /**
  3307. * Request a repaint. The controller will schedule a repaint
  3308. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3309. * is false.
  3310. */
  3311. Controller.prototype.requestRepaint = function requestRepaint(force) {
  3312. if (force) {
  3313. this.repaint();
  3314. }
  3315. else {
  3316. if (!this.repaintTimer) {
  3317. var me = this;
  3318. this.repaintTimer = setTimeout(function () {
  3319. me.repaintTimer = undefined;
  3320. me.repaint();
  3321. }, 0);
  3322. }
  3323. }
  3324. };
  3325. /**
  3326. * Repaint all components
  3327. */
  3328. Controller.prototype.repaint = function repaint() {
  3329. var changed = false;
  3330. // cancel any running repaint request
  3331. if (this.repaintTimer) {
  3332. clearTimeout(this.repaintTimer);
  3333. this.repaintTimer = undefined;
  3334. }
  3335. var done = {};
  3336. function repaint(component, id) {
  3337. if (!(id in done)) {
  3338. // first repaint the components on which this component is dependent
  3339. if (component.depends) {
  3340. component.depends.forEach(function (dep) {
  3341. repaint(dep, dep.id);
  3342. });
  3343. }
  3344. if (component.parent) {
  3345. repaint(component.parent, component.parent.id);
  3346. }
  3347. // repaint the component itself and mark as done
  3348. changed = component.repaint() || changed;
  3349. done[id] = true;
  3350. }
  3351. }
  3352. util.forEach(this.components, repaint);
  3353. // immediately reflow when needed
  3354. if (changed) {
  3355. this.reflow();
  3356. }
  3357. // TODO: limit the number of nested reflows/repaints, prevent loop
  3358. };
  3359. /**
  3360. * Reflow all components
  3361. */
  3362. Controller.prototype.reflow = function reflow() {
  3363. var resized = false;
  3364. // cancel any running repaint request
  3365. if (this.reflowTimer) {
  3366. clearTimeout(this.reflowTimer);
  3367. this.reflowTimer = undefined;
  3368. }
  3369. var done = {};
  3370. function reflow(component, id) {
  3371. if (!(id in done)) {
  3372. // first reflow the components on which this component is dependent
  3373. if (component.depends) {
  3374. component.depends.forEach(function (dep) {
  3375. reflow(dep, dep.id);
  3376. });
  3377. }
  3378. if (component.parent) {
  3379. reflow(component.parent, component.parent.id);
  3380. }
  3381. // reflow the component itself and mark as done
  3382. resized = component.reflow() || resized;
  3383. done[id] = true;
  3384. }
  3385. }
  3386. util.forEach(this.components, reflow);
  3387. // immediately repaint when needed
  3388. if (resized) {
  3389. this.repaint();
  3390. }
  3391. // TODO: limit the number of nested reflows/repaints, prevent loop
  3392. };
  3393. /**
  3394. * Prototype for visual components
  3395. */
  3396. function Component () {
  3397. this.id = null;
  3398. this.parent = null;
  3399. this.depends = null;
  3400. this.controller = null;
  3401. this.options = null;
  3402. this.frame = null; // main DOM element
  3403. this.top = 0;
  3404. this.left = 0;
  3405. this.width = 0;
  3406. this.height = 0;
  3407. }
  3408. /**
  3409. * Set parameters for the frame. Parameters will be merged in current parameter
  3410. * set.
  3411. * @param {Object} options Available parameters:
  3412. * {String | function} [className]
  3413. * {EventBus} [eventBus]
  3414. * {String | Number | function} [left]
  3415. * {String | Number | function} [top]
  3416. * {String | Number | function} [width]
  3417. * {String | Number | function} [height]
  3418. */
  3419. Component.prototype.setOptions = function setOptions(options) {
  3420. if (options) {
  3421. util.extend(this.options, options);
  3422. if (this.controller) {
  3423. this.requestRepaint();
  3424. this.requestReflow();
  3425. }
  3426. }
  3427. };
  3428. /**
  3429. * Get an option value by name
  3430. * The function will first check this.options object, and else will check
  3431. * this.defaultOptions.
  3432. * @param {String} name
  3433. * @return {*} value
  3434. */
  3435. Component.prototype.getOption = function getOption(name) {
  3436. var value;
  3437. if (this.options) {
  3438. value = this.options[name];
  3439. }
  3440. if (value === undefined && this.defaultOptions) {
  3441. value = this.defaultOptions[name];
  3442. }
  3443. return value;
  3444. };
  3445. /**
  3446. * Get the container element of the component, which can be used by a child to
  3447. * add its own widgets. Not all components do have a container for childs, in
  3448. * that case null is returned.
  3449. * @returns {HTMLElement | null} container
  3450. */
  3451. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3452. Component.prototype.getContainer = function getContainer() {
  3453. // should be implemented by the component
  3454. return null;
  3455. };
  3456. /**
  3457. * Get the frame element of the component, the outer HTML DOM element.
  3458. * @returns {HTMLElement | null} frame
  3459. */
  3460. Component.prototype.getFrame = function getFrame() {
  3461. return this.frame;
  3462. };
  3463. /**
  3464. * Repaint the component
  3465. * @return {Boolean} changed
  3466. */
  3467. Component.prototype.repaint = function repaint() {
  3468. // should be implemented by the component
  3469. return false;
  3470. };
  3471. /**
  3472. * Reflow the component
  3473. * @return {Boolean} resized
  3474. */
  3475. Component.prototype.reflow = function reflow() {
  3476. // should be implemented by the component
  3477. return false;
  3478. };
  3479. /**
  3480. * Hide the component from the DOM
  3481. * @return {Boolean} changed
  3482. */
  3483. Component.prototype.hide = function hide() {
  3484. if (this.frame && this.frame.parentNode) {
  3485. this.frame.parentNode.removeChild(this.frame);
  3486. return true;
  3487. }
  3488. else {
  3489. return false;
  3490. }
  3491. };
  3492. /**
  3493. * Show the component in the DOM (when not already visible).
  3494. * A repaint will be executed when the component is not visible
  3495. * @return {Boolean} changed
  3496. */
  3497. Component.prototype.show = function show() {
  3498. if (!this.frame || !this.frame.parentNode) {
  3499. return this.repaint();
  3500. }
  3501. else {
  3502. return false;
  3503. }
  3504. };
  3505. /**
  3506. * Request a repaint. The controller will schedule a repaint
  3507. */
  3508. Component.prototype.requestRepaint = function requestRepaint() {
  3509. if (this.controller) {
  3510. this.controller.requestRepaint();
  3511. }
  3512. else {
  3513. throw new Error('Cannot request a repaint: no controller configured');
  3514. // TODO: just do a repaint when no parent is configured?
  3515. }
  3516. };
  3517. /**
  3518. * Request a reflow. The controller will schedule a reflow
  3519. */
  3520. Component.prototype.requestReflow = function requestReflow() {
  3521. if (this.controller) {
  3522. this.controller.requestReflow();
  3523. }
  3524. else {
  3525. throw new Error('Cannot request a reflow: no controller configured');
  3526. // TODO: just do a reflow when no parent is configured?
  3527. }
  3528. };
  3529. /**
  3530. * A panel can contain components
  3531. * @param {Component} [parent]
  3532. * @param {Component[]} [depends] Components on which this components depends
  3533. * (except for the parent)
  3534. * @param {Object} [options] Available parameters:
  3535. * {String | Number | function} [left]
  3536. * {String | Number | function} [top]
  3537. * {String | Number | function} [width]
  3538. * {String | Number | function} [height]
  3539. * {String | function} [className]
  3540. * @constructor Panel
  3541. * @extends Component
  3542. */
  3543. function Panel(parent, depends, options) {
  3544. this.id = util.randomUUID();
  3545. this.parent = parent;
  3546. this.depends = depends;
  3547. this.options = options || {};
  3548. }
  3549. Panel.prototype = new Component();
  3550. /**
  3551. * Set options. Will extend the current options.
  3552. * @param {Object} [options] Available parameters:
  3553. * {String | function} [className]
  3554. * {String | Number | function} [left]
  3555. * {String | Number | function} [top]
  3556. * {String | Number | function} [width]
  3557. * {String | Number | function} [height]
  3558. */
  3559. Panel.prototype.setOptions = Component.prototype.setOptions;
  3560. /**
  3561. * Get the container element of the panel, which can be used by a child to
  3562. * add its own widgets.
  3563. * @returns {HTMLElement} container
  3564. */
  3565. Panel.prototype.getContainer = function () {
  3566. return this.frame;
  3567. };
  3568. /**
  3569. * Repaint the component
  3570. * @return {Boolean} changed
  3571. */
  3572. Panel.prototype.repaint = function () {
  3573. var changed = 0,
  3574. update = util.updateProperty,
  3575. asSize = util.option.asSize,
  3576. options = this.options,
  3577. frame = this.frame;
  3578. if (!frame) {
  3579. frame = document.createElement('div');
  3580. frame.className = 'panel';
  3581. var className = options.className;
  3582. if (className) {
  3583. if (typeof className == 'function') {
  3584. util.addClassName(frame, String(className()));
  3585. }
  3586. else {
  3587. util.addClassName(frame, String(className));
  3588. }
  3589. }
  3590. this.frame = frame;
  3591. changed += 1;
  3592. }
  3593. if (!frame.parentNode) {
  3594. if (!this.parent) {
  3595. throw new Error('Cannot repaint panel: no parent attached');
  3596. }
  3597. var parentContainer = this.parent.getContainer();
  3598. if (!parentContainer) {
  3599. throw new Error('Cannot repaint panel: parent has no container element');
  3600. }
  3601. parentContainer.appendChild(frame);
  3602. changed += 1;
  3603. }
  3604. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3605. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3606. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3607. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3608. return (changed > 0);
  3609. };
  3610. /**
  3611. * Reflow the component
  3612. * @return {Boolean} resized
  3613. */
  3614. Panel.prototype.reflow = function () {
  3615. var changed = 0,
  3616. update = util.updateProperty,
  3617. frame = this.frame;
  3618. if (frame) {
  3619. changed += update(this, 'top', frame.offsetTop);
  3620. changed += update(this, 'left', frame.offsetLeft);
  3621. changed += update(this, 'width', frame.offsetWidth);
  3622. changed += update(this, 'height', frame.offsetHeight);
  3623. }
  3624. else {
  3625. changed += 1;
  3626. }
  3627. return (changed > 0);
  3628. };
  3629. /**
  3630. * A root panel can hold components. The root panel must be initialized with
  3631. * a DOM element as container.
  3632. * @param {HTMLElement} container
  3633. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3634. * @constructor RootPanel
  3635. * @extends Panel
  3636. */
  3637. function RootPanel(container, options) {
  3638. this.id = util.randomUUID();
  3639. this.container = container;
  3640. this.options = options || {};
  3641. this.defaultOptions = {
  3642. autoResize: true
  3643. };
  3644. this.listeners = {}; // event listeners
  3645. }
  3646. RootPanel.prototype = new Panel();
  3647. /**
  3648. * Set options. Will extend the current options.
  3649. * @param {Object} [options] Available parameters:
  3650. * {String | function} [className]
  3651. * {String | Number | function} [left]
  3652. * {String | Number | function} [top]
  3653. * {String | Number | function} [width]
  3654. * {String | Number | function} [height]
  3655. * {Boolean | function} [autoResize]
  3656. */
  3657. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3658. /**
  3659. * Repaint the component
  3660. * @return {Boolean} changed
  3661. */
  3662. RootPanel.prototype.repaint = function () {
  3663. var changed = 0,
  3664. update = util.updateProperty,
  3665. asSize = util.option.asSize,
  3666. options = this.options,
  3667. frame = this.frame;
  3668. if (!frame) {
  3669. frame = document.createElement('div');
  3670. this.frame = frame;
  3671. changed += 1;
  3672. }
  3673. if (!frame.parentNode) {
  3674. if (!this.container) {
  3675. throw new Error('Cannot repaint root panel: no container attached');
  3676. }
  3677. this.container.appendChild(frame);
  3678. changed += 1;
  3679. }
  3680. frame.className = 'vis timeline rootpanel ' + options.orientation;
  3681. var className = options.className;
  3682. if (className) {
  3683. util.addClassName(frame, util.option.asString(className));
  3684. }
  3685. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3686. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3687. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3688. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3689. this._updateEventEmitters();
  3690. this._updateWatch();
  3691. return (changed > 0);
  3692. };
  3693. /**
  3694. * Reflow the component
  3695. * @return {Boolean} resized
  3696. */
  3697. RootPanel.prototype.reflow = function () {
  3698. var changed = 0,
  3699. update = util.updateProperty,
  3700. frame = this.frame;
  3701. if (frame) {
  3702. changed += update(this, 'top', frame.offsetTop);
  3703. changed += update(this, 'left', frame.offsetLeft);
  3704. changed += update(this, 'width', frame.offsetWidth);
  3705. changed += update(this, 'height', frame.offsetHeight);
  3706. }
  3707. else {
  3708. changed += 1;
  3709. }
  3710. return (changed > 0);
  3711. };
  3712. /**
  3713. * Update watching for resize, depending on the current option
  3714. * @private
  3715. */
  3716. RootPanel.prototype._updateWatch = function () {
  3717. var autoResize = this.getOption('autoResize');
  3718. if (autoResize) {
  3719. this._watch();
  3720. }
  3721. else {
  3722. this._unwatch();
  3723. }
  3724. };
  3725. /**
  3726. * Watch for changes in the size of the frame. On resize, the Panel will
  3727. * automatically redraw itself.
  3728. * @private
  3729. */
  3730. RootPanel.prototype._watch = function () {
  3731. var me = this;
  3732. this._unwatch();
  3733. var checkSize = function () {
  3734. var autoResize = me.getOption('autoResize');
  3735. if (!autoResize) {
  3736. // stop watching when the option autoResize is changed to false
  3737. me._unwatch();
  3738. return;
  3739. }
  3740. if (me.frame) {
  3741. // check whether the frame is resized
  3742. if ((me.frame.clientWidth != me.width) ||
  3743. (me.frame.clientHeight != me.height)) {
  3744. me.requestReflow();
  3745. }
  3746. }
  3747. };
  3748. // TODO: automatically cleanup the event listener when the frame is deleted
  3749. util.addEventListener(window, 'resize', checkSize);
  3750. this.watchTimer = setInterval(checkSize, 1000);
  3751. };
  3752. /**
  3753. * Stop watching for a resize of the frame.
  3754. * @private
  3755. */
  3756. RootPanel.prototype._unwatch = function () {
  3757. if (this.watchTimer) {
  3758. clearInterval(this.watchTimer);
  3759. this.watchTimer = undefined;
  3760. }
  3761. // TODO: remove event listener on window.resize
  3762. };
  3763. /**
  3764. * Event handler
  3765. * @param {String} event name of the event, for example 'click', 'mousemove'
  3766. * @param {function} callback callback handler, invoked with the raw HTML Event
  3767. * as parameter.
  3768. */
  3769. RootPanel.prototype.on = function (event, callback) {
  3770. // register the listener at this component
  3771. var arr = this.listeners[event];
  3772. if (!arr) {
  3773. arr = [];
  3774. this.listeners[event] = arr;
  3775. }
  3776. arr.push(callback);
  3777. this._updateEventEmitters();
  3778. };
  3779. /**
  3780. * Update the event listeners for all event emitters
  3781. * @private
  3782. */
  3783. RootPanel.prototype._updateEventEmitters = function () {
  3784. if (this.listeners) {
  3785. var me = this;
  3786. util.forEach(this.listeners, function (listeners, event) {
  3787. if (!me.emitters) {
  3788. me.emitters = {};
  3789. }
  3790. if (!(event in me.emitters)) {
  3791. // create event
  3792. var frame = me.frame;
  3793. if (frame) {
  3794. //console.log('Created a listener for event ' + event + ' on component ' + me.id); // TODO: cleanup logging
  3795. var callback = function(event) {
  3796. listeners.forEach(function (listener) {
  3797. // TODO: filter on event target!
  3798. listener(event);
  3799. });
  3800. };
  3801. me.emitters[event] = callback;
  3802. if (!me.hammer) {
  3803. me.hammer = Hammer(frame, {
  3804. prevent_default: true
  3805. });
  3806. }
  3807. me.hammer.on(event, callback);
  3808. }
  3809. }
  3810. });
  3811. // TODO: be able to delete event listeners
  3812. // TODO: be able to move event listeners to a parent when available
  3813. }
  3814. };
  3815. /**
  3816. * A horizontal time axis
  3817. * @param {Component} parent
  3818. * @param {Component[]} [depends] Components on which this components depends
  3819. * (except for the parent)
  3820. * @param {Object} [options] See TimeAxis.setOptions for the available
  3821. * options.
  3822. * @constructor TimeAxis
  3823. * @extends Component
  3824. */
  3825. function TimeAxis (parent, depends, options) {
  3826. this.id = util.randomUUID();
  3827. this.parent = parent;
  3828. this.depends = depends;
  3829. this.dom = {
  3830. majorLines: [],
  3831. majorTexts: [],
  3832. minorLines: [],
  3833. minorTexts: [],
  3834. redundant: {
  3835. majorLines: [],
  3836. majorTexts: [],
  3837. minorLines: [],
  3838. minorTexts: []
  3839. }
  3840. };
  3841. this.props = {
  3842. range: {
  3843. start: 0,
  3844. end: 0,
  3845. minimumStep: 0
  3846. },
  3847. lineTop: 0
  3848. };
  3849. this.options = options || {};
  3850. this.defaultOptions = {
  3851. orientation: 'bottom', // supported: 'top', 'bottom'
  3852. // TODO: implement timeaxis orientations 'left' and 'right'
  3853. showMinorLabels: true,
  3854. showMajorLabels: true
  3855. };
  3856. this.conversion = null;
  3857. this.range = null;
  3858. }
  3859. TimeAxis.prototype = new Component();
  3860. // TODO: comment options
  3861. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3862. /**
  3863. * Set a range (start and end)
  3864. * @param {Range | Object} range A Range or an object containing start and end.
  3865. */
  3866. TimeAxis.prototype.setRange = function (range) {
  3867. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3868. throw new TypeError('Range must be an instance of Range, ' +
  3869. 'or an object containing start and end.');
  3870. }
  3871. this.range = range;
  3872. };
  3873. /**
  3874. * Convert a position on screen (pixels) to a datetime
  3875. * @param {int} x Position on the screen in pixels
  3876. * @return {Date} time The datetime the corresponds with given position x
  3877. */
  3878. TimeAxis.prototype.toTime = function(x) {
  3879. var conversion = this.conversion;
  3880. return new Date(x / conversion.scale + conversion.offset);
  3881. };
  3882. /**
  3883. * Convert a datetime (Date object) into a position on the screen
  3884. * @param {Date} time A date
  3885. * @return {int} x The position on the screen in pixels which corresponds
  3886. * with the given date.
  3887. * @private
  3888. */
  3889. TimeAxis.prototype.toScreen = function(time) {
  3890. var conversion = this.conversion;
  3891. return (time.valueOf() - conversion.offset) * conversion.scale;
  3892. };
  3893. /**
  3894. * Repaint the component
  3895. * @return {Boolean} changed
  3896. */
  3897. TimeAxis.prototype.repaint = function () {
  3898. var changed = 0,
  3899. update = util.updateProperty,
  3900. asSize = util.option.asSize,
  3901. options = this.options,
  3902. orientation = this.getOption('orientation'),
  3903. props = this.props,
  3904. step = this.step;
  3905. var frame = this.frame;
  3906. if (!frame) {
  3907. frame = document.createElement('div');
  3908. this.frame = frame;
  3909. changed += 1;
  3910. }
  3911. frame.className = 'axis';
  3912. // TODO: custom className?
  3913. if (!frame.parentNode) {
  3914. if (!this.parent) {
  3915. throw new Error('Cannot repaint time axis: no parent attached');
  3916. }
  3917. var parentContainer = this.parent.getContainer();
  3918. if (!parentContainer) {
  3919. throw new Error('Cannot repaint time axis: parent has no container element');
  3920. }
  3921. parentContainer.appendChild(frame);
  3922. changed += 1;
  3923. }
  3924. var parent = frame.parentNode;
  3925. if (parent) {
  3926. var beforeChild = frame.nextSibling;
  3927. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3928. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3929. (this.props.parentHeight - this.height) + 'px' :
  3930. '0px';
  3931. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3932. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3933. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3934. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3935. // get characters width and height
  3936. this._repaintMeasureChars();
  3937. if (this.step) {
  3938. this._repaintStart();
  3939. step.first();
  3940. var xFirstMajorLabel = undefined;
  3941. var max = 0;
  3942. while (step.hasNext() && max < 1000) {
  3943. max++;
  3944. var cur = step.getCurrent(),
  3945. x = this.toScreen(cur),
  3946. isMajor = step.isMajor();
  3947. // TODO: lines must have a width, such that we can create css backgrounds
  3948. if (this.getOption('showMinorLabels')) {
  3949. this._repaintMinorText(x, step.getLabelMinor());
  3950. }
  3951. if (isMajor && this.getOption('showMajorLabels')) {
  3952. if (x > 0) {
  3953. if (xFirstMajorLabel == undefined) {
  3954. xFirstMajorLabel = x;
  3955. }
  3956. this._repaintMajorText(x, step.getLabelMajor());
  3957. }
  3958. this._repaintMajorLine(x);
  3959. }
  3960. else {
  3961. this._repaintMinorLine(x);
  3962. }
  3963. step.next();
  3964. }
  3965. // create a major label on the left when needed
  3966. if (this.getOption('showMajorLabels')) {
  3967. var leftTime = this.toTime(0),
  3968. leftText = step.getLabelMajor(leftTime),
  3969. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3970. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3971. this._repaintMajorText(0, leftText);
  3972. }
  3973. }
  3974. this._repaintEnd();
  3975. }
  3976. this._repaintLine();
  3977. // put frame online again
  3978. if (beforeChild) {
  3979. parent.insertBefore(frame, beforeChild);
  3980. }
  3981. else {
  3982. parent.appendChild(frame)
  3983. }
  3984. }
  3985. return (changed > 0);
  3986. };
  3987. /**
  3988. * Start a repaint. Move all DOM elements to a redundant list, where they
  3989. * can be picked for re-use, or can be cleaned up in the end
  3990. * @private
  3991. */
  3992. TimeAxis.prototype._repaintStart = function () {
  3993. var dom = this.dom,
  3994. redundant = dom.redundant;
  3995. redundant.majorLines = dom.majorLines;
  3996. redundant.majorTexts = dom.majorTexts;
  3997. redundant.minorLines = dom.minorLines;
  3998. redundant.minorTexts = dom.minorTexts;
  3999. dom.majorLines = [];
  4000. dom.majorTexts = [];
  4001. dom.minorLines = [];
  4002. dom.minorTexts = [];
  4003. };
  4004. /**
  4005. * End a repaint. Cleanup leftover DOM elements in the redundant list
  4006. * @private
  4007. */
  4008. TimeAxis.prototype._repaintEnd = function () {
  4009. util.forEach(this.dom.redundant, function (arr) {
  4010. while (arr.length) {
  4011. var elem = arr.pop();
  4012. if (elem && elem.parentNode) {
  4013. elem.parentNode.removeChild(elem);
  4014. }
  4015. }
  4016. });
  4017. };
  4018. /**
  4019. * Create a minor label for the axis at position x
  4020. * @param {Number} x
  4021. * @param {String} text
  4022. * @private
  4023. */
  4024. TimeAxis.prototype._repaintMinorText = function (x, text) {
  4025. // reuse redundant label
  4026. var label = this.dom.redundant.minorTexts.shift();
  4027. if (!label) {
  4028. // create new label
  4029. var content = document.createTextNode('');
  4030. label = document.createElement('div');
  4031. label.appendChild(content);
  4032. label.className = 'text minor';
  4033. this.frame.appendChild(label);
  4034. }
  4035. this.dom.minorTexts.push(label);
  4036. label.childNodes[0].nodeValue = text;
  4037. label.style.left = x + 'px';
  4038. label.style.top = this.props.minorLabelTop + 'px';
  4039. //label.title = title; // TODO: this is a heavy operation
  4040. };
  4041. /**
  4042. * Create a Major label for the axis at position x
  4043. * @param {Number} x
  4044. * @param {String} text
  4045. * @private
  4046. */
  4047. TimeAxis.prototype._repaintMajorText = function (x, text) {
  4048. // reuse redundant label
  4049. var label = this.dom.redundant.majorTexts.shift();
  4050. if (!label) {
  4051. // create label
  4052. var content = document.createTextNode(text);
  4053. label = document.createElement('div');
  4054. label.className = 'text major';
  4055. label.appendChild(content);
  4056. this.frame.appendChild(label);
  4057. }
  4058. this.dom.majorTexts.push(label);
  4059. label.childNodes[0].nodeValue = text;
  4060. label.style.top = this.props.majorLabelTop + 'px';
  4061. label.style.left = x + 'px';
  4062. //label.title = title; // TODO: this is a heavy operation
  4063. };
  4064. /**
  4065. * Create a minor line for the axis at position x
  4066. * @param {Number} x
  4067. * @private
  4068. */
  4069. TimeAxis.prototype._repaintMinorLine = function (x) {
  4070. // reuse redundant line
  4071. var line = this.dom.redundant.minorLines.shift();
  4072. if (!line) {
  4073. // create vertical line
  4074. line = document.createElement('div');
  4075. line.className = 'grid vertical minor';
  4076. this.frame.appendChild(line);
  4077. }
  4078. this.dom.minorLines.push(line);
  4079. var props = this.props;
  4080. line.style.top = props.minorLineTop + 'px';
  4081. line.style.height = props.minorLineHeight + 'px';
  4082. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  4083. };
  4084. /**
  4085. * Create a Major line for the axis at position x
  4086. * @param {Number} x
  4087. * @private
  4088. */
  4089. TimeAxis.prototype._repaintMajorLine = function (x) {
  4090. // reuse redundant line
  4091. var line = this.dom.redundant.majorLines.shift();
  4092. if (!line) {
  4093. // create vertical line
  4094. line = document.createElement('DIV');
  4095. line.className = 'grid vertical major';
  4096. this.frame.appendChild(line);
  4097. }
  4098. this.dom.majorLines.push(line);
  4099. var props = this.props;
  4100. line.style.top = props.majorLineTop + 'px';
  4101. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4102. line.style.height = props.majorLineHeight + 'px';
  4103. };
  4104. /**
  4105. * Repaint the horizontal line for the axis
  4106. * @private
  4107. */
  4108. TimeAxis.prototype._repaintLine = function() {
  4109. var line = this.dom.line,
  4110. frame = this.frame,
  4111. options = this.options;
  4112. // line before all axis elements
  4113. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4114. if (line) {
  4115. // put this line at the end of all childs
  4116. frame.removeChild(line);
  4117. frame.appendChild(line);
  4118. }
  4119. else {
  4120. // create the axis line
  4121. line = document.createElement('div');
  4122. line.className = 'grid horizontal major';
  4123. frame.appendChild(line);
  4124. this.dom.line = line;
  4125. }
  4126. line.style.top = this.props.lineTop + 'px';
  4127. }
  4128. else {
  4129. if (line && line.parentElement) {
  4130. frame.removeChild(line.line);
  4131. delete this.dom.line;
  4132. }
  4133. }
  4134. };
  4135. /**
  4136. * Create characters used to determine the size of text on the axis
  4137. * @private
  4138. */
  4139. TimeAxis.prototype._repaintMeasureChars = function () {
  4140. // calculate the width and height of a single character
  4141. // this is used to calculate the step size, and also the positioning of the
  4142. // axis
  4143. var dom = this.dom,
  4144. text;
  4145. if (!dom.measureCharMinor) {
  4146. text = document.createTextNode('0');
  4147. var measureCharMinor = document.createElement('DIV');
  4148. measureCharMinor.className = 'text minor measure';
  4149. measureCharMinor.appendChild(text);
  4150. this.frame.appendChild(measureCharMinor);
  4151. dom.measureCharMinor = measureCharMinor;
  4152. }
  4153. if (!dom.measureCharMajor) {
  4154. text = document.createTextNode('0');
  4155. var measureCharMajor = document.createElement('DIV');
  4156. measureCharMajor.className = 'text major measure';
  4157. measureCharMajor.appendChild(text);
  4158. this.frame.appendChild(measureCharMajor);
  4159. dom.measureCharMajor = measureCharMajor;
  4160. }
  4161. };
  4162. /**
  4163. * Reflow the component
  4164. * @return {Boolean} resized
  4165. */
  4166. TimeAxis.prototype.reflow = function () {
  4167. var changed = 0,
  4168. update = util.updateProperty,
  4169. frame = this.frame,
  4170. range = this.range;
  4171. if (!range) {
  4172. throw new Error('Cannot repaint time axis: no range configured');
  4173. }
  4174. if (frame) {
  4175. changed += update(this, 'top', frame.offsetTop);
  4176. changed += update(this, 'left', frame.offsetLeft);
  4177. // calculate size of a character
  4178. var props = this.props,
  4179. showMinorLabels = this.getOption('showMinorLabels'),
  4180. showMajorLabels = this.getOption('showMajorLabels'),
  4181. measureCharMinor = this.dom.measureCharMinor,
  4182. measureCharMajor = this.dom.measureCharMajor;
  4183. if (measureCharMinor) {
  4184. props.minorCharHeight = measureCharMinor.clientHeight;
  4185. props.minorCharWidth = measureCharMinor.clientWidth;
  4186. }
  4187. if (measureCharMajor) {
  4188. props.majorCharHeight = measureCharMajor.clientHeight;
  4189. props.majorCharWidth = measureCharMajor.clientWidth;
  4190. }
  4191. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4192. if (parentHeight != props.parentHeight) {
  4193. props.parentHeight = parentHeight;
  4194. changed += 1;
  4195. }
  4196. switch (this.getOption('orientation')) {
  4197. case 'bottom':
  4198. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4199. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4200. props.minorLabelTop = 0;
  4201. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4202. props.minorLineTop = -this.top;
  4203. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4204. props.minorLineWidth = 1; // TODO: really calculate width
  4205. props.majorLineTop = -this.top;
  4206. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4207. props.majorLineWidth = 1; // TODO: really calculate width
  4208. props.lineTop = 0;
  4209. break;
  4210. case 'top':
  4211. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4212. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4213. props.majorLabelTop = 0;
  4214. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4215. props.minorLineTop = props.minorLabelTop;
  4216. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4217. props.minorLineWidth = 1; // TODO: really calculate width
  4218. props.majorLineTop = 0;
  4219. props.majorLineHeight = Math.max(parentHeight - this.top);
  4220. props.majorLineWidth = 1; // TODO: really calculate width
  4221. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4222. break;
  4223. default:
  4224. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4225. }
  4226. var height = props.minorLabelHeight + props.majorLabelHeight;
  4227. changed += update(this, 'width', frame.offsetWidth);
  4228. changed += update(this, 'height', height);
  4229. // calculate range and step
  4230. this._updateConversion();
  4231. var start = util.convert(range.start, 'Number'),
  4232. end = util.convert(range.end, 'Number'),
  4233. minimumStep = this.toTime((props.minorCharWidth || 10) * 5).valueOf()
  4234. -this.toTime(0).valueOf();
  4235. this.step = new TimeStep(new Date(start), new Date(end), minimumStep);
  4236. changed += update(props.range, 'start', start);
  4237. changed += update(props.range, 'end', end);
  4238. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4239. }
  4240. return (changed > 0);
  4241. };
  4242. /**
  4243. * Calculate the scale and offset to convert a position on screen to the
  4244. * corresponding date and vice versa.
  4245. * After the method _updateConversion is executed once, the methods toTime
  4246. * and toScreen can be used.
  4247. * @private
  4248. */
  4249. TimeAxis.prototype._updateConversion = function() {
  4250. var range = this.range;
  4251. if (!range) {
  4252. throw new Error('No range configured');
  4253. }
  4254. if (range.conversion) {
  4255. this.conversion = range.conversion(this.width);
  4256. }
  4257. else {
  4258. this.conversion = Range.conversion(range.start, range.end, this.width);
  4259. }
  4260. };
  4261. /**
  4262. * A current time bar
  4263. * @param {Component} parent
  4264. * @param {Component[]} [depends] Components on which this components depends
  4265. * (except for the parent)
  4266. * @param {Object} [options] Available parameters:
  4267. * {Boolean} [showCurrentTime]
  4268. * @constructor CurrentTime
  4269. * @extends Component
  4270. */
  4271. function CurrentTime (parent, depends, options) {
  4272. this.id = util.randomUUID();
  4273. this.parent = parent;
  4274. this.depends = depends;
  4275. this.options = options || {};
  4276. this.defaultOptions = {
  4277. showCurrentTime: false
  4278. };
  4279. }
  4280. CurrentTime.prototype = new Component();
  4281. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  4282. /**
  4283. * Get the container element of the bar, which can be used by a child to
  4284. * add its own widgets.
  4285. * @returns {HTMLElement} container
  4286. */
  4287. CurrentTime.prototype.getContainer = function () {
  4288. return this.frame;
  4289. };
  4290. /**
  4291. * Repaint the component
  4292. * @return {Boolean} changed
  4293. */
  4294. CurrentTime.prototype.repaint = function () {
  4295. var bar = this.frame,
  4296. parent = this.parent,
  4297. parentContainer = parent.parent.getContainer();
  4298. if (!parent) {
  4299. throw new Error('Cannot repaint bar: no parent attached');
  4300. }
  4301. if (!parentContainer) {
  4302. throw new Error('Cannot repaint bar: parent has no container element');
  4303. }
  4304. if (!this.getOption('showCurrentTime')) {
  4305. if (bar) {
  4306. parentContainer.removeChild(bar);
  4307. delete this.frame;
  4308. }
  4309. return;
  4310. }
  4311. if (!bar) {
  4312. bar = document.createElement('div');
  4313. bar.className = 'currenttime';
  4314. bar.style.position = 'absolute';
  4315. bar.style.top = '0px';
  4316. bar.style.height = '100%';
  4317. parentContainer.appendChild(bar);
  4318. this.frame = bar;
  4319. }
  4320. if (!parent.conversion) {
  4321. parent._updateConversion();
  4322. }
  4323. var now = new Date();
  4324. var x = parent.toScreen(now);
  4325. bar.style.left = x + 'px';
  4326. bar.title = 'Current time: ' + now;
  4327. // start a timer to adjust for the new time
  4328. if (this.currentTimeTimer !== undefined) {
  4329. clearTimeout(this.currentTimeTimer);
  4330. delete this.currentTimeTimer;
  4331. }
  4332. var timeline = this;
  4333. var interval = 1 / parent.conversion.scale / 2;
  4334. if (interval < 30) {
  4335. interval = 30;
  4336. }
  4337. this.currentTimeTimer = setTimeout(function() {
  4338. timeline.repaint();
  4339. }, interval);
  4340. return false;
  4341. };
  4342. /**
  4343. * A custom time bar
  4344. * @param {Component} parent
  4345. * @param {Component[]} [depends] Components on which this components depends
  4346. * (except for the parent)
  4347. * @param {Object} [options] Available parameters:
  4348. * {Boolean} [showCustomTime]
  4349. * @constructor CustomTime
  4350. * @extends Component
  4351. */
  4352. function CustomTime (parent, depends, options) {
  4353. this.id = util.randomUUID();
  4354. this.parent = parent;
  4355. this.depends = depends;
  4356. this.options = options || {};
  4357. this.defaultOptions = {
  4358. showCustomTime: false
  4359. };
  4360. this.listeners = [];
  4361. this.customTime = new Date();
  4362. }
  4363. CustomTime.prototype = new Component();
  4364. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4365. /**
  4366. * Get the container element of the bar, which can be used by a child to
  4367. * add its own widgets.
  4368. * @returns {HTMLElement} container
  4369. */
  4370. CustomTime.prototype.getContainer = function () {
  4371. return this.frame;
  4372. };
  4373. /**
  4374. * Repaint the component
  4375. * @return {Boolean} changed
  4376. */
  4377. CustomTime.prototype.repaint = function () {
  4378. var bar = this.frame,
  4379. parent = this.parent,
  4380. parentContainer = parent.parent.getContainer();
  4381. if (!parent) {
  4382. throw new Error('Cannot repaint bar: no parent attached');
  4383. }
  4384. if (!parentContainer) {
  4385. throw new Error('Cannot repaint bar: parent has no container element');
  4386. }
  4387. if (!this.getOption('showCustomTime')) {
  4388. if (bar) {
  4389. parentContainer.removeChild(bar);
  4390. delete this.frame;
  4391. }
  4392. return;
  4393. }
  4394. if (!bar) {
  4395. bar = document.createElement('div');
  4396. bar.className = 'customtime';
  4397. bar.style.position = 'absolute';
  4398. bar.style.top = '0px';
  4399. bar.style.height = '100%';
  4400. parentContainer.appendChild(bar);
  4401. var drag = document.createElement('div');
  4402. drag.style.position = 'relative';
  4403. drag.style.top = '0px';
  4404. drag.style.left = '-10px';
  4405. drag.style.height = '100%';
  4406. drag.style.width = '20px';
  4407. bar.appendChild(drag);
  4408. this.frame = bar;
  4409. this.subscribe(this, 'movetime');
  4410. }
  4411. if (!parent.conversion) {
  4412. parent._updateConversion();
  4413. }
  4414. var x = parent.toScreen(this.customTime);
  4415. bar.style.left = x + 'px';
  4416. bar.title = 'Time: ' + this.customTime;
  4417. return false;
  4418. };
  4419. /**
  4420. * Set custom time.
  4421. * @param {Date} time
  4422. */
  4423. CustomTime.prototype._setCustomTime = function(time) {
  4424. this.customTime = new Date(time.valueOf());
  4425. this.repaint();
  4426. };
  4427. /**
  4428. * Retrieve the current custom time.
  4429. * @return {Date} customTime
  4430. */
  4431. CustomTime.prototype._getCustomTime = function() {
  4432. return new Date(this.customTime.valueOf());
  4433. };
  4434. /**
  4435. * Add listeners for mouse and touch events to the component
  4436. * @param {Component} component
  4437. */
  4438. CustomTime.prototype.subscribe = function (component, event) {
  4439. var me = this;
  4440. var listener = {
  4441. component: component,
  4442. event: event,
  4443. callback: function (event) {
  4444. me._onMouseDown(event, listener);
  4445. },
  4446. params: {}
  4447. };
  4448. component.on('mousedown', listener.callback);
  4449. me.listeners.push(listener);
  4450. };
  4451. /**
  4452. * Event handler
  4453. * @param {String} event name of the event, for example 'click', 'mousemove'
  4454. * @param {function} callback callback handler, invoked with the raw HTML Event
  4455. * as parameter.
  4456. */
  4457. CustomTime.prototype.on = function (event, callback) {
  4458. var bar = this.frame;
  4459. if (!bar) {
  4460. throw new Error('Cannot add event listener: no parent attached');
  4461. }
  4462. events.addListener(this, event, callback);
  4463. util.addEventListener(bar, event, callback);
  4464. };
  4465. /**
  4466. * Start moving horizontally
  4467. * @param {Event} event
  4468. * @param {Object} listener Listener containing the component and params
  4469. * @private
  4470. */
  4471. CustomTime.prototype._onMouseDown = function(event, listener) {
  4472. event = event || window.event;
  4473. var params = listener.params;
  4474. // only react on left mouse button down
  4475. var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  4476. if (!leftButtonDown) {
  4477. return;
  4478. }
  4479. // get mouse position
  4480. params.mouseX = util.getPageX(event);
  4481. params.moved = false;
  4482. params.customTime = this.customTime;
  4483. // add event listeners to handle moving the custom time bar
  4484. var me = this;
  4485. if (!params.onMouseMove) {
  4486. params.onMouseMove = function (event) {
  4487. me._onMouseMove(event, listener);
  4488. };
  4489. util.addEventListener(document, 'mousemove', params.onMouseMove);
  4490. }
  4491. if (!params.onMouseUp) {
  4492. params.onMouseUp = function (event) {
  4493. me._onMouseUp(event, listener);
  4494. };
  4495. util.addEventListener(document, 'mouseup', params.onMouseUp);
  4496. }
  4497. util.stopPropagation(event);
  4498. util.preventDefault(event);
  4499. };
  4500. /**
  4501. * Perform moving operating.
  4502. * This function activated from within the funcion CustomTime._onMouseDown().
  4503. * @param {Event} event
  4504. * @param {Object} listener
  4505. * @private
  4506. */
  4507. CustomTime.prototype._onMouseMove = function (event, listener) {
  4508. event = event || window.event;
  4509. var params = listener.params;
  4510. var parent = this.parent;
  4511. // calculate change in mouse position
  4512. var mouseX = util.getPageX(event);
  4513. if (params.mouseX === undefined) {
  4514. params.mouseX = mouseX;
  4515. }
  4516. var diff = mouseX - params.mouseX;
  4517. // if mouse movement is big enough, register it as a "moved" event
  4518. if (Math.abs(diff) >= 1) {
  4519. params.moved = true;
  4520. }
  4521. var x = parent.toScreen(params.customTime);
  4522. var xnew = x + diff;
  4523. var time = parent.toTime(xnew);
  4524. this._setCustomTime(time);
  4525. // fire a timechange event
  4526. events.trigger(this, 'timechange', {customTime: this.customTime});
  4527. util.preventDefault(event);
  4528. };
  4529. /**
  4530. * Stop moving operating.
  4531. * This function activated from within the function CustomTime._onMouseDown().
  4532. * @param {event} event
  4533. * @param {Object} listener
  4534. * @private
  4535. */
  4536. CustomTime.prototype._onMouseUp = function (event, listener) {
  4537. event = event || window.event;
  4538. var params = listener.params;
  4539. // remove event listeners here, important for Safari
  4540. if (params.onMouseMove) {
  4541. util.removeEventListener(document, 'mousemove', params.onMouseMove);
  4542. params.onMouseMove = null;
  4543. }
  4544. if (params.onMouseUp) {
  4545. util.removeEventListener(document, 'mouseup', params.onMouseUp);
  4546. params.onMouseUp = null;
  4547. }
  4548. if (params.moved) {
  4549. // fire a timechanged event
  4550. events.trigger(this, 'timechanged', {customTime: this.customTime});
  4551. }
  4552. };
  4553. /**
  4554. * An ItemSet holds a set of items and ranges which can be displayed in a
  4555. * range. The width is determined by the parent of the ItemSet, and the height
  4556. * is determined by the size of the items.
  4557. * @param {Component} parent
  4558. * @param {Component[]} [depends] Components on which this components depends
  4559. * (except for the parent)
  4560. * @param {Object} [options] See ItemSet.setOptions for the available
  4561. * options.
  4562. * @constructor ItemSet
  4563. * @extends Panel
  4564. */
  4565. // TODO: improve performance by replacing all Array.forEach with a for loop
  4566. function ItemSet(parent, depends, options) {
  4567. this.id = util.randomUUID();
  4568. this.parent = parent;
  4569. this.depends = depends;
  4570. // one options object is shared by this itemset and all its items
  4571. this.options = options || {};
  4572. this.defaultOptions = {
  4573. type: 'box',
  4574. align: 'center',
  4575. orientation: 'bottom',
  4576. margin: {
  4577. axis: 20,
  4578. item: 10
  4579. },
  4580. padding: 5
  4581. };
  4582. this.dom = {};
  4583. var me = this;
  4584. this.itemsData = null; // DataSet
  4585. this.range = null; // Range or Object {start: number, end: number}
  4586. this.listeners = {
  4587. 'add': function (event, params, senderId) {
  4588. if (senderId != me.id) {
  4589. me._onAdd(params.items);
  4590. }
  4591. },
  4592. 'update': function (event, params, senderId) {
  4593. if (senderId != me.id) {
  4594. me._onUpdate(params.items);
  4595. }
  4596. },
  4597. 'remove': function (event, params, senderId) {
  4598. if (senderId != me.id) {
  4599. me._onRemove(params.items);
  4600. }
  4601. }
  4602. };
  4603. this.items = {}; // object with an Item for every data item
  4604. this.selection = []; // list with the ids of all selected nodes
  4605. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4606. this.stack = new Stack(this, Object.create(this.options));
  4607. this.conversion = null;
  4608. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4609. }
  4610. ItemSet.prototype = new Panel();
  4611. // available item types will be registered here
  4612. ItemSet.types = {
  4613. box: ItemBox,
  4614. range: ItemRange,
  4615. rangeoverflow: ItemRangeOverflow,
  4616. point: ItemPoint
  4617. };
  4618. /**
  4619. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4620. * @param {Object} [options] The following options are available:
  4621. * {String | function} [className]
  4622. * class name for the itemset
  4623. * {String} [type]
  4624. * Default type for the items. Choose from 'box'
  4625. * (default), 'point', or 'range'. The default
  4626. * Style can be overwritten by individual items.
  4627. * {String} align
  4628. * Alignment for the items, only applicable for
  4629. * ItemBox. Choose 'center' (default), 'left', or
  4630. * 'right'.
  4631. * {String} orientation
  4632. * Orientation of the item set. Choose 'top' or
  4633. * 'bottom' (default).
  4634. * {Number} margin.axis
  4635. * Margin between the axis and the items in pixels.
  4636. * Default is 20.
  4637. * {Number} margin.item
  4638. * Margin between items in pixels. Default is 10.
  4639. * {Number} padding
  4640. * Padding of the contents of an item in pixels.
  4641. * Must correspond with the items css. Default is 5.
  4642. */
  4643. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4644. /**
  4645. * Set range (start and end).
  4646. * @param {Range | Object} range A Range or an object containing start and end.
  4647. */
  4648. ItemSet.prototype.setRange = function setRange(range) {
  4649. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4650. throw new TypeError('Range must be an instance of Range, ' +
  4651. 'or an object containing start and end.');
  4652. }
  4653. this.range = range;
  4654. };
  4655. /**
  4656. * Change the item selection, and/or get currently selected items
  4657. * @param {Array} [ids] An array with zero or more ids of the items to be selected.
  4658. * @return {Array} ids The ids of the selected items
  4659. */
  4660. ItemSet.prototype.select = function select(ids) {
  4661. var i, ii, id, item, selection;
  4662. if (ids) {
  4663. if (!Array.isArray(ids)) {
  4664. throw new TypeError('Array expected');
  4665. }
  4666. // unselect currently selected items
  4667. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4668. id = this.selection[i];
  4669. item = this.items[id];
  4670. if (item) item.unselect();
  4671. }
  4672. // select items
  4673. this.selection = [];
  4674. for (i = 0, ii = ids.length; i < ii; i++) {
  4675. id = ids[i];
  4676. item = this.items[id];
  4677. if (item) {
  4678. this.selection.push(id);
  4679. item.select();
  4680. }
  4681. }
  4682. // trigger a select event
  4683. selection = this.selection.concat([]);
  4684. events.trigger(this, 'select', {
  4685. ids: selection
  4686. });
  4687. if (this.controller) {
  4688. this.requestRepaint();
  4689. }
  4690. }
  4691. else {
  4692. selection = this.selection.concat([]);
  4693. }
  4694. return selection;
  4695. };
  4696. /**
  4697. * Deselect a selected item
  4698. * @param {String | Number} id
  4699. * @private
  4700. */
  4701. ItemSet.prototype._deselect = function _deselect(id) {
  4702. var selection = this.selection;
  4703. for (var i = 0, ii = selection.length; i < ii; i++) {
  4704. if (selection[i] == id) { // non-strict comparison!
  4705. selection.splice(i, 1);
  4706. break;
  4707. }
  4708. }
  4709. };
  4710. /**
  4711. * Repaint the component
  4712. * @return {Boolean} changed
  4713. */
  4714. ItemSet.prototype.repaint = function repaint() {
  4715. var changed = 0,
  4716. update = util.updateProperty,
  4717. asSize = util.option.asSize,
  4718. options = this.options,
  4719. orientation = this.getOption('orientation'),
  4720. defaultOptions = this.defaultOptions,
  4721. frame = this.frame;
  4722. if (!frame) {
  4723. frame = document.createElement('div');
  4724. frame.className = 'itemset';
  4725. var className = options.className;
  4726. if (className) {
  4727. util.addClassName(frame, util.option.asString(className));
  4728. }
  4729. // create background panel
  4730. var background = document.createElement('div');
  4731. background.className = 'background';
  4732. frame.appendChild(background);
  4733. this.dom.background = background;
  4734. // create foreground panel
  4735. var foreground = document.createElement('div');
  4736. foreground.className = 'foreground';
  4737. frame.appendChild(foreground);
  4738. this.dom.foreground = foreground;
  4739. // create axis panel
  4740. var axis = document.createElement('div');
  4741. axis.className = 'itemset-axis';
  4742. //frame.appendChild(axis);
  4743. this.dom.axis = axis;
  4744. this.frame = frame;
  4745. changed += 1;
  4746. }
  4747. if (!this.parent) {
  4748. throw new Error('Cannot repaint itemset: no parent attached');
  4749. }
  4750. var parentContainer = this.parent.getContainer();
  4751. if (!parentContainer) {
  4752. throw new Error('Cannot repaint itemset: parent has no container element');
  4753. }
  4754. if (!frame.parentNode) {
  4755. parentContainer.appendChild(frame);
  4756. changed += 1;
  4757. }
  4758. if (!this.dom.axis.parentNode) {
  4759. parentContainer.appendChild(this.dom.axis);
  4760. changed += 1;
  4761. }
  4762. // reposition frame
  4763. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4764. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4765. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4766. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4767. // reposition axis
  4768. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4769. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4770. if (orientation == 'bottom') {
  4771. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4772. }
  4773. else { // orientation == 'top'
  4774. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4775. }
  4776. this._updateConversion();
  4777. var me = this,
  4778. queue = this.queue,
  4779. itemsData = this.itemsData,
  4780. items = this.items,
  4781. dataOptions = {
  4782. // TODO: cleanup
  4783. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  4784. };
  4785. // show/hide added/changed/removed items
  4786. Object.keys(queue).forEach(function (id) {
  4787. //var entry = queue[id];
  4788. var action = queue[id];
  4789. var item = items[id];
  4790. //var item = entry.item;
  4791. //noinspection FallthroughInSwitchStatementJS
  4792. switch (action) {
  4793. case 'add':
  4794. case 'update':
  4795. var itemData = itemsData && itemsData.get(id, dataOptions);
  4796. if (itemData) {
  4797. var type = itemData.type ||
  4798. (itemData.start && itemData.end && 'range') ||
  4799. options.type ||
  4800. 'box';
  4801. var constructor = ItemSet.types[type];
  4802. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4803. if (item) {
  4804. // update item
  4805. if (!constructor || !(item instanceof constructor)) {
  4806. // item type has changed, hide and delete the item
  4807. changed += item.hide();
  4808. item = null;
  4809. }
  4810. else {
  4811. item.data = itemData; // TODO: create a method item.setData ?
  4812. changed++;
  4813. }
  4814. }
  4815. if (!item) {
  4816. // create item
  4817. if (constructor) {
  4818. item = new constructor(me, itemData, options, defaultOptions);
  4819. item.id = id;
  4820. changed++;
  4821. }
  4822. else {
  4823. throw new TypeError('Unknown item type "' + type + '"');
  4824. }
  4825. }
  4826. // force a repaint (not only a reposition)
  4827. item.repaint();
  4828. items[id] = item;
  4829. }
  4830. // update queue
  4831. delete queue[id];
  4832. break;
  4833. case 'remove':
  4834. if (item) {
  4835. // remove the item from the set selected items
  4836. if (item.selected) {
  4837. me._deselect(id);
  4838. }
  4839. // remove DOM of the item
  4840. changed += item.hide();
  4841. }
  4842. // update lists
  4843. delete items[id];
  4844. delete queue[id];
  4845. break;
  4846. default:
  4847. console.log('Error: unknown action "' + action + '"');
  4848. }
  4849. });
  4850. // reposition all items. Show items only when in the visible area
  4851. util.forEach(this.items, function (item) {
  4852. if (item.visible) {
  4853. changed += item.show();
  4854. item.reposition();
  4855. }
  4856. else {
  4857. changed += item.hide();
  4858. }
  4859. });
  4860. return (changed > 0);
  4861. };
  4862. /**
  4863. * Get the foreground container element
  4864. * @return {HTMLElement} foreground
  4865. */
  4866. ItemSet.prototype.getForeground = function getForeground() {
  4867. return this.dom.foreground;
  4868. };
  4869. /**
  4870. * Get the background container element
  4871. * @return {HTMLElement} background
  4872. */
  4873. ItemSet.prototype.getBackground = function getBackground() {
  4874. return this.dom.background;
  4875. };
  4876. /**
  4877. * Get the axis container element
  4878. * @return {HTMLElement} axis
  4879. */
  4880. ItemSet.prototype.getAxis = function getAxis() {
  4881. return this.dom.axis;
  4882. };
  4883. /**
  4884. * Reflow the component
  4885. * @return {Boolean} resized
  4886. */
  4887. ItemSet.prototype.reflow = function reflow () {
  4888. var changed = 0,
  4889. options = this.options,
  4890. marginAxis = options.margin && options.margin.axis || this.defaultOptions.margin.axis,
  4891. marginItem = options.margin && options.margin.item || this.defaultOptions.margin.item,
  4892. update = util.updateProperty,
  4893. asNumber = util.option.asNumber,
  4894. asSize = util.option.asSize,
  4895. frame = this.frame;
  4896. if (frame) {
  4897. this._updateConversion();
  4898. util.forEach(this.items, function (item) {
  4899. changed += item.reflow();
  4900. });
  4901. // TODO: stack.update should be triggered via an event, in stack itself
  4902. // TODO: only update the stack when there are changed items
  4903. this.stack.update();
  4904. var maxHeight = asNumber(options.maxHeight);
  4905. var fixedHeight = (asSize(options.height) != null);
  4906. var height;
  4907. if (fixedHeight) {
  4908. height = frame.offsetHeight;
  4909. }
  4910. else {
  4911. // height is not specified, determine the height from the height and positioned items
  4912. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4913. if (visibleItems.length) {
  4914. var min = visibleItems[0].top;
  4915. var max = visibleItems[0].top + visibleItems[0].height;
  4916. util.forEach(visibleItems, function (item) {
  4917. min = Math.min(min, item.top);
  4918. max = Math.max(max, (item.top + item.height));
  4919. });
  4920. height = (max - min) + marginAxis + marginItem;
  4921. }
  4922. else {
  4923. height = marginAxis + marginItem;
  4924. }
  4925. }
  4926. if (maxHeight != null) {
  4927. height = Math.min(height, maxHeight);
  4928. }
  4929. changed += update(this, 'height', height);
  4930. // calculate height from items
  4931. changed += update(this, 'top', frame.offsetTop);
  4932. changed += update(this, 'left', frame.offsetLeft);
  4933. changed += update(this, 'width', frame.offsetWidth);
  4934. }
  4935. else {
  4936. changed += 1;
  4937. }
  4938. return (changed > 0);
  4939. };
  4940. /**
  4941. * Hide this component from the DOM
  4942. * @return {Boolean} changed
  4943. */
  4944. ItemSet.prototype.hide = function hide() {
  4945. var changed = false;
  4946. // remove the DOM
  4947. if (this.frame && this.frame.parentNode) {
  4948. this.frame.parentNode.removeChild(this.frame);
  4949. changed = true;
  4950. }
  4951. if (this.dom.axis && this.dom.axis.parentNode) {
  4952. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4953. changed = true;
  4954. }
  4955. return changed;
  4956. };
  4957. /**
  4958. * Set items
  4959. * @param {vis.DataSet | null} items
  4960. */
  4961. ItemSet.prototype.setItems = function setItems(items) {
  4962. var me = this,
  4963. ids,
  4964. oldItemsData = this.itemsData;
  4965. // replace the dataset
  4966. if (!items) {
  4967. this.itemsData = null;
  4968. }
  4969. else if (items instanceof DataSet || items instanceof DataView) {
  4970. this.itemsData = items;
  4971. }
  4972. else {
  4973. throw new TypeError('Data must be an instance of DataSet');
  4974. }
  4975. if (oldItemsData) {
  4976. // unsubscribe from old dataset
  4977. util.forEach(this.listeners, function (callback, event) {
  4978. oldItemsData.unsubscribe(event, callback);
  4979. });
  4980. // remove all drawn items
  4981. ids = oldItemsData.getIds();
  4982. this._onRemove(ids);
  4983. }
  4984. if (this.itemsData) {
  4985. // subscribe to new dataset
  4986. var id = this.id;
  4987. util.forEach(this.listeners, function (callback, event) {
  4988. me.itemsData.subscribe(event, callback, id);
  4989. });
  4990. // draw all new items
  4991. ids = this.itemsData.getIds();
  4992. this._onAdd(ids);
  4993. }
  4994. };
  4995. /**
  4996. * Get the current items items
  4997. * @returns {vis.DataSet | null}
  4998. */
  4999. ItemSet.prototype.getItems = function getItems() {
  5000. return this.itemsData;
  5001. };
  5002. /**
  5003. * Handle updated items
  5004. * @param {Number[]} ids
  5005. * @private
  5006. */
  5007. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  5008. this._toQueue('update', ids);
  5009. };
  5010. /**
  5011. * Handle changed items
  5012. * @param {Number[]} ids
  5013. * @private
  5014. */
  5015. ItemSet.prototype._onAdd = function _onAdd(ids) {
  5016. this._toQueue('add', ids);
  5017. };
  5018. /**
  5019. * Handle removed items
  5020. * @param {Number[]} ids
  5021. * @private
  5022. */
  5023. ItemSet.prototype._onRemove = function _onRemove(ids) {
  5024. this._toQueue('remove', ids);
  5025. };
  5026. /**
  5027. * Put items in the queue to be added/updated/remove
  5028. * @param {String} action can be 'add', 'update', 'remove'
  5029. * @param {Number[]} ids
  5030. */
  5031. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  5032. var queue = this.queue;
  5033. ids.forEach(function (id) {
  5034. queue[id] = action;
  5035. });
  5036. if (this.controller) {
  5037. //this.requestReflow();
  5038. this.requestRepaint();
  5039. }
  5040. };
  5041. /**
  5042. * Calculate the scale and offset to convert a position on screen to the
  5043. * corresponding date and vice versa.
  5044. * After the method _updateConversion is executed once, the methods toTime
  5045. * and toScreen can be used.
  5046. * @private
  5047. */
  5048. ItemSet.prototype._updateConversion = function _updateConversion() {
  5049. var range = this.range;
  5050. if (!range) {
  5051. throw new Error('No range configured');
  5052. }
  5053. if (range.conversion) {
  5054. this.conversion = range.conversion(this.width);
  5055. }
  5056. else {
  5057. this.conversion = Range.conversion(range.start, range.end, this.width);
  5058. }
  5059. };
  5060. /**
  5061. * Convert a position on screen (pixels) to a datetime
  5062. * Before this method can be used, the method _updateConversion must be
  5063. * executed once.
  5064. * @param {int} x Position on the screen in pixels
  5065. * @return {Date} time The datetime the corresponds with given position x
  5066. */
  5067. ItemSet.prototype.toTime = function toTime(x) {
  5068. var conversion = this.conversion;
  5069. return new Date(x / conversion.scale + conversion.offset);
  5070. };
  5071. /**
  5072. * Convert a datetime (Date object) into a position on the screen
  5073. * Before this method can be used, the method _updateConversion must be
  5074. * executed once.
  5075. * @param {Date} time A date
  5076. * @return {int} x The position on the screen in pixels which corresponds
  5077. * with the given date.
  5078. */
  5079. ItemSet.prototype.toScreen = function toScreen(time) {
  5080. var conversion = this.conversion;
  5081. return (time.valueOf() - conversion.offset) * conversion.scale;
  5082. };
  5083. /**
  5084. * @constructor Item
  5085. * @param {ItemSet} parent
  5086. * @param {Object} data Object containing (optional) parameters type,
  5087. * start, end, content, group, className.
  5088. * @param {Object} [options] Options to set initial property values
  5089. * @param {Object} [defaultOptions] default options
  5090. * // TODO: describe available options
  5091. */
  5092. function Item (parent, data, options, defaultOptions) {
  5093. this.parent = parent;
  5094. this.data = data;
  5095. this.dom = null;
  5096. this.options = options || {};
  5097. this.defaultOptions = defaultOptions || {};
  5098. this.selected = false;
  5099. this.visible = false;
  5100. this.top = 0;
  5101. this.left = 0;
  5102. this.width = 0;
  5103. this.height = 0;
  5104. }
  5105. /**
  5106. * Select current item
  5107. */
  5108. Item.prototype.select = function select() {
  5109. this.selected = true;
  5110. if (this.visible) this.repaint();
  5111. };
  5112. /**
  5113. * Unselect current item
  5114. */
  5115. Item.prototype.unselect = function unselect() {
  5116. this.selected = false;
  5117. if (this.visible) this.repaint();
  5118. };
  5119. /**
  5120. * Show the Item in the DOM (when not already visible)
  5121. * @return {Boolean} changed
  5122. */
  5123. Item.prototype.show = function show() {
  5124. return false;
  5125. };
  5126. /**
  5127. * Hide the Item from the DOM (when visible)
  5128. * @return {Boolean} changed
  5129. */
  5130. Item.prototype.hide = function hide() {
  5131. return false;
  5132. };
  5133. /**
  5134. * Repaint the item
  5135. * @return {Boolean} changed
  5136. */
  5137. Item.prototype.repaint = function repaint() {
  5138. // should be implemented by the item
  5139. return false;
  5140. };
  5141. /**
  5142. * Reflow the item
  5143. * @return {Boolean} resized
  5144. */
  5145. Item.prototype.reflow = function reflow() {
  5146. // should be implemented by the item
  5147. return false;
  5148. };
  5149. /**
  5150. * Return the items width
  5151. * @return {Integer} width
  5152. */
  5153. Item.prototype.getWidth = function getWidth() {
  5154. return this.width;
  5155. }
  5156. /**
  5157. * @constructor ItemBox
  5158. * @extends Item
  5159. * @param {ItemSet} parent
  5160. * @param {Object} data Object containing parameters start
  5161. * content, className.
  5162. * @param {Object} [options] Options to set initial property values
  5163. * @param {Object} [defaultOptions] default options
  5164. * // TODO: describe available options
  5165. */
  5166. function ItemBox (parent, data, options, defaultOptions) {
  5167. this.props = {
  5168. dot: {
  5169. left: 0,
  5170. top: 0,
  5171. width: 0,
  5172. height: 0
  5173. },
  5174. line: {
  5175. top: 0,
  5176. left: 0,
  5177. width: 0,
  5178. height: 0
  5179. }
  5180. };
  5181. Item.call(this, parent, data, options, defaultOptions);
  5182. }
  5183. ItemBox.prototype = new Item (null, null);
  5184. /**
  5185. * Repaint the item
  5186. * @return {Boolean} changed
  5187. */
  5188. ItemBox.prototype.repaint = function repaint() {
  5189. // TODO: make an efficient repaint
  5190. var changed = false;
  5191. var dom = this.dom;
  5192. if (!dom) {
  5193. this._create();
  5194. dom = this.dom;
  5195. changed = true;
  5196. }
  5197. if (dom) {
  5198. if (!this.parent) {
  5199. throw new Error('Cannot repaint item: no parent attached');
  5200. }
  5201. if (!dom.box.parentNode) {
  5202. var foreground = this.parent.getForeground();
  5203. if (!foreground) {
  5204. throw new Error('Cannot repaint time axis: ' +
  5205. 'parent has no foreground container element');
  5206. }
  5207. foreground.appendChild(dom.box);
  5208. changed = true;
  5209. }
  5210. if (!dom.line.parentNode) {
  5211. var background = this.parent.getBackground();
  5212. if (!background) {
  5213. throw new Error('Cannot repaint time axis: ' +
  5214. 'parent has no background container element');
  5215. }
  5216. background.appendChild(dom.line);
  5217. changed = true;
  5218. }
  5219. if (!dom.dot.parentNode) {
  5220. var axis = this.parent.getAxis();
  5221. if (!background) {
  5222. throw new Error('Cannot repaint time axis: ' +
  5223. 'parent has no axis container element');
  5224. }
  5225. axis.appendChild(dom.dot);
  5226. changed = true;
  5227. }
  5228. // update contents
  5229. if (this.data.content != this.content) {
  5230. this.content = this.data.content;
  5231. if (this.content instanceof Element) {
  5232. dom.content.innerHTML = '';
  5233. dom.content.appendChild(this.content);
  5234. }
  5235. else if (this.data.content != undefined) {
  5236. dom.content.innerHTML = this.content;
  5237. }
  5238. else {
  5239. throw new Error('Property "content" missing in item ' + this.data.id);
  5240. }
  5241. changed = true;
  5242. }
  5243. // update class
  5244. var className = (this.data.className? ' ' + this.data.className : '') +
  5245. (this.selected ? ' selected' : '');
  5246. if (this.className != className) {
  5247. this.className = className;
  5248. dom.box.className = 'item box' + className;
  5249. dom.line.className = 'item line' + className;
  5250. dom.dot.className = 'item dot' + className;
  5251. changed = true;
  5252. }
  5253. }
  5254. return changed;
  5255. };
  5256. /**
  5257. * Show the item in the DOM (when not already visible). The items DOM will
  5258. * be created when needed.
  5259. * @return {Boolean} changed
  5260. */
  5261. ItemBox.prototype.show = function show() {
  5262. if (!this.dom || !this.dom.box.parentNode) {
  5263. return this.repaint();
  5264. }
  5265. else {
  5266. return false;
  5267. }
  5268. };
  5269. /**
  5270. * Hide the item from the DOM (when visible)
  5271. * @return {Boolean} changed
  5272. */
  5273. ItemBox.prototype.hide = function hide() {
  5274. var changed = false,
  5275. dom = this.dom;
  5276. if (dom) {
  5277. if (dom.box.parentNode) {
  5278. dom.box.parentNode.removeChild(dom.box);
  5279. changed = true;
  5280. }
  5281. if (dom.line.parentNode) {
  5282. dom.line.parentNode.removeChild(dom.line);
  5283. }
  5284. if (dom.dot.parentNode) {
  5285. dom.dot.parentNode.removeChild(dom.dot);
  5286. }
  5287. }
  5288. return changed;
  5289. };
  5290. /**
  5291. * Reflow the item: calculate its actual size and position from the DOM
  5292. * @return {boolean} resized returns true if the axis is resized
  5293. * @override
  5294. */
  5295. ItemBox.prototype.reflow = function reflow() {
  5296. var changed = 0,
  5297. update,
  5298. dom,
  5299. props,
  5300. options,
  5301. margin,
  5302. start,
  5303. align,
  5304. orientation,
  5305. top,
  5306. left,
  5307. data,
  5308. range;
  5309. if (this.data.start == undefined) {
  5310. throw new Error('Property "start" missing in item ' + this.data.id);
  5311. }
  5312. data = this.data;
  5313. range = this.parent && this.parent.range;
  5314. if (data && range) {
  5315. // TODO: account for the width of the item
  5316. var interval = (range.end - range.start);
  5317. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  5318. }
  5319. else {
  5320. this.visible = false;
  5321. }
  5322. if (this.visible) {
  5323. dom = this.dom;
  5324. if (dom) {
  5325. update = util.updateProperty;
  5326. props = this.props;
  5327. options = this.options;
  5328. start = this.parent.toScreen(this.data.start);
  5329. align = options.align || this.defaultOptions.align;
  5330. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5331. orientation = options.orientation || this.defaultOptions.orientation;
  5332. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5333. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5334. changed += update(props.line, 'width', dom.line.offsetWidth);
  5335. changed += update(props.line, 'height', dom.line.offsetHeight);
  5336. changed += update(props.line, 'top', dom.line.offsetTop);
  5337. changed += update(this, 'width', dom.box.offsetWidth);
  5338. changed += update(this, 'height', dom.box.offsetHeight);
  5339. if (align == 'right') {
  5340. left = start - this.width;
  5341. }
  5342. else if (align == 'left') {
  5343. left = start;
  5344. }
  5345. else {
  5346. // default or 'center'
  5347. left = start - this.width / 2;
  5348. }
  5349. changed += update(this, 'left', left);
  5350. changed += update(props.line, 'left', start - props.line.width / 2);
  5351. changed += update(props.dot, 'left', start - props.dot.width / 2);
  5352. changed += update(props.dot, 'top', -props.dot.height / 2);
  5353. if (orientation == 'top') {
  5354. top = margin;
  5355. changed += update(this, 'top', top);
  5356. }
  5357. else {
  5358. // default or 'bottom'
  5359. var parentHeight = this.parent.height;
  5360. top = parentHeight - this.height - margin;
  5361. changed += update(this, 'top', top);
  5362. }
  5363. }
  5364. else {
  5365. changed += 1;
  5366. }
  5367. }
  5368. return (changed > 0);
  5369. };
  5370. /**
  5371. * Create an items DOM
  5372. * @private
  5373. */
  5374. ItemBox.prototype._create = function _create() {
  5375. var dom = this.dom;
  5376. if (!dom) {
  5377. this.dom = dom = {};
  5378. // create the box
  5379. dom.box = document.createElement('DIV');
  5380. // className is updated in repaint()
  5381. // contents box (inside the background box). used for making margins
  5382. dom.content = document.createElement('DIV');
  5383. dom.content.className = 'content';
  5384. dom.box.appendChild(dom.content);
  5385. // line to axis
  5386. dom.line = document.createElement('DIV');
  5387. dom.line.className = 'line';
  5388. // dot on axis
  5389. dom.dot = document.createElement('DIV');
  5390. dom.dot.className = 'dot';
  5391. }
  5392. };
  5393. /**
  5394. * Reposition the item, recalculate its left, top, and width, using the current
  5395. * range and size of the items itemset
  5396. * @override
  5397. */
  5398. ItemBox.prototype.reposition = function reposition() {
  5399. var dom = this.dom,
  5400. props = this.props,
  5401. orientation = this.options.orientation || this.defaultOptions.orientation;
  5402. if (dom) {
  5403. var box = dom.box,
  5404. line = dom.line,
  5405. dot = dom.dot;
  5406. box.style.left = this.left + 'px';
  5407. box.style.top = this.top + 'px';
  5408. line.style.left = props.line.left + 'px';
  5409. if (orientation == 'top') {
  5410. line.style.top = 0 + 'px';
  5411. line.style.height = this.top + 'px';
  5412. }
  5413. else {
  5414. // orientation 'bottom'
  5415. line.style.top = (this.top + this.height) + 'px';
  5416. line.style.height = Math.max(this.parent.height - this.top - this.height +
  5417. this.props.dot.height / 2, 0) + 'px';
  5418. }
  5419. dot.style.left = props.dot.left + 'px';
  5420. dot.style.top = props.dot.top + 'px';
  5421. }
  5422. };
  5423. /**
  5424. * @constructor ItemPoint
  5425. * @extends Item
  5426. * @param {ItemSet} parent
  5427. * @param {Object} data Object containing parameters start
  5428. * content, className.
  5429. * @param {Object} [options] Options to set initial property values
  5430. * @param {Object} [defaultOptions] default options
  5431. * // TODO: describe available options
  5432. */
  5433. function ItemPoint (parent, data, options, defaultOptions) {
  5434. this.props = {
  5435. dot: {
  5436. top: 0,
  5437. width: 0,
  5438. height: 0
  5439. },
  5440. content: {
  5441. height: 0,
  5442. marginLeft: 0
  5443. }
  5444. };
  5445. Item.call(this, parent, data, options, defaultOptions);
  5446. }
  5447. ItemPoint.prototype = new Item (null, null);
  5448. /**
  5449. * Repaint the item
  5450. * @return {Boolean} changed
  5451. */
  5452. ItemPoint.prototype.repaint = function repaint() {
  5453. // TODO: make an efficient repaint
  5454. var changed = false;
  5455. var dom = this.dom;
  5456. if (!dom) {
  5457. this._create();
  5458. dom = this.dom;
  5459. changed = true;
  5460. }
  5461. if (dom) {
  5462. if (!this.parent) {
  5463. throw new Error('Cannot repaint item: no parent attached');
  5464. }
  5465. var foreground = this.parent.getForeground();
  5466. if (!foreground) {
  5467. throw new Error('Cannot repaint time axis: ' +
  5468. 'parent has no foreground container element');
  5469. }
  5470. if (!dom.point.parentNode) {
  5471. foreground.appendChild(dom.point);
  5472. foreground.appendChild(dom.point);
  5473. changed = true;
  5474. }
  5475. // update contents
  5476. if (this.data.content != this.content) {
  5477. this.content = this.data.content;
  5478. if (this.content instanceof Element) {
  5479. dom.content.innerHTML = '';
  5480. dom.content.appendChild(this.content);
  5481. }
  5482. else if (this.data.content != undefined) {
  5483. dom.content.innerHTML = this.content;
  5484. }
  5485. else {
  5486. throw new Error('Property "content" missing in item ' + this.data.id);
  5487. }
  5488. changed = true;
  5489. }
  5490. // update class
  5491. var className = (this.data.className? ' ' + this.data.className : '') +
  5492. (this.selected ? ' selected' : '');
  5493. if (this.className != className) {
  5494. this.className = className;
  5495. dom.point.className = 'item point' + className;
  5496. changed = true;
  5497. }
  5498. }
  5499. return changed;
  5500. };
  5501. /**
  5502. * Show the item in the DOM (when not already visible). The items DOM will
  5503. * be created when needed.
  5504. * @return {Boolean} changed
  5505. */
  5506. ItemPoint.prototype.show = function show() {
  5507. if (!this.dom || !this.dom.point.parentNode) {
  5508. return this.repaint();
  5509. }
  5510. else {
  5511. return false;
  5512. }
  5513. };
  5514. /**
  5515. * Hide the item from the DOM (when visible)
  5516. * @return {Boolean} changed
  5517. */
  5518. ItemPoint.prototype.hide = function hide() {
  5519. var changed = false,
  5520. dom = this.dom;
  5521. if (dom) {
  5522. if (dom.point.parentNode) {
  5523. dom.point.parentNode.removeChild(dom.point);
  5524. changed = true;
  5525. }
  5526. }
  5527. return changed;
  5528. };
  5529. /**
  5530. * Reflow the item: calculate its actual size from the DOM
  5531. * @return {boolean} resized returns true if the axis is resized
  5532. * @override
  5533. */
  5534. ItemPoint.prototype.reflow = function reflow() {
  5535. var changed = 0,
  5536. update,
  5537. dom,
  5538. props,
  5539. options,
  5540. margin,
  5541. orientation,
  5542. start,
  5543. top,
  5544. data,
  5545. range;
  5546. if (this.data.start == undefined) {
  5547. throw new Error('Property "start" missing in item ' + this.data.id);
  5548. }
  5549. data = this.data;
  5550. range = this.parent && this.parent.range;
  5551. if (data && range) {
  5552. // TODO: account for the width of the item
  5553. var interval = (range.end - range.start);
  5554. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  5555. }
  5556. else {
  5557. this.visible = false;
  5558. }
  5559. if (this.visible) {
  5560. dom = this.dom;
  5561. if (dom) {
  5562. update = util.updateProperty;
  5563. props = this.props;
  5564. options = this.options;
  5565. orientation = options.orientation || this.defaultOptions.orientation;
  5566. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5567. start = this.parent.toScreen(this.data.start);
  5568. changed += update(this, 'width', dom.point.offsetWidth);
  5569. changed += update(this, 'height', dom.point.offsetHeight);
  5570. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5571. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5572. changed += update(props.content, 'height', dom.content.offsetHeight);
  5573. if (orientation == 'top') {
  5574. top = margin;
  5575. }
  5576. else {
  5577. // default or 'bottom'
  5578. var parentHeight = this.parent.height;
  5579. top = Math.max(parentHeight - this.height - margin, 0);
  5580. }
  5581. changed += update(this, 'top', top);
  5582. changed += update(this, 'left', start - props.dot.width / 2);
  5583. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5584. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5585. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5586. }
  5587. else {
  5588. changed += 1;
  5589. }
  5590. }
  5591. return (changed > 0);
  5592. };
  5593. /**
  5594. * Create an items DOM
  5595. * @private
  5596. */
  5597. ItemPoint.prototype._create = function _create() {
  5598. var dom = this.dom;
  5599. if (!dom) {
  5600. this.dom = dom = {};
  5601. // background box
  5602. dom.point = document.createElement('div');
  5603. // className is updated in repaint()
  5604. // contents box, right from the dot
  5605. dom.content = document.createElement('div');
  5606. dom.content.className = 'content';
  5607. dom.point.appendChild(dom.content);
  5608. // dot at start
  5609. dom.dot = document.createElement('div');
  5610. dom.dot.className = 'dot';
  5611. dom.point.appendChild(dom.dot);
  5612. }
  5613. };
  5614. /**
  5615. * Reposition the item, recalculate its left, top, and width, using the current
  5616. * range and size of the items itemset
  5617. * @override
  5618. */
  5619. ItemPoint.prototype.reposition = function reposition() {
  5620. var dom = this.dom,
  5621. props = this.props;
  5622. if (dom) {
  5623. dom.point.style.top = this.top + 'px';
  5624. dom.point.style.left = this.left + 'px';
  5625. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5626. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5627. dom.dot.style.top = props.dot.top + 'px';
  5628. }
  5629. };
  5630. /**
  5631. * @constructor ItemRange
  5632. * @extends Item
  5633. * @param {ItemSet} parent
  5634. * @param {Object} data Object containing parameters start, end
  5635. * content, className.
  5636. * @param {Object} [options] Options to set initial property values
  5637. * @param {Object} [defaultOptions] default options
  5638. * // TODO: describe available options
  5639. */
  5640. function ItemRange (parent, data, options, defaultOptions) {
  5641. this.props = {
  5642. content: {
  5643. left: 0,
  5644. width: 0
  5645. }
  5646. };
  5647. Item.call(this, parent, data, options, defaultOptions);
  5648. }
  5649. ItemRange.prototype = new Item (null, null);
  5650. /**
  5651. * Repaint the item
  5652. * @return {Boolean} changed
  5653. */
  5654. ItemRange.prototype.repaint = function repaint() {
  5655. // TODO: make an efficient repaint
  5656. var changed = false;
  5657. var dom = this.dom;
  5658. if (!dom) {
  5659. this._create();
  5660. dom = this.dom;
  5661. changed = true;
  5662. }
  5663. if (dom) {
  5664. if (!this.parent) {
  5665. throw new Error('Cannot repaint item: no parent attached');
  5666. }
  5667. var foreground = this.parent.getForeground();
  5668. if (!foreground) {
  5669. throw new Error('Cannot repaint time axis: ' +
  5670. 'parent has no foreground container element');
  5671. }
  5672. if (!dom.box.parentNode) {
  5673. foreground.appendChild(dom.box);
  5674. changed = true;
  5675. }
  5676. // update content
  5677. if (this.data.content != this.content) {
  5678. this.content = this.data.content;
  5679. if (this.content instanceof Element) {
  5680. dom.content.innerHTML = '';
  5681. dom.content.appendChild(this.content);
  5682. }
  5683. else if (this.data.content != undefined) {
  5684. dom.content.innerHTML = this.content;
  5685. }
  5686. else {
  5687. throw new Error('Property "content" missing in item ' + this.data.id);
  5688. }
  5689. changed = true;
  5690. }
  5691. // update class
  5692. var className = (this.data.className? ' ' + this.data.className : '') +
  5693. (this.selected ? ' selected' : '');
  5694. if (this.className != className) {
  5695. this.className = className;
  5696. dom.box.className = 'item range' + className;
  5697. changed = true;
  5698. }
  5699. }
  5700. return changed;
  5701. };
  5702. /**
  5703. * Show the item in the DOM (when not already visible). The items DOM will
  5704. * be created when needed.
  5705. * @return {Boolean} changed
  5706. */
  5707. ItemRange.prototype.show = function show() {
  5708. if (!this.dom || !this.dom.box.parentNode) {
  5709. return this.repaint();
  5710. }
  5711. else {
  5712. return false;
  5713. }
  5714. };
  5715. /**
  5716. * Hide the item from the DOM (when visible)
  5717. * @return {Boolean} changed
  5718. */
  5719. ItemRange.prototype.hide = function hide() {
  5720. var changed = false,
  5721. dom = this.dom;
  5722. if (dom) {
  5723. if (dom.box.parentNode) {
  5724. dom.box.parentNode.removeChild(dom.box);
  5725. changed = true;
  5726. }
  5727. }
  5728. return changed;
  5729. };
  5730. /**
  5731. * Reflow the item: calculate its actual size from the DOM
  5732. * @return {boolean} resized returns true if the axis is resized
  5733. * @override
  5734. */
  5735. ItemRange.prototype.reflow = function reflow() {
  5736. var changed = 0,
  5737. dom,
  5738. props,
  5739. options,
  5740. margin,
  5741. padding,
  5742. parent,
  5743. start,
  5744. end,
  5745. data,
  5746. range,
  5747. update,
  5748. box,
  5749. parentWidth,
  5750. contentLeft,
  5751. orientation,
  5752. top;
  5753. if (this.data.start == undefined) {
  5754. throw new Error('Property "start" missing in item ' + this.data.id);
  5755. }
  5756. if (this.data.end == undefined) {
  5757. throw new Error('Property "end" missing in item ' + this.data.id);
  5758. }
  5759. data = this.data;
  5760. range = this.parent && this.parent.range;
  5761. if (data && range) {
  5762. // TODO: account for the width of the item. Take some margin
  5763. this.visible = (data.start < range.end) && (data.end > range.start);
  5764. }
  5765. else {
  5766. this.visible = false;
  5767. }
  5768. if (this.visible) {
  5769. dom = this.dom;
  5770. if (dom) {
  5771. props = this.props;
  5772. options = this.options;
  5773. parent = this.parent;
  5774. start = parent.toScreen(this.data.start);
  5775. end = parent.toScreen(this.data.end);
  5776. update = util.updateProperty;
  5777. box = dom.box;
  5778. parentWidth = parent.width;
  5779. orientation = options.orientation || this.defaultOptions.orientation;
  5780. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5781. padding = options.padding || this.defaultOptions.padding;
  5782. changed += update(props.content, 'width', dom.content.offsetWidth);
  5783. changed += update(this, 'height', box.offsetHeight);
  5784. // limit the width of the this, as browsers cannot draw very wide divs
  5785. if (start < -parentWidth) {
  5786. start = -parentWidth;
  5787. }
  5788. if (end > 2 * parentWidth) {
  5789. end = 2 * parentWidth;
  5790. }
  5791. // when range exceeds left of the window, position the contents at the left of the visible area
  5792. if (start < 0) {
  5793. contentLeft = Math.min(-start,
  5794. (end - start - props.content.width - 2 * padding));
  5795. // TODO: remove the need for options.padding. it's terrible.
  5796. }
  5797. else {
  5798. contentLeft = 0;
  5799. }
  5800. changed += update(props.content, 'left', contentLeft);
  5801. if (orientation == 'top') {
  5802. top = margin;
  5803. changed += update(this, 'top', top);
  5804. }
  5805. else {
  5806. // default or 'bottom'
  5807. top = parent.height - this.height - margin;
  5808. changed += update(this, 'top', top);
  5809. }
  5810. changed += update(this, 'left', start);
  5811. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  5812. }
  5813. else {
  5814. changed += 1;
  5815. }
  5816. }
  5817. return (changed > 0);
  5818. };
  5819. /**
  5820. * Create an items DOM
  5821. * @private
  5822. */
  5823. ItemRange.prototype._create = function _create() {
  5824. var dom = this.dom;
  5825. if (!dom) {
  5826. this.dom = dom = {};
  5827. // background box
  5828. dom.box = document.createElement('div');
  5829. // className is updated in repaint()
  5830. // contents box
  5831. dom.content = document.createElement('div');
  5832. dom.content.className = 'content';
  5833. dom.box.appendChild(dom.content);
  5834. }
  5835. };
  5836. /**
  5837. * Reposition the item, recalculate its left, top, and width, using the current
  5838. * range and size of the items itemset
  5839. * @override
  5840. */
  5841. ItemRange.prototype.reposition = function reposition() {
  5842. var dom = this.dom,
  5843. props = this.props;
  5844. if (dom) {
  5845. dom.box.style.top = this.top + 'px';
  5846. dom.box.style.left = this.left + 'px';
  5847. dom.box.style.width = this.width + 'px';
  5848. dom.content.style.left = props.content.left + 'px';
  5849. }
  5850. };
  5851. /**
  5852. * @constructor ItemRangeOverflow
  5853. * @extends ItemRange
  5854. * @param {ItemSet} parent
  5855. * @param {Object} data Object containing parameters start, end
  5856. * content, className.
  5857. * @param {Object} [options] Options to set initial property values
  5858. * @param {Object} [defaultOptions] default options
  5859. * // TODO: describe available options
  5860. */
  5861. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  5862. this.props = {
  5863. content: {
  5864. left: 0,
  5865. width: 0
  5866. }
  5867. };
  5868. ItemRange.call(this, parent, data, options, defaultOptions);
  5869. }
  5870. ItemRangeOverflow.prototype = new ItemRange (null, null);
  5871. /**
  5872. * Repaint the item
  5873. * @return {Boolean} changed
  5874. */
  5875. ItemRangeOverflow.prototype.repaint = function repaint() {
  5876. // TODO: make an efficient repaint
  5877. var changed = false;
  5878. var dom = this.dom;
  5879. if (!dom) {
  5880. this._create();
  5881. dom = this.dom;
  5882. changed = true;
  5883. }
  5884. if (dom) {
  5885. if (!this.parent) {
  5886. throw new Error('Cannot repaint item: no parent attached');
  5887. }
  5888. var foreground = this.parent.getForeground();
  5889. if (!foreground) {
  5890. throw new Error('Cannot repaint time axis: ' +
  5891. 'parent has no foreground container element');
  5892. }
  5893. if (!dom.box.parentNode) {
  5894. foreground.appendChild(dom.box);
  5895. changed = true;
  5896. }
  5897. // update content
  5898. if (this.data.content != this.content) {
  5899. this.content = this.data.content;
  5900. if (this.content instanceof Element) {
  5901. dom.content.innerHTML = '';
  5902. dom.content.appendChild(this.content);
  5903. }
  5904. else if (this.data.content != undefined) {
  5905. dom.content.innerHTML = this.content;
  5906. }
  5907. else {
  5908. throw new Error('Property "content" missing in item ' + this.data.id);
  5909. }
  5910. changed = true;
  5911. }
  5912. // update class
  5913. var className = this.data.className ? (' ' + this.data.className) : '';
  5914. if (this.className != className) {
  5915. this.className = className;
  5916. dom.box.className = 'item rangeoverflow' + className;
  5917. changed = true;
  5918. }
  5919. }
  5920. return changed;
  5921. };
  5922. /**
  5923. * Return the items width
  5924. * @return {Number} width
  5925. */
  5926. ItemRangeOverflow.prototype.getWidth = function getWidth() {
  5927. if (this.props.content !== undefined && this.width < this.props.content.width)
  5928. return this.props.content.width;
  5929. else
  5930. return this.width;
  5931. };
  5932. /**
  5933. * @constructor Group
  5934. * @param {GroupSet} parent
  5935. * @param {Number | String} groupId
  5936. * @param {Object} [options] Options to set initial property values
  5937. * // TODO: describe available options
  5938. * @extends Component
  5939. */
  5940. function Group (parent, groupId, options) {
  5941. this.id = util.randomUUID();
  5942. this.parent = parent;
  5943. this.groupId = groupId;
  5944. this.itemset = null; // ItemSet
  5945. this.options = options || {};
  5946. this.options.top = 0;
  5947. this.props = {
  5948. label: {
  5949. width: 0,
  5950. height: 0
  5951. }
  5952. };
  5953. this.top = 0;
  5954. this.left = 0;
  5955. this.width = 0;
  5956. this.height = 0;
  5957. }
  5958. Group.prototype = new Component();
  5959. // TODO: comment
  5960. Group.prototype.setOptions = Component.prototype.setOptions;
  5961. /**
  5962. * Get the container element of the panel, which can be used by a child to
  5963. * add its own widgets.
  5964. * @returns {HTMLElement} container
  5965. */
  5966. Group.prototype.getContainer = function () {
  5967. return this.parent.getContainer();
  5968. };
  5969. /**
  5970. * Set item set for the group. The group will create a view on the itemset,
  5971. * filtered by the groups id.
  5972. * @param {DataSet | DataView} items
  5973. */
  5974. Group.prototype.setItems = function setItems(items) {
  5975. if (this.itemset) {
  5976. // remove current item set
  5977. this.itemset.hide();
  5978. this.itemset.setItems();
  5979. this.parent.controller.remove(this.itemset);
  5980. this.itemset = null;
  5981. }
  5982. if (items) {
  5983. var groupId = this.groupId;
  5984. var itemsetOptions = Object.create(this.options);
  5985. this.itemset = new ItemSet(this, null, itemsetOptions);
  5986. this.itemset.setRange(this.parent.range);
  5987. this.view = new DataView(items, {
  5988. filter: function (item) {
  5989. return item.group == groupId;
  5990. }
  5991. });
  5992. this.itemset.setItems(this.view);
  5993. this.parent.controller.add(this.itemset);
  5994. }
  5995. };
  5996. /**
  5997. * Change the item selection, and/or get currently selected items
  5998. * @param {Array} [ids] An array with zero or more ids of the items to be selected.
  5999. * @return {Array} ids The ids of the selected items
  6000. */
  6001. Group.prototype.select = function select(ids) {
  6002. return this.itemset ? this.itemset.select(ids) : [];
  6003. };
  6004. /**
  6005. * Repaint the item
  6006. * @return {Boolean} changed
  6007. */
  6008. Group.prototype.repaint = function repaint() {
  6009. return false;
  6010. };
  6011. /**
  6012. * Reflow the item
  6013. * @return {Boolean} resized
  6014. */
  6015. Group.prototype.reflow = function reflow() {
  6016. var changed = 0,
  6017. update = util.updateProperty;
  6018. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  6019. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  6020. // TODO: reckon with the height of the group label
  6021. if (this.label) {
  6022. var inner = this.label.firstChild;
  6023. changed += update(this.props.label, 'width', inner.clientWidth);
  6024. changed += update(this.props.label, 'height', inner.clientHeight);
  6025. }
  6026. else {
  6027. changed += update(this.props.label, 'width', 0);
  6028. changed += update(this.props.label, 'height', 0);
  6029. }
  6030. return (changed > 0);
  6031. };
  6032. /**
  6033. * An GroupSet holds a set of groups
  6034. * @param {Component} parent
  6035. * @param {Component[]} [depends] Components on which this components depends
  6036. * (except for the parent)
  6037. * @param {Object} [options] See GroupSet.setOptions for the available
  6038. * options.
  6039. * @constructor GroupSet
  6040. * @extends Panel
  6041. */
  6042. function GroupSet(parent, depends, options) {
  6043. this.id = util.randomUUID();
  6044. this.parent = parent;
  6045. this.depends = depends;
  6046. this.options = options || {};
  6047. this.range = null; // Range or Object {start: number, end: number}
  6048. this.itemsData = null; // DataSet with items
  6049. this.groupsData = null; // DataSet with groups
  6050. this.groups = {}; // map with groups
  6051. this.dom = {};
  6052. this.props = {
  6053. labels: {
  6054. width: 0
  6055. }
  6056. };
  6057. // TODO: implement right orientation of the labels
  6058. // changes in groups are queued key/value map containing id/action
  6059. this.queue = {};
  6060. var me = this;
  6061. this.listeners = {
  6062. 'add': function (event, params) {
  6063. me._onAdd(params.items);
  6064. },
  6065. 'update': function (event, params) {
  6066. me._onUpdate(params.items);
  6067. },
  6068. 'remove': function (event, params) {
  6069. me._onRemove(params.items);
  6070. }
  6071. };
  6072. }
  6073. GroupSet.prototype = new Panel();
  6074. /**
  6075. * Set options for the GroupSet. Existing options will be extended/overwritten.
  6076. * @param {Object} [options] The following options are available:
  6077. * {String | function} groupsOrder
  6078. * TODO: describe options
  6079. */
  6080. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  6081. GroupSet.prototype.setRange = function (range) {
  6082. // TODO: implement setRange
  6083. };
  6084. /**
  6085. * Set items
  6086. * @param {vis.DataSet | null} items
  6087. */
  6088. GroupSet.prototype.setItems = function setItems(items) {
  6089. this.itemsData = items;
  6090. for (var id in this.groups) {
  6091. if (this.groups.hasOwnProperty(id)) {
  6092. var group = this.groups[id];
  6093. group.setItems(items);
  6094. }
  6095. }
  6096. };
  6097. /**
  6098. * Get items
  6099. * @return {vis.DataSet | null} items
  6100. */
  6101. GroupSet.prototype.getItems = function getItems() {
  6102. return this.itemsData;
  6103. };
  6104. /**
  6105. * Set range (start and end).
  6106. * @param {Range | Object} range A Range or an object containing start and end.
  6107. */
  6108. GroupSet.prototype.setRange = function setRange(range) {
  6109. this.range = range;
  6110. };
  6111. /**
  6112. * Set groups
  6113. * @param {vis.DataSet} groups
  6114. */
  6115. GroupSet.prototype.setGroups = function setGroups(groups) {
  6116. var me = this,
  6117. ids;
  6118. // unsubscribe from current dataset
  6119. if (this.groupsData) {
  6120. util.forEach(this.listeners, function (callback, event) {
  6121. me.groupsData.unsubscribe(event, callback);
  6122. });
  6123. // remove all drawn groups
  6124. ids = this.groupsData.getIds();
  6125. this._onRemove(ids);
  6126. }
  6127. // replace the dataset
  6128. if (!groups) {
  6129. this.groupsData = null;
  6130. }
  6131. else if (groups instanceof DataSet) {
  6132. this.groupsData = groups;
  6133. }
  6134. else {
  6135. this.groupsData = new DataSet({
  6136. convert: {
  6137. start: 'Date',
  6138. end: 'Date'
  6139. }
  6140. });
  6141. this.groupsData.add(groups);
  6142. }
  6143. if (this.groupsData) {
  6144. // subscribe to new dataset
  6145. var id = this.id;
  6146. util.forEach(this.listeners, function (callback, event) {
  6147. me.groupsData.subscribe(event, callback, id);
  6148. });
  6149. // draw all new groups
  6150. ids = this.groupsData.getIds();
  6151. this._onAdd(ids);
  6152. }
  6153. };
  6154. /**
  6155. * Get groups
  6156. * @return {vis.DataSet | null} groups
  6157. */
  6158. GroupSet.prototype.getGroups = function getGroups() {
  6159. return this.groupsData;
  6160. };
  6161. /**
  6162. * Change the item selection, and/or get currently selected items
  6163. * @param {Array} [ids] An array with zero or more ids of the items to be selected.
  6164. * @return {Array} ids The ids of the selected items
  6165. */
  6166. GroupSet.prototype.select = function select(ids) {
  6167. var selection = [],
  6168. groups = this.groups;
  6169. // iterate over each of the groups
  6170. for (var id in groups) {
  6171. if (groups.hasOwnProperty(id)) {
  6172. var group = groups[id];
  6173. selection = selection.concat(group.select(ids));
  6174. }
  6175. }
  6176. return selection;
  6177. };
  6178. /**
  6179. * Repaint the component
  6180. * @return {Boolean} changed
  6181. */
  6182. GroupSet.prototype.repaint = function repaint() {
  6183. var changed = 0,
  6184. i, id, group, label,
  6185. update = util.updateProperty,
  6186. asSize = util.option.asSize,
  6187. asElement = util.option.asElement,
  6188. options = this.options,
  6189. frame = this.dom.frame,
  6190. labels = this.dom.labels,
  6191. labelSet = this.dom.labelSet;
  6192. // create frame
  6193. if (!this.parent) {
  6194. throw new Error('Cannot repaint groupset: no parent attached');
  6195. }
  6196. var parentContainer = this.parent.getContainer();
  6197. if (!parentContainer) {
  6198. throw new Error('Cannot repaint groupset: parent has no container element');
  6199. }
  6200. if (!frame) {
  6201. frame = document.createElement('div');
  6202. frame.className = 'groupset';
  6203. this.dom.frame = frame;
  6204. var className = options.className;
  6205. if (className) {
  6206. util.addClassName(frame, util.option.asString(className));
  6207. }
  6208. changed += 1;
  6209. }
  6210. if (!frame.parentNode) {
  6211. parentContainer.appendChild(frame);
  6212. changed += 1;
  6213. }
  6214. // create labels
  6215. var labelContainer = asElement(options.labelContainer);
  6216. if (!labelContainer) {
  6217. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  6218. }
  6219. if (!labels) {
  6220. labels = document.createElement('div');
  6221. labels.className = 'labels';
  6222. this.dom.labels = labels;
  6223. }
  6224. if (!labelSet) {
  6225. labelSet = document.createElement('div');
  6226. labelSet.className = 'label-set';
  6227. labels.appendChild(labelSet);
  6228. this.dom.labelSet = labelSet;
  6229. }
  6230. if (!labels.parentNode || labels.parentNode != labelContainer) {
  6231. if (labels.parentNode) {
  6232. labels.parentNode.removeChild(labels.parentNode);
  6233. }
  6234. labelContainer.appendChild(labels);
  6235. }
  6236. // reposition frame
  6237. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  6238. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6239. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6240. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6241. // reposition labels
  6242. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  6243. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  6244. var me = this,
  6245. queue = this.queue,
  6246. groups = this.groups,
  6247. groupsData = this.groupsData;
  6248. // show/hide added/changed/removed groups
  6249. var ids = Object.keys(queue);
  6250. if (ids.length) {
  6251. ids.forEach(function (id) {
  6252. var action = queue[id];
  6253. var group = groups[id];
  6254. //noinspection FallthroughInSwitchStatementJS
  6255. switch (action) {
  6256. case 'add':
  6257. case 'update':
  6258. if (!group) {
  6259. var groupOptions = Object.create(me.options);
  6260. util.extend(groupOptions, {
  6261. height: null,
  6262. maxHeight: null
  6263. });
  6264. group = new Group(me, id, groupOptions);
  6265. group.setItems(me.itemsData); // attach items data
  6266. groups[id] = group;
  6267. me.controller.add(group);
  6268. }
  6269. // TODO: update group data
  6270. group.data = groupsData.get(id);
  6271. delete queue[id];
  6272. break;
  6273. case 'remove':
  6274. if (group) {
  6275. group.setItems(); // detach items data
  6276. delete groups[id];
  6277. me.controller.remove(group);
  6278. }
  6279. // update lists
  6280. delete queue[id];
  6281. break;
  6282. default:
  6283. console.log('Error: unknown action "' + action + '"');
  6284. }
  6285. });
  6286. // the groupset depends on each of the groups
  6287. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  6288. // TODO: apply dependencies of the groupset
  6289. // update the top positions of the groups in the correct order
  6290. var orderedGroups = this.groupsData.getIds({
  6291. order: this.options.groupOrder
  6292. });
  6293. for (i = 0; i < orderedGroups.length; i++) {
  6294. (function (group, prevGroup) {
  6295. var top = 0;
  6296. if (prevGroup) {
  6297. top = function () {
  6298. // TODO: top must reckon with options.maxHeight
  6299. return prevGroup.top + prevGroup.height;
  6300. }
  6301. }
  6302. group.setOptions({
  6303. top: top
  6304. });
  6305. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  6306. }
  6307. // (re)create the labels
  6308. while (labelSet.firstChild) {
  6309. labelSet.removeChild(labelSet.firstChild);
  6310. }
  6311. for (i = 0; i < orderedGroups.length; i++) {
  6312. id = orderedGroups[i];
  6313. label = this._createLabel(id);
  6314. labelSet.appendChild(label);
  6315. }
  6316. changed++;
  6317. }
  6318. // reposition the labels
  6319. // TODO: labels are not displayed correctly when orientation=='top'
  6320. // TODO: width of labelPanel is not immediately updated on a change in groups
  6321. for (id in groups) {
  6322. if (groups.hasOwnProperty(id)) {
  6323. group = groups[id];
  6324. label = group.label;
  6325. if (label) {
  6326. label.style.top = group.top + 'px';
  6327. label.style.height = group.height + 'px';
  6328. }
  6329. }
  6330. }
  6331. return (changed > 0);
  6332. };
  6333. /**
  6334. * Create a label for group with given id
  6335. * @param {Number} id
  6336. * @return {Element} label
  6337. * @private
  6338. */
  6339. GroupSet.prototype._createLabel = function(id) {
  6340. var group = this.groups[id];
  6341. var label = document.createElement('div');
  6342. label.className = 'label';
  6343. var inner = document.createElement('div');
  6344. inner.className = 'inner';
  6345. label.appendChild(inner);
  6346. var content = group.data && group.data.content;
  6347. if (content instanceof Element) {
  6348. inner.appendChild(content);
  6349. }
  6350. else if (content != undefined) {
  6351. inner.innerHTML = content;
  6352. }
  6353. var className = group.data && group.data.className;
  6354. if (className) {
  6355. util.addClassName(label, className);
  6356. }
  6357. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  6358. return label;
  6359. };
  6360. /**
  6361. * Get container element
  6362. * @return {HTMLElement} container
  6363. */
  6364. GroupSet.prototype.getContainer = function getContainer() {
  6365. return this.dom.frame;
  6366. };
  6367. /**
  6368. * Get the width of the group labels
  6369. * @return {Number} width
  6370. */
  6371. GroupSet.prototype.getLabelsWidth = function getContainer() {
  6372. return this.props.labels.width;
  6373. };
  6374. /**
  6375. * Reflow the component
  6376. * @return {Boolean} resized
  6377. */
  6378. GroupSet.prototype.reflow = function reflow() {
  6379. var changed = 0,
  6380. id, group,
  6381. options = this.options,
  6382. update = util.updateProperty,
  6383. asNumber = util.option.asNumber,
  6384. asSize = util.option.asSize,
  6385. frame = this.dom.frame;
  6386. if (frame) {
  6387. var maxHeight = asNumber(options.maxHeight);
  6388. var fixedHeight = (asSize(options.height) != null);
  6389. var height;
  6390. if (fixedHeight) {
  6391. height = frame.offsetHeight;
  6392. }
  6393. else {
  6394. // height is not specified, calculate the sum of the height of all groups
  6395. height = 0;
  6396. for (id in this.groups) {
  6397. if (this.groups.hasOwnProperty(id)) {
  6398. group = this.groups[id];
  6399. height += group.height;
  6400. }
  6401. }
  6402. }
  6403. if (maxHeight != null) {
  6404. height = Math.min(height, maxHeight);
  6405. }
  6406. changed += update(this, 'height', height);
  6407. changed += update(this, 'top', frame.offsetTop);
  6408. changed += update(this, 'left', frame.offsetLeft);
  6409. changed += update(this, 'width', frame.offsetWidth);
  6410. }
  6411. // calculate the maximum width of the labels
  6412. var width = 0;
  6413. for (id in this.groups) {
  6414. if (this.groups.hasOwnProperty(id)) {
  6415. group = this.groups[id];
  6416. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  6417. width = Math.max(width, labelWidth);
  6418. }
  6419. }
  6420. changed += update(this.props.labels, 'width', width);
  6421. return (changed > 0);
  6422. };
  6423. /**
  6424. * Hide the component from the DOM
  6425. * @return {Boolean} changed
  6426. */
  6427. GroupSet.prototype.hide = function hide() {
  6428. if (this.dom.frame && this.dom.frame.parentNode) {
  6429. this.dom.frame.parentNode.removeChild(this.dom.frame);
  6430. return true;
  6431. }
  6432. else {
  6433. return false;
  6434. }
  6435. };
  6436. /**
  6437. * Show the component in the DOM (when not already visible).
  6438. * A repaint will be executed when the component is not visible
  6439. * @return {Boolean} changed
  6440. */
  6441. GroupSet.prototype.show = function show() {
  6442. if (!this.dom.frame || !this.dom.frame.parentNode) {
  6443. return this.repaint();
  6444. }
  6445. else {
  6446. return false;
  6447. }
  6448. };
  6449. /**
  6450. * Handle updated groups
  6451. * @param {Number[]} ids
  6452. * @private
  6453. */
  6454. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  6455. this._toQueue(ids, 'update');
  6456. };
  6457. /**
  6458. * Handle changed groups
  6459. * @param {Number[]} ids
  6460. * @private
  6461. */
  6462. GroupSet.prototype._onAdd = function _onAdd(ids) {
  6463. this._toQueue(ids, 'add');
  6464. };
  6465. /**
  6466. * Handle removed groups
  6467. * @param {Number[]} ids
  6468. * @private
  6469. */
  6470. GroupSet.prototype._onRemove = function _onRemove(ids) {
  6471. this._toQueue(ids, 'remove');
  6472. };
  6473. /**
  6474. * Put groups in the queue to be added/updated/remove
  6475. * @param {Number[]} ids
  6476. * @param {String} action can be 'add', 'update', 'remove'
  6477. */
  6478. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  6479. var queue = this.queue;
  6480. ids.forEach(function (id) {
  6481. queue[id] = action;
  6482. });
  6483. if (this.controller) {
  6484. //this.requestReflow();
  6485. this.requestRepaint();
  6486. }
  6487. };
  6488. /**
  6489. * Create a timeline visualization
  6490. * @param {HTMLElement} container
  6491. * @param {vis.DataSet | Array | DataTable} [items]
  6492. * @param {Object} [options] See Timeline.setOptions for the available options.
  6493. * @constructor
  6494. */
  6495. function Timeline (container, items, options) {
  6496. var me = this;
  6497. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6498. this.options = {
  6499. orientation: 'bottom',
  6500. min: null,
  6501. max: null,
  6502. zoomMin: 10, // milliseconds
  6503. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6504. // moveable: true, // TODO: option moveable
  6505. // zoomable: true, // TODO: option zoomable
  6506. showMinorLabels: true,
  6507. showMajorLabels: true,
  6508. showCurrentTime: false,
  6509. showCustomTime: false,
  6510. autoResize: false
  6511. };
  6512. // controller
  6513. this.controller = new Controller();
  6514. // root panel
  6515. if (!container) {
  6516. throw new Error('No container element provided');
  6517. }
  6518. var rootOptions = Object.create(this.options);
  6519. rootOptions.height = function () {
  6520. // TODO: change to height
  6521. if (me.options.height) {
  6522. // fixed height
  6523. return me.options.height;
  6524. }
  6525. else {
  6526. // auto height
  6527. return (me.timeaxis.height + me.content.height) + 'px';
  6528. }
  6529. };
  6530. this.rootPanel = new RootPanel(container, rootOptions);
  6531. this.controller.add(this.rootPanel);
  6532. // item panel
  6533. var itemOptions = Object.create(this.options);
  6534. itemOptions.left = function () {
  6535. return me.labelPanel.width;
  6536. };
  6537. itemOptions.width = function () {
  6538. return me.rootPanel.width - me.labelPanel.width;
  6539. };
  6540. itemOptions.top = null;
  6541. itemOptions.height = null;
  6542. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  6543. this.controller.add(this.itemPanel);
  6544. // label panel
  6545. var labelOptions = Object.create(this.options);
  6546. labelOptions.top = null;
  6547. labelOptions.left = null;
  6548. labelOptions.height = null;
  6549. labelOptions.width = function () {
  6550. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  6551. return me.content.getLabelsWidth();
  6552. }
  6553. else {
  6554. return 0;
  6555. }
  6556. };
  6557. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  6558. this.controller.add(this.labelPanel);
  6559. // range
  6560. var rangeOptions = Object.create(this.options);
  6561. this.range = new Range(rangeOptions);
  6562. this.range.setRange(
  6563. now.clone().add('days', -3).valueOf(),
  6564. now.clone().add('days', 4).valueOf()
  6565. );
  6566. // TODO: reckon with options moveable and zoomable
  6567. this.range.subscribe(this.rootPanel, 'move', 'horizontal');
  6568. this.range.subscribe(this.rootPanel, 'zoom', 'horizontal');
  6569. this.range.on('rangechange', function () {
  6570. var force = true;
  6571. me.controller.requestReflow(force);
  6572. });
  6573. this.range.on('rangechanged', function () {
  6574. var force = true;
  6575. me.controller.requestReflow(force);
  6576. });
  6577. // TODO: put the listeners in setOptions, be able to dynamically change with options moveable and zoomable
  6578. // time axis
  6579. var timeaxisOptions = Object.create(rootOptions);
  6580. timeaxisOptions.range = this.range;
  6581. timeaxisOptions.left = null;
  6582. timeaxisOptions.top = null;
  6583. timeaxisOptions.width = '100%';
  6584. timeaxisOptions.height = null;
  6585. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6586. this.timeaxis.setRange(this.range);
  6587. this.controller.add(this.timeaxis);
  6588. // current time bar
  6589. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  6590. this.controller.add(this.currenttime);
  6591. // custom time bar
  6592. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  6593. this.controller.add(this.customtime);
  6594. // create groupset
  6595. this.setGroups(null);
  6596. this.itemsData = null; // DataSet
  6597. this.groupsData = null; // DataSet
  6598. // apply options
  6599. if (options) {
  6600. this.setOptions(options);
  6601. }
  6602. // create itemset and groupset
  6603. if (items) {
  6604. this.setItems(items);
  6605. }
  6606. }
  6607. /**
  6608. * Set options
  6609. * @param {Object} options TODO: describe the available options
  6610. */
  6611. Timeline.prototype.setOptions = function (options) {
  6612. util.extend(this.options, options);
  6613. // force update of range
  6614. // options.start and options.end can be undefined
  6615. //this.range.setRange(options.start, options.end);
  6616. this.range.setRange();
  6617. this.controller.reflow();
  6618. this.controller.repaint();
  6619. };
  6620. /**
  6621. * Set a custom time bar
  6622. * @param {Date} time
  6623. */
  6624. Timeline.prototype.setCustomTime = function (time) {
  6625. this.customtime._setCustomTime(time);
  6626. };
  6627. /**
  6628. * Retrieve the current custom time.
  6629. * @return {Date} customTime
  6630. */
  6631. Timeline.prototype.getCustomTime = function() {
  6632. return new Date(this.customtime.customTime.valueOf());
  6633. };
  6634. /**
  6635. * Set items
  6636. * @param {vis.DataSet | Array | DataTable | null} items
  6637. */
  6638. Timeline.prototype.setItems = function(items) {
  6639. var initialLoad = (this.itemsData == null);
  6640. // convert to type DataSet when needed
  6641. var newItemSet;
  6642. if (!items) {
  6643. newItemSet = null;
  6644. }
  6645. else if (items instanceof DataSet) {
  6646. newItemSet = items;
  6647. }
  6648. if (!(items instanceof DataSet)) {
  6649. newItemSet = new DataSet({
  6650. convert: {
  6651. start: 'Date',
  6652. end: 'Date'
  6653. }
  6654. });
  6655. newItemSet.add(items);
  6656. }
  6657. // set items
  6658. this.itemsData = newItemSet;
  6659. this.content.setItems(newItemSet);
  6660. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6661. // apply the data range as range
  6662. var dataRange = this.getItemRange();
  6663. // add 5% space on both sides
  6664. var min = dataRange.min;
  6665. var max = dataRange.max;
  6666. if (min != null && max != null) {
  6667. var interval = (max.valueOf() - min.valueOf());
  6668. if (interval <= 0) {
  6669. // prevent an empty interval
  6670. interval = 24 * 60 * 60 * 1000; // 1 day
  6671. }
  6672. min = new Date(min.valueOf() - interval * 0.05);
  6673. max = new Date(max.valueOf() + interval * 0.05);
  6674. }
  6675. // override specified start and/or end date
  6676. if (this.options.start != undefined) {
  6677. min = util.convert(this.options.start, 'Date');
  6678. }
  6679. if (this.options.end != undefined) {
  6680. max = util.convert(this.options.end, 'Date');
  6681. }
  6682. // apply range if there is a min or max available
  6683. if (min != null || max != null) {
  6684. this.range.setRange(min, max);
  6685. }
  6686. }
  6687. };
  6688. /**
  6689. * Set groups
  6690. * @param {vis.DataSet | Array | DataTable} groups
  6691. */
  6692. Timeline.prototype.setGroups = function(groups) {
  6693. var me = this;
  6694. this.groupsData = groups;
  6695. // switch content type between ItemSet or GroupSet when needed
  6696. var Type = this.groupsData ? GroupSet : ItemSet;
  6697. if (!(this.content instanceof Type)) {
  6698. // remove old content set
  6699. if (this.content) {
  6700. this.content.hide();
  6701. if (this.content.setItems) {
  6702. this.content.setItems(); // disconnect from items
  6703. }
  6704. if (this.content.setGroups) {
  6705. this.content.setGroups(); // disconnect from groups
  6706. }
  6707. this.controller.remove(this.content);
  6708. }
  6709. // create new content set
  6710. var options = Object.create(this.options);
  6711. util.extend(options, {
  6712. top: function () {
  6713. if (me.options.orientation == 'top') {
  6714. return me.timeaxis.height;
  6715. }
  6716. else {
  6717. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  6718. }
  6719. },
  6720. left: null,
  6721. width: '100%',
  6722. height: function () {
  6723. if (me.options.height) {
  6724. // fixed height
  6725. return me.itemPanel.height - me.timeaxis.height;
  6726. }
  6727. else {
  6728. // auto height
  6729. return null;
  6730. }
  6731. },
  6732. maxHeight: function () {
  6733. // TODO: change maxHeight to be a css string like '100%' or '300px'
  6734. if (me.options.maxHeight) {
  6735. if (!util.isNumber(me.options.maxHeight)) {
  6736. throw new TypeError('Number expected for property maxHeight');
  6737. }
  6738. return me.options.maxHeight - me.timeaxis.height;
  6739. }
  6740. else {
  6741. return null;
  6742. }
  6743. },
  6744. labelContainer: function () {
  6745. return me.labelPanel.getContainer();
  6746. }
  6747. });
  6748. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  6749. if (this.content.setRange) {
  6750. this.content.setRange(this.range);
  6751. }
  6752. if (this.content.setItems) {
  6753. this.content.setItems(this.itemsData);
  6754. }
  6755. if (this.content.setGroups) {
  6756. this.content.setGroups(this.groupsData);
  6757. }
  6758. this.controller.add(this.content);
  6759. }
  6760. };
  6761. /**
  6762. * Get the data range of the item set.
  6763. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6764. * When no minimum is found, min==null
  6765. * When no maximum is found, max==null
  6766. */
  6767. Timeline.prototype.getItemRange = function getItemRange() {
  6768. // calculate min from start filed
  6769. var itemsData = this.itemsData,
  6770. min = null,
  6771. max = null;
  6772. if (itemsData) {
  6773. // calculate the minimum value of the field 'start'
  6774. var minItem = itemsData.min('start');
  6775. min = minItem ? minItem.start.valueOf() : null;
  6776. // calculate maximum value of fields 'start' and 'end'
  6777. var maxStartItem = itemsData.max('start');
  6778. if (maxStartItem) {
  6779. max = maxStartItem.start.valueOf();
  6780. }
  6781. var maxEndItem = itemsData.max('end');
  6782. if (maxEndItem) {
  6783. if (max == null) {
  6784. max = maxEndItem.end.valueOf();
  6785. }
  6786. else {
  6787. max = Math.max(max, maxEndItem.end.valueOf());
  6788. }
  6789. }
  6790. }
  6791. return {
  6792. min: (min != null) ? new Date(min) : null,
  6793. max: (max != null) ? new Date(max) : null
  6794. };
  6795. };
  6796. /**
  6797. * Change the item selection, and/or get currently selected items
  6798. * @param {Array} [ids] An array with zero or more ids of the items to be selected.
  6799. * @return {Array} ids The ids of the selected items
  6800. */
  6801. Timeline.prototype.select = function select(ids) {
  6802. return this.content ? this.content.select(ids) : [];
  6803. };
  6804. (function(exports) {
  6805. /**
  6806. * Parse a text source containing data in DOT language into a JSON object.
  6807. * The object contains two lists: one with nodes and one with edges.
  6808. *
  6809. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6810. *
  6811. * @param {String} data Text containing a graph in DOT-notation
  6812. * @return {Object} graph An object containing two parameters:
  6813. * {Object[]} nodes
  6814. * {Object[]} edges
  6815. */
  6816. function parseDOT (data) {
  6817. dot = data;
  6818. return parseGraph();
  6819. }
  6820. // token types enumeration
  6821. var TOKENTYPE = {
  6822. NULL : 0,
  6823. DELIMITER : 1,
  6824. IDENTIFIER: 2,
  6825. UNKNOWN : 3
  6826. };
  6827. // map with all delimiters
  6828. var DELIMITERS = {
  6829. '{': true,
  6830. '}': true,
  6831. '[': true,
  6832. ']': true,
  6833. ';': true,
  6834. '=': true,
  6835. ',': true,
  6836. '->': true,
  6837. '--': true
  6838. };
  6839. var dot = ''; // current dot file
  6840. var index = 0; // current index in dot file
  6841. var c = ''; // current token character in expr
  6842. var token = ''; // current token
  6843. var tokenType = TOKENTYPE.NULL; // type of the token
  6844. /**
  6845. * Get the first character from the dot file.
  6846. * The character is stored into the char c. If the end of the dot file is
  6847. * reached, the function puts an empty string in c.
  6848. */
  6849. function first() {
  6850. index = 0;
  6851. c = dot.charAt(0);
  6852. }
  6853. /**
  6854. * Get the next character from the dot file.
  6855. * The character is stored into the char c. If the end of the dot file is
  6856. * reached, the function puts an empty string in c.
  6857. */
  6858. function next() {
  6859. index++;
  6860. c = dot.charAt(index);
  6861. }
  6862. /**
  6863. * Preview the next character from the dot file.
  6864. * @return {String} cNext
  6865. */
  6866. function nextPreview() {
  6867. return dot.charAt(index + 1);
  6868. }
  6869. /**
  6870. * Test whether given character is alphabetic or numeric
  6871. * @param {String} c
  6872. * @return {Boolean} isAlphaNumeric
  6873. */
  6874. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  6875. function isAlphaNumeric(c) {
  6876. return regexAlphaNumeric.test(c);
  6877. }
  6878. /**
  6879. * Merge all properties of object b into object b
  6880. * @param {Object} a
  6881. * @param {Object} b
  6882. * @return {Object} a
  6883. */
  6884. function merge (a, b) {
  6885. if (!a) {
  6886. a = {};
  6887. }
  6888. if (b) {
  6889. for (var name in b) {
  6890. if (b.hasOwnProperty(name)) {
  6891. a[name] = b[name];
  6892. }
  6893. }
  6894. }
  6895. return a;
  6896. }
  6897. /**
  6898. * Set a value in an object, where the provided parameter name can be a
  6899. * path with nested parameters. For example:
  6900. *
  6901. * var obj = {a: 2};
  6902. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  6903. *
  6904. * @param {Object} obj
  6905. * @param {String} path A parameter name or dot-separated parameter path,
  6906. * like "color.highlight.border".
  6907. * @param {*} value
  6908. */
  6909. function setValue(obj, path, value) {
  6910. var keys = path.split('.');
  6911. var o = obj;
  6912. while (keys.length) {
  6913. var key = keys.shift();
  6914. if (keys.length) {
  6915. // this isn't the end point
  6916. if (!o[key]) {
  6917. o[key] = {};
  6918. }
  6919. o = o[key];
  6920. }
  6921. else {
  6922. // this is the end point
  6923. o[key] = value;
  6924. }
  6925. }
  6926. }
  6927. /**
  6928. * Add a node to a graph object. If there is already a node with
  6929. * the same id, their attributes will be merged.
  6930. * @param {Object} graph
  6931. * @param {Object} node
  6932. */
  6933. function addNode(graph, node) {
  6934. var i, len;
  6935. var current = null;
  6936. // find root graph (in case of subgraph)
  6937. var graphs = [graph]; // list with all graphs from current graph to root graph
  6938. var root = graph;
  6939. while (root.parent) {
  6940. graphs.push(root.parent);
  6941. root = root.parent;
  6942. }
  6943. // find existing node (at root level) by its id
  6944. if (root.nodes) {
  6945. for (i = 0, len = root.nodes.length; i < len; i++) {
  6946. if (node.id === root.nodes[i].id) {
  6947. current = root.nodes[i];
  6948. break;
  6949. }
  6950. }
  6951. }
  6952. if (!current) {
  6953. // this is a new node
  6954. current = {
  6955. id: node.id
  6956. };
  6957. if (graph.node) {
  6958. // clone default attributes
  6959. current.attr = merge(current.attr, graph.node);
  6960. }
  6961. }
  6962. // add node to this (sub)graph and all its parent graphs
  6963. for (i = graphs.length - 1; i >= 0; i--) {
  6964. var g = graphs[i];
  6965. if (!g.nodes) {
  6966. g.nodes = [];
  6967. }
  6968. if (g.nodes.indexOf(current) == -1) {
  6969. g.nodes.push(current);
  6970. }
  6971. }
  6972. // merge attributes
  6973. if (node.attr) {
  6974. current.attr = merge(current.attr, node.attr);
  6975. }
  6976. }
  6977. /**
  6978. * Add an edge to a graph object
  6979. * @param {Object} graph
  6980. * @param {Object} edge
  6981. */
  6982. function addEdge(graph, edge) {
  6983. if (!graph.edges) {
  6984. graph.edges = [];
  6985. }
  6986. graph.edges.push(edge);
  6987. if (graph.edge) {
  6988. var attr = merge({}, graph.edge); // clone default attributes
  6989. edge.attr = merge(attr, edge.attr); // merge attributes
  6990. }
  6991. }
  6992. /**
  6993. * Create an edge to a graph object
  6994. * @param {Object} graph
  6995. * @param {String | Number | Object} from
  6996. * @param {String | Number | Object} to
  6997. * @param {String} type
  6998. * @param {Object | null} attr
  6999. * @return {Object} edge
  7000. */
  7001. function createEdge(graph, from, to, type, attr) {
  7002. var edge = {
  7003. from: from,
  7004. to: to,
  7005. type: type
  7006. };
  7007. if (graph.edge) {
  7008. edge.attr = merge({}, graph.edge); // clone default attributes
  7009. }
  7010. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7011. return edge;
  7012. }
  7013. /**
  7014. * Get next token in the current dot file.
  7015. * The token and token type are available as token and tokenType
  7016. */
  7017. function getToken() {
  7018. tokenType = TOKENTYPE.NULL;
  7019. token = '';
  7020. // skip over whitespaces
  7021. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7022. next();
  7023. }
  7024. do {
  7025. var isComment = false;
  7026. // skip comment
  7027. if (c == '#') {
  7028. // find the previous non-space character
  7029. var i = index - 1;
  7030. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7031. i--;
  7032. }
  7033. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7034. // the # is at the start of a line, this is indeed a line comment
  7035. while (c != '' && c != '\n') {
  7036. next();
  7037. }
  7038. isComment = true;
  7039. }
  7040. }
  7041. if (c == '/' && nextPreview() == '/') {
  7042. // skip line comment
  7043. while (c != '' && c != '\n') {
  7044. next();
  7045. }
  7046. isComment = true;
  7047. }
  7048. if (c == '/' && nextPreview() == '*') {
  7049. // skip block comment
  7050. while (c != '') {
  7051. if (c == '*' && nextPreview() == '/') {
  7052. // end of block comment found. skip these last two characters
  7053. next();
  7054. next();
  7055. break;
  7056. }
  7057. else {
  7058. next();
  7059. }
  7060. }
  7061. isComment = true;
  7062. }
  7063. // skip over whitespaces
  7064. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7065. next();
  7066. }
  7067. }
  7068. while (isComment);
  7069. // check for end of dot file
  7070. if (c == '') {
  7071. // token is still empty
  7072. tokenType = TOKENTYPE.DELIMITER;
  7073. return;
  7074. }
  7075. // check for delimiters consisting of 2 characters
  7076. var c2 = c + nextPreview();
  7077. if (DELIMITERS[c2]) {
  7078. tokenType = TOKENTYPE.DELIMITER;
  7079. token = c2;
  7080. next();
  7081. next();
  7082. return;
  7083. }
  7084. // check for delimiters consisting of 1 character
  7085. if (DELIMITERS[c]) {
  7086. tokenType = TOKENTYPE.DELIMITER;
  7087. token = c;
  7088. next();
  7089. return;
  7090. }
  7091. // check for an identifier (number or string)
  7092. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7093. if (isAlphaNumeric(c) || c == '-') {
  7094. token += c;
  7095. next();
  7096. while (isAlphaNumeric(c)) {
  7097. token += c;
  7098. next();
  7099. }
  7100. if (token == 'false') {
  7101. token = false; // convert to boolean
  7102. }
  7103. else if (token == 'true') {
  7104. token = true; // convert to boolean
  7105. }
  7106. else if (!isNaN(Number(token))) {
  7107. token = Number(token); // convert to number
  7108. }
  7109. tokenType = TOKENTYPE.IDENTIFIER;
  7110. return;
  7111. }
  7112. // check for a string enclosed by double quotes
  7113. if (c == '"') {
  7114. next();
  7115. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7116. token += c;
  7117. if (c == '"') { // skip the escape character
  7118. next();
  7119. }
  7120. next();
  7121. }
  7122. if (c != '"') {
  7123. throw newSyntaxError('End of string " expected');
  7124. }
  7125. next();
  7126. tokenType = TOKENTYPE.IDENTIFIER;
  7127. return;
  7128. }
  7129. // something unknown is found, wrong characters, a syntax error
  7130. tokenType = TOKENTYPE.UNKNOWN;
  7131. while (c != '') {
  7132. token += c;
  7133. next();
  7134. }
  7135. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7136. }
  7137. /**
  7138. * Parse a graph.
  7139. * @returns {Object} graph
  7140. */
  7141. function parseGraph() {
  7142. var graph = {};
  7143. first();
  7144. getToken();
  7145. // optional strict keyword
  7146. if (token == 'strict') {
  7147. graph.strict = true;
  7148. getToken();
  7149. }
  7150. // graph or digraph keyword
  7151. if (token == 'graph' || token == 'digraph') {
  7152. graph.type = token;
  7153. getToken();
  7154. }
  7155. // optional graph id
  7156. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7157. graph.id = token;
  7158. getToken();
  7159. }
  7160. // open angle bracket
  7161. if (token != '{') {
  7162. throw newSyntaxError('Angle bracket { expected');
  7163. }
  7164. getToken();
  7165. // statements
  7166. parseStatements(graph);
  7167. // close angle bracket
  7168. if (token != '}') {
  7169. throw newSyntaxError('Angle bracket } expected');
  7170. }
  7171. getToken();
  7172. // end of file
  7173. if (token !== '') {
  7174. throw newSyntaxError('End of file expected');
  7175. }
  7176. getToken();
  7177. // remove temporary default properties
  7178. delete graph.node;
  7179. delete graph.edge;
  7180. delete graph.graph;
  7181. return graph;
  7182. }
  7183. /**
  7184. * Parse a list with statements.
  7185. * @param {Object} graph
  7186. */
  7187. function parseStatements (graph) {
  7188. while (token !== '' && token != '}') {
  7189. parseStatement(graph);
  7190. if (token == ';') {
  7191. getToken();
  7192. }
  7193. }
  7194. }
  7195. /**
  7196. * Parse a single statement. Can be a an attribute statement, node
  7197. * statement, a series of node statements and edge statements, or a
  7198. * parameter.
  7199. * @param {Object} graph
  7200. */
  7201. function parseStatement(graph) {
  7202. // parse subgraph
  7203. var subgraph = parseSubgraph(graph);
  7204. if (subgraph) {
  7205. // edge statements
  7206. parseEdge(graph, subgraph);
  7207. return;
  7208. }
  7209. // parse an attribute statement
  7210. var attr = parseAttributeStatement(graph);
  7211. if (attr) {
  7212. return;
  7213. }
  7214. // parse node
  7215. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7216. throw newSyntaxError('Identifier expected');
  7217. }
  7218. var id = token; // id can be a string or a number
  7219. getToken();
  7220. if (token == '=') {
  7221. // id statement
  7222. getToken();
  7223. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7224. throw newSyntaxError('Identifier expected');
  7225. }
  7226. graph[id] = token;
  7227. getToken();
  7228. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7229. }
  7230. else {
  7231. parseNodeStatement(graph, id);
  7232. }
  7233. }
  7234. /**
  7235. * Parse a subgraph
  7236. * @param {Object} graph parent graph object
  7237. * @return {Object | null} subgraph
  7238. */
  7239. function parseSubgraph (graph) {
  7240. var subgraph = null;
  7241. // optional subgraph keyword
  7242. if (token == 'subgraph') {
  7243. subgraph = {};
  7244. subgraph.type = 'subgraph';
  7245. getToken();
  7246. // optional graph id
  7247. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7248. subgraph.id = token;
  7249. getToken();
  7250. }
  7251. }
  7252. // open angle bracket
  7253. if (token == '{') {
  7254. getToken();
  7255. if (!subgraph) {
  7256. subgraph = {};
  7257. }
  7258. subgraph.parent = graph;
  7259. subgraph.node = graph.node;
  7260. subgraph.edge = graph.edge;
  7261. subgraph.graph = graph.graph;
  7262. // statements
  7263. parseStatements(subgraph);
  7264. // close angle bracket
  7265. if (token != '}') {
  7266. throw newSyntaxError('Angle bracket } expected');
  7267. }
  7268. getToken();
  7269. // remove temporary default properties
  7270. delete subgraph.node;
  7271. delete subgraph.edge;
  7272. delete subgraph.graph;
  7273. delete subgraph.parent;
  7274. // register at the parent graph
  7275. if (!graph.subgraphs) {
  7276. graph.subgraphs = [];
  7277. }
  7278. graph.subgraphs.push(subgraph);
  7279. }
  7280. return subgraph;
  7281. }
  7282. /**
  7283. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7284. * Available keywords are 'node', 'edge', 'graph'.
  7285. * The previous list with default attributes will be replaced
  7286. * @param {Object} graph
  7287. * @returns {String | null} keyword Returns the name of the parsed attribute
  7288. * (node, edge, graph), or null if nothing
  7289. * is parsed.
  7290. */
  7291. function parseAttributeStatement (graph) {
  7292. // attribute statements
  7293. if (token == 'node') {
  7294. getToken();
  7295. // node attributes
  7296. graph.node = parseAttributeList();
  7297. return 'node';
  7298. }
  7299. else if (token == 'edge') {
  7300. getToken();
  7301. // edge attributes
  7302. graph.edge = parseAttributeList();
  7303. return 'edge';
  7304. }
  7305. else if (token == 'graph') {
  7306. getToken();
  7307. // graph attributes
  7308. graph.graph = parseAttributeList();
  7309. return 'graph';
  7310. }
  7311. return null;
  7312. }
  7313. /**
  7314. * parse a node statement
  7315. * @param {Object} graph
  7316. * @param {String | Number} id
  7317. */
  7318. function parseNodeStatement(graph, id) {
  7319. // node statement
  7320. var node = {
  7321. id: id
  7322. };
  7323. var attr = parseAttributeList();
  7324. if (attr) {
  7325. node.attr = attr;
  7326. }
  7327. addNode(graph, node);
  7328. // edge statements
  7329. parseEdge(graph, id);
  7330. }
  7331. /**
  7332. * Parse an edge or a series of edges
  7333. * @param {Object} graph
  7334. * @param {String | Number} from Id of the from node
  7335. */
  7336. function parseEdge(graph, from) {
  7337. while (token == '->' || token == '--') {
  7338. var to;
  7339. var type = token;
  7340. getToken();
  7341. var subgraph = parseSubgraph(graph);
  7342. if (subgraph) {
  7343. to = subgraph;
  7344. }
  7345. else {
  7346. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7347. throw newSyntaxError('Identifier or subgraph expected');
  7348. }
  7349. to = token;
  7350. addNode(graph, {
  7351. id: to
  7352. });
  7353. getToken();
  7354. }
  7355. // parse edge attributes
  7356. var attr = parseAttributeList();
  7357. // create edge
  7358. var edge = createEdge(graph, from, to, type, attr);
  7359. addEdge(graph, edge);
  7360. from = to;
  7361. }
  7362. }
  7363. /**
  7364. * Parse a set with attributes,
  7365. * for example [label="1.000", shape=solid]
  7366. * @return {Object | null} attr
  7367. */
  7368. function parseAttributeList() {
  7369. var attr = null;
  7370. while (token == '[') {
  7371. getToken();
  7372. attr = {};
  7373. while (token !== '' && token != ']') {
  7374. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7375. throw newSyntaxError('Attribute name expected');
  7376. }
  7377. var name = token;
  7378. getToken();
  7379. if (token != '=') {
  7380. throw newSyntaxError('Equal sign = expected');
  7381. }
  7382. getToken();
  7383. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7384. throw newSyntaxError('Attribute value expected');
  7385. }
  7386. var value = token;
  7387. setValue(attr, name, value); // name can be a path
  7388. getToken();
  7389. if (token ==',') {
  7390. getToken();
  7391. }
  7392. }
  7393. if (token != ']') {
  7394. throw newSyntaxError('Bracket ] expected');
  7395. }
  7396. getToken();
  7397. }
  7398. return attr;
  7399. }
  7400. /**
  7401. * Create a syntax error with extra information on current token and index.
  7402. * @param {String} message
  7403. * @returns {SyntaxError} err
  7404. */
  7405. function newSyntaxError(message) {
  7406. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7407. }
  7408. /**
  7409. * Chop off text after a maximum length
  7410. * @param {String} text
  7411. * @param {Number} maxLength
  7412. * @returns {String}
  7413. */
  7414. function chop (text, maxLength) {
  7415. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7416. }
  7417. /**
  7418. * Execute a function fn for each pair of elements in two arrays
  7419. * @param {Array | *} array1
  7420. * @param {Array | *} array2
  7421. * @param {function} fn
  7422. */
  7423. function forEach2(array1, array2, fn) {
  7424. if (array1 instanceof Array) {
  7425. array1.forEach(function (elem1) {
  7426. if (array2 instanceof Array) {
  7427. array2.forEach(function (elem2) {
  7428. fn(elem1, elem2);
  7429. });
  7430. }
  7431. else {
  7432. fn(elem1, array2);
  7433. }
  7434. });
  7435. }
  7436. else {
  7437. if (array2 instanceof Array) {
  7438. array2.forEach(function (elem2) {
  7439. fn(array1, elem2);
  7440. });
  7441. }
  7442. else {
  7443. fn(array1, array2);
  7444. }
  7445. }
  7446. }
  7447. /**
  7448. * Convert a string containing a graph in DOT language into a map containing
  7449. * with nodes and edges in the format of graph.
  7450. * @param {String} data Text containing a graph in DOT-notation
  7451. * @return {Object} graphData
  7452. */
  7453. function DOTToGraph (data) {
  7454. // parse the DOT file
  7455. var dotData = parseDOT(data);
  7456. var graphData = {
  7457. nodes: [],
  7458. edges: [],
  7459. options: {}
  7460. };
  7461. // copy the nodes
  7462. if (dotData.nodes) {
  7463. dotData.nodes.forEach(function (dotNode) {
  7464. var graphNode = {
  7465. id: dotNode.id,
  7466. label: String(dotNode.label || dotNode.id)
  7467. };
  7468. merge(graphNode, dotNode.attr);
  7469. if (graphNode.image) {
  7470. graphNode.shape = 'image';
  7471. }
  7472. graphData.nodes.push(graphNode);
  7473. });
  7474. }
  7475. // copy the edges
  7476. if (dotData.edges) {
  7477. /**
  7478. * Convert an edge in DOT format to an edge with VisGraph format
  7479. * @param {Object} dotEdge
  7480. * @returns {Object} graphEdge
  7481. */
  7482. function convertEdge(dotEdge) {
  7483. var graphEdge = {
  7484. from: dotEdge.from,
  7485. to: dotEdge.to
  7486. };
  7487. merge(graphEdge, dotEdge.attr);
  7488. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  7489. return graphEdge;
  7490. }
  7491. dotData.edges.forEach(function (dotEdge) {
  7492. var from, to;
  7493. if (dotEdge.from instanceof Object) {
  7494. from = dotEdge.from.nodes;
  7495. }
  7496. else {
  7497. from = {
  7498. id: dotEdge.from
  7499. }
  7500. }
  7501. if (dotEdge.to instanceof Object) {
  7502. to = dotEdge.to.nodes;
  7503. }
  7504. else {
  7505. to = {
  7506. id: dotEdge.to
  7507. }
  7508. }
  7509. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  7510. dotEdge.from.edges.forEach(function (subEdge) {
  7511. var graphEdge = convertEdge(subEdge);
  7512. graphData.edges.push(graphEdge);
  7513. });
  7514. }
  7515. forEach2(from, to, function (from, to) {
  7516. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  7517. var graphEdge = convertEdge(subEdge);
  7518. graphData.edges.push(graphEdge);
  7519. });
  7520. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  7521. dotEdge.to.edges.forEach(function (subEdge) {
  7522. var graphEdge = convertEdge(subEdge);
  7523. graphData.edges.push(graphEdge);
  7524. });
  7525. }
  7526. });
  7527. }
  7528. // copy the options
  7529. if (dotData.attr) {
  7530. graphData.options = dotData.attr;
  7531. }
  7532. return graphData;
  7533. }
  7534. // exports
  7535. exports.parseDOT = parseDOT;
  7536. exports.DOTToGraph = DOTToGraph;
  7537. })(typeof util !== 'undefined' ? util : exports);
  7538. /**
  7539. * Canvas shapes used by the Graph
  7540. */
  7541. if (typeof CanvasRenderingContext2D !== 'undefined') {
  7542. /**
  7543. * Draw a circle shape
  7544. */
  7545. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  7546. this.beginPath();
  7547. this.arc(x, y, r, 0, 2*Math.PI, false);
  7548. };
  7549. /**
  7550. * Draw a square shape
  7551. * @param {Number} x horizontal center
  7552. * @param {Number} y vertical center
  7553. * @param {Number} r size, width and height of the square
  7554. */
  7555. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  7556. this.beginPath();
  7557. this.rect(x - r, y - r, r * 2, r * 2);
  7558. };
  7559. /**
  7560. * Draw a triangle shape
  7561. * @param {Number} x horizontal center
  7562. * @param {Number} y vertical center
  7563. * @param {Number} r radius, half the length of the sides of the triangle
  7564. */
  7565. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  7566. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7567. this.beginPath();
  7568. var s = r * 2;
  7569. var s2 = s / 2;
  7570. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7571. var h = Math.sqrt(s * s - s2 * s2); // height
  7572. this.moveTo(x, y - (h - ir));
  7573. this.lineTo(x + s2, y + ir);
  7574. this.lineTo(x - s2, y + ir);
  7575. this.lineTo(x, y - (h - ir));
  7576. this.closePath();
  7577. };
  7578. /**
  7579. * Draw a triangle shape in downward orientation
  7580. * @param {Number} x horizontal center
  7581. * @param {Number} y vertical center
  7582. * @param {Number} r radius
  7583. */
  7584. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  7585. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7586. this.beginPath();
  7587. var s = r * 2;
  7588. var s2 = s / 2;
  7589. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7590. var h = Math.sqrt(s * s - s2 * s2); // height
  7591. this.moveTo(x, y + (h - ir));
  7592. this.lineTo(x + s2, y - ir);
  7593. this.lineTo(x - s2, y - ir);
  7594. this.lineTo(x, y + (h - ir));
  7595. this.closePath();
  7596. };
  7597. /**
  7598. * Draw a star shape, a star with 5 points
  7599. * @param {Number} x horizontal center
  7600. * @param {Number} y vertical center
  7601. * @param {Number} r radius, half the length of the sides of the triangle
  7602. */
  7603. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  7604. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  7605. this.beginPath();
  7606. for (var n = 0; n < 10; n++) {
  7607. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  7608. this.lineTo(
  7609. x + radius * Math.sin(n * 2 * Math.PI / 10),
  7610. y - radius * Math.cos(n * 2 * Math.PI / 10)
  7611. );
  7612. }
  7613. this.closePath();
  7614. };
  7615. /**
  7616. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7617. */
  7618. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7619. var r2d = Math.PI/180;
  7620. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7621. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7622. this.beginPath();
  7623. this.moveTo(x+r,y);
  7624. this.lineTo(x+w-r,y);
  7625. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7626. this.lineTo(x+w,y+h-r);
  7627. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7628. this.lineTo(x+r,y+h);
  7629. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7630. this.lineTo(x,y+r);
  7631. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7632. };
  7633. /**
  7634. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7635. */
  7636. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7637. var kappa = .5522848,
  7638. ox = (w / 2) * kappa, // control point offset horizontal
  7639. oy = (h / 2) * kappa, // control point offset vertical
  7640. xe = x + w, // x-end
  7641. ye = y + h, // y-end
  7642. xm = x + w / 2, // x-middle
  7643. ym = y + h / 2; // y-middle
  7644. this.beginPath();
  7645. this.moveTo(x, ym);
  7646. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7647. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7648. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7649. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7650. };
  7651. /**
  7652. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7653. */
  7654. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7655. var f = 1/3;
  7656. var wEllipse = w;
  7657. var hEllipse = h * f;
  7658. var kappa = .5522848,
  7659. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7660. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7661. xe = x + wEllipse, // x-end
  7662. ye = y + hEllipse, // y-end
  7663. xm = x + wEllipse / 2, // x-middle
  7664. ym = y + hEllipse / 2, // y-middle
  7665. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7666. yeb = y + h; // y-end, bottom ellipse
  7667. this.beginPath();
  7668. this.moveTo(xe, ym);
  7669. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7670. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7671. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7672. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7673. this.lineTo(xe, ymb);
  7674. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7675. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7676. this.lineTo(x, ym);
  7677. };
  7678. /**
  7679. * Draw an arrow point (no line)
  7680. */
  7681. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  7682. // tail
  7683. var xt = x - length * Math.cos(angle);
  7684. var yt = y - length * Math.sin(angle);
  7685. // inner tail
  7686. // TODO: allow to customize different shapes
  7687. var xi = x - length * 0.9 * Math.cos(angle);
  7688. var yi = y - length * 0.9 * Math.sin(angle);
  7689. // left
  7690. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  7691. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  7692. // right
  7693. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  7694. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  7695. this.beginPath();
  7696. this.moveTo(x, y);
  7697. this.lineTo(xl, yl);
  7698. this.lineTo(xi, yi);
  7699. this.lineTo(xr, yr);
  7700. this.closePath();
  7701. };
  7702. /**
  7703. * Sets up the dashedLine functionality for drawing
  7704. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  7705. * @author David Jordan
  7706. * @date 2012-08-08
  7707. */
  7708. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  7709. if (!dashArray) dashArray=[10,5];
  7710. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  7711. var dashCount = dashArray.length;
  7712. this.moveTo(x, y);
  7713. var dx = (x2-x), dy = (y2-y);
  7714. var slope = dy/dx;
  7715. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  7716. var dashIndex=0, draw=true;
  7717. while (distRemaining>=0.1){
  7718. var dashLength = dashArray[dashIndex++%dashCount];
  7719. if (dashLength > distRemaining) dashLength = distRemaining;
  7720. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  7721. if (dx<0) xStep = -xStep;
  7722. x += xStep;
  7723. y += slope*xStep;
  7724. this[draw ? 'lineTo' : 'moveTo'](x,y);
  7725. distRemaining -= dashLength;
  7726. draw = !draw;
  7727. }
  7728. };
  7729. // TODO: add diamond shape
  7730. }
  7731. /**
  7732. * @class Node
  7733. * A node. A node can be connected to other nodes via one or multiple edges.
  7734. * @param {object} properties An object containing properties for the node. All
  7735. * properties are optional, except for the id.
  7736. * {number} id Id of the node. Required
  7737. * {string} label Text label for the node
  7738. * {number} x Horizontal position of the node
  7739. * {number} y Vertical position of the node
  7740. * {string} shape Node shape, available:
  7741. * "database", "circle", "ellipse",
  7742. * "box", "image", "text", "dot",
  7743. * "star", "triangle", "triangleDown",
  7744. * "square"
  7745. * {string} image An image url
  7746. * {string} title An title text, can be HTML
  7747. * {anytype} group A group name or number
  7748. * @param {Graph.Images} imagelist A list with images. Only needed
  7749. * when the node has an image
  7750. * @param {Graph.Groups} grouplist A list with groups. Needed for
  7751. * retrieving group properties
  7752. * @param {Object} constants An object with default values for
  7753. * example for the color
  7754. */
  7755. function Node(properties, imagelist, grouplist, constants) {
  7756. this.selected = false;
  7757. this.edges = []; // all edges connected to this node
  7758. this.dynamicEdges = [];
  7759. this.reroutedEdges = {};
  7760. this.group = constants.nodes.group;
  7761. this.fontSize = constants.nodes.fontSize;
  7762. this.fontFace = constants.nodes.fontFace;
  7763. this.fontColor = constants.nodes.fontColor;
  7764. this.color = constants.nodes.color;
  7765. // set defaults for the properties
  7766. this.id = undefined;
  7767. this.shape = constants.nodes.shape;
  7768. this.image = constants.nodes.image;
  7769. this.x = 0;
  7770. this.y = 0;
  7771. this.xFixed = false;
  7772. this.yFixed = false;
  7773. this.horizontalAlignLeft = true; // these are for the navigationUI
  7774. this.verticalAlignTop = true; // these are for the navigationUI
  7775. this.radius = constants.nodes.radius;
  7776. this.baseRadiusValue = constants.nodes.radius;
  7777. this.radiusFixed = false;
  7778. this.radiusMin = constants.nodes.radiusMin;
  7779. this.radiusMax = constants.nodes.radiusMax;
  7780. this.imagelist = imagelist;
  7781. this.grouplist = grouplist;
  7782. this.setProperties(properties, constants);
  7783. // creating the variables for clustering
  7784. this.resetCluster();
  7785. this.dynamicEdgesLength = 0;
  7786. this.clusterSession = 0;
  7787. this.clusterSizeWidthFactor = constants.clustering.clusterSizeWidthFactor;
  7788. this.clusterSizeHeightFactor = constants.clustering.clusterSizeHeightFactor;
  7789. this.clusterSizeRadiusFactor = constants.clustering.clusterSizeRadiusFactor;
  7790. // mass, force, velocity
  7791. this.mass = 1; // kg (mass is adjusted for the number of connected edges)
  7792. this.fx = 0.0; // external force x
  7793. this.fy = 0.0; // external force y
  7794. this.vx = 0.0; // velocity x
  7795. this.vy = 0.0; // velocity y
  7796. this.minForce = constants.minForce;
  7797. this.damping = 0.9;
  7798. this.dampingFactor = 75;
  7799. this.graphScaleInv = 1;
  7800. this.canvasTopLeft = {"x": -300, "y": -300};
  7801. this.canvasBottomRight = {"x": 300, "y": 300};
  7802. }
  7803. /**
  7804. * (re)setting the clustering variables and objects
  7805. */
  7806. Node.prototype.resetCluster = function() {
  7807. // clustering variables
  7808. this.formationScale = undefined; // this is used to determine when to open the cluster
  7809. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  7810. this.containedNodes = {};
  7811. this.containedEdges = {};
  7812. this.clusterSessions = [];
  7813. };
  7814. /**
  7815. * Attach a edge to the node
  7816. * @param {Edge} edge
  7817. */
  7818. Node.prototype.attachEdge = function(edge) {
  7819. if (this.edges.indexOf(edge) == -1) {
  7820. this.edges.push(edge);
  7821. }
  7822. if (this.dynamicEdges.indexOf(edge) == -1) {
  7823. this.dynamicEdges.push(edge);
  7824. }
  7825. this.dynamicEdgesLength = this.dynamicEdges.length;
  7826. this._updateMass();
  7827. };
  7828. /**
  7829. * Detach a edge from the node
  7830. * @param {Edge} edge
  7831. */
  7832. Node.prototype.detachEdge = function(edge) {
  7833. var index = this.edges.indexOf(edge);
  7834. if (index != -1) {
  7835. this.edges.splice(index, 1);
  7836. this.dynamicEdges.splice(index, 1);
  7837. }
  7838. this.dynamicEdgesLength = this.dynamicEdges.length;
  7839. this._updateMass();
  7840. };
  7841. /**
  7842. * Update the nodes mass, which is determined by the number of edges connecting
  7843. * to it (more edges -> heavier node).
  7844. * @private
  7845. */
  7846. Node.prototype._updateMass = function() {
  7847. this.mass = 1 + 0.6 * this.edges.length; // kg
  7848. };
  7849. /**
  7850. * Set or overwrite properties for the node
  7851. * @param {Object} properties an object with properties
  7852. * @param {Object} constants and object with default, global properties
  7853. */
  7854. Node.prototype.setProperties = function(properties, constants) {
  7855. if (!properties) {
  7856. return;
  7857. }
  7858. this.originalLabel = undefined;
  7859. // basic properties
  7860. if (properties.id !== undefined) {this.id = properties.id;}
  7861. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  7862. if (properties.title !== undefined) {this.title = properties.title;}
  7863. if (properties.group !== undefined) {this.group = properties.group;}
  7864. if (properties.x !== undefined) {this.x = properties.x;}
  7865. if (properties.y !== undefined) {this.y = properties.y;}
  7866. if (properties.value !== undefined) {this.value = properties.value;}
  7867. // navigationUI properties
  7868. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  7869. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  7870. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  7871. if (this.id === undefined) {
  7872. throw "Node must have an id";
  7873. }
  7874. // copy group properties
  7875. if (this.group) {
  7876. var groupObj = this.grouplist.get(this.group);
  7877. for (var prop in groupObj) {
  7878. if (groupObj.hasOwnProperty(prop)) {
  7879. this[prop] = groupObj[prop];
  7880. }
  7881. }
  7882. }
  7883. // individual shape properties
  7884. if (properties.shape !== undefined) {this.shape = properties.shape;}
  7885. if (properties.image !== undefined) {this.image = properties.image;}
  7886. if (properties.radius !== undefined) {this.radius = properties.radius;}
  7887. if (properties.color !== undefined) {this.color = Node.parseColor(properties.color);}
  7888. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  7889. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  7890. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  7891. if (this.image !== undefined) {
  7892. if (this.imagelist) {
  7893. this.imageObj = this.imagelist.load(this.image);
  7894. }
  7895. else {
  7896. throw "No imagelist provided";
  7897. }
  7898. }
  7899. this.xFixed = this.xFixed || (properties.x !== undefined);
  7900. this.yFixed = this.yFixed || (properties.y !== undefined);
  7901. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  7902. if (this.shape == 'image') {
  7903. this.radiusMin = constants.nodes.widthMin;
  7904. this.radiusMax = constants.nodes.widthMax;
  7905. }
  7906. // choose draw method depending on the shape
  7907. switch (this.shape) {
  7908. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  7909. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  7910. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  7911. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7912. // TODO: add diamond shape
  7913. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  7914. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  7915. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  7916. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  7917. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  7918. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  7919. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  7920. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7921. }
  7922. // reset the size of the node, this can be changed
  7923. this._reset();
  7924. };
  7925. /**
  7926. * Parse a color property into an object with border, background, and
  7927. * hightlight colors
  7928. * @param {Object | String} color
  7929. * @return {Object} colorObject
  7930. */
  7931. Node.parseColor = function(color) {
  7932. var c;
  7933. if (util.isString(color)) {
  7934. c = {
  7935. border: color,
  7936. background: color,
  7937. highlight: {
  7938. border: color,
  7939. background: color
  7940. }
  7941. };
  7942. // TODO: automatically generate a nice highlight color
  7943. }
  7944. else {
  7945. c = {};
  7946. c.background = color.background || 'white';
  7947. c.border = color.border || c.background;
  7948. if (util.isString(color.highlight)) {
  7949. c.highlight = {
  7950. border: color.highlight,
  7951. background: color.highlight
  7952. }
  7953. }
  7954. else {
  7955. c.highlight = {};
  7956. c.highlight.background = color.highlight && color.highlight.background || c.background;
  7957. c.highlight.border = color.highlight && color.highlight.border || c.border;
  7958. }
  7959. }
  7960. return c;
  7961. };
  7962. /**
  7963. * select this node
  7964. */
  7965. Node.prototype.select = function() {
  7966. this.selected = true;
  7967. this._reset();
  7968. };
  7969. /**
  7970. * unselect this node
  7971. */
  7972. Node.prototype.unselect = function() {
  7973. this.selected = false;
  7974. this._reset();
  7975. };
  7976. /**
  7977. * Reset the calculated size of the node, forces it to recalculate its size
  7978. */
  7979. Node.prototype.clearSizeCache = function() {
  7980. this._reset();
  7981. };
  7982. /**
  7983. * Reset the calculated size of the node, forces it to recalculate its size
  7984. * @private
  7985. */
  7986. Node.prototype._reset = function() {
  7987. this.width = undefined;
  7988. this.height = undefined;
  7989. };
  7990. /**
  7991. * get the title of this node.
  7992. * @return {string} title The title of the node, or undefined when no title
  7993. * has been set.
  7994. */
  7995. Node.prototype.getTitle = function() {
  7996. return this.title;
  7997. };
  7998. /**
  7999. * Calculate the distance to the border of the Node
  8000. * @param {CanvasRenderingContext2D} ctx
  8001. * @param {Number} angle Angle in radians
  8002. * @returns {number} distance Distance to the border in pixels
  8003. */
  8004. Node.prototype.distanceToBorder = function (ctx, angle) {
  8005. var borderWidth = 1;
  8006. if (!this.width) {
  8007. this.resize(ctx);
  8008. }
  8009. //noinspection FallthroughInSwitchStatementJS
  8010. switch (this.shape) {
  8011. case 'circle':
  8012. case 'dot':
  8013. return this.radius + borderWidth;
  8014. case 'ellipse':
  8015. var a = this.width / 2;
  8016. var b = this.height / 2;
  8017. var w = (Math.sin(angle) * a);
  8018. var h = (Math.cos(angle) * b);
  8019. return a * b / Math.sqrt(w * w + h * h);
  8020. // TODO: implement distanceToBorder for database
  8021. // TODO: implement distanceToBorder for triangle
  8022. // TODO: implement distanceToBorder for triangleDown
  8023. case 'box':
  8024. case 'image':
  8025. case 'text':
  8026. default:
  8027. if (this.width) {
  8028. return Math.min(
  8029. Math.abs(this.width / 2 / Math.cos(angle)),
  8030. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8031. // TODO: reckon with border radius too in case of box
  8032. }
  8033. else {
  8034. return 0;
  8035. }
  8036. }
  8037. // TODO: implement calculation of distance to border for all shapes
  8038. };
  8039. /**
  8040. * Set forces acting on the node
  8041. * @param {number} fx Force in horizontal direction
  8042. * @param {number} fy Force in vertical direction
  8043. */
  8044. Node.prototype._setForce = function(fx, fy) {
  8045. this.fx = fx;
  8046. this.fy = fy;
  8047. };
  8048. /**
  8049. * Add forces acting on the node
  8050. * @param {number} fx Force in horizontal direction
  8051. * @param {number} fy Force in vertical direction
  8052. * @private
  8053. */
  8054. Node.prototype._addForce = function(fx, fy) {
  8055. this.fx += fx;
  8056. this.fy += fy;
  8057. };
  8058. /**
  8059. * Perform one discrete step for the node
  8060. * @param {number} interval Time interval in seconds
  8061. */
  8062. Node.prototype.discreteStep = function(interval) {
  8063. if (!this.xFixed) {
  8064. var dx = -this.damping * this.vx; // damping force
  8065. var ax = (this.fx + dx) / this.mass; // acceleration
  8066. this.vx += ax * interval; // velocity
  8067. this.x += this.vx * interval; // position
  8068. }
  8069. if (!this.yFixed) {
  8070. var dy = -this.damping * this.vy; // damping force
  8071. var ay = (this.fy + dy) / this.mass; // acceleration
  8072. this.vy += ay * interval; // velocity
  8073. this.y += this.vy * interval; // position
  8074. }
  8075. };
  8076. /**
  8077. * Check if this node has a fixed x and y position
  8078. * @return {boolean} true if fixed, false if not
  8079. */
  8080. Node.prototype.isFixed = function() {
  8081. return (this.xFixed && this.yFixed);
  8082. };
  8083. /**
  8084. * Check if this node is moving
  8085. * @param {number} vmin the minimum velocity considered as "moving"
  8086. * @return {boolean} true if moving, false if it has no velocity
  8087. */
  8088. // TODO: replace this method with calculating the kinetic energy
  8089. Node.prototype.isMoving = function(vmin) {
  8090. if (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin) {
  8091. return true;
  8092. }
  8093. else {
  8094. this.vx = 0; this.vy = 0;
  8095. return false;
  8096. }
  8097. //return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8098. };
  8099. /**
  8100. * check if this node is selecte
  8101. * @return {boolean} selected True if node is selected, else false
  8102. */
  8103. Node.prototype.isSelected = function() {
  8104. return this.selected;
  8105. };
  8106. /**
  8107. * Retrieve the value of the node. Can be undefined
  8108. * @return {Number} value
  8109. */
  8110. Node.prototype.getValue = function() {
  8111. return this.value;
  8112. };
  8113. /**
  8114. * Calculate the distance from the nodes location to the given location (x,y)
  8115. * @param {Number} x
  8116. * @param {Number} y
  8117. * @return {Number} value
  8118. */
  8119. Node.prototype.getDistance = function(x, y) {
  8120. var dx = this.x - x,
  8121. dy = this.y - y;
  8122. return Math.sqrt(dx * dx + dy * dy);
  8123. };
  8124. /**
  8125. * Adjust the value range of the node. The node will adjust it's radius
  8126. * based on its value.
  8127. * @param {Number} min
  8128. * @param {Number} max
  8129. */
  8130. Node.prototype.setValueRange = function(min, max) {
  8131. if (!this.radiusFixed && this.value !== undefined) {
  8132. if (max == min) {
  8133. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8134. }
  8135. else {
  8136. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8137. this.radius = (this.value - min) * scale + this.radiusMin;
  8138. }
  8139. }
  8140. this.baseRadiusValue = this.radius;
  8141. };
  8142. /**
  8143. * Draw this node in the given canvas
  8144. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8145. * @param {CanvasRenderingContext2D} ctx
  8146. */
  8147. Node.prototype.draw = function(ctx) {
  8148. throw "Draw method not initialized for node";
  8149. };
  8150. /**
  8151. * Recalculate the size of this node in the given canvas
  8152. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8153. * @param {CanvasRenderingContext2D} ctx
  8154. */
  8155. Node.prototype.resize = function(ctx) {
  8156. throw "Resize method not initialized for node";
  8157. };
  8158. /**
  8159. * Check if this object is overlapping with the provided object
  8160. * @param {Object} obj an object with parameters left, top, right, bottom
  8161. * @return {boolean} True if location is located on node
  8162. */
  8163. Node.prototype.isOverlappingWith = function(obj) {
  8164. return (this.left < obj.right &&
  8165. this.left + this.width > obj.left &&
  8166. this.top < obj.bottom &&
  8167. this.top + this.height > obj.top);
  8168. };
  8169. Node.prototype._resizeImage = function (ctx) {
  8170. // TODO: pre calculate the image size
  8171. if (!this.width || !this.height) { // undefined or 0
  8172. var width, height;
  8173. if (this.value) {
  8174. this.radius = this.baseRadiusValue;
  8175. var scale = this.imageObj.height / this.imageObj.width;
  8176. if (scale !== undefined) {
  8177. width = this.radius || this.imageObj.width;
  8178. height = this.radius * scale || this.imageObj.height;
  8179. }
  8180. else {
  8181. width = 0;
  8182. height = 0;
  8183. }
  8184. }
  8185. else {
  8186. width = this.imageObj.width;
  8187. height = this.imageObj.height;
  8188. }
  8189. this.width = width;
  8190. this.height = height;
  8191. if (this.width > 0 && this.height > 0) {
  8192. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8193. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8194. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8195. }
  8196. }
  8197. };
  8198. Node.prototype._drawImage = function (ctx) {
  8199. this._resizeImage(ctx);
  8200. this.left = this.x - this.width / 2;
  8201. this.top = this.y - this.height / 2;
  8202. var yLabel;
  8203. if (this.imageObj.width != 0 ) {
  8204. // draw the shade
  8205. if (this.clusterSize > 1) {
  8206. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8207. lineWidth *= this.graphScaleInv;
  8208. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8209. ctx.globalAlpha = 0.5;
  8210. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8211. }
  8212. // draw the image
  8213. ctx.globalAlpha = 1.0;
  8214. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8215. yLabel = this.y + this.height / 2;
  8216. }
  8217. else {
  8218. // image still loading... just draw the label for now
  8219. yLabel = this.y;
  8220. }
  8221. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8222. };
  8223. Node.prototype._resizeBox = function (ctx) {
  8224. if (!this.width) {
  8225. var margin = 5;
  8226. var textSize = this.getTextSize(ctx);
  8227. this.width = textSize.width + 2 * margin;
  8228. this.height = textSize.height + 2 * margin;
  8229. this.width += (this.clusterSize - 1) * 0.5 * this.clusterSizeWidthFactor;
  8230. this.height += (this.clusterSize - 1) * 0.5 * this.clusterSizeHeightFactor;
  8231. // this.radius += (this.clusterSize - 1) * 0.5 * this.clusterSizeRadiusFactor;
  8232. }
  8233. };
  8234. Node.prototype._drawBox = function (ctx) {
  8235. this._resizeBox(ctx);
  8236. this.left = this.x - this.width / 2;
  8237. this.top = this.y - this.height / 2;
  8238. var clusterLineWidth = 2.5;
  8239. var selectionLineWidth = 2;
  8240. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8241. // draw the outer border
  8242. if (this.clusterSize > 1) {
  8243. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8244. ctx.lineWidth *= this.graphScaleInv;
  8245. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8246. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8247. ctx.stroke();
  8248. }
  8249. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8250. ctx.lineWidth *= this.graphScaleInv;
  8251. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8252. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8253. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8254. ctx.fill();
  8255. ctx.stroke();
  8256. this._label(ctx, this.label, this.x, this.y);
  8257. };
  8258. Node.prototype._resizeDatabase = function (ctx) {
  8259. if (!this.width) {
  8260. var margin = 5;
  8261. var textSize = this.getTextSize(ctx);
  8262. var size = textSize.width + 2 * margin;
  8263. this.width = size;
  8264. this.height = size;
  8265. // scaling used for clustering
  8266. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8267. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8268. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8269. }
  8270. };
  8271. Node.prototype._drawDatabase = function (ctx) {
  8272. this._resizeDatabase(ctx);
  8273. this.left = this.x - this.width / 2;
  8274. this.top = this.y - this.height / 2;
  8275. var clusterLineWidth = 2.5;
  8276. var selectionLineWidth = 2;
  8277. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8278. // draw the outer border
  8279. if (this.clusterSize > 1) {
  8280. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8281. ctx.lineWidth *= this.graphScaleInv;
  8282. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8283. 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);
  8284. ctx.stroke();
  8285. }
  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.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8290. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8291. ctx.fill();
  8292. ctx.stroke();
  8293. this._label(ctx, this.label, this.x, this.y);
  8294. };
  8295. Node.prototype._resizeCircle = function (ctx) {
  8296. if (!this.width) {
  8297. var margin = 5;
  8298. var textSize = this.getTextSize(ctx);
  8299. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8300. this.radius = diameter / 2;
  8301. this.width = diameter;
  8302. this.height = diameter;
  8303. // scaling used for clustering
  8304. // this.width += (this.clusterSize - 1) * 0.5 * this.clusterSizeWidthFactor;
  8305. // this.height += (this.clusterSize - 1) * 0.5 * this.clusterSizeHeightFactor;
  8306. this.radius += (this.clusterSize - 1) * 0.5 * this.clusterSizeRadiusFactor;
  8307. }
  8308. };
  8309. Node.prototype._drawCircle = function (ctx) {
  8310. this._resizeCircle(ctx);
  8311. this.left = this.x - this.width / 2;
  8312. this.top = this.y - this.height / 2;
  8313. var clusterLineWidth = 2.5;
  8314. var selectionLineWidth = 2;
  8315. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8316. // draw the outer border
  8317. if (this.clusterSize > 1) {
  8318. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8319. ctx.lineWidth *= this.graphScaleInv;
  8320. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8321. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8322. ctx.stroke();
  8323. }
  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.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8328. ctx.circle(this.x, this.y, this.radius);
  8329. ctx.fill();
  8330. ctx.stroke();
  8331. this._label(ctx, this.label, this.x, this.y);
  8332. };
  8333. Node.prototype._resizeEllipse = function (ctx) {
  8334. if (!this.width) {
  8335. var textSize = this.getTextSize(ctx);
  8336. this.width = textSize.width * 1.5;
  8337. this.height = textSize.height * 2;
  8338. if (this.width < this.height) {
  8339. this.width = this.height;
  8340. }
  8341. // scaling used for clustering
  8342. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8343. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8344. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8345. }
  8346. };
  8347. Node.prototype._drawEllipse = function (ctx) {
  8348. this._resizeEllipse(ctx);
  8349. this.left = this.x - this.width / 2;
  8350. this.top = this.y - this.height / 2;
  8351. var clusterLineWidth = 2.5;
  8352. var selectionLineWidth = 2;
  8353. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8354. // draw the outer border
  8355. if (this.clusterSize > 1) {
  8356. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8357. ctx.lineWidth *= this.graphScaleInv;
  8358. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8359. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8360. ctx.stroke();
  8361. }
  8362. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8363. ctx.lineWidth *= this.graphScaleInv;
  8364. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8365. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8366. ctx.ellipse(this.left, this.top, this.width, this.height);
  8367. ctx.fill();
  8368. ctx.stroke();
  8369. this._label(ctx, this.label, this.x, this.y);
  8370. };
  8371. Node.prototype._drawDot = function (ctx) {
  8372. this._drawShape(ctx, 'circle');
  8373. };
  8374. Node.prototype._drawTriangle = function (ctx) {
  8375. this._drawShape(ctx, 'triangle');
  8376. };
  8377. Node.prototype._drawTriangleDown = function (ctx) {
  8378. this._drawShape(ctx, 'triangleDown');
  8379. };
  8380. Node.prototype._drawSquare = function (ctx) {
  8381. this._drawShape(ctx, 'square');
  8382. };
  8383. Node.prototype._drawStar = function (ctx) {
  8384. this._drawShape(ctx, 'star');
  8385. };
  8386. Node.prototype._resizeShape = function (ctx) {
  8387. if (!this.width) {
  8388. this.radius = this.baseRadiusValue;
  8389. var size = 2 * this.radius;
  8390. this.width = size;
  8391. this.height = size;
  8392. // scaling used for clustering
  8393. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8394. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8395. this.radius += (this.clusterSize - 1) * 0.5 * this.clusterSizeRadiusFactor;
  8396. }
  8397. };
  8398. Node.prototype._drawShape = function (ctx, shape) {
  8399. this._resizeShape(ctx);
  8400. this.left = this.x - this.width / 2;
  8401. this.top = this.y - this.height / 2;
  8402. var clusterLineWidth = 2.5;
  8403. var selectionLineWidth = 2;
  8404. var radiusMultiplier = 2;
  8405. // choose draw method depending on the shape
  8406. switch (shape) {
  8407. case 'dot': radiusMultiplier = 2; break;
  8408. case 'square': radiusMultiplier = 2; break;
  8409. case 'triangle': radiusMultiplier = 3; break;
  8410. case 'triangleDown': radiusMultiplier = 3; break;
  8411. case 'star': radiusMultiplier = 4; break;
  8412. }
  8413. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8414. // draw the outer border
  8415. if (this.clusterSize > 1) {
  8416. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8417. ctx.lineWidth *= this.graphScaleInv;
  8418. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8419. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8420. ctx.stroke();
  8421. }
  8422. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8423. ctx.lineWidth *= this.graphScaleInv;
  8424. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8425. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8426. ctx[shape](this.x, this.y, this.radius);
  8427. ctx.fill();
  8428. ctx.stroke();
  8429. if (this.label) {
  8430. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8431. }
  8432. };
  8433. Node.prototype._resizeText = function (ctx) {
  8434. if (!this.width) {
  8435. var margin = 5;
  8436. var textSize = this.getTextSize(ctx);
  8437. this.width = textSize.width + 2 * margin;
  8438. this.height = textSize.height + 2 * margin;
  8439. // scaling used for clustering
  8440. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8441. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8442. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8443. }
  8444. };
  8445. Node.prototype._drawText = function (ctx) {
  8446. this._resizeText(ctx);
  8447. this.left = this.x - this.width / 2;
  8448. this.top = this.y - this.height / 2;
  8449. this._label(ctx, this.label, this.x, this.y);
  8450. };
  8451. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  8452. if (text) {
  8453. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8454. ctx.fillStyle = this.fontColor || "black";
  8455. ctx.textAlign = align || "center";
  8456. ctx.textBaseline = baseline || "middle";
  8457. var lines = text.split('\n'),
  8458. lineCount = lines.length,
  8459. fontSize = (this.fontSize + 4),
  8460. yLine = y + (1 - lineCount) / 2 * fontSize;
  8461. for (var i = 0; i < lineCount; i++) {
  8462. ctx.fillText(lines[i], x, yLine);
  8463. yLine += fontSize;
  8464. }
  8465. }
  8466. };
  8467. Node.prototype.getTextSize = function(ctx) {
  8468. if (this.label !== undefined) {
  8469. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8470. var lines = this.label.split('\n'),
  8471. height = (this.fontSize + 4) * lines.length,
  8472. width = 0;
  8473. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  8474. width = Math.max(width, ctx.measureText(lines[i]).width);
  8475. }
  8476. return {"width": width, "height": height};
  8477. }
  8478. else {
  8479. return {"width": 0, "height": 0};
  8480. }
  8481. };
  8482. /**
  8483. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  8484. * there is a safety margin of 0.3 * width;
  8485. *
  8486. * @returns {boolean}
  8487. */
  8488. Node.prototype.inArea = function() {
  8489. if (this.width !== undefined) {
  8490. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  8491. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  8492. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  8493. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  8494. }
  8495. else {
  8496. return true;
  8497. }
  8498. }
  8499. /**
  8500. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  8501. * @returns {boolean}
  8502. */
  8503. Node.prototype.inView = function() {
  8504. return (this.x >= this.canvasTopLeft.x &&
  8505. this.x < this.canvasBottomRight.x &&
  8506. this.y >= this.canvasTopLeft.y &&
  8507. this.y < this.canvasBottomRight.y);
  8508. }
  8509. /**
  8510. * This allows the zoom level of the graph to influence the rendering
  8511. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  8512. *
  8513. * @param scale
  8514. * @param canvasTopLeft
  8515. * @param canvasBottomRight
  8516. */
  8517. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  8518. this.graphScaleInv = 1.0/scale;
  8519. this.canvasTopLeft = canvasTopLeft;
  8520. this.canvasBottomRight = canvasBottomRight;
  8521. };
  8522. /**
  8523. * This allows the zoom level of the graph to influence the rendering
  8524. *
  8525. * @param scale
  8526. */
  8527. Node.prototype.setScale = function(scale) {
  8528. this.graphScaleInv = 1.0/scale;
  8529. };
  8530. /**
  8531. * This function updates the damping parameter for clusters, based ont he
  8532. *
  8533. * @param {Number} numberOfNodes
  8534. */
  8535. Node.prototype.updateDamping = function(numberOfNodes) {
  8536. this.damping = (0.8 + 0.1*this.clusterSize * (1 + Math.pow(numberOfNodes,-2)));
  8537. this.damping *= this.dampingFactor;
  8538. };
  8539. /**
  8540. * set the velocity at 0. Is called when this node is contained in another during clustering
  8541. */
  8542. Node.prototype.clearVelocity = function() {
  8543. this.vx = 0;
  8544. this.vy = 0;
  8545. };
  8546. /**
  8547. * Basic preservation of (kinectic) energy
  8548. *
  8549. * @param massBeforeClustering
  8550. */
  8551. Node.prototype.updateVelocity = function(massBeforeClustering) {
  8552. var energyBefore = this.vx * this.vx * massBeforeClustering;
  8553. this.vx = Math.sqrt(energyBefore/this.mass);
  8554. energyBefore = this.vy * this.vy * massBeforeClustering;
  8555. this.vy = Math.sqrt(energyBefore/this.mass);
  8556. };
  8557. /**
  8558. * @class Edge
  8559. *
  8560. * A edge connects two nodes
  8561. * @param {Object} properties Object with properties. Must contain
  8562. * At least properties from and to.
  8563. * Available properties: from (number),
  8564. * to (number), label (string, color (string),
  8565. * width (number), style (string),
  8566. * length (number), title (string)
  8567. * @param {Graph} graph A graph object, used to find and edge to
  8568. * nodes.
  8569. * @param {Object} constants An object with default values for
  8570. * example for the color
  8571. */
  8572. function Edge (properties, graph, constants) {
  8573. if (!graph) {
  8574. throw "No graph provided";
  8575. }
  8576. this.graph = graph;
  8577. // initialize constants
  8578. this.widthMin = constants.edges.widthMin;
  8579. this.widthMax = constants.edges.widthMax;
  8580. // initialize variables
  8581. this.id = undefined;
  8582. this.fromId = undefined;
  8583. this.toId = undefined;
  8584. this.style = constants.edges.style;
  8585. this.title = undefined;
  8586. this.width = constants.edges.width;
  8587. this.value = undefined;
  8588. this.length = constants.edges.length;
  8589. this.from = null; // a node
  8590. this.to = null; // a node
  8591. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  8592. // by storing the original information we can revert to the original connection when the cluser is opened.
  8593. this.originalFromId = [];
  8594. this.originalToId = [];
  8595. this.connected = false;
  8596. // Added to support dashed lines
  8597. // David Jordan
  8598. // 2012-08-08
  8599. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  8600. this.stiffness = undefined; // depends on the length of the edge
  8601. this.color = constants.edges.color;
  8602. this.widthFixed = false;
  8603. this.lengthFixed = false;
  8604. this.setProperties(properties, constants);
  8605. }
  8606. /**
  8607. * Set or overwrite properties for the edge
  8608. * @param {Object} properties an object with properties
  8609. * @param {Object} constants and object with default, global properties
  8610. */
  8611. Edge.prototype.setProperties = function(properties, constants) {
  8612. if (!properties) {
  8613. return;
  8614. }
  8615. if (properties.from !== undefined) {this.fromId = properties.from;}
  8616. if (properties.to !== undefined) {this.toId = properties.to;}
  8617. if (properties.id !== undefined) {this.id = properties.id;}
  8618. if (properties.style !== undefined) {this.style = properties.style;}
  8619. if (properties.label !== undefined) {this.label = properties.label;}
  8620. if (this.label) {
  8621. this.fontSize = constants.edges.fontSize;
  8622. this.fontFace = constants.edges.fontFace;
  8623. this.fontColor = constants.edges.fontColor;
  8624. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8625. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8626. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8627. }
  8628. if (properties.title !== undefined) {this.title = properties.title;}
  8629. if (properties.width !== undefined) {this.width = properties.width;}
  8630. if (properties.value !== undefined) {this.value = properties.value;}
  8631. if (properties.length !== undefined) {this.length = properties.length;}
  8632. // Added to support dashed lines
  8633. // David Jordan
  8634. // 2012-08-08
  8635. if (properties.dash) {
  8636. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  8637. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  8638. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  8639. }
  8640. if (properties.color !== undefined) {this.color = properties.color;}
  8641. // A node is connected when it has a from and to node.
  8642. this.connect();
  8643. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  8644. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  8645. this.stiffness = 1 / this.length;
  8646. // set draw method based on style
  8647. switch (this.style) {
  8648. case 'line': this.draw = this._drawLine; break;
  8649. case 'arrow': this.draw = this._drawArrow; break;
  8650. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  8651. case 'dash-line': this.draw = this._drawDashLine; break;
  8652. default: this.draw = this._drawLine; break;
  8653. }
  8654. };
  8655. /**
  8656. * Connect an edge to its nodes
  8657. */
  8658. Edge.prototype.connect = function () {
  8659. this.disconnect();
  8660. this.from = this.graph.nodes[this.fromId] || null;
  8661. this.to = this.graph.nodes[this.toId] || null;
  8662. this.connected = (this.from && this.to);
  8663. if (this.connected) {
  8664. this.from.attachEdge(this);
  8665. this.to.attachEdge(this);
  8666. }
  8667. else {
  8668. if (this.from) {
  8669. this.from.detachEdge(this);
  8670. }
  8671. if (this.to) {
  8672. this.to.detachEdge(this);
  8673. }
  8674. }
  8675. };
  8676. /**
  8677. * Disconnect an edge from its nodes
  8678. */
  8679. Edge.prototype.disconnect = function () {
  8680. if (this.from) {
  8681. this.from.detachEdge(this);
  8682. this.from = null;
  8683. }
  8684. if (this.to) {
  8685. this.to.detachEdge(this);
  8686. this.to = null;
  8687. }
  8688. this.connected = false;
  8689. };
  8690. /**
  8691. * get the title of this edge.
  8692. * @return {string} title The title of the edge, or undefined when no title
  8693. * has been set.
  8694. */
  8695. Edge.prototype.getTitle = function() {
  8696. return this.title;
  8697. };
  8698. /**
  8699. * Retrieve the value of the edge. Can be undefined
  8700. * @return {Number} value
  8701. */
  8702. Edge.prototype.getValue = function() {
  8703. return this.value;
  8704. };
  8705. /**
  8706. * Adjust the value range of the edge. The edge will adjust it's width
  8707. * based on its value.
  8708. * @param {Number} min
  8709. * @param {Number} max
  8710. */
  8711. Edge.prototype.setValueRange = function(min, max) {
  8712. if (!this.widthFixed && this.value !== undefined) {
  8713. var scale = (this.widthMax - this.widthMin) / (max - min);
  8714. this.width = (this.value - min) * scale + this.widthMin;
  8715. }
  8716. };
  8717. /**
  8718. * Redraw a edge
  8719. * Draw this edge in the given canvas
  8720. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8721. * @param {CanvasRenderingContext2D} ctx
  8722. */
  8723. Edge.prototype.draw = function(ctx) {
  8724. throw "Method draw not initialized in edge";
  8725. };
  8726. /**
  8727. * Check if this object is overlapping with the provided object
  8728. * @param {Object} obj an object with parameters left, top
  8729. * @return {boolean} True if location is located on the edge
  8730. */
  8731. Edge.prototype.isOverlappingWith = function(obj) {
  8732. var distMax = 10;
  8733. var xFrom = this.from.x;
  8734. var yFrom = this.from.y;
  8735. var xTo = this.to.x;
  8736. var yTo = this.to.y;
  8737. var xObj = obj.left;
  8738. var yObj = obj.top;
  8739. var dist = Edge._dist(xFrom, yFrom, xTo, yTo, xObj, yObj);
  8740. return (dist < distMax);
  8741. };
  8742. /**
  8743. * Redraw a edge as a line
  8744. * Draw this edge in the given canvas
  8745. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8746. * @param {CanvasRenderingContext2D} ctx
  8747. * @private
  8748. */
  8749. Edge.prototype._drawLine = function(ctx) {
  8750. // set style
  8751. ctx.strokeStyle = this.color;
  8752. ctx.lineWidth = this._getLineWidth();
  8753. var point;
  8754. if (this.from != this.to) {
  8755. // draw line
  8756. this._line(ctx);
  8757. // draw label
  8758. if (this.label) {
  8759. point = this._pointOnLine(0.5);
  8760. this._label(ctx, this.label, point.x, point.y);
  8761. }
  8762. }
  8763. else {
  8764. var x, y;
  8765. var radius = this.length / 4;
  8766. var node = this.from;
  8767. if (!node.width) {
  8768. node.resize(ctx);
  8769. }
  8770. if (node.width > node.height) {
  8771. x = node.x + node.width / 2;
  8772. y = node.y - radius;
  8773. }
  8774. else {
  8775. x = node.x + radius;
  8776. y = node.y - node.height / 2;
  8777. }
  8778. this._circle(ctx, x, y, radius);
  8779. point = this._pointOnCircle(x, y, radius, 0.5);
  8780. this._label(ctx, this.label, point.x, point.y);
  8781. }
  8782. };
  8783. /**
  8784. * Get the line width of the edge. Depends on width and whether one of the
  8785. * connected nodes is selected.
  8786. * @return {Number} width
  8787. * @private
  8788. */
  8789. Edge.prototype._getLineWidth = function() {
  8790. if (this.from.selected || this.to.selected) {
  8791. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  8792. }
  8793. else {
  8794. return this.width*this.graphScaleInv;
  8795. }
  8796. };
  8797. /**
  8798. * Draw a line between two nodes
  8799. * @param {CanvasRenderingContext2D} ctx
  8800. * @private
  8801. */
  8802. Edge.prototype._line = function (ctx) {
  8803. // draw a straight line
  8804. ctx.beginPath();
  8805. ctx.moveTo(this.from.x, this.from.y);
  8806. ctx.lineTo(this.to.x, this.to.y);
  8807. ctx.stroke();
  8808. };
  8809. /**
  8810. * Draw a line from a node to itself, a circle
  8811. * @param {CanvasRenderingContext2D} ctx
  8812. * @param {Number} x
  8813. * @param {Number} y
  8814. * @param {Number} radius
  8815. * @private
  8816. */
  8817. Edge.prototype._circle = function (ctx, x, y, radius) {
  8818. // draw a circle
  8819. ctx.beginPath();
  8820. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  8821. ctx.stroke();
  8822. };
  8823. /**
  8824. * Draw label with white background and with the middle at (x, y)
  8825. * @param {CanvasRenderingContext2D} ctx
  8826. * @param {String} text
  8827. * @param {Number} x
  8828. * @param {Number} y
  8829. * @private
  8830. */
  8831. Edge.prototype._label = function (ctx, text, x, y) {
  8832. if (text) {
  8833. // TODO: cache the calculated size
  8834. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  8835. this.fontSize + "px " + this.fontFace;
  8836. ctx.fillStyle = 'white';
  8837. var width = ctx.measureText(text).width;
  8838. var height = this.fontSize;
  8839. var left = x - width / 2;
  8840. var top = y - height / 2;
  8841. ctx.fillRect(left, top, width, height);
  8842. // draw text
  8843. ctx.fillStyle = this.fontColor || "black";
  8844. ctx.textAlign = "left";
  8845. ctx.textBaseline = "top";
  8846. ctx.fillText(text, left, top);
  8847. }
  8848. };
  8849. /**
  8850. * Redraw a edge as a dashed line
  8851. * Draw this edge in the given canvas
  8852. * @author David Jordan
  8853. * @date 2012-08-08
  8854. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8855. * @param {CanvasRenderingContext2D} ctx
  8856. * @private
  8857. */
  8858. Edge.prototype._drawDashLine = function(ctx) {
  8859. // set style
  8860. ctx.strokeStyle = this.color;
  8861. ctx.lineWidth = this._getLineWidth();
  8862. // draw dashed line
  8863. ctx.beginPath();
  8864. ctx.lineCap = 'round';
  8865. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  8866. {
  8867. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8868. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  8869. }
  8870. 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
  8871. {
  8872. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8873. [this.dash.length,this.dash.gap]);
  8874. }
  8875. else //If all else fails draw a line
  8876. {
  8877. ctx.moveTo(this.from.x, this.from.y);
  8878. ctx.lineTo(this.to.x, this.to.y);
  8879. }
  8880. ctx.stroke();
  8881. // draw label
  8882. if (this.label) {
  8883. var point = this._pointOnLine(0.5);
  8884. this._label(ctx, this.label, point.x, point.y);
  8885. }
  8886. };
  8887. /**
  8888. * Get a point on a line
  8889. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8890. * @return {Object} point
  8891. * @private
  8892. */
  8893. Edge.prototype._pointOnLine = function (percentage) {
  8894. return {
  8895. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  8896. y: (1 - percentage) * this.from.y + percentage * this.to.y
  8897. }
  8898. };
  8899. /**
  8900. * Get a point on a circle
  8901. * @param {Number} x
  8902. * @param {Number} y
  8903. * @param {Number} radius
  8904. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8905. * @return {Object} point
  8906. * @private
  8907. */
  8908. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  8909. var angle = (percentage - 3/8) * 2 * Math.PI;
  8910. return {
  8911. x: x + radius * Math.cos(angle),
  8912. y: y - radius * Math.sin(angle)
  8913. }
  8914. };
  8915. /**
  8916. * Redraw a edge as a line with an arrow halfway the line
  8917. * Draw this edge in the given canvas
  8918. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8919. * @param {CanvasRenderingContext2D} ctx
  8920. * @private
  8921. */
  8922. Edge.prototype._drawArrowCenter = function(ctx) {
  8923. var point;
  8924. // set style
  8925. ctx.strokeStyle = this.color;
  8926. ctx.fillStyle = this.color;
  8927. ctx.lineWidth = this._getLineWidth();
  8928. if (this.from != this.to) {
  8929. // draw line
  8930. this._line(ctx);
  8931. // draw an arrow halfway the line
  8932. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8933. var length = 10 + 5 * this.width; // TODO: make customizable?
  8934. point = this._pointOnLine(0.5);
  8935. ctx.arrow(point.x, point.y, angle, length);
  8936. ctx.fill();
  8937. ctx.stroke();
  8938. // draw label
  8939. if (this.label) {
  8940. point = this._pointOnLine(0.5);
  8941. this._label(ctx, this.label, point.x, point.y);
  8942. }
  8943. }
  8944. else {
  8945. // draw circle
  8946. var x, y;
  8947. var radius = this.length / 4;
  8948. var node = this.from;
  8949. if (!node.width) {
  8950. node.resize(ctx);
  8951. }
  8952. if (node.width > node.height) {
  8953. x = node.x + node.width / 2;
  8954. y = node.y - radius;
  8955. }
  8956. else {
  8957. x = node.x + radius;
  8958. y = node.y - node.height / 2;
  8959. }
  8960. this._circle(ctx, x, y, radius);
  8961. // draw all arrows
  8962. var angle = 0.2 * Math.PI;
  8963. var length = 10 + 5 * this.width; // TODO: make customizable?
  8964. point = this._pointOnCircle(x, y, radius, 0.5);
  8965. ctx.arrow(point.x, point.y, angle, length);
  8966. ctx.fill();
  8967. ctx.stroke();
  8968. // draw label
  8969. if (this.label) {
  8970. point = this._pointOnCircle(x, y, radius, 0.5);
  8971. this._label(ctx, this.label, point.x, point.y);
  8972. }
  8973. }
  8974. };
  8975. /**
  8976. * Redraw a edge as a line with an arrow
  8977. * Draw this edge in the given canvas
  8978. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8979. * @param {CanvasRenderingContext2D} ctx
  8980. * @private
  8981. */
  8982. Edge.prototype._drawArrow = function(ctx) {
  8983. // set style
  8984. ctx.strokeStyle = this.color;
  8985. ctx.fillStyle = this.color;
  8986. ctx.lineWidth = this._getLineWidth();
  8987. // draw line
  8988. var angle, length;
  8989. if (this.from != this.to) {
  8990. // calculate length and angle of the line
  8991. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8992. var dx = (this.to.x - this.from.x);
  8993. var dy = (this.to.y - this.from.y);
  8994. var lEdge = Math.sqrt(dx * dx + dy * dy);
  8995. var lFrom = this.from.distanceToBorder(ctx, angle + Math.PI);
  8996. var pFrom = (lEdge - lFrom) / lEdge;
  8997. var xFrom = (pFrom) * this.from.x + (1 - pFrom) * this.to.x;
  8998. var yFrom = (pFrom) * this.from.y + (1 - pFrom) * this.to.y;
  8999. var lTo = this.to.distanceToBorder(ctx, angle);
  9000. var pTo = (lEdge - lTo) / lEdge;
  9001. var xTo = (1 - pTo) * this.from.x + pTo * this.to.x;
  9002. var yTo = (1 - pTo) * this.from.y + pTo * this.to.y;
  9003. ctx.beginPath();
  9004. ctx.moveTo(xFrom, yFrom);
  9005. ctx.lineTo(xTo, yTo);
  9006. ctx.stroke();
  9007. // draw arrow at the end of the line
  9008. length = 10 + 5 * this.width; // TODO: make customizable?
  9009. ctx.arrow(xTo, yTo, angle, length);
  9010. ctx.fill();
  9011. ctx.stroke();
  9012. // draw label
  9013. if (this.label) {
  9014. var point = this._pointOnLine(0.5);
  9015. this._label(ctx, this.label, point.x, point.y);
  9016. }
  9017. }
  9018. else {
  9019. // draw circle
  9020. var node = this.from;
  9021. var x, y, arrow;
  9022. var radius = this.length / 4;
  9023. if (!node.width) {
  9024. node.resize(ctx);
  9025. }
  9026. if (node.width > node.height) {
  9027. x = node.x + node.width / 2;
  9028. y = node.y - radius;
  9029. arrow = {
  9030. x: x,
  9031. y: node.y,
  9032. angle: 0.9 * Math.PI
  9033. };
  9034. }
  9035. else {
  9036. x = node.x + radius;
  9037. y = node.y - node.height / 2;
  9038. arrow = {
  9039. x: node.x,
  9040. y: y,
  9041. angle: 0.6 * Math.PI
  9042. };
  9043. }
  9044. ctx.beginPath();
  9045. // TODO: do not draw a circle, but an arc
  9046. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9047. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9048. ctx.stroke();
  9049. // draw all arrows
  9050. length = 10 + 5 * this.width; // TODO: make customizable?
  9051. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9052. ctx.fill();
  9053. ctx.stroke();
  9054. // draw label
  9055. if (this.label) {
  9056. point = this._pointOnCircle(x, y, radius, 0.5);
  9057. this._label(ctx, this.label, point.x, point.y);
  9058. }
  9059. }
  9060. };
  9061. /**
  9062. * Calculate the distance between a point (x3,y3) and a line segment from
  9063. * (x1,y1) to (x2,y2).
  9064. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9065. * @param {number} x1
  9066. * @param {number} y1
  9067. * @param {number} x2
  9068. * @param {number} y2
  9069. * @param {number} x3
  9070. * @param {number} y3
  9071. * @private
  9072. */
  9073. Edge._dist = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9074. var px = x2-x1,
  9075. py = y2-y1,
  9076. something = px*px + py*py,
  9077. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9078. if (u > 1) {
  9079. u = 1;
  9080. }
  9081. else if (u < 0) {
  9082. u = 0;
  9083. }
  9084. var x = x1 + u * px,
  9085. y = y1 + u * py,
  9086. dx = x - x3,
  9087. dy = y - y3;
  9088. //# Note: If the actual distance does not matter,
  9089. //# if you only want to compare what this function
  9090. //# returns to other results of this function, you
  9091. //# can just return the squared distance instead
  9092. //# (i.e. remove the sqrt) to gain a little performance
  9093. return Math.sqrt(dx*dx + dy*dy);
  9094. };
  9095. /**
  9096. * This allows the zoom level of the graph to influence the rendering
  9097. *
  9098. * @param scale
  9099. */
  9100. Edge.prototype.setScale = function(scale) {
  9101. this.graphScaleInv = 1.0/scale;
  9102. };
  9103. /**
  9104. * Popup is a class to create a popup window with some text
  9105. * @param {Element} container The container object.
  9106. * @param {Number} [x]
  9107. * @param {Number} [y]
  9108. * @param {String} [text]
  9109. */
  9110. function Popup(container, x, y, text) {
  9111. if (container) {
  9112. this.container = container;
  9113. }
  9114. else {
  9115. this.container = document.body;
  9116. }
  9117. this.x = 0;
  9118. this.y = 0;
  9119. this.padding = 5;
  9120. if (x !== undefined && y !== undefined ) {
  9121. this.setPosition(x, y);
  9122. }
  9123. if (text !== undefined) {
  9124. this.setText(text);
  9125. }
  9126. // create the frame
  9127. this.frame = document.createElement("div");
  9128. var style = this.frame.style;
  9129. style.position = "absolute";
  9130. style.visibility = "hidden";
  9131. style.border = "1px solid #666";
  9132. style.color = "black";
  9133. style.padding = this.padding + "px";
  9134. style.backgroundColor = "#FFFFC6";
  9135. style.borderRadius = "3px";
  9136. style.MozBorderRadius = "3px";
  9137. style.WebkitBorderRadius = "3px";
  9138. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9139. style.whiteSpace = "nowrap";
  9140. this.container.appendChild(this.frame);
  9141. }
  9142. /**
  9143. * @param {number} x Horizontal position of the popup window
  9144. * @param {number} y Vertical position of the popup window
  9145. */
  9146. Popup.prototype.setPosition = function(x, y) {
  9147. this.x = parseInt(x);
  9148. this.y = parseInt(y);
  9149. };
  9150. /**
  9151. * Set the text for the popup window. This can be HTML code
  9152. * @param {string} text
  9153. */
  9154. Popup.prototype.setText = function(text) {
  9155. this.frame.innerHTML = text;
  9156. };
  9157. /**
  9158. * Show the popup window
  9159. * @param {boolean} show Optional. Show or hide the window
  9160. */
  9161. Popup.prototype.show = function (show) {
  9162. if (show === undefined) {
  9163. show = true;
  9164. }
  9165. if (show) {
  9166. var height = this.frame.clientHeight;
  9167. var width = this.frame.clientWidth;
  9168. var maxHeight = this.frame.parentNode.clientHeight;
  9169. var maxWidth = this.frame.parentNode.clientWidth;
  9170. var top = (this.y - height);
  9171. if (top + height + this.padding > maxHeight) {
  9172. top = maxHeight - height - this.padding;
  9173. }
  9174. if (top < this.padding) {
  9175. top = this.padding;
  9176. }
  9177. var left = this.x;
  9178. if (left + width + this.padding > maxWidth) {
  9179. left = maxWidth - width - this.padding;
  9180. }
  9181. if (left < this.padding) {
  9182. left = this.padding;
  9183. }
  9184. this.frame.style.left = left + "px";
  9185. this.frame.style.top = top + "px";
  9186. this.frame.style.visibility = "visible";
  9187. }
  9188. else {
  9189. this.hide();
  9190. }
  9191. };
  9192. /**
  9193. * Hide the popup window
  9194. */
  9195. Popup.prototype.hide = function () {
  9196. this.frame.style.visibility = "hidden";
  9197. };
  9198. /**
  9199. * @class Groups
  9200. * This class can store groups and properties specific for groups.
  9201. */
  9202. Groups = function () {
  9203. this.clear();
  9204. this.defaultIndex = 0;
  9205. };
  9206. /**
  9207. * default constants for group colors
  9208. */
  9209. Groups.DEFAULT = [
  9210. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9211. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9212. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9213. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9214. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9215. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9216. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9217. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9218. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9219. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9220. ];
  9221. /**
  9222. * Clear all groups
  9223. */
  9224. Groups.prototype.clear = function () {
  9225. this.groups = {};
  9226. this.groups.length = function()
  9227. {
  9228. var i = 0;
  9229. for ( var p in this ) {
  9230. if (this.hasOwnProperty(p)) {
  9231. i++;
  9232. }
  9233. }
  9234. return i;
  9235. }
  9236. };
  9237. /**
  9238. * get group properties of a groupname. If groupname is not found, a new group
  9239. * is added.
  9240. * @param {*} groupname Can be a number, string, Date, etc.
  9241. * @return {Object} group The created group, containing all group properties
  9242. */
  9243. Groups.prototype.get = function (groupname) {
  9244. var group = this.groups[groupname];
  9245. if (group == undefined) {
  9246. // create new group
  9247. var index = this.defaultIndex % Groups.DEFAULT.length;
  9248. this.defaultIndex++;
  9249. group = {};
  9250. group.color = Groups.DEFAULT[index];
  9251. this.groups[groupname] = group;
  9252. }
  9253. return group;
  9254. };
  9255. /**
  9256. * Add a custom group style
  9257. * @param {String} groupname
  9258. * @param {Object} style An object containing borderColor,
  9259. * backgroundColor, etc.
  9260. * @return {Object} group The created group object
  9261. */
  9262. Groups.prototype.add = function (groupname, style) {
  9263. this.groups[groupname] = style;
  9264. if (style.color) {
  9265. style.color = Node.parseColor(style.color);
  9266. }
  9267. return style;
  9268. };
  9269. /**
  9270. * @class Images
  9271. * This class loads images and keeps them stored.
  9272. */
  9273. Images = function () {
  9274. this.images = {};
  9275. this.callback = undefined;
  9276. };
  9277. /**
  9278. * Set an onload callback function. This will be called each time an image
  9279. * is loaded
  9280. * @param {function} callback
  9281. */
  9282. Images.prototype.setOnloadCallback = function(callback) {
  9283. this.callback = callback;
  9284. };
  9285. /**
  9286. *
  9287. * @param {string} url Url of the image
  9288. * @return {Image} img The image object
  9289. */
  9290. Images.prototype.load = function(url) {
  9291. var img = this.images[url];
  9292. if (img == undefined) {
  9293. // create the image
  9294. var images = this;
  9295. img = new Image();
  9296. this.images[url] = img;
  9297. img.onload = function() {
  9298. if (images.callback) {
  9299. images.callback(this);
  9300. }
  9301. };
  9302. img.src = url;
  9303. }
  9304. return img;
  9305. };
  9306. /**
  9307. * Creation of the SectorMixin var.
  9308. *
  9309. * This contains all the functions the Graph object can use to employ the sector system.
  9310. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  9311. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  9312. *
  9313. * Alex de Mulder
  9314. * 21-01-2013
  9315. */
  9316. var SectorMixin = {
  9317. /**
  9318. * This function is only called by the setData function of the Graph object.
  9319. * This loads the global references into the active sector. This initializes the sector.
  9320. *
  9321. * @private
  9322. */
  9323. _putDataInSector : function() {
  9324. this.sectors["active"][this._sector()].nodes = this.nodes;
  9325. this.sectors["active"][this._sector()].edges = this.edges;
  9326. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  9327. },
  9328. /**
  9329. * /**
  9330. * This function sets the global references to nodes, edges and nodeIndices back to
  9331. * those of the supplied (active) sector. If a type is defined, do the specific type
  9332. *
  9333. * @param {String} sectorId
  9334. * @param {String} [sectorType] | "active" or "frozen"
  9335. * @private
  9336. */
  9337. _switchToSector : function(sectorId, sectorType) {
  9338. if (sectorType === undefined || sectorType == "active") {
  9339. this._switchToActiveSector(sectorId);
  9340. }
  9341. else {
  9342. this._switchToFrozenSector(sectorId);
  9343. }
  9344. },
  9345. /**
  9346. * This function sets the global references to nodes, edges and nodeIndices back to
  9347. * those of the supplied active sector.
  9348. *
  9349. * @param sectorId
  9350. * @private
  9351. */
  9352. _switchToActiveSector : function(sectorId) {
  9353. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  9354. this.nodes = this.sectors["active"][sectorId]["nodes"];
  9355. this.edges = this.sectors["active"][sectorId]["edges"];
  9356. },
  9357. /**
  9358. * This function sets the global references to nodes, edges and nodeIndices back to
  9359. * those of the supplied frozen sector.
  9360. *
  9361. * @param sectorId
  9362. * @private
  9363. */
  9364. _switchToFrozenSector : function(sectorId) {
  9365. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  9366. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  9367. this.edges = this.sectors["frozen"][sectorId]["edges"];
  9368. },
  9369. /**
  9370. * This function sets the global references to nodes, edges and nodeIndices to
  9371. * those of the navigationUI sector.
  9372. *
  9373. * @private
  9374. */
  9375. _switchToUISector : function() {
  9376. this.nodeIndices = this.sectors["navigationUI"]["nodeIndices"];
  9377. this.nodes = this.sectors["navigationUI"]["nodes"];
  9378. this.edges = this.sectors["navigationUI"]["edges"];
  9379. },
  9380. /**
  9381. * This function sets the global references to nodes, edges and nodeIndices back to
  9382. * those of the currently active sector.
  9383. *
  9384. * @private
  9385. */
  9386. _loadLatestSector : function() {
  9387. this._switchToSector(this._sector());
  9388. },
  9389. /**
  9390. * This function returns the currently active sector Id
  9391. *
  9392. * @returns {String}
  9393. * @private
  9394. */
  9395. _sector : function() {
  9396. return this.activeSector[this.activeSector.length-1];
  9397. },
  9398. /**
  9399. * This function returns the previously active sector Id
  9400. *
  9401. * @returns {String}
  9402. * @private
  9403. */
  9404. _previousSector : function() {
  9405. if (this.activeSector.length > 1) {
  9406. return this.activeSector[this.activeSector.length-2];
  9407. }
  9408. else {
  9409. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  9410. }
  9411. },
  9412. /**
  9413. * We add the active sector at the end of the this.activeSector array
  9414. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  9415. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  9416. *
  9417. * @param newId
  9418. * @private
  9419. */
  9420. _setActiveSector : function(newId) {
  9421. this.activeSector.push(newId);
  9422. },
  9423. /**
  9424. * We remove the currently active sector id from the active sector stack. This happens when
  9425. * we reactivate the previously active sector
  9426. *
  9427. * @private
  9428. */
  9429. _forgetLastSector : function() {
  9430. this.activeSector.pop();
  9431. },
  9432. /**
  9433. * This function creates a new active sector with the supplied newId. This newId
  9434. * is the expanding node id.
  9435. *
  9436. * @param {String} newId | Id of the new active sector
  9437. * @private
  9438. */
  9439. _createNewSector : function(newId) {
  9440. // create the new sector
  9441. this.sectors["active"][newId] = {"nodes":{},
  9442. "edges":{},
  9443. "nodeIndices":[],
  9444. "formationScale": this.scale,
  9445. "drawingNode": undefined};
  9446. // create the new sector render node. This gives visual feedback that you are in a new sector.
  9447. this.sectors["active"][newId]['drawingNode'] = new Node(
  9448. {id:newId,
  9449. color: {
  9450. background: "#eaefef",
  9451. border: "495c5e"
  9452. }
  9453. },{},{},this.constants);
  9454. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  9455. },
  9456. /**
  9457. * This function removes the currently active sector. This is called when we create a new
  9458. * active sector.
  9459. *
  9460. * @param {String} sectorId | Id of the active sector that will be removed
  9461. * @private
  9462. */
  9463. _deleteActiveSector : function(sectorId) {
  9464. delete this.sectors["active"][sectorId];
  9465. },
  9466. /**
  9467. * This function removes the currently active sector. This is called when we reactivate
  9468. * the previously active sector.
  9469. *
  9470. * @param {String} sectorId | Id of the active sector that will be removed
  9471. * @private
  9472. */
  9473. _deleteFrozenSector : function(sectorId) {
  9474. delete this.sectors["frozen"][sectorId];
  9475. },
  9476. /**
  9477. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  9478. * We copy the references, then delete the active entree.
  9479. *
  9480. * @param sectorId
  9481. * @private
  9482. */
  9483. _freezeSector : function(sectorId) {
  9484. // we move the set references from the active to the frozen stack.
  9485. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  9486. // we have moved the sector data into the frozen set, we now remove it from the active set
  9487. this._deleteActiveSector(sectorId);
  9488. },
  9489. /**
  9490. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  9491. * object to the "active" object.
  9492. *
  9493. * @param sectorId
  9494. * @private
  9495. */
  9496. _activateSector : function(sectorId) {
  9497. // we move the set references from the frozen to the active stack.
  9498. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  9499. // we have moved the sector data into the active set, we now remove it from the frozen stack
  9500. this._deleteFrozenSector(sectorId);
  9501. },
  9502. /**
  9503. * This function merges the data from the currently active sector with a frozen sector. This is used
  9504. * in the process of reverting back to the previously active sector.
  9505. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  9506. * upon the creation of a new active sector.
  9507. *
  9508. * @param sectorId
  9509. * @private
  9510. */
  9511. _mergeThisWithFrozen : function(sectorId) {
  9512. // copy all nodes
  9513. for (var nodeId in this.nodes) {
  9514. if (this.nodes.hasOwnProperty(nodeId)) {
  9515. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  9516. }
  9517. }
  9518. // copy all edges (if not fully clustered, else there are no edges)
  9519. for (var edgeId in this.edges) {
  9520. if (this.edges.hasOwnProperty(edgeId)) {
  9521. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  9522. }
  9523. }
  9524. // merge the nodeIndices
  9525. for (var i = 0; i < this.nodeIndices.length; i++) {
  9526. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  9527. }
  9528. },
  9529. /**
  9530. * This clusters the sector to one cluster. It was a single cluster before this process started so
  9531. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  9532. *
  9533. * @private
  9534. */
  9535. _collapseThisToSingleCluster : function() {
  9536. this.clusterToFit(1,false);
  9537. },
  9538. /**
  9539. * We create a new active sector from the node that we want to open.
  9540. *
  9541. * @param node
  9542. * @private
  9543. */
  9544. _addSector : function(node) {
  9545. // this is the currently active sector
  9546. var sector = this._sector();
  9547. // // this should allow me to select nodes from a frozen set.
  9548. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  9549. // console.log("the node is part of the active sector");
  9550. // }
  9551. // else {
  9552. // console.log("I dont know what the fuck happened!!");
  9553. // }
  9554. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  9555. delete this.nodes[node.id];
  9556. var unqiueIdentifier = util.randomUUID();
  9557. // we fully freeze the currently active sector
  9558. this._freezeSector(sector);
  9559. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  9560. this._createNewSector(unqiueIdentifier);
  9561. // we add the active sector to the sectors array to be able to revert these steps later on
  9562. this._setActiveSector(unqiueIdentifier);
  9563. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  9564. this._switchToSector(this._sector());
  9565. // finally we add the node we removed from our previous active sector to the new active sector
  9566. this.nodes[node.id] = node;
  9567. },
  9568. /**
  9569. * We close the sector that is currently open and revert back to the one before.
  9570. * If the active sector is the "default" sector, nothing happens.
  9571. *
  9572. * @private
  9573. */
  9574. _collapseSector : function() {
  9575. // the currently active sector
  9576. var sector = this._sector();
  9577. // we cannot collapse the default sector
  9578. if (sector != "default") {
  9579. if ((this.nodeIndices.length == 1) ||
  9580. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  9581. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  9582. var previousSector = this._previousSector();
  9583. // we collapse the sector back to a single cluster
  9584. this._collapseThisToSingleCluster();
  9585. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  9586. // This previous sector is the one we will reactivate
  9587. this._mergeThisWithFrozen(previousSector);
  9588. // the previously active (frozen) sector now has all the data from the currently active sector.
  9589. // we can now delete the active sector.
  9590. this._deleteActiveSector(sector);
  9591. // we activate the previously active (and currently frozen) sector.
  9592. this._activateSector(previousSector);
  9593. // we load the references from the newly active sector into the global references
  9594. this._switchToSector(previousSector);
  9595. // we forget the previously active sector because we reverted to the one before
  9596. this._forgetLastSector();
  9597. // finally, we update the node index list.
  9598. this._updateNodeIndexList();
  9599. }
  9600. }
  9601. },
  9602. /**
  9603. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  9604. *
  9605. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9606. * | we dont pass the function itself because then the "this" is the window object
  9607. * | instead of the Graph object
  9608. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9609. * @private
  9610. */
  9611. _doInAllActiveSectors : function(runFunction,argument) {
  9612. if (argument === undefined) {
  9613. for (var sector in this.sectors["active"]) {
  9614. if (this.sectors["active"].hasOwnProperty(sector)) {
  9615. // switch the global references to those of this sector
  9616. this._switchToActiveSector(sector);
  9617. this[runFunction]();
  9618. }
  9619. }
  9620. }
  9621. else {
  9622. for (var sector in this.sectors["active"]) {
  9623. if (this.sectors["active"].hasOwnProperty(sector)) {
  9624. // switch the global references to those of this sector
  9625. this._switchToActiveSector(sector);
  9626. var args = Array.prototype.splice.call(arguments, 1);
  9627. if (args.length > 1) {
  9628. this[runFunction](args[0],args[1]);
  9629. }
  9630. else {
  9631. this[runFunction](argument);
  9632. }
  9633. }
  9634. }
  9635. }
  9636. // we revert the global references back to our active sector
  9637. this._loadLatestSector();
  9638. },
  9639. /**
  9640. * This runs a function in all frozen sectors. This is used in the _redraw().
  9641. *
  9642. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9643. * | we don't pass the function itself because then the "this" is the window object
  9644. * | instead of the Graph object
  9645. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9646. * @private
  9647. */
  9648. _doInAllFrozenSectors : function(runFunction,argument) {
  9649. if (argument === undefined) {
  9650. for (var sector in this.sectors["frozen"]) {
  9651. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  9652. // switch the global references to those of this sector
  9653. this._switchToFrozenSector(sector);
  9654. this[runFunction]();
  9655. }
  9656. }
  9657. }
  9658. else {
  9659. for (var sector in this.sectors["frozen"]) {
  9660. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  9661. // switch the global references to those of this sector
  9662. this._switchToFrozenSector(sector);
  9663. var args = Array.prototype.splice.call(arguments, 1);
  9664. if (args.length > 1) {
  9665. this[runFunction](args[0],args[1]);
  9666. }
  9667. else {
  9668. this[runFunction](argument);
  9669. }
  9670. }
  9671. }
  9672. }
  9673. this._loadLatestSector();
  9674. },
  9675. /**
  9676. * This runs a function in the navigationUI sector.
  9677. *
  9678. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9679. * | we don't pass the function itself because then the "this" is the window object
  9680. * | instead of the Graph object
  9681. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9682. * @private
  9683. */
  9684. _doInUISector : function(runFunction,argument) {
  9685. this._switchToUISector();
  9686. if (argument === undefined) {
  9687. this[runFunction]();
  9688. }
  9689. else {
  9690. var args = Array.prototype.splice.call(arguments, 1);
  9691. if (args.length > 1) {
  9692. this[runFunction](args[0],args[1]);
  9693. }
  9694. else {
  9695. this[runFunction](argument);
  9696. }
  9697. }
  9698. this._loadLatestSector();
  9699. },
  9700. /**
  9701. * This runs a function in all sectors. This is used in the _redraw().
  9702. *
  9703. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9704. * | we don't pass the function itself because then the "this" is the window object
  9705. * | instead of the Graph object
  9706. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9707. * @private
  9708. */
  9709. _doInAllSectors : function(runFunction,argument) {
  9710. var args = Array.prototype.splice.call(arguments, 1);
  9711. if (argument === undefined) {
  9712. this._doInAllActiveSectors(runFunction);
  9713. this._doInAllFrozenSectors(runFunction);
  9714. }
  9715. else {
  9716. if (args.length > 1) {
  9717. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  9718. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  9719. }
  9720. else {
  9721. this._doInAllActiveSectors(runFunction,argument);
  9722. this._doInAllFrozenSectors(runFunction,argument);
  9723. }
  9724. }
  9725. },
  9726. /**
  9727. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  9728. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  9729. *
  9730. * @private
  9731. */
  9732. _clearNodeIndexList : function() {
  9733. var sector = this._sector();
  9734. this.sectors["active"][sector]["nodeIndices"] = [];
  9735. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  9736. },
  9737. /**
  9738. * Draw the encompassing sector node
  9739. *
  9740. * @param ctx
  9741. * @param sectorType
  9742. * @private
  9743. */
  9744. _drawSectorNodes : function(ctx,sectorType) {
  9745. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  9746. for (var sector in this.sectors[sectorType]) {
  9747. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  9748. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  9749. this._switchToSector(sector,sectorType);
  9750. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  9751. for (var nodeId in this.nodes) {
  9752. if (this.nodes.hasOwnProperty(nodeId)) {
  9753. node = this.nodes[nodeId];
  9754. node.resize(ctx);
  9755. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  9756. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  9757. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  9758. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  9759. }
  9760. }
  9761. node = this.sectors[sectorType][sector]["drawingNode"];
  9762. node.x = 0.5 * (maxX + minX);
  9763. node.y = 0.5 * (maxY + minY);
  9764. node.width = 2 * (node.x - minX);
  9765. node.height = 2 * (node.y - minY);
  9766. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  9767. node.setScale(this.scale);
  9768. node._drawCircle(ctx);
  9769. }
  9770. }
  9771. }
  9772. },
  9773. _drawAllSectorNodes : function(ctx) {
  9774. this._drawSectorNodes(ctx,"frozen");
  9775. this._drawSectorNodes(ctx,"active");
  9776. this._loadLatestSector();
  9777. }
  9778. };
  9779. /**
  9780. * Creation of the ClusterMixin var.
  9781. *
  9782. * This contains all the functions the Graph object can use to employ clustering
  9783. *
  9784. * Alex de Mulder
  9785. * 21-01-2013
  9786. */
  9787. var ClusterMixin = {
  9788. /**
  9789. * This is only called in the constructor of the graph object
  9790. * */
  9791. startWithClustering : function() {
  9792. // cluster if the data set is big
  9793. this.clusterToFit(this.constants.clustering.initialMaxNumberOfNodes, true);
  9794. // updates the lables after clustering
  9795. this.updateLabels();
  9796. // this is called here because if clusterin is disabled, the start and stabilize are called in
  9797. // the setData function.
  9798. if (this.stabilize) {
  9799. this._doStabilize();
  9800. }
  9801. this.start();
  9802. },
  9803. /**
  9804. * This function clusters until the initialMaxNumberOfNodes has been reached
  9805. *
  9806. * @param {Number} maxNumberOfNodes
  9807. * @param {Boolean} reposition
  9808. */
  9809. clusterToFit : function(maxNumberOfNodes, reposition) {
  9810. var numberOfNodes = this.nodeIndices.length;
  9811. var maxLevels = 50;
  9812. var level = 0;
  9813. // we first cluster the hubs, then we pull in the outliers, repeat
  9814. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  9815. if (level % 3 == 0) {
  9816. this.forceAggregateHubs();
  9817. }
  9818. else {
  9819. this.increaseClusterLevel();
  9820. }
  9821. numberOfNodes = this.nodeIndices.length;
  9822. level += 1;
  9823. }
  9824. // after the clustering we reposition the nodes to reduce the initial chaos
  9825. if (level > 1 && reposition == true) {
  9826. this.repositionNodes();
  9827. }
  9828. },
  9829. /**
  9830. * This function can be called to open up a specific cluster. It is only called by
  9831. * It will unpack the cluster back one level.
  9832. *
  9833. * @param node | Node object: cluster to open.
  9834. */
  9835. openCluster : function(node) {
  9836. var isMovingBeforeClustering = this.moving;
  9837. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  9838. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  9839. this._addSector(node);
  9840. var level = 0;
  9841. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNumberOfNodes) && (level < 10)) {
  9842. this.decreaseClusterLevel();
  9843. level += 1;
  9844. }
  9845. }
  9846. else {
  9847. this._expandClusterNode(node,false,true);
  9848. // update the index list, dynamic edges and labels
  9849. this._updateNodeIndexList();
  9850. this._updateDynamicEdges();
  9851. this.updateLabels();
  9852. }
  9853. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  9854. if (this.moving != isMovingBeforeClustering) {
  9855. this.start();
  9856. }
  9857. },
  9858. /**
  9859. * This calls the updateClustes with default arguments
  9860. */
  9861. updateClustersDefault : function() {
  9862. if (this.constants.clustering.enabled == true) {
  9863. this.updateClusters(0,false,false);
  9864. }
  9865. },
  9866. /**
  9867. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  9868. * be clustered with their connected node. This can be repeated as many times as needed.
  9869. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  9870. */
  9871. increaseClusterLevel : function() {
  9872. this.updateClusters(-1,false,true);
  9873. },
  9874. /**
  9875. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  9876. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  9877. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  9878. */
  9879. decreaseClusterLevel : function() {
  9880. this.updateClusters(1,false,true);
  9881. },
  9882. /**
  9883. * This is the main clustering function. It clusters and declusters on zoom or forced
  9884. * This function clusters on zoom, it can be called with a predefined zoom direction
  9885. * If out, check if we can form clusters, if in, check if we can open clusters.
  9886. * This function is only called from _zoom()
  9887. *
  9888. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  9889. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  9890. * @param {Boolean} force | enabled or disable forcing
  9891. *
  9892. */
  9893. updateClusters : function(zoomDirection,recursive,force) {
  9894. var isMovingBeforeClustering = this.moving;
  9895. var amountOfNodes = this.nodeIndices.length;
  9896. // on zoom out collapse the sector if the scale is at the level the sector was made
  9897. if (this.previousScale > this.scale && zoomDirection == 0) {
  9898. this._collapseSector();
  9899. }
  9900. // check if we zoom in or out
  9901. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  9902. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  9903. // outer nodes determines if it is being clustered
  9904. this._formClusters(force);
  9905. }
  9906. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  9907. if (force == true) {
  9908. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  9909. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  9910. this._openClusters(recursive,force);
  9911. }
  9912. else {
  9913. // if a cluster takes up a set percentage of the active window
  9914. this._openClustersBySize();
  9915. }
  9916. }
  9917. this._updateNodeIndexList();
  9918. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  9919. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  9920. this._aggregateHubs(force);
  9921. this._updateNodeIndexList();
  9922. }
  9923. // we now reduce chains.
  9924. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  9925. this.handleChains();
  9926. this._updateNodeIndexList();
  9927. }
  9928. this.previousScale = this.scale;
  9929. // rest of the update the index list, dynamic edges and labels
  9930. this._updateDynamicEdges();
  9931. this.updateLabels();
  9932. // if a cluster was formed, we increase the clusterSession
  9933. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  9934. this.clusterSession += 1;
  9935. }
  9936. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  9937. if (this.moving != isMovingBeforeClustering) {
  9938. this.start();
  9939. }
  9940. },
  9941. /**
  9942. * This function handles the chains. It is called on every updateClusters().
  9943. */
  9944. handleChains : function() {
  9945. // after clustering we check how many chains there are
  9946. var chainPercentage = this._getChainFraction();
  9947. if (chainPercentage > this.constants.clustering.chainThreshold) {
  9948. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  9949. }
  9950. },
  9951. /**
  9952. * this functions starts clustering by hubs
  9953. * The minimum hub threshold is set globally
  9954. *
  9955. * @private
  9956. */
  9957. _aggregateHubs : function(force) {
  9958. this._getHubSize();
  9959. this._formClustersByHub(force,false);
  9960. },
  9961. /**
  9962. * This function is fired by keypress. It forces hubs to form.
  9963. *
  9964. */
  9965. forceAggregateHubs : function() {
  9966. var isMovingBeforeClustering = this.moving;
  9967. var amountOfNodes = this.nodeIndices.length;
  9968. this._aggregateHubs(true);
  9969. // update the index list, dynamic edges and labels
  9970. this._updateNodeIndexList();
  9971. this._updateDynamicEdges();
  9972. this.updateLabels();
  9973. // if a cluster was formed, we increase the clusterSession
  9974. if (this.nodeIndices.length != amountOfNodes) {
  9975. this.clusterSession += 1;
  9976. }
  9977. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  9978. if (this.moving != isMovingBeforeClustering) {
  9979. this.start();
  9980. }
  9981. },
  9982. /**
  9983. * If a cluster takes up more than a set percentage of the screen, open the cluster
  9984. *
  9985. * @private
  9986. */
  9987. _openClustersBySize : function() {
  9988. for (var nodeId in this.nodes) {
  9989. if (this.nodes.hasOwnProperty(nodeId)) {
  9990. var node = this.nodes[nodeId];
  9991. if (node.inView() == true) {
  9992. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  9993. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  9994. this.openCluster(node);
  9995. }
  9996. }
  9997. }
  9998. }
  9999. },
  10000. /**
  10001. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  10002. * has to be opened based on the current zoom level.
  10003. *
  10004. * @private
  10005. */
  10006. _openClusters : function(recursive,force) {
  10007. for (var i = 0; i < this.nodeIndices.length; i++) {
  10008. var node = this.nodes[this.nodeIndices[i]];
  10009. this._expandClusterNode(node,recursive,force);
  10010. }
  10011. },
  10012. /**
  10013. * This function checks if a node has to be opened. This is done by checking the zoom level.
  10014. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  10015. * This recursive behaviour is optional and can be set by the recursive argument.
  10016. *
  10017. * @param {Node} parentNode | to check for cluster and expand
  10018. * @param {Boolean} recursive | enabled or disable recursive calling
  10019. * @param {Boolean} force | enabled or disable forcing
  10020. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  10021. * @private
  10022. */
  10023. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  10024. // first check if node is a cluster
  10025. if (parentNode.clusterSize > 1) {
  10026. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  10027. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  10028. openAll = true;
  10029. }
  10030. recursive = openAll ? true : recursive;
  10031. // if the last child has been added on a smaller scale than current scale decluster
  10032. if (parentNode.formationScale < this.scale || force == true) {
  10033. // we will check if any of the contained child nodes should be removed from the cluster
  10034. for (var containedNodeId in parentNode.containedNodes) {
  10035. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  10036. var childNode = parentNode.containedNodes[containedNodeId];
  10037. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  10038. // the largest cluster is the one that comes from outside
  10039. if (force == true) {
  10040. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  10041. || openAll) {
  10042. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  10043. }
  10044. }
  10045. else {
  10046. if (this._nodeInActiveArea(parentNode)) {
  10047. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  10048. }
  10049. }
  10050. }
  10051. }
  10052. }
  10053. }
  10054. },
  10055. /**
  10056. * ONLY CALLED FROM _expandClusterNode
  10057. *
  10058. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  10059. * the child node from the parent contained_node object and put it back into the global nodes object.
  10060. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  10061. *
  10062. * @param {Node} parentNode | the parent node
  10063. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  10064. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  10065. * With force and recursive both true, the entire cluster is unpacked
  10066. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  10067. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  10068. * @private
  10069. */
  10070. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  10071. var childNode = parentNode.containedNodes[containedNodeId];
  10072. // if child node has been added on smaller scale than current, kick out
  10073. if (childNode.formationScale < this.scale || force == true) {
  10074. // put the child node back in the global nodes object
  10075. this.nodes[containedNodeId] = childNode;
  10076. // release the contained edges from this childNode back into the global edges
  10077. this._releaseContainedEdges(parentNode,childNode);
  10078. // reconnect rerouted edges to the childNode
  10079. this._connectEdgeBackToChild(parentNode,childNode);
  10080. // validate all edges in dynamicEdges
  10081. this._validateEdges(parentNode);
  10082. // undo the changes from the clustering operation on the parent node
  10083. parentNode.mass -= this.constants.clustering.massTransferCoefficient * childNode.mass;
  10084. parentNode.fontSize -= this.constants.clustering.fontSizeMultiplier * childNode.clusterSize;
  10085. parentNode.clusterSize -= childNode.clusterSize;
  10086. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  10087. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  10088. childNode.x = parentNode.x + this.constants.edges.length * 0.3 * (0.5 - Math.random()) * parentNode.clusterSize;
  10089. childNode.y = parentNode.y + this.constants.edges.length * 0.3 * (0.5 - Math.random()) * parentNode.clusterSize;
  10090. // remove node from the list
  10091. delete parentNode.containedNodes[containedNodeId];
  10092. // check if there are other childs with this clusterSession in the parent.
  10093. var othersPresent = false;
  10094. for (var childNodeId in parentNode.containedNodes) {
  10095. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  10096. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  10097. othersPresent = true;
  10098. break;
  10099. }
  10100. }
  10101. }
  10102. // if there are no others, remove the cluster session from the list
  10103. if (othersPresent == false) {
  10104. parentNode.clusterSessions.pop();
  10105. }
  10106. // remove the clusterSession from the child node
  10107. childNode.clusterSession = 0;
  10108. // restart the simulation to reorganise all nodes
  10109. this.moving = true;
  10110. // recalculate the size of the node on the next time the node is rendered
  10111. parentNode.clearSizeCache();
  10112. }
  10113. // check if a further expansion step is possible if recursivity is enabled
  10114. if (recursive == true) {
  10115. this._expandClusterNode(childNode,recursive,force,openAll);
  10116. }
  10117. },
  10118. /**
  10119. * This function checks if any nodes at the end of their trees have edges below a threshold length
  10120. * This function is called only from updateClusters()
  10121. * forceLevelCollapse ignores the length of the edge and collapses one level
  10122. * This means that a node with only one edge will be clustered with its connected node
  10123. *
  10124. * @private
  10125. * @param {Boolean} force
  10126. */
  10127. _formClusters : function(force) {
  10128. if (force == false) {
  10129. this._formClustersByZoom();
  10130. }
  10131. else {
  10132. this._forceClustersByZoom();
  10133. }
  10134. },
  10135. /**
  10136. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  10137. *
  10138. * @private
  10139. */
  10140. _formClustersByZoom : function() {
  10141. var dx,dy,length,
  10142. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  10143. // check if any edges are shorter than minLength and start the clustering
  10144. // the clustering favours the node with the larger mass
  10145. for (var edgeId in this.edges) {
  10146. if (this.edges.hasOwnProperty(edgeId)) {
  10147. var edge = this.edges[edgeId];
  10148. if (edge.connected) {
  10149. if (edge.toId != edge.fromId) {
  10150. dx = (edge.to.x - edge.from.x);
  10151. dy = (edge.to.y - edge.from.y);
  10152. length = Math.sqrt(dx * dx + dy * dy);
  10153. if (length < minLength) {
  10154. // first check which node is larger
  10155. var parentNode = edge.from;
  10156. var childNode = edge.to;
  10157. if (edge.to.mass > edge.from.mass) {
  10158. parentNode = edge.to;
  10159. childNode = edge.from;
  10160. }
  10161. if (childNode.dynamicEdgesLength == 1) {
  10162. this._addToCluster(parentNode,childNode,false);
  10163. }
  10164. else if (parentNode.dynamicEdgesLength == 1) {
  10165. this._addToCluster(childNode,parentNode,false);
  10166. }
  10167. }
  10168. }
  10169. }
  10170. }
  10171. }
  10172. },
  10173. /**
  10174. * This function forces the graph to cluster all nodes with only one connecting edge to their
  10175. * connected node.
  10176. *
  10177. * @private
  10178. */
  10179. _forceClustersByZoom : function() {
  10180. for (var nodeId in this.nodes) {
  10181. // another node could have absorbed this child.
  10182. if (this.nodes.hasOwnProperty(nodeId)) {
  10183. var childNode = this.nodes[nodeId];
  10184. // the edges can be swallowed by another decrease
  10185. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  10186. var edge = childNode.dynamicEdges[0];
  10187. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  10188. // group to the largest node
  10189. if (childNode.id != parentNode.id) {
  10190. if (parentNode.mass > childNode.mass) {
  10191. this._addToCluster(parentNode,childNode,true);
  10192. }
  10193. else {
  10194. this._addToCluster(childNode,parentNode,true);
  10195. }
  10196. }
  10197. }
  10198. }
  10199. }
  10200. },
  10201. /**
  10202. * This function forms clusters from hubs, it loops over all nodes
  10203. *
  10204. * @param {Boolean} force | Disregard zoom level
  10205. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  10206. * @private
  10207. */
  10208. _formClustersByHub : function(force, onlyEqual) {
  10209. // we loop over all nodes in the list
  10210. for (var nodeId in this.nodes) {
  10211. // we check if it is still available since it can be used by the clustering in this loop
  10212. if (this.nodes.hasOwnProperty(nodeId)) {
  10213. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  10214. }
  10215. }
  10216. },
  10217. /**
  10218. * This function forms a cluster from a specific preselected hub node
  10219. *
  10220. * @param {Node} hubNode | the node we will cluster as a hub
  10221. * @param {Boolean} force | Disregard zoom level
  10222. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  10223. * @param {Number} [absorptionSizeOffset] |
  10224. * @private
  10225. */
  10226. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  10227. if (absorptionSizeOffset === undefined) {
  10228. absorptionSizeOffset = 0;
  10229. }
  10230. // we decide if the node is a hub
  10231. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  10232. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  10233. // initialize variables
  10234. var dx,dy,length;
  10235. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  10236. var allowCluster = false;
  10237. // we create a list of edges because the dynamicEdges change over the course of this loop
  10238. var edgesIdarray = [];
  10239. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  10240. for (var j = 0; j < amountOfInitialEdges; j++) {
  10241. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  10242. }
  10243. // if the hub clustering is not forces, we check if one of the edges connected
  10244. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  10245. if (force == false) {
  10246. allowCluster = false;
  10247. for (j = 0; j < amountOfInitialEdges; j++) {
  10248. var edge = this.edges[edgesIdarray[j]];
  10249. if (edge !== undefined) {
  10250. if (edge.connected) {
  10251. if (edge.toId != edge.fromId) {
  10252. dx = (edge.to.x - edge.from.x);
  10253. dy = (edge.to.y - edge.from.y);
  10254. length = Math.sqrt(dx * dx + dy * dy);
  10255. if (length < minLength) {
  10256. allowCluster = true;
  10257. break;
  10258. }
  10259. }
  10260. }
  10261. }
  10262. }
  10263. }
  10264. // start the clustering if allowed
  10265. if ((!force && allowCluster) || force) {
  10266. // we loop over all edges INITIALLY connected to this hub
  10267. for (j = 0; j < amountOfInitialEdges; j++) {
  10268. edge = this.edges[edgesIdarray[j]];
  10269. // the edge can be clustered by this function in a previous loop
  10270. if (edge !== undefined) {
  10271. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  10272. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  10273. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  10274. (childNode.id != hubNode.id)) {
  10275. this._addToCluster(hubNode,childNode,force);
  10276. }
  10277. }
  10278. }
  10279. }
  10280. }
  10281. },
  10282. /**
  10283. * This function adds the child node to the parent node, creating a cluster if it is not already.
  10284. *
  10285. * @param {Node} parentNode | this is the node that will house the child node
  10286. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  10287. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  10288. * @private
  10289. */
  10290. _addToCluster : function(parentNode, childNode, force) {
  10291. // join child node in the parent node
  10292. parentNode.containedNodes[childNode.id] = childNode;
  10293. // manage all the edges connected to the child and parent nodes
  10294. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  10295. var edge = childNode.dynamicEdges[i];
  10296. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  10297. this._addToContainedEdges(parentNode,childNode,edge);
  10298. }
  10299. else {
  10300. this._connectEdgeToCluster(parentNode,childNode,edge);
  10301. }
  10302. }
  10303. // a contained node has no dynamic edges.
  10304. childNode.dynamicEdges = [];
  10305. // remove circular edges from clusters
  10306. this._containCircularEdgesFromNode(parentNode,childNode);
  10307. // remove the childNode from the global nodes object
  10308. delete this.nodes[childNode.id];
  10309. // update the properties of the child and parent
  10310. var massBefore = parentNode.mass;
  10311. childNode.clusterSession = this.clusterSession;
  10312. parentNode.mass += this.constants.clustering.massTransferCoefficient * childNode.mass;
  10313. parentNode.clusterSize += childNode.clusterSize;
  10314. parentNode.fontSize += this.constants.clustering.fontSizeMultiplier * childNode.clusterSize;
  10315. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  10316. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  10317. parentNode.clusterSessions.push(this.clusterSession);
  10318. }
  10319. // forced clusters only open from screen size and double tap
  10320. if (force == true) {
  10321. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  10322. parentNode.formationScale = 0;
  10323. }
  10324. else {
  10325. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  10326. }
  10327. // recalculate the size of the node on the next time the node is rendered
  10328. parentNode.clearSizeCache();
  10329. // set the pop-out scale for the childnode
  10330. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  10331. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  10332. childNode.clearVelocity();
  10333. // the mass has altered, preservation of energy dictates the velocity to be updated
  10334. parentNode.updateVelocity(massBefore);
  10335. // restart the simulation to reorganise all nodes
  10336. this.moving = true;
  10337. },
  10338. /**
  10339. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  10340. * This is a seperate function to allow for level-wise collapsing of the node tree.
  10341. * It has to be called if a level is collapsed. It is called by _formClusters().
  10342. * @private
  10343. */
  10344. _updateDynamicEdges : function() {
  10345. for (var i = 0; i < this.nodeIndices.length; i++) {
  10346. var node = this.nodes[this.nodeIndices[i]];
  10347. node.dynamicEdgesLength = node.dynamicEdges.length;
  10348. // this corrects for multiple edges pointing at the same other node
  10349. var correction = 0;
  10350. if (node.dynamicEdgesLength > 1) {
  10351. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  10352. var edgeToId = node.dynamicEdges[j].toId;
  10353. var edgeFromId = node.dynamicEdges[j].fromId;
  10354. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  10355. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  10356. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  10357. correction += 1;
  10358. }
  10359. }
  10360. }
  10361. }
  10362. node.dynamicEdgesLength -= correction;
  10363. }
  10364. },
  10365. /**
  10366. * This adds an edge from the childNode to the contained edges of the parent node
  10367. *
  10368. * @param parentNode | Node object
  10369. * @param childNode | Node object
  10370. * @param edge | Edge object
  10371. * @private
  10372. */
  10373. _addToContainedEdges : function(parentNode, childNode, edge) {
  10374. // create an array object if it does not yet exist for this childNode
  10375. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  10376. parentNode.containedEdges[childNode.id] = []
  10377. }
  10378. // add this edge to the list
  10379. parentNode.containedEdges[childNode.id].push(edge);
  10380. // remove the edge from the global edges object
  10381. delete this.edges[edge.id];
  10382. // remove the edge from the parent object
  10383. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  10384. if (parentNode.dynamicEdges[i].id == edge.id) {
  10385. parentNode.dynamicEdges.splice(i,1);
  10386. break;
  10387. }
  10388. }
  10389. },
  10390. /**
  10391. * This function connects an edge that was connected to a child node to the parent node.
  10392. * It keeps track of which nodes it has been connected to with the originalId array.
  10393. *
  10394. * @param {Node} parentNode | Node object
  10395. * @param {Node} childNode | Node object
  10396. * @param {Edge} edge | Edge object
  10397. * @private
  10398. */
  10399. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  10400. // handle circular edges
  10401. if (edge.toId == edge.fromId) {
  10402. this._addToContainedEdges(parentNode, childNode, edge);
  10403. }
  10404. else {
  10405. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  10406. edge.originalToId.push(childNode.id);
  10407. edge.to = parentNode;
  10408. edge.toId = parentNode.id;
  10409. }
  10410. else { // edge connected to other node with the "from" side
  10411. edge.originalFromId.push(childNode.id);
  10412. edge.from = parentNode;
  10413. edge.fromId = parentNode.id;
  10414. }
  10415. this._addToReroutedEdges(parentNode,childNode,edge);
  10416. }
  10417. },
  10418. _containCircularEdgesFromNode : function(parentNode, childNode) {
  10419. // manage all the edges connected to the child and parent nodes
  10420. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  10421. var edge = parentNode.dynamicEdges[i];
  10422. // handle circular edges
  10423. if (edge.toId == edge.fromId) {
  10424. this._addToContainedEdges(parentNode, childNode, edge);
  10425. }
  10426. }
  10427. },
  10428. /**
  10429. * This adds an edge from the childNode to the rerouted edges of the parent node
  10430. *
  10431. * @param parentNode | Node object
  10432. * @param childNode | Node object
  10433. * @param edge | Edge object
  10434. * @private
  10435. */
  10436. _addToReroutedEdges : function(parentNode, childNode, edge) {
  10437. // create an array object if it does not yet exist for this childNode
  10438. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  10439. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  10440. parentNode.reroutedEdges[childNode.id] = [];
  10441. }
  10442. parentNode.reroutedEdges[childNode.id].push(edge);
  10443. // this edge becomes part of the dynamicEdges of the cluster node
  10444. parentNode.dynamicEdges.push(edge);
  10445. },
  10446. /**
  10447. * This function connects an edge that was connected to a cluster node back to the child node.
  10448. *
  10449. * @param parentNode | Node object
  10450. * @param childNode | Node object
  10451. * @private
  10452. */
  10453. _connectEdgeBackToChild : function(parentNode, childNode) {
  10454. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  10455. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  10456. var edge = parentNode.reroutedEdges[childNode.id][i];
  10457. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  10458. edge.originalFromId.pop();
  10459. edge.fromId = childNode.id;
  10460. edge.from = childNode;
  10461. }
  10462. else {
  10463. edge.originalToId.pop();
  10464. edge.toId = childNode.id;
  10465. edge.to = childNode;
  10466. }
  10467. // append this edge to the list of edges connecting to the childnode
  10468. childNode.dynamicEdges.push(edge);
  10469. // remove the edge from the parent object
  10470. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  10471. if (parentNode.dynamicEdges[j].id == edge.id) {
  10472. parentNode.dynamicEdges.splice(j,1);
  10473. break;
  10474. }
  10475. }
  10476. }
  10477. // remove the entry from the rerouted edges
  10478. delete parentNode.reroutedEdges[childNode.id];
  10479. }
  10480. },
  10481. /**
  10482. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  10483. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  10484. * parentNode
  10485. *
  10486. * @param parentNode | Node object
  10487. * @private
  10488. */
  10489. _validateEdges : function(parentNode) {
  10490. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  10491. var edge = parentNode.dynamicEdges[i];
  10492. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  10493. parentNode.dynamicEdges.splice(i,1);
  10494. }
  10495. }
  10496. },
  10497. /**
  10498. * This function released the contained edges back into the global domain and puts them back into the
  10499. * dynamic edges of both parent and child.
  10500. *
  10501. * @param {Node} parentNode |
  10502. * @param {Node} childNode |
  10503. * @private
  10504. */
  10505. _releaseContainedEdges : function(parentNode, childNode) {
  10506. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  10507. var edge = parentNode.containedEdges[childNode.id][i];
  10508. // put the edge back in the global edges object
  10509. this.edges[edge.id] = edge;
  10510. // put the edge back in the dynamic edges of the child and parent
  10511. childNode.dynamicEdges.push(edge);
  10512. parentNode.dynamicEdges.push(edge);
  10513. }
  10514. // remove the entry from the contained edges
  10515. delete parentNode.containedEdges[childNode.id];
  10516. },
  10517. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  10518. /**
  10519. * This updates the node labels for all nodes (for debugging purposes)
  10520. */
  10521. updateLabels : function() {
  10522. var nodeId;
  10523. // update node labels
  10524. for (nodeId in this.nodes) {
  10525. if (this.nodes.hasOwnProperty(nodeId)) {
  10526. var node = this.nodes[nodeId];
  10527. if (node.clusterSize > 1) {
  10528. node.label = "[".concat(String(node.clusterSize),"]");
  10529. }
  10530. }
  10531. }
  10532. // update node labels
  10533. for (nodeId in this.nodes) {
  10534. if (this.nodes.hasOwnProperty(nodeId)) {
  10535. node = this.nodes[nodeId];
  10536. if (node.clusterSize == 1) {
  10537. if (node.originalLabel !== undefined) {
  10538. node.label = node.originalLabel;
  10539. }
  10540. else {
  10541. node.label = String(node.id);
  10542. }
  10543. }
  10544. }
  10545. }
  10546. /* Debug Override */
  10547. // for (nodeId in this.nodes) {
  10548. // if (this.nodes.hasOwnProperty(nodeId)) {
  10549. // node = this.nodes[nodeId];
  10550. // node.label = String(Math.round(node.width)).concat(":",Math.round(node.width*this.scale));
  10551. // }
  10552. // }
  10553. },
  10554. /**
  10555. * This function determines if the cluster we want to decluster is in the active area
  10556. * this means around the zoom center
  10557. *
  10558. * @param {Node} node
  10559. * @returns {boolean}
  10560. * @private
  10561. */
  10562. _nodeInActiveArea : function(node) {
  10563. return (
  10564. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  10565. &&
  10566. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  10567. )
  10568. },
  10569. /**
  10570. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  10571. * It puts large clusters away from the center and randomizes the order.
  10572. *
  10573. */
  10574. repositionNodes : function() {
  10575. for (var i = 0; i < this.nodeIndices.length; i++) {
  10576. var node = this.nodes[this.nodeIndices[i]];
  10577. if (!node.isFixed()) {
  10578. var radius = this.constants.edges.length * (1 + 0.6*node.clusterSize);
  10579. var angle = 2 * Math.PI * Math.random();
  10580. node.x = radius * Math.cos(angle);
  10581. node.y = radius * Math.sin(angle);
  10582. }
  10583. }
  10584. },
  10585. /**
  10586. * We determine how many connections denote an important hub.
  10587. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  10588. *
  10589. * @private
  10590. */
  10591. _getHubSize : function() {
  10592. var average = 0;
  10593. var averageSquared = 0;
  10594. var hubCounter = 0;
  10595. var largestHub = 0;
  10596. for (var i = 0; i < this.nodeIndices.length; i++) {
  10597. var node = this.nodes[this.nodeIndices[i]];
  10598. if (node.dynamicEdgesLength > largestHub) {
  10599. largestHub = node.dynamicEdgesLength;
  10600. }
  10601. average += node.dynamicEdgesLength;
  10602. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  10603. hubCounter += 1;
  10604. }
  10605. average = average / hubCounter;
  10606. averageSquared = averageSquared / hubCounter;
  10607. var variance = averageSquared - Math.pow(average,2);
  10608. var standardDeviation = Math.sqrt(variance);
  10609. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  10610. // always have at least one to cluster
  10611. if (this.hubThreshold > largestHub) {
  10612. this.hubThreshold = largestHub;
  10613. }
  10614. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  10615. // console.log("hubThreshold:",this.hubThreshold);
  10616. },
  10617. /**
  10618. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  10619. * with this amount we can cluster specifically on these chains.
  10620. *
  10621. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  10622. * @private
  10623. */
  10624. _reduceAmountOfChains : function(fraction) {
  10625. this.hubThreshold = 2;
  10626. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  10627. for (var nodeId in this.nodes) {
  10628. if (this.nodes.hasOwnProperty(nodeId)) {
  10629. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  10630. if (reduceAmount > 0) {
  10631. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  10632. reduceAmount -= 1;
  10633. }
  10634. }
  10635. }
  10636. }
  10637. },
  10638. /**
  10639. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  10640. * with this amount we can cluster specifically on these chains.
  10641. *
  10642. * @private
  10643. */
  10644. _getChainFraction : function() {
  10645. var chains = 0;
  10646. var total = 0;
  10647. for (var nodeId in this.nodes) {
  10648. if (this.nodes.hasOwnProperty(nodeId)) {
  10649. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  10650. chains += 1;
  10651. }
  10652. total += 1;
  10653. }
  10654. }
  10655. return chains/total;
  10656. }
  10657. };
  10658. var SelectionMixin = {
  10659. /**
  10660. * This function can be called from the _doInAllSectors function
  10661. *
  10662. * @param object
  10663. * @param overlappingNodes
  10664. * @private
  10665. */
  10666. _getNodesOverlappingWith : function(object, overlappingNodes) {
  10667. var nodes = this.nodes;
  10668. for (var nodeId in nodes) {
  10669. if (nodes.hasOwnProperty(nodeId)) {
  10670. if (nodes[nodeId].isOverlappingWith(object)) {
  10671. overlappingNodes.push(nodeId);
  10672. }
  10673. }
  10674. }
  10675. },
  10676. /**
  10677. * retrieve all nodes overlapping with given object
  10678. * @param {Object} object An object with parameters left, top, right, bottom
  10679. * @return {Number[]} An array with id's of the overlapping nodes
  10680. * @private
  10681. */
  10682. _getAllNodesOverlappingWith : function (object) {
  10683. var overlappingNodes = [];
  10684. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  10685. return overlappingNodes;
  10686. },
  10687. /**
  10688. * retrieve all nodes in the navigationUI overlapping with given object
  10689. * @param {Object} object An object with parameters left, top, right, bottom
  10690. * @return {Number[]} An array with id's of the overlapping nodes
  10691. * @private
  10692. */
  10693. _getAllUINodesOverlappingWith : function (object) {
  10694. var overlappingNodes = [];
  10695. this._doInUISector("_getNodesOverlappingWith",object,overlappingNodes);
  10696. return overlappingNodes;
  10697. },
  10698. /**
  10699. * Return a position object in canvasspace from a single point in screenspace
  10700. *
  10701. * @param pointer
  10702. * @returns {{left: number, top: number, right: number, bottom: number}}
  10703. * @private
  10704. */
  10705. _pointerToPositionObject : function(pointer) {
  10706. var x = this._canvasToX(pointer.x);
  10707. var y = this._canvasToY(pointer.y);
  10708. return {left: x,
  10709. top: y,
  10710. right: x,
  10711. bottom: y};
  10712. },
  10713. /**
  10714. * Return a position object in canvasspace from a single point in screenspace
  10715. *
  10716. * @param pointer
  10717. * @returns {{left: number, top: number, right: number, bottom: number}}
  10718. * @private
  10719. */
  10720. _pointerToScreenPositionObject : function(pointer) {
  10721. var x = pointer.x;
  10722. var y = pointer.y;
  10723. return {left: x,
  10724. top: y,
  10725. right: x,
  10726. bottom: y};
  10727. },
  10728. /**
  10729. * Get the top navigationUI node at the a specific point (like a click)
  10730. *
  10731. * @param {{x: Number, y: Number}} pointer
  10732. * @return {Node | null} node
  10733. * @private
  10734. */
  10735. _getUINodeAt : function (pointer) {
  10736. var screenPositionObject = this._pointerToScreenPositionObject(pointer);
  10737. var overlappingNodes = this._getAllUINodesOverlappingWith(screenPositionObject);
  10738. if (this.UIvisible && overlappingNodes.length > 0) {
  10739. return this.sectors["navigationUI"]["nodes"][overlappingNodes[overlappingNodes.length - 1]];
  10740. }
  10741. else {
  10742. return null;
  10743. }
  10744. },
  10745. /**
  10746. * Get the top node at the a specific point (like a click)
  10747. *
  10748. * @param {{x: Number, y: Number}} pointer
  10749. * @return {Node | null} node
  10750. * @private
  10751. */
  10752. _getNodeAt : function (pointer) {
  10753. // we first check if this is an navigationUI element
  10754. var positionObject = this._pointerToPositionObject(pointer);
  10755. overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  10756. // if there are overlapping nodes, select the last one, this is the
  10757. // one which is drawn on top of the others
  10758. if (overlappingNodes.length > 0) {
  10759. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  10760. }
  10761. else {
  10762. return null;
  10763. }
  10764. },
  10765. /**
  10766. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  10767. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  10768. *
  10769. * @param pointer
  10770. * @returns {null}
  10771. * @private
  10772. */
  10773. _getEdgeAt : function(pointer) {
  10774. return null;
  10775. },
  10776. /**
  10777. * Add object to the selection array. The this.selection id array may not be needed.
  10778. *
  10779. * @param obj
  10780. * @private
  10781. */
  10782. _addToSelection : function(obj) {
  10783. this.selection.push(obj.id);
  10784. this.selectionObj[obj.id] = obj;
  10785. },
  10786. /**
  10787. * Remove a single option from selection.
  10788. *
  10789. * @param obj
  10790. * @private
  10791. */
  10792. _removeFromSelection : function(obj) {
  10793. for (var i = 0; i < this.selection.length; i++) {
  10794. if (obj.id == this.selection[i]) {
  10795. this.selection.splice(i,1);
  10796. break;
  10797. }
  10798. }
  10799. delete this.selectionObj[obj.id];
  10800. },
  10801. /**
  10802. * Unselect all. The selectionObj is useful for this.
  10803. *
  10804. * @private
  10805. */
  10806. _unselectAll : function() {
  10807. this.selection = [];
  10808. for (var objId in this.selectionObj) {
  10809. if (this.selectionObj.hasOwnProperty(objId)) {
  10810. this.selectionObj[objId].unselect();
  10811. }
  10812. }
  10813. this.selectionObj = {};
  10814. this._trigger('select');
  10815. },
  10816. /**
  10817. * Check if anything is selected
  10818. *
  10819. * @returns {boolean}
  10820. * @private
  10821. */
  10822. _selectionIsEmpty : function() {
  10823. if (this.selection.length == 0) {
  10824. return true;
  10825. }
  10826. else {
  10827. return false;
  10828. }
  10829. },
  10830. /**
  10831. * This is called when someone clicks on a node. either select or deselect it.
  10832. * If there is an existing selection and we don't want to append to it, clear the existing selection
  10833. *
  10834. * @param {Node} node
  10835. * @param {Boolean} append
  10836. * @private
  10837. */
  10838. _selectNode : function(node, append) {
  10839. if (this._selectionIsEmpty() == false && append == false) {
  10840. this._unselectAll();
  10841. }
  10842. if (node.selected == false) {
  10843. node.select();
  10844. this._addToSelection(node);
  10845. }
  10846. else {
  10847. node.unselect();
  10848. this._removeFromSelection(node);
  10849. }
  10850. this._trigger('select');
  10851. },
  10852. /**
  10853. * handles the selection part of the touch, only for navigationUI elements;
  10854. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  10855. * This is the most responsive solution
  10856. *
  10857. * @param {Object} pointer
  10858. * @private
  10859. */
  10860. _handleTouch : function(pointer) {
  10861. var node = this._getUINodeAt(pointer);
  10862. if (node != null) {
  10863. if (this[node.triggerFunction] !== undefined) {
  10864. this[node.triggerFunction]();
  10865. }
  10866. }
  10867. },
  10868. /**
  10869. * handles the selection part of the tap;
  10870. *
  10871. * @param {Object} pointer
  10872. * @private
  10873. */
  10874. _handleTap : function(pointer) {
  10875. var node = this._getNodeAt(pointer);
  10876. if (node != null) {
  10877. this._selectNode(node,false);
  10878. }
  10879. else {
  10880. this._unselectAll();
  10881. }
  10882. this._redraw();
  10883. },
  10884. /**
  10885. * handles the selection part of the double tap and opens a cluster if needed
  10886. *
  10887. * @param {Object} pointer
  10888. * @private
  10889. */
  10890. _handleDoubleTap : function(pointer) {
  10891. var node = this._getNodeAt(pointer);
  10892. if (node != null && node !== undefined) {
  10893. // we reset the areaCenter here so the opening of the node will occur
  10894. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  10895. "y" : this._canvasToY(pointer.y)};
  10896. this.openCluster(node);
  10897. }
  10898. },
  10899. /**
  10900. * Handle the onHold selection part
  10901. *
  10902. * @param pointer
  10903. * @private
  10904. */
  10905. _handleOnHold : function(pointer) {
  10906. var node = this._getNodeAt(pointer);
  10907. if (node != null) {
  10908. this._selectNode(node,true);
  10909. }
  10910. this._redraw();
  10911. },
  10912. /**
  10913. * handle the onRelease event. These functions are here for the navigationUI module.
  10914. *
  10915. * @private
  10916. */
  10917. _handleOnRelease : function() {
  10918. this.xIncrement = 0;
  10919. this.yIncrement = 0;
  10920. this.zoomIncrement = 0;
  10921. this._unHighlightAll();
  10922. },
  10923. /**
  10924. * * // TODO: rework this function, it is from the old system
  10925. *
  10926. * retrieve the currently selected nodes
  10927. * @return {Number[] | String[]} selection An array with the ids of the
  10928. * selected nodes.
  10929. */
  10930. getSelection : function() {
  10931. return this.selection.concat([]);
  10932. },
  10933. /**
  10934. * // TODO: rework this function, it is from the old system
  10935. *
  10936. * select zero or more nodes
  10937. * @param {Number[] | String[]} selection An array with the ids of the
  10938. * selected nodes.
  10939. */
  10940. setSelection : function(selection) {
  10941. var i, iMax, id;
  10942. if (!selection || (selection.length == undefined))
  10943. throw 'Selection must be an array with ids';
  10944. // first unselect any selected node
  10945. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  10946. id = this.selection[i];
  10947. this.nodes[id].unselect();
  10948. }
  10949. this.selection = [];
  10950. for (i = 0, iMax = selection.length; i < iMax; i++) {
  10951. id = selection[i];
  10952. var node = this.nodes[id];
  10953. if (!node) {
  10954. throw new RangeError('Node with id "' + id + '" not found');
  10955. }
  10956. node.select();
  10957. this.selection.push(id);
  10958. }
  10959. this.redraw();
  10960. },
  10961. /**
  10962. * TODO: rework this function, it is from the old system
  10963. *
  10964. * Validate the selection: remove ids of nodes which no longer exist
  10965. * @private
  10966. */
  10967. _updateSelection : function () {
  10968. var i = 0;
  10969. while (i < this.selection.length) {
  10970. var nodeId = this.selection[i];
  10971. if (!this.nodes.hasOwnProperty(nodeId)) {
  10972. this.selection.splice(i, 1);
  10973. delete this.selectionObj[nodeId];
  10974. }
  10975. else {
  10976. i++;
  10977. }
  10978. }
  10979. }
  10980. /**
  10981. * Unselect selected nodes. If no selection array is provided, all nodes
  10982. * are unselected
  10983. * @param {Object[]} selection Array with selection objects, each selection
  10984. * object has a parameter row. Optional
  10985. * @param {Boolean} triggerSelect If true (default), the select event
  10986. * is triggered when nodes are unselected
  10987. * @return {Boolean} changed True if the selection is changed
  10988. * @private
  10989. */
  10990. /* _unselectNodes : function(selection, triggerSelect) {
  10991. var changed = false;
  10992. var i, iMax, id;
  10993. if (selection) {
  10994. // remove provided selections
  10995. for (i = 0, iMax = selection.length; i < iMax; i++) {
  10996. id = selection[i];
  10997. if (this.nodes.hasOwnProperty(id)) {
  10998. this.nodes[id].unselect();
  10999. }
  11000. var j = 0;
  11001. while (j < this.selection.length) {
  11002. if (this.selection[j] == id) {
  11003. this.selection.splice(j, 1);
  11004. changed = true;
  11005. }
  11006. else {
  11007. j++;
  11008. }
  11009. }
  11010. }
  11011. }
  11012. else if (this.selection && this.selection.length) {
  11013. // remove all selections
  11014. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  11015. id = this.selection[i];
  11016. if (this.nodes.hasOwnProperty(id)) {
  11017. this.nodes[id].unselect();
  11018. }
  11019. changed = true;
  11020. }
  11021. this.selection = [];
  11022. }
  11023. if (changed && (triggerSelect == true || triggerSelect == undefined)) {
  11024. // fire the select event
  11025. this._trigger('select');
  11026. }
  11027. return changed;
  11028. },
  11029. */
  11030. /**
  11031. * select all nodes on given location x, y
  11032. * @param {Array} selection an array with node ids
  11033. * @param {boolean} append If true, the new selection will be appended to the
  11034. * current selection (except for duplicate entries)
  11035. * @return {Boolean} changed True if the selection is changed
  11036. * @private
  11037. */
  11038. /* _selectNodes : function(selection, append) {
  11039. var changed = false;
  11040. var i, iMax;
  11041. // TODO: the selectNodes method is a little messy, rework this
  11042. // check if the current selection equals the desired selection
  11043. var selectionAlreadyThere = true;
  11044. if (selection.length != this.selection.length) {
  11045. selectionAlreadyThere = false;
  11046. }
  11047. else {
  11048. for (i = 0, iMax = Math.min(selection.length, this.selection.length); i < iMax; i++) {
  11049. if (selection[i] != this.selection[i]) {
  11050. selectionAlreadyThere = false;
  11051. break;
  11052. }
  11053. }
  11054. }
  11055. if (selectionAlreadyThere) {
  11056. return changed;
  11057. }
  11058. if (append == undefined || append == false) {
  11059. // first deselect any selected node
  11060. var triggerSelect = false;
  11061. changed = this._unselectNodes(undefined, triggerSelect);
  11062. }
  11063. for (i = 0, iMax = selection.length; i < iMax; i++) {
  11064. // add each of the new selections, but only when they are not duplicate
  11065. var id = selection[i];
  11066. var isDuplicate = (this.selection.indexOf(id) != -1);
  11067. if (!isDuplicate) {
  11068. this.nodes[id].select();
  11069. this.selection.push(id);
  11070. changed = true;
  11071. }
  11072. }
  11073. if (changed) {
  11074. // fire the select event
  11075. this._trigger('select');
  11076. }
  11077. return changed;
  11078. },
  11079. */
  11080. };
  11081. /**
  11082. * Created by Alex on 1/22/14.
  11083. */
  11084. var UIMixin = {
  11085. /**
  11086. * This function moves the navigationUI if the canvas size has been changed. If the arugments
  11087. * verticaAlignTop and horizontalAlignLeft are false, the correction will be made
  11088. *
  11089. * @private
  11090. */
  11091. _relocateUI : function() {
  11092. if (this.sectors !== undefined) {
  11093. var xOffset = this.UIclientWidth - this.frame.canvas.clientWidth;
  11094. var yOffset = this.UIclientHeight - this.frame.canvas.clientHeight;
  11095. this.UIclientWidth = this.frame.canvas.clientWidth;
  11096. this.UIclientHeight = this.frame.canvas.clientHeight;
  11097. var node = null;
  11098. for (var nodeId in this.sectors["navigationUI"]["nodes"]) {
  11099. if (this.sectors["navigationUI"]["nodes"].hasOwnProperty(nodeId)) {
  11100. node = this.sectors["navigationUI"]["nodes"][nodeId];
  11101. if (!node.horizontalAlignLeft) {
  11102. node.x -= xOffset;
  11103. }
  11104. if (!node.verticalAlignTop) {
  11105. node.y -= yOffset;
  11106. }
  11107. }
  11108. }
  11109. }
  11110. },
  11111. /**
  11112. * Creation of the navigationUI nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  11113. * they have a triggerFunction which is called on click. If the position of the navigationUI is dependent
  11114. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  11115. * This means that the location will be corrected by the _relocateUI function on a size change of the canvas.
  11116. *
  11117. * @private
  11118. */
  11119. _loadUIElements : function() {
  11120. var DIR = this.constants.navigationUI.iconPath;
  11121. this.UIclientWidth = this.frame.canvas.clientWidth;
  11122. this.UIclientHeight = this.frame.canvas.clientHeight;
  11123. if (this.UIclientWidth === undefined) {
  11124. this.UIclientWidth = 0;
  11125. this.UIclientHeight = 0;
  11126. }
  11127. var offset = 15;
  11128. var intermediateOffset = 7;
  11129. var UINodes = [
  11130. {id: 'UI_up', shape: 'image', image: DIR + 'uparrow.png', triggerFunction: "_moveUp",
  11131. verticalAlignTop: false, x: 45 + offset + intermediateOffset, y: this.UIclientHeight - 45 - offset - intermediateOffset},
  11132. {id: 'UI_down', shape: 'image', image: DIR + 'downarrow.png', triggerFunction: "_moveDown",
  11133. verticalAlignTop: false, x: 45 + offset + intermediateOffset, y: this.UIclientHeight - 15 - offset},
  11134. {id: 'UI_left', shape: 'image', image: DIR + 'leftarrow.png', triggerFunction: "_moveLeft",
  11135. verticalAlignTop: false, x: 15 + offset, y: this.UIclientHeight - 15 - offset},
  11136. {id: 'UI_right', shape: 'image', image: DIR + 'rightarrow.png',triggerFunction: "_moveRight",
  11137. verticalAlignTop: false, x: 75 + offset + 2 * intermediateOffset, y: this.UIclientHeight - 15 - offset},
  11138. {id: 'UI_plus', shape: 'image', image: DIR + 'plus.png', triggerFunction: "_zoomIn",
  11139. verticalAlignTop: false, horizontalAlignLeft: false,
  11140. x: this.UIclientWidth - 45 - offset - intermediateOffset, y: this.UIclientHeight - 15 - offset},
  11141. {id: 'UI_min', shape: 'image', image: DIR + 'minus.png', triggerFunction: "_zoomOut",
  11142. verticalAlignTop: false, horizontalAlignLeft: false,
  11143. x: this.UIclientWidth - 15 - offset, y: this.UIclientHeight - 15 - offset},
  11144. {id: 'UI_zoomExtends', shape: 'image', image: DIR + 'zoomExtends.png', triggerFunction: "zoomToFit",
  11145. verticalAlignTop: false, horizontalAlignLeft: false,
  11146. x: this.UIclientWidth - 15 - offset, y: this.UIclientHeight - 45 - offset - intermediateOffset}
  11147. ];
  11148. var nodeObj = null;
  11149. for (var i = 0; i < UINodes.length; i++) {
  11150. nodeObj = this.sectors["navigationUI"]['nodes'];
  11151. nodeObj[UINodes[i]['id']] = new Node(UINodes[i], this.images, this.groups, this.constants);
  11152. }
  11153. },
  11154. /**
  11155. * By setting the clustersize to be larger than 1, we use the clustering drawing method
  11156. * to illustrate the buttons are presed. We call this highlighting.
  11157. *
  11158. * @param {String} elementId
  11159. * @private
  11160. */
  11161. _highlightUIElement : function(elementId) {
  11162. if (this.sectors["navigationUI"]["nodes"].hasOwnProperty(elementId)) {
  11163. this.sectors["navigationUI"]["nodes"][elementId].clusterSize = 2;
  11164. }
  11165. },
  11166. /**
  11167. * Reverting back to a normal button
  11168. *
  11169. * @param {String} elementId
  11170. * @private
  11171. */
  11172. _unHighlightUIElement : function(elementId) {
  11173. if (this.sectors["navigationUI"]["nodes"].hasOwnProperty(elementId)) {
  11174. this.sectors["navigationUI"]["nodes"][elementId].clusterSize = 1;
  11175. }
  11176. },
  11177. /**
  11178. * toggle the visibility of the navigationUI
  11179. *
  11180. * @private
  11181. */
  11182. _toggleUI : function() {
  11183. if (this.UIvisible === undefined) {
  11184. this.UIvisible = false;
  11185. }
  11186. this.UIvisible = !this.UIvisible;
  11187. this._redraw();
  11188. },
  11189. /**
  11190. * un-highlight (for lack of a better term) all navigationUI elements
  11191. * @private
  11192. */
  11193. _unHighlightAll : function() {
  11194. for (var nodeId in this.sectors['navigationUI']['nodes']) {
  11195. this._unHighlightUIElement(nodeId);
  11196. }
  11197. },
  11198. _preventDefault : function(event) {
  11199. if (event !== undefined) {
  11200. if (event.preventDefault) {
  11201. event.preventDefault();
  11202. } else {
  11203. event.returnValue = false;
  11204. }
  11205. }
  11206. },
  11207. /**
  11208. * move the screen up
  11209. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  11210. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  11211. * To avoid this behaviour, we do the translation in the start loop.
  11212. *
  11213. * @private
  11214. */
  11215. _moveUp : function(event) {
  11216. this._highlightUIElement("UI_up");
  11217. this.yIncrement = this.constants.navigationUI.yMovementSpeed;
  11218. this.start(); // if there is no node movement, the calculation wont be done
  11219. this._preventDefault(event);
  11220. },
  11221. /**
  11222. * move the screen down
  11223. * @private
  11224. */
  11225. _moveDown : function(event) {
  11226. this._highlightUIElement("UI_down");
  11227. this.yIncrement = -this.constants.navigationUI.yMovementSpeed;
  11228. this.start(); // if there is no node movement, the calculation wont be done
  11229. this._preventDefault(event);
  11230. },
  11231. /**
  11232. * move the screen left
  11233. * @private
  11234. */
  11235. _moveLeft : function(event) {
  11236. this._highlightUIElement("UI_left");
  11237. this.xIncrement = this.constants.navigationUI.xMovementSpeed;
  11238. this.start(); // if there is no node movement, the calculation wont be done
  11239. this._preventDefault(event);
  11240. },
  11241. /**
  11242. * move the screen right
  11243. * @private
  11244. */
  11245. _moveRight : function(event) {
  11246. this._highlightUIElement("UI_right");
  11247. this.xIncrement = -this.constants.navigationUI.xMovementSpeed;
  11248. this.start(); // if there is no node movement, the calculation wont be done
  11249. this._preventDefault(event);
  11250. },
  11251. /**
  11252. * Zoom in, using the same method as the movement.
  11253. * @private
  11254. */
  11255. _zoomIn : function(event) {
  11256. this._highlightUIElement("UI_plus");
  11257. this.zoomIncrement = this.constants.navigationUI.zoomMovementSpeed;
  11258. this.start(); // if there is no node movement, the calculation wont be done
  11259. this._preventDefault(event);
  11260. },
  11261. /**
  11262. * Zoom out
  11263. * @private
  11264. */
  11265. _zoomOut : function() {
  11266. this._highlightUIElement("UI_min");
  11267. this.zoomIncrement = -this.constants.navigationUI.zoomMovementSpeed;
  11268. this.start(); // if there is no node movement, the calculation wont be done
  11269. this._preventDefault(event);
  11270. },
  11271. /**
  11272. * Stop zooming and unhighlight the zoom controls
  11273. * @private
  11274. */
  11275. _stopZoom : function() {
  11276. this._unHighlightUIElement("UI_plus");
  11277. this._unHighlightUIElement("UI_min");
  11278. this.zoomIncrement = 0;
  11279. },
  11280. /**
  11281. * Stop moving in the Y direction and unHighlight the up and down
  11282. * @private
  11283. */
  11284. _yStopMoving : function() {
  11285. this._unHighlightUIElement("UI_up");
  11286. this._unHighlightUIElement("UI_down");
  11287. this.yIncrement = 0;
  11288. },
  11289. /**
  11290. * Stop moving in the X direction and unHighlight left and right.
  11291. * @private
  11292. */
  11293. _xStopMoving : function() {
  11294. this._unHighlightUIElement("UI_left");
  11295. this._unHighlightUIElement("UI_right");
  11296. this.xIncrement = 0;
  11297. }
  11298. };
  11299. /**
  11300. * @constructor Graph
  11301. * Create a graph visualization, displaying nodes and edges.
  11302. *
  11303. * @param {Element} container The DOM element in which the Graph will
  11304. * be created. Normally a div element.
  11305. * @param {Object} data An object containing parameters
  11306. * {Array} nodes
  11307. * {Array} edges
  11308. * @param {Object} options Options
  11309. */
  11310. function Graph (container, data, options) {
  11311. // create variables and set default values
  11312. this.containerElement = container;
  11313. this.width = '100%';
  11314. this.height = '100%';
  11315. // to give everything a nice fluidity, we seperate the rendering and calculating of the forces
  11316. this.renderRefreshRate = 60; // hz (fps)
  11317. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  11318. this.stabilize = true; // stabilize before displaying the graph
  11319. this.selectable = true;
  11320. this.forceFactor = 50000;
  11321. // set constant values
  11322. this.constants = {
  11323. nodes: {
  11324. radiusMin: 5,
  11325. radiusMax: 20,
  11326. radius: 5,
  11327. distance: 100, // px
  11328. shape: 'ellipse',
  11329. image: undefined,
  11330. widthMin: 16, // px
  11331. widthMax: 64, // px
  11332. fontColor: 'black',
  11333. fontSize: 14, // px
  11334. //fontFace: verdana,
  11335. fontFace: 'arial',
  11336. color: {
  11337. border: '#2B7CE9',
  11338. background: '#97C2FC',
  11339. highlight: {
  11340. border: '#2B7CE9',
  11341. background: '#D2E5FF'
  11342. }
  11343. },
  11344. borderColor: '#2B7CE9',
  11345. backgroundColor: '#97C2FC',
  11346. highlightColor: '#D2E5FF',
  11347. group: undefined
  11348. },
  11349. edges: {
  11350. widthMin: 1,
  11351. widthMax: 15,
  11352. width: 1,
  11353. style: 'line',
  11354. color: '#343434',
  11355. fontColor: '#343434',
  11356. fontSize: 14, // px
  11357. fontFace: 'arial',
  11358. //distance: 100, //px
  11359. length: 100, // px
  11360. dash: {
  11361. length: 10,
  11362. gap: 5,
  11363. altLength: undefined
  11364. }
  11365. },
  11366. clustering: { // Per Node in Cluster = PNiC
  11367. enabled: false, // (Boolean) | global on/off switch for clustering.
  11368. initialMaxNumberOfNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  11369. 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
  11370. 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
  11371. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  11372. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  11373. sectorThreshold: 50, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  11374. 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.
  11375. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  11376. forceAmplification: 0.6, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  11377. distanceAmplification: 0.2, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  11378. edgeGrowth: 11, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  11379. clusterSizeWidthFactor: 10, // (px PNiC) | growth of the width per node in cluster.
  11380. clusterSizeHeightFactor: 10, // (px PNiC) | growth of the height per node in cluster.
  11381. clusterSizeRadiusFactor: 10, // (px PNiC) | growth of the radius per node in cluster.
  11382. activeAreaBoxSize: 100, // (px) | box area around the curser where clusters are popped open.
  11383. massTransferCoefficient: 1 // (multiplier) | parent.mass += massTransferCoefficient * child.mass
  11384. },
  11385. navigationUI: {
  11386. enabled: true,
  11387. initiallyVisible: true,
  11388. xMovementSpeed: 10,
  11389. yMovementSpeed: 10,
  11390. zoomMovementSpeed: 0.02,
  11391. iconPath: this._getIconURL()
  11392. },
  11393. keyboardNavigation: {
  11394. enabled: false
  11395. },
  11396. minVelocity: 1.0, // px/s
  11397. maxIterations: 1000 // maximum number of iteration to stabilize
  11398. };
  11399. // Node variables
  11400. this.groups = new Groups(); // object with groups
  11401. this.images = new Images(); // object with images
  11402. this.images.setOnloadCallback(function () {
  11403. graph._redraw();
  11404. });
  11405. // navigationUI variables
  11406. this.UIvisible = this.constants.navigationUI.initiallyVisible;
  11407. this.xIncrement = 0;
  11408. this.yIncrement = 0;
  11409. this.zoomIncrement = 0;
  11410. // create a frame and canvas
  11411. this._create();
  11412. // apply options
  11413. this.setOptions(options);
  11414. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  11415. this._loadClusterSystem();
  11416. // load the sector system. (mandatory, fully integrated with Graph)
  11417. this._loadSectorSystem();
  11418. // load the selection system. (mandatory, required by Graph)
  11419. this._loadSelectionSystem();
  11420. // load the navigationUI system. (mandatory, few function calls even when navigationUI is disabled (in this.setSize)
  11421. this._loadUISystem();
  11422. // other vars
  11423. var graph = this;
  11424. this.freezeSimulation = false;// freeze the simulation
  11425. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  11426. this.nodes = {}; // object with Node objects
  11427. this.edges = {}; // object with Edge objects
  11428. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  11429. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  11430. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  11431. this.scale = 1; // defining the global scale variable in the constructor
  11432. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  11433. // TODO: create a counter to keep track on the number of nodes having values
  11434. // TODO: create a counter to keep track on the number of nodes currently moving
  11435. // TODO: create a counter to keep track on the number of edges having values
  11436. this.nodesData = null; // A DataSet or DataView
  11437. this.edgesData = null; // A DataSet or DataView
  11438. // create event listeners used to subscribe on the DataSets of the nodes and edges
  11439. var me = this;
  11440. this.nodesListeners = {
  11441. 'add': function (event, params) {
  11442. me._addNodes(params.items);
  11443. me.start();
  11444. },
  11445. 'update': function (event, params) {
  11446. me._updateNodes(params.items);
  11447. me.start();
  11448. },
  11449. 'remove': function (event, params) {
  11450. me._removeNodes(params.items);
  11451. me.start();
  11452. }
  11453. };
  11454. this.edgesListeners = {
  11455. 'add': function (event, params) {
  11456. me._addEdges(params.items);
  11457. me.start();
  11458. },
  11459. 'update': function (event, params) {
  11460. me._updateEdges(params.items);
  11461. me.start();
  11462. },
  11463. 'remove': function (event, params) {
  11464. me._removeEdges(params.items);
  11465. me.start();
  11466. }
  11467. };
  11468. // properties of the data
  11469. this.moving = false; // True if any of the nodes have an undefined position
  11470. this.timer = undefined;
  11471. // load data (the disable start variable will be the same as the enabled clustering)
  11472. this.setData(data,this.constants.clustering.enabled);
  11473. // zoom so all data will fit on the screen
  11474. this.zoomToFit(true);
  11475. // if clustering is disabled, the simulation will have started in the setData function
  11476. if (this.constants.clustering.enabled) {
  11477. this.startWithClustering();
  11478. }
  11479. }
  11480. /**
  11481. * get the URL where the UI icons are located
  11482. *
  11483. * @returns {string}
  11484. * @private
  11485. */
  11486. Graph.prototype._getIconURL = function() {
  11487. var scripts = document.getElementsByTagName( 'script' );
  11488. var scriptNamePosition, srcPosition, imagePath;
  11489. for (var i = 0; i < scripts.length; i++) {
  11490. srcPosition = scripts[i].outerHTML.search("src");
  11491. if (srcPosition != -1) {
  11492. scriptNamePosition = util._getLowestPositiveNumber(scripts[i].outerHTML.search("vis.js"),
  11493. scripts[i].outerHTML.search("vis.min.js"));
  11494. if (scriptNamePosition != -1) {
  11495. imagePath = scripts[i].outerHTML.substring(srcPosition+5,scriptNamePosition).concat("UI_icons/");
  11496. return imagePath;
  11497. }
  11498. }
  11499. }
  11500. };
  11501. /**
  11502. * Find the center position of the graph
  11503. * @private
  11504. */
  11505. Graph.prototype._getRange = function() {
  11506. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11507. for (var i = 0; i < this.nodeIndices.length; i++) {
  11508. node = this.nodes[this.nodeIndices[i]];
  11509. if (minX > (node.x - node.width)) {minX = node.x - node.width;}
  11510. if (maxX < (node.x + node.width)) {maxX = node.x + node.width;}
  11511. if (minY > (node.y - node.height)) {minY = node.y - node.height;}
  11512. if (maxY < (node.y + node.height)) {maxY = node.y + node.height;}
  11513. }
  11514. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  11515. };
  11516. /**
  11517. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  11518. * @returns {{x: number, y: number}}
  11519. * @private
  11520. */
  11521. Graph.prototype._findCenter = function(range) {
  11522. var center = {x: (0.5 * (range.maxX + range.minX)),
  11523. y: (0.5 * (range.maxY + range.minY))};
  11524. return center;
  11525. };
  11526. /**
  11527. * center the graph
  11528. *
  11529. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  11530. */
  11531. Graph.prototype._centerGraph = function(range) {
  11532. var center = this._findCenter(range);
  11533. center.x *= this.scale;
  11534. center.y *= this.scale;
  11535. center.x -= 0.5 * this.frame.canvas.clientWidth;
  11536. center.y -= 0.5 * this.frame.canvas.clientHeight;
  11537. this._setTranslation(-center.x,-center.y); // set at 0,0
  11538. };
  11539. /**
  11540. * This function zooms out to fit all data on screen based on amount of nodes
  11541. *
  11542. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  11543. */
  11544. Graph.prototype.zoomToFit = function(initialZoom) {
  11545. if (initialZoom === undefined) {
  11546. initialZoom = false;
  11547. }
  11548. var numberOfNodes = this.nodeIndices.length;
  11549. var range = this._getRange();
  11550. if (initialZoom == true) {
  11551. if (this.constants.clustering.enabled == true &&
  11552. numberOfNodes >= this.constants.clustering.initialMaxNumberOfNodes) {
  11553. var zoomLevel = 38.8467 / (numberOfNodes - 14.50184) + 0.0116; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  11554. }
  11555. else {
  11556. var zoomLevel = 42.54117319 / (numberOfNodes + 39.31966387) + 0.1944405; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  11557. }
  11558. }
  11559. else {
  11560. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  11561. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  11562. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  11563. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  11564. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  11565. }
  11566. if (zoomLevel > 1.0) {
  11567. zoomLevel = 1.0;
  11568. }
  11569. this.pinch.mousewheelScale = zoomLevel;
  11570. this._setScale(zoomLevel);
  11571. this._centerGraph(range);
  11572. };
  11573. /**
  11574. * Update the this.nodeIndices with the most recent node index list
  11575. * @private
  11576. */
  11577. Graph.prototype._updateNodeIndexList = function() {
  11578. this._clearNodeIndexList();
  11579. for (var idx in this.nodes) {
  11580. if (this.nodes.hasOwnProperty(idx)) {
  11581. this.nodeIndices.push(idx);
  11582. }
  11583. }
  11584. };
  11585. /**
  11586. * Set nodes and edges, and optionally options as well.
  11587. *
  11588. * @param {Object} data Object containing parameters:
  11589. * {Array | DataSet | DataView} [nodes] Array with nodes
  11590. * {Array | DataSet | DataView} [edges] Array with edges
  11591. * {String} [dot] String containing data in DOT format
  11592. * {Options} [options] Object with options
  11593. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  11594. */
  11595. Graph.prototype.setData = function(data, disableStart) {
  11596. if (disableStart === undefined) {
  11597. disableStart = false;
  11598. }
  11599. if (data && data.dot && (data.nodes || data.edges)) {
  11600. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  11601. ' parameter pair "nodes" and "edges", but not both.');
  11602. }
  11603. // set options
  11604. this.setOptions(data && data.options);
  11605. // set all data
  11606. if (data && data.dot) {
  11607. // parse DOT file
  11608. if(data && data.dot) {
  11609. var dotData = vis.util.DOTToGraph(data.dot);
  11610. this.setData(dotData);
  11611. return;
  11612. }
  11613. }
  11614. else {
  11615. this._setNodes(data && data.nodes);
  11616. this._setEdges(data && data.edges);
  11617. }
  11618. this._putDataInSector();
  11619. if (!disableStart) {
  11620. // find a stable position or start animating to a stable position
  11621. if (this.stabilize) {
  11622. this._doStabilize();
  11623. }
  11624. this.start();
  11625. }
  11626. };
  11627. /**
  11628. * Set options
  11629. * @param {Object} options
  11630. */
  11631. Graph.prototype.setOptions = function (options) {
  11632. if (options) {
  11633. // retrieve parameter values
  11634. if (options.width !== undefined) {this.width = options.width;}
  11635. if (options.height !== undefined) {this.height = options.height;}
  11636. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  11637. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  11638. if (options.clustering) {
  11639. for (var prop in options.clustering) {
  11640. if (options.clustering.hasOwnProperty(prop)) {
  11641. this.constants.clustering[prop] = options.clustering[prop];
  11642. }
  11643. }
  11644. }
  11645. if (options.navigationUI) {
  11646. for (var prop in options.navigationUI) {
  11647. if (options.navigationUI.hasOwnProperty(prop)) {
  11648. this.constants.navigationUI[prop] = options.navigationUI[prop];
  11649. }
  11650. }
  11651. }
  11652. // TODO: work out these options and document them
  11653. if (options.edges) {
  11654. for (prop in options.edges) {
  11655. if (options.edges.hasOwnProperty(prop)) {
  11656. this.constants.edges[prop] = options.edges[prop];
  11657. }
  11658. }
  11659. if (options.edges.length !== undefined &&
  11660. options.nodes && options.nodes.distance === undefined) {
  11661. this.constants.edges.length = options.edges.length;
  11662. this.constants.nodes.distance = options.edges.length * 1.25;
  11663. }
  11664. if (!options.edges.fontColor) {
  11665. this.constants.edges.fontColor = options.edges.color;
  11666. }
  11667. // Added to support dashed lines
  11668. // David Jordan
  11669. // 2012-08-08
  11670. if (options.edges.dash) {
  11671. if (options.edges.dash.length !== undefined) {
  11672. this.constants.edges.dash.length = options.edges.dash.length;
  11673. }
  11674. if (options.edges.dash.gap !== undefined) {
  11675. this.constants.edges.dash.gap = options.edges.dash.gap;
  11676. }
  11677. if (options.edges.dash.altLength !== undefined) {
  11678. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  11679. }
  11680. }
  11681. }
  11682. if (options.nodes) {
  11683. for (prop in options.nodes) {
  11684. if (options.nodes.hasOwnProperty(prop)) {
  11685. this.constants.nodes[prop] = options.nodes[prop];
  11686. }
  11687. }
  11688. if (options.nodes.color) {
  11689. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  11690. }
  11691. /*
  11692. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  11693. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  11694. */
  11695. }
  11696. if (options.groups) {
  11697. for (var groupname in options.groups) {
  11698. if (options.groups.hasOwnProperty(groupname)) {
  11699. var group = options.groups[groupname];
  11700. this.groups.add(groupname, group);
  11701. }
  11702. }
  11703. }
  11704. }
  11705. this.setSize(this.width, this.height);
  11706. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  11707. this._setScale(1);
  11708. };
  11709. /**
  11710. * fire an event
  11711. * @param {String} event The name of an event, for example 'select'
  11712. * @param {Object} params Optional object with event parameters
  11713. * @private
  11714. */
  11715. Graph.prototype._trigger = function (event, params) {
  11716. events.trigger(this, event, params);
  11717. };
  11718. /**
  11719. * Create the main frame for the Graph.
  11720. * This function is executed once when a Graph object is created. The frame
  11721. * contains a canvas, and this canvas contains all objects like the axis and
  11722. * nodes.
  11723. * @private
  11724. */
  11725. Graph.prototype._create = function () {
  11726. // remove all elements from the container element.
  11727. while (this.containerElement.hasChildNodes()) {
  11728. this.containerElement.removeChild(this.containerElement.firstChild);
  11729. }
  11730. this.frame = document.createElement('div');
  11731. this.frame.className = 'graph-frame';
  11732. this.frame.style.position = 'relative';
  11733. this.frame.style.overflow = 'hidden';
  11734. // create the graph canvas (HTML canvas element)
  11735. this.frame.canvas = document.createElement( 'canvas' );
  11736. this.frame.canvas.style.position = 'relative';
  11737. this.frame.appendChild(this.frame.canvas);
  11738. if (!this.frame.canvas.getContext) {
  11739. var noCanvas = document.createElement( 'DIV' );
  11740. noCanvas.style.color = 'red';
  11741. noCanvas.style.fontWeight = 'bold' ;
  11742. noCanvas.style.padding = '10px';
  11743. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  11744. this.frame.canvas.appendChild(noCanvas);
  11745. }
  11746. var me = this;
  11747. this.drag = {};
  11748. this.pinch = {};
  11749. this.hammer = Hammer(this.frame.canvas, {
  11750. prevent_default: true
  11751. });
  11752. this.hammer.on('tap', me._onTap.bind(me) );
  11753. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  11754. this.hammer.on('hold', me._onHold.bind(me) );
  11755. this.hammer.on('pinch', me._onPinch.bind(me) );
  11756. this.hammer.on('touch', me._onTouch.bind(me) );
  11757. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  11758. this.hammer.on('drag', me._onDrag.bind(me) );
  11759. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  11760. this.hammer.on('release', me._onRelease.bind(me) );
  11761. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  11762. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  11763. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  11764. // add the frame to the container element
  11765. this.containerElement.appendChild(this.frame);
  11766. };
  11767. /**
  11768. * Binding the keys for keyboard navigation. These functions are defined in the UIMixin
  11769. * @private
  11770. */
  11771. Graph.prototype._createKeyBinds = function() {
  11772. var me = this;
  11773. this.mousetrap = mousetrap;
  11774. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  11775. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  11776. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  11777. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  11778. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  11779. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  11780. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  11781. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  11782. this.mousetrap.bind("=",this._zoomIn.bind(me), "keydown");
  11783. this.mousetrap.bind("=",this._stopZoom.bind(me), "keyup");
  11784. this.mousetrap.bind("-",this._zoomOut.bind(me), "keydown");
  11785. this.mousetrap.bind("-",this._stopZoom.bind(me), "keyup");
  11786. this.mousetrap.bind("[",this._zoomIn.bind(me), "keydown");
  11787. this.mousetrap.bind("[",this._stopZoom.bind(me), "keyup");
  11788. this.mousetrap.bind("]",this._zoomOut.bind(me), "keydown");
  11789. this.mousetrap.bind("]",this._stopZoom.bind(me), "keyup");
  11790. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  11791. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  11792. this.mousetrap.bind("pagedown",this._zoomOut.bind(me), "keydown");
  11793. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  11794. this.mousetrap.bind("u",this._toggleUI.bind(me) , "keydown");
  11795. /*
  11796. this.mousetrap.bind("=",this.decreaseClusterLevel.bind(me));
  11797. this.mousetrap.bind("-",this.increaseClusterLevel.bind(me));
  11798. this.mousetrap.bind("s",this.singleStep.bind(me));
  11799. this.mousetrap.bind("h",this.updateClustersDefault.bind(me));
  11800. this.mousetrap.bind("c",this._collapseSector.bind(me));
  11801. this.mousetrap.bind("f",this.toggleFreeze.bind(me));
  11802. */
  11803. }
  11804. /**
  11805. * Get the pointer location from a touch location
  11806. * @param {{pageX: Number, pageY: Number}} touch
  11807. * @return {{x: Number, y: Number}} pointer
  11808. * @private
  11809. */
  11810. Graph.prototype._getPointer = function (touch) {
  11811. return {
  11812. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  11813. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  11814. };
  11815. };
  11816. /**
  11817. * On start of a touch gesture, store the pointer
  11818. * @param event
  11819. * @private
  11820. */
  11821. Graph.prototype._onTouch = function (event) {
  11822. this.drag.pointer = this._getPointer(event.gesture.touches[0]);
  11823. this.drag.pinched = false;
  11824. this.pinch.scale = this._getScale();
  11825. this._handleTouch(this.drag.pointer);
  11826. };
  11827. /**
  11828. * handle drag start event
  11829. * @private
  11830. */
  11831. Graph.prototype._onDragStart = function () {
  11832. var drag = this.drag;
  11833. var node = this._getNodeAt(drag.pointer);
  11834. // note: drag.pointer is set in _onTouch to get the initial touch location
  11835. drag.selection = [];
  11836. drag.translation = this._getTranslation();
  11837. drag.nodeId = null;
  11838. if (node != null) {
  11839. drag.nodeId = node.id;
  11840. // select the clicked node if not yet selected
  11841. if (!node.isSelected()) {
  11842. this._selectNode(node,false);
  11843. }
  11844. // create an array with the selected nodes and their original location and status
  11845. var me = this;
  11846. this.selection.forEach(function (id) {
  11847. var node = me.nodes[id];
  11848. if (node) {
  11849. var s = {
  11850. id: id,
  11851. node: node,
  11852. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  11853. x: node.x,
  11854. y: node.y,
  11855. xFixed: node.xFixed,
  11856. yFixed: node.yFixed
  11857. };
  11858. node.xFixed = true;
  11859. node.yFixed = true;
  11860. drag.selection.push(s);
  11861. }
  11862. });
  11863. }
  11864. };
  11865. /**
  11866. * handle drag event
  11867. * @private
  11868. */
  11869. Graph.prototype._onDrag = function (event) {
  11870. if (this.drag.pinched) {
  11871. return;
  11872. }
  11873. var pointer = this._getPointer(event.gesture.touches[0]);
  11874. var me = this,
  11875. drag = this.drag,
  11876. selection = drag.selection;
  11877. if (selection && selection.length) {
  11878. // calculate delta's and new location
  11879. var deltaX = pointer.x - drag.pointer.x,
  11880. deltaY = pointer.y - drag.pointer.y;
  11881. // update position of all selected nodes
  11882. selection.forEach(function (s) {
  11883. var node = s.node;
  11884. if (!s.xFixed) {
  11885. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  11886. }
  11887. if (!s.yFixed) {
  11888. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  11889. }
  11890. });
  11891. // start animation if not yet running
  11892. if (!this.moving) {
  11893. this.moving = true;
  11894. this.start();
  11895. }
  11896. }
  11897. else {
  11898. // move the graph
  11899. var diffX = pointer.x - this.drag.pointer.x;
  11900. var diffY = pointer.y - this.drag.pointer.y;
  11901. this._setTranslation(
  11902. this.drag.translation.x + diffX,
  11903. this.drag.translation.y + diffY);
  11904. this._redraw();
  11905. this.moved = true;
  11906. }
  11907. };
  11908. /**
  11909. * handle drag start event
  11910. * @private
  11911. */
  11912. Graph.prototype._onDragEnd = function () {
  11913. var selection = this.drag.selection;
  11914. if (selection) {
  11915. selection.forEach(function (s) {
  11916. // restore original xFixed and yFixed
  11917. s.node.xFixed = s.xFixed;
  11918. s.node.yFixed = s.yFixed;
  11919. });
  11920. }
  11921. };
  11922. /**
  11923. * handle tap/click event: select/unselect a node
  11924. * @private
  11925. */
  11926. Graph.prototype._onTap = function (event) {
  11927. var pointer = this._getPointer(event.gesture.touches[0]);
  11928. this._handleTap(pointer);
  11929. };
  11930. /**
  11931. * handle doubletap event
  11932. * @private
  11933. */
  11934. Graph.prototype._onDoubleTap = function (event) {
  11935. var pointer = this._getPointer(event.gesture.touches[0]);
  11936. this._handleDoubleTap(pointer);
  11937. };
  11938. /**
  11939. * handle long tap event: multi select nodes
  11940. * @private
  11941. */
  11942. Graph.prototype._onHold = function (event) {
  11943. var pointer = this._getPointer(event.gesture.touches[0]);
  11944. this._handleOnHold(pointer);
  11945. };
  11946. /**
  11947. * handle the release of the screen
  11948. *
  11949. * @param event
  11950. * @private
  11951. */
  11952. Graph.prototype._onRelease = function (event) {
  11953. this._handleOnRelease();
  11954. };
  11955. /**
  11956. * Handle pinch event
  11957. * @param event
  11958. * @private
  11959. */
  11960. Graph.prototype._onPinch = function (event) {
  11961. var pointer = this._getPointer(event.gesture.center);
  11962. this.drag.pinched = true;
  11963. if (!('scale' in this.pinch)) {
  11964. this.pinch.scale = 1;
  11965. }
  11966. // TODO: enabled moving while pinching?
  11967. var scale = this.pinch.scale * event.gesture.scale;
  11968. this._zoom(scale, pointer)
  11969. };
  11970. /**
  11971. * Zoom the graph in or out
  11972. * @param {Number} scale a number around 1, and between 0.01 and 10
  11973. * @param {{x: Number, y: Number}} pointer
  11974. * @return {Number} appliedScale scale is limited within the boundaries
  11975. * @private
  11976. */
  11977. Graph.prototype._zoom = function(scale, pointer) {
  11978. var scaleOld = this._getScale();
  11979. if (scale < 0.00001) {
  11980. scale = 0.00001;
  11981. }
  11982. if (scale > 10) {
  11983. scale = 10;
  11984. }
  11985. // + this.frame.canvas.clientHeight / 2
  11986. var translation = this._getTranslation();
  11987. var scaleFrac = scale / scaleOld;
  11988. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  11989. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  11990. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  11991. "y" : this._canvasToY(pointer.y)};
  11992. // this.areaCenter = {"x" : pointer.x,"y" : pointer.y };
  11993. // console.log(translation.x,translation.y,pointer.x,pointer.y,scale);
  11994. this.pinch.mousewheelScale = scale;
  11995. this._setScale(scale);
  11996. this._setTranslation(tx, ty);
  11997. this.updateClustersDefault();
  11998. this._redraw();
  11999. return scale;
  12000. };
  12001. /**
  12002. * Event handler for mouse wheel event, used to zoom the timeline
  12003. * See http://adomas.org/javascript-mouse-wheel/
  12004. * https://github.com/EightMedia/hammer.js/issues/256
  12005. * @param {MouseEvent} event
  12006. * @private
  12007. */
  12008. Graph.prototype._onMouseWheel = function(event) {
  12009. // retrieve delta
  12010. var delta = 0;
  12011. if (event.wheelDelta) { /* IE/Opera. */
  12012. delta = event.wheelDelta/120;
  12013. } else if (event.detail) { /* Mozilla case. */
  12014. // In Mozilla, sign of delta is different than in IE.
  12015. // Also, delta is multiple of 3.
  12016. delta = -event.detail/3;
  12017. }
  12018. // If delta is nonzero, handle it.
  12019. // Basically, delta is now positive if wheel was scrolled up,
  12020. // and negative, if wheel was scrolled down.
  12021. if (delta) {
  12022. if (!('mousewheelScale' in this.pinch)) {
  12023. this.pinch.mousewheelScale = 1;
  12024. }
  12025. // calculate the new scale
  12026. var scale = this.pinch.mousewheelScale;
  12027. var zoom = delta / 10;
  12028. if (delta < 0) {
  12029. zoom = zoom / (1 - zoom);
  12030. }
  12031. scale *= (1 + zoom);
  12032. // calculate the pointer location
  12033. var gesture = util.fakeGesture(this, event);
  12034. var pointer = this._getPointer(gesture.center);
  12035. // apply the new scale
  12036. scale = this._zoom(scale, pointer);
  12037. // store the new, applied scale -- this is now done in _zoom
  12038. // this.pinch.mousewheelScale = scale;
  12039. }
  12040. // Prevent default actions caused by mouse wheel.
  12041. event.preventDefault();
  12042. };
  12043. /**
  12044. * Mouse move handler for checking whether the title moves over a node with a title.
  12045. * @param {Event} event
  12046. * @private
  12047. */
  12048. Graph.prototype._onMouseMoveTitle = function (event) {
  12049. var gesture = util.fakeGesture(this, event);
  12050. var pointer = this._getPointer(gesture.center);
  12051. this.lastPointerPosition = pointer;
  12052. // check if the previously selected node is still selected
  12053. if (this.popupNode) {
  12054. this._checkHidePopup(pointer);
  12055. }
  12056. // start a timeout that will check if the mouse is positioned above
  12057. // an element
  12058. var me = this;
  12059. var checkShow = function() {
  12060. me._checkShowPopup(pointer);
  12061. };
  12062. if (this.popupTimer) {
  12063. clearInterval(this.popupTimer); // stop any running calculationTimer
  12064. }
  12065. if (!this.leftButtonDown) {
  12066. this.popupTimer = setTimeout(checkShow, 300);
  12067. }
  12068. };
  12069. /**
  12070. * Check if there is an element on the given position in the graph
  12071. * (a node or edge). If so, and if this element has a title,
  12072. * show a popup window with its title.
  12073. *
  12074. * @param {{x:Number, y:Number}} pointer
  12075. * @private
  12076. */
  12077. Graph.prototype._checkShowPopup = function (pointer) {
  12078. var obj = {
  12079. left: this._canvasToX(pointer.x),
  12080. top: this._canvasToY(pointer.y),
  12081. right: this._canvasToX(pointer.x),
  12082. bottom: this._canvasToY(pointer.y)
  12083. };
  12084. var id;
  12085. var lastPopupNode = this.popupNode;
  12086. if (this.popupNode == undefined) {
  12087. // search the nodes for overlap, select the top one in case of multiple nodes
  12088. var nodes = this.nodes;
  12089. for (id in nodes) {
  12090. if (nodes.hasOwnProperty(id)) {
  12091. var node = nodes[id];
  12092. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  12093. this.popupNode = node;
  12094. break;
  12095. }
  12096. }
  12097. }
  12098. }
  12099. if (this.popupNode === undefined) {
  12100. // search the edges for overlap
  12101. var edges = this.edges;
  12102. for (id in edges) {
  12103. if (edges.hasOwnProperty(id)) {
  12104. var edge = edges[id];
  12105. if (edge.connected && (edge.getTitle() !== undefined) &&
  12106. edge.isOverlappingWith(obj)) {
  12107. this.popupNode = edge;
  12108. break;
  12109. }
  12110. }
  12111. }
  12112. }
  12113. if (this.popupNode) {
  12114. // show popup message window
  12115. if (this.popupNode != lastPopupNode) {
  12116. var me = this;
  12117. if (!me.popup) {
  12118. me.popup = new Popup(me.frame);
  12119. }
  12120. // adjust a small offset such that the mouse cursor is located in the
  12121. // bottom left location of the popup, and you can easily move over the
  12122. // popup area
  12123. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  12124. me.popup.setText(me.popupNode.getTitle());
  12125. me.popup.show();
  12126. }
  12127. }
  12128. else {
  12129. if (this.popup) {
  12130. this.popup.hide();
  12131. }
  12132. }
  12133. };
  12134. /**
  12135. * Check if the popup must be hided, which is the case when the mouse is no
  12136. * longer hovering on the object
  12137. * @param {{x:Number, y:Number}} pointer
  12138. * @private
  12139. */
  12140. Graph.prototype._checkHidePopup = function (pointer) {
  12141. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  12142. this.popupNode = undefined;
  12143. if (this.popup) {
  12144. this.popup.hide();
  12145. }
  12146. }
  12147. };
  12148. /**
  12149. * Temporary method to test calculating a hub value for the nodes
  12150. * @param {number} level Maximum number edges between two nodes in order
  12151. * to call them connected. Optional, 1 by default
  12152. * @return {Number[]} connectioncount array with the connection count
  12153. * for each node
  12154. * @private
  12155. */
  12156. Graph.prototype._getConnectionCount = function(level) {
  12157. if (level == undefined) {
  12158. level = 1;
  12159. }
  12160. // get the nodes connected to given nodes
  12161. function getConnectedNodes(nodes) {
  12162. var connectedNodes = [];
  12163. for (var j = 0, jMax = nodes.length; j < jMax; j++) {
  12164. var node = nodes[j];
  12165. // find all nodes connected to this node
  12166. var edges = node.edges;
  12167. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  12168. var edge = edges[i];
  12169. var other = null;
  12170. // check if connected
  12171. if (edge.from == node)
  12172. other = edge.to;
  12173. else if (edge.to == node)
  12174. other = edge.from;
  12175. // check if the other node is not already in the list with nodes
  12176. var k, kMax;
  12177. if (other) {
  12178. for (k = 0, kMax = nodes.length; k < kMax; k++) {
  12179. if (nodes[k] == other) {
  12180. other = null;
  12181. break;
  12182. }
  12183. }
  12184. }
  12185. if (other) {
  12186. for (k = 0, kMax = connectedNodes.length; k < kMax; k++) {
  12187. if (connectedNodes[k] == other) {
  12188. other = null;
  12189. break;
  12190. }
  12191. }
  12192. }
  12193. if (other)
  12194. connectedNodes.push(other);
  12195. }
  12196. }
  12197. return connectedNodes;
  12198. }
  12199. var connections = [];
  12200. var nodes = this.nodes;
  12201. for (var id in nodes) {
  12202. if (nodes.hasOwnProperty(id)) {
  12203. var c = [nodes[id]];
  12204. for (var l = 0; l < level; l++) {
  12205. c = c.concat(getConnectedNodes(c));
  12206. }
  12207. connections.push(c);
  12208. }
  12209. }
  12210. var hubs = [];
  12211. for (var i = 0, len = connections.length; i < len; i++) {
  12212. hubs.push(connections[i].length);
  12213. }
  12214. return hubs;
  12215. };
  12216. /**
  12217. * Set a new size for the graph
  12218. * @param {string} width Width in pixels or percentage (for example '800px'
  12219. * or '50%')
  12220. * @param {string} height Height in pixels or percentage (for example '400px'
  12221. * or '30%')
  12222. */
  12223. Graph.prototype.setSize = function(width, height) {
  12224. this.frame.style.width = width;
  12225. this.frame.style.height = height;
  12226. this.frame.canvas.style.width = '100%';
  12227. this.frame.canvas.style.height = '100%';
  12228. this.frame.canvas.width = this.frame.canvas.clientWidth;
  12229. this.frame.canvas.height = this.frame.canvas.clientHeight;
  12230. if (this.constants.navigationUI.enabled == true) {
  12231. this._relocateUI();
  12232. }
  12233. };
  12234. /**
  12235. * Set a data set with nodes for the graph
  12236. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  12237. * @private
  12238. */
  12239. Graph.prototype._setNodes = function(nodes) {
  12240. var oldNodesData = this.nodesData;
  12241. if (nodes instanceof DataSet || nodes instanceof DataView) {
  12242. this.nodesData = nodes;
  12243. }
  12244. else if (nodes instanceof Array) {
  12245. this.nodesData = new DataSet();
  12246. this.nodesData.add(nodes);
  12247. }
  12248. else if (!nodes) {
  12249. this.nodesData = new DataSet();
  12250. }
  12251. else {
  12252. throw new TypeError('Array or DataSet expected');
  12253. }
  12254. if (oldNodesData) {
  12255. // unsubscribe from old dataset
  12256. util.forEach(this.nodesListeners, function (callback, event) {
  12257. oldNodesData.unsubscribe(event, callback);
  12258. });
  12259. }
  12260. // remove drawn nodes
  12261. this.nodes = {};
  12262. if (this.nodesData) {
  12263. // subscribe to new dataset
  12264. var me = this;
  12265. util.forEach(this.nodesListeners, function (callback, event) {
  12266. me.nodesData.subscribe(event, callback);
  12267. });
  12268. // draw all new nodes
  12269. var ids = this.nodesData.getIds();
  12270. this._addNodes(ids);
  12271. }
  12272. this._updateSelection();
  12273. };
  12274. /**
  12275. * Add nodes
  12276. * @param {Number[] | String[]} ids
  12277. * @private
  12278. */
  12279. Graph.prototype._addNodes = function(ids) {
  12280. var id;
  12281. for (var i = 0, len = ids.length; i < len; i++) {
  12282. id = ids[i];
  12283. var data = this.nodesData.get(id);
  12284. var node = new Node(data, this.images, this.groups, this.constants);
  12285. this.nodes[id] = node; // note: this may replace an existing node
  12286. if (!node.isFixed()) {
  12287. // TODO: position new nodes in a smarter way!
  12288. var radius = this.constants.edges.length * 2;
  12289. var count = ids.length;
  12290. var angle = 2 * Math.PI * (i / count);
  12291. node.x = radius * Math.cos(angle);
  12292. node.y = radius * Math.sin(angle);
  12293. // note: no not use node.isMoving() here, as that gives the current
  12294. // velocity of the node, which is zero after creation of the node.
  12295. this.moving = true;
  12296. }
  12297. }
  12298. this._updateNodeIndexList();
  12299. this._reconnectEdges();
  12300. this._updateValueRange(this.nodes);
  12301. };
  12302. /**
  12303. * Update existing nodes, or create them when not yet existing
  12304. * @param {Number[] | String[]} ids
  12305. * @private
  12306. */
  12307. Graph.prototype._updateNodes = function(ids) {
  12308. var nodes = this.nodes,
  12309. nodesData = this.nodesData;
  12310. for (var i = 0, len = ids.length; i < len; i++) {
  12311. var id = ids[i];
  12312. var node = nodes[id];
  12313. var data = nodesData.get(id);
  12314. if (node) {
  12315. // update node
  12316. node.setProperties(data, this.constants);
  12317. }
  12318. else {
  12319. // create node
  12320. node = new Node(properties, this.images, this.groups, this.constants);
  12321. nodes[id] = node;
  12322. if (!node.isFixed()) {
  12323. this.moving = true;
  12324. }
  12325. }
  12326. }
  12327. this._updateNodeIndexList();
  12328. this._reconnectEdges();
  12329. this._updateValueRange(nodes);
  12330. };
  12331. /**
  12332. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  12333. * @param {Number[] | String[]} ids
  12334. * @private
  12335. */
  12336. Graph.prototype._removeNodes = function(ids) {
  12337. var nodes = this.nodes;
  12338. for (var i = 0, len = ids.length; i < len; i++) {
  12339. var id = ids[i];
  12340. delete nodes[id];
  12341. }
  12342. this._updateNodeIndexList();
  12343. this._reconnectEdges();
  12344. this._updateSelection();
  12345. this._updateValueRange(nodes);
  12346. };
  12347. /**
  12348. * Load edges by reading the data table
  12349. * @param {Array | DataSet | DataView} edges The data containing the edges.
  12350. * @private
  12351. * @private
  12352. */
  12353. Graph.prototype._setEdges = function(edges) {
  12354. var oldEdgesData = this.edgesData;
  12355. if (edges instanceof DataSet || edges instanceof DataView) {
  12356. this.edgesData = edges;
  12357. }
  12358. else if (edges instanceof Array) {
  12359. this.edgesData = new DataSet();
  12360. this.edgesData.add(edges);
  12361. }
  12362. else if (!edges) {
  12363. this.edgesData = new DataSet();
  12364. }
  12365. else {
  12366. throw new TypeError('Array or DataSet expected');
  12367. }
  12368. if (oldEdgesData) {
  12369. // unsubscribe from old dataset
  12370. util.forEach(this.edgesListeners, function (callback, event) {
  12371. oldEdgesData.unsubscribe(event, callback);
  12372. });
  12373. }
  12374. // remove drawn edges
  12375. this.edges = {};
  12376. if (this.edgesData) {
  12377. // subscribe to new dataset
  12378. var me = this;
  12379. util.forEach(this.edgesListeners, function (callback, event) {
  12380. me.edgesData.subscribe(event, callback);
  12381. });
  12382. // draw all new nodes
  12383. var ids = this.edgesData.getIds();
  12384. this._addEdges(ids);
  12385. }
  12386. this._reconnectEdges();
  12387. };
  12388. /**
  12389. * Add edges
  12390. * @param {Number[] | String[]} ids
  12391. * @private
  12392. */
  12393. Graph.prototype._addEdges = function (ids) {
  12394. var edges = this.edges,
  12395. edgesData = this.edgesData;
  12396. for (var i = 0, len = ids.length; i < len; i++) {
  12397. var id = ids[i];
  12398. var oldEdge = edges[id];
  12399. if (oldEdge) {
  12400. oldEdge.disconnect();
  12401. }
  12402. var data = edgesData.get(id, {"showInternalIds" : true});
  12403. edges[id] = new Edge(data, this, this.constants);
  12404. }
  12405. this.moving = true;
  12406. this._updateValueRange(edges);
  12407. };
  12408. /**
  12409. * Update existing edges, or create them when not yet existing
  12410. * @param {Number[] | String[]} ids
  12411. * @private
  12412. */
  12413. Graph.prototype._updateEdges = function (ids) {
  12414. var edges = this.edges,
  12415. edgesData = this.edgesData;
  12416. for (var i = 0, len = ids.length; i < len; i++) {
  12417. var id = ids[i];
  12418. var data = edgesData.get(id);
  12419. var edge = edges[id];
  12420. if (edge) {
  12421. // update edge
  12422. edge.disconnect();
  12423. edge.setProperties(data, this.constants);
  12424. edge.connect();
  12425. }
  12426. else {
  12427. // create edge
  12428. edge = new Edge(data, this, this.constants);
  12429. this.edges[id] = edge;
  12430. }
  12431. }
  12432. this.moving = true;
  12433. this._updateValueRange(edges);
  12434. };
  12435. /**
  12436. * Remove existing edges. Non existing ids will be ignored
  12437. * @param {Number[] | String[]} ids
  12438. * @private
  12439. */
  12440. Graph.prototype._removeEdges = function (ids) {
  12441. var edges = this.edges;
  12442. for (var i = 0, len = ids.length; i < len; i++) {
  12443. var id = ids[i];
  12444. var edge = edges[id];
  12445. if (edge) {
  12446. edge.disconnect();
  12447. delete edges[id];
  12448. }
  12449. }
  12450. this.moving = true;
  12451. this._updateValueRange(edges);
  12452. };
  12453. /**
  12454. * Reconnect all edges
  12455. * @private
  12456. */
  12457. Graph.prototype._reconnectEdges = function() {
  12458. var id,
  12459. nodes = this.nodes,
  12460. edges = this.edges;
  12461. for (id in nodes) {
  12462. if (nodes.hasOwnProperty(id)) {
  12463. nodes[id].edges = [];
  12464. }
  12465. }
  12466. for (id in edges) {
  12467. if (edges.hasOwnProperty(id)) {
  12468. var edge = edges[id];
  12469. edge.from = null;
  12470. edge.to = null;
  12471. edge.connect();
  12472. }
  12473. }
  12474. };
  12475. /**
  12476. * Update the values of all object in the given array according to the current
  12477. * value range of the objects in the array.
  12478. * @param {Object} obj An object containing a set of Edges or Nodes
  12479. * The objects must have a method getValue() and
  12480. * setValueRange(min, max).
  12481. * @private
  12482. */
  12483. Graph.prototype._updateValueRange = function(obj) {
  12484. var id;
  12485. // determine the range of the objects
  12486. var valueMin = undefined;
  12487. var valueMax = undefined;
  12488. for (id in obj) {
  12489. if (obj.hasOwnProperty(id)) {
  12490. var value = obj[id].getValue();
  12491. if (value !== undefined) {
  12492. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  12493. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  12494. }
  12495. }
  12496. }
  12497. // adjust the range of all objects
  12498. if (valueMin !== undefined && valueMax !== undefined) {
  12499. for (id in obj) {
  12500. if (obj.hasOwnProperty(id)) {
  12501. obj[id].setValueRange(valueMin, valueMax);
  12502. }
  12503. }
  12504. }
  12505. };
  12506. /**
  12507. * Redraw the graph with the current data
  12508. * chart will be resized too.
  12509. */
  12510. Graph.prototype.redraw = function() {
  12511. this.setSize(this.width, this.height);
  12512. this._redraw();
  12513. };
  12514. /**
  12515. * Redraw the graph with the current data
  12516. * @private
  12517. */
  12518. Graph.prototype._redraw = function() {
  12519. var ctx = this.frame.canvas.getContext('2d');
  12520. // clear the canvas
  12521. var w = this.frame.canvas.width;
  12522. var h = this.frame.canvas.height;
  12523. ctx.clearRect(0, 0, w, h);
  12524. // set scaling and translation
  12525. ctx.save();
  12526. ctx.translate(this.translation.x, this.translation.y);
  12527. ctx.scale(this.scale, this.scale);
  12528. this.canvasTopLeft = {"x": this._canvasToX(0),
  12529. "y": this._canvasToY(0)};
  12530. this.canvasBottomRight = {"x": this._canvasToX(this.frame.canvas.clientWidth),
  12531. "y": this._canvasToY(this.frame.canvas.clientHeight)};
  12532. this._doInAllSectors("_drawAllSectorNodes",ctx);
  12533. this._doInAllSectors("_drawEdges",ctx);
  12534. this._doInAllSectors("_drawNodes",ctx);
  12535. // restore original scaling and translation
  12536. ctx.restore();
  12537. if (this.UIvisible == true) {
  12538. this._doInUISector("_drawNodes",ctx,true);
  12539. }
  12540. };
  12541. /**
  12542. * Set the translation of the graph
  12543. * @param {Number} offsetX Horizontal offset
  12544. * @param {Number} offsetY Vertical offset
  12545. * @private
  12546. */
  12547. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  12548. if (this.translation === undefined) {
  12549. this.translation = {
  12550. x: 0,
  12551. y: 0
  12552. };
  12553. }
  12554. if (offsetX !== undefined) {
  12555. this.translation.x = offsetX;
  12556. }
  12557. if (offsetY !== undefined) {
  12558. this.translation.y = offsetY;
  12559. }
  12560. };
  12561. /**
  12562. * Get the translation of the graph
  12563. * @return {Object} translation An object with parameters x and y, both a number
  12564. * @private
  12565. */
  12566. Graph.prototype._getTranslation = function() {
  12567. return {
  12568. x: this.translation.x,
  12569. y: this.translation.y
  12570. };
  12571. };
  12572. /**
  12573. * Scale the graph
  12574. * @param {Number} scale Scaling factor 1.0 is unscaled
  12575. * @private
  12576. */
  12577. Graph.prototype._setScale = function(scale) {
  12578. this.scale = scale;
  12579. };
  12580. /**
  12581. * Get the current scale of the graph
  12582. * @return {Number} scale Scaling factor 1.0 is unscaled
  12583. * @private
  12584. */
  12585. Graph.prototype._getScale = function() {
  12586. return this.scale;
  12587. };
  12588. /**
  12589. * Convert a horizontal point on the HTML canvas to the x-value of the model
  12590. * @param {number} x
  12591. * @returns {number}
  12592. * @private
  12593. */
  12594. Graph.prototype._canvasToX = function(x) {
  12595. return (x - this.translation.x) / this.scale;
  12596. };
  12597. /**
  12598. * Convert an x-value in the model to a horizontal point on the HTML canvas
  12599. * @param {number} x
  12600. * @returns {number}
  12601. * @private
  12602. */
  12603. Graph.prototype._xToCanvas = function(x) {
  12604. return x * this.scale + this.translation.x;
  12605. };
  12606. /**
  12607. * Convert a vertical point on the HTML canvas to the y-value of the model
  12608. * @param {number} y
  12609. * @returns {number}
  12610. * @private
  12611. */
  12612. Graph.prototype._canvasToY = function(y) {
  12613. return (y - this.translation.y) / this.scale;
  12614. };
  12615. /**
  12616. * Convert an y-value in the model to a vertical point on the HTML canvas
  12617. * @param {number} y
  12618. * @returns {number}
  12619. * @private
  12620. */
  12621. Graph.prototype._yToCanvas = function(y) {
  12622. return y * this.scale + this.translation.y ;
  12623. };
  12624. /**
  12625. * Redraw all nodes
  12626. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  12627. * @param {CanvasRenderingContext2D} ctx
  12628. * @param {Boolean} [alwaysShow]
  12629. * @private
  12630. */
  12631. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  12632. if (alwaysShow === undefined) {
  12633. alwaysShow = false;
  12634. }
  12635. // first draw the unselected nodes
  12636. var nodes = this.nodes;
  12637. var selected = [];
  12638. for (var id in nodes) {
  12639. if (nodes.hasOwnProperty(id)) {
  12640. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  12641. if (nodes[id].isSelected()) {
  12642. selected.push(id);
  12643. }
  12644. else {
  12645. if (nodes[id].inArea() || alwaysShow) {
  12646. nodes[id].draw(ctx);
  12647. }
  12648. }
  12649. }
  12650. }
  12651. // draw the selected nodes on top
  12652. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  12653. if (nodes[selected[s]].inArea() || alwaysShow) {
  12654. nodes[selected[s]].draw(ctx);
  12655. }
  12656. }
  12657. };
  12658. /**
  12659. * Redraw all edges
  12660. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  12661. * @param {CanvasRenderingContext2D} ctx
  12662. * @private
  12663. */
  12664. Graph.prototype._drawEdges = function(ctx) {
  12665. var edges = this.edges;
  12666. for (var id in edges) {
  12667. if (edges.hasOwnProperty(id)) {
  12668. var edge = edges[id];
  12669. edge.setScale(this.scale);
  12670. if (edge.connected) {
  12671. edges[id].draw(ctx);
  12672. }
  12673. }
  12674. }
  12675. };
  12676. /**
  12677. * Find a stable position for all nodes
  12678. * @private
  12679. */
  12680. Graph.prototype._doStabilize = function() {
  12681. //var start = new Date();
  12682. // find stable position
  12683. var count = 0;
  12684. var vmin = this.constants.minVelocity;
  12685. var stable = false;
  12686. while (!stable && count < this.constants.maxIterations) {
  12687. this._initializeForceCalculation();
  12688. this._discreteStepNodes();
  12689. stable = !this._isMoving(vmin);
  12690. count++;
  12691. }
  12692. this.zoomToFit();
  12693. // var end = new Date();
  12694. // console.log('Stabilized in ' + (end-start) + ' ms, ' + count + ' iterations' ); // TODO: cleanup
  12695. };
  12696. /**
  12697. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  12698. * if there is more than one node. If it is just one node, we dont calculate anything.
  12699. *
  12700. * @private
  12701. */
  12702. Graph.prototype._initializeForceCalculation = function() {
  12703. // stop calculation if there is only one node
  12704. if (this.nodeIndices.length == 1) {
  12705. this.nodes[this.nodeIndices[0]]._setForce(0,0);
  12706. }
  12707. else {
  12708. // if there are too many nodes on screen, we cluster without repositioning
  12709. if (this.nodeIndices.length > this.constants.clustering.absoluteMaxNumberOfNodes && this.constants.clustering.enabled == true) {
  12710. this.clusterToFit(this.constants.clustering.reduceToMaxNumberOfNodes, false);
  12711. }
  12712. // we now start the force calculation
  12713. this._calculateForces();
  12714. }
  12715. };
  12716. /**
  12717. * Calculate the external forces acting on the nodes
  12718. * Forces are caused by: edges, repulsing forces between nodes, gravity
  12719. * @private
  12720. */
  12721. Graph.prototype._calculateForces = function() {
  12722. var screenCenterPos = {"x":(0.5*(this.canvasTopLeft.x + this.canvasBottomRight.x)),
  12723. "y":(0.5*(this.canvasTopLeft.y + this.canvasBottomRight.y))}
  12724. // create a local edge to the nodes and edges, that is faster
  12725. var dx, dy, angle, distance, fx, fy,
  12726. repulsingForce, springForce, length, edgeLength,
  12727. node, node1, node2, edge, edgeId, i, j, nodeId, xCenter, yCenter;
  12728. var clusterSize;
  12729. var nodes = this.nodes;
  12730. var edges = this.edges;
  12731. // Gravity is required to keep separated groups from floating off
  12732. // the forces are reset to zero in this loop by using _setForce instead
  12733. // of _addForce
  12734. var gravity = 0.10 * this.forceFactor;
  12735. for (i = 0; i < this.nodeIndices.length; i++) {
  12736. node = nodes[this.nodeIndices[i]];
  12737. // gravity does not apply when we are in a pocket sector
  12738. if (this._sector() == "default") {
  12739. dx = -node.x + screenCenterPos.x;
  12740. dy = -node.y + screenCenterPos.y;
  12741. angle = Math.atan2(dy, dx);
  12742. fx = Math.cos(angle) * gravity;
  12743. fy = Math.sin(angle) * gravity;
  12744. }
  12745. else {
  12746. fx = 0;
  12747. fy = 0;
  12748. }
  12749. node._setForce(fx, fy);
  12750. node.updateDamping(this.nodeIndices.length);
  12751. }
  12752. // repulsing forces between nodes
  12753. var minimumDistance = this.constants.nodes.distance,
  12754. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  12755. // we loop from i over all but the last entree in the array
  12756. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  12757. for (i = 0; i < this.nodeIndices.length-1; i++) {
  12758. node1 = nodes[this.nodeIndices[i]];
  12759. for (j = i+1; j < this.nodeIndices.length; j++) {
  12760. node2 = nodes[this.nodeIndices[j]];
  12761. clusterSize = (node1.clusterSize + node2.clusterSize - 2);
  12762. dx = node2.x - node1.x;
  12763. dy = node2.y - node1.y;
  12764. distance = Math.sqrt(dx * dx + dy * dy);
  12765. // clusters have a larger region of influence
  12766. minimumDistance = (clusterSize == 0) ? this.constants.nodes.distance : (this.constants.nodes.distance * (1 + clusterSize * this.constants.clustering.distanceAmplification));
  12767. if (distance < 2*minimumDistance) { // at 2.0 * the minimum distance, the force is 0.000045
  12768. angle = Math.atan2(dy, dx);
  12769. if (distance < 0.5*minimumDistance) { // at 0.5 * the minimum distance, the force is 0.993307
  12770. repulsingForce = 1.0;
  12771. }
  12772. else {
  12773. // TODO: correct factor for repulsing force
  12774. //repulsingForce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12775. //repulsingForce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12776. repulsingForce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)); // TODO: customize the repulsing force
  12777. }
  12778. // amplify the repulsion for clusters.
  12779. repulsingForce *= (clusterSize == 0) ? 1 : 1 + clusterSize * this.constants.clustering.forceAmplification;
  12780. repulsingForce *= this.forceFactor;
  12781. fx = Math.cos(angle) * repulsingForce;
  12782. fy = Math.sin(angle) * repulsingForce ;
  12783. node1._addForce(-fx, -fy);
  12784. node2._addForce(fx, fy);
  12785. }
  12786. }
  12787. }
  12788. /*
  12789. // repulsion of the edges on the nodes and
  12790. for (var nodeId in nodes) {
  12791. if (nodes.hasOwnProperty(nodeId)) {
  12792. node = nodes[nodeId];
  12793. for(var edgeId in edges) {
  12794. if (edges.hasOwnProperty(edgeId)) {
  12795. edge = edges[edgeId];
  12796. // get the center of the edge
  12797. xCenter = edge.from.x+(edge.to.x - edge.from.x)/2;
  12798. yCenter = edge.from.y+(edge.to.y - edge.from.y)/2;
  12799. // calculate normally distributed force
  12800. dx = node.x - xCenter;
  12801. dy = node.y - yCenter;
  12802. distance = Math.sqrt(dx * dx + dy * dy);
  12803. if (distance < 2*minimumDistance) { // at 2.0 * the minimum distance, the force is 0.000045
  12804. angle = Math.atan2(dy, dx);
  12805. if (distance < 0.5*minimumDistance) { // at 0.5 * the minimum distance, the force is 0.993307
  12806. repulsingForce = 1.0;
  12807. }
  12808. else {
  12809. // TODO: correct factor for repulsing force
  12810. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12811. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  12812. repulsingForce = 1 / (1 + Math.exp((distance / (minimumDistance / 2) - 1) * steepness)); // TODO: customize the repulsing force
  12813. }
  12814. fx = Math.cos(angle) * repulsingForce;
  12815. fy = Math.sin(angle) * repulsingForce;
  12816. node._addForce(fx, fy);
  12817. edge.from._addForce(-fx/2,-fy/2);
  12818. edge.to._addForce(-fx/2,-fy/2);
  12819. }
  12820. }
  12821. }
  12822. }
  12823. }
  12824. */
  12825. // forces caused by the edges, modelled as springs
  12826. for (edgeId in edges) {
  12827. if (edges.hasOwnProperty(edgeId)) {
  12828. edge = edges[edgeId];
  12829. if (edge.connected) {
  12830. // only calculate forces if nodes are in the same sector
  12831. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  12832. clusterSize = (edge.to.clusterSize + edge.from.clusterSize - 2);
  12833. dx = (edge.to.x - edge.from.x);
  12834. dy = (edge.to.y - edge.from.y);
  12835. //edgeLength = (edge.from.width + edge.from.height + edge.to.width + edge.to.height)/2 || edge.length; // TODO: dmin
  12836. //edgeLength = (edge.from.width + edge.to.width)/2 || edge.length; // TODO: dmin
  12837. //edgeLength = 20 + ((edge.from.width + edge.to.width) || 0) / 2;
  12838. edgeLength = edge.length;
  12839. // this implies that the edges between big clusters are longer
  12840. edgeLength += clusterSize * this.constants.clustering.edgeGrowth;
  12841. length = Math.sqrt(dx * dx + dy * dy);
  12842. angle = Math.atan2(dy, dx);
  12843. springForce = edge.stiffness * (edgeLength - length) * this.forceFactor;
  12844. fx = Math.cos(angle) * springForce;
  12845. fy = Math.sin(angle) * springForce;
  12846. edge.from._addForce(-fx, -fy);
  12847. edge.to._addForce(fx, fy);
  12848. }
  12849. }
  12850. }
  12851. }
  12852. /*
  12853. // TODO: re-implement repulsion of edges
  12854. // repulsing forces between edges
  12855. var minimumDistance = this.constants.edges.distance,
  12856. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  12857. for (var l = 0; l < edges.length; l++) {
  12858. //Keep distance from other edge centers
  12859. for (var l2 = l + 1; l2 < this.edges.length; l2++) {
  12860. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  12861. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  12862. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  12863. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  12864. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  12865. l2x = edges[l2].from.x+(edges[l2].to.x - edges[l2].from.x)/2,
  12866. l2y = edges[l2].from.y+(edges[l2].to.y - edges[l2].from.y)/2,
  12867. // calculate normally distributed force
  12868. dx = l2x - lx,
  12869. dy = l2y - ly,
  12870. distance = Math.sqrt(dx * dx + dy * dy),
  12871. angle = Math.atan2(dy, dx),
  12872. // TODO: correct factor for repulsing force
  12873. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12874. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  12875. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  12876. fx = Math.cos(angle) * repulsingforce,
  12877. fy = Math.sin(angle) * repulsingforce;
  12878. edges[l].from._addForce(-fx, -fy);
  12879. edges[l].to._addForce(-fx, -fy);
  12880. edges[l2].from._addForce(fx, fy);
  12881. edges[l2].to._addForce(fx, fy);
  12882. }
  12883. }
  12884. */
  12885. };
  12886. /**
  12887. * Check if any of the nodes is still moving
  12888. * @param {number} vmin the minimum velocity considered as 'moving'
  12889. * @return {boolean} true if moving, false if non of the nodes is moving
  12890. * @private
  12891. */
  12892. Graph.prototype._isMoving = function(vmin) {
  12893. var vminCorrected = vmin / this.scale;
  12894. var nodes = this.nodes;
  12895. for (var id in nodes) {
  12896. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vminCorrected)) {
  12897. return true;
  12898. }
  12899. }
  12900. return false;
  12901. };
  12902. /**
  12903. * /**
  12904. * Perform one discrete step for all nodes
  12905. *
  12906. * @param interval
  12907. * @private
  12908. */
  12909. Graph.prototype._discreteStepNodes = function() {
  12910. var interval = 0.010;
  12911. var nodes = this.nodes;
  12912. for (var id in nodes) {
  12913. if (nodes.hasOwnProperty(id)) {
  12914. nodes[id].discreteStep(interval);
  12915. }
  12916. }
  12917. var vmin = this.constants.minVelocity;
  12918. this.moving = this._isMoving(vmin);
  12919. };
  12920. /**
  12921. * Start animating nodes and edges
  12922. *
  12923. * @poram {Boolean} runCalculationStep
  12924. */
  12925. Graph.prototype.start = function() {
  12926. if (!this.freezeSimulation) {
  12927. if (this.moving) {
  12928. this._doInAllActiveSectors("_initializeForceCalculation");
  12929. this._doInAllActiveSectors("_discreteStepNodes");
  12930. this._findCenter(this._getRange())
  12931. }
  12932. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  12933. // start animation. only start calculationTimer if it is not already running
  12934. if (!this.timer) {
  12935. var graph = this;
  12936. this.timer = window.setTimeout(function () {
  12937. graph.timer = undefined;
  12938. // keyboad movement
  12939. if (graph.xIncrement != 0 || graph.yIncrement != 0) {
  12940. var translation = graph._getTranslation();
  12941. graph._setTranslation(translation.x+graph.xIncrement,translation.y+graph.yIncrement);
  12942. }
  12943. if (graph.zoomIncrement != 0) {
  12944. graph._zoom(graph.scale*(1 + graph.zoomIncrement),graph.lastPointerPosition);
  12945. }
  12946. graph.start();
  12947. graph._redraw();
  12948. //this.end = window.performance.now();
  12949. //this.time = this.end - this.startTime;
  12950. //console.log('refresh time: ' + this.time);
  12951. //this.startTime = window.performance.now();
  12952. }, this.renderTimestep);
  12953. }
  12954. }
  12955. else {
  12956. this._redraw();
  12957. }
  12958. }
  12959. };
  12960. Graph.prototype.singleStep = function() {
  12961. if (this.moving) {
  12962. this._initializeForceCalculation();
  12963. this._discreteStepNodes();
  12964. var vmin = this.constants.minVelocity;
  12965. this.moving = this._isMoving(vmin);
  12966. this._redraw();
  12967. }
  12968. };
  12969. /**
  12970. * Freeze the animation
  12971. */
  12972. Graph.prototype.toggleFreeze = function() {
  12973. if (this.freezeSimulation == false) {
  12974. this.freezeSimulation = true;
  12975. }
  12976. else {
  12977. this.freezeSimulation = false;
  12978. this.start();
  12979. }
  12980. };
  12981. /**
  12982. * Mixin the cluster system and initialize the parameters required.
  12983. *
  12984. * @private
  12985. */
  12986. Graph.prototype._loadClusterSystem = function() {
  12987. this.clusterSession = 0;
  12988. this.hubThreshold = 5;
  12989. for (var mixinFunction in ClusterMixin) {
  12990. if (ClusterMixin.hasOwnProperty(mixinFunction)) {
  12991. Graph.prototype[mixinFunction] = ClusterMixin[mixinFunction];
  12992. }
  12993. }
  12994. }
  12995. /**
  12996. * Mixin the sector system and initialize the parameters required
  12997. *
  12998. * @private
  12999. */
  13000. Graph.prototype._loadSectorSystem = function() {
  13001. this.sectors = {};
  13002. this.activeSector = ["default"];
  13003. this.sectors["active"] = {};
  13004. this.sectors["active"]["default"] = {"nodes":{},
  13005. "edges":{},
  13006. "nodeIndices":[],
  13007. "formationScale": 1.0,
  13008. "drawingNode": undefined};
  13009. this.sectors["frozen"] = {};
  13010. this.sectors["navigationUI"] = {"nodes":{},
  13011. "edges":{},
  13012. "nodeIndices":[],
  13013. "formationScale": 1.0,
  13014. "drawingNode": undefined};
  13015. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13016. for (var mixinFunction in SectorMixin) {
  13017. if (SectorMixin.hasOwnProperty(mixinFunction)) {
  13018. Graph.prototype[mixinFunction] = SectorMixin[mixinFunction];
  13019. }
  13020. }
  13021. };
  13022. /**
  13023. * Mixin the selection system and initialize the parameters required
  13024. *
  13025. * @private
  13026. */
  13027. Graph.prototype._loadSelectionSystem = function() {
  13028. this.selection = [];
  13029. this.selectionObj = {};
  13030. for (var mixinFunction in SelectionMixin) {
  13031. if (SelectionMixin.hasOwnProperty(mixinFunction)) {
  13032. Graph.prototype[mixinFunction] = SelectionMixin[mixinFunction];
  13033. }
  13034. }
  13035. }
  13036. /**
  13037. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13038. *
  13039. * @private
  13040. */
  13041. Graph.prototype._loadUISystem = function() {
  13042. for (var mixinFunction in UIMixin) {
  13043. if (UIMixin.hasOwnProperty(mixinFunction)) {
  13044. Graph.prototype[mixinFunction] = UIMixin[mixinFunction];
  13045. }
  13046. }
  13047. if (this.constants.navigationUI.enabled == true) {
  13048. this._loadUIElements();
  13049. this._createKeyBinds();
  13050. }
  13051. }
  13052. /**
  13053. * this function exists to avoid errors when not loading the navigationUI system
  13054. */
  13055. Graph.prototype._relocateUI = function() {
  13056. // empty, is overloaded by navigationUI system
  13057. }
  13058. /**
  13059. * * this function exists to avoid errors when not loading the navigationUI system
  13060. */
  13061. Graph.prototype._unHighlightAll = function() {
  13062. // empty, is overloaded by the navigationUI system
  13063. }
  13064. /**
  13065. * vis.js module exports
  13066. */
  13067. var vis = {
  13068. util: util,
  13069. events: events,
  13070. Controller: Controller,
  13071. DataSet: DataSet,
  13072. DataView: DataView,
  13073. Range: Range,
  13074. Stack: Stack,
  13075. TimeStep: TimeStep,
  13076. EventBus: EventBus,
  13077. components: {
  13078. items: {
  13079. Item: Item,
  13080. ItemBox: ItemBox,
  13081. ItemPoint: ItemPoint,
  13082. ItemRange: ItemRange
  13083. },
  13084. Component: Component,
  13085. Panel: Panel,
  13086. RootPanel: RootPanel,
  13087. ItemSet: ItemSet,
  13088. TimeAxis: TimeAxis
  13089. },
  13090. graph: {
  13091. Node: Node,
  13092. Edge: Edge,
  13093. Popup: Popup,
  13094. Groups: Groups,
  13095. Images: Images
  13096. },
  13097. Timeline: Timeline,
  13098. Graph: Graph
  13099. };
  13100. /**
  13101. * CommonJS module exports
  13102. */
  13103. if (typeof exports !== 'undefined') {
  13104. exports = vis;
  13105. }
  13106. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  13107. module.exports = vis;
  13108. }
  13109. /**
  13110. * AMD module exports
  13111. */
  13112. if (typeof(define) === 'function') {
  13113. define(function () {
  13114. return vis;
  13115. });
  13116. }
  13117. /**
  13118. * Window exports
  13119. */
  13120. if (typeof window !== 'undefined') {
  13121. // attach the module to the window, load as a regular javascript file
  13122. window['vis'] = vis;
  13123. }
  13124. },{"hammerjs":2,"moment":3,"mousetrap":4}],2:[function(require,module,exports){
  13125. /*! Hammer.JS - v1.0.5 - 2013-04-07
  13126. * http://eightmedia.github.com/hammer.js
  13127. *
  13128. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  13129. * Licensed under the MIT license */
  13130. (function(window, undefined) {
  13131. 'use strict';
  13132. /**
  13133. * Hammer
  13134. * use this to create instances
  13135. * @param {HTMLElement} element
  13136. * @param {Object} options
  13137. * @returns {Hammer.Instance}
  13138. * @constructor
  13139. */
  13140. var Hammer = function(element, options) {
  13141. return new Hammer.Instance(element, options || {});
  13142. };
  13143. // default settings
  13144. Hammer.defaults = {
  13145. // add styles and attributes to the element to prevent the browser from doing
  13146. // its native behavior. this doesnt prevent the scrolling, but cancels
  13147. // the contextmenu, tap highlighting etc
  13148. // set to false to disable this
  13149. stop_browser_behavior: {
  13150. // this also triggers onselectstart=false for IE
  13151. userSelect: 'none',
  13152. // this makes the element blocking in IE10 >, you could experiment with the value
  13153. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  13154. touchAction: 'none',
  13155. touchCallout: 'none',
  13156. contentZooming: 'none',
  13157. userDrag: 'none',
  13158. tapHighlightColor: 'rgba(0,0,0,0)'
  13159. }
  13160. // more settings are defined per gesture at gestures.js
  13161. };
  13162. // detect touchevents
  13163. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  13164. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  13165. // dont use mouseevents on mobile devices
  13166. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  13167. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  13168. // eventtypes per touchevent (start, move, end)
  13169. // are filled by Hammer.event.determineEventTypes on setup
  13170. Hammer.EVENT_TYPES = {};
  13171. // direction defines
  13172. Hammer.DIRECTION_DOWN = 'down';
  13173. Hammer.DIRECTION_LEFT = 'left';
  13174. Hammer.DIRECTION_UP = 'up';
  13175. Hammer.DIRECTION_RIGHT = 'right';
  13176. // pointer type
  13177. Hammer.POINTER_MOUSE = 'mouse';
  13178. Hammer.POINTER_TOUCH = 'touch';
  13179. Hammer.POINTER_PEN = 'pen';
  13180. // touch event defines
  13181. Hammer.EVENT_START = 'start';
  13182. Hammer.EVENT_MOVE = 'move';
  13183. Hammer.EVENT_END = 'end';
  13184. // hammer document where the base events are added at
  13185. Hammer.DOCUMENT = document;
  13186. // plugins namespace
  13187. Hammer.plugins = {};
  13188. // if the window events are set...
  13189. Hammer.READY = false;
  13190. /**
  13191. * setup events to detect gestures on the document
  13192. */
  13193. function setup() {
  13194. if(Hammer.READY) {
  13195. return;
  13196. }
  13197. // find what eventtypes we add listeners to
  13198. Hammer.event.determineEventTypes();
  13199. // Register all gestures inside Hammer.gestures
  13200. for(var name in Hammer.gestures) {
  13201. if(Hammer.gestures.hasOwnProperty(name)) {
  13202. Hammer.detection.register(Hammer.gestures[name]);
  13203. }
  13204. }
  13205. // Add touch events on the document
  13206. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  13207. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  13208. // Hammer is ready...!
  13209. Hammer.READY = true;
  13210. }
  13211. /**
  13212. * create new hammer instance
  13213. * all methods should return the instance itself, so it is chainable.
  13214. * @param {HTMLElement} element
  13215. * @param {Object} [options={}]
  13216. * @returns {Hammer.Instance}
  13217. * @constructor
  13218. */
  13219. Hammer.Instance = function(element, options) {
  13220. var self = this;
  13221. // setup HammerJS window events and register all gestures
  13222. // this also sets up the default options
  13223. setup();
  13224. this.element = element;
  13225. // start/stop detection option
  13226. this.enabled = true;
  13227. // merge options
  13228. this.options = Hammer.utils.extend(
  13229. Hammer.utils.extend({}, Hammer.defaults),
  13230. options || {});
  13231. // add some css to the element to prevent the browser from doing its native behavoir
  13232. if(this.options.stop_browser_behavior) {
  13233. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  13234. }
  13235. // start detection on touchstart
  13236. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  13237. if(self.enabled) {
  13238. Hammer.detection.startDetect(self, ev);
  13239. }
  13240. });
  13241. // return instance
  13242. return this;
  13243. };
  13244. Hammer.Instance.prototype = {
  13245. /**
  13246. * bind events to the instance
  13247. * @param {String} gesture
  13248. * @param {Function} handler
  13249. * @returns {Hammer.Instance}
  13250. */
  13251. on: function onEvent(gesture, handler){
  13252. var gestures = gesture.split(' ');
  13253. for(var t=0; t<gestures.length; t++) {
  13254. this.element.addEventListener(gestures[t], handler, false);
  13255. }
  13256. return this;
  13257. },
  13258. /**
  13259. * unbind events to the instance
  13260. * @param {String} gesture
  13261. * @param {Function} handler
  13262. * @returns {Hammer.Instance}
  13263. */
  13264. off: function offEvent(gesture, handler){
  13265. var gestures = gesture.split(' ');
  13266. for(var t=0; t<gestures.length; t++) {
  13267. this.element.removeEventListener(gestures[t], handler, false);
  13268. }
  13269. return this;
  13270. },
  13271. /**
  13272. * trigger gesture event
  13273. * @param {String} gesture
  13274. * @param {Object} eventData
  13275. * @returns {Hammer.Instance}
  13276. */
  13277. trigger: function triggerEvent(gesture, eventData){
  13278. // create DOM event
  13279. var event = Hammer.DOCUMENT.createEvent('Event');
  13280. event.initEvent(gesture, true, true);
  13281. event.gesture = eventData;
  13282. // trigger on the target if it is in the instance element,
  13283. // this is for event delegation tricks
  13284. var element = this.element;
  13285. if(Hammer.utils.hasParent(eventData.target, element)) {
  13286. element = eventData.target;
  13287. }
  13288. element.dispatchEvent(event);
  13289. return this;
  13290. },
  13291. /**
  13292. * enable of disable hammer.js detection
  13293. * @param {Boolean} state
  13294. * @returns {Hammer.Instance}
  13295. */
  13296. enable: function enable(state) {
  13297. this.enabled = state;
  13298. return this;
  13299. }
  13300. };
  13301. /**
  13302. * this holds the last move event,
  13303. * used to fix empty touchend issue
  13304. * see the onTouch event for an explanation
  13305. * @type {Object}
  13306. */
  13307. var last_move_event = null;
  13308. /**
  13309. * when the mouse is hold down, this is true
  13310. * @type {Boolean}
  13311. */
  13312. var enable_detect = false;
  13313. /**
  13314. * when touch events have been fired, this is true
  13315. * @type {Boolean}
  13316. */
  13317. var touch_triggered = false;
  13318. Hammer.event = {
  13319. /**
  13320. * simple addEventListener
  13321. * @param {HTMLElement} element
  13322. * @param {String} type
  13323. * @param {Function} handler
  13324. */
  13325. bindDom: function(element, type, handler) {
  13326. var types = type.split(' ');
  13327. for(var t=0; t<types.length; t++) {
  13328. element.addEventListener(types[t], handler, false);
  13329. }
  13330. },
  13331. /**
  13332. * touch events with mouse fallback
  13333. * @param {HTMLElement} element
  13334. * @param {String} eventType like Hammer.EVENT_MOVE
  13335. * @param {Function} handler
  13336. */
  13337. onTouch: function onTouch(element, eventType, handler) {
  13338. var self = this;
  13339. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  13340. var sourceEventType = ev.type.toLowerCase();
  13341. // onmouseup, but when touchend has been fired we do nothing.
  13342. // this is for touchdevices which also fire a mouseup on touchend
  13343. if(sourceEventType.match(/mouse/) && touch_triggered) {
  13344. return;
  13345. }
  13346. // mousebutton must be down or a touch event
  13347. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  13348. sourceEventType.match(/pointerdown/) || // pointerevents touch
  13349. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  13350. ){
  13351. enable_detect = true;
  13352. }
  13353. // we are in a touch event, set the touch triggered bool to true,
  13354. // this for the conflicts that may occur on ios and android
  13355. if(sourceEventType.match(/touch|pointer/)) {
  13356. touch_triggered = true;
  13357. }
  13358. // count the total touches on the screen
  13359. var count_touches = 0;
  13360. // when touch has been triggered in this detection session
  13361. // and we are now handling a mouse event, we stop that to prevent conflicts
  13362. if(enable_detect) {
  13363. // update pointerevent
  13364. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  13365. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  13366. }
  13367. // touch
  13368. else if(sourceEventType.match(/touch/)) {
  13369. count_touches = ev.touches.length;
  13370. }
  13371. // mouse
  13372. else if(!touch_triggered) {
  13373. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  13374. }
  13375. // if we are in a end event, but when we remove one touch and
  13376. // we still have enough, set eventType to move
  13377. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  13378. eventType = Hammer.EVENT_MOVE;
  13379. }
  13380. // no touches, force the end event
  13381. else if(!count_touches) {
  13382. eventType = Hammer.EVENT_END;
  13383. }
  13384. // because touchend has no touches, and we often want to use these in our gestures,
  13385. // we send the last move event as our eventData in touchend
  13386. if(!count_touches && last_move_event !== null) {
  13387. ev = last_move_event;
  13388. }
  13389. // store the last move event
  13390. else {
  13391. last_move_event = ev;
  13392. }
  13393. // trigger the handler
  13394. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  13395. // remove pointerevent from list
  13396. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  13397. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  13398. }
  13399. }
  13400. //debug(sourceEventType +" "+ eventType);
  13401. // on the end we reset everything
  13402. if(!count_touches) {
  13403. last_move_event = null;
  13404. enable_detect = false;
  13405. touch_triggered = false;
  13406. Hammer.PointerEvent.reset();
  13407. }
  13408. });
  13409. },
  13410. /**
  13411. * we have different events for each device/browser
  13412. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  13413. */
  13414. determineEventTypes: function determineEventTypes() {
  13415. // determine the eventtype we want to set
  13416. var types;
  13417. // pointerEvents magic
  13418. if(Hammer.HAS_POINTEREVENTS) {
  13419. types = Hammer.PointerEvent.getEvents();
  13420. }
  13421. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  13422. else if(Hammer.NO_MOUSEEVENTS) {
  13423. types = [
  13424. 'touchstart',
  13425. 'touchmove',
  13426. 'touchend touchcancel'];
  13427. }
  13428. // for non pointer events browsers and mixed browsers,
  13429. // like chrome on windows8 touch laptop
  13430. else {
  13431. types = [
  13432. 'touchstart mousedown',
  13433. 'touchmove mousemove',
  13434. 'touchend touchcancel mouseup'];
  13435. }
  13436. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  13437. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  13438. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  13439. },
  13440. /**
  13441. * create touchlist depending on the event
  13442. * @param {Object} ev
  13443. * @param {String} eventType used by the fakemultitouch plugin
  13444. */
  13445. getTouchList: function getTouchList(ev/*, eventType*/) {
  13446. // get the fake pointerEvent touchlist
  13447. if(Hammer.HAS_POINTEREVENTS) {
  13448. return Hammer.PointerEvent.getTouchList();
  13449. }
  13450. // get the touchlist
  13451. else if(ev.touches) {
  13452. return ev.touches;
  13453. }
  13454. // make fake touchlist from mouse position
  13455. else {
  13456. return [{
  13457. identifier: 1,
  13458. pageX: ev.pageX,
  13459. pageY: ev.pageY,
  13460. target: ev.target
  13461. }];
  13462. }
  13463. },
  13464. /**
  13465. * collect event data for Hammer js
  13466. * @param {HTMLElement} element
  13467. * @param {String} eventType like Hammer.EVENT_MOVE
  13468. * @param {Object} eventData
  13469. */
  13470. collectEventData: function collectEventData(element, eventType, ev) {
  13471. var touches = this.getTouchList(ev, eventType);
  13472. // find out pointerType
  13473. var pointerType = Hammer.POINTER_TOUCH;
  13474. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  13475. pointerType = Hammer.POINTER_MOUSE;
  13476. }
  13477. return {
  13478. center : Hammer.utils.getCenter(touches),
  13479. timeStamp : new Date().getTime(),
  13480. target : ev.target,
  13481. touches : touches,
  13482. eventType : eventType,
  13483. pointerType : pointerType,
  13484. srcEvent : ev,
  13485. /**
  13486. * prevent the browser default actions
  13487. * mostly used to disable scrolling of the browser
  13488. */
  13489. preventDefault: function() {
  13490. if(this.srcEvent.preventManipulation) {
  13491. this.srcEvent.preventManipulation();
  13492. }
  13493. if(this.srcEvent.preventDefault) {
  13494. this.srcEvent.preventDefault();
  13495. }
  13496. },
  13497. /**
  13498. * stop bubbling the event up to its parents
  13499. */
  13500. stopPropagation: function() {
  13501. this.srcEvent.stopPropagation();
  13502. },
  13503. /**
  13504. * immediately stop gesture detection
  13505. * might be useful after a swipe was detected
  13506. * @return {*}
  13507. */
  13508. stopDetect: function() {
  13509. return Hammer.detection.stopDetect();
  13510. }
  13511. };
  13512. }
  13513. };
  13514. Hammer.PointerEvent = {
  13515. /**
  13516. * holds all pointers
  13517. * @type {Object}
  13518. */
  13519. pointers: {},
  13520. /**
  13521. * get a list of pointers
  13522. * @returns {Array} touchlist
  13523. */
  13524. getTouchList: function() {
  13525. var self = this;
  13526. var touchlist = [];
  13527. // we can use forEach since pointerEvents only is in IE10
  13528. Object.keys(self.pointers).sort().forEach(function(id) {
  13529. touchlist.push(self.pointers[id]);
  13530. });
  13531. return touchlist;
  13532. },
  13533. /**
  13534. * update the position of a pointer
  13535. * @param {String} type Hammer.EVENT_END
  13536. * @param {Object} pointerEvent
  13537. */
  13538. updatePointer: function(type, pointerEvent) {
  13539. if(type == Hammer.EVENT_END) {
  13540. this.pointers = {};
  13541. }
  13542. else {
  13543. pointerEvent.identifier = pointerEvent.pointerId;
  13544. this.pointers[pointerEvent.pointerId] = pointerEvent;
  13545. }
  13546. return Object.keys(this.pointers).length;
  13547. },
  13548. /**
  13549. * check if ev matches pointertype
  13550. * @param {String} pointerType Hammer.POINTER_MOUSE
  13551. * @param {PointerEvent} ev
  13552. */
  13553. matchType: function(pointerType, ev) {
  13554. if(!ev.pointerType) {
  13555. return false;
  13556. }
  13557. var types = {};
  13558. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  13559. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  13560. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  13561. return types[pointerType];
  13562. },
  13563. /**
  13564. * get events
  13565. */
  13566. getEvents: function() {
  13567. return [
  13568. 'pointerdown MSPointerDown',
  13569. 'pointermove MSPointerMove',
  13570. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  13571. ];
  13572. },
  13573. /**
  13574. * reset the list
  13575. */
  13576. reset: function() {
  13577. this.pointers = {};
  13578. }
  13579. };
  13580. Hammer.utils = {
  13581. /**
  13582. * extend method,
  13583. * also used for cloning when dest is an empty object
  13584. * @param {Object} dest
  13585. * @param {Object} src
  13586. * @parm {Boolean} merge do a merge
  13587. * @returns {Object} dest
  13588. */
  13589. extend: function extend(dest, src, merge) {
  13590. for (var key in src) {
  13591. if(dest[key] !== undefined && merge) {
  13592. continue;
  13593. }
  13594. dest[key] = src[key];
  13595. }
  13596. return dest;
  13597. },
  13598. /**
  13599. * find if a node is in the given parent
  13600. * used for event delegation tricks
  13601. * @param {HTMLElement} node
  13602. * @param {HTMLElement} parent
  13603. * @returns {boolean} has_parent
  13604. */
  13605. hasParent: function(node, parent) {
  13606. while(node){
  13607. if(node == parent) {
  13608. return true;
  13609. }
  13610. node = node.parentNode;
  13611. }
  13612. return false;
  13613. },
  13614. /**
  13615. * get the center of all the touches
  13616. * @param {Array} touches
  13617. * @returns {Object} center
  13618. */
  13619. getCenter: function getCenter(touches) {
  13620. var valuesX = [], valuesY = [];
  13621. for(var t= 0,len=touches.length; t<len; t++) {
  13622. valuesX.push(touches[t].pageX);
  13623. valuesY.push(touches[t].pageY);
  13624. }
  13625. return {
  13626. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  13627. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  13628. };
  13629. },
  13630. /**
  13631. * calculate the velocity between two points
  13632. * @param {Number} delta_time
  13633. * @param {Number} delta_x
  13634. * @param {Number} delta_y
  13635. * @returns {Object} velocity
  13636. */
  13637. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  13638. return {
  13639. x: Math.abs(delta_x / delta_time) || 0,
  13640. y: Math.abs(delta_y / delta_time) || 0
  13641. };
  13642. },
  13643. /**
  13644. * calculate the angle between two coordinates
  13645. * @param {Touch} touch1
  13646. * @param {Touch} touch2
  13647. * @returns {Number} angle
  13648. */
  13649. getAngle: function getAngle(touch1, touch2) {
  13650. var y = touch2.pageY - touch1.pageY,
  13651. x = touch2.pageX - touch1.pageX;
  13652. return Math.atan2(y, x) * 180 / Math.PI;
  13653. },
  13654. /**
  13655. * angle to direction define
  13656. * @param {Touch} touch1
  13657. * @param {Touch} touch2
  13658. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  13659. */
  13660. getDirection: function getDirection(touch1, touch2) {
  13661. var x = Math.abs(touch1.pageX - touch2.pageX),
  13662. y = Math.abs(touch1.pageY - touch2.pageY);
  13663. if(x >= y) {
  13664. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  13665. }
  13666. else {
  13667. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  13668. }
  13669. },
  13670. /**
  13671. * calculate the distance between two touches
  13672. * @param {Touch} touch1
  13673. * @param {Touch} touch2
  13674. * @returns {Number} distance
  13675. */
  13676. getDistance: function getDistance(touch1, touch2) {
  13677. var x = touch2.pageX - touch1.pageX,
  13678. y = touch2.pageY - touch1.pageY;
  13679. return Math.sqrt((x*x) + (y*y));
  13680. },
  13681. /**
  13682. * calculate the scale factor between two touchLists (fingers)
  13683. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  13684. * @param {Array} start
  13685. * @param {Array} end
  13686. * @returns {Number} scale
  13687. */
  13688. getScale: function getScale(start, end) {
  13689. // need two fingers...
  13690. if(start.length >= 2 && end.length >= 2) {
  13691. return this.getDistance(end[0], end[1]) /
  13692. this.getDistance(start[0], start[1]);
  13693. }
  13694. return 1;
  13695. },
  13696. /**
  13697. * calculate the rotation degrees between two touchLists (fingers)
  13698. * @param {Array} start
  13699. * @param {Array} end
  13700. * @returns {Number} rotation
  13701. */
  13702. getRotation: function getRotation(start, end) {
  13703. // need two fingers
  13704. if(start.length >= 2 && end.length >= 2) {
  13705. return this.getAngle(end[1], end[0]) -
  13706. this.getAngle(start[1], start[0]);
  13707. }
  13708. return 0;
  13709. },
  13710. /**
  13711. * boolean if the direction is vertical
  13712. * @param {String} direction
  13713. * @returns {Boolean} is_vertical
  13714. */
  13715. isVertical: function isVertical(direction) {
  13716. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  13717. },
  13718. /**
  13719. * stop browser default behavior with css props
  13720. * @param {HtmlElement} element
  13721. * @param {Object} css_props
  13722. */
  13723. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  13724. var prop,
  13725. vendors = ['webkit','khtml','moz','ms','o',''];
  13726. if(!css_props || !element.style) {
  13727. return;
  13728. }
  13729. // with css properties for modern browsers
  13730. for(var i = 0; i < vendors.length; i++) {
  13731. for(var p in css_props) {
  13732. if(css_props.hasOwnProperty(p)) {
  13733. prop = p;
  13734. // vender prefix at the property
  13735. if(vendors[i]) {
  13736. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  13737. }
  13738. // set the style
  13739. element.style[prop] = css_props[p];
  13740. }
  13741. }
  13742. }
  13743. // also the disable onselectstart
  13744. if(css_props.userSelect == 'none') {
  13745. element.onselectstart = function() {
  13746. return false;
  13747. };
  13748. }
  13749. }
  13750. };
  13751. Hammer.detection = {
  13752. // contains all registred Hammer.gestures in the correct order
  13753. gestures: [],
  13754. // data of the current Hammer.gesture detection session
  13755. current: null,
  13756. // the previous Hammer.gesture session data
  13757. // is a full clone of the previous gesture.current object
  13758. previous: null,
  13759. // when this becomes true, no gestures are fired
  13760. stopped: false,
  13761. /**
  13762. * start Hammer.gesture detection
  13763. * @param {Hammer.Instance} inst
  13764. * @param {Object} eventData
  13765. */
  13766. startDetect: function startDetect(inst, eventData) {
  13767. // already busy with a Hammer.gesture detection on an element
  13768. if(this.current) {
  13769. return;
  13770. }
  13771. this.stopped = false;
  13772. this.current = {
  13773. inst : inst, // reference to HammerInstance we're working for
  13774. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  13775. lastEvent : false, // last eventData
  13776. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  13777. };
  13778. this.detect(eventData);
  13779. },
  13780. /**
  13781. * Hammer.gesture detection
  13782. * @param {Object} eventData
  13783. * @param {Object} eventData
  13784. */
  13785. detect: function detect(eventData) {
  13786. if(!this.current || this.stopped) {
  13787. return;
  13788. }
  13789. // extend event data with calculations about scale, distance etc
  13790. eventData = this.extendEventData(eventData);
  13791. // instance options
  13792. var inst_options = this.current.inst.options;
  13793. // call Hammer.gesture handlers
  13794. for(var g=0,len=this.gestures.length; g<len; g++) {
  13795. var gesture = this.gestures[g];
  13796. // only when the instance options have enabled this gesture
  13797. if(!this.stopped && inst_options[gesture.name] !== false) {
  13798. // if a handler returns false, we stop with the detection
  13799. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  13800. this.stopDetect();
  13801. break;
  13802. }
  13803. }
  13804. }
  13805. // store as previous event event
  13806. if(this.current) {
  13807. this.current.lastEvent = eventData;
  13808. }
  13809. // endevent, but not the last touch, so dont stop
  13810. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  13811. this.stopDetect();
  13812. }
  13813. return eventData;
  13814. },
  13815. /**
  13816. * clear the Hammer.gesture vars
  13817. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  13818. * to stop other Hammer.gestures from being fired
  13819. */
  13820. stopDetect: function stopDetect() {
  13821. // clone current data to the store as the previous gesture
  13822. // used for the double tap gesture, since this is an other gesture detect session
  13823. this.previous = Hammer.utils.extend({}, this.current);
  13824. // reset the current
  13825. this.current = null;
  13826. // stopped!
  13827. this.stopped = true;
  13828. },
  13829. /**
  13830. * extend eventData for Hammer.gestures
  13831. * @param {Object} ev
  13832. * @returns {Object} ev
  13833. */
  13834. extendEventData: function extendEventData(ev) {
  13835. var startEv = this.current.startEvent;
  13836. // if the touches change, set the new touches over the startEvent touches
  13837. // this because touchevents don't have all the touches on touchstart, or the
  13838. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  13839. // but, sometimes it happens that both fingers are touching at the EXACT same time
  13840. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  13841. // extend 1 level deep to get the touchlist with the touch objects
  13842. startEv.touches = [];
  13843. for(var i=0,len=ev.touches.length; i<len; i++) {
  13844. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  13845. }
  13846. }
  13847. var delta_time = ev.timeStamp - startEv.timeStamp,
  13848. delta_x = ev.center.pageX - startEv.center.pageX,
  13849. delta_y = ev.center.pageY - startEv.center.pageY,
  13850. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  13851. Hammer.utils.extend(ev, {
  13852. deltaTime : delta_time,
  13853. deltaX : delta_x,
  13854. deltaY : delta_y,
  13855. velocityX : velocity.x,
  13856. velocityY : velocity.y,
  13857. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  13858. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  13859. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  13860. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  13861. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  13862. startEvent : startEv
  13863. });
  13864. return ev;
  13865. },
  13866. /**
  13867. * register new gesture
  13868. * @param {Object} gesture object, see gestures.js for documentation
  13869. * @returns {Array} gestures
  13870. */
  13871. register: function register(gesture) {
  13872. // add an enable gesture options if there is no given
  13873. var options = gesture.defaults || {};
  13874. if(options[gesture.name] === undefined) {
  13875. options[gesture.name] = true;
  13876. }
  13877. // extend Hammer default options with the Hammer.gesture options
  13878. Hammer.utils.extend(Hammer.defaults, options, true);
  13879. // set its index
  13880. gesture.index = gesture.index || 1000;
  13881. // add Hammer.gesture to the list
  13882. this.gestures.push(gesture);
  13883. // sort the list by index
  13884. this.gestures.sort(function(a, b) {
  13885. if (a.index < b.index) {
  13886. return -1;
  13887. }
  13888. if (a.index > b.index) {
  13889. return 1;
  13890. }
  13891. return 0;
  13892. });
  13893. return this.gestures;
  13894. }
  13895. };
  13896. Hammer.gestures = Hammer.gestures || {};
  13897. /**
  13898. * Custom gestures
  13899. * ==============================
  13900. *
  13901. * Gesture object
  13902. * --------------------
  13903. * The object structure of a gesture:
  13904. *
  13905. * { name: 'mygesture',
  13906. * index: 1337,
  13907. * defaults: {
  13908. * mygesture_option: true
  13909. * }
  13910. * handler: function(type, ev, inst) {
  13911. * // trigger gesture event
  13912. * inst.trigger(this.name, ev);
  13913. * }
  13914. * }
  13915. * @param {String} name
  13916. * this should be the name of the gesture, lowercase
  13917. * it is also being used to disable/enable the gesture per instance config.
  13918. *
  13919. * @param {Number} [index=1000]
  13920. * the index of the gesture, where it is going to be in the stack of gestures detection
  13921. * like when you build an gesture that depends on the drag gesture, it is a good
  13922. * idea to place it after the index of the drag gesture.
  13923. *
  13924. * @param {Object} [defaults={}]
  13925. * the default settings of the gesture. these are added to the instance settings,
  13926. * and can be overruled per instance. you can also add the name of the gesture,
  13927. * but this is also added by default (and set to true).
  13928. *
  13929. * @param {Function} handler
  13930. * this handles the gesture detection of your custom gesture and receives the
  13931. * following arguments:
  13932. *
  13933. * @param {Object} eventData
  13934. * event data containing the following properties:
  13935. * timeStamp {Number} time the event occurred
  13936. * target {HTMLElement} target element
  13937. * touches {Array} touches (fingers, pointers, mouse) on the screen
  13938. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  13939. * center {Object} center position of the touches. contains pageX and pageY
  13940. * deltaTime {Number} the total time of the touches in the screen
  13941. * deltaX {Number} the delta on x axis we haved moved
  13942. * deltaY {Number} the delta on y axis we haved moved
  13943. * velocityX {Number} the velocity on the x
  13944. * velocityY {Number} the velocity on y
  13945. * angle {Number} the angle we are moving
  13946. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  13947. * distance {Number} the distance we haved moved
  13948. * scale {Number} scaling of the touches, needs 2 touches
  13949. * rotation {Number} rotation of the touches, needs 2 touches *
  13950. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  13951. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  13952. * startEvent {Object} contains the same properties as above,
  13953. * but from the first touch. this is used to calculate
  13954. * distances, deltaTime, scaling etc
  13955. *
  13956. * @param {Hammer.Instance} inst
  13957. * the instance we are doing the detection for. you can get the options from
  13958. * the inst.options object and trigger the gesture event by calling inst.trigger
  13959. *
  13960. *
  13961. * Handle gestures
  13962. * --------------------
  13963. * inside the handler you can get/set Hammer.detection.current. This is the current
  13964. * detection session. It has the following properties
  13965. * @param {String} name
  13966. * contains the name of the gesture we have detected. it has not a real function,
  13967. * only to check in other gestures if something is detected.
  13968. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  13969. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  13970. *
  13971. * @readonly
  13972. * @param {Hammer.Instance} inst
  13973. * the instance we do the detection for
  13974. *
  13975. * @readonly
  13976. * @param {Object} startEvent
  13977. * contains the properties of the first gesture detection in this session.
  13978. * Used for calculations about timing, distance, etc.
  13979. *
  13980. * @readonly
  13981. * @param {Object} lastEvent
  13982. * contains all the properties of the last gesture detect in this session.
  13983. *
  13984. * after the gesture detection session has been completed (user has released the screen)
  13985. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  13986. * this is usefull for gestures like doubletap, where you need to know if the
  13987. * previous gesture was a tap
  13988. *
  13989. * options that have been set by the instance can be received by calling inst.options
  13990. *
  13991. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  13992. * The first param is the name of your gesture, the second the event argument
  13993. *
  13994. *
  13995. * Register gestures
  13996. * --------------------
  13997. * When an gesture is added to the Hammer.gestures object, it is auto registered
  13998. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  13999. * manually and pass your gesture object as a param
  14000. *
  14001. */
  14002. /**
  14003. * Hold
  14004. * Touch stays at the same place for x time
  14005. * @events hold
  14006. */
  14007. Hammer.gestures.Hold = {
  14008. name: 'hold',
  14009. index: 10,
  14010. defaults: {
  14011. hold_timeout : 500,
  14012. hold_threshold : 1
  14013. },
  14014. timer: null,
  14015. handler: function holdGesture(ev, inst) {
  14016. switch(ev.eventType) {
  14017. case Hammer.EVENT_START:
  14018. // clear any running timers
  14019. clearTimeout(this.timer);
  14020. // set the gesture so we can check in the timeout if it still is
  14021. Hammer.detection.current.name = this.name;
  14022. // set timer and if after the timeout it still is hold,
  14023. // we trigger the hold event
  14024. this.timer = setTimeout(function() {
  14025. if(Hammer.detection.current.name == 'hold') {
  14026. inst.trigger('hold', ev);
  14027. }
  14028. }, inst.options.hold_timeout);
  14029. break;
  14030. // when you move or end we clear the timer
  14031. case Hammer.EVENT_MOVE:
  14032. if(ev.distance > inst.options.hold_threshold) {
  14033. clearTimeout(this.timer);
  14034. }
  14035. break;
  14036. case Hammer.EVENT_END:
  14037. clearTimeout(this.timer);
  14038. break;
  14039. }
  14040. }
  14041. };
  14042. /**
  14043. * Tap/DoubleTap
  14044. * Quick touch at a place or double at the same place
  14045. * @events tap, doubletap
  14046. */
  14047. Hammer.gestures.Tap = {
  14048. name: 'tap',
  14049. index: 100,
  14050. defaults: {
  14051. tap_max_touchtime : 250,
  14052. tap_max_distance : 10,
  14053. tap_always : true,
  14054. doubletap_distance : 20,
  14055. doubletap_interval : 300
  14056. },
  14057. handler: function tapGesture(ev, inst) {
  14058. if(ev.eventType == Hammer.EVENT_END) {
  14059. // previous gesture, for the double tap since these are two different gesture detections
  14060. var prev = Hammer.detection.previous,
  14061. did_doubletap = false;
  14062. // when the touchtime is higher then the max touch time
  14063. // or when the moving distance is too much
  14064. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  14065. ev.distance > inst.options.tap_max_distance) {
  14066. return;
  14067. }
  14068. // check if double tap
  14069. if(prev && prev.name == 'tap' &&
  14070. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  14071. ev.distance < inst.options.doubletap_distance) {
  14072. inst.trigger('doubletap', ev);
  14073. did_doubletap = true;
  14074. }
  14075. // do a single tap
  14076. if(!did_doubletap || inst.options.tap_always) {
  14077. Hammer.detection.current.name = 'tap';
  14078. inst.trigger(Hammer.detection.current.name, ev);
  14079. }
  14080. }
  14081. }
  14082. };
  14083. /**
  14084. * Swipe
  14085. * triggers swipe events when the end velocity is above the threshold
  14086. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  14087. */
  14088. Hammer.gestures.Swipe = {
  14089. name: 'swipe',
  14090. index: 40,
  14091. defaults: {
  14092. // set 0 for unlimited, but this can conflict with transform
  14093. swipe_max_touches : 1,
  14094. swipe_velocity : 0.7
  14095. },
  14096. handler: function swipeGesture(ev, inst) {
  14097. if(ev.eventType == Hammer.EVENT_END) {
  14098. // max touches
  14099. if(inst.options.swipe_max_touches > 0 &&
  14100. ev.touches.length > inst.options.swipe_max_touches) {
  14101. return;
  14102. }
  14103. // when the distance we moved is too small we skip this gesture
  14104. // or we can be already in dragging
  14105. if(ev.velocityX > inst.options.swipe_velocity ||
  14106. ev.velocityY > inst.options.swipe_velocity) {
  14107. // trigger swipe events
  14108. inst.trigger(this.name, ev);
  14109. inst.trigger(this.name + ev.direction, ev);
  14110. }
  14111. }
  14112. }
  14113. };
  14114. /**
  14115. * Drag
  14116. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  14117. * moving left and right is a good practice. When all the drag events are blocking
  14118. * you disable scrolling on that area.
  14119. * @events drag, drapleft, dragright, dragup, dragdown
  14120. */
  14121. Hammer.gestures.Drag = {
  14122. name: 'drag',
  14123. index: 50,
  14124. defaults: {
  14125. drag_min_distance : 10,
  14126. // set 0 for unlimited, but this can conflict with transform
  14127. drag_max_touches : 1,
  14128. // prevent default browser behavior when dragging occurs
  14129. // be careful with it, it makes the element a blocking element
  14130. // when you are using the drag gesture, it is a good practice to set this true
  14131. drag_block_horizontal : false,
  14132. drag_block_vertical : false,
  14133. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  14134. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  14135. drag_lock_to_axis : false,
  14136. // drag lock only kicks in when distance > drag_lock_min_distance
  14137. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  14138. drag_lock_min_distance : 25
  14139. },
  14140. triggered: false,
  14141. handler: function dragGesture(ev, inst) {
  14142. // current gesture isnt drag, but dragged is true
  14143. // this means an other gesture is busy. now call dragend
  14144. if(Hammer.detection.current.name != this.name && this.triggered) {
  14145. inst.trigger(this.name +'end', ev);
  14146. this.triggered = false;
  14147. return;
  14148. }
  14149. // max touches
  14150. if(inst.options.drag_max_touches > 0 &&
  14151. ev.touches.length > inst.options.drag_max_touches) {
  14152. return;
  14153. }
  14154. switch(ev.eventType) {
  14155. case Hammer.EVENT_START:
  14156. this.triggered = false;
  14157. break;
  14158. case Hammer.EVENT_MOVE:
  14159. // when the distance we moved is too small we skip this gesture
  14160. // or we can be already in dragging
  14161. if(ev.distance < inst.options.drag_min_distance &&
  14162. Hammer.detection.current.name != this.name) {
  14163. return;
  14164. }
  14165. // we are dragging!
  14166. Hammer.detection.current.name = this.name;
  14167. // lock drag to axis?
  14168. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  14169. ev.drag_locked_to_axis = true;
  14170. }
  14171. var last_direction = Hammer.detection.current.lastEvent.direction;
  14172. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  14173. // keep direction on the axis that the drag gesture started on
  14174. if(Hammer.utils.isVertical(last_direction)) {
  14175. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  14176. }
  14177. else {
  14178. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  14179. }
  14180. }
  14181. // first time, trigger dragstart event
  14182. if(!this.triggered) {
  14183. inst.trigger(this.name +'start', ev);
  14184. this.triggered = true;
  14185. }
  14186. // trigger normal event
  14187. inst.trigger(this.name, ev);
  14188. // direction event, like dragdown
  14189. inst.trigger(this.name + ev.direction, ev);
  14190. // block the browser events
  14191. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  14192. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  14193. ev.preventDefault();
  14194. }
  14195. break;
  14196. case Hammer.EVENT_END:
  14197. // trigger dragend
  14198. if(this.triggered) {
  14199. inst.trigger(this.name +'end', ev);
  14200. }
  14201. this.triggered = false;
  14202. break;
  14203. }
  14204. }
  14205. };
  14206. /**
  14207. * Transform
  14208. * User want to scale or rotate with 2 fingers
  14209. * @events transform, pinch, pinchin, pinchout, rotate
  14210. */
  14211. Hammer.gestures.Transform = {
  14212. name: 'transform',
  14213. index: 45,
  14214. defaults: {
  14215. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  14216. transform_min_scale : 0.01,
  14217. // rotation in degrees
  14218. transform_min_rotation : 1,
  14219. // prevent default browser behavior when two touches are on the screen
  14220. // but it makes the element a blocking element
  14221. // when you are using the transform gesture, it is a good practice to set this true
  14222. transform_always_block : false
  14223. },
  14224. triggered: false,
  14225. handler: function transformGesture(ev, inst) {
  14226. // current gesture isnt drag, but dragged is true
  14227. // this means an other gesture is busy. now call dragend
  14228. if(Hammer.detection.current.name != this.name && this.triggered) {
  14229. inst.trigger(this.name +'end', ev);
  14230. this.triggered = false;
  14231. return;
  14232. }
  14233. // atleast multitouch
  14234. if(ev.touches.length < 2) {
  14235. return;
  14236. }
  14237. // prevent default when two fingers are on the screen
  14238. if(inst.options.transform_always_block) {
  14239. ev.preventDefault();
  14240. }
  14241. switch(ev.eventType) {
  14242. case Hammer.EVENT_START:
  14243. this.triggered = false;
  14244. break;
  14245. case Hammer.EVENT_MOVE:
  14246. var scale_threshold = Math.abs(1-ev.scale);
  14247. var rotation_threshold = Math.abs(ev.rotation);
  14248. // when the distance we moved is too small we skip this gesture
  14249. // or we can be already in dragging
  14250. if(scale_threshold < inst.options.transform_min_scale &&
  14251. rotation_threshold < inst.options.transform_min_rotation) {
  14252. return;
  14253. }
  14254. // we are transforming!
  14255. Hammer.detection.current.name = this.name;
  14256. // first time, trigger dragstart event
  14257. if(!this.triggered) {
  14258. inst.trigger(this.name +'start', ev);
  14259. this.triggered = true;
  14260. }
  14261. inst.trigger(this.name, ev); // basic transform event
  14262. // trigger rotate event
  14263. if(rotation_threshold > inst.options.transform_min_rotation) {
  14264. inst.trigger('rotate', ev);
  14265. }
  14266. // trigger pinch event
  14267. if(scale_threshold > inst.options.transform_min_scale) {
  14268. inst.trigger('pinch', ev);
  14269. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  14270. }
  14271. break;
  14272. case Hammer.EVENT_END:
  14273. // trigger dragend
  14274. if(this.triggered) {
  14275. inst.trigger(this.name +'end', ev);
  14276. }
  14277. this.triggered = false;
  14278. break;
  14279. }
  14280. }
  14281. };
  14282. /**
  14283. * Touch
  14284. * Called as first, tells the user has touched the screen
  14285. * @events touch
  14286. */
  14287. Hammer.gestures.Touch = {
  14288. name: 'touch',
  14289. index: -Infinity,
  14290. defaults: {
  14291. // call preventDefault at touchstart, and makes the element blocking by
  14292. // disabling the scrolling of the page, but it improves gestures like
  14293. // transforming and dragging.
  14294. // be careful with using this, it can be very annoying for users to be stuck
  14295. // on the page
  14296. prevent_default: false,
  14297. // disable mouse events, so only touch (or pen!) input triggers events
  14298. prevent_mouseevents: false
  14299. },
  14300. handler: function touchGesture(ev, inst) {
  14301. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  14302. ev.stopDetect();
  14303. return;
  14304. }
  14305. if(inst.options.prevent_default) {
  14306. ev.preventDefault();
  14307. }
  14308. if(ev.eventType == Hammer.EVENT_START) {
  14309. inst.trigger(this.name, ev);
  14310. }
  14311. }
  14312. };
  14313. /**
  14314. * Release
  14315. * Called as last, tells the user has released the screen
  14316. * @events release
  14317. */
  14318. Hammer.gestures.Release = {
  14319. name: 'release',
  14320. index: Infinity,
  14321. handler: function releaseGesture(ev, inst) {
  14322. if(ev.eventType == Hammer.EVENT_END) {
  14323. inst.trigger(this.name, ev);
  14324. }
  14325. }
  14326. };
  14327. // node export
  14328. if(typeof module === 'object' && typeof module.exports === 'object'){
  14329. module.exports = Hammer;
  14330. }
  14331. // just window export
  14332. else {
  14333. window.Hammer = Hammer;
  14334. // requireJS module definition
  14335. if(typeof window.define === 'function' && window.define.amd) {
  14336. window.define('hammer', [], function() {
  14337. return Hammer;
  14338. });
  14339. }
  14340. }
  14341. })(this);
  14342. },{}],3:[function(require,module,exports){
  14343. //! moment.js
  14344. //! version : 2.5.1
  14345. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  14346. //! license : MIT
  14347. //! momentjs.com
  14348. (function (undefined) {
  14349. /************************************
  14350. Constants
  14351. ************************************/
  14352. var moment,
  14353. VERSION = "2.5.1",
  14354. global = this,
  14355. round = Math.round,
  14356. i,
  14357. YEAR = 0,
  14358. MONTH = 1,
  14359. DATE = 2,
  14360. HOUR = 3,
  14361. MINUTE = 4,
  14362. SECOND = 5,
  14363. MILLISECOND = 6,
  14364. // internal storage for language config files
  14365. languages = {},
  14366. // moment internal properties
  14367. momentProperties = {
  14368. _isAMomentObject: null,
  14369. _i : null,
  14370. _f : null,
  14371. _l : null,
  14372. _strict : null,
  14373. _isUTC : null,
  14374. _offset : null, // optional. Combine with _isUTC
  14375. _pf : null,
  14376. _lang : null // optional
  14377. },
  14378. // check for nodeJS
  14379. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  14380. // ASP.NET json date format regex
  14381. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  14382. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  14383. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  14384. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  14385. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  14386. // format tokens
  14387. 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,
  14388. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  14389. // parsing token regexes
  14390. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  14391. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  14392. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  14393. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  14394. parseTokenDigits = /\d+/, // nonzero number of digits
  14395. 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.
  14396. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  14397. parseTokenT = /T/i, // T (ISO separator)
  14398. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  14399. //strict parsing regexes
  14400. parseTokenOneDigit = /\d/, // 0 - 9
  14401. parseTokenTwoDigits = /\d\d/, // 00 - 99
  14402. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  14403. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  14404. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  14405. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  14406. // iso 8601 regex
  14407. // 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)
  14408. isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
  14409. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  14410. isoDates = [
  14411. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  14412. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  14413. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  14414. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  14415. ['YYYY-DDD', /\d{4}-\d{3}/]
  14416. ],
  14417. // iso time formats and regexes
  14418. isoTimes = [
  14419. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  14420. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  14421. ['HH:mm', /(T| )\d\d:\d\d/],
  14422. ['HH', /(T| )\d\d/]
  14423. ],
  14424. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  14425. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  14426. // getter and setter names
  14427. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  14428. unitMillisecondFactors = {
  14429. 'Milliseconds' : 1,
  14430. 'Seconds' : 1e3,
  14431. 'Minutes' : 6e4,
  14432. 'Hours' : 36e5,
  14433. 'Days' : 864e5,
  14434. 'Months' : 2592e6,
  14435. 'Years' : 31536e6
  14436. },
  14437. unitAliases = {
  14438. ms : 'millisecond',
  14439. s : 'second',
  14440. m : 'minute',
  14441. h : 'hour',
  14442. d : 'day',
  14443. D : 'date',
  14444. w : 'week',
  14445. W : 'isoWeek',
  14446. M : 'month',
  14447. y : 'year',
  14448. DDD : 'dayOfYear',
  14449. e : 'weekday',
  14450. E : 'isoWeekday',
  14451. gg: 'weekYear',
  14452. GG: 'isoWeekYear'
  14453. },
  14454. camelFunctions = {
  14455. dayofyear : 'dayOfYear',
  14456. isoweekday : 'isoWeekday',
  14457. isoweek : 'isoWeek',
  14458. weekyear : 'weekYear',
  14459. isoweekyear : 'isoWeekYear'
  14460. },
  14461. // format function strings
  14462. formatFunctions = {},
  14463. // tokens to ordinalize and pad
  14464. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  14465. paddedTokens = 'M D H h m s w W'.split(' '),
  14466. formatTokenFunctions = {
  14467. M : function () {
  14468. return this.month() + 1;
  14469. },
  14470. MMM : function (format) {
  14471. return this.lang().monthsShort(this, format);
  14472. },
  14473. MMMM : function (format) {
  14474. return this.lang().months(this, format);
  14475. },
  14476. D : function () {
  14477. return this.date();
  14478. },
  14479. DDD : function () {
  14480. return this.dayOfYear();
  14481. },
  14482. d : function () {
  14483. return this.day();
  14484. },
  14485. dd : function (format) {
  14486. return this.lang().weekdaysMin(this, format);
  14487. },
  14488. ddd : function (format) {
  14489. return this.lang().weekdaysShort(this, format);
  14490. },
  14491. dddd : function (format) {
  14492. return this.lang().weekdays(this, format);
  14493. },
  14494. w : function () {
  14495. return this.week();
  14496. },
  14497. W : function () {
  14498. return this.isoWeek();
  14499. },
  14500. YY : function () {
  14501. return leftZeroFill(this.year() % 100, 2);
  14502. },
  14503. YYYY : function () {
  14504. return leftZeroFill(this.year(), 4);
  14505. },
  14506. YYYYY : function () {
  14507. return leftZeroFill(this.year(), 5);
  14508. },
  14509. YYYYYY : function () {
  14510. var y = this.year(), sign = y >= 0 ? '+' : '-';
  14511. return sign + leftZeroFill(Math.abs(y), 6);
  14512. },
  14513. gg : function () {
  14514. return leftZeroFill(this.weekYear() % 100, 2);
  14515. },
  14516. gggg : function () {
  14517. return leftZeroFill(this.weekYear(), 4);
  14518. },
  14519. ggggg : function () {
  14520. return leftZeroFill(this.weekYear(), 5);
  14521. },
  14522. GG : function () {
  14523. return leftZeroFill(this.isoWeekYear() % 100, 2);
  14524. },
  14525. GGGG : function () {
  14526. return leftZeroFill(this.isoWeekYear(), 4);
  14527. },
  14528. GGGGG : function () {
  14529. return leftZeroFill(this.isoWeekYear(), 5);
  14530. },
  14531. e : function () {
  14532. return this.weekday();
  14533. },
  14534. E : function () {
  14535. return this.isoWeekday();
  14536. },
  14537. a : function () {
  14538. return this.lang().meridiem(this.hours(), this.minutes(), true);
  14539. },
  14540. A : function () {
  14541. return this.lang().meridiem(this.hours(), this.minutes(), false);
  14542. },
  14543. H : function () {
  14544. return this.hours();
  14545. },
  14546. h : function () {
  14547. return this.hours() % 12 || 12;
  14548. },
  14549. m : function () {
  14550. return this.minutes();
  14551. },
  14552. s : function () {
  14553. return this.seconds();
  14554. },
  14555. S : function () {
  14556. return toInt(this.milliseconds() / 100);
  14557. },
  14558. SS : function () {
  14559. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  14560. },
  14561. SSS : function () {
  14562. return leftZeroFill(this.milliseconds(), 3);
  14563. },
  14564. SSSS : function () {
  14565. return leftZeroFill(this.milliseconds(), 3);
  14566. },
  14567. Z : function () {
  14568. var a = -this.zone(),
  14569. b = "+";
  14570. if (a < 0) {
  14571. a = -a;
  14572. b = "-";
  14573. }
  14574. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  14575. },
  14576. ZZ : function () {
  14577. var a = -this.zone(),
  14578. b = "+";
  14579. if (a < 0) {
  14580. a = -a;
  14581. b = "-";
  14582. }
  14583. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  14584. },
  14585. z : function () {
  14586. return this.zoneAbbr();
  14587. },
  14588. zz : function () {
  14589. return this.zoneName();
  14590. },
  14591. X : function () {
  14592. return this.unix();
  14593. },
  14594. Q : function () {
  14595. return this.quarter();
  14596. }
  14597. },
  14598. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  14599. function defaultParsingFlags() {
  14600. // We need to deep clone this object, and es5 standard is not very
  14601. // helpful.
  14602. return {
  14603. empty : false,
  14604. unusedTokens : [],
  14605. unusedInput : [],
  14606. overflow : -2,
  14607. charsLeftOver : 0,
  14608. nullInput : false,
  14609. invalidMonth : null,
  14610. invalidFormat : false,
  14611. userInvalidated : false,
  14612. iso: false
  14613. };
  14614. }
  14615. function padToken(func, count) {
  14616. return function (a) {
  14617. return leftZeroFill(func.call(this, a), count);
  14618. };
  14619. }
  14620. function ordinalizeToken(func, period) {
  14621. return function (a) {
  14622. return this.lang().ordinal(func.call(this, a), period);
  14623. };
  14624. }
  14625. while (ordinalizeTokens.length) {
  14626. i = ordinalizeTokens.pop();
  14627. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  14628. }
  14629. while (paddedTokens.length) {
  14630. i = paddedTokens.pop();
  14631. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  14632. }
  14633. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  14634. /************************************
  14635. Constructors
  14636. ************************************/
  14637. function Language() {
  14638. }
  14639. // Moment prototype object
  14640. function Moment(config) {
  14641. checkOverflow(config);
  14642. extend(this, config);
  14643. }
  14644. // Duration Constructor
  14645. function Duration(duration) {
  14646. var normalizedInput = normalizeObjectUnits(duration),
  14647. years = normalizedInput.year || 0,
  14648. months = normalizedInput.month || 0,
  14649. weeks = normalizedInput.week || 0,
  14650. days = normalizedInput.day || 0,
  14651. hours = normalizedInput.hour || 0,
  14652. minutes = normalizedInput.minute || 0,
  14653. seconds = normalizedInput.second || 0,
  14654. milliseconds = normalizedInput.millisecond || 0;
  14655. // representation for dateAddRemove
  14656. this._milliseconds = +milliseconds +
  14657. seconds * 1e3 + // 1000
  14658. minutes * 6e4 + // 1000 * 60
  14659. hours * 36e5; // 1000 * 60 * 60
  14660. // Because of dateAddRemove treats 24 hours as different from a
  14661. // day when working around DST, we need to store them separately
  14662. this._days = +days +
  14663. weeks * 7;
  14664. // It is impossible translate months into days without knowing
  14665. // which months you are are talking about, so we have to store
  14666. // it separately.
  14667. this._months = +months +
  14668. years * 12;
  14669. this._data = {};
  14670. this._bubble();
  14671. }
  14672. /************************************
  14673. Helpers
  14674. ************************************/
  14675. function extend(a, b) {
  14676. for (var i in b) {
  14677. if (b.hasOwnProperty(i)) {
  14678. a[i] = b[i];
  14679. }
  14680. }
  14681. if (b.hasOwnProperty("toString")) {
  14682. a.toString = b.toString;
  14683. }
  14684. if (b.hasOwnProperty("valueOf")) {
  14685. a.valueOf = b.valueOf;
  14686. }
  14687. return a;
  14688. }
  14689. function cloneMoment(m) {
  14690. var result = {}, i;
  14691. for (i in m) {
  14692. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  14693. result[i] = m[i];
  14694. }
  14695. }
  14696. return result;
  14697. }
  14698. function absRound(number) {
  14699. if (number < 0) {
  14700. return Math.ceil(number);
  14701. } else {
  14702. return Math.floor(number);
  14703. }
  14704. }
  14705. // left zero fill a number
  14706. // see http://jsperf.com/left-zero-filling for performance comparison
  14707. function leftZeroFill(number, targetLength, forceSign) {
  14708. var output = '' + Math.abs(number),
  14709. sign = number >= 0;
  14710. while (output.length < targetLength) {
  14711. output = '0' + output;
  14712. }
  14713. return (sign ? (forceSign ? '+' : '') : '-') + output;
  14714. }
  14715. // helper function for _.addTime and _.subtractTime
  14716. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  14717. var milliseconds = duration._milliseconds,
  14718. days = duration._days,
  14719. months = duration._months,
  14720. minutes,
  14721. hours;
  14722. if (milliseconds) {
  14723. mom._d.setTime(+mom._d + milliseconds * isAdding);
  14724. }
  14725. // store the minutes and hours so we can restore them
  14726. if (days || months) {
  14727. minutes = mom.minute();
  14728. hours = mom.hour();
  14729. }
  14730. if (days) {
  14731. mom.date(mom.date() + days * isAdding);
  14732. }
  14733. if (months) {
  14734. mom.month(mom.month() + months * isAdding);
  14735. }
  14736. if (milliseconds && !ignoreUpdateOffset) {
  14737. moment.updateOffset(mom);
  14738. }
  14739. // restore the minutes and hours after possibly changing dst
  14740. if (days || months) {
  14741. mom.minute(minutes);
  14742. mom.hour(hours);
  14743. }
  14744. }
  14745. // check if is an array
  14746. function isArray(input) {
  14747. return Object.prototype.toString.call(input) === '[object Array]';
  14748. }
  14749. function isDate(input) {
  14750. return Object.prototype.toString.call(input) === '[object Date]' ||
  14751. input instanceof Date;
  14752. }
  14753. // compare two arrays, return the number of differences
  14754. function compareArrays(array1, array2, dontConvert) {
  14755. var len = Math.min(array1.length, array2.length),
  14756. lengthDiff = Math.abs(array1.length - array2.length),
  14757. diffs = 0,
  14758. i;
  14759. for (i = 0; i < len; i++) {
  14760. if ((dontConvert && array1[i] !== array2[i]) ||
  14761. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  14762. diffs++;
  14763. }
  14764. }
  14765. return diffs + lengthDiff;
  14766. }
  14767. function normalizeUnits(units) {
  14768. if (units) {
  14769. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  14770. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  14771. }
  14772. return units;
  14773. }
  14774. function normalizeObjectUnits(inputObject) {
  14775. var normalizedInput = {},
  14776. normalizedProp,
  14777. prop;
  14778. for (prop in inputObject) {
  14779. if (inputObject.hasOwnProperty(prop)) {
  14780. normalizedProp = normalizeUnits(prop);
  14781. if (normalizedProp) {
  14782. normalizedInput[normalizedProp] = inputObject[prop];
  14783. }
  14784. }
  14785. }
  14786. return normalizedInput;
  14787. }
  14788. function makeList(field) {
  14789. var count, setter;
  14790. if (field.indexOf('week') === 0) {
  14791. count = 7;
  14792. setter = 'day';
  14793. }
  14794. else if (field.indexOf('month') === 0) {
  14795. count = 12;
  14796. setter = 'month';
  14797. }
  14798. else {
  14799. return;
  14800. }
  14801. moment[field] = function (format, index) {
  14802. var i, getter,
  14803. method = moment.fn._lang[field],
  14804. results = [];
  14805. if (typeof format === 'number') {
  14806. index = format;
  14807. format = undefined;
  14808. }
  14809. getter = function (i) {
  14810. var m = moment().utc().set(setter, i);
  14811. return method.call(moment.fn._lang, m, format || '');
  14812. };
  14813. if (index != null) {
  14814. return getter(index);
  14815. }
  14816. else {
  14817. for (i = 0; i < count; i++) {
  14818. results.push(getter(i));
  14819. }
  14820. return results;
  14821. }
  14822. };
  14823. }
  14824. function toInt(argumentForCoercion) {
  14825. var coercedNumber = +argumentForCoercion,
  14826. value = 0;
  14827. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  14828. if (coercedNumber >= 0) {
  14829. value = Math.floor(coercedNumber);
  14830. } else {
  14831. value = Math.ceil(coercedNumber);
  14832. }
  14833. }
  14834. return value;
  14835. }
  14836. function daysInMonth(year, month) {
  14837. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  14838. }
  14839. function daysInYear(year) {
  14840. return isLeapYear(year) ? 366 : 365;
  14841. }
  14842. function isLeapYear(year) {
  14843. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  14844. }
  14845. function checkOverflow(m) {
  14846. var overflow;
  14847. if (m._a && m._pf.overflow === -2) {
  14848. overflow =
  14849. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  14850. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  14851. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  14852. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  14853. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  14854. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  14855. -1;
  14856. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  14857. overflow = DATE;
  14858. }
  14859. m._pf.overflow = overflow;
  14860. }
  14861. }
  14862. function isValid(m) {
  14863. if (m._isValid == null) {
  14864. m._isValid = !isNaN(m._d.getTime()) &&
  14865. m._pf.overflow < 0 &&
  14866. !m._pf.empty &&
  14867. !m._pf.invalidMonth &&
  14868. !m._pf.nullInput &&
  14869. !m._pf.invalidFormat &&
  14870. !m._pf.userInvalidated;
  14871. if (m._strict) {
  14872. m._isValid = m._isValid &&
  14873. m._pf.charsLeftOver === 0 &&
  14874. m._pf.unusedTokens.length === 0;
  14875. }
  14876. }
  14877. return m._isValid;
  14878. }
  14879. function normalizeLanguage(key) {
  14880. return key ? key.toLowerCase().replace('_', '-') : key;
  14881. }
  14882. // Return a moment from input, that is local/utc/zone equivalent to model.
  14883. function makeAs(input, model) {
  14884. return model._isUTC ? moment(input).zone(model._offset || 0) :
  14885. moment(input).local();
  14886. }
  14887. /************************************
  14888. Languages
  14889. ************************************/
  14890. extend(Language.prototype, {
  14891. set : function (config) {
  14892. var prop, i;
  14893. for (i in config) {
  14894. prop = config[i];
  14895. if (typeof prop === 'function') {
  14896. this[i] = prop;
  14897. } else {
  14898. this['_' + i] = prop;
  14899. }
  14900. }
  14901. },
  14902. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  14903. months : function (m) {
  14904. return this._months[m.month()];
  14905. },
  14906. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  14907. monthsShort : function (m) {
  14908. return this._monthsShort[m.month()];
  14909. },
  14910. monthsParse : function (monthName) {
  14911. var i, mom, regex;
  14912. if (!this._monthsParse) {
  14913. this._monthsParse = [];
  14914. }
  14915. for (i = 0; i < 12; i++) {
  14916. // make the regex if we don't have it already
  14917. if (!this._monthsParse[i]) {
  14918. mom = moment.utc([2000, i]);
  14919. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  14920. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  14921. }
  14922. // test the regex
  14923. if (this._monthsParse[i].test(monthName)) {
  14924. return i;
  14925. }
  14926. }
  14927. },
  14928. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  14929. weekdays : function (m) {
  14930. return this._weekdays[m.day()];
  14931. },
  14932. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  14933. weekdaysShort : function (m) {
  14934. return this._weekdaysShort[m.day()];
  14935. },
  14936. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  14937. weekdaysMin : function (m) {
  14938. return this._weekdaysMin[m.day()];
  14939. },
  14940. weekdaysParse : function (weekdayName) {
  14941. var i, mom, regex;
  14942. if (!this._weekdaysParse) {
  14943. this._weekdaysParse = [];
  14944. }
  14945. for (i = 0; i < 7; i++) {
  14946. // make the regex if we don't have it already
  14947. if (!this._weekdaysParse[i]) {
  14948. mom = moment([2000, 1]).day(i);
  14949. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  14950. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  14951. }
  14952. // test the regex
  14953. if (this._weekdaysParse[i].test(weekdayName)) {
  14954. return i;
  14955. }
  14956. }
  14957. },
  14958. _longDateFormat : {
  14959. LT : "h:mm A",
  14960. L : "MM/DD/YYYY",
  14961. LL : "MMMM D YYYY",
  14962. LLL : "MMMM D YYYY LT",
  14963. LLLL : "dddd, MMMM D YYYY LT"
  14964. },
  14965. longDateFormat : function (key) {
  14966. var output = this._longDateFormat[key];
  14967. if (!output && this._longDateFormat[key.toUpperCase()]) {
  14968. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  14969. return val.slice(1);
  14970. });
  14971. this._longDateFormat[key] = output;
  14972. }
  14973. return output;
  14974. },
  14975. isPM : function (input) {
  14976. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  14977. // Using charAt should be more compatible.
  14978. return ((input + '').toLowerCase().charAt(0) === 'p');
  14979. },
  14980. _meridiemParse : /[ap]\.?m?\.?/i,
  14981. meridiem : function (hours, minutes, isLower) {
  14982. if (hours > 11) {
  14983. return isLower ? 'pm' : 'PM';
  14984. } else {
  14985. return isLower ? 'am' : 'AM';
  14986. }
  14987. },
  14988. _calendar : {
  14989. sameDay : '[Today at] LT',
  14990. nextDay : '[Tomorrow at] LT',
  14991. nextWeek : 'dddd [at] LT',
  14992. lastDay : '[Yesterday at] LT',
  14993. lastWeek : '[Last] dddd [at] LT',
  14994. sameElse : 'L'
  14995. },
  14996. calendar : function (key, mom) {
  14997. var output = this._calendar[key];
  14998. return typeof output === 'function' ? output.apply(mom) : output;
  14999. },
  15000. _relativeTime : {
  15001. future : "in %s",
  15002. past : "%s ago",
  15003. s : "a few seconds",
  15004. m : "a minute",
  15005. mm : "%d minutes",
  15006. h : "an hour",
  15007. hh : "%d hours",
  15008. d : "a day",
  15009. dd : "%d days",
  15010. M : "a month",
  15011. MM : "%d months",
  15012. y : "a year",
  15013. yy : "%d years"
  15014. },
  15015. relativeTime : function (number, withoutSuffix, string, isFuture) {
  15016. var output = this._relativeTime[string];
  15017. return (typeof output === 'function') ?
  15018. output(number, withoutSuffix, string, isFuture) :
  15019. output.replace(/%d/i, number);
  15020. },
  15021. pastFuture : function (diff, output) {
  15022. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  15023. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  15024. },
  15025. ordinal : function (number) {
  15026. return this._ordinal.replace("%d", number);
  15027. },
  15028. _ordinal : "%d",
  15029. preparse : function (string) {
  15030. return string;
  15031. },
  15032. postformat : function (string) {
  15033. return string;
  15034. },
  15035. week : function (mom) {
  15036. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  15037. },
  15038. _week : {
  15039. dow : 0, // Sunday is the first day of the week.
  15040. doy : 6 // The week that contains Jan 1st is the first week of the year.
  15041. },
  15042. _invalidDate: 'Invalid date',
  15043. invalidDate: function () {
  15044. return this._invalidDate;
  15045. }
  15046. });
  15047. // Loads a language definition into the `languages` cache. The function
  15048. // takes a key and optionally values. If not in the browser and no values
  15049. // are provided, it will load the language file module. As a convenience,
  15050. // this function also returns the language values.
  15051. function loadLang(key, values) {
  15052. values.abbr = key;
  15053. if (!languages[key]) {
  15054. languages[key] = new Language();
  15055. }
  15056. languages[key].set(values);
  15057. return languages[key];
  15058. }
  15059. // Remove a language from the `languages` cache. Mostly useful in tests.
  15060. function unloadLang(key) {
  15061. delete languages[key];
  15062. }
  15063. // Determines which language definition to use and returns it.
  15064. //
  15065. // With no parameters, it will return the global language. If you
  15066. // pass in a language key, such as 'en', it will return the
  15067. // definition for 'en', so long as 'en' has already been loaded using
  15068. // moment.lang.
  15069. function getLangDefinition(key) {
  15070. var i = 0, j, lang, next, split,
  15071. get = function (k) {
  15072. if (!languages[k] && hasModule) {
  15073. try {
  15074. require('./lang/' + k);
  15075. } catch (e) { }
  15076. }
  15077. return languages[k];
  15078. };
  15079. if (!key) {
  15080. return moment.fn._lang;
  15081. }
  15082. if (!isArray(key)) {
  15083. //short-circuit everything else
  15084. lang = get(key);
  15085. if (lang) {
  15086. return lang;
  15087. }
  15088. key = [key];
  15089. }
  15090. //pick the language from the array
  15091. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  15092. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  15093. while (i < key.length) {
  15094. split = normalizeLanguage(key[i]).split('-');
  15095. j = split.length;
  15096. next = normalizeLanguage(key[i + 1]);
  15097. next = next ? next.split('-') : null;
  15098. while (j > 0) {
  15099. lang = get(split.slice(0, j).join('-'));
  15100. if (lang) {
  15101. return lang;
  15102. }
  15103. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  15104. //the next array item is better than a shallower substring of this one
  15105. break;
  15106. }
  15107. j--;
  15108. }
  15109. i++;
  15110. }
  15111. return moment.fn._lang;
  15112. }
  15113. /************************************
  15114. Formatting
  15115. ************************************/
  15116. function removeFormattingTokens(input) {
  15117. if (input.match(/\[[\s\S]/)) {
  15118. return input.replace(/^\[|\]$/g, "");
  15119. }
  15120. return input.replace(/\\/g, "");
  15121. }
  15122. function makeFormatFunction(format) {
  15123. var array = format.match(formattingTokens), i, length;
  15124. for (i = 0, length = array.length; i < length; i++) {
  15125. if (formatTokenFunctions[array[i]]) {
  15126. array[i] = formatTokenFunctions[array[i]];
  15127. } else {
  15128. array[i] = removeFormattingTokens(array[i]);
  15129. }
  15130. }
  15131. return function (mom) {
  15132. var output = "";
  15133. for (i = 0; i < length; i++) {
  15134. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  15135. }
  15136. return output;
  15137. };
  15138. }
  15139. // format date using native date object
  15140. function formatMoment(m, format) {
  15141. if (!m.isValid()) {
  15142. return m.lang().invalidDate();
  15143. }
  15144. format = expandFormat(format, m.lang());
  15145. if (!formatFunctions[format]) {
  15146. formatFunctions[format] = makeFormatFunction(format);
  15147. }
  15148. return formatFunctions[format](m);
  15149. }
  15150. function expandFormat(format, lang) {
  15151. var i = 5;
  15152. function replaceLongDateFormatTokens(input) {
  15153. return lang.longDateFormat(input) || input;
  15154. }
  15155. localFormattingTokens.lastIndex = 0;
  15156. while (i >= 0 && localFormattingTokens.test(format)) {
  15157. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  15158. localFormattingTokens.lastIndex = 0;
  15159. i -= 1;
  15160. }
  15161. return format;
  15162. }
  15163. /************************************
  15164. Parsing
  15165. ************************************/
  15166. // get the regex to find the next token
  15167. function getParseRegexForToken(token, config) {
  15168. var a, strict = config._strict;
  15169. switch (token) {
  15170. case 'DDDD':
  15171. return parseTokenThreeDigits;
  15172. case 'YYYY':
  15173. case 'GGGG':
  15174. case 'gggg':
  15175. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  15176. case 'Y':
  15177. case 'G':
  15178. case 'g':
  15179. return parseTokenSignedNumber;
  15180. case 'YYYYYY':
  15181. case 'YYYYY':
  15182. case 'GGGGG':
  15183. case 'ggggg':
  15184. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  15185. case 'S':
  15186. if (strict) { return parseTokenOneDigit; }
  15187. /* falls through */
  15188. case 'SS':
  15189. if (strict) { return parseTokenTwoDigits; }
  15190. /* falls through */
  15191. case 'SSS':
  15192. if (strict) { return parseTokenThreeDigits; }
  15193. /* falls through */
  15194. case 'DDD':
  15195. return parseTokenOneToThreeDigits;
  15196. case 'MMM':
  15197. case 'MMMM':
  15198. case 'dd':
  15199. case 'ddd':
  15200. case 'dddd':
  15201. return parseTokenWord;
  15202. case 'a':
  15203. case 'A':
  15204. return getLangDefinition(config._l)._meridiemParse;
  15205. case 'X':
  15206. return parseTokenTimestampMs;
  15207. case 'Z':
  15208. case 'ZZ':
  15209. return parseTokenTimezone;
  15210. case 'T':
  15211. return parseTokenT;
  15212. case 'SSSS':
  15213. return parseTokenDigits;
  15214. case 'MM':
  15215. case 'DD':
  15216. case 'YY':
  15217. case 'GG':
  15218. case 'gg':
  15219. case 'HH':
  15220. case 'hh':
  15221. case 'mm':
  15222. case 'ss':
  15223. case 'ww':
  15224. case 'WW':
  15225. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  15226. case 'M':
  15227. case 'D':
  15228. case 'd':
  15229. case 'H':
  15230. case 'h':
  15231. case 'm':
  15232. case 's':
  15233. case 'w':
  15234. case 'W':
  15235. case 'e':
  15236. case 'E':
  15237. return parseTokenOneOrTwoDigits;
  15238. default :
  15239. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  15240. return a;
  15241. }
  15242. }
  15243. function timezoneMinutesFromString(string) {
  15244. string = string || "";
  15245. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  15246. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  15247. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  15248. minutes = +(parts[1] * 60) + toInt(parts[2]);
  15249. return parts[0] === '+' ? -minutes : minutes;
  15250. }
  15251. // function to convert string input to date
  15252. function addTimeToArrayFromToken(token, input, config) {
  15253. var a, datePartArray = config._a;
  15254. switch (token) {
  15255. // MONTH
  15256. case 'M' : // fall through to MM
  15257. case 'MM' :
  15258. if (input != null) {
  15259. datePartArray[MONTH] = toInt(input) - 1;
  15260. }
  15261. break;
  15262. case 'MMM' : // fall through to MMMM
  15263. case 'MMMM' :
  15264. a = getLangDefinition(config._l).monthsParse(input);
  15265. // if we didn't find a month name, mark the date as invalid.
  15266. if (a != null) {
  15267. datePartArray[MONTH] = a;
  15268. } else {
  15269. config._pf.invalidMonth = input;
  15270. }
  15271. break;
  15272. // DAY OF MONTH
  15273. case 'D' : // fall through to DD
  15274. case 'DD' :
  15275. if (input != null) {
  15276. datePartArray[DATE] = toInt(input);
  15277. }
  15278. break;
  15279. // DAY OF YEAR
  15280. case 'DDD' : // fall through to DDDD
  15281. case 'DDDD' :
  15282. if (input != null) {
  15283. config._dayOfYear = toInt(input);
  15284. }
  15285. break;
  15286. // YEAR
  15287. case 'YY' :
  15288. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  15289. break;
  15290. case 'YYYY' :
  15291. case 'YYYYY' :
  15292. case 'YYYYYY' :
  15293. datePartArray[YEAR] = toInt(input);
  15294. break;
  15295. // AM / PM
  15296. case 'a' : // fall through to A
  15297. case 'A' :
  15298. config._isPm = getLangDefinition(config._l).isPM(input);
  15299. break;
  15300. // 24 HOUR
  15301. case 'H' : // fall through to hh
  15302. case 'HH' : // fall through to hh
  15303. case 'h' : // fall through to hh
  15304. case 'hh' :
  15305. datePartArray[HOUR] = toInt(input);
  15306. break;
  15307. // MINUTE
  15308. case 'm' : // fall through to mm
  15309. case 'mm' :
  15310. datePartArray[MINUTE] = toInt(input);
  15311. break;
  15312. // SECOND
  15313. case 's' : // fall through to ss
  15314. case 'ss' :
  15315. datePartArray[SECOND] = toInt(input);
  15316. break;
  15317. // MILLISECOND
  15318. case 'S' :
  15319. case 'SS' :
  15320. case 'SSS' :
  15321. case 'SSSS' :
  15322. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  15323. break;
  15324. // UNIX TIMESTAMP WITH MS
  15325. case 'X':
  15326. config._d = new Date(parseFloat(input) * 1000);
  15327. break;
  15328. // TIMEZONE
  15329. case 'Z' : // fall through to ZZ
  15330. case 'ZZ' :
  15331. config._useUTC = true;
  15332. config._tzm = timezoneMinutesFromString(input);
  15333. break;
  15334. case 'w':
  15335. case 'ww':
  15336. case 'W':
  15337. case 'WW':
  15338. case 'd':
  15339. case 'dd':
  15340. case 'ddd':
  15341. case 'dddd':
  15342. case 'e':
  15343. case 'E':
  15344. token = token.substr(0, 1);
  15345. /* falls through */
  15346. case 'gg':
  15347. case 'gggg':
  15348. case 'GG':
  15349. case 'GGGG':
  15350. case 'GGGGG':
  15351. token = token.substr(0, 2);
  15352. if (input) {
  15353. config._w = config._w || {};
  15354. config._w[token] = input;
  15355. }
  15356. break;
  15357. }
  15358. }
  15359. // convert an array to a date.
  15360. // the array should mirror the parameters below
  15361. // note: all values past the year are optional and will default to the lowest possible value.
  15362. // [year, month, day , hour, minute, second, millisecond]
  15363. function dateFromConfig(config) {
  15364. var i, date, input = [], currentDate,
  15365. yearToUse, fixYear, w, temp, lang, weekday, week;
  15366. if (config._d) {
  15367. return;
  15368. }
  15369. currentDate = currentDateArray(config);
  15370. //compute day of the year from weeks and weekdays
  15371. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  15372. fixYear = function (val) {
  15373. var int_val = parseInt(val, 10);
  15374. return val ?
  15375. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  15376. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  15377. };
  15378. w = config._w;
  15379. if (w.GG != null || w.W != null || w.E != null) {
  15380. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  15381. }
  15382. else {
  15383. lang = getLangDefinition(config._l);
  15384. weekday = w.d != null ? parseWeekday(w.d, lang) :
  15385. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  15386. week = parseInt(w.w, 10) || 1;
  15387. //if we're parsing 'd', then the low day numbers may be next week
  15388. if (w.d != null && weekday < lang._week.dow) {
  15389. week++;
  15390. }
  15391. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  15392. }
  15393. config._a[YEAR] = temp.year;
  15394. config._dayOfYear = temp.dayOfYear;
  15395. }
  15396. //if the day of the year is set, figure out what it is
  15397. if (config._dayOfYear) {
  15398. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  15399. if (config._dayOfYear > daysInYear(yearToUse)) {
  15400. config._pf._overflowDayOfYear = true;
  15401. }
  15402. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  15403. config._a[MONTH] = date.getUTCMonth();
  15404. config._a[DATE] = date.getUTCDate();
  15405. }
  15406. // Default to current date.
  15407. // * if no year, month, day of month are given, default to today
  15408. // * if day of month is given, default month and year
  15409. // * if month is given, default only year
  15410. // * if year is given, don't default anything
  15411. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  15412. config._a[i] = input[i] = currentDate[i];
  15413. }
  15414. // Zero out whatever was not defaulted, including time
  15415. for (; i < 7; i++) {
  15416. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  15417. }
  15418. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  15419. input[HOUR] += toInt((config._tzm || 0) / 60);
  15420. input[MINUTE] += toInt((config._tzm || 0) % 60);
  15421. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  15422. }
  15423. function dateFromObject(config) {
  15424. var normalizedInput;
  15425. if (config._d) {
  15426. return;
  15427. }
  15428. normalizedInput = normalizeObjectUnits(config._i);
  15429. config._a = [
  15430. normalizedInput.year,
  15431. normalizedInput.month,
  15432. normalizedInput.day,
  15433. normalizedInput.hour,
  15434. normalizedInput.minute,
  15435. normalizedInput.second,
  15436. normalizedInput.millisecond
  15437. ];
  15438. dateFromConfig(config);
  15439. }
  15440. function currentDateArray(config) {
  15441. var now = new Date();
  15442. if (config._useUTC) {
  15443. return [
  15444. now.getUTCFullYear(),
  15445. now.getUTCMonth(),
  15446. now.getUTCDate()
  15447. ];
  15448. } else {
  15449. return [now.getFullYear(), now.getMonth(), now.getDate()];
  15450. }
  15451. }
  15452. // date from string and format string
  15453. function makeDateFromStringAndFormat(config) {
  15454. config._a = [];
  15455. config._pf.empty = true;
  15456. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  15457. var lang = getLangDefinition(config._l),
  15458. string = '' + config._i,
  15459. i, parsedInput, tokens, token, skipped,
  15460. stringLength = string.length,
  15461. totalParsedInputLength = 0;
  15462. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  15463. for (i = 0; i < tokens.length; i++) {
  15464. token = tokens[i];
  15465. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  15466. if (parsedInput) {
  15467. skipped = string.substr(0, string.indexOf(parsedInput));
  15468. if (skipped.length > 0) {
  15469. config._pf.unusedInput.push(skipped);
  15470. }
  15471. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  15472. totalParsedInputLength += parsedInput.length;
  15473. }
  15474. // don't parse if it's not a known token
  15475. if (formatTokenFunctions[token]) {
  15476. if (parsedInput) {
  15477. config._pf.empty = false;
  15478. }
  15479. else {
  15480. config._pf.unusedTokens.push(token);
  15481. }
  15482. addTimeToArrayFromToken(token, parsedInput, config);
  15483. }
  15484. else if (config._strict && !parsedInput) {
  15485. config._pf.unusedTokens.push(token);
  15486. }
  15487. }
  15488. // add remaining unparsed input length to the string
  15489. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  15490. if (string.length > 0) {
  15491. config._pf.unusedInput.push(string);
  15492. }
  15493. // handle am pm
  15494. if (config._isPm && config._a[HOUR] < 12) {
  15495. config._a[HOUR] += 12;
  15496. }
  15497. // if is 12 am, change hours to 0
  15498. if (config._isPm === false && config._a[HOUR] === 12) {
  15499. config._a[HOUR] = 0;
  15500. }
  15501. dateFromConfig(config);
  15502. checkOverflow(config);
  15503. }
  15504. function unescapeFormat(s) {
  15505. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  15506. return p1 || p2 || p3 || p4;
  15507. });
  15508. }
  15509. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  15510. function regexpEscape(s) {
  15511. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  15512. }
  15513. // date from string and array of format strings
  15514. function makeDateFromStringAndArray(config) {
  15515. var tempConfig,
  15516. bestMoment,
  15517. scoreToBeat,
  15518. i,
  15519. currentScore;
  15520. if (config._f.length === 0) {
  15521. config._pf.invalidFormat = true;
  15522. config._d = new Date(NaN);
  15523. return;
  15524. }
  15525. for (i = 0; i < config._f.length; i++) {
  15526. currentScore = 0;
  15527. tempConfig = extend({}, config);
  15528. tempConfig._pf = defaultParsingFlags();
  15529. tempConfig._f = config._f[i];
  15530. makeDateFromStringAndFormat(tempConfig);
  15531. if (!isValid(tempConfig)) {
  15532. continue;
  15533. }
  15534. // if there is any input that was not parsed add a penalty for that format
  15535. currentScore += tempConfig._pf.charsLeftOver;
  15536. //or tokens
  15537. currentScore += tempConfig._pf.unusedTokens.length * 10;
  15538. tempConfig._pf.score = currentScore;
  15539. if (scoreToBeat == null || currentScore < scoreToBeat) {
  15540. scoreToBeat = currentScore;
  15541. bestMoment = tempConfig;
  15542. }
  15543. }
  15544. extend(config, bestMoment || tempConfig);
  15545. }
  15546. // date from iso format
  15547. function makeDateFromString(config) {
  15548. var i, l,
  15549. string = config._i,
  15550. match = isoRegex.exec(string);
  15551. if (match) {
  15552. config._pf.iso = true;
  15553. for (i = 0, l = isoDates.length; i < l; i++) {
  15554. if (isoDates[i][1].exec(string)) {
  15555. // match[5] should be "T" or undefined
  15556. config._f = isoDates[i][0] + (match[6] || " ");
  15557. break;
  15558. }
  15559. }
  15560. for (i = 0, l = isoTimes.length; i < l; i++) {
  15561. if (isoTimes[i][1].exec(string)) {
  15562. config._f += isoTimes[i][0];
  15563. break;
  15564. }
  15565. }
  15566. if (string.match(parseTokenTimezone)) {
  15567. config._f += "Z";
  15568. }
  15569. makeDateFromStringAndFormat(config);
  15570. }
  15571. else {
  15572. config._d = new Date(string);
  15573. }
  15574. }
  15575. function makeDateFromInput(config) {
  15576. var input = config._i,
  15577. matched = aspNetJsonRegex.exec(input);
  15578. if (input === undefined) {
  15579. config._d = new Date();
  15580. } else if (matched) {
  15581. config._d = new Date(+matched[1]);
  15582. } else if (typeof input === 'string') {
  15583. makeDateFromString(config);
  15584. } else if (isArray(input)) {
  15585. config._a = input.slice(0);
  15586. dateFromConfig(config);
  15587. } else if (isDate(input)) {
  15588. config._d = new Date(+input);
  15589. } else if (typeof(input) === 'object') {
  15590. dateFromObject(config);
  15591. } else {
  15592. config._d = new Date(input);
  15593. }
  15594. }
  15595. function makeDate(y, m, d, h, M, s, ms) {
  15596. //can't just apply() to create a date:
  15597. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  15598. var date = new Date(y, m, d, h, M, s, ms);
  15599. //the date constructor doesn't accept years < 1970
  15600. if (y < 1970) {
  15601. date.setFullYear(y);
  15602. }
  15603. return date;
  15604. }
  15605. function makeUTCDate(y) {
  15606. var date = new Date(Date.UTC.apply(null, arguments));
  15607. if (y < 1970) {
  15608. date.setUTCFullYear(y);
  15609. }
  15610. return date;
  15611. }
  15612. function parseWeekday(input, language) {
  15613. if (typeof input === 'string') {
  15614. if (!isNaN(input)) {
  15615. input = parseInt(input, 10);
  15616. }
  15617. else {
  15618. input = language.weekdaysParse(input);
  15619. if (typeof input !== 'number') {
  15620. return null;
  15621. }
  15622. }
  15623. }
  15624. return input;
  15625. }
  15626. /************************************
  15627. Relative Time
  15628. ************************************/
  15629. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  15630. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  15631. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  15632. }
  15633. function relativeTime(milliseconds, withoutSuffix, lang) {
  15634. var seconds = round(Math.abs(milliseconds) / 1000),
  15635. minutes = round(seconds / 60),
  15636. hours = round(minutes / 60),
  15637. days = round(hours / 24),
  15638. years = round(days / 365),
  15639. args = seconds < 45 && ['s', seconds] ||
  15640. minutes === 1 && ['m'] ||
  15641. minutes < 45 && ['mm', minutes] ||
  15642. hours === 1 && ['h'] ||
  15643. hours < 22 && ['hh', hours] ||
  15644. days === 1 && ['d'] ||
  15645. days <= 25 && ['dd', days] ||
  15646. days <= 45 && ['M'] ||
  15647. days < 345 && ['MM', round(days / 30)] ||
  15648. years === 1 && ['y'] || ['yy', years];
  15649. args[2] = withoutSuffix;
  15650. args[3] = milliseconds > 0;
  15651. args[4] = lang;
  15652. return substituteTimeAgo.apply({}, args);
  15653. }
  15654. /************************************
  15655. Week of Year
  15656. ************************************/
  15657. // firstDayOfWeek 0 = sun, 6 = sat
  15658. // the day of the week that starts the week
  15659. // (usually sunday or monday)
  15660. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  15661. // the first week is the week that contains the first
  15662. // of this day of the week
  15663. // (eg. ISO weeks use thursday (4))
  15664. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  15665. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  15666. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  15667. adjustedMoment;
  15668. if (daysToDayOfWeek > end) {
  15669. daysToDayOfWeek -= 7;
  15670. }
  15671. if (daysToDayOfWeek < end - 7) {
  15672. daysToDayOfWeek += 7;
  15673. }
  15674. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  15675. return {
  15676. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  15677. year: adjustedMoment.year()
  15678. };
  15679. }
  15680. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  15681. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  15682. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  15683. weekday = weekday != null ? weekday : firstDayOfWeek;
  15684. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  15685. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  15686. return {
  15687. year: dayOfYear > 0 ? year : year - 1,
  15688. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  15689. };
  15690. }
  15691. /************************************
  15692. Top Level Functions
  15693. ************************************/
  15694. function makeMoment(config) {
  15695. var input = config._i,
  15696. format = config._f;
  15697. if (input === null) {
  15698. return moment.invalid({nullInput: true});
  15699. }
  15700. if (typeof input === 'string') {
  15701. config._i = input = getLangDefinition().preparse(input);
  15702. }
  15703. if (moment.isMoment(input)) {
  15704. config = cloneMoment(input);
  15705. config._d = new Date(+input._d);
  15706. } else if (format) {
  15707. if (isArray(format)) {
  15708. makeDateFromStringAndArray(config);
  15709. } else {
  15710. makeDateFromStringAndFormat(config);
  15711. }
  15712. } else {
  15713. makeDateFromInput(config);
  15714. }
  15715. return new Moment(config);
  15716. }
  15717. moment = function (input, format, lang, strict) {
  15718. var c;
  15719. if (typeof(lang) === "boolean") {
  15720. strict = lang;
  15721. lang = undefined;
  15722. }
  15723. // object construction must be done this way.
  15724. // https://github.com/moment/moment/issues/1423
  15725. c = {};
  15726. c._isAMomentObject = true;
  15727. c._i = input;
  15728. c._f = format;
  15729. c._l = lang;
  15730. c._strict = strict;
  15731. c._isUTC = false;
  15732. c._pf = defaultParsingFlags();
  15733. return makeMoment(c);
  15734. };
  15735. // creating with utc
  15736. moment.utc = function (input, format, lang, strict) {
  15737. var c;
  15738. if (typeof(lang) === "boolean") {
  15739. strict = lang;
  15740. lang = undefined;
  15741. }
  15742. // object construction must be done this way.
  15743. // https://github.com/moment/moment/issues/1423
  15744. c = {};
  15745. c._isAMomentObject = true;
  15746. c._useUTC = true;
  15747. c._isUTC = true;
  15748. c._l = lang;
  15749. c._i = input;
  15750. c._f = format;
  15751. c._strict = strict;
  15752. c._pf = defaultParsingFlags();
  15753. return makeMoment(c).utc();
  15754. };
  15755. // creating with unix timestamp (in seconds)
  15756. moment.unix = function (input) {
  15757. return moment(input * 1000);
  15758. };
  15759. // duration
  15760. moment.duration = function (input, key) {
  15761. var duration = input,
  15762. // matching against regexp is expensive, do it on demand
  15763. match = null,
  15764. sign,
  15765. ret,
  15766. parseIso;
  15767. if (moment.isDuration(input)) {
  15768. duration = {
  15769. ms: input._milliseconds,
  15770. d: input._days,
  15771. M: input._months
  15772. };
  15773. } else if (typeof input === 'number') {
  15774. duration = {};
  15775. if (key) {
  15776. duration[key] = input;
  15777. } else {
  15778. duration.milliseconds = input;
  15779. }
  15780. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  15781. sign = (match[1] === "-") ? -1 : 1;
  15782. duration = {
  15783. y: 0,
  15784. d: toInt(match[DATE]) * sign,
  15785. h: toInt(match[HOUR]) * sign,
  15786. m: toInt(match[MINUTE]) * sign,
  15787. s: toInt(match[SECOND]) * sign,
  15788. ms: toInt(match[MILLISECOND]) * sign
  15789. };
  15790. } else if (!!(match = isoDurationRegex.exec(input))) {
  15791. sign = (match[1] === "-") ? -1 : 1;
  15792. parseIso = function (inp) {
  15793. // We'd normally use ~~inp for this, but unfortunately it also
  15794. // converts floats to ints.
  15795. // inp may be undefined, so careful calling replace on it.
  15796. var res = inp && parseFloat(inp.replace(',', '.'));
  15797. // apply sign while we're at it
  15798. return (isNaN(res) ? 0 : res) * sign;
  15799. };
  15800. duration = {
  15801. y: parseIso(match[2]),
  15802. M: parseIso(match[3]),
  15803. d: parseIso(match[4]),
  15804. h: parseIso(match[5]),
  15805. m: parseIso(match[6]),
  15806. s: parseIso(match[7]),
  15807. w: parseIso(match[8])
  15808. };
  15809. }
  15810. ret = new Duration(duration);
  15811. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  15812. ret._lang = input._lang;
  15813. }
  15814. return ret;
  15815. };
  15816. // version number
  15817. moment.version = VERSION;
  15818. // default format
  15819. moment.defaultFormat = isoFormat;
  15820. // This function will be called whenever a moment is mutated.
  15821. // It is intended to keep the offset in sync with the timezone.
  15822. moment.updateOffset = function () {};
  15823. // This function will load languages and then set the global language. If
  15824. // no arguments are passed in, it will simply return the current global
  15825. // language key.
  15826. moment.lang = function (key, values) {
  15827. var r;
  15828. if (!key) {
  15829. return moment.fn._lang._abbr;
  15830. }
  15831. if (values) {
  15832. loadLang(normalizeLanguage(key), values);
  15833. } else if (values === null) {
  15834. unloadLang(key);
  15835. key = 'en';
  15836. } else if (!languages[key]) {
  15837. getLangDefinition(key);
  15838. }
  15839. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  15840. return r._abbr;
  15841. };
  15842. // returns language data
  15843. moment.langData = function (key) {
  15844. if (key && key._lang && key._lang._abbr) {
  15845. key = key._lang._abbr;
  15846. }
  15847. return getLangDefinition(key);
  15848. };
  15849. // compare moment object
  15850. moment.isMoment = function (obj) {
  15851. return obj instanceof Moment ||
  15852. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  15853. };
  15854. // for typechecking Duration objects
  15855. moment.isDuration = function (obj) {
  15856. return obj instanceof Duration;
  15857. };
  15858. for (i = lists.length - 1; i >= 0; --i) {
  15859. makeList(lists[i]);
  15860. }
  15861. moment.normalizeUnits = function (units) {
  15862. return normalizeUnits(units);
  15863. };
  15864. moment.invalid = function (flags) {
  15865. var m = moment.utc(NaN);
  15866. if (flags != null) {
  15867. extend(m._pf, flags);
  15868. }
  15869. else {
  15870. m._pf.userInvalidated = true;
  15871. }
  15872. return m;
  15873. };
  15874. moment.parseZone = function (input) {
  15875. return moment(input).parseZone();
  15876. };
  15877. /************************************
  15878. Moment Prototype
  15879. ************************************/
  15880. extend(moment.fn = Moment.prototype, {
  15881. clone : function () {
  15882. return moment(this);
  15883. },
  15884. valueOf : function () {
  15885. return +this._d + ((this._offset || 0) * 60000);
  15886. },
  15887. unix : function () {
  15888. return Math.floor(+this / 1000);
  15889. },
  15890. toString : function () {
  15891. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  15892. },
  15893. toDate : function () {
  15894. return this._offset ? new Date(+this) : this._d;
  15895. },
  15896. toISOString : function () {
  15897. var m = moment(this).utc();
  15898. if (0 < m.year() && m.year() <= 9999) {
  15899. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  15900. } else {
  15901. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  15902. }
  15903. },
  15904. toArray : function () {
  15905. var m = this;
  15906. return [
  15907. m.year(),
  15908. m.month(),
  15909. m.date(),
  15910. m.hours(),
  15911. m.minutes(),
  15912. m.seconds(),
  15913. m.milliseconds()
  15914. ];
  15915. },
  15916. isValid : function () {
  15917. return isValid(this);
  15918. },
  15919. isDSTShifted : function () {
  15920. if (this._a) {
  15921. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  15922. }
  15923. return false;
  15924. },
  15925. parsingFlags : function () {
  15926. return extend({}, this._pf);
  15927. },
  15928. invalidAt: function () {
  15929. return this._pf.overflow;
  15930. },
  15931. utc : function () {
  15932. return this.zone(0);
  15933. },
  15934. local : function () {
  15935. this.zone(0);
  15936. this._isUTC = false;
  15937. return this;
  15938. },
  15939. format : function (inputString) {
  15940. var output = formatMoment(this, inputString || moment.defaultFormat);
  15941. return this.lang().postformat(output);
  15942. },
  15943. add : function (input, val) {
  15944. var dur;
  15945. // switch args to support add('s', 1) and add(1, 's')
  15946. if (typeof input === 'string') {
  15947. dur = moment.duration(+val, input);
  15948. } else {
  15949. dur = moment.duration(input, val);
  15950. }
  15951. addOrSubtractDurationFromMoment(this, dur, 1);
  15952. return this;
  15953. },
  15954. subtract : function (input, val) {
  15955. var dur;
  15956. // switch args to support subtract('s', 1) and subtract(1, 's')
  15957. if (typeof input === 'string') {
  15958. dur = moment.duration(+val, input);
  15959. } else {
  15960. dur = moment.duration(input, val);
  15961. }
  15962. addOrSubtractDurationFromMoment(this, dur, -1);
  15963. return this;
  15964. },
  15965. diff : function (input, units, asFloat) {
  15966. var that = makeAs(input, this),
  15967. zoneDiff = (this.zone() - that.zone()) * 6e4,
  15968. diff, output;
  15969. units = normalizeUnits(units);
  15970. if (units === 'year' || units === 'month') {
  15971. // average number of days in the months in the given dates
  15972. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  15973. // difference in months
  15974. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  15975. // adjust by taking difference in days, average number of days
  15976. // and dst in the given months.
  15977. output += ((this - moment(this).startOf('month')) -
  15978. (that - moment(that).startOf('month'))) / diff;
  15979. // same as above but with zones, to negate all dst
  15980. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  15981. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  15982. if (units === 'year') {
  15983. output = output / 12;
  15984. }
  15985. } else {
  15986. diff = (this - that);
  15987. output = units === 'second' ? diff / 1e3 : // 1000
  15988. units === 'minute' ? diff / 6e4 : // 1000 * 60
  15989. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  15990. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  15991. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  15992. diff;
  15993. }
  15994. return asFloat ? output : absRound(output);
  15995. },
  15996. from : function (time, withoutSuffix) {
  15997. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  15998. },
  15999. fromNow : function (withoutSuffix) {
  16000. return this.from(moment(), withoutSuffix);
  16001. },
  16002. calendar : function () {
  16003. // We want to compare the start of today, vs this.
  16004. // Getting start-of-today depends on whether we're zone'd or not.
  16005. var sod = makeAs(moment(), this).startOf('day'),
  16006. diff = this.diff(sod, 'days', true),
  16007. format = diff < -6 ? 'sameElse' :
  16008. diff < -1 ? 'lastWeek' :
  16009. diff < 0 ? 'lastDay' :
  16010. diff < 1 ? 'sameDay' :
  16011. diff < 2 ? 'nextDay' :
  16012. diff < 7 ? 'nextWeek' : 'sameElse';
  16013. return this.format(this.lang().calendar(format, this));
  16014. },
  16015. isLeapYear : function () {
  16016. return isLeapYear(this.year());
  16017. },
  16018. isDST : function () {
  16019. return (this.zone() < this.clone().month(0).zone() ||
  16020. this.zone() < this.clone().month(5).zone());
  16021. },
  16022. day : function (input) {
  16023. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  16024. if (input != null) {
  16025. input = parseWeekday(input, this.lang());
  16026. return this.add({ d : input - day });
  16027. } else {
  16028. return day;
  16029. }
  16030. },
  16031. month : function (input) {
  16032. var utc = this._isUTC ? 'UTC' : '',
  16033. dayOfMonth;
  16034. if (input != null) {
  16035. if (typeof input === 'string') {
  16036. input = this.lang().monthsParse(input);
  16037. if (typeof input !== 'number') {
  16038. return this;
  16039. }
  16040. }
  16041. dayOfMonth = this.date();
  16042. this.date(1);
  16043. this._d['set' + utc + 'Month'](input);
  16044. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  16045. moment.updateOffset(this);
  16046. return this;
  16047. } else {
  16048. return this._d['get' + utc + 'Month']();
  16049. }
  16050. },
  16051. startOf: function (units) {
  16052. units = normalizeUnits(units);
  16053. // the following switch intentionally omits break keywords
  16054. // to utilize falling through the cases.
  16055. switch (units) {
  16056. case 'year':
  16057. this.month(0);
  16058. /* falls through */
  16059. case 'month':
  16060. this.date(1);
  16061. /* falls through */
  16062. case 'week':
  16063. case 'isoWeek':
  16064. case 'day':
  16065. this.hours(0);
  16066. /* falls through */
  16067. case 'hour':
  16068. this.minutes(0);
  16069. /* falls through */
  16070. case 'minute':
  16071. this.seconds(0);
  16072. /* falls through */
  16073. case 'second':
  16074. this.milliseconds(0);
  16075. /* falls through */
  16076. }
  16077. // weeks are a special case
  16078. if (units === 'week') {
  16079. this.weekday(0);
  16080. } else if (units === 'isoWeek') {
  16081. this.isoWeekday(1);
  16082. }
  16083. return this;
  16084. },
  16085. endOf: function (units) {
  16086. units = normalizeUnits(units);
  16087. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  16088. },
  16089. isAfter: function (input, units) {
  16090. units = typeof units !== 'undefined' ? units : 'millisecond';
  16091. return +this.clone().startOf(units) > +moment(input).startOf(units);
  16092. },
  16093. isBefore: function (input, units) {
  16094. units = typeof units !== 'undefined' ? units : 'millisecond';
  16095. return +this.clone().startOf(units) < +moment(input).startOf(units);
  16096. },
  16097. isSame: function (input, units) {
  16098. units = units || 'ms';
  16099. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  16100. },
  16101. min: function (other) {
  16102. other = moment.apply(null, arguments);
  16103. return other < this ? this : other;
  16104. },
  16105. max: function (other) {
  16106. other = moment.apply(null, arguments);
  16107. return other > this ? this : other;
  16108. },
  16109. zone : function (input) {
  16110. var offset = this._offset || 0;
  16111. if (input != null) {
  16112. if (typeof input === "string") {
  16113. input = timezoneMinutesFromString(input);
  16114. }
  16115. if (Math.abs(input) < 16) {
  16116. input = input * 60;
  16117. }
  16118. this._offset = input;
  16119. this._isUTC = true;
  16120. if (offset !== input) {
  16121. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  16122. }
  16123. } else {
  16124. return this._isUTC ? offset : this._d.getTimezoneOffset();
  16125. }
  16126. return this;
  16127. },
  16128. zoneAbbr : function () {
  16129. return this._isUTC ? "UTC" : "";
  16130. },
  16131. zoneName : function () {
  16132. return this._isUTC ? "Coordinated Universal Time" : "";
  16133. },
  16134. parseZone : function () {
  16135. if (this._tzm) {
  16136. this.zone(this._tzm);
  16137. } else if (typeof this._i === 'string') {
  16138. this.zone(this._i);
  16139. }
  16140. return this;
  16141. },
  16142. hasAlignedHourOffset : function (input) {
  16143. if (!input) {
  16144. input = 0;
  16145. }
  16146. else {
  16147. input = moment(input).zone();
  16148. }
  16149. return (this.zone() - input) % 60 === 0;
  16150. },
  16151. daysInMonth : function () {
  16152. return daysInMonth(this.year(), this.month());
  16153. },
  16154. dayOfYear : function (input) {
  16155. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  16156. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  16157. },
  16158. quarter : function () {
  16159. return Math.ceil((this.month() + 1.0) / 3.0);
  16160. },
  16161. weekYear : function (input) {
  16162. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  16163. return input == null ? year : this.add("y", (input - year));
  16164. },
  16165. isoWeekYear : function (input) {
  16166. var year = weekOfYear(this, 1, 4).year;
  16167. return input == null ? year : this.add("y", (input - year));
  16168. },
  16169. week : function (input) {
  16170. var week = this.lang().week(this);
  16171. return input == null ? week : this.add("d", (input - week) * 7);
  16172. },
  16173. isoWeek : function (input) {
  16174. var week = weekOfYear(this, 1, 4).week;
  16175. return input == null ? week : this.add("d", (input - week) * 7);
  16176. },
  16177. weekday : function (input) {
  16178. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  16179. return input == null ? weekday : this.add("d", input - weekday);
  16180. },
  16181. isoWeekday : function (input) {
  16182. // behaves the same as moment#day except
  16183. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  16184. // as a setter, sunday should belong to the previous week.
  16185. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  16186. },
  16187. get : function (units) {
  16188. units = normalizeUnits(units);
  16189. return this[units]();
  16190. },
  16191. set : function (units, value) {
  16192. units = normalizeUnits(units);
  16193. if (typeof this[units] === 'function') {
  16194. this[units](value);
  16195. }
  16196. return this;
  16197. },
  16198. // If passed a language key, it will set the language for this
  16199. // instance. Otherwise, it will return the language configuration
  16200. // variables for this instance.
  16201. lang : function (key) {
  16202. if (key === undefined) {
  16203. return this._lang;
  16204. } else {
  16205. this._lang = getLangDefinition(key);
  16206. return this;
  16207. }
  16208. }
  16209. });
  16210. // helper for adding shortcuts
  16211. function makeGetterAndSetter(name, key) {
  16212. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  16213. var utc = this._isUTC ? 'UTC' : '';
  16214. if (input != null) {
  16215. this._d['set' + utc + key](input);
  16216. moment.updateOffset(this);
  16217. return this;
  16218. } else {
  16219. return this._d['get' + utc + key]();
  16220. }
  16221. };
  16222. }
  16223. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  16224. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  16225. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  16226. }
  16227. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  16228. makeGetterAndSetter('year', 'FullYear');
  16229. // add plural methods
  16230. moment.fn.days = moment.fn.day;
  16231. moment.fn.months = moment.fn.month;
  16232. moment.fn.weeks = moment.fn.week;
  16233. moment.fn.isoWeeks = moment.fn.isoWeek;
  16234. // add aliased format methods
  16235. moment.fn.toJSON = moment.fn.toISOString;
  16236. /************************************
  16237. Duration Prototype
  16238. ************************************/
  16239. extend(moment.duration.fn = Duration.prototype, {
  16240. _bubble : function () {
  16241. var milliseconds = this._milliseconds,
  16242. days = this._days,
  16243. months = this._months,
  16244. data = this._data,
  16245. seconds, minutes, hours, years;
  16246. // The following code bubbles up values, see the tests for
  16247. // examples of what that means.
  16248. data.milliseconds = milliseconds % 1000;
  16249. seconds = absRound(milliseconds / 1000);
  16250. data.seconds = seconds % 60;
  16251. minutes = absRound(seconds / 60);
  16252. data.minutes = minutes % 60;
  16253. hours = absRound(minutes / 60);
  16254. data.hours = hours % 24;
  16255. days += absRound(hours / 24);
  16256. data.days = days % 30;
  16257. months += absRound(days / 30);
  16258. data.months = months % 12;
  16259. years = absRound(months / 12);
  16260. data.years = years;
  16261. },
  16262. weeks : function () {
  16263. return absRound(this.days() / 7);
  16264. },
  16265. valueOf : function () {
  16266. return this._milliseconds +
  16267. this._days * 864e5 +
  16268. (this._months % 12) * 2592e6 +
  16269. toInt(this._months / 12) * 31536e6;
  16270. },
  16271. humanize : function (withSuffix) {
  16272. var difference = +this,
  16273. output = relativeTime(difference, !withSuffix, this.lang());
  16274. if (withSuffix) {
  16275. output = this.lang().pastFuture(difference, output);
  16276. }
  16277. return this.lang().postformat(output);
  16278. },
  16279. add : function (input, val) {
  16280. // supports only 2.0-style add(1, 's') or add(moment)
  16281. var dur = moment.duration(input, val);
  16282. this._milliseconds += dur._milliseconds;
  16283. this._days += dur._days;
  16284. this._months += dur._months;
  16285. this._bubble();
  16286. return this;
  16287. },
  16288. subtract : function (input, val) {
  16289. var dur = moment.duration(input, val);
  16290. this._milliseconds -= dur._milliseconds;
  16291. this._days -= dur._days;
  16292. this._months -= dur._months;
  16293. this._bubble();
  16294. return this;
  16295. },
  16296. get : function (units) {
  16297. units = normalizeUnits(units);
  16298. return this[units.toLowerCase() + 's']();
  16299. },
  16300. as : function (units) {
  16301. units = normalizeUnits(units);
  16302. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  16303. },
  16304. lang : moment.fn.lang,
  16305. toIsoString : function () {
  16306. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  16307. var years = Math.abs(this.years()),
  16308. months = Math.abs(this.months()),
  16309. days = Math.abs(this.days()),
  16310. hours = Math.abs(this.hours()),
  16311. minutes = Math.abs(this.minutes()),
  16312. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  16313. if (!this.asSeconds()) {
  16314. // this is the same as C#'s (Noda) and python (isodate)...
  16315. // but not other JS (goog.date)
  16316. return 'P0D';
  16317. }
  16318. return (this.asSeconds() < 0 ? '-' : '') +
  16319. 'P' +
  16320. (years ? years + 'Y' : '') +
  16321. (months ? months + 'M' : '') +
  16322. (days ? days + 'D' : '') +
  16323. ((hours || minutes || seconds) ? 'T' : '') +
  16324. (hours ? hours + 'H' : '') +
  16325. (minutes ? minutes + 'M' : '') +
  16326. (seconds ? seconds + 'S' : '');
  16327. }
  16328. });
  16329. function makeDurationGetter(name) {
  16330. moment.duration.fn[name] = function () {
  16331. return this._data[name];
  16332. };
  16333. }
  16334. function makeDurationAsGetter(name, factor) {
  16335. moment.duration.fn['as' + name] = function () {
  16336. return +this / factor;
  16337. };
  16338. }
  16339. for (i in unitMillisecondFactors) {
  16340. if (unitMillisecondFactors.hasOwnProperty(i)) {
  16341. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  16342. makeDurationGetter(i.toLowerCase());
  16343. }
  16344. }
  16345. makeDurationAsGetter('Weeks', 6048e5);
  16346. moment.duration.fn.asMonths = function () {
  16347. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  16348. };
  16349. /************************************
  16350. Default Lang
  16351. ************************************/
  16352. // Set default language, other languages will inherit from English.
  16353. moment.lang('en', {
  16354. ordinal : function (number) {
  16355. var b = number % 10,
  16356. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  16357. (b === 1) ? 'st' :
  16358. (b === 2) ? 'nd' :
  16359. (b === 3) ? 'rd' : 'th';
  16360. return number + output;
  16361. }
  16362. });
  16363. /* EMBED_LANGUAGES */
  16364. /************************************
  16365. Exposing Moment
  16366. ************************************/
  16367. function makeGlobal(deprecate) {
  16368. var warned = false, local_moment = moment;
  16369. /*global ender:false */
  16370. if (typeof ender !== 'undefined') {
  16371. return;
  16372. }
  16373. // here, `this` means `window` in the browser, or `global` on the server
  16374. // add `moment` as a global object via a string identifier,
  16375. // for Closure Compiler "advanced" mode
  16376. if (deprecate) {
  16377. global.moment = function () {
  16378. if (!warned && console && console.warn) {
  16379. warned = true;
  16380. console.warn(
  16381. "Accessing Moment through the global scope is " +
  16382. "deprecated, and will be removed in an upcoming " +
  16383. "release.");
  16384. }
  16385. return local_moment.apply(null, arguments);
  16386. };
  16387. extend(global.moment, local_moment);
  16388. } else {
  16389. global['moment'] = moment;
  16390. }
  16391. }
  16392. // CommonJS module is defined
  16393. if (hasModule) {
  16394. module.exports = moment;
  16395. makeGlobal(true);
  16396. } else if (typeof define === "function" && define.amd) {
  16397. define("moment", function (require, exports, module) {
  16398. if (module.config && module.config() && module.config().noGlobal !== true) {
  16399. // If user provided noGlobal, he is aware of global
  16400. makeGlobal(module.config().noGlobal === undefined);
  16401. }
  16402. return moment;
  16403. });
  16404. } else {
  16405. makeGlobal();
  16406. }
  16407. }).call(this);
  16408. },{}],4:[function(require,module,exports){
  16409. /**
  16410. * Copyright 2012 Craig Campbell
  16411. *
  16412. * Licensed under the Apache License, Version 2.0 (the "License");
  16413. * you may not use this file except in compliance with the License.
  16414. * You may obtain a copy of the License at
  16415. *
  16416. * http://www.apache.org/licenses/LICENSE-2.0
  16417. *
  16418. * Unless required by applicable law or agreed to in writing, software
  16419. * distributed under the License is distributed on an "AS IS" BASIS,
  16420. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16421. * See the License for the specific language governing permissions and
  16422. * limitations under the License.
  16423. *
  16424. * Mousetrap is a simple keyboard shortcut library for Javascript with
  16425. * no external dependencies
  16426. *
  16427. * @version 1.1.2
  16428. * @url craig.is/killing/mice
  16429. */
  16430. /**
  16431. * mapping of special keycodes to their corresponding keys
  16432. *
  16433. * everything in this dictionary cannot use keypress events
  16434. * so it has to be here to map to the correct keycodes for
  16435. * keyup/keydown events
  16436. *
  16437. * @type {Object}
  16438. */
  16439. var _MAP = {
  16440. 8: 'backspace',
  16441. 9: 'tab',
  16442. 13: 'enter',
  16443. 16: 'shift',
  16444. 17: 'ctrl',
  16445. 18: 'alt',
  16446. 20: 'capslock',
  16447. 27: 'esc',
  16448. 32: 'space',
  16449. 33: 'pageup',
  16450. 34: 'pagedown',
  16451. 35: 'end',
  16452. 36: 'home',
  16453. 37: 'left',
  16454. 38: 'up',
  16455. 39: 'right',
  16456. 40: 'down',
  16457. 45: 'ins',
  16458. 46: 'del',
  16459. 91: 'meta',
  16460. 93: 'meta',
  16461. 224: 'meta'
  16462. },
  16463. /**
  16464. * mapping for special characters so they can support
  16465. *
  16466. * this dictionary is only used incase you want to bind a
  16467. * keyup or keydown event to one of these keys
  16468. *
  16469. * @type {Object}
  16470. */
  16471. _KEYCODE_MAP = {
  16472. 106: '*',
  16473. 107: '+',
  16474. 109: '-',
  16475. 110: '.',
  16476. 111 : '/',
  16477. 186: ';',
  16478. 187: '=',
  16479. 188: ',',
  16480. 189: '-',
  16481. 190: '.',
  16482. 191: '/',
  16483. 192: '`',
  16484. 219: '[',
  16485. 220: '\\',
  16486. 221: ']',
  16487. 222: '\''
  16488. },
  16489. /**
  16490. * this is a mapping of keys that require shift on a US keypad
  16491. * back to the non shift equivelents
  16492. *
  16493. * this is so you can use keyup events with these keys
  16494. *
  16495. * note that this will only work reliably on US keyboards
  16496. *
  16497. * @type {Object}
  16498. */
  16499. _SHIFT_MAP = {
  16500. '~': '`',
  16501. '!': '1',
  16502. '@': '2',
  16503. '#': '3',
  16504. '$': '4',
  16505. '%': '5',
  16506. '^': '6',
  16507. '&': '7',
  16508. '*': '8',
  16509. '(': '9',
  16510. ')': '0',
  16511. '_': '-',
  16512. '+': '=',
  16513. ':': ';',
  16514. '\"': '\'',
  16515. '<': ',',
  16516. '>': '.',
  16517. '?': '/',
  16518. '|': '\\'
  16519. },
  16520. /**
  16521. * this is a list of special strings you can use to map
  16522. * to modifier keys when you specify your keyboard shortcuts
  16523. *
  16524. * @type {Object}
  16525. */
  16526. _SPECIAL_ALIASES = {
  16527. 'option': 'alt',
  16528. 'command': 'meta',
  16529. 'return': 'enter',
  16530. 'escape': 'esc'
  16531. },
  16532. /**
  16533. * variable to store the flipped version of _MAP from above
  16534. * needed to check if we should use keypress or not when no action
  16535. * is specified
  16536. *
  16537. * @type {Object|undefined}
  16538. */
  16539. _REVERSE_MAP,
  16540. /**
  16541. * a list of all the callbacks setup via Mousetrap.bind()
  16542. *
  16543. * @type {Object}
  16544. */
  16545. _callbacks = {},
  16546. /**
  16547. * direct map of string combinations to callbacks used for trigger()
  16548. *
  16549. * @type {Object}
  16550. */
  16551. _direct_map = {},
  16552. /**
  16553. * keeps track of what level each sequence is at since multiple
  16554. * sequences can start out with the same sequence
  16555. *
  16556. * @type {Object}
  16557. */
  16558. _sequence_levels = {},
  16559. /**
  16560. * variable to store the setTimeout call
  16561. *
  16562. * @type {null|number}
  16563. */
  16564. _reset_timer,
  16565. /**
  16566. * temporary state where we will ignore the next keyup
  16567. *
  16568. * @type {boolean|string}
  16569. */
  16570. _ignore_next_keyup = false,
  16571. /**
  16572. * are we currently inside of a sequence?
  16573. * type of action ("keyup" or "keydown" or "keypress") or false
  16574. *
  16575. * @type {boolean|string}
  16576. */
  16577. _inside_sequence = false;
  16578. /**
  16579. * loop through the f keys, f1 to f19 and add them to the map
  16580. * programatically
  16581. */
  16582. for (var i = 1; i < 20; ++i) {
  16583. _MAP[111 + i] = 'f' + i;
  16584. }
  16585. /**
  16586. * loop through to map numbers on the numeric keypad
  16587. */
  16588. for (i = 0; i <= 9; ++i) {
  16589. _MAP[i + 96] = i;
  16590. }
  16591. /**
  16592. * cross browser add event method
  16593. *
  16594. * @param {Element|HTMLDocument} object
  16595. * @param {string} type
  16596. * @param {Function} callback
  16597. * @returns void
  16598. */
  16599. function _addEvent(object, type, callback) {
  16600. if (object.addEventListener) {
  16601. return object.addEventListener(type, callback, false);
  16602. }
  16603. object.attachEvent('on' + type, callback);
  16604. }
  16605. /**
  16606. * takes the event and returns the key character
  16607. *
  16608. * @param {Event} e
  16609. * @return {string}
  16610. */
  16611. function _characterFromEvent(e) {
  16612. // for keypress events we should return the character as is
  16613. if (e.type == 'keypress') {
  16614. return String.fromCharCode(e.which);
  16615. }
  16616. // for non keypress events the special maps are needed
  16617. if (_MAP[e.which]) {
  16618. return _MAP[e.which];
  16619. }
  16620. if (_KEYCODE_MAP[e.which]) {
  16621. return _KEYCODE_MAP[e.which];
  16622. }
  16623. // if it is not in the special map
  16624. return String.fromCharCode(e.which).toLowerCase();
  16625. }
  16626. /**
  16627. * should we stop this event before firing off callbacks
  16628. *
  16629. * @param {Event} e
  16630. * @return {boolean}
  16631. */
  16632. function _stop(e) {
  16633. var element = e.target || e.srcElement,
  16634. tag_name = element.tagName;
  16635. // if the element has the class "mousetrap" then no need to stop
  16636. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  16637. return false;
  16638. }
  16639. // stop for input, select, and textarea
  16640. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  16641. }
  16642. /**
  16643. * checks if two arrays are equal
  16644. *
  16645. * @param {Array} modifiers1
  16646. * @param {Array} modifiers2
  16647. * @returns {boolean}
  16648. */
  16649. function _modifiersMatch(modifiers1, modifiers2) {
  16650. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  16651. }
  16652. /**
  16653. * resets all sequence counters except for the ones passed in
  16654. *
  16655. * @param {Object} do_not_reset
  16656. * @returns void
  16657. */
  16658. function _resetSequences(do_not_reset) {
  16659. do_not_reset = do_not_reset || {};
  16660. var active_sequences = false,
  16661. key;
  16662. for (key in _sequence_levels) {
  16663. if (do_not_reset[key]) {
  16664. active_sequences = true;
  16665. continue;
  16666. }
  16667. _sequence_levels[key] = 0;
  16668. }
  16669. if (!active_sequences) {
  16670. _inside_sequence = false;
  16671. }
  16672. }
  16673. /**
  16674. * finds all callbacks that match based on the keycode, modifiers,
  16675. * and action
  16676. *
  16677. * @param {string} character
  16678. * @param {Array} modifiers
  16679. * @param {string} action
  16680. * @param {boolean=} remove - should we remove any matches
  16681. * @param {string=} combination
  16682. * @returns {Array}
  16683. */
  16684. function _getMatches(character, modifiers, action, remove, combination) {
  16685. var i,
  16686. callback,
  16687. matches = [];
  16688. // if there are no events related to this keycode
  16689. if (!_callbacks[character]) {
  16690. return [];
  16691. }
  16692. // if a modifier key is coming up on its own we should allow it
  16693. if (action == 'keyup' && _isModifier(character)) {
  16694. modifiers = [character];
  16695. }
  16696. // loop through all callbacks for the key that was pressed
  16697. // and see if any of them match
  16698. for (i = 0; i < _callbacks[character].length; ++i) {
  16699. callback = _callbacks[character][i];
  16700. // if this is a sequence but it is not at the right level
  16701. // then move onto the next match
  16702. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  16703. continue;
  16704. }
  16705. // if the action we are looking for doesn't match the action we got
  16706. // then we should keep going
  16707. if (action != callback.action) {
  16708. continue;
  16709. }
  16710. // if this is a keypress event that means that we need to only
  16711. // look at the character, otherwise check the modifiers as
  16712. // well
  16713. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  16714. // remove is used so if you change your mind and call bind a
  16715. // second time with a new function the first one is overwritten
  16716. if (remove && callback.combo == combination) {
  16717. _callbacks[character].splice(i, 1);
  16718. }
  16719. matches.push(callback);
  16720. }
  16721. }
  16722. return matches;
  16723. }
  16724. /**
  16725. * takes a key event and figures out what the modifiers are
  16726. *
  16727. * @param {Event} e
  16728. * @returns {Array}
  16729. */
  16730. function _eventModifiers(e) {
  16731. var modifiers = [];
  16732. if (e.shiftKey) {
  16733. modifiers.push('shift');
  16734. }
  16735. if (e.altKey) {
  16736. modifiers.push('alt');
  16737. }
  16738. if (e.ctrlKey) {
  16739. modifiers.push('ctrl');
  16740. }
  16741. if (e.metaKey) {
  16742. modifiers.push('meta');
  16743. }
  16744. return modifiers;
  16745. }
  16746. /**
  16747. * actually calls the callback function
  16748. *
  16749. * if your callback function returns false this will use the jquery
  16750. * convention - prevent default and stop propogation on the event
  16751. *
  16752. * @param {Function} callback
  16753. * @param {Event} e
  16754. * @returns void
  16755. */
  16756. function _fireCallback(callback, e) {
  16757. if (callback(e) === false) {
  16758. if (e.preventDefault) {
  16759. e.preventDefault();
  16760. }
  16761. if (e.stopPropagation) {
  16762. e.stopPropagation();
  16763. }
  16764. e.returnValue = false;
  16765. e.cancelBubble = true;
  16766. }
  16767. }
  16768. /**
  16769. * handles a character key event
  16770. *
  16771. * @param {string} character
  16772. * @param {Event} e
  16773. * @returns void
  16774. */
  16775. function _handleCharacter(character, e) {
  16776. // if this event should not happen stop here
  16777. if (_stop(e)) {
  16778. return;
  16779. }
  16780. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  16781. i,
  16782. do_not_reset = {},
  16783. processed_sequence_callback = false;
  16784. // loop through matching callbacks for this key event
  16785. for (i = 0; i < callbacks.length; ++i) {
  16786. // fire for all sequence callbacks
  16787. // this is because if for example you have multiple sequences
  16788. // bound such as "g i" and "g t" they both need to fire the
  16789. // callback for matching g cause otherwise you can only ever
  16790. // match the first one
  16791. if (callbacks[i].seq) {
  16792. processed_sequence_callback = true;
  16793. // keep a list of which sequences were matches for later
  16794. do_not_reset[callbacks[i].seq] = 1;
  16795. _fireCallback(callbacks[i].callback, e);
  16796. continue;
  16797. }
  16798. // if there were no sequence matches but we are still here
  16799. // that means this is a regular match so we should fire that
  16800. if (!processed_sequence_callback && !_inside_sequence) {
  16801. _fireCallback(callbacks[i].callback, e);
  16802. }
  16803. }
  16804. // if you are inside of a sequence and the key you are pressing
  16805. // is not a modifier key then we should reset all sequences
  16806. // that were not matched by this key event
  16807. if (e.type == _inside_sequence && !_isModifier(character)) {
  16808. _resetSequences(do_not_reset);
  16809. }
  16810. }
  16811. /**
  16812. * handles a keydown event
  16813. *
  16814. * @param {Event} e
  16815. * @returns void
  16816. */
  16817. function _handleKey(e) {
  16818. // normalize e.which for key events
  16819. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  16820. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  16821. var character = _characterFromEvent(e);
  16822. // no character found then stop
  16823. if (!character) {
  16824. return;
  16825. }
  16826. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  16827. _ignore_next_keyup = false;
  16828. return;
  16829. }
  16830. _handleCharacter(character, e);
  16831. }
  16832. /**
  16833. * determines if the keycode specified is a modifier key or not
  16834. *
  16835. * @param {string} key
  16836. * @returns {boolean}
  16837. */
  16838. function _isModifier(key) {
  16839. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  16840. }
  16841. /**
  16842. * called to set a 1 second timeout on the specified sequence
  16843. *
  16844. * this is so after each key press in the sequence you have 1 second
  16845. * to press the next key before you have to start over
  16846. *
  16847. * @returns void
  16848. */
  16849. function _resetSequenceTimer() {
  16850. clearTimeout(_reset_timer);
  16851. _reset_timer = setTimeout(_resetSequences, 1000);
  16852. }
  16853. /**
  16854. * reverses the map lookup so that we can look for specific keys
  16855. * to see what can and can't use keypress
  16856. *
  16857. * @return {Object}
  16858. */
  16859. function _getReverseMap() {
  16860. if (!_REVERSE_MAP) {
  16861. _REVERSE_MAP = {};
  16862. for (var key in _MAP) {
  16863. // pull out the numeric keypad from here cause keypress should
  16864. // be able to detect the keys from the character
  16865. if (key > 95 && key < 112) {
  16866. continue;
  16867. }
  16868. if (_MAP.hasOwnProperty(key)) {
  16869. _REVERSE_MAP[_MAP[key]] = key;
  16870. }
  16871. }
  16872. }
  16873. return _REVERSE_MAP;
  16874. }
  16875. /**
  16876. * picks the best action based on the key combination
  16877. *
  16878. * @param {string} key - character for key
  16879. * @param {Array} modifiers
  16880. * @param {string=} action passed in
  16881. */
  16882. function _pickBestAction(key, modifiers, action) {
  16883. // if no action was picked in we should try to pick the one
  16884. // that we think would work best for this key
  16885. if (!action) {
  16886. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  16887. }
  16888. // modifier keys don't work as expected with keypress,
  16889. // switch to keydown
  16890. if (action == 'keypress' && modifiers.length) {
  16891. action = 'keydown';
  16892. }
  16893. return action;
  16894. }
  16895. /**
  16896. * binds a key sequence to an event
  16897. *
  16898. * @param {string} combo - combo specified in bind call
  16899. * @param {Array} keys
  16900. * @param {Function} callback
  16901. * @param {string=} action
  16902. * @returns void
  16903. */
  16904. function _bindSequence(combo, keys, callback, action) {
  16905. // start off by adding a sequence level record for this combination
  16906. // and setting the level to 0
  16907. _sequence_levels[combo] = 0;
  16908. // if there is no action pick the best one for the first key
  16909. // in the sequence
  16910. if (!action) {
  16911. action = _pickBestAction(keys[0], []);
  16912. }
  16913. /**
  16914. * callback to increase the sequence level for this sequence and reset
  16915. * all other sequences that were active
  16916. *
  16917. * @param {Event} e
  16918. * @returns void
  16919. */
  16920. var _increaseSequence = function(e) {
  16921. _inside_sequence = action;
  16922. ++_sequence_levels[combo];
  16923. _resetSequenceTimer();
  16924. },
  16925. /**
  16926. * wraps the specified callback inside of another function in order
  16927. * to reset all sequence counters as soon as this sequence is done
  16928. *
  16929. * @param {Event} e
  16930. * @returns void
  16931. */
  16932. _callbackAndReset = function(e) {
  16933. _fireCallback(callback, e);
  16934. // we should ignore the next key up if the action is key down
  16935. // or keypress. this is so if you finish a sequence and
  16936. // release the key the final key will not trigger a keyup
  16937. if (action !== 'keyup') {
  16938. _ignore_next_keyup = _characterFromEvent(e);
  16939. }
  16940. // weird race condition if a sequence ends with the key
  16941. // another sequence begins with
  16942. setTimeout(_resetSequences, 10);
  16943. },
  16944. i;
  16945. // loop through keys one at a time and bind the appropriate callback
  16946. // function. for any key leading up to the final one it should
  16947. // increase the sequence. after the final, it should reset all sequences
  16948. for (i = 0; i < keys.length; ++i) {
  16949. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  16950. }
  16951. }
  16952. /**
  16953. * binds a single keyboard combination
  16954. *
  16955. * @param {string} combination
  16956. * @param {Function} callback
  16957. * @param {string=} action
  16958. * @param {string=} sequence_name - name of sequence if part of sequence
  16959. * @param {number=} level - what part of the sequence the command is
  16960. * @returns void
  16961. */
  16962. function _bindSingle(combination, callback, action, sequence_name, level) {
  16963. // make sure multiple spaces in a row become a single space
  16964. combination = combination.replace(/\s+/g, ' ');
  16965. var sequence = combination.split(' '),
  16966. i,
  16967. key,
  16968. keys,
  16969. modifiers = [];
  16970. // if this pattern is a sequence of keys then run through this method
  16971. // to reprocess each pattern one key at a time
  16972. if (sequence.length > 1) {
  16973. return _bindSequence(combination, sequence, callback, action);
  16974. }
  16975. // take the keys from this pattern and figure out what the actual
  16976. // pattern is all about
  16977. keys = combination === '+' ? ['+'] : combination.split('+');
  16978. for (i = 0; i < keys.length; ++i) {
  16979. key = keys[i];
  16980. // normalize key names
  16981. if (_SPECIAL_ALIASES[key]) {
  16982. key = _SPECIAL_ALIASES[key];
  16983. }
  16984. // if this is not a keypress event then we should
  16985. // be smart about using shift keys
  16986. // this will only work for US keyboards however
  16987. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  16988. key = _SHIFT_MAP[key];
  16989. modifiers.push('shift');
  16990. }
  16991. // if this key is a modifier then add it to the list of modifiers
  16992. if (_isModifier(key)) {
  16993. modifiers.push(key);
  16994. }
  16995. }
  16996. // depending on what the key combination is
  16997. // we will try to pick the best event for it
  16998. action = _pickBestAction(key, modifiers, action);
  16999. // make sure to initialize array if this is the first time
  17000. // a callback is added for this key
  17001. if (!_callbacks[key]) {
  17002. _callbacks[key] = [];
  17003. }
  17004. // remove an existing match if there is one
  17005. _getMatches(key, modifiers, action, !sequence_name, combination);
  17006. // add this call back to the array
  17007. // if it is a sequence put it at the beginning
  17008. // if not put it at the end
  17009. //
  17010. // this is important because the way these are processed expects
  17011. // the sequence ones to come first
  17012. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  17013. callback: callback,
  17014. modifiers: modifiers,
  17015. action: action,
  17016. seq: sequence_name,
  17017. level: level,
  17018. combo: combination
  17019. });
  17020. }
  17021. /**
  17022. * binds multiple combinations to the same callback
  17023. *
  17024. * @param {Array} combinations
  17025. * @param {Function} callback
  17026. * @param {string|undefined} action
  17027. * @returns void
  17028. */
  17029. function _bindMultiple(combinations, callback, action) {
  17030. for (var i = 0; i < combinations.length; ++i) {
  17031. _bindSingle(combinations[i], callback, action);
  17032. }
  17033. }
  17034. // start!
  17035. _addEvent(document, 'keypress', _handleKey);
  17036. _addEvent(document, 'keydown', _handleKey);
  17037. _addEvent(document, 'keyup', _handleKey);
  17038. var mousetrap = {
  17039. /**
  17040. * binds an event to mousetrap
  17041. *
  17042. * can be a single key, a combination of keys separated with +,
  17043. * a comma separated list of keys, an array of keys, or
  17044. * a sequence of keys separated by spaces
  17045. *
  17046. * be sure to list the modifier keys first to make sure that the
  17047. * correct key ends up getting bound (the last key in the pattern)
  17048. *
  17049. * @param {string|Array} keys
  17050. * @param {Function} callback
  17051. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  17052. * @returns void
  17053. */
  17054. bind: function(keys, callback, action) {
  17055. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  17056. _direct_map[keys + ':' + action] = callback;
  17057. return this;
  17058. },
  17059. /**
  17060. * unbinds an event to mousetrap
  17061. *
  17062. * the unbinding sets the callback function of the specified key combo
  17063. * to an empty function and deletes the corresponding key in the
  17064. * _direct_map dict.
  17065. *
  17066. * the keycombo+action has to be exactly the same as
  17067. * it was defined in the bind method
  17068. *
  17069. * TODO: actually remove this from the _callbacks dictionary instead
  17070. * of binding an empty function
  17071. *
  17072. * @param {string|Array} keys
  17073. * @param {string} action
  17074. * @returns void
  17075. */
  17076. unbind: function(keys, action) {
  17077. if (_direct_map[keys + ':' + action]) {
  17078. delete _direct_map[keys + ':' + action];
  17079. this.bind(keys, function() {}, action);
  17080. }
  17081. return this;
  17082. },
  17083. /**
  17084. * triggers an event that has already been bound
  17085. *
  17086. * @param {string} keys
  17087. * @param {string=} action
  17088. * @returns void
  17089. */
  17090. trigger: function(keys, action) {
  17091. _direct_map[keys + ':' + action]();
  17092. return this;
  17093. },
  17094. /**
  17095. * resets the library back to its initial state. this is useful
  17096. * if you want to clear out the current keyboard shortcuts and bind
  17097. * new ones - for example if you switch to another page
  17098. *
  17099. * @returns void
  17100. */
  17101. reset: function() {
  17102. _callbacks = {};
  17103. _direct_map = {};
  17104. return this;
  17105. }
  17106. };
  17107. module.exports = mousetrap;
  17108. },{}]},{},[1])
  17109. (1)
  17110. });