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.

19690 lines
565 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.nodeScaling.width;
  7788. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  7789. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  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. // console.log(vmin,this.vx,this.vy);
  8092. return true;
  8093. }
  8094. else {
  8095. this.vx = 0; this.vy = 0;
  8096. return false;
  8097. }
  8098. //return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8099. };
  8100. /**
  8101. * check if this node is selecte
  8102. * @return {boolean} selected True if node is selected, else false
  8103. */
  8104. Node.prototype.isSelected = function() {
  8105. return this.selected;
  8106. };
  8107. /**
  8108. * Retrieve the value of the node. Can be undefined
  8109. * @return {Number} value
  8110. */
  8111. Node.prototype.getValue = function() {
  8112. return this.value;
  8113. };
  8114. /**
  8115. * Calculate the distance from the nodes location to the given location (x,y)
  8116. * @param {Number} x
  8117. * @param {Number} y
  8118. * @return {Number} value
  8119. */
  8120. Node.prototype.getDistance = function(x, y) {
  8121. var dx = this.x - x,
  8122. dy = this.y - y;
  8123. return Math.sqrt(dx * dx + dy * dy);
  8124. };
  8125. /**
  8126. * Adjust the value range of the node. The node will adjust it's radius
  8127. * based on its value.
  8128. * @param {Number} min
  8129. * @param {Number} max
  8130. */
  8131. Node.prototype.setValueRange = function(min, max) {
  8132. if (!this.radiusFixed && this.value !== undefined) {
  8133. if (max == min) {
  8134. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8135. }
  8136. else {
  8137. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8138. this.radius = (this.value - min) * scale + this.radiusMin;
  8139. }
  8140. }
  8141. this.baseRadiusValue = this.radius;
  8142. };
  8143. /**
  8144. * Draw this node in the given canvas
  8145. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8146. * @param {CanvasRenderingContext2D} ctx
  8147. */
  8148. Node.prototype.draw = function(ctx) {
  8149. throw "Draw method not initialized for node";
  8150. };
  8151. /**
  8152. * Recalculate the size of this node in the given canvas
  8153. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8154. * @param {CanvasRenderingContext2D} ctx
  8155. */
  8156. Node.prototype.resize = function(ctx) {
  8157. throw "Resize method not initialized for node";
  8158. };
  8159. /**
  8160. * Check if this object is overlapping with the provided object
  8161. * @param {Object} obj an object with parameters left, top, right, bottom
  8162. * @return {boolean} True if location is located on node
  8163. */
  8164. Node.prototype.isOverlappingWith = function(obj) {
  8165. return (this.left < obj.right &&
  8166. this.left + this.width > obj.left &&
  8167. this.top < obj.bottom &&
  8168. this.top + this.height > obj.top);
  8169. };
  8170. Node.prototype._resizeImage = function (ctx) {
  8171. // TODO: pre calculate the image size
  8172. if (!this.width || !this.height) { // undefined or 0
  8173. var width, height;
  8174. if (this.value) {
  8175. this.radius = this.baseRadiusValue;
  8176. var scale = this.imageObj.height / this.imageObj.width;
  8177. if (scale !== undefined) {
  8178. width = this.radius || this.imageObj.width;
  8179. height = this.radius * scale || this.imageObj.height;
  8180. }
  8181. else {
  8182. width = 0;
  8183. height = 0;
  8184. }
  8185. }
  8186. else {
  8187. width = this.imageObj.width;
  8188. height = this.imageObj.height;
  8189. }
  8190. this.width = width;
  8191. this.height = height;
  8192. if (this.width > 0 && this.height > 0) {
  8193. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8194. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8195. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8196. }
  8197. }
  8198. };
  8199. Node.prototype._drawImage = function (ctx) {
  8200. this._resizeImage(ctx);
  8201. this.left = this.x - this.width / 2;
  8202. this.top = this.y - this.height / 2;
  8203. var yLabel;
  8204. if (this.imageObj.width != 0 ) {
  8205. // draw the shade
  8206. if (this.clusterSize > 1) {
  8207. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8208. lineWidth *= this.graphScaleInv;
  8209. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8210. ctx.globalAlpha = 0.5;
  8211. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8212. }
  8213. // draw the image
  8214. ctx.globalAlpha = 1.0;
  8215. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8216. yLabel = this.y + this.height / 2;
  8217. }
  8218. else {
  8219. // image still loading... just draw the label for now
  8220. yLabel = this.y;
  8221. }
  8222. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8223. };
  8224. Node.prototype._resizeBox = function (ctx) {
  8225. if (!this.width) {
  8226. var margin = 5;
  8227. var textSize = this.getTextSize(ctx);
  8228. this.width = textSize.width + 2 * margin;
  8229. this.height = textSize.height + 2 * margin;
  8230. this.width += (this.clusterSize - 1) * 0.5 * this.clusterSizeWidthFactor;
  8231. this.height += (this.clusterSize - 1) * 0.5 * this.clusterSizeHeightFactor;
  8232. // this.radius += (this.clusterSize - 1) * 0.5 * this.clusterSizeRadiusFactor;
  8233. }
  8234. };
  8235. Node.prototype._drawBox = function (ctx) {
  8236. this._resizeBox(ctx);
  8237. this.left = this.x - this.width / 2;
  8238. this.top = this.y - this.height / 2;
  8239. var clusterLineWidth = 2.5;
  8240. var selectionLineWidth = 2;
  8241. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8242. // draw the outer border
  8243. if (this.clusterSize > 1) {
  8244. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8245. ctx.lineWidth *= this.graphScaleInv;
  8246. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8247. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8248. ctx.stroke();
  8249. }
  8250. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8251. ctx.lineWidth *= this.graphScaleInv;
  8252. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8253. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8254. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8255. ctx.fill();
  8256. ctx.stroke();
  8257. this._label(ctx, this.label, this.x, this.y);
  8258. };
  8259. Node.prototype._resizeDatabase = function (ctx) {
  8260. if (!this.width) {
  8261. var margin = 5;
  8262. var textSize = this.getTextSize(ctx);
  8263. var size = textSize.width + 2 * margin;
  8264. this.width = size;
  8265. this.height = size;
  8266. // scaling used for clustering
  8267. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8268. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8269. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8270. }
  8271. };
  8272. Node.prototype._drawDatabase = function (ctx) {
  8273. this._resizeDatabase(ctx);
  8274. this.left = this.x - this.width / 2;
  8275. this.top = this.y - this.height / 2;
  8276. var clusterLineWidth = 2.5;
  8277. var selectionLineWidth = 2;
  8278. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8279. // draw the outer border
  8280. if (this.clusterSize > 1) {
  8281. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8282. ctx.lineWidth *= this.graphScaleInv;
  8283. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8284. 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);
  8285. ctx.stroke();
  8286. }
  8287. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8288. ctx.lineWidth *= this.graphScaleInv;
  8289. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8290. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8291. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8292. ctx.fill();
  8293. ctx.stroke();
  8294. this._label(ctx, this.label, this.x, this.y);
  8295. };
  8296. Node.prototype._resizeCircle = function (ctx) {
  8297. if (!this.width) {
  8298. var margin = 5;
  8299. var textSize = this.getTextSize(ctx);
  8300. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8301. this.radius = diameter / 2;
  8302. this.width = diameter;
  8303. this.height = diameter;
  8304. // scaling used for clustering
  8305. // this.width += (this.clusterSize - 1) * 0.5 * this.clusterSizeWidthFactor;
  8306. // this.height += (this.clusterSize - 1) * 0.5 * this.clusterSizeHeightFactor;
  8307. this.radius += (this.clusterSize - 1) * 0.5 * this.clusterSizeRadiusFactor;
  8308. }
  8309. };
  8310. Node.prototype._drawCircle = function (ctx) {
  8311. this._resizeCircle(ctx);
  8312. this.left = this.x - this.width / 2;
  8313. this.top = this.y - this.height / 2;
  8314. var clusterLineWidth = 2.5;
  8315. var selectionLineWidth = 2;
  8316. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8317. // draw the outer border
  8318. if (this.clusterSize > 1) {
  8319. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8320. ctx.lineWidth *= this.graphScaleInv;
  8321. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8322. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8323. ctx.stroke();
  8324. }
  8325. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8326. ctx.lineWidth *= this.graphScaleInv;
  8327. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8328. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8329. ctx.circle(this.x, this.y, this.radius);
  8330. ctx.fill();
  8331. ctx.stroke();
  8332. this._label(ctx, this.label, this.x, this.y);
  8333. };
  8334. Node.prototype._resizeEllipse = function (ctx) {
  8335. if (!this.width) {
  8336. var textSize = this.getTextSize(ctx);
  8337. this.width = textSize.width * 1.5;
  8338. this.height = textSize.height * 2;
  8339. if (this.width < this.height) {
  8340. this.width = this.height;
  8341. }
  8342. // scaling used for clustering
  8343. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8344. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8345. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8346. }
  8347. };
  8348. Node.prototype._drawEllipse = function (ctx) {
  8349. this._resizeEllipse(ctx);
  8350. this.left = this.x - this.width / 2;
  8351. this.top = this.y - this.height / 2;
  8352. var clusterLineWidth = 2.5;
  8353. var selectionLineWidth = 2;
  8354. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8355. // draw the outer border
  8356. if (this.clusterSize > 1) {
  8357. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8358. ctx.lineWidth *= this.graphScaleInv;
  8359. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8360. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8361. ctx.stroke();
  8362. }
  8363. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8364. ctx.lineWidth *= this.graphScaleInv;
  8365. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8366. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8367. ctx.ellipse(this.left, this.top, this.width, this.height);
  8368. ctx.fill();
  8369. ctx.stroke();
  8370. this._label(ctx, this.label, this.x, this.y);
  8371. };
  8372. Node.prototype._drawDot = function (ctx) {
  8373. this._drawShape(ctx, 'circle');
  8374. };
  8375. Node.prototype._drawTriangle = function (ctx) {
  8376. this._drawShape(ctx, 'triangle');
  8377. };
  8378. Node.prototype._drawTriangleDown = function (ctx) {
  8379. this._drawShape(ctx, 'triangleDown');
  8380. };
  8381. Node.prototype._drawSquare = function (ctx) {
  8382. this._drawShape(ctx, 'square');
  8383. };
  8384. Node.prototype._drawStar = function (ctx) {
  8385. this._drawShape(ctx, 'star');
  8386. };
  8387. Node.prototype._resizeShape = function (ctx) {
  8388. if (!this.width) {
  8389. this.radius = this.baseRadiusValue;
  8390. var size = 2 * this.radius;
  8391. this.width = size;
  8392. this.height = size;
  8393. // scaling used for clustering
  8394. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8395. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8396. this.radius += (this.clusterSize - 1) * 0.5 * this.clusterSizeRadiusFactor;
  8397. }
  8398. };
  8399. Node.prototype._drawShape = function (ctx, shape) {
  8400. this._resizeShape(ctx);
  8401. this.left = this.x - this.width / 2;
  8402. this.top = this.y - this.height / 2;
  8403. var clusterLineWidth = 2.5;
  8404. var selectionLineWidth = 2;
  8405. var radiusMultiplier = 2;
  8406. // choose draw method depending on the shape
  8407. switch (shape) {
  8408. case 'dot': radiusMultiplier = 2; break;
  8409. case 'square': radiusMultiplier = 2; break;
  8410. case 'triangle': radiusMultiplier = 3; break;
  8411. case 'triangleDown': radiusMultiplier = 3; break;
  8412. case 'star': radiusMultiplier = 4; break;
  8413. }
  8414. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8415. // draw the outer border
  8416. if (this.clusterSize > 1) {
  8417. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8418. ctx.lineWidth *= this.graphScaleInv;
  8419. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8420. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8421. ctx.stroke();
  8422. }
  8423. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8424. ctx.lineWidth *= this.graphScaleInv;
  8425. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8426. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8427. ctx[shape](this.x, this.y, this.radius);
  8428. ctx.fill();
  8429. ctx.stroke();
  8430. if (this.label) {
  8431. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8432. }
  8433. };
  8434. Node.prototype._resizeText = function (ctx) {
  8435. if (!this.width) {
  8436. var margin = 5;
  8437. var textSize = this.getTextSize(ctx);
  8438. this.width = textSize.width + 2 * margin;
  8439. this.height = textSize.height + 2 * margin;
  8440. // scaling used for clustering
  8441. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8442. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8443. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8444. }
  8445. };
  8446. Node.prototype._drawText = function (ctx) {
  8447. this._resizeText(ctx);
  8448. this.left = this.x - this.width / 2;
  8449. this.top = this.y - this.height / 2;
  8450. this._label(ctx, this.label, this.x, this.y);
  8451. };
  8452. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  8453. if (text) {
  8454. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8455. ctx.fillStyle = this.fontColor || "black";
  8456. ctx.textAlign = align || "center";
  8457. ctx.textBaseline = baseline || "middle";
  8458. var lines = text.split('\n'),
  8459. lineCount = lines.length,
  8460. fontSize = (this.fontSize + 4),
  8461. yLine = y + (1 - lineCount) / 2 * fontSize;
  8462. for (var i = 0; i < lineCount; i++) {
  8463. ctx.fillText(lines[i], x, yLine);
  8464. yLine += fontSize;
  8465. }
  8466. }
  8467. };
  8468. Node.prototype.getTextSize = function(ctx) {
  8469. if (this.label !== undefined) {
  8470. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8471. var lines = this.label.split('\n'),
  8472. height = (this.fontSize + 4) * lines.length,
  8473. width = 0;
  8474. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  8475. width = Math.max(width, ctx.measureText(lines[i]).width);
  8476. }
  8477. return {"width": width, "height": height};
  8478. }
  8479. else {
  8480. return {"width": 0, "height": 0};
  8481. }
  8482. };
  8483. /**
  8484. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  8485. * there is a safety margin of 0.3 * width;
  8486. *
  8487. * @returns {boolean}
  8488. */
  8489. Node.prototype.inArea = function() {
  8490. if (this.width !== undefined) {
  8491. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  8492. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  8493. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  8494. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  8495. }
  8496. else {
  8497. return true;
  8498. }
  8499. }
  8500. /**
  8501. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  8502. * @returns {boolean}
  8503. */
  8504. Node.prototype.inView = function() {
  8505. return (this.x >= this.canvasTopLeft.x &&
  8506. this.x < this.canvasBottomRight.x &&
  8507. this.y >= this.canvasTopLeft.y &&
  8508. this.y < this.canvasBottomRight.y);
  8509. }
  8510. /**
  8511. * This allows the zoom level of the graph to influence the rendering
  8512. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  8513. *
  8514. * @param scale
  8515. * @param canvasTopLeft
  8516. * @param canvasBottomRight
  8517. */
  8518. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  8519. this.graphScaleInv = 1.0/scale;
  8520. this.canvasTopLeft = canvasTopLeft;
  8521. this.canvasBottomRight = canvasBottomRight;
  8522. };
  8523. /**
  8524. * This allows the zoom level of the graph to influence the rendering
  8525. *
  8526. * @param scale
  8527. */
  8528. Node.prototype.setScale = function(scale) {
  8529. this.graphScaleInv = 1.0/scale;
  8530. };
  8531. /**
  8532. * This function updates the damping parameter for clusters, based ont he
  8533. *
  8534. * @param {Number} numberOfNodes
  8535. */
  8536. Node.prototype.updateDamping = function(numberOfNodes) {
  8537. this.damping = (0.8 + 0.1*this.clusterSize * (1 + Math.pow(numberOfNodes,-2)));
  8538. this.damping *= this.dampingFactor;
  8539. };
  8540. /**
  8541. * set the velocity at 0. Is called when this node is contained in another during clustering
  8542. */
  8543. Node.prototype.clearVelocity = function() {
  8544. this.vx = 0;
  8545. this.vy = 0;
  8546. };
  8547. /**
  8548. * Basic preservation of (kinectic) energy
  8549. *
  8550. * @param massBeforeClustering
  8551. */
  8552. Node.prototype.updateVelocity = function(massBeforeClustering) {
  8553. var energyBefore = this.vx * this.vx * massBeforeClustering;
  8554. this.vx = Math.sqrt(energyBefore/this.mass);
  8555. energyBefore = this.vy * this.vy * massBeforeClustering;
  8556. this.vy = Math.sqrt(energyBefore/this.mass);
  8557. };
  8558. /**
  8559. * @class Edge
  8560. *
  8561. * A edge connects two nodes
  8562. * @param {Object} properties Object with properties. Must contain
  8563. * At least properties from and to.
  8564. * Available properties: from (number),
  8565. * to (number), label (string, color (string),
  8566. * width (number), style (string),
  8567. * length (number), title (string)
  8568. * @param {Graph} graph A graph object, used to find and edge to
  8569. * nodes.
  8570. * @param {Object} constants An object with default values for
  8571. * example for the color
  8572. */
  8573. function Edge (properties, graph, constants) {
  8574. if (!graph) {
  8575. throw "No graph provided";
  8576. }
  8577. this.graph = graph;
  8578. // initialize constants
  8579. this.widthMin = constants.edges.widthMin;
  8580. this.widthMax = constants.edges.widthMax;
  8581. // initialize variables
  8582. this.id = undefined;
  8583. this.fromId = undefined;
  8584. this.toId = undefined;
  8585. this.style = constants.edges.style;
  8586. this.title = undefined;
  8587. this.width = constants.edges.width;
  8588. this.value = undefined;
  8589. this.length = constants.edges.length;
  8590. this.from = null; // a node
  8591. this.to = null; // a node
  8592. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  8593. // by storing the original information we can revert to the original connection when the cluser is opened.
  8594. this.originalFromId = [];
  8595. this.originalToId = [];
  8596. this.connected = false;
  8597. // Added to support dashed lines
  8598. // David Jordan
  8599. // 2012-08-08
  8600. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  8601. this.stiffness = undefined; // depends on the length of the edge
  8602. this.color = constants.edges.color;
  8603. this.widthFixed = false;
  8604. this.lengthFixed = false;
  8605. this.setProperties(properties, constants);
  8606. }
  8607. /**
  8608. * Set or overwrite properties for the edge
  8609. * @param {Object} properties an object with properties
  8610. * @param {Object} constants and object with default, global properties
  8611. */
  8612. Edge.prototype.setProperties = function(properties, constants) {
  8613. if (!properties) {
  8614. return;
  8615. }
  8616. if (properties.from !== undefined) {this.fromId = properties.from;}
  8617. if (properties.to !== undefined) {this.toId = properties.to;}
  8618. if (properties.id !== undefined) {this.id = properties.id;}
  8619. if (properties.style !== undefined) {this.style = properties.style;}
  8620. if (properties.label !== undefined) {this.label = properties.label;}
  8621. if (this.label) {
  8622. this.fontSize = constants.edges.fontSize;
  8623. this.fontFace = constants.edges.fontFace;
  8624. this.fontColor = constants.edges.fontColor;
  8625. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8626. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8627. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8628. }
  8629. if (properties.title !== undefined) {this.title = properties.title;}
  8630. if (properties.width !== undefined) {this.width = properties.width;}
  8631. if (properties.value !== undefined) {this.value = properties.value;}
  8632. if (properties.length !== undefined) {this.length = properties.length;}
  8633. // Added to support dashed lines
  8634. // David Jordan
  8635. // 2012-08-08
  8636. if (properties.dash) {
  8637. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  8638. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  8639. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  8640. }
  8641. if (properties.color !== undefined) {this.color = properties.color;}
  8642. // A node is connected when it has a from and to node.
  8643. this.connect();
  8644. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  8645. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  8646. this.stiffness = 1 / this.length;
  8647. // set draw method based on style
  8648. switch (this.style) {
  8649. case 'line': this.draw = this._drawLine; break;
  8650. case 'arrow': this.draw = this._drawArrow; break;
  8651. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  8652. case 'dash-line': this.draw = this._drawDashLine; break;
  8653. default: this.draw = this._drawLine; break;
  8654. }
  8655. };
  8656. /**
  8657. * Connect an edge to its nodes
  8658. */
  8659. Edge.prototype.connect = function () {
  8660. this.disconnect();
  8661. this.from = this.graph.nodes[this.fromId] || null;
  8662. this.to = this.graph.nodes[this.toId] || null;
  8663. this.connected = (this.from && this.to);
  8664. if (this.connected) {
  8665. this.from.attachEdge(this);
  8666. this.to.attachEdge(this);
  8667. }
  8668. else {
  8669. if (this.from) {
  8670. this.from.detachEdge(this);
  8671. }
  8672. if (this.to) {
  8673. this.to.detachEdge(this);
  8674. }
  8675. }
  8676. };
  8677. /**
  8678. * Disconnect an edge from its nodes
  8679. */
  8680. Edge.prototype.disconnect = function () {
  8681. if (this.from) {
  8682. this.from.detachEdge(this);
  8683. this.from = null;
  8684. }
  8685. if (this.to) {
  8686. this.to.detachEdge(this);
  8687. this.to = null;
  8688. }
  8689. this.connected = false;
  8690. };
  8691. /**
  8692. * get the title of this edge.
  8693. * @return {string} title The title of the edge, or undefined when no title
  8694. * has been set.
  8695. */
  8696. Edge.prototype.getTitle = function() {
  8697. return this.title;
  8698. };
  8699. /**
  8700. * Retrieve the value of the edge. Can be undefined
  8701. * @return {Number} value
  8702. */
  8703. Edge.prototype.getValue = function() {
  8704. return this.value;
  8705. };
  8706. /**
  8707. * Adjust the value range of the edge. The edge will adjust it's width
  8708. * based on its value.
  8709. * @param {Number} min
  8710. * @param {Number} max
  8711. */
  8712. Edge.prototype.setValueRange = function(min, max) {
  8713. if (!this.widthFixed && this.value !== undefined) {
  8714. var scale = (this.widthMax - this.widthMin) / (max - min);
  8715. this.width = (this.value - min) * scale + this.widthMin;
  8716. }
  8717. };
  8718. /**
  8719. * Redraw a edge
  8720. * Draw this edge in the given canvas
  8721. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8722. * @param {CanvasRenderingContext2D} ctx
  8723. */
  8724. Edge.prototype.draw = function(ctx) {
  8725. throw "Method draw not initialized in edge";
  8726. };
  8727. /**
  8728. * Check if this object is overlapping with the provided object
  8729. * @param {Object} obj an object with parameters left, top
  8730. * @return {boolean} True if location is located on the edge
  8731. */
  8732. Edge.prototype.isOverlappingWith = function(obj) {
  8733. var distMax = 10;
  8734. var xFrom = this.from.x;
  8735. var yFrom = this.from.y;
  8736. var xTo = this.to.x;
  8737. var yTo = this.to.y;
  8738. var xObj = obj.left;
  8739. var yObj = obj.top;
  8740. var dist = Edge._dist(xFrom, yFrom, xTo, yTo, xObj, yObj);
  8741. return (dist < distMax);
  8742. };
  8743. /**
  8744. * Redraw a edge as a line
  8745. * Draw this edge in the given canvas
  8746. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8747. * @param {CanvasRenderingContext2D} ctx
  8748. * @private
  8749. */
  8750. Edge.prototype._drawLine = function(ctx) {
  8751. // set style
  8752. ctx.strokeStyle = this.color;
  8753. ctx.lineWidth = this._getLineWidth();
  8754. var point;
  8755. if (this.from != this.to) {
  8756. // draw line
  8757. this._line(ctx);
  8758. // draw label
  8759. if (this.label) {
  8760. point = this._pointOnLine(0.5);
  8761. this._label(ctx, this.label, point.x, point.y);
  8762. }
  8763. }
  8764. else {
  8765. var x, y;
  8766. var radius = this.length / 4;
  8767. var node = this.from;
  8768. if (!node.width) {
  8769. node.resize(ctx);
  8770. }
  8771. if (node.width > node.height) {
  8772. x = node.x + node.width / 2;
  8773. y = node.y - radius;
  8774. }
  8775. else {
  8776. x = node.x + radius;
  8777. y = node.y - node.height / 2;
  8778. }
  8779. this._circle(ctx, x, y, radius);
  8780. point = this._pointOnCircle(x, y, radius, 0.5);
  8781. this._label(ctx, this.label, point.x, point.y);
  8782. }
  8783. };
  8784. /**
  8785. * Get the line width of the edge. Depends on width and whether one of the
  8786. * connected nodes is selected.
  8787. * @return {Number} width
  8788. * @private
  8789. */
  8790. Edge.prototype._getLineWidth = function() {
  8791. if (this.from.selected || this.to.selected) {
  8792. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  8793. }
  8794. else {
  8795. return this.width*this.graphScaleInv;
  8796. }
  8797. };
  8798. /**
  8799. * Draw a line between two nodes
  8800. * @param {CanvasRenderingContext2D} ctx
  8801. * @private
  8802. */
  8803. Edge.prototype._line = function (ctx) {
  8804. // draw a straight line
  8805. ctx.beginPath();
  8806. ctx.moveTo(this.from.x, this.from.y);
  8807. ctx.lineTo(this.to.x, this.to.y);
  8808. ctx.stroke();
  8809. };
  8810. /**
  8811. * Draw a line from a node to itself, a circle
  8812. * @param {CanvasRenderingContext2D} ctx
  8813. * @param {Number} x
  8814. * @param {Number} y
  8815. * @param {Number} radius
  8816. * @private
  8817. */
  8818. Edge.prototype._circle = function (ctx, x, y, radius) {
  8819. // draw a circle
  8820. ctx.beginPath();
  8821. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  8822. ctx.stroke();
  8823. };
  8824. /**
  8825. * Draw label with white background and with the middle at (x, y)
  8826. * @param {CanvasRenderingContext2D} ctx
  8827. * @param {String} text
  8828. * @param {Number} x
  8829. * @param {Number} y
  8830. * @private
  8831. */
  8832. Edge.prototype._label = function (ctx, text, x, y) {
  8833. if (text) {
  8834. // TODO: cache the calculated size
  8835. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  8836. this.fontSize + "px " + this.fontFace;
  8837. ctx.fillStyle = 'white';
  8838. var width = ctx.measureText(text).width;
  8839. var height = this.fontSize;
  8840. var left = x - width / 2;
  8841. var top = y - height / 2;
  8842. ctx.fillRect(left, top, width, height);
  8843. // draw text
  8844. ctx.fillStyle = this.fontColor || "black";
  8845. ctx.textAlign = "left";
  8846. ctx.textBaseline = "top";
  8847. ctx.fillText(text, left, top);
  8848. }
  8849. };
  8850. /**
  8851. * Redraw a edge as a dashed line
  8852. * Draw this edge in the given canvas
  8853. * @author David Jordan
  8854. * @date 2012-08-08
  8855. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8856. * @param {CanvasRenderingContext2D} ctx
  8857. * @private
  8858. */
  8859. Edge.prototype._drawDashLine = function(ctx) {
  8860. // set style
  8861. ctx.strokeStyle = this.color;
  8862. ctx.lineWidth = this._getLineWidth();
  8863. // draw dashed line
  8864. ctx.beginPath();
  8865. ctx.lineCap = 'round';
  8866. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  8867. {
  8868. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8869. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  8870. }
  8871. 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
  8872. {
  8873. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8874. [this.dash.length,this.dash.gap]);
  8875. }
  8876. else //If all else fails draw a line
  8877. {
  8878. ctx.moveTo(this.from.x, this.from.y);
  8879. ctx.lineTo(this.to.x, this.to.y);
  8880. }
  8881. ctx.stroke();
  8882. // draw label
  8883. if (this.label) {
  8884. var point = this._pointOnLine(0.5);
  8885. this._label(ctx, this.label, point.x, point.y);
  8886. }
  8887. };
  8888. /**
  8889. * Get a point on a line
  8890. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8891. * @return {Object} point
  8892. * @private
  8893. */
  8894. Edge.prototype._pointOnLine = function (percentage) {
  8895. return {
  8896. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  8897. y: (1 - percentage) * this.from.y + percentage * this.to.y
  8898. }
  8899. };
  8900. /**
  8901. * Get a point on a circle
  8902. * @param {Number} x
  8903. * @param {Number} y
  8904. * @param {Number} radius
  8905. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8906. * @return {Object} point
  8907. * @private
  8908. */
  8909. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  8910. var angle = (percentage - 3/8) * 2 * Math.PI;
  8911. return {
  8912. x: x + radius * Math.cos(angle),
  8913. y: y - radius * Math.sin(angle)
  8914. }
  8915. };
  8916. /**
  8917. * Redraw a edge as a line with an arrow halfway the line
  8918. * Draw this edge in the given canvas
  8919. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8920. * @param {CanvasRenderingContext2D} ctx
  8921. * @private
  8922. */
  8923. Edge.prototype._drawArrowCenter = function(ctx) {
  8924. var point;
  8925. // set style
  8926. ctx.strokeStyle = this.color;
  8927. ctx.fillStyle = this.color;
  8928. ctx.lineWidth = this._getLineWidth();
  8929. if (this.from != this.to) {
  8930. // draw line
  8931. this._line(ctx);
  8932. // draw an arrow halfway the line
  8933. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8934. var length = 10 + 5 * this.width; // TODO: make customizable?
  8935. point = this._pointOnLine(0.5);
  8936. ctx.arrow(point.x, point.y, angle, length);
  8937. ctx.fill();
  8938. ctx.stroke();
  8939. // draw label
  8940. if (this.label) {
  8941. point = this._pointOnLine(0.5);
  8942. this._label(ctx, this.label, point.x, point.y);
  8943. }
  8944. }
  8945. else {
  8946. // draw circle
  8947. var x, y;
  8948. var radius = this.length / 4;
  8949. var node = this.from;
  8950. if (!node.width) {
  8951. node.resize(ctx);
  8952. }
  8953. if (node.width > node.height) {
  8954. x = node.x + node.width / 2;
  8955. y = node.y - radius;
  8956. }
  8957. else {
  8958. x = node.x + radius;
  8959. y = node.y - node.height / 2;
  8960. }
  8961. this._circle(ctx, x, y, radius);
  8962. // draw all arrows
  8963. var angle = 0.2 * Math.PI;
  8964. var length = 10 + 5 * this.width; // TODO: make customizable?
  8965. point = this._pointOnCircle(x, y, radius, 0.5);
  8966. ctx.arrow(point.x, point.y, angle, length);
  8967. ctx.fill();
  8968. ctx.stroke();
  8969. // draw label
  8970. if (this.label) {
  8971. point = this._pointOnCircle(x, y, radius, 0.5);
  8972. this._label(ctx, this.label, point.x, point.y);
  8973. }
  8974. }
  8975. };
  8976. /**
  8977. * Redraw a edge as a line with an arrow
  8978. * Draw this edge in the given canvas
  8979. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8980. * @param {CanvasRenderingContext2D} ctx
  8981. * @private
  8982. */
  8983. Edge.prototype._drawArrow = function(ctx) {
  8984. // set style
  8985. ctx.strokeStyle = this.color;
  8986. ctx.fillStyle = this.color;
  8987. ctx.lineWidth = this._getLineWidth();
  8988. // draw line
  8989. var angle, length;
  8990. if (this.from != this.to) {
  8991. // calculate length and angle of the line
  8992. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8993. var dx = (this.to.x - this.from.x);
  8994. var dy = (this.to.y - this.from.y);
  8995. var lEdge = Math.sqrt(dx * dx + dy * dy);
  8996. var lFrom = this.from.distanceToBorder(ctx, angle + Math.PI);
  8997. var pFrom = (lEdge - lFrom) / lEdge;
  8998. var xFrom = (pFrom) * this.from.x + (1 - pFrom) * this.to.x;
  8999. var yFrom = (pFrom) * this.from.y + (1 - pFrom) * this.to.y;
  9000. var lTo = this.to.distanceToBorder(ctx, angle);
  9001. var pTo = (lEdge - lTo) / lEdge;
  9002. var xTo = (1 - pTo) * this.from.x + pTo * this.to.x;
  9003. var yTo = (1 - pTo) * this.from.y + pTo * this.to.y;
  9004. ctx.beginPath();
  9005. ctx.moveTo(xFrom, yFrom);
  9006. ctx.lineTo(xTo, yTo);
  9007. ctx.stroke();
  9008. // draw arrow at the end of the line
  9009. length = 10 + 5 * this.width; // TODO: make customizable?
  9010. ctx.arrow(xTo, yTo, angle, length);
  9011. ctx.fill();
  9012. ctx.stroke();
  9013. // draw label
  9014. if (this.label) {
  9015. var point = this._pointOnLine(0.5);
  9016. this._label(ctx, this.label, point.x, point.y);
  9017. }
  9018. }
  9019. else {
  9020. // draw circle
  9021. var node = this.from;
  9022. var x, y, arrow;
  9023. var radius = this.length / 4;
  9024. if (!node.width) {
  9025. node.resize(ctx);
  9026. }
  9027. if (node.width > node.height) {
  9028. x = node.x + node.width / 2;
  9029. y = node.y - radius;
  9030. arrow = {
  9031. x: x,
  9032. y: node.y,
  9033. angle: 0.9 * Math.PI
  9034. };
  9035. }
  9036. else {
  9037. x = node.x + radius;
  9038. y = node.y - node.height / 2;
  9039. arrow = {
  9040. x: node.x,
  9041. y: y,
  9042. angle: 0.6 * Math.PI
  9043. };
  9044. }
  9045. ctx.beginPath();
  9046. // TODO: do not draw a circle, but an arc
  9047. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9048. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9049. ctx.stroke();
  9050. // draw all arrows
  9051. length = 10 + 5 * this.width; // TODO: make customizable?
  9052. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9053. ctx.fill();
  9054. ctx.stroke();
  9055. // draw label
  9056. if (this.label) {
  9057. point = this._pointOnCircle(x, y, radius, 0.5);
  9058. this._label(ctx, this.label, point.x, point.y);
  9059. }
  9060. }
  9061. };
  9062. /**
  9063. * Calculate the distance between a point (x3,y3) and a line segment from
  9064. * (x1,y1) to (x2,y2).
  9065. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9066. * @param {number} x1
  9067. * @param {number} y1
  9068. * @param {number} x2
  9069. * @param {number} y2
  9070. * @param {number} x3
  9071. * @param {number} y3
  9072. * @private
  9073. */
  9074. Edge._dist = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9075. var px = x2-x1,
  9076. py = y2-y1,
  9077. something = px*px + py*py,
  9078. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9079. if (u > 1) {
  9080. u = 1;
  9081. }
  9082. else if (u < 0) {
  9083. u = 0;
  9084. }
  9085. var x = x1 + u * px,
  9086. y = y1 + u * py,
  9087. dx = x - x3,
  9088. dy = y - y3;
  9089. //# Note: If the actual distance does not matter,
  9090. //# if you only want to compare what this function
  9091. //# returns to other results of this function, you
  9092. //# can just return the squared distance instead
  9093. //# (i.e. remove the sqrt) to gain a little performance
  9094. return Math.sqrt(dx*dx + dy*dy);
  9095. };
  9096. /**
  9097. * This allows the zoom level of the graph to influence the rendering
  9098. *
  9099. * @param scale
  9100. */
  9101. Edge.prototype.setScale = function(scale) {
  9102. this.graphScaleInv = 1.0/scale;
  9103. };
  9104. /**
  9105. * Popup is a class to create a popup window with some text
  9106. * @param {Element} container The container object.
  9107. * @param {Number} [x]
  9108. * @param {Number} [y]
  9109. * @param {String} [text]
  9110. */
  9111. function Popup(container, x, y, text) {
  9112. if (container) {
  9113. this.container = container;
  9114. }
  9115. else {
  9116. this.container = document.body;
  9117. }
  9118. this.x = 0;
  9119. this.y = 0;
  9120. this.padding = 5;
  9121. if (x !== undefined && y !== undefined ) {
  9122. this.setPosition(x, y);
  9123. }
  9124. if (text !== undefined) {
  9125. this.setText(text);
  9126. }
  9127. // create the frame
  9128. this.frame = document.createElement("div");
  9129. var style = this.frame.style;
  9130. style.position = "absolute";
  9131. style.visibility = "hidden";
  9132. style.border = "1px solid #666";
  9133. style.color = "black";
  9134. style.padding = this.padding + "px";
  9135. style.backgroundColor = "#FFFFC6";
  9136. style.borderRadius = "3px";
  9137. style.MozBorderRadius = "3px";
  9138. style.WebkitBorderRadius = "3px";
  9139. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9140. style.whiteSpace = "nowrap";
  9141. this.container.appendChild(this.frame);
  9142. }
  9143. /**
  9144. * @param {number} x Horizontal position of the popup window
  9145. * @param {number} y Vertical position of the popup window
  9146. */
  9147. Popup.prototype.setPosition = function(x, y) {
  9148. this.x = parseInt(x);
  9149. this.y = parseInt(y);
  9150. };
  9151. /**
  9152. * Set the text for the popup window. This can be HTML code
  9153. * @param {string} text
  9154. */
  9155. Popup.prototype.setText = function(text) {
  9156. this.frame.innerHTML = text;
  9157. };
  9158. /**
  9159. * Show the popup window
  9160. * @param {boolean} show Optional. Show or hide the window
  9161. */
  9162. Popup.prototype.show = function (show) {
  9163. if (show === undefined) {
  9164. show = true;
  9165. }
  9166. if (show) {
  9167. var height = this.frame.clientHeight;
  9168. var width = this.frame.clientWidth;
  9169. var maxHeight = this.frame.parentNode.clientHeight;
  9170. var maxWidth = this.frame.parentNode.clientWidth;
  9171. var top = (this.y - height);
  9172. if (top + height + this.padding > maxHeight) {
  9173. top = maxHeight - height - this.padding;
  9174. }
  9175. if (top < this.padding) {
  9176. top = this.padding;
  9177. }
  9178. var left = this.x;
  9179. if (left + width + this.padding > maxWidth) {
  9180. left = maxWidth - width - this.padding;
  9181. }
  9182. if (left < this.padding) {
  9183. left = this.padding;
  9184. }
  9185. this.frame.style.left = left + "px";
  9186. this.frame.style.top = top + "px";
  9187. this.frame.style.visibility = "visible";
  9188. }
  9189. else {
  9190. this.hide();
  9191. }
  9192. };
  9193. /**
  9194. * Hide the popup window
  9195. */
  9196. Popup.prototype.hide = function () {
  9197. this.frame.style.visibility = "hidden";
  9198. };
  9199. /**
  9200. * @class Groups
  9201. * This class can store groups and properties specific for groups.
  9202. */
  9203. Groups = function () {
  9204. this.clear();
  9205. this.defaultIndex = 0;
  9206. };
  9207. /**
  9208. * default constants for group colors
  9209. */
  9210. Groups.DEFAULT = [
  9211. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9212. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9213. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9214. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9215. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9216. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9217. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9218. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9219. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9220. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9221. ];
  9222. /**
  9223. * Clear all groups
  9224. */
  9225. Groups.prototype.clear = function () {
  9226. this.groups = {};
  9227. this.groups.length = function()
  9228. {
  9229. var i = 0;
  9230. for ( var p in this ) {
  9231. if (this.hasOwnProperty(p)) {
  9232. i++;
  9233. }
  9234. }
  9235. return i;
  9236. }
  9237. };
  9238. /**
  9239. * get group properties of a groupname. If groupname is not found, a new group
  9240. * is added.
  9241. * @param {*} groupname Can be a number, string, Date, etc.
  9242. * @return {Object} group The created group, containing all group properties
  9243. */
  9244. Groups.prototype.get = function (groupname) {
  9245. var group = this.groups[groupname];
  9246. if (group == undefined) {
  9247. // create new group
  9248. var index = this.defaultIndex % Groups.DEFAULT.length;
  9249. this.defaultIndex++;
  9250. group = {};
  9251. group.color = Groups.DEFAULT[index];
  9252. this.groups[groupname] = group;
  9253. }
  9254. return group;
  9255. };
  9256. /**
  9257. * Add a custom group style
  9258. * @param {String} groupname
  9259. * @param {Object} style An object containing borderColor,
  9260. * backgroundColor, etc.
  9261. * @return {Object} group The created group object
  9262. */
  9263. Groups.prototype.add = function (groupname, style) {
  9264. this.groups[groupname] = style;
  9265. if (style.color) {
  9266. style.color = Node.parseColor(style.color);
  9267. }
  9268. return style;
  9269. };
  9270. /**
  9271. * @class Images
  9272. * This class loads images and keeps them stored.
  9273. */
  9274. Images = function () {
  9275. this.images = {};
  9276. this.callback = undefined;
  9277. };
  9278. /**
  9279. * Set an onload callback function. This will be called each time an image
  9280. * is loaded
  9281. * @param {function} callback
  9282. */
  9283. Images.prototype.setOnloadCallback = function(callback) {
  9284. this.callback = callback;
  9285. };
  9286. /**
  9287. *
  9288. * @param {string} url Url of the image
  9289. * @return {Image} img The image object
  9290. */
  9291. Images.prototype.load = function(url) {
  9292. var img = this.images[url];
  9293. if (img == undefined) {
  9294. // create the image
  9295. var images = this;
  9296. img = new Image();
  9297. this.images[url] = img;
  9298. img.onload = function() {
  9299. if (images.callback) {
  9300. images.callback(this);
  9301. }
  9302. };
  9303. img.src = url;
  9304. }
  9305. return img;
  9306. };
  9307. /**
  9308. * Creation of the SectorMixin var.
  9309. *
  9310. * This contains all the functions the Graph object can use to employ the sector system.
  9311. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  9312. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  9313. *
  9314. * Alex de Mulder
  9315. * 21-01-2013
  9316. */
  9317. var SectorMixin = {
  9318. /**
  9319. * This function is only called by the setData function of the Graph object.
  9320. * This loads the global references into the active sector. This initializes the sector.
  9321. *
  9322. * @private
  9323. */
  9324. _putDataInSector : function() {
  9325. this.sectors["active"][this._sector()].nodes = this.nodes;
  9326. this.sectors["active"][this._sector()].edges = this.edges;
  9327. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  9328. },
  9329. /**
  9330. * /**
  9331. * This function sets the global references to nodes, edges and nodeIndices back to
  9332. * those of the supplied (active) sector. If a type is defined, do the specific type
  9333. *
  9334. * @param {String} sectorId
  9335. * @param {String} [sectorType] | "active" or "frozen"
  9336. * @private
  9337. */
  9338. _switchToSector : function(sectorId, sectorType) {
  9339. if (sectorType === undefined || sectorType == "active") {
  9340. this._switchToActiveSector(sectorId);
  9341. }
  9342. else {
  9343. this._switchToFrozenSector(sectorId);
  9344. }
  9345. },
  9346. /**
  9347. * This function sets the global references to nodes, edges and nodeIndices back to
  9348. * those of the supplied active sector.
  9349. *
  9350. * @param sectorId
  9351. * @private
  9352. */
  9353. _switchToActiveSector : function(sectorId) {
  9354. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  9355. this.nodes = this.sectors["active"][sectorId]["nodes"];
  9356. this.edges = this.sectors["active"][sectorId]["edges"];
  9357. },
  9358. /**
  9359. * This function sets the global references to nodes, edges and nodeIndices back to
  9360. * those of the supplied frozen sector.
  9361. *
  9362. * @param sectorId
  9363. * @private
  9364. */
  9365. _switchToFrozenSector : function(sectorId) {
  9366. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  9367. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  9368. this.edges = this.sectors["frozen"][sectorId]["edges"];
  9369. },
  9370. /**
  9371. * This function sets the global references to nodes, edges and nodeIndices to
  9372. * those of the navigationUI sector.
  9373. *
  9374. * @private
  9375. */
  9376. _switchToUISector : function() {
  9377. this.nodeIndices = this.sectors["navigationUI"]["nodeIndices"];
  9378. this.nodes = this.sectors["navigationUI"]["nodes"];
  9379. this.edges = this.sectors["navigationUI"]["edges"];
  9380. },
  9381. /**
  9382. * This function sets the global references to nodes, edges and nodeIndices back to
  9383. * those of the currently active sector.
  9384. *
  9385. * @private
  9386. */
  9387. _loadLatestSector : function() {
  9388. this._switchToSector(this._sector());
  9389. },
  9390. /**
  9391. * This function returns the currently active sector Id
  9392. *
  9393. * @returns {String}
  9394. * @private
  9395. */
  9396. _sector : function() {
  9397. return this.activeSector[this.activeSector.length-1];
  9398. },
  9399. /**
  9400. * This function returns the previously active sector Id
  9401. *
  9402. * @returns {String}
  9403. * @private
  9404. */
  9405. _previousSector : function() {
  9406. if (this.activeSector.length > 1) {
  9407. return this.activeSector[this.activeSector.length-2];
  9408. }
  9409. else {
  9410. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  9411. }
  9412. },
  9413. /**
  9414. * We add the active sector at the end of the this.activeSector array
  9415. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  9416. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  9417. *
  9418. * @param newId
  9419. * @private
  9420. */
  9421. _setActiveSector : function(newId) {
  9422. this.activeSector.push(newId);
  9423. },
  9424. /**
  9425. * We remove the currently active sector id from the active sector stack. This happens when
  9426. * we reactivate the previously active sector
  9427. *
  9428. * @private
  9429. */
  9430. _forgetLastSector : function() {
  9431. this.activeSector.pop();
  9432. },
  9433. /**
  9434. * This function creates a new active sector with the supplied newId. This newId
  9435. * is the expanding node id.
  9436. *
  9437. * @param {String} newId | Id of the new active sector
  9438. * @private
  9439. */
  9440. _createNewSector : function(newId) {
  9441. // create the new sector
  9442. this.sectors["active"][newId] = {"nodes":{},
  9443. "edges":{},
  9444. "nodeIndices":[],
  9445. "formationScale": this.scale,
  9446. "drawingNode": undefined};
  9447. // create the new sector render node. This gives visual feedback that you are in a new sector.
  9448. this.sectors["active"][newId]['drawingNode'] = new Node(
  9449. {id:newId,
  9450. color: {
  9451. background: "#eaefef",
  9452. border: "495c5e"
  9453. }
  9454. },{},{},this.constants);
  9455. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  9456. },
  9457. /**
  9458. * This function removes the currently active sector. This is called when we create a new
  9459. * active sector.
  9460. *
  9461. * @param {String} sectorId | Id of the active sector that will be removed
  9462. * @private
  9463. */
  9464. _deleteActiveSector : function(sectorId) {
  9465. delete this.sectors["active"][sectorId];
  9466. },
  9467. /**
  9468. * This function removes the currently active sector. This is called when we reactivate
  9469. * the previously active sector.
  9470. *
  9471. * @param {String} sectorId | Id of the active sector that will be removed
  9472. * @private
  9473. */
  9474. _deleteFrozenSector : function(sectorId) {
  9475. delete this.sectors["frozen"][sectorId];
  9476. },
  9477. /**
  9478. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  9479. * We copy the references, then delete the active entree.
  9480. *
  9481. * @param sectorId
  9482. * @private
  9483. */
  9484. _freezeSector : function(sectorId) {
  9485. // we move the set references from the active to the frozen stack.
  9486. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  9487. // we have moved the sector data into the frozen set, we now remove it from the active set
  9488. this._deleteActiveSector(sectorId);
  9489. },
  9490. /**
  9491. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  9492. * object to the "active" object.
  9493. *
  9494. * @param sectorId
  9495. * @private
  9496. */
  9497. _activateSector : function(sectorId) {
  9498. // we move the set references from the frozen to the active stack.
  9499. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  9500. // we have moved the sector data into the active set, we now remove it from the frozen stack
  9501. this._deleteFrozenSector(sectorId);
  9502. },
  9503. /**
  9504. * This function merges the data from the currently active sector with a frozen sector. This is used
  9505. * in the process of reverting back to the previously active sector.
  9506. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  9507. * upon the creation of a new active sector.
  9508. *
  9509. * @param sectorId
  9510. * @private
  9511. */
  9512. _mergeThisWithFrozen : function(sectorId) {
  9513. // copy all nodes
  9514. for (var nodeId in this.nodes) {
  9515. if (this.nodes.hasOwnProperty(nodeId)) {
  9516. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  9517. }
  9518. }
  9519. // copy all edges (if not fully clustered, else there are no edges)
  9520. for (var edgeId in this.edges) {
  9521. if (this.edges.hasOwnProperty(edgeId)) {
  9522. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  9523. }
  9524. }
  9525. // merge the nodeIndices
  9526. for (var i = 0; i < this.nodeIndices.length; i++) {
  9527. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  9528. }
  9529. },
  9530. /**
  9531. * This clusters the sector to one cluster. It was a single cluster before this process started so
  9532. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  9533. *
  9534. * @private
  9535. */
  9536. _collapseThisToSingleCluster : function() {
  9537. this.clusterToFit(1,false);
  9538. },
  9539. /**
  9540. * We create a new active sector from the node that we want to open.
  9541. *
  9542. * @param node
  9543. * @private
  9544. */
  9545. _addSector : function(node) {
  9546. // this is the currently active sector
  9547. var sector = this._sector();
  9548. // // this should allow me to select nodes from a frozen set.
  9549. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  9550. // console.log("the node is part of the active sector");
  9551. // }
  9552. // else {
  9553. // console.log("I dont know what the fuck happened!!");
  9554. // }
  9555. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  9556. delete this.nodes[node.id];
  9557. var unqiueIdentifier = util.randomUUID();
  9558. // we fully freeze the currently active sector
  9559. this._freezeSector(sector);
  9560. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  9561. this._createNewSector(unqiueIdentifier);
  9562. // we add the active sector to the sectors array to be able to revert these steps later on
  9563. this._setActiveSector(unqiueIdentifier);
  9564. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  9565. this._switchToSector(this._sector());
  9566. // finally we add the node we removed from our previous active sector to the new active sector
  9567. this.nodes[node.id] = node;
  9568. },
  9569. /**
  9570. * We close the sector that is currently open and revert back to the one before.
  9571. * If the active sector is the "default" sector, nothing happens.
  9572. *
  9573. * @private
  9574. */
  9575. _collapseSector : function() {
  9576. // the currently active sector
  9577. var sector = this._sector();
  9578. // we cannot collapse the default sector
  9579. if (sector != "default") {
  9580. if ((this.nodeIndices.length == 1) ||
  9581. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  9582. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  9583. var previousSector = this._previousSector();
  9584. // we collapse the sector back to a single cluster
  9585. this._collapseThisToSingleCluster();
  9586. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  9587. // This previous sector is the one we will reactivate
  9588. this._mergeThisWithFrozen(previousSector);
  9589. // the previously active (frozen) sector now has all the data from the currently active sector.
  9590. // we can now delete the active sector.
  9591. this._deleteActiveSector(sector);
  9592. // we activate the previously active (and currently frozen) sector.
  9593. this._activateSector(previousSector);
  9594. // we load the references from the newly active sector into the global references
  9595. this._switchToSector(previousSector);
  9596. // we forget the previously active sector because we reverted to the one before
  9597. this._forgetLastSector();
  9598. // finally, we update the node index list.
  9599. this._updateNodeIndexList();
  9600. }
  9601. }
  9602. },
  9603. /**
  9604. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  9605. *
  9606. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9607. * | we dont pass the function itself because then the "this" is the window object
  9608. * | instead of the Graph object
  9609. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9610. * @private
  9611. */
  9612. _doInAllActiveSectors : function(runFunction,argument) {
  9613. if (argument === undefined) {
  9614. for (var sector in this.sectors["active"]) {
  9615. if (this.sectors["active"].hasOwnProperty(sector)) {
  9616. // switch the global references to those of this sector
  9617. this._switchToActiveSector(sector);
  9618. this[runFunction]();
  9619. }
  9620. }
  9621. }
  9622. else {
  9623. for (var sector in this.sectors["active"]) {
  9624. if (this.sectors["active"].hasOwnProperty(sector)) {
  9625. // switch the global references to those of this sector
  9626. this._switchToActiveSector(sector);
  9627. var args = Array.prototype.splice.call(arguments, 1);
  9628. if (args.length > 1) {
  9629. this[runFunction](args[0],args[1]);
  9630. }
  9631. else {
  9632. this[runFunction](argument);
  9633. }
  9634. }
  9635. }
  9636. }
  9637. // we revert the global references back to our active sector
  9638. this._loadLatestSector();
  9639. },
  9640. /**
  9641. * This runs a function in all frozen sectors. This is used in the _redraw().
  9642. *
  9643. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9644. * | we don't pass the function itself because then the "this" is the window object
  9645. * | instead of the Graph object
  9646. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9647. * @private
  9648. */
  9649. _doInAllFrozenSectors : function(runFunction,argument) {
  9650. if (argument === undefined) {
  9651. for (var sector in this.sectors["frozen"]) {
  9652. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  9653. // switch the global references to those of this sector
  9654. this._switchToFrozenSector(sector);
  9655. this[runFunction]();
  9656. }
  9657. }
  9658. }
  9659. else {
  9660. for (var sector in this.sectors["frozen"]) {
  9661. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  9662. // switch the global references to those of this sector
  9663. this._switchToFrozenSector(sector);
  9664. var args = Array.prototype.splice.call(arguments, 1);
  9665. if (args.length > 1) {
  9666. this[runFunction](args[0],args[1]);
  9667. }
  9668. else {
  9669. this[runFunction](argument);
  9670. }
  9671. }
  9672. }
  9673. }
  9674. this._loadLatestSector();
  9675. },
  9676. /**
  9677. * This runs a function in the navigationUI sector.
  9678. *
  9679. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9680. * | we don't pass the function itself because then the "this" is the window object
  9681. * | instead of the Graph object
  9682. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9683. * @private
  9684. */
  9685. _doInUISector : function(runFunction,argument) {
  9686. this._switchToUISector();
  9687. if (argument === undefined) {
  9688. this[runFunction]();
  9689. }
  9690. else {
  9691. var args = Array.prototype.splice.call(arguments, 1);
  9692. if (args.length > 1) {
  9693. this[runFunction](args[0],args[1]);
  9694. }
  9695. else {
  9696. this[runFunction](argument);
  9697. }
  9698. }
  9699. this._loadLatestSector();
  9700. },
  9701. /**
  9702. * This runs a function in all sectors. This is used in the _redraw().
  9703. *
  9704. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9705. * | we don't pass the function itself because then the "this" is the window object
  9706. * | instead of the Graph object
  9707. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9708. * @private
  9709. */
  9710. _doInAllSectors : function(runFunction,argument) {
  9711. var args = Array.prototype.splice.call(arguments, 1);
  9712. if (argument === undefined) {
  9713. this._doInAllActiveSectors(runFunction);
  9714. this._doInAllFrozenSectors(runFunction);
  9715. }
  9716. else {
  9717. if (args.length > 1) {
  9718. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  9719. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  9720. }
  9721. else {
  9722. this._doInAllActiveSectors(runFunction,argument);
  9723. this._doInAllFrozenSectors(runFunction,argument);
  9724. }
  9725. }
  9726. },
  9727. /**
  9728. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  9729. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  9730. *
  9731. * @private
  9732. */
  9733. _clearNodeIndexList : function() {
  9734. var sector = this._sector();
  9735. this.sectors["active"][sector]["nodeIndices"] = [];
  9736. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  9737. },
  9738. /**
  9739. * Draw the encompassing sector node
  9740. *
  9741. * @param ctx
  9742. * @param sectorType
  9743. * @private
  9744. */
  9745. _drawSectorNodes : function(ctx,sectorType) {
  9746. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  9747. for (var sector in this.sectors[sectorType]) {
  9748. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  9749. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  9750. this._switchToSector(sector,sectorType);
  9751. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  9752. for (var nodeId in this.nodes) {
  9753. if (this.nodes.hasOwnProperty(nodeId)) {
  9754. node = this.nodes[nodeId];
  9755. node.resize(ctx);
  9756. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  9757. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  9758. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  9759. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  9760. }
  9761. }
  9762. node = this.sectors[sectorType][sector]["drawingNode"];
  9763. node.x = 0.5 * (maxX + minX);
  9764. node.y = 0.5 * (maxY + minY);
  9765. node.width = 2 * (node.x - minX);
  9766. node.height = 2 * (node.y - minY);
  9767. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  9768. node.setScale(this.scale);
  9769. node._drawCircle(ctx);
  9770. }
  9771. }
  9772. }
  9773. },
  9774. _drawAllSectorNodes : function(ctx) {
  9775. this._drawSectorNodes(ctx,"frozen");
  9776. this._drawSectorNodes(ctx,"active");
  9777. this._loadLatestSector();
  9778. }
  9779. };
  9780. /**
  9781. * Creation of the ClusterMixin var.
  9782. *
  9783. * This contains all the functions the Graph object can use to employ clustering
  9784. *
  9785. * Alex de Mulder
  9786. * 21-01-2013
  9787. */
  9788. var ClusterMixin = {
  9789. /**
  9790. * This is only called in the constructor of the graph object
  9791. * */
  9792. startWithClustering : function() {
  9793. // cluster if the data set is big
  9794. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  9795. // updates the lables after clustering
  9796. this.updateLabels();
  9797. // this is called here because if clusterin is disabled, the start and stabilize are called in
  9798. // the setData function.
  9799. if (this.stabilize) {
  9800. this._doStabilize();
  9801. }
  9802. this.start();
  9803. },
  9804. /**
  9805. * This function clusters until the initialMaxNodes has been reached
  9806. *
  9807. * @param {Number} maxNumberOfNodes
  9808. * @param {Boolean} reposition
  9809. */
  9810. clusterToFit : function(maxNumberOfNodes, reposition) {
  9811. var numberOfNodes = this.nodeIndices.length;
  9812. var maxLevels = 50;
  9813. var level = 0;
  9814. // we first cluster the hubs, then we pull in the outliers, repeat
  9815. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  9816. if (level % 3 == 0) {
  9817. this.forceAggregateHubs();
  9818. }
  9819. else {
  9820. this.increaseClusterLevel();
  9821. }
  9822. numberOfNodes = this.nodeIndices.length;
  9823. level += 1;
  9824. }
  9825. // after the clustering we reposition the nodes to reduce the initial chaos
  9826. if (level > 1 && reposition == true) {
  9827. this.repositionNodes();
  9828. }
  9829. },
  9830. /**
  9831. * This function can be called to open up a specific cluster. It is only called by
  9832. * It will unpack the cluster back one level.
  9833. *
  9834. * @param node | Node object: cluster to open.
  9835. */
  9836. openCluster : function(node) {
  9837. var isMovingBeforeClustering = this.moving;
  9838. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  9839. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  9840. this._addSector(node);
  9841. var level = 0;
  9842. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  9843. this.decreaseClusterLevel();
  9844. level += 1;
  9845. }
  9846. }
  9847. else {
  9848. this._expandClusterNode(node,false,true);
  9849. // update the index list, dynamic edges and labels
  9850. this._updateNodeIndexList();
  9851. this._updateDynamicEdges();
  9852. this.updateLabels();
  9853. }
  9854. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  9855. if (this.moving != isMovingBeforeClustering) {
  9856. this.start();
  9857. }
  9858. },
  9859. /**
  9860. * This calls the updateClustes with default arguments
  9861. */
  9862. updateClustersDefault : function() {
  9863. if (this.constants.clustering.enabled == true) {
  9864. this.updateClusters(0,false,false);
  9865. }
  9866. },
  9867. /**
  9868. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  9869. * be clustered with their connected node. This can be repeated as many times as needed.
  9870. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  9871. */
  9872. increaseClusterLevel : function() {
  9873. this.updateClusters(-1,false,true);
  9874. },
  9875. /**
  9876. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  9877. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  9878. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  9879. */
  9880. decreaseClusterLevel : function() {
  9881. this.updateClusters(1,false,true);
  9882. },
  9883. /**
  9884. * This is the main clustering function. It clusters and declusters on zoom or forced
  9885. * This function clusters on zoom, it can be called with a predefined zoom direction
  9886. * If out, check if we can form clusters, if in, check if we can open clusters.
  9887. * This function is only called from _zoom()
  9888. *
  9889. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  9890. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  9891. * @param {Boolean} force | enabled or disable forcing
  9892. *
  9893. */
  9894. updateClusters : function(zoomDirection,recursive,force) {
  9895. var isMovingBeforeClustering = this.moving;
  9896. var amountOfNodes = this.nodeIndices.length;
  9897. // on zoom out collapse the sector if the scale is at the level the sector was made
  9898. if (this.previousScale > this.scale && zoomDirection == 0) {
  9899. this._collapseSector();
  9900. }
  9901. // check if we zoom in or out
  9902. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  9903. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  9904. // outer nodes determines if it is being clustered
  9905. this._formClusters(force);
  9906. }
  9907. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  9908. if (force == true) {
  9909. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  9910. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  9911. this._openClusters(recursive,force);
  9912. }
  9913. else {
  9914. // if a cluster takes up a set percentage of the active window
  9915. this._openClustersBySize();
  9916. }
  9917. }
  9918. this._updateNodeIndexList();
  9919. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  9920. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  9921. this._aggregateHubs(force);
  9922. this._updateNodeIndexList();
  9923. }
  9924. // we now reduce chains.
  9925. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  9926. this.handleChains();
  9927. this._updateNodeIndexList();
  9928. }
  9929. this.previousScale = this.scale;
  9930. // rest of the update the index list, dynamic edges and labels
  9931. this._updateDynamicEdges();
  9932. this.updateLabels();
  9933. // if a cluster was formed, we increase the clusterSession
  9934. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  9935. this.clusterSession += 1;
  9936. }
  9937. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  9938. if (this.moving != isMovingBeforeClustering) {
  9939. this.start();
  9940. }
  9941. },
  9942. /**
  9943. * This function handles the chains. It is called on every updateClusters().
  9944. */
  9945. handleChains : function() {
  9946. // after clustering we check how many chains there are
  9947. var chainPercentage = this._getChainFraction();
  9948. if (chainPercentage > this.constants.clustering.chainThreshold) {
  9949. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  9950. }
  9951. },
  9952. /**
  9953. * this functions starts clustering by hubs
  9954. * The minimum hub threshold is set globally
  9955. *
  9956. * @private
  9957. */
  9958. _aggregateHubs : function(force) {
  9959. this._getHubSize();
  9960. this._formClustersByHub(force,false);
  9961. },
  9962. /**
  9963. * This function is fired by keypress. It forces hubs to form.
  9964. *
  9965. */
  9966. forceAggregateHubs : function() {
  9967. var isMovingBeforeClustering = this.moving;
  9968. var amountOfNodes = this.nodeIndices.length;
  9969. this._aggregateHubs(true);
  9970. // update the index list, dynamic edges and labels
  9971. this._updateNodeIndexList();
  9972. this._updateDynamicEdges();
  9973. this.updateLabels();
  9974. // if a cluster was formed, we increase the clusterSession
  9975. if (this.nodeIndices.length != amountOfNodes) {
  9976. this.clusterSession += 1;
  9977. }
  9978. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  9979. if (this.moving != isMovingBeforeClustering) {
  9980. this.start();
  9981. }
  9982. },
  9983. /**
  9984. * If a cluster takes up more than a set percentage of the screen, open the cluster
  9985. *
  9986. * @private
  9987. */
  9988. _openClustersBySize : function() {
  9989. for (var nodeId in this.nodes) {
  9990. if (this.nodes.hasOwnProperty(nodeId)) {
  9991. var node = this.nodes[nodeId];
  9992. if (node.inView() == true) {
  9993. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  9994. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  9995. this.openCluster(node);
  9996. }
  9997. }
  9998. }
  9999. }
  10000. },
  10001. /**
  10002. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  10003. * has to be opened based on the current zoom level.
  10004. *
  10005. * @private
  10006. */
  10007. _openClusters : function(recursive,force) {
  10008. for (var i = 0; i < this.nodeIndices.length; i++) {
  10009. var node = this.nodes[this.nodeIndices[i]];
  10010. this._expandClusterNode(node,recursive,force);
  10011. }
  10012. },
  10013. /**
  10014. * This function checks if a node has to be opened. This is done by checking the zoom level.
  10015. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  10016. * This recursive behaviour is optional and can be set by the recursive argument.
  10017. *
  10018. * @param {Node} parentNode | to check for cluster and expand
  10019. * @param {Boolean} recursive | enabled or disable recursive calling
  10020. * @param {Boolean} force | enabled or disable forcing
  10021. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  10022. * @private
  10023. */
  10024. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  10025. // first check if node is a cluster
  10026. if (parentNode.clusterSize > 1) {
  10027. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  10028. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  10029. openAll = true;
  10030. }
  10031. recursive = openAll ? true : recursive;
  10032. // if the last child has been added on a smaller scale than current scale decluster
  10033. if (parentNode.formationScale < this.scale || force == true) {
  10034. // we will check if any of the contained child nodes should be removed from the cluster
  10035. for (var containedNodeId in parentNode.containedNodes) {
  10036. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  10037. var childNode = parentNode.containedNodes[containedNodeId];
  10038. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  10039. // the largest cluster is the one that comes from outside
  10040. if (force == true) {
  10041. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  10042. || openAll) {
  10043. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  10044. }
  10045. }
  10046. else {
  10047. if (this._nodeInActiveArea(parentNode)) {
  10048. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  10049. }
  10050. }
  10051. }
  10052. }
  10053. }
  10054. }
  10055. },
  10056. /**
  10057. * ONLY CALLED FROM _expandClusterNode
  10058. *
  10059. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  10060. * the child node from the parent contained_node object and put it back into the global nodes object.
  10061. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  10062. *
  10063. * @param {Node} parentNode | the parent node
  10064. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  10065. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  10066. * With force and recursive both true, the entire cluster is unpacked
  10067. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  10068. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  10069. * @private
  10070. */
  10071. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  10072. var childNode = parentNode.containedNodes[containedNodeId];
  10073. // if child node has been added on smaller scale than current, kick out
  10074. if (childNode.formationScale < this.scale || force == true) {
  10075. // put the child node back in the global nodes object
  10076. this.nodes[containedNodeId] = childNode;
  10077. // release the contained edges from this childNode back into the global edges
  10078. this._releaseContainedEdges(parentNode,childNode);
  10079. // reconnect rerouted edges to the childNode
  10080. this._connectEdgeBackToChild(parentNode,childNode);
  10081. // validate all edges in dynamicEdges
  10082. this._validateEdges(parentNode);
  10083. // undo the changes from the clustering operation on the parent node
  10084. parentNode.mass -= this.constants.clustering.massTransferCoefficient * childNode.mass;
  10085. parentNode.fontSize -= this.constants.clustering.fontSizeMultiplier * childNode.clusterSize;
  10086. parentNode.clusterSize -= childNode.clusterSize;
  10087. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  10088. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  10089. childNode.x = parentNode.x + this.constants.edges.length * 0.3 * (0.5 - Math.random()) * parentNode.clusterSize;
  10090. childNode.y = parentNode.y + this.constants.edges.length * 0.3 * (0.5 - Math.random()) * parentNode.clusterSize;
  10091. // remove node from the list
  10092. delete parentNode.containedNodes[containedNodeId];
  10093. // check if there are other childs with this clusterSession in the parent.
  10094. var othersPresent = false;
  10095. for (var childNodeId in parentNode.containedNodes) {
  10096. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  10097. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  10098. othersPresent = true;
  10099. break;
  10100. }
  10101. }
  10102. }
  10103. // if there are no others, remove the cluster session from the list
  10104. if (othersPresent == false) {
  10105. parentNode.clusterSessions.pop();
  10106. }
  10107. // remove the clusterSession from the child node
  10108. childNode.clusterSession = 0;
  10109. // restart the simulation to reorganise all nodes
  10110. this.moving = true;
  10111. // recalculate the size of the node on the next time the node is rendered
  10112. parentNode.clearSizeCache();
  10113. }
  10114. // check if a further expansion step is possible if recursivity is enabled
  10115. if (recursive == true) {
  10116. this._expandClusterNode(childNode,recursive,force,openAll);
  10117. }
  10118. },
  10119. /**
  10120. * This function checks if any nodes at the end of their trees have edges below a threshold length
  10121. * This function is called only from updateClusters()
  10122. * forceLevelCollapse ignores the length of the edge and collapses one level
  10123. * This means that a node with only one edge will be clustered with its connected node
  10124. *
  10125. * @private
  10126. * @param {Boolean} force
  10127. */
  10128. _formClusters : function(force) {
  10129. if (force == false) {
  10130. this._formClustersByZoom();
  10131. }
  10132. else {
  10133. this._forceClustersByZoom();
  10134. }
  10135. },
  10136. /**
  10137. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  10138. *
  10139. * @private
  10140. */
  10141. _formClustersByZoom : function() {
  10142. var dx,dy,length,
  10143. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  10144. // check if any edges are shorter than minLength and start the clustering
  10145. // the clustering favours the node with the larger mass
  10146. for (var edgeId in this.edges) {
  10147. if (this.edges.hasOwnProperty(edgeId)) {
  10148. var edge = this.edges[edgeId];
  10149. if (edge.connected) {
  10150. if (edge.toId != edge.fromId) {
  10151. dx = (edge.to.x - edge.from.x);
  10152. dy = (edge.to.y - edge.from.y);
  10153. length = Math.sqrt(dx * dx + dy * dy);
  10154. if (length < minLength) {
  10155. // first check which node is larger
  10156. var parentNode = edge.from;
  10157. var childNode = edge.to;
  10158. if (edge.to.mass > edge.from.mass) {
  10159. parentNode = edge.to;
  10160. childNode = edge.from;
  10161. }
  10162. if (childNode.dynamicEdgesLength == 1) {
  10163. this._addToCluster(parentNode,childNode,false);
  10164. }
  10165. else if (parentNode.dynamicEdgesLength == 1) {
  10166. this._addToCluster(childNode,parentNode,false);
  10167. }
  10168. }
  10169. }
  10170. }
  10171. }
  10172. }
  10173. },
  10174. /**
  10175. * This function forces the graph to cluster all nodes with only one connecting edge to their
  10176. * connected node.
  10177. *
  10178. * @private
  10179. */
  10180. _forceClustersByZoom : function() {
  10181. for (var nodeId in this.nodes) {
  10182. // another node could have absorbed this child.
  10183. if (this.nodes.hasOwnProperty(nodeId)) {
  10184. var childNode = this.nodes[nodeId];
  10185. // the edges can be swallowed by another decrease
  10186. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  10187. var edge = childNode.dynamicEdges[0];
  10188. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  10189. // group to the largest node
  10190. if (childNode.id != parentNode.id) {
  10191. if (parentNode.mass > childNode.mass) {
  10192. this._addToCluster(parentNode,childNode,true);
  10193. }
  10194. else {
  10195. this._addToCluster(childNode,parentNode,true);
  10196. }
  10197. }
  10198. }
  10199. }
  10200. }
  10201. },
  10202. /**
  10203. * This function forms clusters from hubs, it loops over all nodes
  10204. *
  10205. * @param {Boolean} force | Disregard zoom level
  10206. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  10207. * @private
  10208. */
  10209. _formClustersByHub : function(force, onlyEqual) {
  10210. // we loop over all nodes in the list
  10211. for (var nodeId in this.nodes) {
  10212. // we check if it is still available since it can be used by the clustering in this loop
  10213. if (this.nodes.hasOwnProperty(nodeId)) {
  10214. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  10215. }
  10216. }
  10217. },
  10218. /**
  10219. * This function forms a cluster from a specific preselected hub node
  10220. *
  10221. * @param {Node} hubNode | the node we will cluster as a hub
  10222. * @param {Boolean} force | Disregard zoom level
  10223. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  10224. * @param {Number} [absorptionSizeOffset] |
  10225. * @private
  10226. */
  10227. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  10228. if (absorptionSizeOffset === undefined) {
  10229. absorptionSizeOffset = 0;
  10230. }
  10231. // we decide if the node is a hub
  10232. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  10233. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  10234. // initialize variables
  10235. var dx,dy,length;
  10236. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  10237. var allowCluster = false;
  10238. // we create a list of edges because the dynamicEdges change over the course of this loop
  10239. var edgesIdarray = [];
  10240. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  10241. for (var j = 0; j < amountOfInitialEdges; j++) {
  10242. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  10243. }
  10244. // if the hub clustering is not forces, we check if one of the edges connected
  10245. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  10246. if (force == false) {
  10247. allowCluster = false;
  10248. for (j = 0; j < amountOfInitialEdges; j++) {
  10249. var edge = this.edges[edgesIdarray[j]];
  10250. if (edge !== undefined) {
  10251. if (edge.connected) {
  10252. if (edge.toId != edge.fromId) {
  10253. dx = (edge.to.x - edge.from.x);
  10254. dy = (edge.to.y - edge.from.y);
  10255. length = Math.sqrt(dx * dx + dy * dy);
  10256. if (length < minLength) {
  10257. allowCluster = true;
  10258. break;
  10259. }
  10260. }
  10261. }
  10262. }
  10263. }
  10264. }
  10265. // start the clustering if allowed
  10266. if ((!force && allowCluster) || force) {
  10267. // we loop over all edges INITIALLY connected to this hub
  10268. for (j = 0; j < amountOfInitialEdges; j++) {
  10269. edge = this.edges[edgesIdarray[j]];
  10270. // the edge can be clustered by this function in a previous loop
  10271. if (edge !== undefined) {
  10272. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  10273. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  10274. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  10275. (childNode.id != hubNode.id)) {
  10276. this._addToCluster(hubNode,childNode,force);
  10277. }
  10278. }
  10279. }
  10280. }
  10281. }
  10282. },
  10283. /**
  10284. * This function adds the child node to the parent node, creating a cluster if it is not already.
  10285. *
  10286. * @param {Node} parentNode | this is the node that will house the child node
  10287. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  10288. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  10289. * @private
  10290. */
  10291. _addToCluster : function(parentNode, childNode, force) {
  10292. // join child node in the parent node
  10293. parentNode.containedNodes[childNode.id] = childNode;
  10294. // manage all the edges connected to the child and parent nodes
  10295. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  10296. var edge = childNode.dynamicEdges[i];
  10297. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  10298. this._addToContainedEdges(parentNode,childNode,edge);
  10299. }
  10300. else {
  10301. this._connectEdgeToCluster(parentNode,childNode,edge);
  10302. }
  10303. }
  10304. // a contained node has no dynamic edges.
  10305. childNode.dynamicEdges = [];
  10306. // remove circular edges from clusters
  10307. this._containCircularEdgesFromNode(parentNode,childNode);
  10308. // remove the childNode from the global nodes object
  10309. delete this.nodes[childNode.id];
  10310. // update the properties of the child and parent
  10311. var massBefore = parentNode.mass;
  10312. childNode.clusterSession = this.clusterSession;
  10313. parentNode.mass += this.constants.clustering.massTransferCoefficient * childNode.mass;
  10314. parentNode.clusterSize += childNode.clusterSize;
  10315. parentNode.fontSize += this.constants.clustering.fontSizeMultiplier * childNode.clusterSize;
  10316. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  10317. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  10318. parentNode.clusterSessions.push(this.clusterSession);
  10319. }
  10320. // forced clusters only open from screen size and double tap
  10321. if (force == true) {
  10322. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  10323. parentNode.formationScale = 0;
  10324. }
  10325. else {
  10326. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  10327. }
  10328. // recalculate the size of the node on the next time the node is rendered
  10329. parentNode.clearSizeCache();
  10330. // set the pop-out scale for the childnode
  10331. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  10332. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  10333. childNode.clearVelocity();
  10334. // the mass has altered, preservation of energy dictates the velocity to be updated
  10335. parentNode.updateVelocity(massBefore);
  10336. // restart the simulation to reorganise all nodes
  10337. this.moving = true;
  10338. },
  10339. /**
  10340. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  10341. * This is a seperate function to allow for level-wise collapsing of the node tree.
  10342. * It has to be called if a level is collapsed. It is called by _formClusters().
  10343. * @private
  10344. */
  10345. _updateDynamicEdges : function() {
  10346. for (var i = 0; i < this.nodeIndices.length; i++) {
  10347. var node = this.nodes[this.nodeIndices[i]];
  10348. node.dynamicEdgesLength = node.dynamicEdges.length;
  10349. // this corrects for multiple edges pointing at the same other node
  10350. var correction = 0;
  10351. if (node.dynamicEdgesLength > 1) {
  10352. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  10353. var edgeToId = node.dynamicEdges[j].toId;
  10354. var edgeFromId = node.dynamicEdges[j].fromId;
  10355. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  10356. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  10357. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  10358. correction += 1;
  10359. }
  10360. }
  10361. }
  10362. }
  10363. node.dynamicEdgesLength -= correction;
  10364. }
  10365. },
  10366. /**
  10367. * This adds an edge from the childNode to the contained edges of the parent node
  10368. *
  10369. * @param parentNode | Node object
  10370. * @param childNode | Node object
  10371. * @param edge | Edge object
  10372. * @private
  10373. */
  10374. _addToContainedEdges : function(parentNode, childNode, edge) {
  10375. // create an array object if it does not yet exist for this childNode
  10376. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  10377. parentNode.containedEdges[childNode.id] = []
  10378. }
  10379. // add this edge to the list
  10380. parentNode.containedEdges[childNode.id].push(edge);
  10381. // remove the edge from the global edges object
  10382. delete this.edges[edge.id];
  10383. // remove the edge from the parent object
  10384. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  10385. if (parentNode.dynamicEdges[i].id == edge.id) {
  10386. parentNode.dynamicEdges.splice(i,1);
  10387. break;
  10388. }
  10389. }
  10390. },
  10391. /**
  10392. * This function connects an edge that was connected to a child node to the parent node.
  10393. * It keeps track of which nodes it has been connected to with the originalId array.
  10394. *
  10395. * @param {Node} parentNode | Node object
  10396. * @param {Node} childNode | Node object
  10397. * @param {Edge} edge | Edge object
  10398. * @private
  10399. */
  10400. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  10401. // handle circular edges
  10402. if (edge.toId == edge.fromId) {
  10403. this._addToContainedEdges(parentNode, childNode, edge);
  10404. }
  10405. else {
  10406. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  10407. edge.originalToId.push(childNode.id);
  10408. edge.to = parentNode;
  10409. edge.toId = parentNode.id;
  10410. }
  10411. else { // edge connected to other node with the "from" side
  10412. edge.originalFromId.push(childNode.id);
  10413. edge.from = parentNode;
  10414. edge.fromId = parentNode.id;
  10415. }
  10416. this._addToReroutedEdges(parentNode,childNode,edge);
  10417. }
  10418. },
  10419. _containCircularEdgesFromNode : function(parentNode, childNode) {
  10420. // manage all the edges connected to the child and parent nodes
  10421. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  10422. var edge = parentNode.dynamicEdges[i];
  10423. // handle circular edges
  10424. if (edge.toId == edge.fromId) {
  10425. this._addToContainedEdges(parentNode, childNode, edge);
  10426. }
  10427. }
  10428. },
  10429. /**
  10430. * This adds an edge from the childNode to the rerouted edges of the parent node
  10431. *
  10432. * @param parentNode | Node object
  10433. * @param childNode | Node object
  10434. * @param edge | Edge object
  10435. * @private
  10436. */
  10437. _addToReroutedEdges : function(parentNode, childNode, edge) {
  10438. // create an array object if it does not yet exist for this childNode
  10439. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  10440. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  10441. parentNode.reroutedEdges[childNode.id] = [];
  10442. }
  10443. parentNode.reroutedEdges[childNode.id].push(edge);
  10444. // this edge becomes part of the dynamicEdges of the cluster node
  10445. parentNode.dynamicEdges.push(edge);
  10446. },
  10447. /**
  10448. * This function connects an edge that was connected to a cluster node back to the child node.
  10449. *
  10450. * @param parentNode | Node object
  10451. * @param childNode | Node object
  10452. * @private
  10453. */
  10454. _connectEdgeBackToChild : function(parentNode, childNode) {
  10455. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  10456. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  10457. var edge = parentNode.reroutedEdges[childNode.id][i];
  10458. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  10459. edge.originalFromId.pop();
  10460. edge.fromId = childNode.id;
  10461. edge.from = childNode;
  10462. }
  10463. else {
  10464. edge.originalToId.pop();
  10465. edge.toId = childNode.id;
  10466. edge.to = childNode;
  10467. }
  10468. // append this edge to the list of edges connecting to the childnode
  10469. childNode.dynamicEdges.push(edge);
  10470. // remove the edge from the parent object
  10471. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  10472. if (parentNode.dynamicEdges[j].id == edge.id) {
  10473. parentNode.dynamicEdges.splice(j,1);
  10474. break;
  10475. }
  10476. }
  10477. }
  10478. // remove the entry from the rerouted edges
  10479. delete parentNode.reroutedEdges[childNode.id];
  10480. }
  10481. },
  10482. /**
  10483. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  10484. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  10485. * parentNode
  10486. *
  10487. * @param parentNode | Node object
  10488. * @private
  10489. */
  10490. _validateEdges : function(parentNode) {
  10491. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  10492. var edge = parentNode.dynamicEdges[i];
  10493. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  10494. parentNode.dynamicEdges.splice(i,1);
  10495. }
  10496. }
  10497. },
  10498. /**
  10499. * This function released the contained edges back into the global domain and puts them back into the
  10500. * dynamic edges of both parent and child.
  10501. *
  10502. * @param {Node} parentNode |
  10503. * @param {Node} childNode |
  10504. * @private
  10505. */
  10506. _releaseContainedEdges : function(parentNode, childNode) {
  10507. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  10508. var edge = parentNode.containedEdges[childNode.id][i];
  10509. // put the edge back in the global edges object
  10510. this.edges[edge.id] = edge;
  10511. // put the edge back in the dynamic edges of the child and parent
  10512. childNode.dynamicEdges.push(edge);
  10513. parentNode.dynamicEdges.push(edge);
  10514. }
  10515. // remove the entry from the contained edges
  10516. delete parentNode.containedEdges[childNode.id];
  10517. },
  10518. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  10519. /**
  10520. * This updates the node labels for all nodes (for debugging purposes)
  10521. */
  10522. updateLabels : function() {
  10523. var nodeId;
  10524. // update node labels
  10525. for (nodeId in this.nodes) {
  10526. if (this.nodes.hasOwnProperty(nodeId)) {
  10527. var node = this.nodes[nodeId];
  10528. if (node.clusterSize > 1) {
  10529. node.label = "[".concat(String(node.clusterSize),"]");
  10530. }
  10531. }
  10532. }
  10533. // update node labels
  10534. for (nodeId in this.nodes) {
  10535. if (this.nodes.hasOwnProperty(nodeId)) {
  10536. node = this.nodes[nodeId];
  10537. if (node.clusterSize == 1) {
  10538. if (node.originalLabel !== undefined) {
  10539. node.label = node.originalLabel;
  10540. }
  10541. else {
  10542. node.label = String(node.id);
  10543. }
  10544. }
  10545. }
  10546. }
  10547. /* Debug Override */
  10548. // for (nodeId in this.nodes) {
  10549. // if (this.nodes.hasOwnProperty(nodeId)) {
  10550. // node = this.nodes[nodeId];
  10551. // node.label = String(Math.round(node.width)).concat(":",Math.round(node.width*this.scale));
  10552. // }
  10553. // }
  10554. },
  10555. /**
  10556. * This function determines if the cluster we want to decluster is in the active area
  10557. * this means around the zoom center
  10558. *
  10559. * @param {Node} node
  10560. * @returns {boolean}
  10561. * @private
  10562. */
  10563. _nodeInActiveArea : function(node) {
  10564. return (
  10565. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  10566. &&
  10567. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  10568. )
  10569. },
  10570. /**
  10571. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  10572. * It puts large clusters away from the center and randomizes the order.
  10573. *
  10574. */
  10575. repositionNodes : function() {
  10576. for (var i = 0; i < this.nodeIndices.length; i++) {
  10577. var node = this.nodes[this.nodeIndices[i]];
  10578. if (!node.isFixed()) {
  10579. var radius = this.constants.edges.length * (1 + 0.6*node.clusterSize);
  10580. var angle = 2 * Math.PI * Math.random();
  10581. node.x = radius * Math.cos(angle);
  10582. node.y = radius * Math.sin(angle);
  10583. }
  10584. }
  10585. },
  10586. /**
  10587. * We determine how many connections denote an important hub.
  10588. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  10589. *
  10590. * @private
  10591. */
  10592. _getHubSize : function() {
  10593. var average = 0;
  10594. var averageSquared = 0;
  10595. var hubCounter = 0;
  10596. var largestHub = 0;
  10597. for (var i = 0; i < this.nodeIndices.length; i++) {
  10598. var node = this.nodes[this.nodeIndices[i]];
  10599. if (node.dynamicEdgesLength > largestHub) {
  10600. largestHub = node.dynamicEdgesLength;
  10601. }
  10602. average += node.dynamicEdgesLength;
  10603. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  10604. hubCounter += 1;
  10605. }
  10606. average = average / hubCounter;
  10607. averageSquared = averageSquared / hubCounter;
  10608. var variance = averageSquared - Math.pow(average,2);
  10609. var standardDeviation = Math.sqrt(variance);
  10610. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  10611. // always have at least one to cluster
  10612. if (this.hubThreshold > largestHub) {
  10613. this.hubThreshold = largestHub;
  10614. }
  10615. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  10616. // console.log("hubThreshold:",this.hubThreshold);
  10617. },
  10618. /**
  10619. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  10620. * with this amount we can cluster specifically on these chains.
  10621. *
  10622. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  10623. * @private
  10624. */
  10625. _reduceAmountOfChains : function(fraction) {
  10626. this.hubThreshold = 2;
  10627. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  10628. for (var nodeId in this.nodes) {
  10629. if (this.nodes.hasOwnProperty(nodeId)) {
  10630. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  10631. if (reduceAmount > 0) {
  10632. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  10633. reduceAmount -= 1;
  10634. }
  10635. }
  10636. }
  10637. }
  10638. },
  10639. /**
  10640. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  10641. * with this amount we can cluster specifically on these chains.
  10642. *
  10643. * @private
  10644. */
  10645. _getChainFraction : function() {
  10646. var chains = 0;
  10647. var total = 0;
  10648. for (var nodeId in this.nodes) {
  10649. if (this.nodes.hasOwnProperty(nodeId)) {
  10650. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  10651. chains += 1;
  10652. }
  10653. total += 1;
  10654. }
  10655. }
  10656. return chains/total;
  10657. }
  10658. };
  10659. var SelectionMixin = {
  10660. /**
  10661. * This function can be called from the _doInAllSectors function
  10662. *
  10663. * @param object
  10664. * @param overlappingNodes
  10665. * @private
  10666. */
  10667. _getNodesOverlappingWith : function(object, overlappingNodes) {
  10668. var nodes = this.nodes;
  10669. for (var nodeId in nodes) {
  10670. if (nodes.hasOwnProperty(nodeId)) {
  10671. if (nodes[nodeId].isOverlappingWith(object)) {
  10672. overlappingNodes.push(nodeId);
  10673. }
  10674. }
  10675. }
  10676. },
  10677. /**
  10678. * retrieve all nodes overlapping with given object
  10679. * @param {Object} object An object with parameters left, top, right, bottom
  10680. * @return {Number[]} An array with id's of the overlapping nodes
  10681. * @private
  10682. */
  10683. _getAllNodesOverlappingWith : function (object) {
  10684. var overlappingNodes = [];
  10685. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  10686. return overlappingNodes;
  10687. },
  10688. /**
  10689. * retrieve all nodes in the navigationUI overlapping with given object
  10690. * @param {Object} object An object with parameters left, top, right, bottom
  10691. * @return {Number[]} An array with id's of the overlapping nodes
  10692. * @private
  10693. */
  10694. _getAllUINodesOverlappingWith : function (object) {
  10695. var overlappingNodes = [];
  10696. this._doInUISector("_getNodesOverlappingWith",object,overlappingNodes);
  10697. return overlappingNodes;
  10698. },
  10699. /**
  10700. * Return a position object in canvasspace from a single point in screenspace
  10701. *
  10702. * @param pointer
  10703. * @returns {{left: number, top: number, right: number, bottom: number}}
  10704. * @private
  10705. */
  10706. _pointerToPositionObject : function(pointer) {
  10707. var x = this._canvasToX(pointer.x);
  10708. var y = this._canvasToY(pointer.y);
  10709. return {left: x,
  10710. top: y,
  10711. right: x,
  10712. bottom: y};
  10713. },
  10714. /**
  10715. * Return a position object in canvasspace from a single point in screenspace
  10716. *
  10717. * @param pointer
  10718. * @returns {{left: number, top: number, right: number, bottom: number}}
  10719. * @private
  10720. */
  10721. _pointerToScreenPositionObject : function(pointer) {
  10722. var x = pointer.x;
  10723. var y = pointer.y;
  10724. return {left: x,
  10725. top: y,
  10726. right: x,
  10727. bottom: y};
  10728. },
  10729. /**
  10730. * Get the top navigationUI node at the a specific point (like a click)
  10731. *
  10732. * @param {{x: Number, y: Number}} pointer
  10733. * @return {Node | null} node
  10734. * @private
  10735. */
  10736. _getUINodeAt : function (pointer) {
  10737. var screenPositionObject = this._pointerToScreenPositionObject(pointer);
  10738. var overlappingNodes = this._getAllUINodesOverlappingWith(screenPositionObject);
  10739. if (overlappingNodes.length > 0) {
  10740. return this.sectors["navigationUI"]["nodes"][overlappingNodes[overlappingNodes.length - 1]];
  10741. }
  10742. else {
  10743. return null;
  10744. }
  10745. },
  10746. /**
  10747. * Get the top node at the a specific point (like a click)
  10748. *
  10749. * @param {{x: Number, y: Number}} pointer
  10750. * @return {Node | null} node
  10751. * @private
  10752. */
  10753. _getNodeAt : function (pointer) {
  10754. // we first check if this is an navigationUI element
  10755. var positionObject = this._pointerToPositionObject(pointer);
  10756. overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  10757. // if there are overlapping nodes, select the last one, this is the
  10758. // one which is drawn on top of the others
  10759. if (overlappingNodes.length > 0) {
  10760. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  10761. }
  10762. else {
  10763. return null;
  10764. }
  10765. },
  10766. /**
  10767. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  10768. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  10769. *
  10770. * @param pointer
  10771. * @returns {null}
  10772. * @private
  10773. */
  10774. _getEdgeAt : function(pointer) {
  10775. return null;
  10776. },
  10777. /**
  10778. * Add object to the selection array. The this.selection id array may not be needed.
  10779. *
  10780. * @param obj
  10781. * @private
  10782. */
  10783. _addToSelection : function(obj) {
  10784. this.selection.push(obj.id);
  10785. this.selectionObj[obj.id] = obj;
  10786. },
  10787. /**
  10788. * Remove a single option from selection.
  10789. *
  10790. * @param obj
  10791. * @private
  10792. */
  10793. _removeFromSelection : function(obj) {
  10794. for (var i = 0; i < this.selection.length; i++) {
  10795. if (obj.id == this.selection[i]) {
  10796. this.selection.splice(i,1);
  10797. break;
  10798. }
  10799. }
  10800. delete this.selectionObj[obj.id];
  10801. },
  10802. /**
  10803. * Unselect all. The selectionObj is useful for this.
  10804. *
  10805. * @param {Boolean} [doNotTrigger] | ignore trigger
  10806. * @private
  10807. */
  10808. _unselectAll : function(doNotTrigger) {
  10809. if (doNotTrigger === undefined) {
  10810. doNotTrigger = false;
  10811. }
  10812. this.selection = [];
  10813. for (var objId in this.selectionObj) {
  10814. if (this.selectionObj.hasOwnProperty(objId)) {
  10815. this.selectionObj[objId].unselect();
  10816. }
  10817. }
  10818. this.selectionObj = {};
  10819. if (doNotTrigger == false) {
  10820. this._trigger('select');
  10821. }
  10822. },
  10823. /**
  10824. * Check if anything is selected
  10825. *
  10826. * @returns {boolean}
  10827. * @private
  10828. */
  10829. _selectionIsEmpty : function() {
  10830. if (this.selection.length == 0) {
  10831. return true;
  10832. }
  10833. else {
  10834. return false;
  10835. }
  10836. },
  10837. /**
  10838. * This is called when someone clicks on a node. either select or deselect it.
  10839. * If there is an existing selection and we don't want to append to it, clear the existing selection
  10840. *
  10841. * @param {Node} node
  10842. * @param {Boolean} append
  10843. * @param {Boolean} [doNotTrigger] | ignore trigger
  10844. * @private
  10845. */
  10846. _selectNode : function(node, append, doNotTrigger) {
  10847. if (doNotTrigger === undefined) {
  10848. doNotTrigger = false;
  10849. }
  10850. if (this._selectionIsEmpty() == false && append == false) {
  10851. this._unselectAll(true);
  10852. }
  10853. if (node.selected == false) {
  10854. node.select();
  10855. this._addToSelection(node);
  10856. }
  10857. else {
  10858. node.unselect();
  10859. this._removeFromSelection(node);
  10860. }
  10861. if (doNotTrigger == false) {
  10862. this._trigger('select');
  10863. }
  10864. },
  10865. /**
  10866. * handles the selection part of the touch, only for navigationUI elements;
  10867. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  10868. * This is the most responsive solution
  10869. *
  10870. * @param {Object} pointer
  10871. * @private
  10872. */
  10873. _handleTouch : function(pointer) {
  10874. if (this.constants.navigationUI.enabled == true) {
  10875. var node = this._getUINodeAt(pointer);
  10876. if (node != null) {
  10877. if (this[node.triggerFunction] !== undefined) {
  10878. this[node.triggerFunction]();
  10879. }
  10880. }
  10881. }
  10882. },
  10883. /**
  10884. * handles the selection part of the tap;
  10885. *
  10886. * @param {Object} pointer
  10887. * @private
  10888. */
  10889. _handleTap : function(pointer) {
  10890. var node = this._getNodeAt(pointer);
  10891. if (node != null) {
  10892. this._selectNode(node,false);
  10893. }
  10894. else {
  10895. this._unselectAll();
  10896. }
  10897. this._redraw();
  10898. },
  10899. /**
  10900. * handles the selection part of the double tap and opens a cluster if needed
  10901. *
  10902. * @param {Object} pointer
  10903. * @private
  10904. */
  10905. _handleDoubleTap : function(pointer) {
  10906. var node = this._getNodeAt(pointer);
  10907. if (node != null && node !== undefined) {
  10908. // we reset the areaCenter here so the opening of the node will occur
  10909. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  10910. "y" : this._canvasToY(pointer.y)};
  10911. this.openCluster(node);
  10912. }
  10913. },
  10914. /**
  10915. * Handle the onHold selection part
  10916. *
  10917. * @param pointer
  10918. * @private
  10919. */
  10920. _handleOnHold : function(pointer) {
  10921. var node = this._getNodeAt(pointer);
  10922. if (node != null) {
  10923. this._selectNode(node,true);
  10924. }
  10925. this._redraw();
  10926. },
  10927. /**
  10928. * handle the onRelease event. These functions are here for the navigationUI module.
  10929. *
  10930. * @private
  10931. */
  10932. _handleOnRelease : function() {
  10933. this.xIncrement = 0;
  10934. this.yIncrement = 0;
  10935. this.zoomIncrement = 0;
  10936. this._unHighlightAll();
  10937. },
  10938. /**
  10939. *
  10940. * retrieve the currently selected nodes
  10941. * @return {Number[] | String[]} selection An array with the ids of the
  10942. * selected nodes.
  10943. */
  10944. getSelection : function() {
  10945. return this.selection.concat([]);
  10946. },
  10947. /**
  10948. *
  10949. * retrieve the currently selected nodes as objects
  10950. * @return {Objects} selection An array with the ids of the
  10951. * selected nodes.
  10952. */
  10953. getSelectionObjects : function() {
  10954. return this.selectionObj;
  10955. },
  10956. /**
  10957. * // TODO: rework this function, it is from the old system
  10958. *
  10959. * select zero or more nodes
  10960. * @param {Number[] | String[]} selection An array with the ids of the
  10961. * selected nodes.
  10962. */
  10963. setSelection : function(selection) {
  10964. var i, iMax, id;
  10965. if (!selection || (selection.length == undefined))
  10966. throw 'Selection must be an array with ids';
  10967. // first unselect any selected node
  10968. this._unselectAll(true);
  10969. for (i = 0, iMax = selection.length; i < iMax; i++) {
  10970. id = selection[i];
  10971. var node = this.nodes[id];
  10972. if (!node) {
  10973. throw new RangeError('Node with id "' + id + '" not found');
  10974. }
  10975. this._selectNode(node,true,true);
  10976. }
  10977. this.redraw();
  10978. },
  10979. /**
  10980. * TODO: rework this function, it is from the old system
  10981. *
  10982. * Validate the selection: remove ids of nodes which no longer exist
  10983. * @private
  10984. */
  10985. _updateSelection : function () {
  10986. var i = 0;
  10987. while (i < this.selection.length) {
  10988. var nodeId = this.selection[i];
  10989. if (!this.nodes.hasOwnProperty(nodeId)) {
  10990. this.selection.splice(i, 1);
  10991. delete this.selectionObj[nodeId];
  10992. }
  10993. else {
  10994. i++;
  10995. }
  10996. }
  10997. }
  10998. /**
  10999. * Unselect selected nodes. If no selection array is provided, all nodes
  11000. * are unselected
  11001. * @param {Object[]} selection Array with selection objects, each selection
  11002. * object has a parameter row. Optional
  11003. * @param {Boolean} triggerSelect If true (default), the select event
  11004. * is triggered when nodes are unselected
  11005. * @return {Boolean} changed True if the selection is changed
  11006. * @private
  11007. */
  11008. /* _unselectNodes : function(selection, triggerSelect) {
  11009. var changed = false;
  11010. var i, iMax, id;
  11011. if (selection) {
  11012. // remove provided selections
  11013. for (i = 0, iMax = selection.length; i < iMax; i++) {
  11014. id = selection[i];
  11015. if (this.nodes.hasOwnProperty(id)) {
  11016. this.nodes[id].unselect();
  11017. }
  11018. var j = 0;
  11019. while (j < this.selection.length) {
  11020. if (this.selection[j] == id) {
  11021. this.selection.splice(j, 1);
  11022. changed = true;
  11023. }
  11024. else {
  11025. j++;
  11026. }
  11027. }
  11028. }
  11029. }
  11030. else if (this.selection && this.selection.length) {
  11031. // remove all selections
  11032. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  11033. id = this.selection[i];
  11034. if (this.nodes.hasOwnProperty(id)) {
  11035. this.nodes[id].unselect();
  11036. }
  11037. changed = true;
  11038. }
  11039. this.selection = [];
  11040. }
  11041. if (changed && (triggerSelect == true || triggerSelect == undefined)) {
  11042. // fire the select event
  11043. this._trigger('select');
  11044. }
  11045. return changed;
  11046. },
  11047. */
  11048. /**
  11049. * select all nodes on given location x, y
  11050. * @param {Array} selection an array with node ids
  11051. * @param {boolean} append If true, the new selection will be appended to the
  11052. * current selection (except for duplicate entries)
  11053. * @return {Boolean} changed True if the selection is changed
  11054. * @private
  11055. */
  11056. /* _selectNodes : function(selection, append) {
  11057. var changed = false;
  11058. var i, iMax;
  11059. // TODO: the selectNodes method is a little messy, rework this
  11060. // check if the current selection equals the desired selection
  11061. var selectionAlreadyThere = true;
  11062. if (selection.length != this.selection.length) {
  11063. selectionAlreadyThere = false;
  11064. }
  11065. else {
  11066. for (i = 0, iMax = Math.min(selection.length, this.selection.length); i < iMax; i++) {
  11067. if (selection[i] != this.selection[i]) {
  11068. selectionAlreadyThere = false;
  11069. break;
  11070. }
  11071. }
  11072. }
  11073. if (selectionAlreadyThere) {
  11074. return changed;
  11075. }
  11076. if (append == undefined || append == false) {
  11077. // first deselect any selected node
  11078. var triggerSelect = false;
  11079. changed = this._unselectNodes(undefined, triggerSelect);
  11080. }
  11081. for (i = 0, iMax = selection.length; i < iMax; i++) {
  11082. // add each of the new selections, but only when they are not duplicate
  11083. var id = selection[i];
  11084. var isDuplicate = (this.selection.indexOf(id) != -1);
  11085. if (!isDuplicate) {
  11086. this.nodes[id].select();
  11087. this.selection.push(id);
  11088. changed = true;
  11089. }
  11090. }
  11091. if (changed) {
  11092. // fire the select event
  11093. this._trigger('select');
  11094. }
  11095. return changed;
  11096. },
  11097. */
  11098. };
  11099. /**
  11100. * Created by Alex on 1/22/14.
  11101. */
  11102. var UIMixin = {
  11103. /**
  11104. * This function moves the navigationUI if the canvas size has been changed. If the arugments
  11105. * verticaAlignTop and horizontalAlignLeft are false, the correction will be made
  11106. *
  11107. * @private
  11108. */
  11109. _relocateUI : function() {
  11110. if (this.sectors !== undefined) {
  11111. var xOffset = this.UIclientWidth - this.frame.canvas.clientWidth;
  11112. var yOffset = this.UIclientHeight - this.frame.canvas.clientHeight;
  11113. this.UIclientWidth = this.frame.canvas.clientWidth;
  11114. this.UIclientHeight = this.frame.canvas.clientHeight;
  11115. var node = null;
  11116. for (var nodeId in this.sectors["navigationUI"]["nodes"]) {
  11117. if (this.sectors["navigationUI"]["nodes"].hasOwnProperty(nodeId)) {
  11118. node = this.sectors["navigationUI"]["nodes"][nodeId];
  11119. if (!node.horizontalAlignLeft) {
  11120. node.x -= xOffset;
  11121. }
  11122. if (!node.verticalAlignTop) {
  11123. node.y -= yOffset;
  11124. }
  11125. }
  11126. }
  11127. }
  11128. },
  11129. /**
  11130. * Creation of the navigationUI nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  11131. * they have a triggerFunction which is called on click. If the position of the navigationUI is dependent
  11132. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  11133. * This means that the location will be corrected by the _relocateUI function on a size change of the canvas.
  11134. *
  11135. * @private
  11136. */
  11137. _loadUIElements : function() {
  11138. var DIR = this.constants.navigationUI.iconPath;
  11139. this.UIclientWidth = this.frame.canvas.clientWidth;
  11140. this.UIclientHeight = this.frame.canvas.clientHeight;
  11141. if (this.UIclientWidth === undefined) {
  11142. this.UIclientWidth = 0;
  11143. this.UIclientHeight = 0;
  11144. }
  11145. var offset = 15;
  11146. var intermediateOffset = 7;
  11147. var UINodes = [
  11148. {id: 'UI_up', shape: 'image', image: DIR + 'uparrow.png', triggerFunction: "_moveUp",
  11149. verticalAlignTop: false, x: 45 + offset + intermediateOffset, y: this.UIclientHeight - 45 - offset - intermediateOffset},
  11150. {id: 'UI_down', shape: 'image', image: DIR + 'downarrow.png', triggerFunction: "_moveDown",
  11151. verticalAlignTop: false, x: 45 + offset + intermediateOffset, y: this.UIclientHeight - 15 - offset},
  11152. {id: 'UI_left', shape: 'image', image: DIR + 'leftarrow.png', triggerFunction: "_moveLeft",
  11153. verticalAlignTop: false, x: 15 + offset, y: this.UIclientHeight - 15 - offset},
  11154. {id: 'UI_right', shape: 'image', image: DIR + 'rightarrow.png',triggerFunction: "_moveRight",
  11155. verticalAlignTop: false, x: 75 + offset + 2 * intermediateOffset, y: this.UIclientHeight - 15 - offset},
  11156. {id: 'UI_plus', shape: 'image', image: DIR + 'plus.png', triggerFunction: "_zoomIn",
  11157. verticalAlignTop: false, horizontalAlignLeft: false,
  11158. x: this.UIclientWidth - 45 - offset - intermediateOffset, y: this.UIclientHeight - 15 - offset},
  11159. {id: 'UI_min', shape: 'image', image: DIR + 'minus.png', triggerFunction: "_zoomOut",
  11160. verticalAlignTop: false, horizontalAlignLeft: false,
  11161. x: this.UIclientWidth - 15 - offset, y: this.UIclientHeight - 15 - offset},
  11162. {id: 'UI_zoomExtends', shape: 'image', image: DIR + 'zoomExtends.png', triggerFunction: "zoomToFit",
  11163. verticalAlignTop: false, horizontalAlignLeft: false,
  11164. x: this.UIclientWidth - 15 - offset, y: this.UIclientHeight - 45 - offset - intermediateOffset}
  11165. ];
  11166. var nodeObj = null;
  11167. for (var i = 0; i < UINodes.length; i++) {
  11168. nodeObj = this.sectors["navigationUI"]['nodes'];
  11169. nodeObj[UINodes[i]['id']] = new Node(UINodes[i], this.images, this.groups, this.constants);
  11170. }
  11171. },
  11172. /**
  11173. * By setting the clustersize to be larger than 1, we use the clustering drawing method
  11174. * to illustrate the buttons are presed. We call this highlighting.
  11175. *
  11176. * @param {String} elementId
  11177. * @private
  11178. */
  11179. _highlightUIElement : function(elementId) {
  11180. if (this.sectors["navigationUI"]["nodes"].hasOwnProperty(elementId)) {
  11181. this.sectors["navigationUI"]["nodes"][elementId].clusterSize = 2;
  11182. }
  11183. },
  11184. /**
  11185. * Reverting back to a normal button
  11186. *
  11187. * @param {String} elementId
  11188. * @private
  11189. */
  11190. _unHighlightUIElement : function(elementId) {
  11191. if (this.sectors["navigationUI"]["nodes"].hasOwnProperty(elementId)) {
  11192. this.sectors["navigationUI"]["nodes"][elementId].clusterSize = 1;
  11193. }
  11194. },
  11195. /**
  11196. * un-highlight (for lack of a better term) all navigationUI elements
  11197. * @private
  11198. */
  11199. _unHighlightAll : function() {
  11200. for (var nodeId in this.sectors['navigationUI']['nodes']) {
  11201. this._unHighlightUIElement(nodeId);
  11202. }
  11203. },
  11204. _preventDefault : function(event) {
  11205. if (event !== undefined) {
  11206. if (event.preventDefault) {
  11207. event.preventDefault();
  11208. } else {
  11209. event.returnValue = false;
  11210. }
  11211. }
  11212. },
  11213. /**
  11214. * move the screen up
  11215. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  11216. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  11217. * To avoid this behaviour, we do the translation in the start loop.
  11218. *
  11219. * @private
  11220. */
  11221. _moveUp : function(event) {
  11222. this._highlightUIElement("UI_up");
  11223. this.yIncrement = this.constants.keyboardNavigation.speed.y;
  11224. this.start(); // if there is no node movement, the calculation wont be done
  11225. this._preventDefault(event);
  11226. },
  11227. /**
  11228. * move the screen down
  11229. * @private
  11230. */
  11231. _moveDown : function(event) {
  11232. this._highlightUIElement("UI_down");
  11233. this.yIncrement = -this.constants.keyboardNavigation.speed.y;
  11234. this.start(); // if there is no node movement, the calculation wont be done
  11235. this._preventDefault(event);
  11236. },
  11237. /**
  11238. * move the screen left
  11239. * @private
  11240. */
  11241. _moveLeft : function(event) {
  11242. this._highlightUIElement("UI_left");
  11243. this.xIncrement = this.constants.keyboardNavigation.speed.x;
  11244. this.start(); // if there is no node movement, the calculation wont be done
  11245. this._preventDefault(event);
  11246. },
  11247. /**
  11248. * move the screen right
  11249. * @private
  11250. */
  11251. _moveRight : function(event) {
  11252. this._highlightUIElement("UI_right");
  11253. this.xIncrement = -this.constants.keyboardNavigation.speed.y;
  11254. this.start(); // if there is no node movement, the calculation wont be done
  11255. this._preventDefault(event);
  11256. },
  11257. /**
  11258. * Zoom in, using the same method as the movement.
  11259. * @private
  11260. */
  11261. _zoomIn : function(event) {
  11262. this._highlightUIElement("UI_plus");
  11263. this.zoomIncrement = this.constants.keyboardNavigation.speed.zoom;
  11264. this.start(); // if there is no node movement, the calculation wont be done
  11265. this._preventDefault(event);
  11266. },
  11267. /**
  11268. * Zoom out
  11269. * @private
  11270. */
  11271. _zoomOut : function() {
  11272. this._highlightUIElement("UI_min");
  11273. this.zoomIncrement = -this.constants.keyboardNavigation.speed.zoom;
  11274. this.start(); // if there is no node movement, the calculation wont be done
  11275. this._preventDefault(event);
  11276. },
  11277. /**
  11278. * Stop zooming and unhighlight the zoom controls
  11279. * @private
  11280. */
  11281. _stopZoom : function() {
  11282. this._unHighlightUIElement("UI_plus");
  11283. this._unHighlightUIElement("UI_min");
  11284. this.zoomIncrement = 0;
  11285. },
  11286. /**
  11287. * Stop moving in the Y direction and unHighlight the up and down
  11288. * @private
  11289. */
  11290. _yStopMoving : function() {
  11291. this._unHighlightUIElement("UI_up");
  11292. this._unHighlightUIElement("UI_down");
  11293. this.yIncrement = 0;
  11294. },
  11295. /**
  11296. * Stop moving in the X direction and unHighlight left and right.
  11297. * @private
  11298. */
  11299. _xStopMoving : function() {
  11300. this._unHighlightUIElement("UI_left");
  11301. this._unHighlightUIElement("UI_right");
  11302. this.xIncrement = 0;
  11303. }
  11304. };
  11305. /**
  11306. * @constructor Graph
  11307. * Create a graph visualization, displaying nodes and edges.
  11308. *
  11309. * @param {Element} container The DOM element in which the Graph will
  11310. * be created. Normally a div element.
  11311. * @param {Object} data An object containing parameters
  11312. * {Array} nodes
  11313. * {Array} edges
  11314. * @param {Object} options Options
  11315. */
  11316. function Graph (container, data, options) {
  11317. // create variables and set default values
  11318. this.containerElement = container;
  11319. this.width = '100%';
  11320. this.height = '100%';
  11321. // to give everything a nice fluidity, we seperate the rendering and calculating of the forces
  11322. this.renderRefreshRate = 60; // hz (fps)
  11323. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  11324. this.stabilize = true; // stabilize before displaying the graph
  11325. this.selectable = true;
  11326. this.forceFactor = 50000;
  11327. // set constant values
  11328. this.constants = {
  11329. nodes: {
  11330. radiusMin: 5,
  11331. radiusMax: 20,
  11332. radius: 5,
  11333. distance: 100, // px
  11334. shape: 'ellipse',
  11335. image: undefined,
  11336. widthMin: 16, // px
  11337. widthMax: 64, // px
  11338. fontColor: 'black',
  11339. fontSize: 14, // px
  11340. //fontFace: verdana,
  11341. fontFace: 'arial',
  11342. color: {
  11343. border: '#2B7CE9',
  11344. background: '#97C2FC',
  11345. highlight: {
  11346. border: '#2B7CE9',
  11347. background: '#D2E5FF'
  11348. }
  11349. },
  11350. borderColor: '#2B7CE9',
  11351. backgroundColor: '#97C2FC',
  11352. highlightColor: '#D2E5FF',
  11353. group: undefined
  11354. },
  11355. edges: {
  11356. widthMin: 1,
  11357. widthMax: 15,
  11358. width: 1,
  11359. style: 'line',
  11360. color: '#343434',
  11361. fontColor: '#343434',
  11362. fontSize: 14, // px
  11363. fontFace: 'arial',
  11364. //distance: 100, //px
  11365. length: 100, // px
  11366. dash: {
  11367. length: 10,
  11368. gap: 5,
  11369. altLength: undefined
  11370. }
  11371. },
  11372. clustering: { // Per Node in Cluster = PNiC
  11373. enabled: false, // (Boolean) | global on/off switch for clustering.
  11374. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  11375. clusterThreshold:500, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than this. If it is, cluster until reduced to reduceToNodes
  11376. reduceToNodes:300, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than clusterThreshold. If it is, cluster until reduced to this
  11377. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  11378. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  11379. sectorThreshold: 50, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  11380. 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.
  11381. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  11382. forceAmplification: 0.6, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  11383. distanceAmplification: 0.2, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  11384. edgeGrowth: 11, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  11385. nodeScaling: {width: 10, // (px PNiC) | growth of the width per node in cluster.
  11386. height: 10, // (px PNiC) | growth of the height per node in cluster.
  11387. radius: 10}, // (px PNiC) | growth of the radius per node in cluster.
  11388. activeAreaBoxSize: 100, // (px) | box area around the curser where clusters are popped open.
  11389. massTransferCoefficient: 1 // (multiplier) | parent.mass += massTransferCoefficient * child.mass
  11390. },
  11391. navigationUI: {
  11392. enabled: false,
  11393. iconPath: this._getIconURL()
  11394. },
  11395. keyboardNavigation: {
  11396. enabled: false,
  11397. speed: {x: 10, y: 10, zoom: 0.02}
  11398. },
  11399. minVelocity: 2, // px/s
  11400. maxIterations: 1000 // maximum number of iteration to stabilize
  11401. };
  11402. // Node variables
  11403. this.groups = new Groups(); // object with groups
  11404. this.images = new Images(); // object with images
  11405. this.images.setOnloadCallback(function () {
  11406. graph._redraw();
  11407. });
  11408. // navigationUI variables
  11409. this.xIncrement = 0;
  11410. this.yIncrement = 0;
  11411. this.zoomIncrement = 0;
  11412. // create a frame and canvas
  11413. this._create();
  11414. // load the sector system. (mandatory, fully integrated with Graph)
  11415. this._loadSectorSystem();
  11416. // apply options
  11417. this.setOptions(options);
  11418. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  11419. this._loadClusterSystem();
  11420. // load the selection system. (mandatory, required by Graph)
  11421. this._loadSelectionSystem();
  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. this.lastPointerPosition = {"x": 0,"y": 0}; // this is used for keyboard navigation
  11434. // TODO: create a counter to keep track on the number of nodes having values
  11435. // TODO: create a counter to keep track on the number of nodes currently moving
  11436. // TODO: create a counter to keep track on the number of edges having values
  11437. this.nodesData = null; // A DataSet or DataView
  11438. this.edgesData = null; // A DataSet or DataView
  11439. // create event listeners used to subscribe on the DataSets of the nodes and edges
  11440. var me = this;
  11441. this.nodesListeners = {
  11442. 'add': function (event, params) {
  11443. me._addNodes(params.items);
  11444. me.start();
  11445. },
  11446. 'update': function (event, params) {
  11447. me._updateNodes(params.items);
  11448. me.start();
  11449. },
  11450. 'remove': function (event, params) {
  11451. me._removeNodes(params.items);
  11452. me.start();
  11453. }
  11454. };
  11455. this.edgesListeners = {
  11456. 'add': function (event, params) {
  11457. me._addEdges(params.items);
  11458. me.start();
  11459. },
  11460. 'update': function (event, params) {
  11461. me._updateEdges(params.items);
  11462. me.start();
  11463. },
  11464. 'remove': function (event, params) {
  11465. me._removeEdges(params.items);
  11466. me.start();
  11467. }
  11468. };
  11469. // properties of the data
  11470. this.moving = false; // True if any of the nodes have an undefined position
  11471. this.timer = undefined;
  11472. // load data (the disable start variable will be the same as the enabled clustering)
  11473. this.setData(data,this.constants.clustering.enabled);
  11474. // zoom so all data will fit on the screen
  11475. this.zoomToFit(true);
  11476. // if clustering is disabled, the simulation will have started in the setData function
  11477. if (this.constants.clustering.enabled) {
  11478. this.startWithClustering();
  11479. }
  11480. }
  11481. /**
  11482. * get the URL where the UI icons are located
  11483. *
  11484. * @returns {string}
  11485. * @private
  11486. */
  11487. Graph.prototype._getIconURL = function() {
  11488. var scripts = document.getElementsByTagName( 'script' );
  11489. var scriptNamePosition, srcPosition, imagePath;
  11490. for (var i = 0; i < scripts.length; i++) {
  11491. srcPosition = scripts[i].outerHTML.search("src");
  11492. if (srcPosition != -1) {
  11493. scriptNamePosition = util._getLowestPositiveNumber(scripts[i].outerHTML.search("vis.js"),
  11494. scripts[i].outerHTML.search("vis.min.js"));
  11495. if (scriptNamePosition != -1) {
  11496. imagePath = scripts[i].outerHTML.substring(srcPosition+5,scriptNamePosition).concat("UI_icons/");
  11497. return imagePath;
  11498. }
  11499. }
  11500. }
  11501. };
  11502. /**
  11503. * Find the center position of the graph
  11504. * @private
  11505. */
  11506. Graph.prototype._getRange = function() {
  11507. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11508. for (var i = 0; i < this.nodeIndices.length; i++) {
  11509. node = this.nodes[this.nodeIndices[i]];
  11510. if (minX > (node.x - node.width)) {minX = node.x - node.width;}
  11511. if (maxX < (node.x + node.width)) {maxX = node.x + node.width;}
  11512. if (minY > (node.y - node.height)) {minY = node.y - node.height;}
  11513. if (maxY < (node.y + node.height)) {maxY = node.y + node.height;}
  11514. }
  11515. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  11516. };
  11517. /**
  11518. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  11519. * @returns {{x: number, y: number}}
  11520. * @private
  11521. */
  11522. Graph.prototype._findCenter = function(range) {
  11523. var center = {x: (0.5 * (range.maxX + range.minX)),
  11524. y: (0.5 * (range.maxY + range.minY))};
  11525. return center;
  11526. };
  11527. /**
  11528. * center the graph
  11529. *
  11530. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  11531. */
  11532. Graph.prototype._centerGraph = function(range) {
  11533. var center = this._findCenter(range);
  11534. center.x *= this.scale;
  11535. center.y *= this.scale;
  11536. center.x -= 0.5 * this.frame.canvas.clientWidth;
  11537. center.y -= 0.5 * this.frame.canvas.clientHeight;
  11538. this._setTranslation(-center.x,-center.y); // set at 0,0
  11539. };
  11540. /**
  11541. * This function zooms out to fit all data on screen based on amount of nodes
  11542. *
  11543. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  11544. */
  11545. Graph.prototype.zoomToFit = function(initialZoom) {
  11546. if (initialZoom === undefined) {
  11547. initialZoom = false;
  11548. }
  11549. var numberOfNodes = this.nodeIndices.length;
  11550. var range = this._getRange();
  11551. if (initialZoom == true) {
  11552. if (this.constants.clustering.enabled == true &&
  11553. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  11554. 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.
  11555. }
  11556. else {
  11557. 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.
  11558. }
  11559. }
  11560. else {
  11561. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  11562. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  11563. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  11564. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  11565. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  11566. }
  11567. if (zoomLevel > 1.0) {
  11568. zoomLevel = 1.0;
  11569. }
  11570. this.pinch.mousewheelScale = zoomLevel;
  11571. this._setScale(zoomLevel);
  11572. this._centerGraph(range);
  11573. this.start();
  11574. };
  11575. /**
  11576. * Update the this.nodeIndices with the most recent node index list
  11577. * @private
  11578. */
  11579. Graph.prototype._updateNodeIndexList = function() {
  11580. this._clearNodeIndexList();
  11581. for (var idx in this.nodes) {
  11582. if (this.nodes.hasOwnProperty(idx)) {
  11583. this.nodeIndices.push(idx);
  11584. }
  11585. }
  11586. };
  11587. /**
  11588. * Set nodes and edges, and optionally options as well.
  11589. *
  11590. * @param {Object} data Object containing parameters:
  11591. * {Array | DataSet | DataView} [nodes] Array with nodes
  11592. * {Array | DataSet | DataView} [edges] Array with edges
  11593. * {String} [dot] String containing data in DOT format
  11594. * {Options} [options] Object with options
  11595. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  11596. */
  11597. Graph.prototype.setData = function(data, disableStart) {
  11598. if (disableStart === undefined) {
  11599. disableStart = false;
  11600. }
  11601. if (data && data.dot && (data.nodes || data.edges)) {
  11602. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  11603. ' parameter pair "nodes" and "edges", but not both.');
  11604. }
  11605. // set options
  11606. this.setOptions(data && data.options);
  11607. // set all data
  11608. if (data && data.dot) {
  11609. // parse DOT file
  11610. if(data && data.dot) {
  11611. var dotData = vis.util.DOTToGraph(data.dot);
  11612. this.setData(dotData);
  11613. return;
  11614. }
  11615. }
  11616. else {
  11617. this._setNodes(data && data.nodes);
  11618. this._setEdges(data && data.edges);
  11619. }
  11620. this._putDataInSector();
  11621. if (!disableStart) {
  11622. // find a stable position or start animating to a stable position
  11623. if (this.stabilize) {
  11624. this._doStabilize();
  11625. }
  11626. this.moving = true;
  11627. this.start();
  11628. }
  11629. };
  11630. /**
  11631. * Set options
  11632. * @param {Object} options
  11633. */
  11634. Graph.prototype.setOptions = function (options) {
  11635. if (options) {
  11636. // retrieve parameter values
  11637. if (options.width !== undefined) {this.width = options.width;}
  11638. if (options.height !== undefined) {this.height = options.height;}
  11639. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  11640. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  11641. if (options.clustering) {
  11642. this.constants.clustering.enabled = true;
  11643. for (var prop in options.clustering) {
  11644. if (options.clustering.hasOwnProperty(prop)) {
  11645. this.constants.clustering[prop] = options.clustering[prop];
  11646. }
  11647. }
  11648. }
  11649. else if (options.clustering !== undefined) {
  11650. this.constants.clustering.enabled = false;
  11651. }
  11652. if (options.navigationUI) {
  11653. this.constants.navigationUI.enabled = true;
  11654. for (var prop in options.navigationUI) {
  11655. if (options.navigationUI.hasOwnProperty(prop)) {
  11656. this.constants.navigationUI[prop] = options.navigationUI[prop];
  11657. }
  11658. }
  11659. }
  11660. else if (options.navigationUI !== undefined) {
  11661. this.constants.navigationUI.enabled = false;
  11662. }
  11663. if (options.keyboardNavigation) {
  11664. this.constants.keyboardNavigation.enabled = true;
  11665. for (var prop in options.keyboardNavigation) {
  11666. if (options.keyboardNavigation.hasOwnProperty(prop)) {
  11667. this.constants.keyboardNavigation[prop] = options.keyboardNavigation[prop];
  11668. }
  11669. }
  11670. }
  11671. else if (options.keyboardNavigation !== undefined) {
  11672. this.constants.keyboardNavigation.enabled = false;
  11673. }
  11674. // TODO: work out these options and document them
  11675. if (options.edges) {
  11676. for (prop in options.edges) {
  11677. if (options.edges.hasOwnProperty(prop)) {
  11678. this.constants.edges[prop] = options.edges[prop];
  11679. }
  11680. }
  11681. if (options.edges.length !== undefined &&
  11682. options.nodes && options.nodes.distance === undefined) {
  11683. this.constants.edges.length = options.edges.length;
  11684. this.constants.nodes.distance = options.edges.length * 1.25;
  11685. }
  11686. if (!options.edges.fontColor) {
  11687. this.constants.edges.fontColor = options.edges.color;
  11688. }
  11689. // Added to support dashed lines
  11690. // David Jordan
  11691. // 2012-08-08
  11692. if (options.edges.dash) {
  11693. if (options.edges.dash.length !== undefined) {
  11694. this.constants.edges.dash.length = options.edges.dash.length;
  11695. }
  11696. if (options.edges.dash.gap !== undefined) {
  11697. this.constants.edges.dash.gap = options.edges.dash.gap;
  11698. }
  11699. if (options.edges.dash.altLength !== undefined) {
  11700. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  11701. }
  11702. }
  11703. }
  11704. if (options.nodes) {
  11705. for (prop in options.nodes) {
  11706. if (options.nodes.hasOwnProperty(prop)) {
  11707. this.constants.nodes[prop] = options.nodes[prop];
  11708. }
  11709. }
  11710. if (options.nodes.color) {
  11711. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  11712. }
  11713. /*
  11714. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  11715. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  11716. */
  11717. }
  11718. if (options.groups) {
  11719. for (var groupname in options.groups) {
  11720. if (options.groups.hasOwnProperty(groupname)) {
  11721. var group = options.groups[groupname];
  11722. this.groups.add(groupname, group);
  11723. }
  11724. }
  11725. }
  11726. }
  11727. this.setSize(this.width, this.height);
  11728. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  11729. this._setScale(1);
  11730. // load the navigationUI system.
  11731. this._loadUISystem();
  11732. // bind keys. If disabled, this will not do anything;
  11733. this._createKeyBinds();
  11734. this._redraw();
  11735. };
  11736. /**
  11737. * fire an event
  11738. * @param {String} event The name of an event, for example 'select'
  11739. * @param {Object} params Optional object with event parameters
  11740. * @private
  11741. */
  11742. Graph.prototype._trigger = function (event, params) {
  11743. events.trigger(this, event, params);
  11744. };
  11745. /**
  11746. * Create the main frame for the Graph.
  11747. * This function is executed once when a Graph object is created. The frame
  11748. * contains a canvas, and this canvas contains all objects like the axis and
  11749. * nodes.
  11750. * @private
  11751. */
  11752. Graph.prototype._create = function () {
  11753. // remove all elements from the container element.
  11754. while (this.containerElement.hasChildNodes()) {
  11755. this.containerElement.removeChild(this.containerElement.firstChild);
  11756. }
  11757. this.frame = document.createElement('div');
  11758. this.frame.className = 'graph-frame';
  11759. this.frame.style.position = 'relative';
  11760. this.frame.style.overflow = 'hidden';
  11761. // create the graph canvas (HTML canvas element)
  11762. this.frame.canvas = document.createElement( 'canvas' );
  11763. this.frame.canvas.style.position = 'relative';
  11764. this.frame.appendChild(this.frame.canvas);
  11765. if (!this.frame.canvas.getContext) {
  11766. var noCanvas = document.createElement( 'DIV' );
  11767. noCanvas.style.color = 'red';
  11768. noCanvas.style.fontWeight = 'bold' ;
  11769. noCanvas.style.padding = '10px';
  11770. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  11771. this.frame.canvas.appendChild(noCanvas);
  11772. }
  11773. var me = this;
  11774. this.drag = {};
  11775. this.pinch = {};
  11776. this.hammer = Hammer(this.frame.canvas, {
  11777. prevent_default: true
  11778. });
  11779. this.hammer.on('tap', me._onTap.bind(me) );
  11780. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  11781. this.hammer.on('hold', me._onHold.bind(me) );
  11782. this.hammer.on('pinch', me._onPinch.bind(me) );
  11783. this.hammer.on('touch', me._onTouch.bind(me) );
  11784. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  11785. this.hammer.on('drag', me._onDrag.bind(me) );
  11786. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  11787. this.hammer.on('release', me._onRelease.bind(me) );
  11788. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  11789. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  11790. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  11791. // add the frame to the container element
  11792. this.containerElement.appendChild(this.frame);
  11793. };
  11794. /**
  11795. * Binding the keys for keyboard navigation. These functions are defined in the UIMixin
  11796. * @private
  11797. */
  11798. Graph.prototype._createKeyBinds = function() {
  11799. var me = this;
  11800. this.mousetrap = mousetrap;
  11801. this.mousetrap.reset();
  11802. if (this.constants.keyboardNavigation.enabled == true) {
  11803. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  11804. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  11805. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  11806. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  11807. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  11808. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  11809. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  11810. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  11811. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  11812. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  11813. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  11814. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  11815. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  11816. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  11817. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  11818. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  11819. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  11820. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  11821. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  11822. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  11823. }
  11824. /*
  11825. this.mousetrap.bind("=",this.decreaseClusterLevel.bind(me));
  11826. this.mousetrap.bind("-",this.increaseClusterLevel.bind(me));
  11827. this.mousetrap.bind("s",this.singleStep.bind(me));
  11828. this.mousetrap.bind("h",this.updateClustersDefault.bind(me));
  11829. this.mousetrap.bind("c",this._collapseSector.bind(me));
  11830. this.mousetrap.bind("f",this.toggleFreeze.bind(me));
  11831. */
  11832. }
  11833. /**
  11834. * Get the pointer location from a touch location
  11835. * @param {{pageX: Number, pageY: Number}} touch
  11836. * @return {{x: Number, y: Number}} pointer
  11837. * @private
  11838. */
  11839. Graph.prototype._getPointer = function (touch) {
  11840. return {
  11841. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  11842. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  11843. };
  11844. };
  11845. /**
  11846. * On start of a touch gesture, store the pointer
  11847. * @param event
  11848. * @private
  11849. */
  11850. Graph.prototype._onTouch = function (event) {
  11851. this.drag.pointer = this._getPointer(event.gesture.touches[0]);
  11852. this.drag.pinched = false;
  11853. this.pinch.scale = this._getScale();
  11854. this._handleTouch(this.drag.pointer);
  11855. };
  11856. /**
  11857. * handle drag start event
  11858. * @private
  11859. */
  11860. Graph.prototype._onDragStart = function () {
  11861. var drag = this.drag;
  11862. var node = this._getNodeAt(drag.pointer);
  11863. // note: drag.pointer is set in _onTouch to get the initial touch location
  11864. drag.selection = [];
  11865. drag.translation = this._getTranslation();
  11866. drag.nodeId = null;
  11867. if (node != null) {
  11868. drag.nodeId = node.id;
  11869. // select the clicked node if not yet selected
  11870. if (!node.isSelected()) {
  11871. this._selectNode(node,false);
  11872. }
  11873. // create an array with the selected nodes and their original location and status
  11874. var me = this;
  11875. this.selection.forEach(function (id) {
  11876. var node = me.nodes[id];
  11877. if (node) {
  11878. var s = {
  11879. id: id,
  11880. node: node,
  11881. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  11882. x: node.x,
  11883. y: node.y,
  11884. xFixed: node.xFixed,
  11885. yFixed: node.yFixed
  11886. };
  11887. node.xFixed = true;
  11888. node.yFixed = true;
  11889. drag.selection.push(s);
  11890. }
  11891. });
  11892. }
  11893. };
  11894. /**
  11895. * handle drag event
  11896. * @private
  11897. */
  11898. Graph.prototype._onDrag = function (event) {
  11899. if (this.drag.pinched) {
  11900. return;
  11901. }
  11902. var pointer = this._getPointer(event.gesture.touches[0]);
  11903. var me = this,
  11904. drag = this.drag,
  11905. selection = drag.selection;
  11906. if (selection && selection.length) {
  11907. // calculate delta's and new location
  11908. var deltaX = pointer.x - drag.pointer.x,
  11909. deltaY = pointer.y - drag.pointer.y;
  11910. // update position of all selected nodes
  11911. selection.forEach(function (s) {
  11912. var node = s.node;
  11913. if (!s.xFixed) {
  11914. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  11915. }
  11916. if (!s.yFixed) {
  11917. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  11918. }
  11919. });
  11920. // start animation if not yet running
  11921. if (!this.moving) {
  11922. this.moving = true;
  11923. this.start();
  11924. }
  11925. }
  11926. else {
  11927. // move the graph
  11928. var diffX = pointer.x - this.drag.pointer.x;
  11929. var diffY = pointer.y - this.drag.pointer.y;
  11930. this._setTranslation(
  11931. this.drag.translation.x + diffX,
  11932. this.drag.translation.y + diffY);
  11933. this._redraw();
  11934. this.moved = true;
  11935. }
  11936. };
  11937. /**
  11938. * handle drag start event
  11939. * @private
  11940. */
  11941. Graph.prototype._onDragEnd = function () {
  11942. var selection = this.drag.selection;
  11943. if (selection) {
  11944. selection.forEach(function (s) {
  11945. // restore original xFixed and yFixed
  11946. s.node.xFixed = s.xFixed;
  11947. s.node.yFixed = s.yFixed;
  11948. });
  11949. }
  11950. };
  11951. /**
  11952. * handle tap/click event: select/unselect a node
  11953. * @private
  11954. */
  11955. Graph.prototype._onTap = function (event) {
  11956. var pointer = this._getPointer(event.gesture.touches[0]);
  11957. this._handleTap(pointer);
  11958. };
  11959. /**
  11960. * handle doubletap event
  11961. * @private
  11962. */
  11963. Graph.prototype._onDoubleTap = function (event) {
  11964. var pointer = this._getPointer(event.gesture.touches[0]);
  11965. this._handleDoubleTap(pointer);
  11966. };
  11967. /**
  11968. * handle long tap event: multi select nodes
  11969. * @private
  11970. */
  11971. Graph.prototype._onHold = function (event) {
  11972. var pointer = this._getPointer(event.gesture.touches[0]);
  11973. this._handleOnHold(pointer);
  11974. };
  11975. /**
  11976. * handle the release of the screen
  11977. *
  11978. * @param event
  11979. * @private
  11980. */
  11981. Graph.prototype._onRelease = function (event) {
  11982. this._handleOnRelease();
  11983. };
  11984. /**
  11985. * Handle pinch event
  11986. * @param event
  11987. * @private
  11988. */
  11989. Graph.prototype._onPinch = function (event) {
  11990. var pointer = this._getPointer(event.gesture.center);
  11991. this.drag.pinched = true;
  11992. if (!('scale' in this.pinch)) {
  11993. this.pinch.scale = 1;
  11994. }
  11995. // TODO: enabled moving while pinching?
  11996. var scale = this.pinch.scale * event.gesture.scale;
  11997. this._zoom(scale, pointer)
  11998. };
  11999. /**
  12000. * Zoom the graph in or out
  12001. * @param {Number} scale a number around 1, and between 0.01 and 10
  12002. * @param {{x: Number, y: Number}} pointer
  12003. * @return {Number} appliedScale scale is limited within the boundaries
  12004. * @private
  12005. */
  12006. Graph.prototype._zoom = function(scale, pointer) {
  12007. var scaleOld = this._getScale();
  12008. if (scale < 0.00001) {
  12009. scale = 0.00001;
  12010. }
  12011. if (scale > 10) {
  12012. scale = 10;
  12013. }
  12014. // + this.frame.canvas.clientHeight / 2
  12015. var translation = this._getTranslation();
  12016. var scaleFrac = scale / scaleOld;
  12017. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  12018. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  12019. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  12020. "y" : this._canvasToY(pointer.y)};
  12021. // this.areaCenter = {"x" : pointer.x,"y" : pointer.y };
  12022. // console.log(translation.x,translation.y,pointer.x,pointer.y,scale);
  12023. this.pinch.mousewheelScale = scale;
  12024. this._setScale(scale);
  12025. this._setTranslation(tx, ty);
  12026. this.updateClustersDefault();
  12027. this._redraw();
  12028. return scale;
  12029. };
  12030. /**
  12031. * Event handler for mouse wheel event, used to zoom the timeline
  12032. * See http://adomas.org/javascript-mouse-wheel/
  12033. * https://github.com/EightMedia/hammer.js/issues/256
  12034. * @param {MouseEvent} event
  12035. * @private
  12036. */
  12037. Graph.prototype._onMouseWheel = function(event) {
  12038. // retrieve delta
  12039. var delta = 0;
  12040. if (event.wheelDelta) { /* IE/Opera. */
  12041. delta = event.wheelDelta/120;
  12042. } else if (event.detail) { /* Mozilla case. */
  12043. // In Mozilla, sign of delta is different than in IE.
  12044. // Also, delta is multiple of 3.
  12045. delta = -event.detail/3;
  12046. }
  12047. // If delta is nonzero, handle it.
  12048. // Basically, delta is now positive if wheel was scrolled up,
  12049. // and negative, if wheel was scrolled down.
  12050. if (delta) {
  12051. if (!('mousewheelScale' in this.pinch)) {
  12052. this.pinch.mousewheelScale = 1;
  12053. }
  12054. // calculate the new scale
  12055. var scale = this.pinch.mousewheelScale;
  12056. var zoom = delta / 10;
  12057. if (delta < 0) {
  12058. zoom = zoom / (1 - zoom);
  12059. }
  12060. scale *= (1 + zoom);
  12061. // calculate the pointer location
  12062. var gesture = util.fakeGesture(this, event);
  12063. var pointer = this._getPointer(gesture.center);
  12064. // apply the new scale
  12065. scale = this._zoom(scale, pointer);
  12066. // store the new, applied scale -- this is now done in _zoom
  12067. // this.pinch.mousewheelScale = scale;
  12068. }
  12069. // Prevent default actions caused by mouse wheel.
  12070. event.preventDefault();
  12071. };
  12072. /**
  12073. * Mouse move handler for checking whether the title moves over a node with a title.
  12074. * @param {Event} event
  12075. * @private
  12076. */
  12077. Graph.prototype._onMouseMoveTitle = function (event) {
  12078. var gesture = util.fakeGesture(this, event);
  12079. var pointer = this._getPointer(gesture.center);
  12080. this.lastPointerPosition = pointer;
  12081. // check if the previously selected node is still selected
  12082. if (this.popupNode) {
  12083. this._checkHidePopup(pointer);
  12084. }
  12085. // start a timeout that will check if the mouse is positioned above
  12086. // an element
  12087. var me = this;
  12088. var checkShow = function() {
  12089. me._checkShowPopup(pointer);
  12090. };
  12091. if (this.popupTimer) {
  12092. clearInterval(this.popupTimer); // stop any running calculationTimer
  12093. }
  12094. if (!this.leftButtonDown) {
  12095. this.popupTimer = setTimeout(checkShow, 300);
  12096. }
  12097. };
  12098. /**
  12099. * Check if there is an element on the given position in the graph
  12100. * (a node or edge). If so, and if this element has a title,
  12101. * show a popup window with its title.
  12102. *
  12103. * @param {{x:Number, y:Number}} pointer
  12104. * @private
  12105. */
  12106. Graph.prototype._checkShowPopup = function (pointer) {
  12107. var obj = {
  12108. left: this._canvasToX(pointer.x),
  12109. top: this._canvasToY(pointer.y),
  12110. right: this._canvasToX(pointer.x),
  12111. bottom: this._canvasToY(pointer.y)
  12112. };
  12113. var id;
  12114. var lastPopupNode = this.popupNode;
  12115. if (this.popupNode == undefined) {
  12116. // search the nodes for overlap, select the top one in case of multiple nodes
  12117. var nodes = this.nodes;
  12118. for (id in nodes) {
  12119. if (nodes.hasOwnProperty(id)) {
  12120. var node = nodes[id];
  12121. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  12122. this.popupNode = node;
  12123. break;
  12124. }
  12125. }
  12126. }
  12127. }
  12128. if (this.popupNode === undefined) {
  12129. // search the edges for overlap
  12130. var edges = this.edges;
  12131. for (id in edges) {
  12132. if (edges.hasOwnProperty(id)) {
  12133. var edge = edges[id];
  12134. if (edge.connected && (edge.getTitle() !== undefined) &&
  12135. edge.isOverlappingWith(obj)) {
  12136. this.popupNode = edge;
  12137. break;
  12138. }
  12139. }
  12140. }
  12141. }
  12142. if (this.popupNode) {
  12143. // show popup message window
  12144. if (this.popupNode != lastPopupNode) {
  12145. var me = this;
  12146. if (!me.popup) {
  12147. me.popup = new Popup(me.frame);
  12148. }
  12149. // adjust a small offset such that the mouse cursor is located in the
  12150. // bottom left location of the popup, and you can easily move over the
  12151. // popup area
  12152. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  12153. me.popup.setText(me.popupNode.getTitle());
  12154. me.popup.show();
  12155. }
  12156. }
  12157. else {
  12158. if (this.popup) {
  12159. this.popup.hide();
  12160. }
  12161. }
  12162. };
  12163. /**
  12164. * Check if the popup must be hided, which is the case when the mouse is no
  12165. * longer hovering on the object
  12166. * @param {{x:Number, y:Number}} pointer
  12167. * @private
  12168. */
  12169. Graph.prototype._checkHidePopup = function (pointer) {
  12170. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  12171. this.popupNode = undefined;
  12172. if (this.popup) {
  12173. this.popup.hide();
  12174. }
  12175. }
  12176. };
  12177. /**
  12178. * Temporary method to test calculating a hub value for the nodes
  12179. * @param {number} level Maximum number edges between two nodes in order
  12180. * to call them connected. Optional, 1 by default
  12181. * @return {Number[]} connectioncount array with the connection count
  12182. * for each node
  12183. * @private
  12184. */
  12185. Graph.prototype._getConnectionCount = function(level) {
  12186. if (level == undefined) {
  12187. level = 1;
  12188. }
  12189. // get the nodes connected to given nodes
  12190. function getConnectedNodes(nodes) {
  12191. var connectedNodes = [];
  12192. for (var j = 0, jMax = nodes.length; j < jMax; j++) {
  12193. var node = nodes[j];
  12194. // find all nodes connected to this node
  12195. var edges = node.edges;
  12196. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  12197. var edge = edges[i];
  12198. var other = null;
  12199. // check if connected
  12200. if (edge.from == node)
  12201. other = edge.to;
  12202. else if (edge.to == node)
  12203. other = edge.from;
  12204. // check if the other node is not already in the list with nodes
  12205. var k, kMax;
  12206. if (other) {
  12207. for (k = 0, kMax = nodes.length; k < kMax; k++) {
  12208. if (nodes[k] == other) {
  12209. other = null;
  12210. break;
  12211. }
  12212. }
  12213. }
  12214. if (other) {
  12215. for (k = 0, kMax = connectedNodes.length; k < kMax; k++) {
  12216. if (connectedNodes[k] == other) {
  12217. other = null;
  12218. break;
  12219. }
  12220. }
  12221. }
  12222. if (other)
  12223. connectedNodes.push(other);
  12224. }
  12225. }
  12226. return connectedNodes;
  12227. }
  12228. var connections = [];
  12229. var nodes = this.nodes;
  12230. for (var id in nodes) {
  12231. if (nodes.hasOwnProperty(id)) {
  12232. var c = [nodes[id]];
  12233. for (var l = 0; l < level; l++) {
  12234. c = c.concat(getConnectedNodes(c));
  12235. }
  12236. connections.push(c);
  12237. }
  12238. }
  12239. var hubs = [];
  12240. for (var i = 0, len = connections.length; i < len; i++) {
  12241. hubs.push(connections[i].length);
  12242. }
  12243. return hubs;
  12244. };
  12245. /**
  12246. * Set a new size for the graph
  12247. * @param {string} width Width in pixels or percentage (for example '800px'
  12248. * or '50%')
  12249. * @param {string} height Height in pixels or percentage (for example '400px'
  12250. * or '30%')
  12251. */
  12252. Graph.prototype.setSize = function(width, height) {
  12253. this.frame.style.width = width;
  12254. this.frame.style.height = height;
  12255. this.frame.canvas.style.width = '100%';
  12256. this.frame.canvas.style.height = '100%';
  12257. this.frame.canvas.width = this.frame.canvas.clientWidth;
  12258. this.frame.canvas.height = this.frame.canvas.clientHeight;
  12259. if (this.constants.navigationUI.enabled == true) {
  12260. this._relocateUI();
  12261. }
  12262. };
  12263. /**
  12264. * Set a data set with nodes for the graph
  12265. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  12266. * @private
  12267. */
  12268. Graph.prototype._setNodes = function(nodes) {
  12269. var oldNodesData = this.nodesData;
  12270. if (nodes instanceof DataSet || nodes instanceof DataView) {
  12271. this.nodesData = nodes;
  12272. }
  12273. else if (nodes instanceof Array) {
  12274. this.nodesData = new DataSet();
  12275. this.nodesData.add(nodes);
  12276. }
  12277. else if (!nodes) {
  12278. this.nodesData = new DataSet();
  12279. }
  12280. else {
  12281. throw new TypeError('Array or DataSet expected');
  12282. }
  12283. if (oldNodesData) {
  12284. // unsubscribe from old dataset
  12285. util.forEach(this.nodesListeners, function (callback, event) {
  12286. oldNodesData.unsubscribe(event, callback);
  12287. });
  12288. }
  12289. // remove drawn nodes
  12290. this.nodes = {};
  12291. if (this.nodesData) {
  12292. // subscribe to new dataset
  12293. var me = this;
  12294. util.forEach(this.nodesListeners, function (callback, event) {
  12295. me.nodesData.subscribe(event, callback);
  12296. });
  12297. // draw all new nodes
  12298. var ids = this.nodesData.getIds();
  12299. this._addNodes(ids);
  12300. }
  12301. this._updateSelection();
  12302. };
  12303. /**
  12304. * Add nodes
  12305. * @param {Number[] | String[]} ids
  12306. * @private
  12307. */
  12308. Graph.prototype._addNodes = function(ids) {
  12309. var id;
  12310. for (var i = 0, len = ids.length; i < len; i++) {
  12311. id = ids[i];
  12312. var data = this.nodesData.get(id);
  12313. var node = new Node(data, this.images, this.groups, this.constants);
  12314. this.nodes[id] = node; // note: this may replace an existing node
  12315. if (!node.isFixed()) {
  12316. // TODO: position new nodes in a smarter way!
  12317. var radius = this.constants.edges.length * 2;
  12318. var count = ids.length;
  12319. var angle = 2 * Math.PI * (i / count);
  12320. node.x = radius * Math.cos(angle);
  12321. node.y = radius * Math.sin(angle);
  12322. // note: no not use node.isMoving() here, as that gives the current
  12323. // velocity of the node, which is zero after creation of the node.
  12324. this.moving = true;
  12325. }
  12326. }
  12327. this._updateNodeIndexList();
  12328. this._reconnectEdges();
  12329. this._updateValueRange(this.nodes);
  12330. };
  12331. /**
  12332. * Update existing nodes, or create them when not yet existing
  12333. * @param {Number[] | String[]} ids
  12334. * @private
  12335. */
  12336. Graph.prototype._updateNodes = function(ids) {
  12337. var nodes = this.nodes,
  12338. nodesData = this.nodesData;
  12339. for (var i = 0, len = ids.length; i < len; i++) {
  12340. var id = ids[i];
  12341. var node = nodes[id];
  12342. var data = nodesData.get(id);
  12343. if (node) {
  12344. // update node
  12345. node.setProperties(data, this.constants);
  12346. }
  12347. else {
  12348. // create node
  12349. node = new Node(properties, this.images, this.groups, this.constants);
  12350. nodes[id] = node;
  12351. if (!node.isFixed()) {
  12352. this.moving = true;
  12353. }
  12354. }
  12355. }
  12356. this._updateNodeIndexList();
  12357. this._reconnectEdges();
  12358. this._updateValueRange(nodes);
  12359. };
  12360. /**
  12361. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  12362. * @param {Number[] | String[]} ids
  12363. * @private
  12364. */
  12365. Graph.prototype._removeNodes = function(ids) {
  12366. var nodes = this.nodes;
  12367. for (var i = 0, len = ids.length; i < len; i++) {
  12368. var id = ids[i];
  12369. delete nodes[id];
  12370. }
  12371. this._updateNodeIndexList();
  12372. this._reconnectEdges();
  12373. this._updateSelection();
  12374. this._updateValueRange(nodes);
  12375. };
  12376. /**
  12377. * Load edges by reading the data table
  12378. * @param {Array | DataSet | DataView} edges The data containing the edges.
  12379. * @private
  12380. * @private
  12381. */
  12382. Graph.prototype._setEdges = function(edges) {
  12383. var oldEdgesData = this.edgesData;
  12384. if (edges instanceof DataSet || edges instanceof DataView) {
  12385. this.edgesData = edges;
  12386. }
  12387. else if (edges instanceof Array) {
  12388. this.edgesData = new DataSet();
  12389. this.edgesData.add(edges);
  12390. }
  12391. else if (!edges) {
  12392. this.edgesData = new DataSet();
  12393. }
  12394. else {
  12395. throw new TypeError('Array or DataSet expected');
  12396. }
  12397. if (oldEdgesData) {
  12398. // unsubscribe from old dataset
  12399. util.forEach(this.edgesListeners, function (callback, event) {
  12400. oldEdgesData.unsubscribe(event, callback);
  12401. });
  12402. }
  12403. // remove drawn edges
  12404. this.edges = {};
  12405. if (this.edgesData) {
  12406. // subscribe to new dataset
  12407. var me = this;
  12408. util.forEach(this.edgesListeners, function (callback, event) {
  12409. me.edgesData.subscribe(event, callback);
  12410. });
  12411. // draw all new nodes
  12412. var ids = this.edgesData.getIds();
  12413. this._addEdges(ids);
  12414. }
  12415. this._reconnectEdges();
  12416. };
  12417. /**
  12418. * Add edges
  12419. * @param {Number[] | String[]} ids
  12420. * @private
  12421. */
  12422. Graph.prototype._addEdges = function (ids) {
  12423. var edges = this.edges,
  12424. edgesData = this.edgesData;
  12425. for (var i = 0, len = ids.length; i < len; i++) {
  12426. var id = ids[i];
  12427. var oldEdge = edges[id];
  12428. if (oldEdge) {
  12429. oldEdge.disconnect();
  12430. }
  12431. var data = edgesData.get(id, {"showInternalIds" : true});
  12432. edges[id] = new Edge(data, this, this.constants);
  12433. }
  12434. this.moving = true;
  12435. this._updateValueRange(edges);
  12436. };
  12437. /**
  12438. * Update existing edges, or create them when not yet existing
  12439. * @param {Number[] | String[]} ids
  12440. * @private
  12441. */
  12442. Graph.prototype._updateEdges = function (ids) {
  12443. var edges = this.edges,
  12444. edgesData = this.edgesData;
  12445. for (var i = 0, len = ids.length; i < len; i++) {
  12446. var id = ids[i];
  12447. var data = edgesData.get(id);
  12448. var edge = edges[id];
  12449. if (edge) {
  12450. // update edge
  12451. edge.disconnect();
  12452. edge.setProperties(data, this.constants);
  12453. edge.connect();
  12454. }
  12455. else {
  12456. // create edge
  12457. edge = new Edge(data, this, this.constants);
  12458. this.edges[id] = edge;
  12459. }
  12460. }
  12461. this.moving = true;
  12462. this._updateValueRange(edges);
  12463. };
  12464. /**
  12465. * Remove existing edges. Non existing ids will be ignored
  12466. * @param {Number[] | String[]} ids
  12467. * @private
  12468. */
  12469. Graph.prototype._removeEdges = function (ids) {
  12470. var edges = this.edges;
  12471. for (var i = 0, len = ids.length; i < len; i++) {
  12472. var id = ids[i];
  12473. var edge = edges[id];
  12474. if (edge) {
  12475. edge.disconnect();
  12476. delete edges[id];
  12477. }
  12478. }
  12479. this.moving = true;
  12480. this._updateValueRange(edges);
  12481. };
  12482. /**
  12483. * Reconnect all edges
  12484. * @private
  12485. */
  12486. Graph.prototype._reconnectEdges = function() {
  12487. var id,
  12488. nodes = this.nodes,
  12489. edges = this.edges;
  12490. for (id in nodes) {
  12491. if (nodes.hasOwnProperty(id)) {
  12492. nodes[id].edges = [];
  12493. }
  12494. }
  12495. for (id in edges) {
  12496. if (edges.hasOwnProperty(id)) {
  12497. var edge = edges[id];
  12498. edge.from = null;
  12499. edge.to = null;
  12500. edge.connect();
  12501. }
  12502. }
  12503. };
  12504. /**
  12505. * Update the values of all object in the given array according to the current
  12506. * value range of the objects in the array.
  12507. * @param {Object} obj An object containing a set of Edges or Nodes
  12508. * The objects must have a method getValue() and
  12509. * setValueRange(min, max).
  12510. * @private
  12511. */
  12512. Graph.prototype._updateValueRange = function(obj) {
  12513. var id;
  12514. // determine the range of the objects
  12515. var valueMin = undefined;
  12516. var valueMax = undefined;
  12517. for (id in obj) {
  12518. if (obj.hasOwnProperty(id)) {
  12519. var value = obj[id].getValue();
  12520. if (value !== undefined) {
  12521. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  12522. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  12523. }
  12524. }
  12525. }
  12526. // adjust the range of all objects
  12527. if (valueMin !== undefined && valueMax !== undefined) {
  12528. for (id in obj) {
  12529. if (obj.hasOwnProperty(id)) {
  12530. obj[id].setValueRange(valueMin, valueMax);
  12531. }
  12532. }
  12533. }
  12534. };
  12535. /**
  12536. * Redraw the graph with the current data
  12537. * chart will be resized too.
  12538. */
  12539. Graph.prototype.redraw = function() {
  12540. this.setSize(this.width, this.height);
  12541. this._redraw();
  12542. };
  12543. /**
  12544. * Redraw the graph with the current data
  12545. * @private
  12546. */
  12547. Graph.prototype._redraw = function() {
  12548. var ctx = this.frame.canvas.getContext('2d');
  12549. // clear the canvas
  12550. var w = this.frame.canvas.width;
  12551. var h = this.frame.canvas.height;
  12552. ctx.clearRect(0, 0, w, h);
  12553. // set scaling and translation
  12554. ctx.save();
  12555. ctx.translate(this.translation.x, this.translation.y);
  12556. ctx.scale(this.scale, this.scale);
  12557. this.canvasTopLeft = {"x": this._canvasToX(0),
  12558. "y": this._canvasToY(0)};
  12559. this.canvasBottomRight = {"x": this._canvasToX(this.frame.canvas.clientWidth),
  12560. "y": this._canvasToY(this.frame.canvas.clientHeight)};
  12561. this._doInAllSectors("_drawAllSectorNodes",ctx);
  12562. this._doInAllSectors("_drawEdges",ctx);
  12563. this._doInAllSectors("_drawNodes",ctx);
  12564. // restore original scaling and translation
  12565. ctx.restore();
  12566. if (this.constants.navigationUI.enabled == true) {
  12567. this._doInUISector("_drawNodes",ctx,true);
  12568. }
  12569. };
  12570. /**
  12571. * Set the translation of the graph
  12572. * @param {Number} offsetX Horizontal offset
  12573. * @param {Number} offsetY Vertical offset
  12574. * @private
  12575. */
  12576. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  12577. if (this.translation === undefined) {
  12578. this.translation = {
  12579. x: 0,
  12580. y: 0
  12581. };
  12582. }
  12583. if (offsetX !== undefined) {
  12584. this.translation.x = offsetX;
  12585. }
  12586. if (offsetY !== undefined) {
  12587. this.translation.y = offsetY;
  12588. }
  12589. };
  12590. /**
  12591. * Get the translation of the graph
  12592. * @return {Object} translation An object with parameters x and y, both a number
  12593. * @private
  12594. */
  12595. Graph.prototype._getTranslation = function() {
  12596. return {
  12597. x: this.translation.x,
  12598. y: this.translation.y
  12599. };
  12600. };
  12601. /**
  12602. * Scale the graph
  12603. * @param {Number} scale Scaling factor 1.0 is unscaled
  12604. * @private
  12605. */
  12606. Graph.prototype._setScale = function(scale) {
  12607. this.scale = scale;
  12608. };
  12609. /**
  12610. * Get the current scale of the graph
  12611. * @return {Number} scale Scaling factor 1.0 is unscaled
  12612. * @private
  12613. */
  12614. Graph.prototype._getScale = function() {
  12615. return this.scale;
  12616. };
  12617. /**
  12618. * Convert a horizontal point on the HTML canvas to the x-value of the model
  12619. * @param {number} x
  12620. * @returns {number}
  12621. * @private
  12622. */
  12623. Graph.prototype._canvasToX = function(x) {
  12624. return (x - this.translation.x) / this.scale;
  12625. };
  12626. /**
  12627. * Convert an x-value in the model to a horizontal point on the HTML canvas
  12628. * @param {number} x
  12629. * @returns {number}
  12630. * @private
  12631. */
  12632. Graph.prototype._xToCanvas = function(x) {
  12633. return x * this.scale + this.translation.x;
  12634. };
  12635. /**
  12636. * Convert a vertical point on the HTML canvas to the y-value of the model
  12637. * @param {number} y
  12638. * @returns {number}
  12639. * @private
  12640. */
  12641. Graph.prototype._canvasToY = function(y) {
  12642. return (y - this.translation.y) / this.scale;
  12643. };
  12644. /**
  12645. * Convert an y-value in the model to a vertical point on the HTML canvas
  12646. * @param {number} y
  12647. * @returns {number}
  12648. * @private
  12649. */
  12650. Graph.prototype._yToCanvas = function(y) {
  12651. return y * this.scale + this.translation.y ;
  12652. };
  12653. /**
  12654. * Redraw all nodes
  12655. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  12656. * @param {CanvasRenderingContext2D} ctx
  12657. * @param {Boolean} [alwaysShow]
  12658. * @private
  12659. */
  12660. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  12661. if (alwaysShow === undefined) {
  12662. alwaysShow = false;
  12663. }
  12664. // first draw the unselected nodes
  12665. var nodes = this.nodes;
  12666. var selected = [];
  12667. for (var id in nodes) {
  12668. if (nodes.hasOwnProperty(id)) {
  12669. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  12670. if (nodes[id].isSelected()) {
  12671. selected.push(id);
  12672. }
  12673. else {
  12674. if (nodes[id].inArea() || alwaysShow) {
  12675. nodes[id].draw(ctx);
  12676. }
  12677. }
  12678. }
  12679. }
  12680. // draw the selected nodes on top
  12681. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  12682. if (nodes[selected[s]].inArea() || alwaysShow) {
  12683. nodes[selected[s]].draw(ctx);
  12684. }
  12685. }
  12686. };
  12687. /**
  12688. * Redraw all edges
  12689. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  12690. * @param {CanvasRenderingContext2D} ctx
  12691. * @private
  12692. */
  12693. Graph.prototype._drawEdges = function(ctx) {
  12694. var edges = this.edges;
  12695. for (var id in edges) {
  12696. if (edges.hasOwnProperty(id)) {
  12697. var edge = edges[id];
  12698. edge.setScale(this.scale);
  12699. if (edge.connected) {
  12700. edges[id].draw(ctx);
  12701. }
  12702. }
  12703. }
  12704. };
  12705. /**
  12706. * Find a stable position for all nodes
  12707. * @private
  12708. */
  12709. Graph.prototype._doStabilize = function() {
  12710. //var start = new Date();
  12711. // find stable position
  12712. var count = 0;
  12713. var vmin = this.constants.minVelocity;
  12714. var stable = false;
  12715. while (!stable && count < this.constants.maxIterations) {
  12716. this._initializeForceCalculation();
  12717. this._discreteStepNodes();
  12718. stable = !this._isMoving(vmin);
  12719. count++;
  12720. }
  12721. this.zoomToFit();
  12722. // var end = new Date();
  12723. // console.log('Stabilized in ' + (end-start) + ' ms, ' + count + ' iterations' ); // TODO: cleanup
  12724. };
  12725. /**
  12726. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  12727. * if there is more than one node. If it is just one node, we dont calculate anything.
  12728. *
  12729. * @private
  12730. */
  12731. Graph.prototype._initializeForceCalculation = function() {
  12732. // stop calculation if there is only one node
  12733. if (this.nodeIndices.length == 1) {
  12734. this.nodes[this.nodeIndices[0]]._setForce(0,0);
  12735. }
  12736. else {
  12737. // if there are too many nodes on screen, we cluster without repositioning
  12738. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  12739. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  12740. }
  12741. // we now start the force calculation
  12742. this._calculateForces();
  12743. }
  12744. };
  12745. /**
  12746. * Calculate the external forces acting on the nodes
  12747. * Forces are caused by: edges, repulsing forces between nodes, gravity
  12748. * @private
  12749. */
  12750. Graph.prototype._calculateForces = function() {
  12751. // var screenCenterPos = {"x":(0.5*(this.canvasTopLeft.x + this.canvasBottomRight.x)),
  12752. // "y":(0.5*(this.canvasTopLeft.y + this.canvasBottomRight.y))}
  12753. // create a local edge to the nodes and edges, that is faster
  12754. var dx, dy, angle, distance, fx, fy,
  12755. repulsingForce, springForce, length, edgeLength,
  12756. node, node1, node2, edge, edgeId, i, j, nodeId, xCenter, yCenter;
  12757. var clusterSize;
  12758. var nodes = this.nodes;
  12759. var edges = this.edges;
  12760. // Gravity is required to keep separated groups from floating off
  12761. // the forces are reset to zero in this loop by using _setForce instead
  12762. // of _addForce
  12763. var gravity = 0.08 * this.forceFactor;
  12764. for (i = 0; i < this.nodeIndices.length; i++) {
  12765. node = nodes[this.nodeIndices[i]];
  12766. // gravity does not apply when we are in a pocket sector
  12767. if (this._sector() == "default") {
  12768. dx = -node.x;// + screenCenterPos.x;
  12769. dy = -node.y;// + screenCenterPos.y;
  12770. angle = Math.atan2(dy, dx);
  12771. fx = Math.cos(angle) * gravity;
  12772. fy = Math.sin(angle) * gravity;
  12773. }
  12774. else {
  12775. fx = 0;
  12776. fy = 0;
  12777. }
  12778. node._setForce(fx, fy);
  12779. node.updateDamping(this.nodeIndices.length);
  12780. }
  12781. // repulsing forces between nodes
  12782. var minimumDistance = this.constants.nodes.distance,
  12783. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  12784. // we loop from i over all but the last entree in the array
  12785. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  12786. for (i = 0; i < this.nodeIndices.length-1; i++) {
  12787. node1 = nodes[this.nodeIndices[i]];
  12788. for (j = i+1; j < this.nodeIndices.length; j++) {
  12789. node2 = nodes[this.nodeIndices[j]];
  12790. clusterSize = (node1.clusterSize + node2.clusterSize - 2);
  12791. dx = node2.x - node1.x;
  12792. dy = node2.y - node1.y;
  12793. distance = Math.sqrt(dx * dx + dy * dy);
  12794. // clusters have a larger region of influence
  12795. minimumDistance = (clusterSize == 0) ? this.constants.nodes.distance : (this.constants.nodes.distance * (1 + clusterSize * this.constants.clustering.distanceAmplification));
  12796. if (distance < 2*minimumDistance) { // at 2.0 * the minimum distance, the force is 0.000045
  12797. angle = Math.atan2(dy, dx);
  12798. if (distance < 0.5*minimumDistance) { // at 0.5 * the minimum distance, the force is 0.993307
  12799. repulsingForce = 1.0;
  12800. }
  12801. else {
  12802. // TODO: correct factor for repulsing force
  12803. //repulsingForce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12804. //repulsingForce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12805. repulsingForce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)); // TODO: customize the repulsing force
  12806. }
  12807. // amplify the repulsion for clusters.
  12808. repulsingForce *= (clusterSize == 0) ? 1 : 1 + clusterSize * this.constants.clustering.forceAmplification;
  12809. repulsingForce *= this.forceFactor;
  12810. fx = Math.cos(angle) * repulsingForce;
  12811. fy = Math.sin(angle) * repulsingForce ;
  12812. node1._addForce(-fx, -fy);
  12813. node2._addForce(fx, fy);
  12814. }
  12815. }
  12816. }
  12817. /*
  12818. // repulsion of the edges on the nodes and
  12819. for (var nodeId in nodes) {
  12820. if (nodes.hasOwnProperty(nodeId)) {
  12821. node = nodes[nodeId];
  12822. for(var edgeId in edges) {
  12823. if (edges.hasOwnProperty(edgeId)) {
  12824. edge = edges[edgeId];
  12825. // get the center of the edge
  12826. xCenter = edge.from.x+(edge.to.x - edge.from.x)/2;
  12827. yCenter = edge.from.y+(edge.to.y - edge.from.y)/2;
  12828. // calculate normally distributed force
  12829. dx = node.x - xCenter;
  12830. dy = node.y - yCenter;
  12831. distance = Math.sqrt(dx * dx + dy * dy);
  12832. if (distance < 2*minimumDistance) { // at 2.0 * the minimum distance, the force is 0.000045
  12833. angle = Math.atan2(dy, dx);
  12834. if (distance < 0.5*minimumDistance) { // at 0.5 * the minimum distance, the force is 0.993307
  12835. repulsingForce = 1.0;
  12836. }
  12837. else {
  12838. // TODO: correct factor for repulsing force
  12839. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12840. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  12841. repulsingForce = 1 / (1 + Math.exp((distance / (minimumDistance / 2) - 1) * steepness)); // TODO: customize the repulsing force
  12842. }
  12843. fx = Math.cos(angle) * repulsingForce;
  12844. fy = Math.sin(angle) * repulsingForce;
  12845. node._addForce(fx, fy);
  12846. edge.from._addForce(-fx/2,-fy/2);
  12847. edge.to._addForce(-fx/2,-fy/2);
  12848. }
  12849. }
  12850. }
  12851. }
  12852. }
  12853. */
  12854. // forces caused by the edges, modelled as springs
  12855. for (edgeId in edges) {
  12856. if (edges.hasOwnProperty(edgeId)) {
  12857. edge = edges[edgeId];
  12858. if (edge.connected) {
  12859. // only calculate forces if nodes are in the same sector
  12860. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  12861. clusterSize = (edge.to.clusterSize + edge.from.clusterSize - 2);
  12862. dx = (edge.to.x - edge.from.x);
  12863. dy = (edge.to.y - edge.from.y);
  12864. //edgeLength = (edge.from.width + edge.from.height + edge.to.width + edge.to.height)/2 || edge.length; // TODO: dmin
  12865. //edgeLength = (edge.from.width + edge.to.width)/2 || edge.length; // TODO: dmin
  12866. //edgeLength = 20 + ((edge.from.width + edge.to.width) || 0) / 2;
  12867. edgeLength = edge.length;
  12868. // this implies that the edges between big clusters are longer
  12869. edgeLength += clusterSize * this.constants.clustering.edgeGrowth;
  12870. length = Math.sqrt(dx * dx + dy * dy);
  12871. angle = Math.atan2(dy, dx);
  12872. springForce = edge.stiffness * (edgeLength - length) * this.forceFactor;
  12873. fx = Math.cos(angle) * springForce;
  12874. fy = Math.sin(angle) * springForce;
  12875. edge.from._addForce(-fx, -fy);
  12876. edge.to._addForce(fx, fy);
  12877. }
  12878. }
  12879. }
  12880. }
  12881. /*
  12882. // TODO: re-implement repulsion of edges
  12883. // repulsing forces between edges
  12884. var minimumDistance = this.constants.edges.distance,
  12885. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  12886. for (var l = 0; l < edges.length; l++) {
  12887. //Keep distance from other edge centers
  12888. for (var l2 = l + 1; l2 < this.edges.length; l2++) {
  12889. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  12890. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  12891. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  12892. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  12893. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  12894. l2x = edges[l2].from.x+(edges[l2].to.x - edges[l2].from.x)/2,
  12895. l2y = edges[l2].from.y+(edges[l2].to.y - edges[l2].from.y)/2,
  12896. // calculate normally distributed force
  12897. dx = l2x - lx,
  12898. dy = l2y - ly,
  12899. distance = Math.sqrt(dx * dx + dy * dy),
  12900. angle = Math.atan2(dy, dx),
  12901. // TODO: correct factor for repulsing force
  12902. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12903. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  12904. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  12905. fx = Math.cos(angle) * repulsingforce,
  12906. fy = Math.sin(angle) * repulsingforce;
  12907. edges[l].from._addForce(-fx, -fy);
  12908. edges[l].to._addForce(-fx, -fy);
  12909. edges[l2].from._addForce(fx, fy);
  12910. edges[l2].to._addForce(fx, fy);
  12911. }
  12912. }
  12913. */
  12914. };
  12915. /**
  12916. * Check if any of the nodes is still moving
  12917. * @param {number} vmin the minimum velocity considered as 'moving'
  12918. * @return {boolean} true if moving, false if non of the nodes is moving
  12919. * @private
  12920. */
  12921. Graph.prototype._isMoving = function(vmin) {
  12922. var vminCorrected = vmin / this.scale;
  12923. var nodes = this.nodes;
  12924. for (var id in nodes) {
  12925. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vminCorrected)) {
  12926. return true;
  12927. }
  12928. }
  12929. return false;
  12930. };
  12931. /**
  12932. * /**
  12933. * Perform one discrete step for all nodes
  12934. *
  12935. * @param interval
  12936. * @private
  12937. */
  12938. Graph.prototype._discreteStepNodes = function() {
  12939. var interval = 0.01;
  12940. var nodes = this.nodes;
  12941. for (var id in nodes) {
  12942. if (nodes.hasOwnProperty(id)) {
  12943. nodes[id].discreteStep(interval);
  12944. }
  12945. }
  12946. var vmin = this.constants.minVelocity;
  12947. this.moving = this._isMoving(vmin);
  12948. };
  12949. /**
  12950. * Start animating nodes and edges
  12951. *
  12952. * @poram {Boolean} runCalculationStep
  12953. */
  12954. Graph.prototype.start = function() {
  12955. if (!this.freezeSimulation) {
  12956. if (this.moving) {
  12957. this._doInAllActiveSectors("_initializeForceCalculation");
  12958. this._doInAllActiveSectors("_discreteStepNodes");
  12959. this._findCenter(this._getRange())
  12960. }
  12961. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  12962. // start animation. only start calculationTimer if it is not already running
  12963. if (!this.timer) {
  12964. var graph = this;
  12965. this.timer = window.setTimeout(function () {
  12966. graph.timer = undefined;
  12967. // keyboad movement
  12968. if (graph.xIncrement != 0 || graph.yIncrement != 0) {
  12969. var translation = graph._getTranslation();
  12970. graph._setTranslation(translation.x+graph.xIncrement,translation.y+graph.yIncrement);
  12971. }
  12972. if (graph.zoomIncrement != 0) {
  12973. graph._zoom(graph.scale*(1 + graph.zoomIncrement),graph.lastPointerPosition);
  12974. }
  12975. graph.start();
  12976. graph._redraw();
  12977. //this.end = window.performance.now();
  12978. //this.time = this.end - this.startTime;
  12979. //console.log('refresh time: ' + this.time);
  12980. //this.startTime = window.performance.now();
  12981. }, this.renderTimestep);
  12982. }
  12983. }
  12984. else {
  12985. this._redraw();
  12986. }
  12987. }
  12988. };
  12989. Graph.prototype.singleStep = function() {
  12990. if (this.moving) {
  12991. this._initializeForceCalculation();
  12992. this._discreteStepNodes();
  12993. var vmin = this.constants.minVelocity;
  12994. this.moving = this._isMoving(vmin);
  12995. this._redraw();
  12996. }
  12997. };
  12998. /**
  12999. * Freeze the animation
  13000. */
  13001. Graph.prototype.toggleFreeze = function() {
  13002. if (this.freezeSimulation == false) {
  13003. this.freezeSimulation = true;
  13004. }
  13005. else {
  13006. this.freezeSimulation = false;
  13007. this.start();
  13008. }
  13009. };
  13010. /**
  13011. * Mixin the cluster system and initialize the parameters required.
  13012. *
  13013. * @private
  13014. */
  13015. Graph.prototype._loadClusterSystem = function() {
  13016. this.clusterSession = 0;
  13017. this.hubThreshold = 5;
  13018. for (var mixinFunction in ClusterMixin) {
  13019. if (ClusterMixin.hasOwnProperty(mixinFunction)) {
  13020. Graph.prototype[mixinFunction] = ClusterMixin[mixinFunction];
  13021. }
  13022. }
  13023. }
  13024. /**
  13025. * Mixin the sector system and initialize the parameters required
  13026. *
  13027. * @private
  13028. */
  13029. Graph.prototype._loadSectorSystem = function() {
  13030. this.sectors = {};
  13031. this.activeSector = ["default"];
  13032. this.sectors["active"] = {};
  13033. this.sectors["active"]["default"] = {"nodes":{},
  13034. "edges":{},
  13035. "nodeIndices":[],
  13036. "formationScale": 1.0,
  13037. "drawingNode": undefined};
  13038. this.sectors["frozen"] = {};
  13039. this.sectors["navigationUI"] = {"nodes":{},
  13040. "edges":{},
  13041. "nodeIndices":[],
  13042. "formationScale": 1.0,
  13043. "drawingNode": undefined};
  13044. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13045. for (var mixinFunction in SectorMixin) {
  13046. if (SectorMixin.hasOwnProperty(mixinFunction)) {
  13047. Graph.prototype[mixinFunction] = SectorMixin[mixinFunction];
  13048. }
  13049. }
  13050. };
  13051. /**
  13052. * Mixin the selection system and initialize the parameters required
  13053. *
  13054. * @private
  13055. */
  13056. Graph.prototype._loadSelectionSystem = function() {
  13057. this.selection = [];
  13058. this.selectionObj = {};
  13059. for (var mixinFunction in SelectionMixin) {
  13060. if (SelectionMixin.hasOwnProperty(mixinFunction)) {
  13061. Graph.prototype[mixinFunction] = SelectionMixin[mixinFunction];
  13062. }
  13063. }
  13064. }
  13065. /**
  13066. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13067. *
  13068. * @private
  13069. */
  13070. Graph.prototype._loadUISystem = function() {
  13071. for (var mixinFunction in UIMixin) {
  13072. if (UIMixin.hasOwnProperty(mixinFunction)) {
  13073. Graph.prototype[mixinFunction] = UIMixin[mixinFunction];
  13074. }
  13075. }
  13076. if (this.constants.navigationUI.enabled == true) {
  13077. this._loadUIElements();
  13078. }
  13079. }
  13080. /**
  13081. * this function exists to avoid errors when not loading the navigationUI system
  13082. */
  13083. Graph.prototype._relocateUI = function() {
  13084. // empty, is overloaded by navigationUI system
  13085. }
  13086. /**
  13087. * * this function exists to avoid errors when not loading the navigationUI system
  13088. */
  13089. Graph.prototype._unHighlightAll = function() {
  13090. // empty, is overloaded by the navigationUI system
  13091. }
  13092. /**
  13093. * vis.js module exports
  13094. */
  13095. var vis = {
  13096. util: util,
  13097. events: events,
  13098. Controller: Controller,
  13099. DataSet: DataSet,
  13100. DataView: DataView,
  13101. Range: Range,
  13102. Stack: Stack,
  13103. TimeStep: TimeStep,
  13104. EventBus: EventBus,
  13105. components: {
  13106. items: {
  13107. Item: Item,
  13108. ItemBox: ItemBox,
  13109. ItemPoint: ItemPoint,
  13110. ItemRange: ItemRange
  13111. },
  13112. Component: Component,
  13113. Panel: Panel,
  13114. RootPanel: RootPanel,
  13115. ItemSet: ItemSet,
  13116. TimeAxis: TimeAxis
  13117. },
  13118. graph: {
  13119. Node: Node,
  13120. Edge: Edge,
  13121. Popup: Popup,
  13122. Groups: Groups,
  13123. Images: Images
  13124. },
  13125. Timeline: Timeline,
  13126. Graph: Graph
  13127. };
  13128. /**
  13129. * CommonJS module exports
  13130. */
  13131. if (typeof exports !== 'undefined') {
  13132. exports = vis;
  13133. }
  13134. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  13135. module.exports = vis;
  13136. }
  13137. /**
  13138. * AMD module exports
  13139. */
  13140. if (typeof(define) === 'function') {
  13141. define(function () {
  13142. return vis;
  13143. });
  13144. }
  13145. /**
  13146. * Window exports
  13147. */
  13148. if (typeof window !== 'undefined') {
  13149. // attach the module to the window, load as a regular javascript file
  13150. window['vis'] = vis;
  13151. }
  13152. },{"hammerjs":2,"moment":3,"mousetrap":4}],2:[function(require,module,exports){
  13153. /*! Hammer.JS - v1.0.5 - 2013-04-07
  13154. * http://eightmedia.github.com/hammer.js
  13155. *
  13156. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  13157. * Licensed under the MIT license */
  13158. (function(window, undefined) {
  13159. 'use strict';
  13160. /**
  13161. * Hammer
  13162. * use this to create instances
  13163. * @param {HTMLElement} element
  13164. * @param {Object} options
  13165. * @returns {Hammer.Instance}
  13166. * @constructor
  13167. */
  13168. var Hammer = function(element, options) {
  13169. return new Hammer.Instance(element, options || {});
  13170. };
  13171. // default settings
  13172. Hammer.defaults = {
  13173. // add styles and attributes to the element to prevent the browser from doing
  13174. // its native behavior. this doesnt prevent the scrolling, but cancels
  13175. // the contextmenu, tap highlighting etc
  13176. // set to false to disable this
  13177. stop_browser_behavior: {
  13178. // this also triggers onselectstart=false for IE
  13179. userSelect: 'none',
  13180. // this makes the element blocking in IE10 >, you could experiment with the value
  13181. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  13182. touchAction: 'none',
  13183. touchCallout: 'none',
  13184. contentZooming: 'none',
  13185. userDrag: 'none',
  13186. tapHighlightColor: 'rgba(0,0,0,0)'
  13187. }
  13188. // more settings are defined per gesture at gestures.js
  13189. };
  13190. // detect touchevents
  13191. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  13192. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  13193. // dont use mouseevents on mobile devices
  13194. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  13195. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  13196. // eventtypes per touchevent (start, move, end)
  13197. // are filled by Hammer.event.determineEventTypes on setup
  13198. Hammer.EVENT_TYPES = {};
  13199. // direction defines
  13200. Hammer.DIRECTION_DOWN = 'down';
  13201. Hammer.DIRECTION_LEFT = 'left';
  13202. Hammer.DIRECTION_UP = 'up';
  13203. Hammer.DIRECTION_RIGHT = 'right';
  13204. // pointer type
  13205. Hammer.POINTER_MOUSE = 'mouse';
  13206. Hammer.POINTER_TOUCH = 'touch';
  13207. Hammer.POINTER_PEN = 'pen';
  13208. // touch event defines
  13209. Hammer.EVENT_START = 'start';
  13210. Hammer.EVENT_MOVE = 'move';
  13211. Hammer.EVENT_END = 'end';
  13212. // hammer document where the base events are added at
  13213. Hammer.DOCUMENT = document;
  13214. // plugins namespace
  13215. Hammer.plugins = {};
  13216. // if the window events are set...
  13217. Hammer.READY = false;
  13218. /**
  13219. * setup events to detect gestures on the document
  13220. */
  13221. function setup() {
  13222. if(Hammer.READY) {
  13223. return;
  13224. }
  13225. // find what eventtypes we add listeners to
  13226. Hammer.event.determineEventTypes();
  13227. // Register all gestures inside Hammer.gestures
  13228. for(var name in Hammer.gestures) {
  13229. if(Hammer.gestures.hasOwnProperty(name)) {
  13230. Hammer.detection.register(Hammer.gestures[name]);
  13231. }
  13232. }
  13233. // Add touch events on the document
  13234. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  13235. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  13236. // Hammer is ready...!
  13237. Hammer.READY = true;
  13238. }
  13239. /**
  13240. * create new hammer instance
  13241. * all methods should return the instance itself, so it is chainable.
  13242. * @param {HTMLElement} element
  13243. * @param {Object} [options={}]
  13244. * @returns {Hammer.Instance}
  13245. * @constructor
  13246. */
  13247. Hammer.Instance = function(element, options) {
  13248. var self = this;
  13249. // setup HammerJS window events and register all gestures
  13250. // this also sets up the default options
  13251. setup();
  13252. this.element = element;
  13253. // start/stop detection option
  13254. this.enabled = true;
  13255. // merge options
  13256. this.options = Hammer.utils.extend(
  13257. Hammer.utils.extend({}, Hammer.defaults),
  13258. options || {});
  13259. // add some css to the element to prevent the browser from doing its native behavoir
  13260. if(this.options.stop_browser_behavior) {
  13261. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  13262. }
  13263. // start detection on touchstart
  13264. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  13265. if(self.enabled) {
  13266. Hammer.detection.startDetect(self, ev);
  13267. }
  13268. });
  13269. // return instance
  13270. return this;
  13271. };
  13272. Hammer.Instance.prototype = {
  13273. /**
  13274. * bind events to the instance
  13275. * @param {String} gesture
  13276. * @param {Function} handler
  13277. * @returns {Hammer.Instance}
  13278. */
  13279. on: function onEvent(gesture, handler){
  13280. var gestures = gesture.split(' ');
  13281. for(var t=0; t<gestures.length; t++) {
  13282. this.element.addEventListener(gestures[t], handler, false);
  13283. }
  13284. return this;
  13285. },
  13286. /**
  13287. * unbind events to the instance
  13288. * @param {String} gesture
  13289. * @param {Function} handler
  13290. * @returns {Hammer.Instance}
  13291. */
  13292. off: function offEvent(gesture, handler){
  13293. var gestures = gesture.split(' ');
  13294. for(var t=0; t<gestures.length; t++) {
  13295. this.element.removeEventListener(gestures[t], handler, false);
  13296. }
  13297. return this;
  13298. },
  13299. /**
  13300. * trigger gesture event
  13301. * @param {String} gesture
  13302. * @param {Object} eventData
  13303. * @returns {Hammer.Instance}
  13304. */
  13305. trigger: function triggerEvent(gesture, eventData){
  13306. // create DOM event
  13307. var event = Hammer.DOCUMENT.createEvent('Event');
  13308. event.initEvent(gesture, true, true);
  13309. event.gesture = eventData;
  13310. // trigger on the target if it is in the instance element,
  13311. // this is for event delegation tricks
  13312. var element = this.element;
  13313. if(Hammer.utils.hasParent(eventData.target, element)) {
  13314. element = eventData.target;
  13315. }
  13316. element.dispatchEvent(event);
  13317. return this;
  13318. },
  13319. /**
  13320. * enable of disable hammer.js detection
  13321. * @param {Boolean} state
  13322. * @returns {Hammer.Instance}
  13323. */
  13324. enable: function enable(state) {
  13325. this.enabled = state;
  13326. return this;
  13327. }
  13328. };
  13329. /**
  13330. * this holds the last move event,
  13331. * used to fix empty touchend issue
  13332. * see the onTouch event for an explanation
  13333. * @type {Object}
  13334. */
  13335. var last_move_event = null;
  13336. /**
  13337. * when the mouse is hold down, this is true
  13338. * @type {Boolean}
  13339. */
  13340. var enable_detect = false;
  13341. /**
  13342. * when touch events have been fired, this is true
  13343. * @type {Boolean}
  13344. */
  13345. var touch_triggered = false;
  13346. Hammer.event = {
  13347. /**
  13348. * simple addEventListener
  13349. * @param {HTMLElement} element
  13350. * @param {String} type
  13351. * @param {Function} handler
  13352. */
  13353. bindDom: function(element, type, handler) {
  13354. var types = type.split(' ');
  13355. for(var t=0; t<types.length; t++) {
  13356. element.addEventListener(types[t], handler, false);
  13357. }
  13358. },
  13359. /**
  13360. * touch events with mouse fallback
  13361. * @param {HTMLElement} element
  13362. * @param {String} eventType like Hammer.EVENT_MOVE
  13363. * @param {Function} handler
  13364. */
  13365. onTouch: function onTouch(element, eventType, handler) {
  13366. var self = this;
  13367. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  13368. var sourceEventType = ev.type.toLowerCase();
  13369. // onmouseup, but when touchend has been fired we do nothing.
  13370. // this is for touchdevices which also fire a mouseup on touchend
  13371. if(sourceEventType.match(/mouse/) && touch_triggered) {
  13372. return;
  13373. }
  13374. // mousebutton must be down or a touch event
  13375. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  13376. sourceEventType.match(/pointerdown/) || // pointerevents touch
  13377. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  13378. ){
  13379. enable_detect = true;
  13380. }
  13381. // we are in a touch event, set the touch triggered bool to true,
  13382. // this for the conflicts that may occur on ios and android
  13383. if(sourceEventType.match(/touch|pointer/)) {
  13384. touch_triggered = true;
  13385. }
  13386. // count the total touches on the screen
  13387. var count_touches = 0;
  13388. // when touch has been triggered in this detection session
  13389. // and we are now handling a mouse event, we stop that to prevent conflicts
  13390. if(enable_detect) {
  13391. // update pointerevent
  13392. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  13393. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  13394. }
  13395. // touch
  13396. else if(sourceEventType.match(/touch/)) {
  13397. count_touches = ev.touches.length;
  13398. }
  13399. // mouse
  13400. else if(!touch_triggered) {
  13401. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  13402. }
  13403. // if we are in a end event, but when we remove one touch and
  13404. // we still have enough, set eventType to move
  13405. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  13406. eventType = Hammer.EVENT_MOVE;
  13407. }
  13408. // no touches, force the end event
  13409. else if(!count_touches) {
  13410. eventType = Hammer.EVENT_END;
  13411. }
  13412. // because touchend has no touches, and we often want to use these in our gestures,
  13413. // we send the last move event as our eventData in touchend
  13414. if(!count_touches && last_move_event !== null) {
  13415. ev = last_move_event;
  13416. }
  13417. // store the last move event
  13418. else {
  13419. last_move_event = ev;
  13420. }
  13421. // trigger the handler
  13422. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  13423. // remove pointerevent from list
  13424. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  13425. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  13426. }
  13427. }
  13428. //debug(sourceEventType +" "+ eventType);
  13429. // on the end we reset everything
  13430. if(!count_touches) {
  13431. last_move_event = null;
  13432. enable_detect = false;
  13433. touch_triggered = false;
  13434. Hammer.PointerEvent.reset();
  13435. }
  13436. });
  13437. },
  13438. /**
  13439. * we have different events for each device/browser
  13440. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  13441. */
  13442. determineEventTypes: function determineEventTypes() {
  13443. // determine the eventtype we want to set
  13444. var types;
  13445. // pointerEvents magic
  13446. if(Hammer.HAS_POINTEREVENTS) {
  13447. types = Hammer.PointerEvent.getEvents();
  13448. }
  13449. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  13450. else if(Hammer.NO_MOUSEEVENTS) {
  13451. types = [
  13452. 'touchstart',
  13453. 'touchmove',
  13454. 'touchend touchcancel'];
  13455. }
  13456. // for non pointer events browsers and mixed browsers,
  13457. // like chrome on windows8 touch laptop
  13458. else {
  13459. types = [
  13460. 'touchstart mousedown',
  13461. 'touchmove mousemove',
  13462. 'touchend touchcancel mouseup'];
  13463. }
  13464. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  13465. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  13466. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  13467. },
  13468. /**
  13469. * create touchlist depending on the event
  13470. * @param {Object} ev
  13471. * @param {String} eventType used by the fakemultitouch plugin
  13472. */
  13473. getTouchList: function getTouchList(ev/*, eventType*/) {
  13474. // get the fake pointerEvent touchlist
  13475. if(Hammer.HAS_POINTEREVENTS) {
  13476. return Hammer.PointerEvent.getTouchList();
  13477. }
  13478. // get the touchlist
  13479. else if(ev.touches) {
  13480. return ev.touches;
  13481. }
  13482. // make fake touchlist from mouse position
  13483. else {
  13484. return [{
  13485. identifier: 1,
  13486. pageX: ev.pageX,
  13487. pageY: ev.pageY,
  13488. target: ev.target
  13489. }];
  13490. }
  13491. },
  13492. /**
  13493. * collect event data for Hammer js
  13494. * @param {HTMLElement} element
  13495. * @param {String} eventType like Hammer.EVENT_MOVE
  13496. * @param {Object} eventData
  13497. */
  13498. collectEventData: function collectEventData(element, eventType, ev) {
  13499. var touches = this.getTouchList(ev, eventType);
  13500. // find out pointerType
  13501. var pointerType = Hammer.POINTER_TOUCH;
  13502. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  13503. pointerType = Hammer.POINTER_MOUSE;
  13504. }
  13505. return {
  13506. center : Hammer.utils.getCenter(touches),
  13507. timeStamp : new Date().getTime(),
  13508. target : ev.target,
  13509. touches : touches,
  13510. eventType : eventType,
  13511. pointerType : pointerType,
  13512. srcEvent : ev,
  13513. /**
  13514. * prevent the browser default actions
  13515. * mostly used to disable scrolling of the browser
  13516. */
  13517. preventDefault: function() {
  13518. if(this.srcEvent.preventManipulation) {
  13519. this.srcEvent.preventManipulation();
  13520. }
  13521. if(this.srcEvent.preventDefault) {
  13522. this.srcEvent.preventDefault();
  13523. }
  13524. },
  13525. /**
  13526. * stop bubbling the event up to its parents
  13527. */
  13528. stopPropagation: function() {
  13529. this.srcEvent.stopPropagation();
  13530. },
  13531. /**
  13532. * immediately stop gesture detection
  13533. * might be useful after a swipe was detected
  13534. * @return {*}
  13535. */
  13536. stopDetect: function() {
  13537. return Hammer.detection.stopDetect();
  13538. }
  13539. };
  13540. }
  13541. };
  13542. Hammer.PointerEvent = {
  13543. /**
  13544. * holds all pointers
  13545. * @type {Object}
  13546. */
  13547. pointers: {},
  13548. /**
  13549. * get a list of pointers
  13550. * @returns {Array} touchlist
  13551. */
  13552. getTouchList: function() {
  13553. var self = this;
  13554. var touchlist = [];
  13555. // we can use forEach since pointerEvents only is in IE10
  13556. Object.keys(self.pointers).sort().forEach(function(id) {
  13557. touchlist.push(self.pointers[id]);
  13558. });
  13559. return touchlist;
  13560. },
  13561. /**
  13562. * update the position of a pointer
  13563. * @param {String} type Hammer.EVENT_END
  13564. * @param {Object} pointerEvent
  13565. */
  13566. updatePointer: function(type, pointerEvent) {
  13567. if(type == Hammer.EVENT_END) {
  13568. this.pointers = {};
  13569. }
  13570. else {
  13571. pointerEvent.identifier = pointerEvent.pointerId;
  13572. this.pointers[pointerEvent.pointerId] = pointerEvent;
  13573. }
  13574. return Object.keys(this.pointers).length;
  13575. },
  13576. /**
  13577. * check if ev matches pointertype
  13578. * @param {String} pointerType Hammer.POINTER_MOUSE
  13579. * @param {PointerEvent} ev
  13580. */
  13581. matchType: function(pointerType, ev) {
  13582. if(!ev.pointerType) {
  13583. return false;
  13584. }
  13585. var types = {};
  13586. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  13587. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  13588. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  13589. return types[pointerType];
  13590. },
  13591. /**
  13592. * get events
  13593. */
  13594. getEvents: function() {
  13595. return [
  13596. 'pointerdown MSPointerDown',
  13597. 'pointermove MSPointerMove',
  13598. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  13599. ];
  13600. },
  13601. /**
  13602. * reset the list
  13603. */
  13604. reset: function() {
  13605. this.pointers = {};
  13606. }
  13607. };
  13608. Hammer.utils = {
  13609. /**
  13610. * extend method,
  13611. * also used for cloning when dest is an empty object
  13612. * @param {Object} dest
  13613. * @param {Object} src
  13614. * @parm {Boolean} merge do a merge
  13615. * @returns {Object} dest
  13616. */
  13617. extend: function extend(dest, src, merge) {
  13618. for (var key in src) {
  13619. if(dest[key] !== undefined && merge) {
  13620. continue;
  13621. }
  13622. dest[key] = src[key];
  13623. }
  13624. return dest;
  13625. },
  13626. /**
  13627. * find if a node is in the given parent
  13628. * used for event delegation tricks
  13629. * @param {HTMLElement} node
  13630. * @param {HTMLElement} parent
  13631. * @returns {boolean} has_parent
  13632. */
  13633. hasParent: function(node, parent) {
  13634. while(node){
  13635. if(node == parent) {
  13636. return true;
  13637. }
  13638. node = node.parentNode;
  13639. }
  13640. return false;
  13641. },
  13642. /**
  13643. * get the center of all the touches
  13644. * @param {Array} touches
  13645. * @returns {Object} center
  13646. */
  13647. getCenter: function getCenter(touches) {
  13648. var valuesX = [], valuesY = [];
  13649. for(var t= 0,len=touches.length; t<len; t++) {
  13650. valuesX.push(touches[t].pageX);
  13651. valuesY.push(touches[t].pageY);
  13652. }
  13653. return {
  13654. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  13655. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  13656. };
  13657. },
  13658. /**
  13659. * calculate the velocity between two points
  13660. * @param {Number} delta_time
  13661. * @param {Number} delta_x
  13662. * @param {Number} delta_y
  13663. * @returns {Object} velocity
  13664. */
  13665. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  13666. return {
  13667. x: Math.abs(delta_x / delta_time) || 0,
  13668. y: Math.abs(delta_y / delta_time) || 0
  13669. };
  13670. },
  13671. /**
  13672. * calculate the angle between two coordinates
  13673. * @param {Touch} touch1
  13674. * @param {Touch} touch2
  13675. * @returns {Number} angle
  13676. */
  13677. getAngle: function getAngle(touch1, touch2) {
  13678. var y = touch2.pageY - touch1.pageY,
  13679. x = touch2.pageX - touch1.pageX;
  13680. return Math.atan2(y, x) * 180 / Math.PI;
  13681. },
  13682. /**
  13683. * angle to direction define
  13684. * @param {Touch} touch1
  13685. * @param {Touch} touch2
  13686. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  13687. */
  13688. getDirection: function getDirection(touch1, touch2) {
  13689. var x = Math.abs(touch1.pageX - touch2.pageX),
  13690. y = Math.abs(touch1.pageY - touch2.pageY);
  13691. if(x >= y) {
  13692. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  13693. }
  13694. else {
  13695. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  13696. }
  13697. },
  13698. /**
  13699. * calculate the distance between two touches
  13700. * @param {Touch} touch1
  13701. * @param {Touch} touch2
  13702. * @returns {Number} distance
  13703. */
  13704. getDistance: function getDistance(touch1, touch2) {
  13705. var x = touch2.pageX - touch1.pageX,
  13706. y = touch2.pageY - touch1.pageY;
  13707. return Math.sqrt((x*x) + (y*y));
  13708. },
  13709. /**
  13710. * calculate the scale factor between two touchLists (fingers)
  13711. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  13712. * @param {Array} start
  13713. * @param {Array} end
  13714. * @returns {Number} scale
  13715. */
  13716. getScale: function getScale(start, end) {
  13717. // need two fingers...
  13718. if(start.length >= 2 && end.length >= 2) {
  13719. return this.getDistance(end[0], end[1]) /
  13720. this.getDistance(start[0], start[1]);
  13721. }
  13722. return 1;
  13723. },
  13724. /**
  13725. * calculate the rotation degrees between two touchLists (fingers)
  13726. * @param {Array} start
  13727. * @param {Array} end
  13728. * @returns {Number} rotation
  13729. */
  13730. getRotation: function getRotation(start, end) {
  13731. // need two fingers
  13732. if(start.length >= 2 && end.length >= 2) {
  13733. return this.getAngle(end[1], end[0]) -
  13734. this.getAngle(start[1], start[0]);
  13735. }
  13736. return 0;
  13737. },
  13738. /**
  13739. * boolean if the direction is vertical
  13740. * @param {String} direction
  13741. * @returns {Boolean} is_vertical
  13742. */
  13743. isVertical: function isVertical(direction) {
  13744. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  13745. },
  13746. /**
  13747. * stop browser default behavior with css props
  13748. * @param {HtmlElement} element
  13749. * @param {Object} css_props
  13750. */
  13751. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  13752. var prop,
  13753. vendors = ['webkit','khtml','moz','ms','o',''];
  13754. if(!css_props || !element.style) {
  13755. return;
  13756. }
  13757. // with css properties for modern browsers
  13758. for(var i = 0; i < vendors.length; i++) {
  13759. for(var p in css_props) {
  13760. if(css_props.hasOwnProperty(p)) {
  13761. prop = p;
  13762. // vender prefix at the property
  13763. if(vendors[i]) {
  13764. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  13765. }
  13766. // set the style
  13767. element.style[prop] = css_props[p];
  13768. }
  13769. }
  13770. }
  13771. // also the disable onselectstart
  13772. if(css_props.userSelect == 'none') {
  13773. element.onselectstart = function() {
  13774. return false;
  13775. };
  13776. }
  13777. }
  13778. };
  13779. Hammer.detection = {
  13780. // contains all registred Hammer.gestures in the correct order
  13781. gestures: [],
  13782. // data of the current Hammer.gesture detection session
  13783. current: null,
  13784. // the previous Hammer.gesture session data
  13785. // is a full clone of the previous gesture.current object
  13786. previous: null,
  13787. // when this becomes true, no gestures are fired
  13788. stopped: false,
  13789. /**
  13790. * start Hammer.gesture detection
  13791. * @param {Hammer.Instance} inst
  13792. * @param {Object} eventData
  13793. */
  13794. startDetect: function startDetect(inst, eventData) {
  13795. // already busy with a Hammer.gesture detection on an element
  13796. if(this.current) {
  13797. return;
  13798. }
  13799. this.stopped = false;
  13800. this.current = {
  13801. inst : inst, // reference to HammerInstance we're working for
  13802. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  13803. lastEvent : false, // last eventData
  13804. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  13805. };
  13806. this.detect(eventData);
  13807. },
  13808. /**
  13809. * Hammer.gesture detection
  13810. * @param {Object} eventData
  13811. * @param {Object} eventData
  13812. */
  13813. detect: function detect(eventData) {
  13814. if(!this.current || this.stopped) {
  13815. return;
  13816. }
  13817. // extend event data with calculations about scale, distance etc
  13818. eventData = this.extendEventData(eventData);
  13819. // instance options
  13820. var inst_options = this.current.inst.options;
  13821. // call Hammer.gesture handlers
  13822. for(var g=0,len=this.gestures.length; g<len; g++) {
  13823. var gesture = this.gestures[g];
  13824. // only when the instance options have enabled this gesture
  13825. if(!this.stopped && inst_options[gesture.name] !== false) {
  13826. // if a handler returns false, we stop with the detection
  13827. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  13828. this.stopDetect();
  13829. break;
  13830. }
  13831. }
  13832. }
  13833. // store as previous event event
  13834. if(this.current) {
  13835. this.current.lastEvent = eventData;
  13836. }
  13837. // endevent, but not the last touch, so dont stop
  13838. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  13839. this.stopDetect();
  13840. }
  13841. return eventData;
  13842. },
  13843. /**
  13844. * clear the Hammer.gesture vars
  13845. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  13846. * to stop other Hammer.gestures from being fired
  13847. */
  13848. stopDetect: function stopDetect() {
  13849. // clone current data to the store as the previous gesture
  13850. // used for the double tap gesture, since this is an other gesture detect session
  13851. this.previous = Hammer.utils.extend({}, this.current);
  13852. // reset the current
  13853. this.current = null;
  13854. // stopped!
  13855. this.stopped = true;
  13856. },
  13857. /**
  13858. * extend eventData for Hammer.gestures
  13859. * @param {Object} ev
  13860. * @returns {Object} ev
  13861. */
  13862. extendEventData: function extendEventData(ev) {
  13863. var startEv = this.current.startEvent;
  13864. // if the touches change, set the new touches over the startEvent touches
  13865. // this because touchevents don't have all the touches on touchstart, or the
  13866. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  13867. // but, sometimes it happens that both fingers are touching at the EXACT same time
  13868. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  13869. // extend 1 level deep to get the touchlist with the touch objects
  13870. startEv.touches = [];
  13871. for(var i=0,len=ev.touches.length; i<len; i++) {
  13872. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  13873. }
  13874. }
  13875. var delta_time = ev.timeStamp - startEv.timeStamp,
  13876. delta_x = ev.center.pageX - startEv.center.pageX,
  13877. delta_y = ev.center.pageY - startEv.center.pageY,
  13878. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  13879. Hammer.utils.extend(ev, {
  13880. deltaTime : delta_time,
  13881. deltaX : delta_x,
  13882. deltaY : delta_y,
  13883. velocityX : velocity.x,
  13884. velocityY : velocity.y,
  13885. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  13886. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  13887. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  13888. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  13889. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  13890. startEvent : startEv
  13891. });
  13892. return ev;
  13893. },
  13894. /**
  13895. * register new gesture
  13896. * @param {Object} gesture object, see gestures.js for documentation
  13897. * @returns {Array} gestures
  13898. */
  13899. register: function register(gesture) {
  13900. // add an enable gesture options if there is no given
  13901. var options = gesture.defaults || {};
  13902. if(options[gesture.name] === undefined) {
  13903. options[gesture.name] = true;
  13904. }
  13905. // extend Hammer default options with the Hammer.gesture options
  13906. Hammer.utils.extend(Hammer.defaults, options, true);
  13907. // set its index
  13908. gesture.index = gesture.index || 1000;
  13909. // add Hammer.gesture to the list
  13910. this.gestures.push(gesture);
  13911. // sort the list by index
  13912. this.gestures.sort(function(a, b) {
  13913. if (a.index < b.index) {
  13914. return -1;
  13915. }
  13916. if (a.index > b.index) {
  13917. return 1;
  13918. }
  13919. return 0;
  13920. });
  13921. return this.gestures;
  13922. }
  13923. };
  13924. Hammer.gestures = Hammer.gestures || {};
  13925. /**
  13926. * Custom gestures
  13927. * ==============================
  13928. *
  13929. * Gesture object
  13930. * --------------------
  13931. * The object structure of a gesture:
  13932. *
  13933. * { name: 'mygesture',
  13934. * index: 1337,
  13935. * defaults: {
  13936. * mygesture_option: true
  13937. * }
  13938. * handler: function(type, ev, inst) {
  13939. * // trigger gesture event
  13940. * inst.trigger(this.name, ev);
  13941. * }
  13942. * }
  13943. * @param {String} name
  13944. * this should be the name of the gesture, lowercase
  13945. * it is also being used to disable/enable the gesture per instance config.
  13946. *
  13947. * @param {Number} [index=1000]
  13948. * the index of the gesture, where it is going to be in the stack of gestures detection
  13949. * like when you build an gesture that depends on the drag gesture, it is a good
  13950. * idea to place it after the index of the drag gesture.
  13951. *
  13952. * @param {Object} [defaults={}]
  13953. * the default settings of the gesture. these are added to the instance settings,
  13954. * and can be overruled per instance. you can also add the name of the gesture,
  13955. * but this is also added by default (and set to true).
  13956. *
  13957. * @param {Function} handler
  13958. * this handles the gesture detection of your custom gesture and receives the
  13959. * following arguments:
  13960. *
  13961. * @param {Object} eventData
  13962. * event data containing the following properties:
  13963. * timeStamp {Number} time the event occurred
  13964. * target {HTMLElement} target element
  13965. * touches {Array} touches (fingers, pointers, mouse) on the screen
  13966. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  13967. * center {Object} center position of the touches. contains pageX and pageY
  13968. * deltaTime {Number} the total time of the touches in the screen
  13969. * deltaX {Number} the delta on x axis we haved moved
  13970. * deltaY {Number} the delta on y axis we haved moved
  13971. * velocityX {Number} the velocity on the x
  13972. * velocityY {Number} the velocity on y
  13973. * angle {Number} the angle we are moving
  13974. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  13975. * distance {Number} the distance we haved moved
  13976. * scale {Number} scaling of the touches, needs 2 touches
  13977. * rotation {Number} rotation of the touches, needs 2 touches *
  13978. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  13979. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  13980. * startEvent {Object} contains the same properties as above,
  13981. * but from the first touch. this is used to calculate
  13982. * distances, deltaTime, scaling etc
  13983. *
  13984. * @param {Hammer.Instance} inst
  13985. * the instance we are doing the detection for. you can get the options from
  13986. * the inst.options object and trigger the gesture event by calling inst.trigger
  13987. *
  13988. *
  13989. * Handle gestures
  13990. * --------------------
  13991. * inside the handler you can get/set Hammer.detection.current. This is the current
  13992. * detection session. It has the following properties
  13993. * @param {String} name
  13994. * contains the name of the gesture we have detected. it has not a real function,
  13995. * only to check in other gestures if something is detected.
  13996. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  13997. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  13998. *
  13999. * @readonly
  14000. * @param {Hammer.Instance} inst
  14001. * the instance we do the detection for
  14002. *
  14003. * @readonly
  14004. * @param {Object} startEvent
  14005. * contains the properties of the first gesture detection in this session.
  14006. * Used for calculations about timing, distance, etc.
  14007. *
  14008. * @readonly
  14009. * @param {Object} lastEvent
  14010. * contains all the properties of the last gesture detect in this session.
  14011. *
  14012. * after the gesture detection session has been completed (user has released the screen)
  14013. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  14014. * this is usefull for gestures like doubletap, where you need to know if the
  14015. * previous gesture was a tap
  14016. *
  14017. * options that have been set by the instance can be received by calling inst.options
  14018. *
  14019. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  14020. * The first param is the name of your gesture, the second the event argument
  14021. *
  14022. *
  14023. * Register gestures
  14024. * --------------------
  14025. * When an gesture is added to the Hammer.gestures object, it is auto registered
  14026. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  14027. * manually and pass your gesture object as a param
  14028. *
  14029. */
  14030. /**
  14031. * Hold
  14032. * Touch stays at the same place for x time
  14033. * @events hold
  14034. */
  14035. Hammer.gestures.Hold = {
  14036. name: 'hold',
  14037. index: 10,
  14038. defaults: {
  14039. hold_timeout : 500,
  14040. hold_threshold : 1
  14041. },
  14042. timer: null,
  14043. handler: function holdGesture(ev, inst) {
  14044. switch(ev.eventType) {
  14045. case Hammer.EVENT_START:
  14046. // clear any running timers
  14047. clearTimeout(this.timer);
  14048. // set the gesture so we can check in the timeout if it still is
  14049. Hammer.detection.current.name = this.name;
  14050. // set timer and if after the timeout it still is hold,
  14051. // we trigger the hold event
  14052. this.timer = setTimeout(function() {
  14053. if(Hammer.detection.current.name == 'hold') {
  14054. inst.trigger('hold', ev);
  14055. }
  14056. }, inst.options.hold_timeout);
  14057. break;
  14058. // when you move or end we clear the timer
  14059. case Hammer.EVENT_MOVE:
  14060. if(ev.distance > inst.options.hold_threshold) {
  14061. clearTimeout(this.timer);
  14062. }
  14063. break;
  14064. case Hammer.EVENT_END:
  14065. clearTimeout(this.timer);
  14066. break;
  14067. }
  14068. }
  14069. };
  14070. /**
  14071. * Tap/DoubleTap
  14072. * Quick touch at a place or double at the same place
  14073. * @events tap, doubletap
  14074. */
  14075. Hammer.gestures.Tap = {
  14076. name: 'tap',
  14077. index: 100,
  14078. defaults: {
  14079. tap_max_touchtime : 250,
  14080. tap_max_distance : 10,
  14081. tap_always : true,
  14082. doubletap_distance : 20,
  14083. doubletap_interval : 300
  14084. },
  14085. handler: function tapGesture(ev, inst) {
  14086. if(ev.eventType == Hammer.EVENT_END) {
  14087. // previous gesture, for the double tap since these are two different gesture detections
  14088. var prev = Hammer.detection.previous,
  14089. did_doubletap = false;
  14090. // when the touchtime is higher then the max touch time
  14091. // or when the moving distance is too much
  14092. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  14093. ev.distance > inst.options.tap_max_distance) {
  14094. return;
  14095. }
  14096. // check if double tap
  14097. if(prev && prev.name == 'tap' &&
  14098. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  14099. ev.distance < inst.options.doubletap_distance) {
  14100. inst.trigger('doubletap', ev);
  14101. did_doubletap = true;
  14102. }
  14103. // do a single tap
  14104. if(!did_doubletap || inst.options.tap_always) {
  14105. Hammer.detection.current.name = 'tap';
  14106. inst.trigger(Hammer.detection.current.name, ev);
  14107. }
  14108. }
  14109. }
  14110. };
  14111. /**
  14112. * Swipe
  14113. * triggers swipe events when the end velocity is above the threshold
  14114. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  14115. */
  14116. Hammer.gestures.Swipe = {
  14117. name: 'swipe',
  14118. index: 40,
  14119. defaults: {
  14120. // set 0 for unlimited, but this can conflict with transform
  14121. swipe_max_touches : 1,
  14122. swipe_velocity : 0.7
  14123. },
  14124. handler: function swipeGesture(ev, inst) {
  14125. if(ev.eventType == Hammer.EVENT_END) {
  14126. // max touches
  14127. if(inst.options.swipe_max_touches > 0 &&
  14128. ev.touches.length > inst.options.swipe_max_touches) {
  14129. return;
  14130. }
  14131. // when the distance we moved is too small we skip this gesture
  14132. // or we can be already in dragging
  14133. if(ev.velocityX > inst.options.swipe_velocity ||
  14134. ev.velocityY > inst.options.swipe_velocity) {
  14135. // trigger swipe events
  14136. inst.trigger(this.name, ev);
  14137. inst.trigger(this.name + ev.direction, ev);
  14138. }
  14139. }
  14140. }
  14141. };
  14142. /**
  14143. * Drag
  14144. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  14145. * moving left and right is a good practice. When all the drag events are blocking
  14146. * you disable scrolling on that area.
  14147. * @events drag, drapleft, dragright, dragup, dragdown
  14148. */
  14149. Hammer.gestures.Drag = {
  14150. name: 'drag',
  14151. index: 50,
  14152. defaults: {
  14153. drag_min_distance : 10,
  14154. // set 0 for unlimited, but this can conflict with transform
  14155. drag_max_touches : 1,
  14156. // prevent default browser behavior when dragging occurs
  14157. // be careful with it, it makes the element a blocking element
  14158. // when you are using the drag gesture, it is a good practice to set this true
  14159. drag_block_horizontal : false,
  14160. drag_block_vertical : false,
  14161. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  14162. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  14163. drag_lock_to_axis : false,
  14164. // drag lock only kicks in when distance > drag_lock_min_distance
  14165. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  14166. drag_lock_min_distance : 25
  14167. },
  14168. triggered: false,
  14169. handler: function dragGesture(ev, inst) {
  14170. // current gesture isnt drag, but dragged is true
  14171. // this means an other gesture is busy. now call dragend
  14172. if(Hammer.detection.current.name != this.name && this.triggered) {
  14173. inst.trigger(this.name +'end', ev);
  14174. this.triggered = false;
  14175. return;
  14176. }
  14177. // max touches
  14178. if(inst.options.drag_max_touches > 0 &&
  14179. ev.touches.length > inst.options.drag_max_touches) {
  14180. return;
  14181. }
  14182. switch(ev.eventType) {
  14183. case Hammer.EVENT_START:
  14184. this.triggered = false;
  14185. break;
  14186. case Hammer.EVENT_MOVE:
  14187. // when the distance we moved is too small we skip this gesture
  14188. // or we can be already in dragging
  14189. if(ev.distance < inst.options.drag_min_distance &&
  14190. Hammer.detection.current.name != this.name) {
  14191. return;
  14192. }
  14193. // we are dragging!
  14194. Hammer.detection.current.name = this.name;
  14195. // lock drag to axis?
  14196. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  14197. ev.drag_locked_to_axis = true;
  14198. }
  14199. var last_direction = Hammer.detection.current.lastEvent.direction;
  14200. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  14201. // keep direction on the axis that the drag gesture started on
  14202. if(Hammer.utils.isVertical(last_direction)) {
  14203. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  14204. }
  14205. else {
  14206. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  14207. }
  14208. }
  14209. // first time, trigger dragstart event
  14210. if(!this.triggered) {
  14211. inst.trigger(this.name +'start', ev);
  14212. this.triggered = true;
  14213. }
  14214. // trigger normal event
  14215. inst.trigger(this.name, ev);
  14216. // direction event, like dragdown
  14217. inst.trigger(this.name + ev.direction, ev);
  14218. // block the browser events
  14219. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  14220. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  14221. ev.preventDefault();
  14222. }
  14223. break;
  14224. case Hammer.EVENT_END:
  14225. // trigger dragend
  14226. if(this.triggered) {
  14227. inst.trigger(this.name +'end', ev);
  14228. }
  14229. this.triggered = false;
  14230. break;
  14231. }
  14232. }
  14233. };
  14234. /**
  14235. * Transform
  14236. * User want to scale or rotate with 2 fingers
  14237. * @events transform, pinch, pinchin, pinchout, rotate
  14238. */
  14239. Hammer.gestures.Transform = {
  14240. name: 'transform',
  14241. index: 45,
  14242. defaults: {
  14243. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  14244. transform_min_scale : 0.01,
  14245. // rotation in degrees
  14246. transform_min_rotation : 1,
  14247. // prevent default browser behavior when two touches are on the screen
  14248. // but it makes the element a blocking element
  14249. // when you are using the transform gesture, it is a good practice to set this true
  14250. transform_always_block : false
  14251. },
  14252. triggered: false,
  14253. handler: function transformGesture(ev, inst) {
  14254. // current gesture isnt drag, but dragged is true
  14255. // this means an other gesture is busy. now call dragend
  14256. if(Hammer.detection.current.name != this.name && this.triggered) {
  14257. inst.trigger(this.name +'end', ev);
  14258. this.triggered = false;
  14259. return;
  14260. }
  14261. // atleast multitouch
  14262. if(ev.touches.length < 2) {
  14263. return;
  14264. }
  14265. // prevent default when two fingers are on the screen
  14266. if(inst.options.transform_always_block) {
  14267. ev.preventDefault();
  14268. }
  14269. switch(ev.eventType) {
  14270. case Hammer.EVENT_START:
  14271. this.triggered = false;
  14272. break;
  14273. case Hammer.EVENT_MOVE:
  14274. var scale_threshold = Math.abs(1-ev.scale);
  14275. var rotation_threshold = Math.abs(ev.rotation);
  14276. // when the distance we moved is too small we skip this gesture
  14277. // or we can be already in dragging
  14278. if(scale_threshold < inst.options.transform_min_scale &&
  14279. rotation_threshold < inst.options.transform_min_rotation) {
  14280. return;
  14281. }
  14282. // we are transforming!
  14283. Hammer.detection.current.name = this.name;
  14284. // first time, trigger dragstart event
  14285. if(!this.triggered) {
  14286. inst.trigger(this.name +'start', ev);
  14287. this.triggered = true;
  14288. }
  14289. inst.trigger(this.name, ev); // basic transform event
  14290. // trigger rotate event
  14291. if(rotation_threshold > inst.options.transform_min_rotation) {
  14292. inst.trigger('rotate', ev);
  14293. }
  14294. // trigger pinch event
  14295. if(scale_threshold > inst.options.transform_min_scale) {
  14296. inst.trigger('pinch', ev);
  14297. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  14298. }
  14299. break;
  14300. case Hammer.EVENT_END:
  14301. // trigger dragend
  14302. if(this.triggered) {
  14303. inst.trigger(this.name +'end', ev);
  14304. }
  14305. this.triggered = false;
  14306. break;
  14307. }
  14308. }
  14309. };
  14310. /**
  14311. * Touch
  14312. * Called as first, tells the user has touched the screen
  14313. * @events touch
  14314. */
  14315. Hammer.gestures.Touch = {
  14316. name: 'touch',
  14317. index: -Infinity,
  14318. defaults: {
  14319. // call preventDefault at touchstart, and makes the element blocking by
  14320. // disabling the scrolling of the page, but it improves gestures like
  14321. // transforming and dragging.
  14322. // be careful with using this, it can be very annoying for users to be stuck
  14323. // on the page
  14324. prevent_default: false,
  14325. // disable mouse events, so only touch (or pen!) input triggers events
  14326. prevent_mouseevents: false
  14327. },
  14328. handler: function touchGesture(ev, inst) {
  14329. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  14330. ev.stopDetect();
  14331. return;
  14332. }
  14333. if(inst.options.prevent_default) {
  14334. ev.preventDefault();
  14335. }
  14336. if(ev.eventType == Hammer.EVENT_START) {
  14337. inst.trigger(this.name, ev);
  14338. }
  14339. }
  14340. };
  14341. /**
  14342. * Release
  14343. * Called as last, tells the user has released the screen
  14344. * @events release
  14345. */
  14346. Hammer.gestures.Release = {
  14347. name: 'release',
  14348. index: Infinity,
  14349. handler: function releaseGesture(ev, inst) {
  14350. if(ev.eventType == Hammer.EVENT_END) {
  14351. inst.trigger(this.name, ev);
  14352. }
  14353. }
  14354. };
  14355. // node export
  14356. if(typeof module === 'object' && typeof module.exports === 'object'){
  14357. module.exports = Hammer;
  14358. }
  14359. // just window export
  14360. else {
  14361. window.Hammer = Hammer;
  14362. // requireJS module definition
  14363. if(typeof window.define === 'function' && window.define.amd) {
  14364. window.define('hammer', [], function() {
  14365. return Hammer;
  14366. });
  14367. }
  14368. }
  14369. })(this);
  14370. },{}],3:[function(require,module,exports){
  14371. //! moment.js
  14372. //! version : 2.5.1
  14373. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  14374. //! license : MIT
  14375. //! momentjs.com
  14376. (function (undefined) {
  14377. /************************************
  14378. Constants
  14379. ************************************/
  14380. var moment,
  14381. VERSION = "2.5.1",
  14382. global = this,
  14383. round = Math.round,
  14384. i,
  14385. YEAR = 0,
  14386. MONTH = 1,
  14387. DATE = 2,
  14388. HOUR = 3,
  14389. MINUTE = 4,
  14390. SECOND = 5,
  14391. MILLISECOND = 6,
  14392. // internal storage for language config files
  14393. languages = {},
  14394. // moment internal properties
  14395. momentProperties = {
  14396. _isAMomentObject: null,
  14397. _i : null,
  14398. _f : null,
  14399. _l : null,
  14400. _strict : null,
  14401. _isUTC : null,
  14402. _offset : null, // optional. Combine with _isUTC
  14403. _pf : null,
  14404. _lang : null // optional
  14405. },
  14406. // check for nodeJS
  14407. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  14408. // ASP.NET json date format regex
  14409. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  14410. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  14411. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  14412. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  14413. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  14414. // format tokens
  14415. 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,
  14416. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  14417. // parsing token regexes
  14418. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  14419. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  14420. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  14421. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  14422. parseTokenDigits = /\d+/, // nonzero number of digits
  14423. 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.
  14424. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  14425. parseTokenT = /T/i, // T (ISO separator)
  14426. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  14427. //strict parsing regexes
  14428. parseTokenOneDigit = /\d/, // 0 - 9
  14429. parseTokenTwoDigits = /\d\d/, // 00 - 99
  14430. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  14431. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  14432. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  14433. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  14434. // iso 8601 regex
  14435. // 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)
  14436. 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)?)?$/,
  14437. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  14438. isoDates = [
  14439. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  14440. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  14441. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  14442. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  14443. ['YYYY-DDD', /\d{4}-\d{3}/]
  14444. ],
  14445. // iso time formats and regexes
  14446. isoTimes = [
  14447. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  14448. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  14449. ['HH:mm', /(T| )\d\d:\d\d/],
  14450. ['HH', /(T| )\d\d/]
  14451. ],
  14452. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  14453. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  14454. // getter and setter names
  14455. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  14456. unitMillisecondFactors = {
  14457. 'Milliseconds' : 1,
  14458. 'Seconds' : 1e3,
  14459. 'Minutes' : 6e4,
  14460. 'Hours' : 36e5,
  14461. 'Days' : 864e5,
  14462. 'Months' : 2592e6,
  14463. 'Years' : 31536e6
  14464. },
  14465. unitAliases = {
  14466. ms : 'millisecond',
  14467. s : 'second',
  14468. m : 'minute',
  14469. h : 'hour',
  14470. d : 'day',
  14471. D : 'date',
  14472. w : 'week',
  14473. W : 'isoWeek',
  14474. M : 'month',
  14475. y : 'year',
  14476. DDD : 'dayOfYear',
  14477. e : 'weekday',
  14478. E : 'isoWeekday',
  14479. gg: 'weekYear',
  14480. GG: 'isoWeekYear'
  14481. },
  14482. camelFunctions = {
  14483. dayofyear : 'dayOfYear',
  14484. isoweekday : 'isoWeekday',
  14485. isoweek : 'isoWeek',
  14486. weekyear : 'weekYear',
  14487. isoweekyear : 'isoWeekYear'
  14488. },
  14489. // format function strings
  14490. formatFunctions = {},
  14491. // tokens to ordinalize and pad
  14492. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  14493. paddedTokens = 'M D H h m s w W'.split(' '),
  14494. formatTokenFunctions = {
  14495. M : function () {
  14496. return this.month() + 1;
  14497. },
  14498. MMM : function (format) {
  14499. return this.lang().monthsShort(this, format);
  14500. },
  14501. MMMM : function (format) {
  14502. return this.lang().months(this, format);
  14503. },
  14504. D : function () {
  14505. return this.date();
  14506. },
  14507. DDD : function () {
  14508. return this.dayOfYear();
  14509. },
  14510. d : function () {
  14511. return this.day();
  14512. },
  14513. dd : function (format) {
  14514. return this.lang().weekdaysMin(this, format);
  14515. },
  14516. ddd : function (format) {
  14517. return this.lang().weekdaysShort(this, format);
  14518. },
  14519. dddd : function (format) {
  14520. return this.lang().weekdays(this, format);
  14521. },
  14522. w : function () {
  14523. return this.week();
  14524. },
  14525. W : function () {
  14526. return this.isoWeek();
  14527. },
  14528. YY : function () {
  14529. return leftZeroFill(this.year() % 100, 2);
  14530. },
  14531. YYYY : function () {
  14532. return leftZeroFill(this.year(), 4);
  14533. },
  14534. YYYYY : function () {
  14535. return leftZeroFill(this.year(), 5);
  14536. },
  14537. YYYYYY : function () {
  14538. var y = this.year(), sign = y >= 0 ? '+' : '-';
  14539. return sign + leftZeroFill(Math.abs(y), 6);
  14540. },
  14541. gg : function () {
  14542. return leftZeroFill(this.weekYear() % 100, 2);
  14543. },
  14544. gggg : function () {
  14545. return leftZeroFill(this.weekYear(), 4);
  14546. },
  14547. ggggg : function () {
  14548. return leftZeroFill(this.weekYear(), 5);
  14549. },
  14550. GG : function () {
  14551. return leftZeroFill(this.isoWeekYear() % 100, 2);
  14552. },
  14553. GGGG : function () {
  14554. return leftZeroFill(this.isoWeekYear(), 4);
  14555. },
  14556. GGGGG : function () {
  14557. return leftZeroFill(this.isoWeekYear(), 5);
  14558. },
  14559. e : function () {
  14560. return this.weekday();
  14561. },
  14562. E : function () {
  14563. return this.isoWeekday();
  14564. },
  14565. a : function () {
  14566. return this.lang().meridiem(this.hours(), this.minutes(), true);
  14567. },
  14568. A : function () {
  14569. return this.lang().meridiem(this.hours(), this.minutes(), false);
  14570. },
  14571. H : function () {
  14572. return this.hours();
  14573. },
  14574. h : function () {
  14575. return this.hours() % 12 || 12;
  14576. },
  14577. m : function () {
  14578. return this.minutes();
  14579. },
  14580. s : function () {
  14581. return this.seconds();
  14582. },
  14583. S : function () {
  14584. return toInt(this.milliseconds() / 100);
  14585. },
  14586. SS : function () {
  14587. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  14588. },
  14589. SSS : function () {
  14590. return leftZeroFill(this.milliseconds(), 3);
  14591. },
  14592. SSSS : function () {
  14593. return leftZeroFill(this.milliseconds(), 3);
  14594. },
  14595. Z : function () {
  14596. var a = -this.zone(),
  14597. b = "+";
  14598. if (a < 0) {
  14599. a = -a;
  14600. b = "-";
  14601. }
  14602. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  14603. },
  14604. ZZ : function () {
  14605. var a = -this.zone(),
  14606. b = "+";
  14607. if (a < 0) {
  14608. a = -a;
  14609. b = "-";
  14610. }
  14611. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  14612. },
  14613. z : function () {
  14614. return this.zoneAbbr();
  14615. },
  14616. zz : function () {
  14617. return this.zoneName();
  14618. },
  14619. X : function () {
  14620. return this.unix();
  14621. },
  14622. Q : function () {
  14623. return this.quarter();
  14624. }
  14625. },
  14626. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  14627. function defaultParsingFlags() {
  14628. // We need to deep clone this object, and es5 standard is not very
  14629. // helpful.
  14630. return {
  14631. empty : false,
  14632. unusedTokens : [],
  14633. unusedInput : [],
  14634. overflow : -2,
  14635. charsLeftOver : 0,
  14636. nullInput : false,
  14637. invalidMonth : null,
  14638. invalidFormat : false,
  14639. userInvalidated : false,
  14640. iso: false
  14641. };
  14642. }
  14643. function padToken(func, count) {
  14644. return function (a) {
  14645. return leftZeroFill(func.call(this, a), count);
  14646. };
  14647. }
  14648. function ordinalizeToken(func, period) {
  14649. return function (a) {
  14650. return this.lang().ordinal(func.call(this, a), period);
  14651. };
  14652. }
  14653. while (ordinalizeTokens.length) {
  14654. i = ordinalizeTokens.pop();
  14655. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  14656. }
  14657. while (paddedTokens.length) {
  14658. i = paddedTokens.pop();
  14659. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  14660. }
  14661. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  14662. /************************************
  14663. Constructors
  14664. ************************************/
  14665. function Language() {
  14666. }
  14667. // Moment prototype object
  14668. function Moment(config) {
  14669. checkOverflow(config);
  14670. extend(this, config);
  14671. }
  14672. // Duration Constructor
  14673. function Duration(duration) {
  14674. var normalizedInput = normalizeObjectUnits(duration),
  14675. years = normalizedInput.year || 0,
  14676. months = normalizedInput.month || 0,
  14677. weeks = normalizedInput.week || 0,
  14678. days = normalizedInput.day || 0,
  14679. hours = normalizedInput.hour || 0,
  14680. minutes = normalizedInput.minute || 0,
  14681. seconds = normalizedInput.second || 0,
  14682. milliseconds = normalizedInput.millisecond || 0;
  14683. // representation for dateAddRemove
  14684. this._milliseconds = +milliseconds +
  14685. seconds * 1e3 + // 1000
  14686. minutes * 6e4 + // 1000 * 60
  14687. hours * 36e5; // 1000 * 60 * 60
  14688. // Because of dateAddRemove treats 24 hours as different from a
  14689. // day when working around DST, we need to store them separately
  14690. this._days = +days +
  14691. weeks * 7;
  14692. // It is impossible translate months into days without knowing
  14693. // which months you are are talking about, so we have to store
  14694. // it separately.
  14695. this._months = +months +
  14696. years * 12;
  14697. this._data = {};
  14698. this._bubble();
  14699. }
  14700. /************************************
  14701. Helpers
  14702. ************************************/
  14703. function extend(a, b) {
  14704. for (var i in b) {
  14705. if (b.hasOwnProperty(i)) {
  14706. a[i] = b[i];
  14707. }
  14708. }
  14709. if (b.hasOwnProperty("toString")) {
  14710. a.toString = b.toString;
  14711. }
  14712. if (b.hasOwnProperty("valueOf")) {
  14713. a.valueOf = b.valueOf;
  14714. }
  14715. return a;
  14716. }
  14717. function cloneMoment(m) {
  14718. var result = {}, i;
  14719. for (i in m) {
  14720. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  14721. result[i] = m[i];
  14722. }
  14723. }
  14724. return result;
  14725. }
  14726. function absRound(number) {
  14727. if (number < 0) {
  14728. return Math.ceil(number);
  14729. } else {
  14730. return Math.floor(number);
  14731. }
  14732. }
  14733. // left zero fill a number
  14734. // see http://jsperf.com/left-zero-filling for performance comparison
  14735. function leftZeroFill(number, targetLength, forceSign) {
  14736. var output = '' + Math.abs(number),
  14737. sign = number >= 0;
  14738. while (output.length < targetLength) {
  14739. output = '0' + output;
  14740. }
  14741. return (sign ? (forceSign ? '+' : '') : '-') + output;
  14742. }
  14743. // helper function for _.addTime and _.subtractTime
  14744. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  14745. var milliseconds = duration._milliseconds,
  14746. days = duration._days,
  14747. months = duration._months,
  14748. minutes,
  14749. hours;
  14750. if (milliseconds) {
  14751. mom._d.setTime(+mom._d + milliseconds * isAdding);
  14752. }
  14753. // store the minutes and hours so we can restore them
  14754. if (days || months) {
  14755. minutes = mom.minute();
  14756. hours = mom.hour();
  14757. }
  14758. if (days) {
  14759. mom.date(mom.date() + days * isAdding);
  14760. }
  14761. if (months) {
  14762. mom.month(mom.month() + months * isAdding);
  14763. }
  14764. if (milliseconds && !ignoreUpdateOffset) {
  14765. moment.updateOffset(mom);
  14766. }
  14767. // restore the minutes and hours after possibly changing dst
  14768. if (days || months) {
  14769. mom.minute(minutes);
  14770. mom.hour(hours);
  14771. }
  14772. }
  14773. // check if is an array
  14774. function isArray(input) {
  14775. return Object.prototype.toString.call(input) === '[object Array]';
  14776. }
  14777. function isDate(input) {
  14778. return Object.prototype.toString.call(input) === '[object Date]' ||
  14779. input instanceof Date;
  14780. }
  14781. // compare two arrays, return the number of differences
  14782. function compareArrays(array1, array2, dontConvert) {
  14783. var len = Math.min(array1.length, array2.length),
  14784. lengthDiff = Math.abs(array1.length - array2.length),
  14785. diffs = 0,
  14786. i;
  14787. for (i = 0; i < len; i++) {
  14788. if ((dontConvert && array1[i] !== array2[i]) ||
  14789. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  14790. diffs++;
  14791. }
  14792. }
  14793. return diffs + lengthDiff;
  14794. }
  14795. function normalizeUnits(units) {
  14796. if (units) {
  14797. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  14798. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  14799. }
  14800. return units;
  14801. }
  14802. function normalizeObjectUnits(inputObject) {
  14803. var normalizedInput = {},
  14804. normalizedProp,
  14805. prop;
  14806. for (prop in inputObject) {
  14807. if (inputObject.hasOwnProperty(prop)) {
  14808. normalizedProp = normalizeUnits(prop);
  14809. if (normalizedProp) {
  14810. normalizedInput[normalizedProp] = inputObject[prop];
  14811. }
  14812. }
  14813. }
  14814. return normalizedInput;
  14815. }
  14816. function makeList(field) {
  14817. var count, setter;
  14818. if (field.indexOf('week') === 0) {
  14819. count = 7;
  14820. setter = 'day';
  14821. }
  14822. else if (field.indexOf('month') === 0) {
  14823. count = 12;
  14824. setter = 'month';
  14825. }
  14826. else {
  14827. return;
  14828. }
  14829. moment[field] = function (format, index) {
  14830. var i, getter,
  14831. method = moment.fn._lang[field],
  14832. results = [];
  14833. if (typeof format === 'number') {
  14834. index = format;
  14835. format = undefined;
  14836. }
  14837. getter = function (i) {
  14838. var m = moment().utc().set(setter, i);
  14839. return method.call(moment.fn._lang, m, format || '');
  14840. };
  14841. if (index != null) {
  14842. return getter(index);
  14843. }
  14844. else {
  14845. for (i = 0; i < count; i++) {
  14846. results.push(getter(i));
  14847. }
  14848. return results;
  14849. }
  14850. };
  14851. }
  14852. function toInt(argumentForCoercion) {
  14853. var coercedNumber = +argumentForCoercion,
  14854. value = 0;
  14855. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  14856. if (coercedNumber >= 0) {
  14857. value = Math.floor(coercedNumber);
  14858. } else {
  14859. value = Math.ceil(coercedNumber);
  14860. }
  14861. }
  14862. return value;
  14863. }
  14864. function daysInMonth(year, month) {
  14865. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  14866. }
  14867. function daysInYear(year) {
  14868. return isLeapYear(year) ? 366 : 365;
  14869. }
  14870. function isLeapYear(year) {
  14871. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  14872. }
  14873. function checkOverflow(m) {
  14874. var overflow;
  14875. if (m._a && m._pf.overflow === -2) {
  14876. overflow =
  14877. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  14878. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  14879. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  14880. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  14881. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  14882. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  14883. -1;
  14884. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  14885. overflow = DATE;
  14886. }
  14887. m._pf.overflow = overflow;
  14888. }
  14889. }
  14890. function isValid(m) {
  14891. if (m._isValid == null) {
  14892. m._isValid = !isNaN(m._d.getTime()) &&
  14893. m._pf.overflow < 0 &&
  14894. !m._pf.empty &&
  14895. !m._pf.invalidMonth &&
  14896. !m._pf.nullInput &&
  14897. !m._pf.invalidFormat &&
  14898. !m._pf.userInvalidated;
  14899. if (m._strict) {
  14900. m._isValid = m._isValid &&
  14901. m._pf.charsLeftOver === 0 &&
  14902. m._pf.unusedTokens.length === 0;
  14903. }
  14904. }
  14905. return m._isValid;
  14906. }
  14907. function normalizeLanguage(key) {
  14908. return key ? key.toLowerCase().replace('_', '-') : key;
  14909. }
  14910. // Return a moment from input, that is local/utc/zone equivalent to model.
  14911. function makeAs(input, model) {
  14912. return model._isUTC ? moment(input).zone(model._offset || 0) :
  14913. moment(input).local();
  14914. }
  14915. /************************************
  14916. Languages
  14917. ************************************/
  14918. extend(Language.prototype, {
  14919. set : function (config) {
  14920. var prop, i;
  14921. for (i in config) {
  14922. prop = config[i];
  14923. if (typeof prop === 'function') {
  14924. this[i] = prop;
  14925. } else {
  14926. this['_' + i] = prop;
  14927. }
  14928. }
  14929. },
  14930. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  14931. months : function (m) {
  14932. return this._months[m.month()];
  14933. },
  14934. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  14935. monthsShort : function (m) {
  14936. return this._monthsShort[m.month()];
  14937. },
  14938. monthsParse : function (monthName) {
  14939. var i, mom, regex;
  14940. if (!this._monthsParse) {
  14941. this._monthsParse = [];
  14942. }
  14943. for (i = 0; i < 12; i++) {
  14944. // make the regex if we don't have it already
  14945. if (!this._monthsParse[i]) {
  14946. mom = moment.utc([2000, i]);
  14947. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  14948. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  14949. }
  14950. // test the regex
  14951. if (this._monthsParse[i].test(monthName)) {
  14952. return i;
  14953. }
  14954. }
  14955. },
  14956. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  14957. weekdays : function (m) {
  14958. return this._weekdays[m.day()];
  14959. },
  14960. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  14961. weekdaysShort : function (m) {
  14962. return this._weekdaysShort[m.day()];
  14963. },
  14964. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  14965. weekdaysMin : function (m) {
  14966. return this._weekdaysMin[m.day()];
  14967. },
  14968. weekdaysParse : function (weekdayName) {
  14969. var i, mom, regex;
  14970. if (!this._weekdaysParse) {
  14971. this._weekdaysParse = [];
  14972. }
  14973. for (i = 0; i < 7; i++) {
  14974. // make the regex if we don't have it already
  14975. if (!this._weekdaysParse[i]) {
  14976. mom = moment([2000, 1]).day(i);
  14977. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  14978. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  14979. }
  14980. // test the regex
  14981. if (this._weekdaysParse[i].test(weekdayName)) {
  14982. return i;
  14983. }
  14984. }
  14985. },
  14986. _longDateFormat : {
  14987. LT : "h:mm A",
  14988. L : "MM/DD/YYYY",
  14989. LL : "MMMM D YYYY",
  14990. LLL : "MMMM D YYYY LT",
  14991. LLLL : "dddd, MMMM D YYYY LT"
  14992. },
  14993. longDateFormat : function (key) {
  14994. var output = this._longDateFormat[key];
  14995. if (!output && this._longDateFormat[key.toUpperCase()]) {
  14996. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  14997. return val.slice(1);
  14998. });
  14999. this._longDateFormat[key] = output;
  15000. }
  15001. return output;
  15002. },
  15003. isPM : function (input) {
  15004. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  15005. // Using charAt should be more compatible.
  15006. return ((input + '').toLowerCase().charAt(0) === 'p');
  15007. },
  15008. _meridiemParse : /[ap]\.?m?\.?/i,
  15009. meridiem : function (hours, minutes, isLower) {
  15010. if (hours > 11) {
  15011. return isLower ? 'pm' : 'PM';
  15012. } else {
  15013. return isLower ? 'am' : 'AM';
  15014. }
  15015. },
  15016. _calendar : {
  15017. sameDay : '[Today at] LT',
  15018. nextDay : '[Tomorrow at] LT',
  15019. nextWeek : 'dddd [at] LT',
  15020. lastDay : '[Yesterday at] LT',
  15021. lastWeek : '[Last] dddd [at] LT',
  15022. sameElse : 'L'
  15023. },
  15024. calendar : function (key, mom) {
  15025. var output = this._calendar[key];
  15026. return typeof output === 'function' ? output.apply(mom) : output;
  15027. },
  15028. _relativeTime : {
  15029. future : "in %s",
  15030. past : "%s ago",
  15031. s : "a few seconds",
  15032. m : "a minute",
  15033. mm : "%d minutes",
  15034. h : "an hour",
  15035. hh : "%d hours",
  15036. d : "a day",
  15037. dd : "%d days",
  15038. M : "a month",
  15039. MM : "%d months",
  15040. y : "a year",
  15041. yy : "%d years"
  15042. },
  15043. relativeTime : function (number, withoutSuffix, string, isFuture) {
  15044. var output = this._relativeTime[string];
  15045. return (typeof output === 'function') ?
  15046. output(number, withoutSuffix, string, isFuture) :
  15047. output.replace(/%d/i, number);
  15048. },
  15049. pastFuture : function (diff, output) {
  15050. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  15051. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  15052. },
  15053. ordinal : function (number) {
  15054. return this._ordinal.replace("%d", number);
  15055. },
  15056. _ordinal : "%d",
  15057. preparse : function (string) {
  15058. return string;
  15059. },
  15060. postformat : function (string) {
  15061. return string;
  15062. },
  15063. week : function (mom) {
  15064. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  15065. },
  15066. _week : {
  15067. dow : 0, // Sunday is the first day of the week.
  15068. doy : 6 // The week that contains Jan 1st is the first week of the year.
  15069. },
  15070. _invalidDate: 'Invalid date',
  15071. invalidDate: function () {
  15072. return this._invalidDate;
  15073. }
  15074. });
  15075. // Loads a language definition into the `languages` cache. The function
  15076. // takes a key and optionally values. If not in the browser and no values
  15077. // are provided, it will load the language file module. As a convenience,
  15078. // this function also returns the language values.
  15079. function loadLang(key, values) {
  15080. values.abbr = key;
  15081. if (!languages[key]) {
  15082. languages[key] = new Language();
  15083. }
  15084. languages[key].set(values);
  15085. return languages[key];
  15086. }
  15087. // Remove a language from the `languages` cache. Mostly useful in tests.
  15088. function unloadLang(key) {
  15089. delete languages[key];
  15090. }
  15091. // Determines which language definition to use and returns it.
  15092. //
  15093. // With no parameters, it will return the global language. If you
  15094. // pass in a language key, such as 'en', it will return the
  15095. // definition for 'en', so long as 'en' has already been loaded using
  15096. // moment.lang.
  15097. function getLangDefinition(key) {
  15098. var i = 0, j, lang, next, split,
  15099. get = function (k) {
  15100. if (!languages[k] && hasModule) {
  15101. try {
  15102. require('./lang/' + k);
  15103. } catch (e) { }
  15104. }
  15105. return languages[k];
  15106. };
  15107. if (!key) {
  15108. return moment.fn._lang;
  15109. }
  15110. if (!isArray(key)) {
  15111. //short-circuit everything else
  15112. lang = get(key);
  15113. if (lang) {
  15114. return lang;
  15115. }
  15116. key = [key];
  15117. }
  15118. //pick the language from the array
  15119. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  15120. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  15121. while (i < key.length) {
  15122. split = normalizeLanguage(key[i]).split('-');
  15123. j = split.length;
  15124. next = normalizeLanguage(key[i + 1]);
  15125. next = next ? next.split('-') : null;
  15126. while (j > 0) {
  15127. lang = get(split.slice(0, j).join('-'));
  15128. if (lang) {
  15129. return lang;
  15130. }
  15131. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  15132. //the next array item is better than a shallower substring of this one
  15133. break;
  15134. }
  15135. j--;
  15136. }
  15137. i++;
  15138. }
  15139. return moment.fn._lang;
  15140. }
  15141. /************************************
  15142. Formatting
  15143. ************************************/
  15144. function removeFormattingTokens(input) {
  15145. if (input.match(/\[[\s\S]/)) {
  15146. return input.replace(/^\[|\]$/g, "");
  15147. }
  15148. return input.replace(/\\/g, "");
  15149. }
  15150. function makeFormatFunction(format) {
  15151. var array = format.match(formattingTokens), i, length;
  15152. for (i = 0, length = array.length; i < length; i++) {
  15153. if (formatTokenFunctions[array[i]]) {
  15154. array[i] = formatTokenFunctions[array[i]];
  15155. } else {
  15156. array[i] = removeFormattingTokens(array[i]);
  15157. }
  15158. }
  15159. return function (mom) {
  15160. var output = "";
  15161. for (i = 0; i < length; i++) {
  15162. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  15163. }
  15164. return output;
  15165. };
  15166. }
  15167. // format date using native date object
  15168. function formatMoment(m, format) {
  15169. if (!m.isValid()) {
  15170. return m.lang().invalidDate();
  15171. }
  15172. format = expandFormat(format, m.lang());
  15173. if (!formatFunctions[format]) {
  15174. formatFunctions[format] = makeFormatFunction(format);
  15175. }
  15176. return formatFunctions[format](m);
  15177. }
  15178. function expandFormat(format, lang) {
  15179. var i = 5;
  15180. function replaceLongDateFormatTokens(input) {
  15181. return lang.longDateFormat(input) || input;
  15182. }
  15183. localFormattingTokens.lastIndex = 0;
  15184. while (i >= 0 && localFormattingTokens.test(format)) {
  15185. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  15186. localFormattingTokens.lastIndex = 0;
  15187. i -= 1;
  15188. }
  15189. return format;
  15190. }
  15191. /************************************
  15192. Parsing
  15193. ************************************/
  15194. // get the regex to find the next token
  15195. function getParseRegexForToken(token, config) {
  15196. var a, strict = config._strict;
  15197. switch (token) {
  15198. case 'DDDD':
  15199. return parseTokenThreeDigits;
  15200. case 'YYYY':
  15201. case 'GGGG':
  15202. case 'gggg':
  15203. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  15204. case 'Y':
  15205. case 'G':
  15206. case 'g':
  15207. return parseTokenSignedNumber;
  15208. case 'YYYYYY':
  15209. case 'YYYYY':
  15210. case 'GGGGG':
  15211. case 'ggggg':
  15212. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  15213. case 'S':
  15214. if (strict) { return parseTokenOneDigit; }
  15215. /* falls through */
  15216. case 'SS':
  15217. if (strict) { return parseTokenTwoDigits; }
  15218. /* falls through */
  15219. case 'SSS':
  15220. if (strict) { return parseTokenThreeDigits; }
  15221. /* falls through */
  15222. case 'DDD':
  15223. return parseTokenOneToThreeDigits;
  15224. case 'MMM':
  15225. case 'MMMM':
  15226. case 'dd':
  15227. case 'ddd':
  15228. case 'dddd':
  15229. return parseTokenWord;
  15230. case 'a':
  15231. case 'A':
  15232. return getLangDefinition(config._l)._meridiemParse;
  15233. case 'X':
  15234. return parseTokenTimestampMs;
  15235. case 'Z':
  15236. case 'ZZ':
  15237. return parseTokenTimezone;
  15238. case 'T':
  15239. return parseTokenT;
  15240. case 'SSSS':
  15241. return parseTokenDigits;
  15242. case 'MM':
  15243. case 'DD':
  15244. case 'YY':
  15245. case 'GG':
  15246. case 'gg':
  15247. case 'HH':
  15248. case 'hh':
  15249. case 'mm':
  15250. case 'ss':
  15251. case 'ww':
  15252. case 'WW':
  15253. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  15254. case 'M':
  15255. case 'D':
  15256. case 'd':
  15257. case 'H':
  15258. case 'h':
  15259. case 'm':
  15260. case 's':
  15261. case 'w':
  15262. case 'W':
  15263. case 'e':
  15264. case 'E':
  15265. return parseTokenOneOrTwoDigits;
  15266. default :
  15267. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  15268. return a;
  15269. }
  15270. }
  15271. function timezoneMinutesFromString(string) {
  15272. string = string || "";
  15273. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  15274. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  15275. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  15276. minutes = +(parts[1] * 60) + toInt(parts[2]);
  15277. return parts[0] === '+' ? -minutes : minutes;
  15278. }
  15279. // function to convert string input to date
  15280. function addTimeToArrayFromToken(token, input, config) {
  15281. var a, datePartArray = config._a;
  15282. switch (token) {
  15283. // MONTH
  15284. case 'M' : // fall through to MM
  15285. case 'MM' :
  15286. if (input != null) {
  15287. datePartArray[MONTH] = toInt(input) - 1;
  15288. }
  15289. break;
  15290. case 'MMM' : // fall through to MMMM
  15291. case 'MMMM' :
  15292. a = getLangDefinition(config._l).monthsParse(input);
  15293. // if we didn't find a month name, mark the date as invalid.
  15294. if (a != null) {
  15295. datePartArray[MONTH] = a;
  15296. } else {
  15297. config._pf.invalidMonth = input;
  15298. }
  15299. break;
  15300. // DAY OF MONTH
  15301. case 'D' : // fall through to DD
  15302. case 'DD' :
  15303. if (input != null) {
  15304. datePartArray[DATE] = toInt(input);
  15305. }
  15306. break;
  15307. // DAY OF YEAR
  15308. case 'DDD' : // fall through to DDDD
  15309. case 'DDDD' :
  15310. if (input != null) {
  15311. config._dayOfYear = toInt(input);
  15312. }
  15313. break;
  15314. // YEAR
  15315. case 'YY' :
  15316. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  15317. break;
  15318. case 'YYYY' :
  15319. case 'YYYYY' :
  15320. case 'YYYYYY' :
  15321. datePartArray[YEAR] = toInt(input);
  15322. break;
  15323. // AM / PM
  15324. case 'a' : // fall through to A
  15325. case 'A' :
  15326. config._isPm = getLangDefinition(config._l).isPM(input);
  15327. break;
  15328. // 24 HOUR
  15329. case 'H' : // fall through to hh
  15330. case 'HH' : // fall through to hh
  15331. case 'h' : // fall through to hh
  15332. case 'hh' :
  15333. datePartArray[HOUR] = toInt(input);
  15334. break;
  15335. // MINUTE
  15336. case 'm' : // fall through to mm
  15337. case 'mm' :
  15338. datePartArray[MINUTE] = toInt(input);
  15339. break;
  15340. // SECOND
  15341. case 's' : // fall through to ss
  15342. case 'ss' :
  15343. datePartArray[SECOND] = toInt(input);
  15344. break;
  15345. // MILLISECOND
  15346. case 'S' :
  15347. case 'SS' :
  15348. case 'SSS' :
  15349. case 'SSSS' :
  15350. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  15351. break;
  15352. // UNIX TIMESTAMP WITH MS
  15353. case 'X':
  15354. config._d = new Date(parseFloat(input) * 1000);
  15355. break;
  15356. // TIMEZONE
  15357. case 'Z' : // fall through to ZZ
  15358. case 'ZZ' :
  15359. config._useUTC = true;
  15360. config._tzm = timezoneMinutesFromString(input);
  15361. break;
  15362. case 'w':
  15363. case 'ww':
  15364. case 'W':
  15365. case 'WW':
  15366. case 'd':
  15367. case 'dd':
  15368. case 'ddd':
  15369. case 'dddd':
  15370. case 'e':
  15371. case 'E':
  15372. token = token.substr(0, 1);
  15373. /* falls through */
  15374. case 'gg':
  15375. case 'gggg':
  15376. case 'GG':
  15377. case 'GGGG':
  15378. case 'GGGGG':
  15379. token = token.substr(0, 2);
  15380. if (input) {
  15381. config._w = config._w || {};
  15382. config._w[token] = input;
  15383. }
  15384. break;
  15385. }
  15386. }
  15387. // convert an array to a date.
  15388. // the array should mirror the parameters below
  15389. // note: all values past the year are optional and will default to the lowest possible value.
  15390. // [year, month, day , hour, minute, second, millisecond]
  15391. function dateFromConfig(config) {
  15392. var i, date, input = [], currentDate,
  15393. yearToUse, fixYear, w, temp, lang, weekday, week;
  15394. if (config._d) {
  15395. return;
  15396. }
  15397. currentDate = currentDateArray(config);
  15398. //compute day of the year from weeks and weekdays
  15399. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  15400. fixYear = function (val) {
  15401. var int_val = parseInt(val, 10);
  15402. return val ?
  15403. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  15404. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  15405. };
  15406. w = config._w;
  15407. if (w.GG != null || w.W != null || w.E != null) {
  15408. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  15409. }
  15410. else {
  15411. lang = getLangDefinition(config._l);
  15412. weekday = w.d != null ? parseWeekday(w.d, lang) :
  15413. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  15414. week = parseInt(w.w, 10) || 1;
  15415. //if we're parsing 'd', then the low day numbers may be next week
  15416. if (w.d != null && weekday < lang._week.dow) {
  15417. week++;
  15418. }
  15419. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  15420. }
  15421. config._a[YEAR] = temp.year;
  15422. config._dayOfYear = temp.dayOfYear;
  15423. }
  15424. //if the day of the year is set, figure out what it is
  15425. if (config._dayOfYear) {
  15426. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  15427. if (config._dayOfYear > daysInYear(yearToUse)) {
  15428. config._pf._overflowDayOfYear = true;
  15429. }
  15430. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  15431. config._a[MONTH] = date.getUTCMonth();
  15432. config._a[DATE] = date.getUTCDate();
  15433. }
  15434. // Default to current date.
  15435. // * if no year, month, day of month are given, default to today
  15436. // * if day of month is given, default month and year
  15437. // * if month is given, default only year
  15438. // * if year is given, don't default anything
  15439. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  15440. config._a[i] = input[i] = currentDate[i];
  15441. }
  15442. // Zero out whatever was not defaulted, including time
  15443. for (; i < 7; i++) {
  15444. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  15445. }
  15446. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  15447. input[HOUR] += toInt((config._tzm || 0) / 60);
  15448. input[MINUTE] += toInt((config._tzm || 0) % 60);
  15449. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  15450. }
  15451. function dateFromObject(config) {
  15452. var normalizedInput;
  15453. if (config._d) {
  15454. return;
  15455. }
  15456. normalizedInput = normalizeObjectUnits(config._i);
  15457. config._a = [
  15458. normalizedInput.year,
  15459. normalizedInput.month,
  15460. normalizedInput.day,
  15461. normalizedInput.hour,
  15462. normalizedInput.minute,
  15463. normalizedInput.second,
  15464. normalizedInput.millisecond
  15465. ];
  15466. dateFromConfig(config);
  15467. }
  15468. function currentDateArray(config) {
  15469. var now = new Date();
  15470. if (config._useUTC) {
  15471. return [
  15472. now.getUTCFullYear(),
  15473. now.getUTCMonth(),
  15474. now.getUTCDate()
  15475. ];
  15476. } else {
  15477. return [now.getFullYear(), now.getMonth(), now.getDate()];
  15478. }
  15479. }
  15480. // date from string and format string
  15481. function makeDateFromStringAndFormat(config) {
  15482. config._a = [];
  15483. config._pf.empty = true;
  15484. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  15485. var lang = getLangDefinition(config._l),
  15486. string = '' + config._i,
  15487. i, parsedInput, tokens, token, skipped,
  15488. stringLength = string.length,
  15489. totalParsedInputLength = 0;
  15490. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  15491. for (i = 0; i < tokens.length; i++) {
  15492. token = tokens[i];
  15493. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  15494. if (parsedInput) {
  15495. skipped = string.substr(0, string.indexOf(parsedInput));
  15496. if (skipped.length > 0) {
  15497. config._pf.unusedInput.push(skipped);
  15498. }
  15499. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  15500. totalParsedInputLength += parsedInput.length;
  15501. }
  15502. // don't parse if it's not a known token
  15503. if (formatTokenFunctions[token]) {
  15504. if (parsedInput) {
  15505. config._pf.empty = false;
  15506. }
  15507. else {
  15508. config._pf.unusedTokens.push(token);
  15509. }
  15510. addTimeToArrayFromToken(token, parsedInput, config);
  15511. }
  15512. else if (config._strict && !parsedInput) {
  15513. config._pf.unusedTokens.push(token);
  15514. }
  15515. }
  15516. // add remaining unparsed input length to the string
  15517. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  15518. if (string.length > 0) {
  15519. config._pf.unusedInput.push(string);
  15520. }
  15521. // handle am pm
  15522. if (config._isPm && config._a[HOUR] < 12) {
  15523. config._a[HOUR] += 12;
  15524. }
  15525. // if is 12 am, change hours to 0
  15526. if (config._isPm === false && config._a[HOUR] === 12) {
  15527. config._a[HOUR] = 0;
  15528. }
  15529. dateFromConfig(config);
  15530. checkOverflow(config);
  15531. }
  15532. function unescapeFormat(s) {
  15533. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  15534. return p1 || p2 || p3 || p4;
  15535. });
  15536. }
  15537. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  15538. function regexpEscape(s) {
  15539. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  15540. }
  15541. // date from string and array of format strings
  15542. function makeDateFromStringAndArray(config) {
  15543. var tempConfig,
  15544. bestMoment,
  15545. scoreToBeat,
  15546. i,
  15547. currentScore;
  15548. if (config._f.length === 0) {
  15549. config._pf.invalidFormat = true;
  15550. config._d = new Date(NaN);
  15551. return;
  15552. }
  15553. for (i = 0; i < config._f.length; i++) {
  15554. currentScore = 0;
  15555. tempConfig = extend({}, config);
  15556. tempConfig._pf = defaultParsingFlags();
  15557. tempConfig._f = config._f[i];
  15558. makeDateFromStringAndFormat(tempConfig);
  15559. if (!isValid(tempConfig)) {
  15560. continue;
  15561. }
  15562. // if there is any input that was not parsed add a penalty for that format
  15563. currentScore += tempConfig._pf.charsLeftOver;
  15564. //or tokens
  15565. currentScore += tempConfig._pf.unusedTokens.length * 10;
  15566. tempConfig._pf.score = currentScore;
  15567. if (scoreToBeat == null || currentScore < scoreToBeat) {
  15568. scoreToBeat = currentScore;
  15569. bestMoment = tempConfig;
  15570. }
  15571. }
  15572. extend(config, bestMoment || tempConfig);
  15573. }
  15574. // date from iso format
  15575. function makeDateFromString(config) {
  15576. var i, l,
  15577. string = config._i,
  15578. match = isoRegex.exec(string);
  15579. if (match) {
  15580. config._pf.iso = true;
  15581. for (i = 0, l = isoDates.length; i < l; i++) {
  15582. if (isoDates[i][1].exec(string)) {
  15583. // match[5] should be "T" or undefined
  15584. config._f = isoDates[i][0] + (match[6] || " ");
  15585. break;
  15586. }
  15587. }
  15588. for (i = 0, l = isoTimes.length; i < l; i++) {
  15589. if (isoTimes[i][1].exec(string)) {
  15590. config._f += isoTimes[i][0];
  15591. break;
  15592. }
  15593. }
  15594. if (string.match(parseTokenTimezone)) {
  15595. config._f += "Z";
  15596. }
  15597. makeDateFromStringAndFormat(config);
  15598. }
  15599. else {
  15600. config._d = new Date(string);
  15601. }
  15602. }
  15603. function makeDateFromInput(config) {
  15604. var input = config._i,
  15605. matched = aspNetJsonRegex.exec(input);
  15606. if (input === undefined) {
  15607. config._d = new Date();
  15608. } else if (matched) {
  15609. config._d = new Date(+matched[1]);
  15610. } else if (typeof input === 'string') {
  15611. makeDateFromString(config);
  15612. } else if (isArray(input)) {
  15613. config._a = input.slice(0);
  15614. dateFromConfig(config);
  15615. } else if (isDate(input)) {
  15616. config._d = new Date(+input);
  15617. } else if (typeof(input) === 'object') {
  15618. dateFromObject(config);
  15619. } else {
  15620. config._d = new Date(input);
  15621. }
  15622. }
  15623. function makeDate(y, m, d, h, M, s, ms) {
  15624. //can't just apply() to create a date:
  15625. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  15626. var date = new Date(y, m, d, h, M, s, ms);
  15627. //the date constructor doesn't accept years < 1970
  15628. if (y < 1970) {
  15629. date.setFullYear(y);
  15630. }
  15631. return date;
  15632. }
  15633. function makeUTCDate(y) {
  15634. var date = new Date(Date.UTC.apply(null, arguments));
  15635. if (y < 1970) {
  15636. date.setUTCFullYear(y);
  15637. }
  15638. return date;
  15639. }
  15640. function parseWeekday(input, language) {
  15641. if (typeof input === 'string') {
  15642. if (!isNaN(input)) {
  15643. input = parseInt(input, 10);
  15644. }
  15645. else {
  15646. input = language.weekdaysParse(input);
  15647. if (typeof input !== 'number') {
  15648. return null;
  15649. }
  15650. }
  15651. }
  15652. return input;
  15653. }
  15654. /************************************
  15655. Relative Time
  15656. ************************************/
  15657. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  15658. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  15659. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  15660. }
  15661. function relativeTime(milliseconds, withoutSuffix, lang) {
  15662. var seconds = round(Math.abs(milliseconds) / 1000),
  15663. minutes = round(seconds / 60),
  15664. hours = round(minutes / 60),
  15665. days = round(hours / 24),
  15666. years = round(days / 365),
  15667. args = seconds < 45 && ['s', seconds] ||
  15668. minutes === 1 && ['m'] ||
  15669. minutes < 45 && ['mm', minutes] ||
  15670. hours === 1 && ['h'] ||
  15671. hours < 22 && ['hh', hours] ||
  15672. days === 1 && ['d'] ||
  15673. days <= 25 && ['dd', days] ||
  15674. days <= 45 && ['M'] ||
  15675. days < 345 && ['MM', round(days / 30)] ||
  15676. years === 1 && ['y'] || ['yy', years];
  15677. args[2] = withoutSuffix;
  15678. args[3] = milliseconds > 0;
  15679. args[4] = lang;
  15680. return substituteTimeAgo.apply({}, args);
  15681. }
  15682. /************************************
  15683. Week of Year
  15684. ************************************/
  15685. // firstDayOfWeek 0 = sun, 6 = sat
  15686. // the day of the week that starts the week
  15687. // (usually sunday or monday)
  15688. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  15689. // the first week is the week that contains the first
  15690. // of this day of the week
  15691. // (eg. ISO weeks use thursday (4))
  15692. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  15693. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  15694. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  15695. adjustedMoment;
  15696. if (daysToDayOfWeek > end) {
  15697. daysToDayOfWeek -= 7;
  15698. }
  15699. if (daysToDayOfWeek < end - 7) {
  15700. daysToDayOfWeek += 7;
  15701. }
  15702. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  15703. return {
  15704. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  15705. year: adjustedMoment.year()
  15706. };
  15707. }
  15708. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  15709. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  15710. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  15711. weekday = weekday != null ? weekday : firstDayOfWeek;
  15712. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  15713. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  15714. return {
  15715. year: dayOfYear > 0 ? year : year - 1,
  15716. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  15717. };
  15718. }
  15719. /************************************
  15720. Top Level Functions
  15721. ************************************/
  15722. function makeMoment(config) {
  15723. var input = config._i,
  15724. format = config._f;
  15725. if (input === null) {
  15726. return moment.invalid({nullInput: true});
  15727. }
  15728. if (typeof input === 'string') {
  15729. config._i = input = getLangDefinition().preparse(input);
  15730. }
  15731. if (moment.isMoment(input)) {
  15732. config = cloneMoment(input);
  15733. config._d = new Date(+input._d);
  15734. } else if (format) {
  15735. if (isArray(format)) {
  15736. makeDateFromStringAndArray(config);
  15737. } else {
  15738. makeDateFromStringAndFormat(config);
  15739. }
  15740. } else {
  15741. makeDateFromInput(config);
  15742. }
  15743. return new Moment(config);
  15744. }
  15745. moment = function (input, format, lang, strict) {
  15746. var c;
  15747. if (typeof(lang) === "boolean") {
  15748. strict = lang;
  15749. lang = undefined;
  15750. }
  15751. // object construction must be done this way.
  15752. // https://github.com/moment/moment/issues/1423
  15753. c = {};
  15754. c._isAMomentObject = true;
  15755. c._i = input;
  15756. c._f = format;
  15757. c._l = lang;
  15758. c._strict = strict;
  15759. c._isUTC = false;
  15760. c._pf = defaultParsingFlags();
  15761. return makeMoment(c);
  15762. };
  15763. // creating with utc
  15764. moment.utc = function (input, format, lang, strict) {
  15765. var c;
  15766. if (typeof(lang) === "boolean") {
  15767. strict = lang;
  15768. lang = undefined;
  15769. }
  15770. // object construction must be done this way.
  15771. // https://github.com/moment/moment/issues/1423
  15772. c = {};
  15773. c._isAMomentObject = true;
  15774. c._useUTC = true;
  15775. c._isUTC = true;
  15776. c._l = lang;
  15777. c._i = input;
  15778. c._f = format;
  15779. c._strict = strict;
  15780. c._pf = defaultParsingFlags();
  15781. return makeMoment(c).utc();
  15782. };
  15783. // creating with unix timestamp (in seconds)
  15784. moment.unix = function (input) {
  15785. return moment(input * 1000);
  15786. };
  15787. // duration
  15788. moment.duration = function (input, key) {
  15789. var duration = input,
  15790. // matching against regexp is expensive, do it on demand
  15791. match = null,
  15792. sign,
  15793. ret,
  15794. parseIso;
  15795. if (moment.isDuration(input)) {
  15796. duration = {
  15797. ms: input._milliseconds,
  15798. d: input._days,
  15799. M: input._months
  15800. };
  15801. } else if (typeof input === 'number') {
  15802. duration = {};
  15803. if (key) {
  15804. duration[key] = input;
  15805. } else {
  15806. duration.milliseconds = input;
  15807. }
  15808. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  15809. sign = (match[1] === "-") ? -1 : 1;
  15810. duration = {
  15811. y: 0,
  15812. d: toInt(match[DATE]) * sign,
  15813. h: toInt(match[HOUR]) * sign,
  15814. m: toInt(match[MINUTE]) * sign,
  15815. s: toInt(match[SECOND]) * sign,
  15816. ms: toInt(match[MILLISECOND]) * sign
  15817. };
  15818. } else if (!!(match = isoDurationRegex.exec(input))) {
  15819. sign = (match[1] === "-") ? -1 : 1;
  15820. parseIso = function (inp) {
  15821. // We'd normally use ~~inp for this, but unfortunately it also
  15822. // converts floats to ints.
  15823. // inp may be undefined, so careful calling replace on it.
  15824. var res = inp && parseFloat(inp.replace(',', '.'));
  15825. // apply sign while we're at it
  15826. return (isNaN(res) ? 0 : res) * sign;
  15827. };
  15828. duration = {
  15829. y: parseIso(match[2]),
  15830. M: parseIso(match[3]),
  15831. d: parseIso(match[4]),
  15832. h: parseIso(match[5]),
  15833. m: parseIso(match[6]),
  15834. s: parseIso(match[7]),
  15835. w: parseIso(match[8])
  15836. };
  15837. }
  15838. ret = new Duration(duration);
  15839. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  15840. ret._lang = input._lang;
  15841. }
  15842. return ret;
  15843. };
  15844. // version number
  15845. moment.version = VERSION;
  15846. // default format
  15847. moment.defaultFormat = isoFormat;
  15848. // This function will be called whenever a moment is mutated.
  15849. // It is intended to keep the offset in sync with the timezone.
  15850. moment.updateOffset = function () {};
  15851. // This function will load languages and then set the global language. If
  15852. // no arguments are passed in, it will simply return the current global
  15853. // language key.
  15854. moment.lang = function (key, values) {
  15855. var r;
  15856. if (!key) {
  15857. return moment.fn._lang._abbr;
  15858. }
  15859. if (values) {
  15860. loadLang(normalizeLanguage(key), values);
  15861. } else if (values === null) {
  15862. unloadLang(key);
  15863. key = 'en';
  15864. } else if (!languages[key]) {
  15865. getLangDefinition(key);
  15866. }
  15867. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  15868. return r._abbr;
  15869. };
  15870. // returns language data
  15871. moment.langData = function (key) {
  15872. if (key && key._lang && key._lang._abbr) {
  15873. key = key._lang._abbr;
  15874. }
  15875. return getLangDefinition(key);
  15876. };
  15877. // compare moment object
  15878. moment.isMoment = function (obj) {
  15879. return obj instanceof Moment ||
  15880. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  15881. };
  15882. // for typechecking Duration objects
  15883. moment.isDuration = function (obj) {
  15884. return obj instanceof Duration;
  15885. };
  15886. for (i = lists.length - 1; i >= 0; --i) {
  15887. makeList(lists[i]);
  15888. }
  15889. moment.normalizeUnits = function (units) {
  15890. return normalizeUnits(units);
  15891. };
  15892. moment.invalid = function (flags) {
  15893. var m = moment.utc(NaN);
  15894. if (flags != null) {
  15895. extend(m._pf, flags);
  15896. }
  15897. else {
  15898. m._pf.userInvalidated = true;
  15899. }
  15900. return m;
  15901. };
  15902. moment.parseZone = function (input) {
  15903. return moment(input).parseZone();
  15904. };
  15905. /************************************
  15906. Moment Prototype
  15907. ************************************/
  15908. extend(moment.fn = Moment.prototype, {
  15909. clone : function () {
  15910. return moment(this);
  15911. },
  15912. valueOf : function () {
  15913. return +this._d + ((this._offset || 0) * 60000);
  15914. },
  15915. unix : function () {
  15916. return Math.floor(+this / 1000);
  15917. },
  15918. toString : function () {
  15919. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  15920. },
  15921. toDate : function () {
  15922. return this._offset ? new Date(+this) : this._d;
  15923. },
  15924. toISOString : function () {
  15925. var m = moment(this).utc();
  15926. if (0 < m.year() && m.year() <= 9999) {
  15927. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  15928. } else {
  15929. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  15930. }
  15931. },
  15932. toArray : function () {
  15933. var m = this;
  15934. return [
  15935. m.year(),
  15936. m.month(),
  15937. m.date(),
  15938. m.hours(),
  15939. m.minutes(),
  15940. m.seconds(),
  15941. m.milliseconds()
  15942. ];
  15943. },
  15944. isValid : function () {
  15945. return isValid(this);
  15946. },
  15947. isDSTShifted : function () {
  15948. if (this._a) {
  15949. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  15950. }
  15951. return false;
  15952. },
  15953. parsingFlags : function () {
  15954. return extend({}, this._pf);
  15955. },
  15956. invalidAt: function () {
  15957. return this._pf.overflow;
  15958. },
  15959. utc : function () {
  15960. return this.zone(0);
  15961. },
  15962. local : function () {
  15963. this.zone(0);
  15964. this._isUTC = false;
  15965. return this;
  15966. },
  15967. format : function (inputString) {
  15968. var output = formatMoment(this, inputString || moment.defaultFormat);
  15969. return this.lang().postformat(output);
  15970. },
  15971. add : function (input, val) {
  15972. var dur;
  15973. // switch args to support add('s', 1) and add(1, 's')
  15974. if (typeof input === 'string') {
  15975. dur = moment.duration(+val, input);
  15976. } else {
  15977. dur = moment.duration(input, val);
  15978. }
  15979. addOrSubtractDurationFromMoment(this, dur, 1);
  15980. return this;
  15981. },
  15982. subtract : function (input, val) {
  15983. var dur;
  15984. // switch args to support subtract('s', 1) and subtract(1, 's')
  15985. if (typeof input === 'string') {
  15986. dur = moment.duration(+val, input);
  15987. } else {
  15988. dur = moment.duration(input, val);
  15989. }
  15990. addOrSubtractDurationFromMoment(this, dur, -1);
  15991. return this;
  15992. },
  15993. diff : function (input, units, asFloat) {
  15994. var that = makeAs(input, this),
  15995. zoneDiff = (this.zone() - that.zone()) * 6e4,
  15996. diff, output;
  15997. units = normalizeUnits(units);
  15998. if (units === 'year' || units === 'month') {
  15999. // average number of days in the months in the given dates
  16000. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  16001. // difference in months
  16002. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  16003. // adjust by taking difference in days, average number of days
  16004. // and dst in the given months.
  16005. output += ((this - moment(this).startOf('month')) -
  16006. (that - moment(that).startOf('month'))) / diff;
  16007. // same as above but with zones, to negate all dst
  16008. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  16009. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  16010. if (units === 'year') {
  16011. output = output / 12;
  16012. }
  16013. } else {
  16014. diff = (this - that);
  16015. output = units === 'second' ? diff / 1e3 : // 1000
  16016. units === 'minute' ? diff / 6e4 : // 1000 * 60
  16017. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  16018. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  16019. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  16020. diff;
  16021. }
  16022. return asFloat ? output : absRound(output);
  16023. },
  16024. from : function (time, withoutSuffix) {
  16025. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  16026. },
  16027. fromNow : function (withoutSuffix) {
  16028. return this.from(moment(), withoutSuffix);
  16029. },
  16030. calendar : function () {
  16031. // We want to compare the start of today, vs this.
  16032. // Getting start-of-today depends on whether we're zone'd or not.
  16033. var sod = makeAs(moment(), this).startOf('day'),
  16034. diff = this.diff(sod, 'days', true),
  16035. format = diff < -6 ? 'sameElse' :
  16036. diff < -1 ? 'lastWeek' :
  16037. diff < 0 ? 'lastDay' :
  16038. diff < 1 ? 'sameDay' :
  16039. diff < 2 ? 'nextDay' :
  16040. diff < 7 ? 'nextWeek' : 'sameElse';
  16041. return this.format(this.lang().calendar(format, this));
  16042. },
  16043. isLeapYear : function () {
  16044. return isLeapYear(this.year());
  16045. },
  16046. isDST : function () {
  16047. return (this.zone() < this.clone().month(0).zone() ||
  16048. this.zone() < this.clone().month(5).zone());
  16049. },
  16050. day : function (input) {
  16051. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  16052. if (input != null) {
  16053. input = parseWeekday(input, this.lang());
  16054. return this.add({ d : input - day });
  16055. } else {
  16056. return day;
  16057. }
  16058. },
  16059. month : function (input) {
  16060. var utc = this._isUTC ? 'UTC' : '',
  16061. dayOfMonth;
  16062. if (input != null) {
  16063. if (typeof input === 'string') {
  16064. input = this.lang().monthsParse(input);
  16065. if (typeof input !== 'number') {
  16066. return this;
  16067. }
  16068. }
  16069. dayOfMonth = this.date();
  16070. this.date(1);
  16071. this._d['set' + utc + 'Month'](input);
  16072. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  16073. moment.updateOffset(this);
  16074. return this;
  16075. } else {
  16076. return this._d['get' + utc + 'Month']();
  16077. }
  16078. },
  16079. startOf: function (units) {
  16080. units = normalizeUnits(units);
  16081. // the following switch intentionally omits break keywords
  16082. // to utilize falling through the cases.
  16083. switch (units) {
  16084. case 'year':
  16085. this.month(0);
  16086. /* falls through */
  16087. case 'month':
  16088. this.date(1);
  16089. /* falls through */
  16090. case 'week':
  16091. case 'isoWeek':
  16092. case 'day':
  16093. this.hours(0);
  16094. /* falls through */
  16095. case 'hour':
  16096. this.minutes(0);
  16097. /* falls through */
  16098. case 'minute':
  16099. this.seconds(0);
  16100. /* falls through */
  16101. case 'second':
  16102. this.milliseconds(0);
  16103. /* falls through */
  16104. }
  16105. // weeks are a special case
  16106. if (units === 'week') {
  16107. this.weekday(0);
  16108. } else if (units === 'isoWeek') {
  16109. this.isoWeekday(1);
  16110. }
  16111. return this;
  16112. },
  16113. endOf: function (units) {
  16114. units = normalizeUnits(units);
  16115. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  16116. },
  16117. isAfter: function (input, units) {
  16118. units = typeof units !== 'undefined' ? units : 'millisecond';
  16119. return +this.clone().startOf(units) > +moment(input).startOf(units);
  16120. },
  16121. isBefore: function (input, units) {
  16122. units = typeof units !== 'undefined' ? units : 'millisecond';
  16123. return +this.clone().startOf(units) < +moment(input).startOf(units);
  16124. },
  16125. isSame: function (input, units) {
  16126. units = units || 'ms';
  16127. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  16128. },
  16129. min: function (other) {
  16130. other = moment.apply(null, arguments);
  16131. return other < this ? this : other;
  16132. },
  16133. max: function (other) {
  16134. other = moment.apply(null, arguments);
  16135. return other > this ? this : other;
  16136. },
  16137. zone : function (input) {
  16138. var offset = this._offset || 0;
  16139. if (input != null) {
  16140. if (typeof input === "string") {
  16141. input = timezoneMinutesFromString(input);
  16142. }
  16143. if (Math.abs(input) < 16) {
  16144. input = input * 60;
  16145. }
  16146. this._offset = input;
  16147. this._isUTC = true;
  16148. if (offset !== input) {
  16149. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  16150. }
  16151. } else {
  16152. return this._isUTC ? offset : this._d.getTimezoneOffset();
  16153. }
  16154. return this;
  16155. },
  16156. zoneAbbr : function () {
  16157. return this._isUTC ? "UTC" : "";
  16158. },
  16159. zoneName : function () {
  16160. return this._isUTC ? "Coordinated Universal Time" : "";
  16161. },
  16162. parseZone : function () {
  16163. if (this._tzm) {
  16164. this.zone(this._tzm);
  16165. } else if (typeof this._i === 'string') {
  16166. this.zone(this._i);
  16167. }
  16168. return this;
  16169. },
  16170. hasAlignedHourOffset : function (input) {
  16171. if (!input) {
  16172. input = 0;
  16173. }
  16174. else {
  16175. input = moment(input).zone();
  16176. }
  16177. return (this.zone() - input) % 60 === 0;
  16178. },
  16179. daysInMonth : function () {
  16180. return daysInMonth(this.year(), this.month());
  16181. },
  16182. dayOfYear : function (input) {
  16183. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  16184. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  16185. },
  16186. quarter : function () {
  16187. return Math.ceil((this.month() + 1.0) / 3.0);
  16188. },
  16189. weekYear : function (input) {
  16190. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  16191. return input == null ? year : this.add("y", (input - year));
  16192. },
  16193. isoWeekYear : function (input) {
  16194. var year = weekOfYear(this, 1, 4).year;
  16195. return input == null ? year : this.add("y", (input - year));
  16196. },
  16197. week : function (input) {
  16198. var week = this.lang().week(this);
  16199. return input == null ? week : this.add("d", (input - week) * 7);
  16200. },
  16201. isoWeek : function (input) {
  16202. var week = weekOfYear(this, 1, 4).week;
  16203. return input == null ? week : this.add("d", (input - week) * 7);
  16204. },
  16205. weekday : function (input) {
  16206. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  16207. return input == null ? weekday : this.add("d", input - weekday);
  16208. },
  16209. isoWeekday : function (input) {
  16210. // behaves the same as moment#day except
  16211. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  16212. // as a setter, sunday should belong to the previous week.
  16213. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  16214. },
  16215. get : function (units) {
  16216. units = normalizeUnits(units);
  16217. return this[units]();
  16218. },
  16219. set : function (units, value) {
  16220. units = normalizeUnits(units);
  16221. if (typeof this[units] === 'function') {
  16222. this[units](value);
  16223. }
  16224. return this;
  16225. },
  16226. // If passed a language key, it will set the language for this
  16227. // instance. Otherwise, it will return the language configuration
  16228. // variables for this instance.
  16229. lang : function (key) {
  16230. if (key === undefined) {
  16231. return this._lang;
  16232. } else {
  16233. this._lang = getLangDefinition(key);
  16234. return this;
  16235. }
  16236. }
  16237. });
  16238. // helper for adding shortcuts
  16239. function makeGetterAndSetter(name, key) {
  16240. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  16241. var utc = this._isUTC ? 'UTC' : '';
  16242. if (input != null) {
  16243. this._d['set' + utc + key](input);
  16244. moment.updateOffset(this);
  16245. return this;
  16246. } else {
  16247. return this._d['get' + utc + key]();
  16248. }
  16249. };
  16250. }
  16251. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  16252. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  16253. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  16254. }
  16255. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  16256. makeGetterAndSetter('year', 'FullYear');
  16257. // add plural methods
  16258. moment.fn.days = moment.fn.day;
  16259. moment.fn.months = moment.fn.month;
  16260. moment.fn.weeks = moment.fn.week;
  16261. moment.fn.isoWeeks = moment.fn.isoWeek;
  16262. // add aliased format methods
  16263. moment.fn.toJSON = moment.fn.toISOString;
  16264. /************************************
  16265. Duration Prototype
  16266. ************************************/
  16267. extend(moment.duration.fn = Duration.prototype, {
  16268. _bubble : function () {
  16269. var milliseconds = this._milliseconds,
  16270. days = this._days,
  16271. months = this._months,
  16272. data = this._data,
  16273. seconds, minutes, hours, years;
  16274. // The following code bubbles up values, see the tests for
  16275. // examples of what that means.
  16276. data.milliseconds = milliseconds % 1000;
  16277. seconds = absRound(milliseconds / 1000);
  16278. data.seconds = seconds % 60;
  16279. minutes = absRound(seconds / 60);
  16280. data.minutes = minutes % 60;
  16281. hours = absRound(minutes / 60);
  16282. data.hours = hours % 24;
  16283. days += absRound(hours / 24);
  16284. data.days = days % 30;
  16285. months += absRound(days / 30);
  16286. data.months = months % 12;
  16287. years = absRound(months / 12);
  16288. data.years = years;
  16289. },
  16290. weeks : function () {
  16291. return absRound(this.days() / 7);
  16292. },
  16293. valueOf : function () {
  16294. return this._milliseconds +
  16295. this._days * 864e5 +
  16296. (this._months % 12) * 2592e6 +
  16297. toInt(this._months / 12) * 31536e6;
  16298. },
  16299. humanize : function (withSuffix) {
  16300. var difference = +this,
  16301. output = relativeTime(difference, !withSuffix, this.lang());
  16302. if (withSuffix) {
  16303. output = this.lang().pastFuture(difference, output);
  16304. }
  16305. return this.lang().postformat(output);
  16306. },
  16307. add : function (input, val) {
  16308. // supports only 2.0-style add(1, 's') or add(moment)
  16309. var dur = moment.duration(input, val);
  16310. this._milliseconds += dur._milliseconds;
  16311. this._days += dur._days;
  16312. this._months += dur._months;
  16313. this._bubble();
  16314. return this;
  16315. },
  16316. subtract : function (input, val) {
  16317. var dur = moment.duration(input, val);
  16318. this._milliseconds -= dur._milliseconds;
  16319. this._days -= dur._days;
  16320. this._months -= dur._months;
  16321. this._bubble();
  16322. return this;
  16323. },
  16324. get : function (units) {
  16325. units = normalizeUnits(units);
  16326. return this[units.toLowerCase() + 's']();
  16327. },
  16328. as : function (units) {
  16329. units = normalizeUnits(units);
  16330. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  16331. },
  16332. lang : moment.fn.lang,
  16333. toIsoString : function () {
  16334. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  16335. var years = Math.abs(this.years()),
  16336. months = Math.abs(this.months()),
  16337. days = Math.abs(this.days()),
  16338. hours = Math.abs(this.hours()),
  16339. minutes = Math.abs(this.minutes()),
  16340. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  16341. if (!this.asSeconds()) {
  16342. // this is the same as C#'s (Noda) and python (isodate)...
  16343. // but not other JS (goog.date)
  16344. return 'P0D';
  16345. }
  16346. return (this.asSeconds() < 0 ? '-' : '') +
  16347. 'P' +
  16348. (years ? years + 'Y' : '') +
  16349. (months ? months + 'M' : '') +
  16350. (days ? days + 'D' : '') +
  16351. ((hours || minutes || seconds) ? 'T' : '') +
  16352. (hours ? hours + 'H' : '') +
  16353. (minutes ? minutes + 'M' : '') +
  16354. (seconds ? seconds + 'S' : '');
  16355. }
  16356. });
  16357. function makeDurationGetter(name) {
  16358. moment.duration.fn[name] = function () {
  16359. return this._data[name];
  16360. };
  16361. }
  16362. function makeDurationAsGetter(name, factor) {
  16363. moment.duration.fn['as' + name] = function () {
  16364. return +this / factor;
  16365. };
  16366. }
  16367. for (i in unitMillisecondFactors) {
  16368. if (unitMillisecondFactors.hasOwnProperty(i)) {
  16369. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  16370. makeDurationGetter(i.toLowerCase());
  16371. }
  16372. }
  16373. makeDurationAsGetter('Weeks', 6048e5);
  16374. moment.duration.fn.asMonths = function () {
  16375. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  16376. };
  16377. /************************************
  16378. Default Lang
  16379. ************************************/
  16380. // Set default language, other languages will inherit from English.
  16381. moment.lang('en', {
  16382. ordinal : function (number) {
  16383. var b = number % 10,
  16384. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  16385. (b === 1) ? 'st' :
  16386. (b === 2) ? 'nd' :
  16387. (b === 3) ? 'rd' : 'th';
  16388. return number + output;
  16389. }
  16390. });
  16391. /* EMBED_LANGUAGES */
  16392. /************************************
  16393. Exposing Moment
  16394. ************************************/
  16395. function makeGlobal(deprecate) {
  16396. var warned = false, local_moment = moment;
  16397. /*global ender:false */
  16398. if (typeof ender !== 'undefined') {
  16399. return;
  16400. }
  16401. // here, `this` means `window` in the browser, or `global` on the server
  16402. // add `moment` as a global object via a string identifier,
  16403. // for Closure Compiler "advanced" mode
  16404. if (deprecate) {
  16405. global.moment = function () {
  16406. if (!warned && console && console.warn) {
  16407. warned = true;
  16408. console.warn(
  16409. "Accessing Moment through the global scope is " +
  16410. "deprecated, and will be removed in an upcoming " +
  16411. "release.");
  16412. }
  16413. return local_moment.apply(null, arguments);
  16414. };
  16415. extend(global.moment, local_moment);
  16416. } else {
  16417. global['moment'] = moment;
  16418. }
  16419. }
  16420. // CommonJS module is defined
  16421. if (hasModule) {
  16422. module.exports = moment;
  16423. makeGlobal(true);
  16424. } else if (typeof define === "function" && define.amd) {
  16425. define("moment", function (require, exports, module) {
  16426. if (module.config && module.config() && module.config().noGlobal !== true) {
  16427. // If user provided noGlobal, he is aware of global
  16428. makeGlobal(module.config().noGlobal === undefined);
  16429. }
  16430. return moment;
  16431. });
  16432. } else {
  16433. makeGlobal();
  16434. }
  16435. }).call(this);
  16436. },{}],4:[function(require,module,exports){
  16437. /**
  16438. * Copyright 2012 Craig Campbell
  16439. *
  16440. * Licensed under the Apache License, Version 2.0 (the "License");
  16441. * you may not use this file except in compliance with the License.
  16442. * You may obtain a copy of the License at
  16443. *
  16444. * http://www.apache.org/licenses/LICENSE-2.0
  16445. *
  16446. * Unless required by applicable law or agreed to in writing, software
  16447. * distributed under the License is distributed on an "AS IS" BASIS,
  16448. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16449. * See the License for the specific language governing permissions and
  16450. * limitations under the License.
  16451. *
  16452. * Mousetrap is a simple keyboard shortcut library for Javascript with
  16453. * no external dependencies
  16454. *
  16455. * @version 1.1.2
  16456. * @url craig.is/killing/mice
  16457. */
  16458. /**
  16459. * mapping of special keycodes to their corresponding keys
  16460. *
  16461. * everything in this dictionary cannot use keypress events
  16462. * so it has to be here to map to the correct keycodes for
  16463. * keyup/keydown events
  16464. *
  16465. * @type {Object}
  16466. */
  16467. var _MAP = {
  16468. 8: 'backspace',
  16469. 9: 'tab',
  16470. 13: 'enter',
  16471. 16: 'shift',
  16472. 17: 'ctrl',
  16473. 18: 'alt',
  16474. 20: 'capslock',
  16475. 27: 'esc',
  16476. 32: 'space',
  16477. 33: 'pageup',
  16478. 34: 'pagedown',
  16479. 35: 'end',
  16480. 36: 'home',
  16481. 37: 'left',
  16482. 38: 'up',
  16483. 39: 'right',
  16484. 40: 'down',
  16485. 45: 'ins',
  16486. 46: 'del',
  16487. 91: 'meta',
  16488. 93: 'meta',
  16489. 224: 'meta'
  16490. },
  16491. /**
  16492. * mapping for special characters so they can support
  16493. *
  16494. * this dictionary is only used incase you want to bind a
  16495. * keyup or keydown event to one of these keys
  16496. *
  16497. * @type {Object}
  16498. */
  16499. _KEYCODE_MAP = {
  16500. 106: '*',
  16501. 107: '+',
  16502. 109: '-',
  16503. 110: '.',
  16504. 111 : '/',
  16505. 186: ';',
  16506. 187: '=',
  16507. 188: ',',
  16508. 189: '-',
  16509. 190: '.',
  16510. 191: '/',
  16511. 192: '`',
  16512. 219: '[',
  16513. 220: '\\',
  16514. 221: ']',
  16515. 222: '\''
  16516. },
  16517. /**
  16518. * this is a mapping of keys that require shift on a US keypad
  16519. * back to the non shift equivelents
  16520. *
  16521. * this is so you can use keyup events with these keys
  16522. *
  16523. * note that this will only work reliably on US keyboards
  16524. *
  16525. * @type {Object}
  16526. */
  16527. _SHIFT_MAP = {
  16528. '~': '`',
  16529. '!': '1',
  16530. '@': '2',
  16531. '#': '3',
  16532. '$': '4',
  16533. '%': '5',
  16534. '^': '6',
  16535. '&': '7',
  16536. '*': '8',
  16537. '(': '9',
  16538. ')': '0',
  16539. '_': '-',
  16540. '+': '=',
  16541. ':': ';',
  16542. '\"': '\'',
  16543. '<': ',',
  16544. '>': '.',
  16545. '?': '/',
  16546. '|': '\\'
  16547. },
  16548. /**
  16549. * this is a list of special strings you can use to map
  16550. * to modifier keys when you specify your keyboard shortcuts
  16551. *
  16552. * @type {Object}
  16553. */
  16554. _SPECIAL_ALIASES = {
  16555. 'option': 'alt',
  16556. 'command': 'meta',
  16557. 'return': 'enter',
  16558. 'escape': 'esc'
  16559. },
  16560. /**
  16561. * variable to store the flipped version of _MAP from above
  16562. * needed to check if we should use keypress or not when no action
  16563. * is specified
  16564. *
  16565. * @type {Object|undefined}
  16566. */
  16567. _REVERSE_MAP,
  16568. /**
  16569. * a list of all the callbacks setup via Mousetrap.bind()
  16570. *
  16571. * @type {Object}
  16572. */
  16573. _callbacks = {},
  16574. /**
  16575. * direct map of string combinations to callbacks used for trigger()
  16576. *
  16577. * @type {Object}
  16578. */
  16579. _direct_map = {},
  16580. /**
  16581. * keeps track of what level each sequence is at since multiple
  16582. * sequences can start out with the same sequence
  16583. *
  16584. * @type {Object}
  16585. */
  16586. _sequence_levels = {},
  16587. /**
  16588. * variable to store the setTimeout call
  16589. *
  16590. * @type {null|number}
  16591. */
  16592. _reset_timer,
  16593. /**
  16594. * temporary state where we will ignore the next keyup
  16595. *
  16596. * @type {boolean|string}
  16597. */
  16598. _ignore_next_keyup = false,
  16599. /**
  16600. * are we currently inside of a sequence?
  16601. * type of action ("keyup" or "keydown" or "keypress") or false
  16602. *
  16603. * @type {boolean|string}
  16604. */
  16605. _inside_sequence = false;
  16606. /**
  16607. * loop through the f keys, f1 to f19 and add them to the map
  16608. * programatically
  16609. */
  16610. for (var i = 1; i < 20; ++i) {
  16611. _MAP[111 + i] = 'f' + i;
  16612. }
  16613. /**
  16614. * loop through to map numbers on the numeric keypad
  16615. */
  16616. for (i = 0; i <= 9; ++i) {
  16617. _MAP[i + 96] = i;
  16618. }
  16619. /**
  16620. * cross browser add event method
  16621. *
  16622. * @param {Element|HTMLDocument} object
  16623. * @param {string} type
  16624. * @param {Function} callback
  16625. * @returns void
  16626. */
  16627. function _addEvent(object, type, callback) {
  16628. if (object.addEventListener) {
  16629. return object.addEventListener(type, callback, false);
  16630. }
  16631. object.attachEvent('on' + type, callback);
  16632. }
  16633. /**
  16634. * takes the event and returns the key character
  16635. *
  16636. * @param {Event} e
  16637. * @return {string}
  16638. */
  16639. function _characterFromEvent(e) {
  16640. // for keypress events we should return the character as is
  16641. if (e.type == 'keypress') {
  16642. return String.fromCharCode(e.which);
  16643. }
  16644. // for non keypress events the special maps are needed
  16645. if (_MAP[e.which]) {
  16646. return _MAP[e.which];
  16647. }
  16648. if (_KEYCODE_MAP[e.which]) {
  16649. return _KEYCODE_MAP[e.which];
  16650. }
  16651. // if it is not in the special map
  16652. return String.fromCharCode(e.which).toLowerCase();
  16653. }
  16654. /**
  16655. * should we stop this event before firing off callbacks
  16656. *
  16657. * @param {Event} e
  16658. * @return {boolean}
  16659. */
  16660. function _stop(e) {
  16661. var element = e.target || e.srcElement,
  16662. tag_name = element.tagName;
  16663. // if the element has the class "mousetrap" then no need to stop
  16664. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  16665. return false;
  16666. }
  16667. // stop for input, select, and textarea
  16668. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  16669. }
  16670. /**
  16671. * checks if two arrays are equal
  16672. *
  16673. * @param {Array} modifiers1
  16674. * @param {Array} modifiers2
  16675. * @returns {boolean}
  16676. */
  16677. function _modifiersMatch(modifiers1, modifiers2) {
  16678. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  16679. }
  16680. /**
  16681. * resets all sequence counters except for the ones passed in
  16682. *
  16683. * @param {Object} do_not_reset
  16684. * @returns void
  16685. */
  16686. function _resetSequences(do_not_reset) {
  16687. do_not_reset = do_not_reset || {};
  16688. var active_sequences = false,
  16689. key;
  16690. for (key in _sequence_levels) {
  16691. if (do_not_reset[key]) {
  16692. active_sequences = true;
  16693. continue;
  16694. }
  16695. _sequence_levels[key] = 0;
  16696. }
  16697. if (!active_sequences) {
  16698. _inside_sequence = false;
  16699. }
  16700. }
  16701. /**
  16702. * finds all callbacks that match based on the keycode, modifiers,
  16703. * and action
  16704. *
  16705. * @param {string} character
  16706. * @param {Array} modifiers
  16707. * @param {string} action
  16708. * @param {boolean=} remove - should we remove any matches
  16709. * @param {string=} combination
  16710. * @returns {Array}
  16711. */
  16712. function _getMatches(character, modifiers, action, remove, combination) {
  16713. var i,
  16714. callback,
  16715. matches = [];
  16716. // if there are no events related to this keycode
  16717. if (!_callbacks[character]) {
  16718. return [];
  16719. }
  16720. // if a modifier key is coming up on its own we should allow it
  16721. if (action == 'keyup' && _isModifier(character)) {
  16722. modifiers = [character];
  16723. }
  16724. // loop through all callbacks for the key that was pressed
  16725. // and see if any of them match
  16726. for (i = 0; i < _callbacks[character].length; ++i) {
  16727. callback = _callbacks[character][i];
  16728. // if this is a sequence but it is not at the right level
  16729. // then move onto the next match
  16730. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  16731. continue;
  16732. }
  16733. // if the action we are looking for doesn't match the action we got
  16734. // then we should keep going
  16735. if (action != callback.action) {
  16736. continue;
  16737. }
  16738. // if this is a keypress event that means that we need to only
  16739. // look at the character, otherwise check the modifiers as
  16740. // well
  16741. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  16742. // remove is used so if you change your mind and call bind a
  16743. // second time with a new function the first one is overwritten
  16744. if (remove && callback.combo == combination) {
  16745. _callbacks[character].splice(i, 1);
  16746. }
  16747. matches.push(callback);
  16748. }
  16749. }
  16750. return matches;
  16751. }
  16752. /**
  16753. * takes a key event and figures out what the modifiers are
  16754. *
  16755. * @param {Event} e
  16756. * @returns {Array}
  16757. */
  16758. function _eventModifiers(e) {
  16759. var modifiers = [];
  16760. if (e.shiftKey) {
  16761. modifiers.push('shift');
  16762. }
  16763. if (e.altKey) {
  16764. modifiers.push('alt');
  16765. }
  16766. if (e.ctrlKey) {
  16767. modifiers.push('ctrl');
  16768. }
  16769. if (e.metaKey) {
  16770. modifiers.push('meta');
  16771. }
  16772. return modifiers;
  16773. }
  16774. /**
  16775. * actually calls the callback function
  16776. *
  16777. * if your callback function returns false this will use the jquery
  16778. * convention - prevent default and stop propogation on the event
  16779. *
  16780. * @param {Function} callback
  16781. * @param {Event} e
  16782. * @returns void
  16783. */
  16784. function _fireCallback(callback, e) {
  16785. if (callback(e) === false) {
  16786. if (e.preventDefault) {
  16787. e.preventDefault();
  16788. }
  16789. if (e.stopPropagation) {
  16790. e.stopPropagation();
  16791. }
  16792. e.returnValue = false;
  16793. e.cancelBubble = true;
  16794. }
  16795. }
  16796. /**
  16797. * handles a character key event
  16798. *
  16799. * @param {string} character
  16800. * @param {Event} e
  16801. * @returns void
  16802. */
  16803. function _handleCharacter(character, e) {
  16804. // if this event should not happen stop here
  16805. if (_stop(e)) {
  16806. return;
  16807. }
  16808. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  16809. i,
  16810. do_not_reset = {},
  16811. processed_sequence_callback = false;
  16812. // loop through matching callbacks for this key event
  16813. for (i = 0; i < callbacks.length; ++i) {
  16814. // fire for all sequence callbacks
  16815. // this is because if for example you have multiple sequences
  16816. // bound such as "g i" and "g t" they both need to fire the
  16817. // callback for matching g cause otherwise you can only ever
  16818. // match the first one
  16819. if (callbacks[i].seq) {
  16820. processed_sequence_callback = true;
  16821. // keep a list of which sequences were matches for later
  16822. do_not_reset[callbacks[i].seq] = 1;
  16823. _fireCallback(callbacks[i].callback, e);
  16824. continue;
  16825. }
  16826. // if there were no sequence matches but we are still here
  16827. // that means this is a regular match so we should fire that
  16828. if (!processed_sequence_callback && !_inside_sequence) {
  16829. _fireCallback(callbacks[i].callback, e);
  16830. }
  16831. }
  16832. // if you are inside of a sequence and the key you are pressing
  16833. // is not a modifier key then we should reset all sequences
  16834. // that were not matched by this key event
  16835. if (e.type == _inside_sequence && !_isModifier(character)) {
  16836. _resetSequences(do_not_reset);
  16837. }
  16838. }
  16839. /**
  16840. * handles a keydown event
  16841. *
  16842. * @param {Event} e
  16843. * @returns void
  16844. */
  16845. function _handleKey(e) {
  16846. // normalize e.which for key events
  16847. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  16848. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  16849. var character = _characterFromEvent(e);
  16850. // no character found then stop
  16851. if (!character) {
  16852. return;
  16853. }
  16854. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  16855. _ignore_next_keyup = false;
  16856. return;
  16857. }
  16858. _handleCharacter(character, e);
  16859. }
  16860. /**
  16861. * determines if the keycode specified is a modifier key or not
  16862. *
  16863. * @param {string} key
  16864. * @returns {boolean}
  16865. */
  16866. function _isModifier(key) {
  16867. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  16868. }
  16869. /**
  16870. * called to set a 1 second timeout on the specified sequence
  16871. *
  16872. * this is so after each key press in the sequence you have 1 second
  16873. * to press the next key before you have to start over
  16874. *
  16875. * @returns void
  16876. */
  16877. function _resetSequenceTimer() {
  16878. clearTimeout(_reset_timer);
  16879. _reset_timer = setTimeout(_resetSequences, 1000);
  16880. }
  16881. /**
  16882. * reverses the map lookup so that we can look for specific keys
  16883. * to see what can and can't use keypress
  16884. *
  16885. * @return {Object}
  16886. */
  16887. function _getReverseMap() {
  16888. if (!_REVERSE_MAP) {
  16889. _REVERSE_MAP = {};
  16890. for (var key in _MAP) {
  16891. // pull out the numeric keypad from here cause keypress should
  16892. // be able to detect the keys from the character
  16893. if (key > 95 && key < 112) {
  16894. continue;
  16895. }
  16896. if (_MAP.hasOwnProperty(key)) {
  16897. _REVERSE_MAP[_MAP[key]] = key;
  16898. }
  16899. }
  16900. }
  16901. return _REVERSE_MAP;
  16902. }
  16903. /**
  16904. * picks the best action based on the key combination
  16905. *
  16906. * @param {string} key - character for key
  16907. * @param {Array} modifiers
  16908. * @param {string=} action passed in
  16909. */
  16910. function _pickBestAction(key, modifiers, action) {
  16911. // if no action was picked in we should try to pick the one
  16912. // that we think would work best for this key
  16913. if (!action) {
  16914. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  16915. }
  16916. // modifier keys don't work as expected with keypress,
  16917. // switch to keydown
  16918. if (action == 'keypress' && modifiers.length) {
  16919. action = 'keydown';
  16920. }
  16921. return action;
  16922. }
  16923. /**
  16924. * binds a key sequence to an event
  16925. *
  16926. * @param {string} combo - combo specified in bind call
  16927. * @param {Array} keys
  16928. * @param {Function} callback
  16929. * @param {string=} action
  16930. * @returns void
  16931. */
  16932. function _bindSequence(combo, keys, callback, action) {
  16933. // start off by adding a sequence level record for this combination
  16934. // and setting the level to 0
  16935. _sequence_levels[combo] = 0;
  16936. // if there is no action pick the best one for the first key
  16937. // in the sequence
  16938. if (!action) {
  16939. action = _pickBestAction(keys[0], []);
  16940. }
  16941. /**
  16942. * callback to increase the sequence level for this sequence and reset
  16943. * all other sequences that were active
  16944. *
  16945. * @param {Event} e
  16946. * @returns void
  16947. */
  16948. var _increaseSequence = function(e) {
  16949. _inside_sequence = action;
  16950. ++_sequence_levels[combo];
  16951. _resetSequenceTimer();
  16952. },
  16953. /**
  16954. * wraps the specified callback inside of another function in order
  16955. * to reset all sequence counters as soon as this sequence is done
  16956. *
  16957. * @param {Event} e
  16958. * @returns void
  16959. */
  16960. _callbackAndReset = function(e) {
  16961. _fireCallback(callback, e);
  16962. // we should ignore the next key up if the action is key down
  16963. // or keypress. this is so if you finish a sequence and
  16964. // release the key the final key will not trigger a keyup
  16965. if (action !== 'keyup') {
  16966. _ignore_next_keyup = _characterFromEvent(e);
  16967. }
  16968. // weird race condition if a sequence ends with the key
  16969. // another sequence begins with
  16970. setTimeout(_resetSequences, 10);
  16971. },
  16972. i;
  16973. // loop through keys one at a time and bind the appropriate callback
  16974. // function. for any key leading up to the final one it should
  16975. // increase the sequence. after the final, it should reset all sequences
  16976. for (i = 0; i < keys.length; ++i) {
  16977. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  16978. }
  16979. }
  16980. /**
  16981. * binds a single keyboard combination
  16982. *
  16983. * @param {string} combination
  16984. * @param {Function} callback
  16985. * @param {string=} action
  16986. * @param {string=} sequence_name - name of sequence if part of sequence
  16987. * @param {number=} level - what part of the sequence the command is
  16988. * @returns void
  16989. */
  16990. function _bindSingle(combination, callback, action, sequence_name, level) {
  16991. // make sure multiple spaces in a row become a single space
  16992. combination = combination.replace(/\s+/g, ' ');
  16993. var sequence = combination.split(' '),
  16994. i,
  16995. key,
  16996. keys,
  16997. modifiers = [];
  16998. // if this pattern is a sequence of keys then run through this method
  16999. // to reprocess each pattern one key at a time
  17000. if (sequence.length > 1) {
  17001. return _bindSequence(combination, sequence, callback, action);
  17002. }
  17003. // take the keys from this pattern and figure out what the actual
  17004. // pattern is all about
  17005. keys = combination === '+' ? ['+'] : combination.split('+');
  17006. for (i = 0; i < keys.length; ++i) {
  17007. key = keys[i];
  17008. // normalize key names
  17009. if (_SPECIAL_ALIASES[key]) {
  17010. key = _SPECIAL_ALIASES[key];
  17011. }
  17012. // if this is not a keypress event then we should
  17013. // be smart about using shift keys
  17014. // this will only work for US keyboards however
  17015. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  17016. key = _SHIFT_MAP[key];
  17017. modifiers.push('shift');
  17018. }
  17019. // if this key is a modifier then add it to the list of modifiers
  17020. if (_isModifier(key)) {
  17021. modifiers.push(key);
  17022. }
  17023. }
  17024. // depending on what the key combination is
  17025. // we will try to pick the best event for it
  17026. action = _pickBestAction(key, modifiers, action);
  17027. // make sure to initialize array if this is the first time
  17028. // a callback is added for this key
  17029. if (!_callbacks[key]) {
  17030. _callbacks[key] = [];
  17031. }
  17032. // remove an existing match if there is one
  17033. _getMatches(key, modifiers, action, !sequence_name, combination);
  17034. // add this call back to the array
  17035. // if it is a sequence put it at the beginning
  17036. // if not put it at the end
  17037. //
  17038. // this is important because the way these are processed expects
  17039. // the sequence ones to come first
  17040. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  17041. callback: callback,
  17042. modifiers: modifiers,
  17043. action: action,
  17044. seq: sequence_name,
  17045. level: level,
  17046. combo: combination
  17047. });
  17048. }
  17049. /**
  17050. * binds multiple combinations to the same callback
  17051. *
  17052. * @param {Array} combinations
  17053. * @param {Function} callback
  17054. * @param {string|undefined} action
  17055. * @returns void
  17056. */
  17057. function _bindMultiple(combinations, callback, action) {
  17058. for (var i = 0; i < combinations.length; ++i) {
  17059. _bindSingle(combinations[i], callback, action);
  17060. }
  17061. }
  17062. // start!
  17063. _addEvent(document, 'keypress', _handleKey);
  17064. _addEvent(document, 'keydown', _handleKey);
  17065. _addEvent(document, 'keyup', _handleKey);
  17066. var mousetrap = {
  17067. /**
  17068. * binds an event to mousetrap
  17069. *
  17070. * can be a single key, a combination of keys separated with +,
  17071. * a comma separated list of keys, an array of keys, or
  17072. * a sequence of keys separated by spaces
  17073. *
  17074. * be sure to list the modifier keys first to make sure that the
  17075. * correct key ends up getting bound (the last key in the pattern)
  17076. *
  17077. * @param {string|Array} keys
  17078. * @param {Function} callback
  17079. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  17080. * @returns void
  17081. */
  17082. bind: function(keys, callback, action) {
  17083. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  17084. _direct_map[keys + ':' + action] = callback;
  17085. return this;
  17086. },
  17087. /**
  17088. * unbinds an event to mousetrap
  17089. *
  17090. * the unbinding sets the callback function of the specified key combo
  17091. * to an empty function and deletes the corresponding key in the
  17092. * _direct_map dict.
  17093. *
  17094. * the keycombo+action has to be exactly the same as
  17095. * it was defined in the bind method
  17096. *
  17097. * TODO: actually remove this from the _callbacks dictionary instead
  17098. * of binding an empty function
  17099. *
  17100. * @param {string|Array} keys
  17101. * @param {string} action
  17102. * @returns void
  17103. */
  17104. unbind: function(keys, action) {
  17105. if (_direct_map[keys + ':' + action]) {
  17106. delete _direct_map[keys + ':' + action];
  17107. this.bind(keys, function() {}, action);
  17108. }
  17109. return this;
  17110. },
  17111. /**
  17112. * triggers an event that has already been bound
  17113. *
  17114. * @param {string} keys
  17115. * @param {string=} action
  17116. * @returns void
  17117. */
  17118. trigger: function(keys, action) {
  17119. _direct_map[keys + ':' + action]();
  17120. return this;
  17121. },
  17122. /**
  17123. * resets the library back to its initial state. this is useful
  17124. * if you want to clear out the current keyboard shortcuts and bind
  17125. * new ones - for example if you switch to another page
  17126. *
  17127. * @returns void
  17128. */
  17129. reset: function() {
  17130. _callbacks = {};
  17131. _direct_map = {};
  17132. return this;
  17133. }
  17134. };
  17135. module.exports = mousetrap;
  17136. },{}]},{},[1])
  17137. (1)
  17138. });