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.

19895 lines
571 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.4.0
  8. * @date 2014-01-31
  9. *
  10. * @license
  11. * Copyright (C) 2011-2014 Almende B.V, http://almende.com
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  14. * use this file except in compliance with the License. You may obtain a copy
  15. * of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  22. * License for the specific language governing permissions and limitations under
  23. * the License.
  24. */
  25. !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.vis=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  26. /**
  27. * vis.js module imports
  28. */
  29. // Try to load dependencies from the global window object.
  30. // If not available there, load via require.
  31. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment');
  32. var Hammer;
  33. if (typeof window !== 'undefined') {
  34. // load hammer.js only when running in a browser (where window is available)
  35. Hammer = window['Hammer'] || require('hammerjs');
  36. }
  37. else {
  38. Hammer = function () {
  39. throw Error('hammer.js is only available in a browser, not in node.js.');
  40. }
  41. }
  42. var mousetrap;
  43. if (typeof window !== 'undefined') {
  44. // load mousetrap.js only when running in a browser (where window is available)
  45. mousetrap = window['mousetrap'] || require('mousetrap');
  46. }
  47. else {
  48. mousetrap = function () {
  49. throw Error('mouseTrap is only available in a browser, not in node.js.');
  50. }
  51. }
  52. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  53. // it here in that case.
  54. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  55. if(!Array.prototype.indexOf) {
  56. Array.prototype.indexOf = function(obj){
  57. for(var i = 0; i < this.length; i++){
  58. if(this[i] == obj){
  59. return i;
  60. }
  61. }
  62. return -1;
  63. };
  64. try {
  65. console.log("Warning: Ancient browser detected. Please update your browser");
  66. }
  67. catch (err) {
  68. }
  69. }
  70. // Internet Explorer 8 and older does not support Array.forEach, so we define
  71. // it here in that case.
  72. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  73. if (!Array.prototype.forEach) {
  74. Array.prototype.forEach = function(fn, scope) {
  75. for(var i = 0, len = this.length; i < len; ++i) {
  76. fn.call(scope || this, this[i], i, this);
  77. }
  78. }
  79. }
  80. // Internet Explorer 8 and older does not support Array.map, so we define it
  81. // here in that case.
  82. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  83. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  84. // Reference: http://es5.github.com/#x15.4.4.19
  85. if (!Array.prototype.map) {
  86. Array.prototype.map = function(callback, thisArg) {
  87. var T, A, k;
  88. if (this == null) {
  89. throw new TypeError(" this is null or not defined");
  90. }
  91. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  92. var O = Object(this);
  93. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  94. // 3. Let len be ToUint32(lenValue).
  95. var len = O.length >>> 0;
  96. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  97. // See: http://es5.github.com/#x9.11
  98. if (typeof callback !== "function") {
  99. throw new TypeError(callback + " is not a function");
  100. }
  101. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  102. if (thisArg) {
  103. T = thisArg;
  104. }
  105. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  106. // the standard built-in constructor with that name and len is the value of len.
  107. A = new Array(len);
  108. // 7. Let k be 0
  109. k = 0;
  110. // 8. Repeat, while k < len
  111. while(k < len) {
  112. var kValue, mappedValue;
  113. // a. Let Pk be ToString(k).
  114. // This is implicit for LHS operands of the in operator
  115. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  116. // This step can be combined with c
  117. // c. If kPresent is true, then
  118. if (k in O) {
  119. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  120. kValue = O[ k ];
  121. // ii. Let mappedValue be the result of calling the Call internal method of callback
  122. // with T as the this value and argument list containing kValue, k, and O.
  123. mappedValue = callback.call(T, kValue, k, O);
  124. // iii. Call the DefineOwnProperty internal method of A with arguments
  125. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  126. // and false.
  127. // In browsers that support Object.defineProperty, use the following:
  128. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  129. // For best browser support, use the following:
  130. A[ k ] = mappedValue;
  131. }
  132. // d. Increase k by 1.
  133. k++;
  134. }
  135. // 9. return A
  136. return A;
  137. };
  138. }
  139. // Internet Explorer 8 and older does not support Array.filter, so we define it
  140. // here in that case.
  141. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  142. if (!Array.prototype.filter) {
  143. Array.prototype.filter = function(fun /*, thisp */) {
  144. "use strict";
  145. if (this == null) {
  146. throw new TypeError();
  147. }
  148. var t = Object(this);
  149. var len = t.length >>> 0;
  150. if (typeof fun != "function") {
  151. throw new TypeError();
  152. }
  153. var res = [];
  154. var thisp = arguments[1];
  155. for (var i = 0; i < len; i++) {
  156. if (i in t) {
  157. var val = t[i]; // in case fun mutates this
  158. if (fun.call(thisp, val, i, t))
  159. res.push(val);
  160. }
  161. }
  162. return res;
  163. };
  164. }
  165. // Internet Explorer 8 and older does not support Object.keys, so we define it
  166. // here in that case.
  167. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  168. if (!Object.keys) {
  169. Object.keys = (function () {
  170. var hasOwnProperty = Object.prototype.hasOwnProperty,
  171. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  172. dontEnums = [
  173. 'toString',
  174. 'toLocaleString',
  175. 'valueOf',
  176. 'hasOwnProperty',
  177. 'isPrototypeOf',
  178. 'propertyIsEnumerable',
  179. 'constructor'
  180. ],
  181. dontEnumsLength = dontEnums.length;
  182. return function (obj) {
  183. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  184. throw new TypeError('Object.keys called on non-object');
  185. }
  186. var result = [];
  187. for (var prop in obj) {
  188. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  189. }
  190. if (hasDontEnumBug) {
  191. for (var i=0; i < dontEnumsLength; i++) {
  192. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  193. }
  194. }
  195. return result;
  196. }
  197. })()
  198. }
  199. // Internet Explorer 8 and older does not support Array.isArray,
  200. // so we define it here in that case.
  201. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  202. if(!Array.isArray) {
  203. Array.isArray = function (vArg) {
  204. return Object.prototype.toString.call(vArg) === "[object Array]";
  205. };
  206. }
  207. // Internet Explorer 8 and older does not support Function.bind,
  208. // so we define it here in that case.
  209. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  210. if (!Function.prototype.bind) {
  211. Function.prototype.bind = function (oThis) {
  212. if (typeof this !== "function") {
  213. // closest thing possible to the ECMAScript 5 internal IsCallable function
  214. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  215. }
  216. var aArgs = Array.prototype.slice.call(arguments, 1),
  217. fToBind = this,
  218. fNOP = function () {},
  219. fBound = function () {
  220. return fToBind.apply(this instanceof fNOP && oThis
  221. ? this
  222. : oThis,
  223. aArgs.concat(Array.prototype.slice.call(arguments)));
  224. };
  225. fNOP.prototype = this.prototype;
  226. fBound.prototype = new fNOP();
  227. return fBound;
  228. };
  229. }
  230. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  231. if (!Object.create) {
  232. Object.create = function (o) {
  233. if (arguments.length > 1) {
  234. throw new Error('Object.create implementation only accepts the first parameter.');
  235. }
  236. function F() {}
  237. F.prototype = o;
  238. return new F();
  239. };
  240. }
  241. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  242. if (!Function.prototype.bind) {
  243. Function.prototype.bind = function (oThis) {
  244. if (typeof this !== "function") {
  245. // closest thing possible to the ECMAScript 5 internal IsCallable function
  246. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  247. }
  248. var aArgs = Array.prototype.slice.call(arguments, 1),
  249. fToBind = this,
  250. fNOP = function () {},
  251. fBound = function () {
  252. return fToBind.apply(this instanceof fNOP && oThis
  253. ? this
  254. : oThis,
  255. aArgs.concat(Array.prototype.slice.call(arguments)));
  256. };
  257. fNOP.prototype = this.prototype;
  258. fBound.prototype = new fNOP();
  259. return fBound;
  260. };
  261. }
  262. /**
  263. * utility functions
  264. */
  265. var util = {};
  266. /**
  267. * Test whether given object is a number
  268. * @param {*} object
  269. * @return {Boolean} isNumber
  270. */
  271. util.isNumber = function isNumber(object) {
  272. return (object instanceof Number || typeof object == 'number');
  273. };
  274. /**
  275. * Test whether given object is a string
  276. * @param {*} object
  277. * @return {Boolean} isString
  278. */
  279. util.isString = function isString(object) {
  280. return (object instanceof String || typeof object == 'string');
  281. };
  282. /**
  283. * Test whether given object is a Date, or a String containing a Date
  284. * @param {Date | String} object
  285. * @return {Boolean} isDate
  286. */
  287. util.isDate = function isDate(object) {
  288. if (object instanceof Date) {
  289. return true;
  290. }
  291. else if (util.isString(object)) {
  292. // test whether this string contains a date
  293. var match = ASPDateRegex.exec(object);
  294. if (match) {
  295. return true;
  296. }
  297. else if (!isNaN(Date.parse(object))) {
  298. return true;
  299. }
  300. }
  301. return false;
  302. };
  303. /**
  304. * Test whether given object is an instance of google.visualization.DataTable
  305. * @param {*} object
  306. * @return {Boolean} isDataTable
  307. */
  308. util.isDataTable = function isDataTable(object) {
  309. return (typeof (google) !== 'undefined') &&
  310. (google.visualization) &&
  311. (google.visualization.DataTable) &&
  312. (object instanceof google.visualization.DataTable);
  313. };
  314. /**
  315. * Create a semi UUID
  316. * source: http://stackoverflow.com/a/105074/1262753
  317. * @return {String} uuid
  318. */
  319. util.randomUUID = function randomUUID () {
  320. var S4 = function () {
  321. return Math.floor(
  322. Math.random() * 0x10000 /* 65536 */
  323. ).toString(16);
  324. };
  325. return (
  326. S4() + S4() + '-' +
  327. S4() + '-' +
  328. S4() + '-' +
  329. S4() + '-' +
  330. S4() + S4() + S4()
  331. );
  332. };
  333. /**
  334. * Extend object a with the properties of object b or a series of objects
  335. * Only properties with defined values are copied
  336. * @param {Object} a
  337. * @param {... Object} b
  338. * @return {Object} a
  339. */
  340. util.extend = function (a, b) {
  341. for (var i = 1, len = arguments.length; i < len; i++) {
  342. var other = arguments[i];
  343. for (var prop in other) {
  344. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  345. a[prop] = other[prop];
  346. }
  347. }
  348. }
  349. return a;
  350. };
  351. /**
  352. * Convert an object to another type
  353. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  354. * @param {String | undefined} type Name of the type. Available types:
  355. * 'Boolean', 'Number', 'String',
  356. * 'Date', 'Moment', ISODate', 'ASPDate'.
  357. * @return {*} object
  358. * @throws Error
  359. */
  360. util.convert = function convert(object, type) {
  361. var match;
  362. if (object === undefined) {
  363. return undefined;
  364. }
  365. if (object === null) {
  366. return null;
  367. }
  368. if (!type) {
  369. return object;
  370. }
  371. if (!(typeof type === 'string') && !(type instanceof String)) {
  372. throw new Error('Type must be a string');
  373. }
  374. //noinspection FallthroughInSwitchStatementJS
  375. switch (type) {
  376. case 'boolean':
  377. case 'Boolean':
  378. return Boolean(object);
  379. case 'number':
  380. case 'Number':
  381. return Number(object.valueOf());
  382. case 'string':
  383. case 'String':
  384. return String(object);
  385. case 'Date':
  386. if (util.isNumber(object)) {
  387. return new Date(object);
  388. }
  389. if (object instanceof Date) {
  390. return new Date(object.valueOf());
  391. }
  392. else if (moment.isMoment(object)) {
  393. return new Date(object.valueOf());
  394. }
  395. if (util.isString(object)) {
  396. match = ASPDateRegex.exec(object);
  397. if (match) {
  398. // object is an ASP date
  399. return new Date(Number(match[1])); // parse number
  400. }
  401. else {
  402. return moment(object).toDate(); // parse string
  403. }
  404. }
  405. else {
  406. throw new Error(
  407. 'Cannot convert object of type ' + util.getType(object) +
  408. ' to type Date');
  409. }
  410. case 'Moment':
  411. if (util.isNumber(object)) {
  412. return moment(object);
  413. }
  414. if (object instanceof Date) {
  415. return moment(object.valueOf());
  416. }
  417. else if (moment.isMoment(object)) {
  418. return moment(object);
  419. }
  420. if (util.isString(object)) {
  421. match = ASPDateRegex.exec(object);
  422. if (match) {
  423. // object is an ASP date
  424. return moment(Number(match[1])); // parse number
  425. }
  426. else {
  427. return moment(object); // parse string
  428. }
  429. }
  430. else {
  431. throw new Error(
  432. 'Cannot convert object of type ' + util.getType(object) +
  433. ' to type Date');
  434. }
  435. case 'ISODate':
  436. if (util.isNumber(object)) {
  437. return new Date(object);
  438. }
  439. else if (object instanceof Date) {
  440. return object.toISOString();
  441. }
  442. else if (moment.isMoment(object)) {
  443. return object.toDate().toISOString();
  444. }
  445. else if (util.isString(object)) {
  446. match = ASPDateRegex.exec(object);
  447. if (match) {
  448. // object is an ASP date
  449. return new Date(Number(match[1])).toISOString(); // parse number
  450. }
  451. else {
  452. return new Date(object).toISOString(); // parse string
  453. }
  454. }
  455. else {
  456. throw new Error(
  457. 'Cannot convert object of type ' + util.getType(object) +
  458. ' to type ISODate');
  459. }
  460. case 'ASPDate':
  461. if (util.isNumber(object)) {
  462. return '/Date(' + object + ')/';
  463. }
  464. else if (object instanceof Date) {
  465. return '/Date(' + object.valueOf() + ')/';
  466. }
  467. else if (util.isString(object)) {
  468. match = ASPDateRegex.exec(object);
  469. var value;
  470. if (match) {
  471. // object is an ASP date
  472. value = new Date(Number(match[1])).valueOf(); // parse number
  473. }
  474. else {
  475. value = new Date(object).valueOf(); // parse string
  476. }
  477. return '/Date(' + value + ')/';
  478. }
  479. else {
  480. throw new Error(
  481. 'Cannot convert object of type ' + util.getType(object) +
  482. ' to type ASPDate');
  483. }
  484. default:
  485. throw new Error('Cannot convert object of type ' + util.getType(object) +
  486. ' to type "' + type + '"');
  487. }
  488. };
  489. // parse ASP.Net Date pattern,
  490. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  491. // code from http://momentjs.com/
  492. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  493. /**
  494. * Get the type of an object, for example util.getType([]) returns 'Array'
  495. * @param {*} object
  496. * @return {String} type
  497. */
  498. util.getType = function getType(object) {
  499. var type = typeof object;
  500. if (type == 'object') {
  501. if (object == null) {
  502. return 'null';
  503. }
  504. if (object instanceof Boolean) {
  505. return 'Boolean';
  506. }
  507. if (object instanceof Number) {
  508. return 'Number';
  509. }
  510. if (object instanceof String) {
  511. return 'String';
  512. }
  513. if (object instanceof Array) {
  514. return 'Array';
  515. }
  516. if (object instanceof Date) {
  517. return 'Date';
  518. }
  519. return 'Object';
  520. }
  521. else if (type == 'number') {
  522. return 'Number';
  523. }
  524. else if (type == 'boolean') {
  525. return 'Boolean';
  526. }
  527. else if (type == 'string') {
  528. return 'String';
  529. }
  530. return type;
  531. };
  532. /**
  533. * Retrieve the absolute left value of a DOM element
  534. * @param {Element} elem A dom element, for example a div
  535. * @return {number} left The absolute left position of this element
  536. * in the browser page.
  537. */
  538. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  539. var doc = document.documentElement;
  540. var body = document.body;
  541. var left = elem.offsetLeft;
  542. var e = elem.offsetParent;
  543. while (e != null && e != body && e != doc) {
  544. left += e.offsetLeft;
  545. left -= e.scrollLeft;
  546. e = e.offsetParent;
  547. }
  548. return left;
  549. };
  550. /**
  551. * Retrieve the absolute top value of a DOM element
  552. * @param {Element} elem A dom element, for example a div
  553. * @return {number} top The absolute top position of this element
  554. * in the browser page.
  555. */
  556. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  557. var doc = document.documentElement;
  558. var body = document.body;
  559. var top = elem.offsetTop;
  560. var e = elem.offsetParent;
  561. while (e != null && e != body && e != doc) {
  562. top += e.offsetTop;
  563. top -= e.scrollTop;
  564. e = e.offsetParent;
  565. }
  566. return top;
  567. };
  568. /**
  569. * Get the absolute, vertical mouse position from an event.
  570. * @param {Event} event
  571. * @return {Number} pageY
  572. */
  573. util.getPageY = function getPageY (event) {
  574. if ('pageY' in event) {
  575. return event.pageY;
  576. }
  577. else {
  578. var clientY;
  579. if (('targetTouches' in event) && event.targetTouches.length) {
  580. clientY = event.targetTouches[0].clientY;
  581. }
  582. else {
  583. clientY = event.clientY;
  584. }
  585. var doc = document.documentElement;
  586. var body = document.body;
  587. return clientY +
  588. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  589. ( doc && doc.clientTop || body && body.clientTop || 0 );
  590. }
  591. };
  592. /**
  593. * Get the absolute, horizontal mouse position from an event.
  594. * @param {Event} event
  595. * @return {Number} pageX
  596. */
  597. util.getPageX = function getPageX (event) {
  598. if ('pageY' in event) {
  599. return event.pageX;
  600. }
  601. else {
  602. var clientX;
  603. if (('targetTouches' in event) && event.targetTouches.length) {
  604. clientX = event.targetTouches[0].clientX;
  605. }
  606. else {
  607. clientX = event.clientX;
  608. }
  609. var doc = document.documentElement;
  610. var body = document.body;
  611. return clientX +
  612. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  613. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  614. }
  615. };
  616. /**
  617. * add a className to the given elements style
  618. * @param {Element} elem
  619. * @param {String} className
  620. */
  621. util.addClassName = function addClassName(elem, className) {
  622. var classes = elem.className.split(' ');
  623. if (classes.indexOf(className) == -1) {
  624. classes.push(className); // add the class to the array
  625. elem.className = classes.join(' ');
  626. }
  627. };
  628. /**
  629. * add a className to the given elements style
  630. * @param {Element} elem
  631. * @param {String} className
  632. */
  633. util.removeClassName = function removeClassname(elem, className) {
  634. var classes = elem.className.split(' ');
  635. var index = classes.indexOf(className);
  636. if (index != -1) {
  637. classes.splice(index, 1); // remove the class from the array
  638. elem.className = classes.join(' ');
  639. }
  640. };
  641. /**
  642. * For each method for both arrays and objects.
  643. * In case of an array, the built-in Array.forEach() is applied.
  644. * In case of an Object, the method loops over all properties of the object.
  645. * @param {Object | Array} object An Object or Array
  646. * @param {function} callback Callback method, called for each item in
  647. * the object or array with three parameters:
  648. * callback(value, index, object)
  649. */
  650. util.forEach = function forEach (object, callback) {
  651. var i,
  652. len;
  653. if (object instanceof Array) {
  654. // array
  655. for (i = 0, len = object.length; i < len; i++) {
  656. callback(object[i], i, object);
  657. }
  658. }
  659. else {
  660. // object
  661. for (i in object) {
  662. if (object.hasOwnProperty(i)) {
  663. callback(object[i], i, object);
  664. }
  665. }
  666. }
  667. };
  668. /**
  669. * Update a property in an object
  670. * @param {Object} object
  671. * @param {String} key
  672. * @param {*} value
  673. * @return {Boolean} changed
  674. */
  675. util.updateProperty = function updateProp (object, key, value) {
  676. if (object[key] !== value) {
  677. object[key] = value;
  678. return true;
  679. }
  680. else {
  681. return false;
  682. }
  683. };
  684. /**
  685. * Add and event listener. Works for all browsers
  686. * @param {Element} element An html element
  687. * @param {string} action The action, for example "click",
  688. * without the prefix "on"
  689. * @param {function} listener The callback function to be executed
  690. * @param {boolean} [useCapture]
  691. */
  692. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  693. if (element.addEventListener) {
  694. if (useCapture === undefined)
  695. useCapture = false;
  696. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  697. action = "DOMMouseScroll"; // For Firefox
  698. }
  699. element.addEventListener(action, listener, useCapture);
  700. } else {
  701. element.attachEvent("on" + action, listener); // IE browsers
  702. }
  703. };
  704. /**
  705. * Remove an event listener from an element
  706. * @param {Element} element An html dom element
  707. * @param {string} action The name of the event, for example "mousedown"
  708. * @param {function} listener The listener function
  709. * @param {boolean} [useCapture]
  710. */
  711. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  712. if (element.removeEventListener) {
  713. // non-IE browsers
  714. if (useCapture === undefined)
  715. useCapture = false;
  716. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  717. action = "DOMMouseScroll"; // For Firefox
  718. }
  719. element.removeEventListener(action, listener, useCapture);
  720. } else {
  721. // IE browsers
  722. element.detachEvent("on" + action, listener);
  723. }
  724. };
  725. /**
  726. * Get HTML element which is the target of the event
  727. * @param {Event} event
  728. * @return {Element} target element
  729. */
  730. util.getTarget = function getTarget(event) {
  731. // code from http://www.quirksmode.org/js/events_properties.html
  732. if (!event) {
  733. event = window.event;
  734. }
  735. var target;
  736. if (event.target) {
  737. target = event.target;
  738. }
  739. else if (event.srcElement) {
  740. target = event.srcElement;
  741. }
  742. if (target.nodeType != undefined && target.nodeType == 3) {
  743. // defeat Safari bug
  744. target = target.parentNode;
  745. }
  746. return target;
  747. };
  748. /**
  749. * Stop event propagation
  750. */
  751. util.stopPropagation = function stopPropagation(event) {
  752. if (!event)
  753. event = window.event;
  754. if (event.stopPropagation) {
  755. event.stopPropagation(); // non-IE browsers
  756. }
  757. else {
  758. event.cancelBubble = true; // IE browsers
  759. }
  760. };
  761. /**
  762. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  763. * @param {Element} element
  764. * @param {Event} event
  765. */
  766. util.fakeGesture = function fakeGesture (element, event) {
  767. var eventType = null;
  768. // for hammer.js 1.0.5
  769. return Hammer.event.collectEventData(this, eventType, event);
  770. // for hammer.js 1.0.6
  771. //var touches = Hammer.event.getTouchList(event, eventType);
  772. //return Hammer.event.collectEventData(this, eventType, touches, event);
  773. };
  774. /**
  775. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  776. */
  777. util.preventDefault = function preventDefault (event) {
  778. if (!event)
  779. event = window.event;
  780. if (event.preventDefault) {
  781. event.preventDefault(); // non-IE browsers
  782. }
  783. else {
  784. event.returnValue = false; // IE browsers
  785. }
  786. };
  787. util.option = {};
  788. /**
  789. * Convert a value into a boolean
  790. * @param {Boolean | function | undefined} value
  791. * @param {Boolean} [defaultValue]
  792. * @returns {Boolean} bool
  793. */
  794. util.option.asBoolean = function (value, defaultValue) {
  795. if (typeof value == 'function') {
  796. value = value();
  797. }
  798. if (value != null) {
  799. return (value != false);
  800. }
  801. return defaultValue || null;
  802. };
  803. /**
  804. * Convert a value into a number
  805. * @param {Boolean | function | undefined} value
  806. * @param {Number} [defaultValue]
  807. * @returns {Number} number
  808. */
  809. util.option.asNumber = function (value, defaultValue) {
  810. if (typeof value == 'function') {
  811. value = value();
  812. }
  813. if (value != null) {
  814. return Number(value) || defaultValue || null;
  815. }
  816. return defaultValue || null;
  817. };
  818. /**
  819. * Convert a value into a string
  820. * @param {String | function | undefined} value
  821. * @param {String} [defaultValue]
  822. * @returns {String} str
  823. */
  824. util.option.asString = function (value, defaultValue) {
  825. if (typeof value == 'function') {
  826. value = value();
  827. }
  828. if (value != null) {
  829. return String(value);
  830. }
  831. return defaultValue || null;
  832. };
  833. /**
  834. * Convert a size or location into a string with pixels or a percentage
  835. * @param {String | Number | function | undefined} value
  836. * @param {String} [defaultValue]
  837. * @returns {String} size
  838. */
  839. util.option.asSize = function (value, defaultValue) {
  840. if (typeof value == 'function') {
  841. value = value();
  842. }
  843. if (util.isString(value)) {
  844. return value;
  845. }
  846. else if (util.isNumber(value)) {
  847. return value + 'px';
  848. }
  849. else {
  850. return defaultValue || null;
  851. }
  852. };
  853. /**
  854. * Convert a value into a DOM element
  855. * @param {HTMLElement | function | undefined} value
  856. * @param {HTMLElement} [defaultValue]
  857. * @returns {HTMLElement | null} dom
  858. */
  859. util.option.asElement = function (value, defaultValue) {
  860. if (typeof value == 'function') {
  861. value = value();
  862. }
  863. return value || defaultValue || null;
  864. };
  865. /**
  866. * Event listener (singleton)
  867. */
  868. // TODO: replace usage of the event listener for the EventBus
  869. var events = {
  870. 'listeners': [],
  871. /**
  872. * Find a single listener by its object
  873. * @param {Object} object
  874. * @return {Number} index -1 when not found
  875. */
  876. 'indexOf': function (object) {
  877. var listeners = this.listeners;
  878. for (var i = 0, iMax = this.listeners.length; i < iMax; i++) {
  879. var listener = listeners[i];
  880. if (listener && listener.object == object) {
  881. return i;
  882. }
  883. }
  884. return -1;
  885. },
  886. /**
  887. * Add an event listener
  888. * @param {Object} object
  889. * @param {String} event The name of an event, for example 'select'
  890. * @param {function} callback The callback method, called when the
  891. * event takes place
  892. */
  893. 'addListener': function (object, event, callback) {
  894. var index = this.indexOf(object);
  895. var listener = this.listeners[index];
  896. if (!listener) {
  897. listener = {
  898. 'object': object,
  899. 'events': {}
  900. };
  901. this.listeners.push(listener);
  902. }
  903. var callbacks = listener.events[event];
  904. if (!callbacks) {
  905. callbacks = [];
  906. listener.events[event] = callbacks;
  907. }
  908. // add the callback if it does not yet exist
  909. if (callbacks.indexOf(callback) == -1) {
  910. callbacks.push(callback);
  911. }
  912. },
  913. /**
  914. * Remove an event listener
  915. * @param {Object} object
  916. * @param {String} event The name of an event, for example 'select'
  917. * @param {function} callback The registered callback method
  918. */
  919. 'removeListener': function (object, event, callback) {
  920. var index = this.indexOf(object);
  921. var listener = this.listeners[index];
  922. if (listener) {
  923. var callbacks = listener.events[event];
  924. if (callbacks) {
  925. index = callbacks.indexOf(callback);
  926. if (index != -1) {
  927. callbacks.splice(index, 1);
  928. }
  929. // remove the array when empty
  930. if (callbacks.length == 0) {
  931. delete listener.events[event];
  932. }
  933. }
  934. // count the number of registered events. remove listener when empty
  935. var count = 0;
  936. var events = listener.events;
  937. for (var e in events) {
  938. if (events.hasOwnProperty(e)) {
  939. count++;
  940. }
  941. }
  942. if (count == 0) {
  943. delete this.listeners[index];
  944. }
  945. }
  946. },
  947. /**
  948. * Remove all registered event listeners
  949. */
  950. 'removeAllListeners': function () {
  951. this.listeners = [];
  952. },
  953. /**
  954. * Trigger an event. All registered event handlers will be called
  955. * @param {Object} object
  956. * @param {String} event
  957. * @param {Object} properties (optional)
  958. */
  959. 'trigger': function (object, event, properties) {
  960. var index = this.indexOf(object);
  961. var listener = this.listeners[index];
  962. if (listener) {
  963. var callbacks = listener.events[event];
  964. if (callbacks) {
  965. for (var i = 0, iMax = callbacks.length; i < iMax; i++) {
  966. callbacks[i](properties);
  967. }
  968. }
  969. }
  970. }
  971. };
  972. /**
  973. * An event bus can be used to emit events, and to subscribe to events
  974. * @constructor EventBus
  975. */
  976. function EventBus() {
  977. this.subscriptions = [];
  978. }
  979. /**
  980. * Subscribe to an event
  981. * @param {String | RegExp} event The event can be a regular expression, or
  982. * a string with wildcards, like 'server.*'.
  983. * @param {function} callback. Callback are called with three parameters:
  984. * {String} event, {*} [data], {*} [source]
  985. * @param {*} [target]
  986. * @returns {String} id A subscription id
  987. */
  988. EventBus.prototype.on = function (event, callback, target) {
  989. var regexp = (event instanceof RegExp) ?
  990. event :
  991. new RegExp(event.replace('*', '\\w+'));
  992. var subscription = {
  993. id: util.randomUUID(),
  994. event: event,
  995. regexp: regexp,
  996. callback: (typeof callback === 'function') ? callback : null,
  997. target: target
  998. };
  999. this.subscriptions.push(subscription);
  1000. return subscription.id;
  1001. };
  1002. /**
  1003. * Unsubscribe from an event
  1004. * @param {String | Object} filter Filter for subscriptions to be removed
  1005. * Filter can be a string containing a
  1006. * subscription id, or an object containing
  1007. * one or more of the fields id, event,
  1008. * callback, and target.
  1009. */
  1010. EventBus.prototype.off = function (filter) {
  1011. var i = 0;
  1012. while (i < this.subscriptions.length) {
  1013. var subscription = this.subscriptions[i];
  1014. var match = true;
  1015. if (filter instanceof Object) {
  1016. // filter is an object. All fields must match
  1017. for (var prop in filter) {
  1018. if (filter.hasOwnProperty(prop)) {
  1019. if (filter[prop] !== subscription[prop]) {
  1020. match = false;
  1021. }
  1022. }
  1023. }
  1024. }
  1025. else {
  1026. // filter is a string, filter on id
  1027. match = (subscription.id == filter);
  1028. }
  1029. if (match) {
  1030. this.subscriptions.splice(i, 1);
  1031. }
  1032. else {
  1033. i++;
  1034. }
  1035. }
  1036. };
  1037. /**
  1038. * Emit an event
  1039. * @param {String} event
  1040. * @param {*} [data]
  1041. * @param {*} [source]
  1042. */
  1043. EventBus.prototype.emit = function (event, data, source) {
  1044. for (var i =0; i < this.subscriptions.length; i++) {
  1045. var subscription = this.subscriptions[i];
  1046. if (subscription.regexp.test(event)) {
  1047. if (subscription.callback) {
  1048. subscription.callback(event, data, source);
  1049. }
  1050. }
  1051. }
  1052. };
  1053. /**
  1054. * DataSet
  1055. *
  1056. * Usage:
  1057. * var dataSet = new DataSet({
  1058. * fieldId: '_id',
  1059. * convert: {
  1060. * // ...
  1061. * }
  1062. * });
  1063. *
  1064. * dataSet.add(item);
  1065. * dataSet.add(data);
  1066. * dataSet.update(item);
  1067. * dataSet.update(data);
  1068. * dataSet.remove(id);
  1069. * dataSet.remove(ids);
  1070. * var data = dataSet.get();
  1071. * var data = dataSet.get(id);
  1072. * var data = dataSet.get(ids);
  1073. * var data = dataSet.get(ids, options, data);
  1074. * dataSet.clear();
  1075. *
  1076. * A data set can:
  1077. * - add/remove/update data
  1078. * - gives triggers upon changes in the data
  1079. * - can import/export data in various data formats
  1080. *
  1081. * @param {Object} [options] Available options:
  1082. * {String} fieldId Field name of the id in the
  1083. * items, 'id' by default.
  1084. * {Object.<String, String} convert
  1085. * A map with field names as key,
  1086. * and the field type as value.
  1087. * @constructor DataSet
  1088. */
  1089. // TODO: add a DataSet constructor DataSet(data, options)
  1090. function DataSet (options) {
  1091. this.id = util.randomUUID();
  1092. this.options = options || {};
  1093. this.data = {}; // map with data indexed by id
  1094. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1095. this.convert = {}; // field types by field name
  1096. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1097. if (this.options.convert) {
  1098. for (var field in this.options.convert) {
  1099. if (this.options.convert.hasOwnProperty(field)) {
  1100. var value = this.options.convert[field];
  1101. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1102. this.convert[field] = 'Date';
  1103. }
  1104. else {
  1105. this.convert[field] = value;
  1106. }
  1107. }
  1108. }
  1109. }
  1110. // event subscribers
  1111. this.subscribers = {};
  1112. this.internalIds = {}; // internally generated id's
  1113. }
  1114. /**
  1115. * Subscribe to an event, add an event listener
  1116. * @param {String} event Event name. Available events: 'put', 'update',
  1117. * 'remove'
  1118. * @param {function} callback Callback method. Called with three parameters:
  1119. * {String} event
  1120. * {Object | null} params
  1121. * {String | Number} senderId
  1122. */
  1123. DataSet.prototype.subscribe = function (event, callback) {
  1124. var subscribers = this.subscribers[event];
  1125. if (!subscribers) {
  1126. subscribers = [];
  1127. this.subscribers[event] = subscribers;
  1128. }
  1129. subscribers.push({
  1130. callback: callback
  1131. });
  1132. };
  1133. /**
  1134. * Unsubscribe from an event, remove an event listener
  1135. * @param {String} event
  1136. * @param {function} callback
  1137. */
  1138. DataSet.prototype.unsubscribe = function (event, callback) {
  1139. var subscribers = this.subscribers[event];
  1140. if (subscribers) {
  1141. this.subscribers[event] = subscribers.filter(function (listener) {
  1142. return (listener.callback != callback);
  1143. });
  1144. }
  1145. };
  1146. /**
  1147. * Trigger an event
  1148. * @param {String} event
  1149. * @param {Object | null} params
  1150. * @param {String} [senderId] Optional id of the sender.
  1151. * @private
  1152. */
  1153. DataSet.prototype._trigger = function (event, params, senderId) {
  1154. if (event == '*') {
  1155. throw new Error('Cannot trigger event *');
  1156. }
  1157. var subscribers = [];
  1158. if (event in this.subscribers) {
  1159. subscribers = subscribers.concat(this.subscribers[event]);
  1160. }
  1161. if ('*' in this.subscribers) {
  1162. subscribers = subscribers.concat(this.subscribers['*']);
  1163. }
  1164. for (var i = 0; i < subscribers.length; i++) {
  1165. var subscriber = subscribers[i];
  1166. if (subscriber.callback) {
  1167. subscriber.callback(event, params, senderId || null);
  1168. }
  1169. }
  1170. };
  1171. /**
  1172. * Add data.
  1173. * Adding an item will fail when there already is an item with the same id.
  1174. * @param {Object | Array | DataTable} data
  1175. * @param {String} [senderId] Optional sender id
  1176. * @return {Array} addedIds Array with the ids of the added items
  1177. */
  1178. DataSet.prototype.add = function (data, senderId) {
  1179. var addedIds = [],
  1180. id,
  1181. me = this;
  1182. if (data instanceof Array) {
  1183. // Array
  1184. for (var i = 0, len = data.length; i < len; i++) {
  1185. id = me._addItem(data[i]);
  1186. addedIds.push(id);
  1187. }
  1188. }
  1189. else if (util.isDataTable(data)) {
  1190. // Google DataTable
  1191. var columns = this._getColumnNames(data);
  1192. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1193. var item = {};
  1194. for (var col = 0, cols = columns.length; col < cols; col++) {
  1195. var field = columns[col];
  1196. item[field] = data.getValue(row, col);
  1197. }
  1198. id = me._addItem(item);
  1199. addedIds.push(id);
  1200. }
  1201. }
  1202. else if (data instanceof Object) {
  1203. // Single item
  1204. id = me._addItem(data);
  1205. addedIds.push(id);
  1206. }
  1207. else {
  1208. throw new Error('Unknown dataType');
  1209. }
  1210. if (addedIds.length) {
  1211. this._trigger('add', {items: addedIds}, senderId);
  1212. }
  1213. return addedIds;
  1214. };
  1215. /**
  1216. * Update existing items. When an item does not exist, it will be created
  1217. * @param {Object | Array | DataTable} data
  1218. * @param {String} [senderId] Optional sender id
  1219. * @return {Array} updatedIds The ids of the added or updated items
  1220. */
  1221. DataSet.prototype.update = function (data, senderId) {
  1222. var addedIds = [],
  1223. updatedIds = [],
  1224. me = this,
  1225. fieldId = me.fieldId;
  1226. var addOrUpdate = function (item) {
  1227. var id = item[fieldId];
  1228. if (me.data[id]) {
  1229. // update item
  1230. id = me._updateItem(item);
  1231. updatedIds.push(id);
  1232. }
  1233. else {
  1234. // add new item
  1235. id = me._addItem(item);
  1236. addedIds.push(id);
  1237. }
  1238. };
  1239. if (data instanceof Array) {
  1240. // Array
  1241. for (var i = 0, len = data.length; i < len; i++) {
  1242. addOrUpdate(data[i]);
  1243. }
  1244. }
  1245. else if (util.isDataTable(data)) {
  1246. // Google DataTable
  1247. var columns = this._getColumnNames(data);
  1248. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1249. var item = {};
  1250. for (var col = 0, cols = columns.length; col < cols; col++) {
  1251. var field = columns[col];
  1252. item[field] = data.getValue(row, col);
  1253. }
  1254. addOrUpdate(item);
  1255. }
  1256. }
  1257. else if (data instanceof Object) {
  1258. // Single item
  1259. addOrUpdate(data);
  1260. }
  1261. else {
  1262. throw new Error('Unknown dataType');
  1263. }
  1264. if (addedIds.length) {
  1265. this._trigger('add', {items: addedIds}, senderId);
  1266. }
  1267. if (updatedIds.length) {
  1268. this._trigger('update', {items: updatedIds}, senderId);
  1269. }
  1270. return addedIds.concat(updatedIds);
  1271. };
  1272. /**
  1273. * Get a data item or multiple items.
  1274. *
  1275. * Usage:
  1276. *
  1277. * get()
  1278. * get(options: Object)
  1279. * get(options: Object, data: Array | DataTable)
  1280. *
  1281. * get(id: Number | String)
  1282. * get(id: Number | String, options: Object)
  1283. * get(id: Number | String, options: Object, data: Array | DataTable)
  1284. *
  1285. * get(ids: Number[] | String[])
  1286. * get(ids: Number[] | String[], options: Object)
  1287. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1288. *
  1289. * Where:
  1290. *
  1291. * {Number | String} id The id of an item
  1292. * {Number[] | String{}} ids An array with ids of items
  1293. * {Object} options An Object with options. Available options:
  1294. * {String} [type] Type of data to be returned. Can
  1295. * be 'DataTable' or 'Array' (default)
  1296. * {Object.<String, String>} [convert]
  1297. * {String[]} [fields] field names to be returned
  1298. * {function} [filter] filter items
  1299. * {String | function} [order] Order the items by
  1300. * a field name or custom sort function.
  1301. * {Array | DataTable} [data] If provided, items will be appended to this
  1302. * array or table. Required in case of Google
  1303. * DataTable.
  1304. *
  1305. * @throws Error
  1306. */
  1307. DataSet.prototype.get = function (args) {
  1308. var me = this;
  1309. var globalShowInternalIds = this.showInternalIds;
  1310. // parse the arguments
  1311. var id, ids, options, data;
  1312. var firstType = util.getType(arguments[0]);
  1313. if (firstType == 'String' || firstType == 'Number') {
  1314. // get(id [, options] [, data])
  1315. id = arguments[0];
  1316. options = arguments[1];
  1317. data = arguments[2];
  1318. }
  1319. else if (firstType == 'Array') {
  1320. // get(ids [, options] [, data])
  1321. ids = arguments[0];
  1322. options = arguments[1];
  1323. data = arguments[2];
  1324. }
  1325. else {
  1326. // get([, options] [, data])
  1327. options = arguments[0];
  1328. data = arguments[1];
  1329. }
  1330. // determine the return type
  1331. var type;
  1332. if (options && options.type) {
  1333. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1334. if (data && (type != util.getType(data))) {
  1335. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1336. 'does not correspond with specified options.type (' + options.type + ')');
  1337. }
  1338. if (type == 'DataTable' && !util.isDataTable(data)) {
  1339. throw new Error('Parameter "data" must be a DataTable ' +
  1340. 'when options.type is "DataTable"');
  1341. }
  1342. }
  1343. else if (data) {
  1344. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1345. }
  1346. else {
  1347. type = 'Array';
  1348. }
  1349. // we allow the setting of this value for a single get request.
  1350. if (options != undefined) {
  1351. if (options.showInternalIds != undefined) {
  1352. this.showInternalIds = options.showInternalIds;
  1353. }
  1354. }
  1355. // build options
  1356. var convert = options && options.convert || this.options.convert;
  1357. var filter = options && options.filter;
  1358. var items = [], item, itemId, i, len;
  1359. // convert items
  1360. if (id != undefined) {
  1361. // return a single item
  1362. item = me._getItem(id, convert);
  1363. if (filter && !filter(item)) {
  1364. item = null;
  1365. }
  1366. }
  1367. else if (ids != undefined) {
  1368. // return a subset of items
  1369. for (i = 0, len = ids.length; i < len; i++) {
  1370. item = me._getItem(ids[i], convert);
  1371. if (!filter || filter(item)) {
  1372. items.push(item);
  1373. }
  1374. }
  1375. }
  1376. else {
  1377. // return all items
  1378. for (itemId in this.data) {
  1379. if (this.data.hasOwnProperty(itemId)) {
  1380. item = me._getItem(itemId, convert);
  1381. if (!filter || filter(item)) {
  1382. items.push(item);
  1383. }
  1384. }
  1385. }
  1386. }
  1387. // restore the global value of showInternalIds
  1388. this.showInternalIds = globalShowInternalIds;
  1389. // order the results
  1390. if (options && options.order && id == undefined) {
  1391. this._sort(items, options.order);
  1392. }
  1393. // filter fields of the items
  1394. if (options && options.fields) {
  1395. var fields = options.fields;
  1396. if (id != undefined) {
  1397. item = this._filterFields(item, fields);
  1398. }
  1399. else {
  1400. for (i = 0, len = items.length; i < len; i++) {
  1401. items[i] = this._filterFields(items[i], fields);
  1402. }
  1403. }
  1404. }
  1405. // return the results
  1406. if (type == 'DataTable') {
  1407. var columns = this._getColumnNames(data);
  1408. if (id != undefined) {
  1409. // append a single item to the data table
  1410. me._appendRow(data, columns, item);
  1411. }
  1412. else {
  1413. // copy the items to the provided data table
  1414. for (i = 0, len = items.length; i < len; i++) {
  1415. me._appendRow(data, columns, items[i]);
  1416. }
  1417. }
  1418. return data;
  1419. }
  1420. else {
  1421. // return an array
  1422. if (id != undefined) {
  1423. // a single item
  1424. return item;
  1425. }
  1426. else {
  1427. // multiple items
  1428. if (data) {
  1429. // copy the items to the provided array
  1430. for (i = 0, len = items.length; i < len; i++) {
  1431. data.push(items[i]);
  1432. }
  1433. return data;
  1434. }
  1435. else {
  1436. // just return our array
  1437. return items;
  1438. }
  1439. }
  1440. }
  1441. };
  1442. /**
  1443. * Get ids of all items or from a filtered set of items.
  1444. * @param {Object} [options] An Object with options. Available options:
  1445. * {function} [filter] filter items
  1446. * {String | function} [order] Order the items by
  1447. * a field name or custom sort function.
  1448. * @return {Array} ids
  1449. */
  1450. DataSet.prototype.getIds = function (options) {
  1451. var data = this.data,
  1452. filter = options && options.filter,
  1453. order = options && options.order,
  1454. convert = options && options.convert || this.options.convert,
  1455. i,
  1456. len,
  1457. id,
  1458. item,
  1459. items,
  1460. ids = [];
  1461. if (filter) {
  1462. // get filtered items
  1463. if (order) {
  1464. // create ordered list
  1465. items = [];
  1466. for (id in data) {
  1467. if (data.hasOwnProperty(id)) {
  1468. item = this._getItem(id, convert);
  1469. if (filter(item)) {
  1470. items.push(item);
  1471. }
  1472. }
  1473. }
  1474. this._sort(items, order);
  1475. for (i = 0, len = items.length; i < len; i++) {
  1476. ids[i] = items[i][this.fieldId];
  1477. }
  1478. }
  1479. else {
  1480. // create unordered list
  1481. for (id in data) {
  1482. if (data.hasOwnProperty(id)) {
  1483. item = this._getItem(id, convert);
  1484. if (filter(item)) {
  1485. ids.push(item[this.fieldId]);
  1486. }
  1487. }
  1488. }
  1489. }
  1490. }
  1491. else {
  1492. // get all items
  1493. if (order) {
  1494. // create an ordered list
  1495. items = [];
  1496. for (id in data) {
  1497. if (data.hasOwnProperty(id)) {
  1498. items.push(data[id]);
  1499. }
  1500. }
  1501. this._sort(items, order);
  1502. for (i = 0, len = items.length; i < len; i++) {
  1503. ids[i] = items[i][this.fieldId];
  1504. }
  1505. }
  1506. else {
  1507. // create unordered list
  1508. for (id in data) {
  1509. if (data.hasOwnProperty(id)) {
  1510. item = data[id];
  1511. ids.push(item[this.fieldId]);
  1512. }
  1513. }
  1514. }
  1515. }
  1516. return ids;
  1517. };
  1518. /**
  1519. * Execute a callback function for every item in the dataset.
  1520. * The order of the items is not determined.
  1521. * @param {function} callback
  1522. * @param {Object} [options] Available options:
  1523. * {Object.<String, String>} [convert]
  1524. * {String[]} [fields] filter fields
  1525. * {function} [filter] filter items
  1526. * {String | function} [order] Order the items by
  1527. * a field name or custom sort function.
  1528. */
  1529. DataSet.prototype.forEach = function (callback, options) {
  1530. var filter = options && options.filter,
  1531. convert = options && options.convert || this.options.convert,
  1532. data = this.data,
  1533. item,
  1534. id;
  1535. if (options && options.order) {
  1536. // execute forEach on ordered list
  1537. var items = this.get(options);
  1538. for (var i = 0, len = items.length; i < len; i++) {
  1539. item = items[i];
  1540. id = item[this.fieldId];
  1541. callback(item, id);
  1542. }
  1543. }
  1544. else {
  1545. // unordered
  1546. for (id in data) {
  1547. if (data.hasOwnProperty(id)) {
  1548. item = this._getItem(id, convert);
  1549. if (!filter || filter(item)) {
  1550. callback(item, id);
  1551. }
  1552. }
  1553. }
  1554. }
  1555. };
  1556. /**
  1557. * Map every item in the dataset.
  1558. * @param {function} callback
  1559. * @param {Object} [options] Available options:
  1560. * {Object.<String, String>} [convert]
  1561. * {String[]} [fields] filter fields
  1562. * {function} [filter] filter items
  1563. * {String | function} [order] Order the items by
  1564. * a field name or custom sort function.
  1565. * @return {Object[]} mappedItems
  1566. */
  1567. DataSet.prototype.map = function (callback, options) {
  1568. var filter = options && options.filter,
  1569. convert = options && options.convert || this.options.convert,
  1570. mappedItems = [],
  1571. data = this.data,
  1572. item;
  1573. // convert and filter items
  1574. for (var id in data) {
  1575. if (data.hasOwnProperty(id)) {
  1576. item = this._getItem(id, convert);
  1577. if (!filter || filter(item)) {
  1578. mappedItems.push(callback(item, id));
  1579. }
  1580. }
  1581. }
  1582. // order items
  1583. if (options && options.order) {
  1584. this._sort(mappedItems, options.order);
  1585. }
  1586. return mappedItems;
  1587. };
  1588. /**
  1589. * Filter the fields of an item
  1590. * @param {Object} item
  1591. * @param {String[]} fields Field names
  1592. * @return {Object} filteredItem
  1593. * @private
  1594. */
  1595. DataSet.prototype._filterFields = function (item, fields) {
  1596. var filteredItem = {};
  1597. for (var field in item) {
  1598. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1599. filteredItem[field] = item[field];
  1600. }
  1601. }
  1602. return filteredItem;
  1603. };
  1604. /**
  1605. * Sort the provided array with items
  1606. * @param {Object[]} items
  1607. * @param {String | function} order A field name or custom sort function.
  1608. * @private
  1609. */
  1610. DataSet.prototype._sort = function (items, order) {
  1611. if (util.isString(order)) {
  1612. // order by provided field name
  1613. var name = order; // field name
  1614. items.sort(function (a, b) {
  1615. var av = a[name];
  1616. var bv = b[name];
  1617. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1618. });
  1619. }
  1620. else if (typeof order === 'function') {
  1621. // order by sort function
  1622. items.sort(order);
  1623. }
  1624. // TODO: extend order by an Object {field:String, direction:String}
  1625. // where direction can be 'asc' or 'desc'
  1626. else {
  1627. throw new TypeError('Order must be a function or a string');
  1628. }
  1629. };
  1630. /**
  1631. * Remove an object by pointer or by id
  1632. * @param {String | Number | Object | Array} id Object or id, or an array with
  1633. * objects or ids to be removed
  1634. * @param {String} [senderId] Optional sender id
  1635. * @return {Array} removedIds
  1636. */
  1637. DataSet.prototype.remove = function (id, senderId) {
  1638. var removedIds = [],
  1639. i, len, removedId;
  1640. if (id instanceof Array) {
  1641. for (i = 0, len = id.length; i < len; i++) {
  1642. removedId = this._remove(id[i]);
  1643. if (removedId != null) {
  1644. removedIds.push(removedId);
  1645. }
  1646. }
  1647. }
  1648. else {
  1649. removedId = this._remove(id);
  1650. if (removedId != null) {
  1651. removedIds.push(removedId);
  1652. }
  1653. }
  1654. if (removedIds.length) {
  1655. this._trigger('remove', {items: removedIds}, senderId);
  1656. }
  1657. return removedIds;
  1658. };
  1659. /**
  1660. * Remove an item by its id
  1661. * @param {Number | String | Object} id id or item
  1662. * @returns {Number | String | null} id
  1663. * @private
  1664. */
  1665. DataSet.prototype._remove = function (id) {
  1666. if (util.isNumber(id) || util.isString(id)) {
  1667. if (this.data[id]) {
  1668. delete this.data[id];
  1669. delete this.internalIds[id];
  1670. return id;
  1671. }
  1672. }
  1673. else if (id instanceof Object) {
  1674. var itemId = id[this.fieldId];
  1675. if (itemId && this.data[itemId]) {
  1676. delete this.data[itemId];
  1677. delete this.internalIds[itemId];
  1678. return itemId;
  1679. }
  1680. }
  1681. return null;
  1682. };
  1683. /**
  1684. * Clear the data
  1685. * @param {String} [senderId] Optional sender id
  1686. * @return {Array} removedIds The ids of all removed items
  1687. */
  1688. DataSet.prototype.clear = function (senderId) {
  1689. var ids = Object.keys(this.data);
  1690. this.data = {};
  1691. this.internalIds = {};
  1692. this._trigger('remove', {items: ids}, senderId);
  1693. return ids;
  1694. };
  1695. /**
  1696. * Find the item with maximum value of a specified field
  1697. * @param {String} field
  1698. * @return {Object | null} item Item containing max value, or null if no items
  1699. */
  1700. DataSet.prototype.max = function (field) {
  1701. var data = this.data,
  1702. max = null,
  1703. maxField = null;
  1704. for (var id in data) {
  1705. if (data.hasOwnProperty(id)) {
  1706. var item = data[id];
  1707. var itemField = item[field];
  1708. if (itemField != null && (!max || itemField > maxField)) {
  1709. max = item;
  1710. maxField = itemField;
  1711. }
  1712. }
  1713. }
  1714. return max;
  1715. };
  1716. /**
  1717. * Find the item with minimum value of a specified field
  1718. * @param {String} field
  1719. * @return {Object | null} item Item containing max value, or null if no items
  1720. */
  1721. DataSet.prototype.min = function (field) {
  1722. var data = this.data,
  1723. min = null,
  1724. minField = null;
  1725. for (var id in data) {
  1726. if (data.hasOwnProperty(id)) {
  1727. var item = data[id];
  1728. var itemField = item[field];
  1729. if (itemField != null && (!min || itemField < minField)) {
  1730. min = item;
  1731. minField = itemField;
  1732. }
  1733. }
  1734. }
  1735. return min;
  1736. };
  1737. /**
  1738. * Find all distinct values of a specified field
  1739. * @param {String} field
  1740. * @return {Array} values Array containing all distinct values. If the data
  1741. * items do not contain the specified field, an array
  1742. * containing a single value undefined is returned.
  1743. * The returned array is unordered.
  1744. */
  1745. DataSet.prototype.distinct = function (field) {
  1746. var data = this.data,
  1747. values = [],
  1748. fieldType = this.options.convert[field],
  1749. count = 0;
  1750. for (var prop in data) {
  1751. if (data.hasOwnProperty(prop)) {
  1752. var item = data[prop];
  1753. var value = util.convert(item[field], fieldType);
  1754. var exists = false;
  1755. for (var i = 0; i < count; i++) {
  1756. if (values[i] == value) {
  1757. exists = true;
  1758. break;
  1759. }
  1760. }
  1761. if (!exists) {
  1762. values[count] = value;
  1763. count++;
  1764. }
  1765. }
  1766. }
  1767. return values;
  1768. };
  1769. /**
  1770. * Add a single item. Will fail when an item with the same id already exists.
  1771. * @param {Object} item
  1772. * @return {String} id
  1773. * @private
  1774. */
  1775. DataSet.prototype._addItem = function (item) {
  1776. var id = item[this.fieldId];
  1777. if (id != undefined) {
  1778. // check whether this id is already taken
  1779. if (this.data[id]) {
  1780. // item already exists
  1781. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1782. }
  1783. }
  1784. else {
  1785. // generate an id
  1786. id = util.randomUUID();
  1787. item[this.fieldId] = id;
  1788. this.internalIds[id] = item;
  1789. }
  1790. var d = {};
  1791. for (var field in item) {
  1792. if (item.hasOwnProperty(field)) {
  1793. var fieldType = this.convert[field]; // type may be undefined
  1794. d[field] = util.convert(item[field], fieldType);
  1795. }
  1796. }
  1797. this.data[id] = d;
  1798. return id;
  1799. };
  1800. /**
  1801. * Get an item. Fields can be converted to a specific type
  1802. * @param {String} id
  1803. * @param {Object.<String, String>} [convert] field types to convert
  1804. * @return {Object | null} item
  1805. * @private
  1806. */
  1807. DataSet.prototype._getItem = function (id, convert) {
  1808. var field, value;
  1809. // get the item from the dataset
  1810. var raw = this.data[id];
  1811. if (!raw) {
  1812. return null;
  1813. }
  1814. // convert the items field types
  1815. var converted = {},
  1816. fieldId = this.fieldId,
  1817. internalIds = this.internalIds;
  1818. if (convert) {
  1819. for (field in raw) {
  1820. if (raw.hasOwnProperty(field)) {
  1821. value = raw[field];
  1822. // output all fields, except internal ids
  1823. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1824. converted[field] = util.convert(value, convert[field]);
  1825. }
  1826. }
  1827. }
  1828. }
  1829. else {
  1830. // no field types specified, no converting needed
  1831. for (field in raw) {
  1832. if (raw.hasOwnProperty(field)) {
  1833. value = raw[field];
  1834. // output all fields, except internal ids
  1835. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1836. converted[field] = value;
  1837. }
  1838. }
  1839. }
  1840. }
  1841. return converted;
  1842. };
  1843. /**
  1844. * Update a single item: merge with existing item.
  1845. * Will fail when the item has no id, or when there does not exist an item
  1846. * with the same id.
  1847. * @param {Object} item
  1848. * @return {String} id
  1849. * @private
  1850. */
  1851. DataSet.prototype._updateItem = function (item) {
  1852. var id = item[this.fieldId];
  1853. if (id == undefined) {
  1854. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1855. }
  1856. var d = this.data[id];
  1857. if (!d) {
  1858. // item doesn't exist
  1859. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1860. }
  1861. // merge with current item
  1862. for (var field in item) {
  1863. if (item.hasOwnProperty(field)) {
  1864. var fieldType = this.convert[field]; // type may be undefined
  1865. d[field] = util.convert(item[field], fieldType);
  1866. }
  1867. }
  1868. return id;
  1869. };
  1870. /**
  1871. * check if an id is an internal or external id
  1872. * @param id
  1873. * @returns {boolean}
  1874. * @private
  1875. */
  1876. DataSet.prototype.isInternalId = function(id) {
  1877. return (id in this.internalIds);
  1878. };
  1879. /**
  1880. * Get an array with the column names of a Google DataTable
  1881. * @param {DataTable} dataTable
  1882. * @return {String[]} columnNames
  1883. * @private
  1884. */
  1885. DataSet.prototype._getColumnNames = function (dataTable) {
  1886. var columns = [];
  1887. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1888. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1889. }
  1890. return columns;
  1891. };
  1892. /**
  1893. * Append an item as a row to the dataTable
  1894. * @param dataTable
  1895. * @param columns
  1896. * @param item
  1897. * @private
  1898. */
  1899. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1900. var row = dataTable.addRow();
  1901. for (var col = 0, cols = columns.length; col < cols; col++) {
  1902. var field = columns[col];
  1903. dataTable.setValue(row, col, item[field]);
  1904. }
  1905. };
  1906. /**
  1907. * DataView
  1908. *
  1909. * a dataview offers a filtered view on a dataset or an other dataview.
  1910. *
  1911. * @param {DataSet | DataView} data
  1912. * @param {Object} [options] Available options: see method get
  1913. *
  1914. * @constructor DataView
  1915. */
  1916. function DataView (data, options) {
  1917. this.id = util.randomUUID();
  1918. this.data = null;
  1919. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1920. this.options = options || {};
  1921. this.fieldId = 'id'; // name of the field containing id
  1922. this.subscribers = {}; // event subscribers
  1923. var me = this;
  1924. this.listener = function () {
  1925. me._onEvent.apply(me, arguments);
  1926. };
  1927. this.setData(data);
  1928. }
  1929. // TODO: implement a function .config() to dynamically update things like configured filter
  1930. // and trigger changes accordingly
  1931. /**
  1932. * Set a data source for the view
  1933. * @param {DataSet | DataView} data
  1934. */
  1935. DataView.prototype.setData = function (data) {
  1936. var ids, dataItems, i, len;
  1937. if (this.data) {
  1938. // unsubscribe from current dataset
  1939. if (this.data.unsubscribe) {
  1940. this.data.unsubscribe('*', this.listener);
  1941. }
  1942. // trigger a remove of all items in memory
  1943. ids = [];
  1944. for (var id in this.ids) {
  1945. if (this.ids.hasOwnProperty(id)) {
  1946. ids.push(id);
  1947. }
  1948. }
  1949. this.ids = {};
  1950. this._trigger('remove', {items: ids});
  1951. }
  1952. this.data = data;
  1953. if (this.data) {
  1954. // update fieldId
  1955. this.fieldId = this.options.fieldId ||
  1956. (this.data && this.data.options && this.data.options.fieldId) ||
  1957. 'id';
  1958. // trigger an add of all added items
  1959. ids = this.data.getIds({filter: this.options && this.options.filter});
  1960. for (i = 0, len = ids.length; i < len; i++) {
  1961. id = ids[i];
  1962. this.ids[id] = true;
  1963. }
  1964. this._trigger('add', {items: ids});
  1965. // subscribe to new dataset
  1966. if (this.data.subscribe) {
  1967. this.data.subscribe('*', this.listener);
  1968. }
  1969. }
  1970. };
  1971. /**
  1972. * Get data from the data view
  1973. *
  1974. * Usage:
  1975. *
  1976. * get()
  1977. * get(options: Object)
  1978. * get(options: Object, data: Array | DataTable)
  1979. *
  1980. * get(id: Number)
  1981. * get(id: Number, options: Object)
  1982. * get(id: Number, options: Object, data: Array | DataTable)
  1983. *
  1984. * get(ids: Number[])
  1985. * get(ids: Number[], options: Object)
  1986. * get(ids: Number[], options: Object, data: Array | DataTable)
  1987. *
  1988. * Where:
  1989. *
  1990. * {Number | String} id The id of an item
  1991. * {Number[] | String{}} ids An array with ids of items
  1992. * {Object} options An Object with options. Available options:
  1993. * {String} [type] Type of data to be returned. Can
  1994. * be 'DataTable' or 'Array' (default)
  1995. * {Object.<String, String>} [convert]
  1996. * {String[]} [fields] field names to be returned
  1997. * {function} [filter] filter items
  1998. * {String | function} [order] Order the items by
  1999. * a field name or custom sort function.
  2000. * {Array | DataTable} [data] If provided, items will be appended to this
  2001. * array or table. Required in case of Google
  2002. * DataTable.
  2003. * @param args
  2004. */
  2005. DataView.prototype.get = function (args) {
  2006. var me = this;
  2007. // parse the arguments
  2008. var ids, options, data;
  2009. var firstType = util.getType(arguments[0]);
  2010. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2011. // get(id(s) [, options] [, data])
  2012. ids = arguments[0]; // can be a single id or an array with ids
  2013. options = arguments[1];
  2014. data = arguments[2];
  2015. }
  2016. else {
  2017. // get([, options] [, data])
  2018. options = arguments[0];
  2019. data = arguments[1];
  2020. }
  2021. // extend the options with the default options and provided options
  2022. var viewOptions = util.extend({}, this.options, options);
  2023. // create a combined filter method when needed
  2024. if (this.options.filter && options && options.filter) {
  2025. viewOptions.filter = function (item) {
  2026. return me.options.filter(item) && options.filter(item);
  2027. }
  2028. }
  2029. // build up the call to the linked data set
  2030. var getArguments = [];
  2031. if (ids != undefined) {
  2032. getArguments.push(ids);
  2033. }
  2034. getArguments.push(viewOptions);
  2035. getArguments.push(data);
  2036. return this.data && this.data.get.apply(this.data, getArguments);
  2037. };
  2038. /**
  2039. * Get ids of all items or from a filtered set of items.
  2040. * @param {Object} [options] An Object with options. Available options:
  2041. * {function} [filter] filter items
  2042. * {String | function} [order] Order the items by
  2043. * a field name or custom sort function.
  2044. * @return {Array} ids
  2045. */
  2046. DataView.prototype.getIds = function (options) {
  2047. var ids;
  2048. if (this.data) {
  2049. var defaultFilter = this.options.filter;
  2050. var filter;
  2051. if (options && options.filter) {
  2052. if (defaultFilter) {
  2053. filter = function (item) {
  2054. return defaultFilter(item) && options.filter(item);
  2055. }
  2056. }
  2057. else {
  2058. filter = options.filter;
  2059. }
  2060. }
  2061. else {
  2062. filter = defaultFilter;
  2063. }
  2064. ids = this.data.getIds({
  2065. filter: filter,
  2066. order: options && options.order
  2067. });
  2068. }
  2069. else {
  2070. ids = [];
  2071. }
  2072. return ids;
  2073. };
  2074. /**
  2075. * Event listener. Will propagate all events from the connected data set to
  2076. * the subscribers of the DataView, but will filter the items and only trigger
  2077. * when there are changes in the filtered data set.
  2078. * @param {String} event
  2079. * @param {Object | null} params
  2080. * @param {String} senderId
  2081. * @private
  2082. */
  2083. DataView.prototype._onEvent = function (event, params, senderId) {
  2084. var i, len, id, item,
  2085. ids = params && params.items,
  2086. data = this.data,
  2087. added = [],
  2088. updated = [],
  2089. removed = [];
  2090. if (ids && data) {
  2091. switch (event) {
  2092. case 'add':
  2093. // filter the ids of the added items
  2094. for (i = 0, len = ids.length; i < len; i++) {
  2095. id = ids[i];
  2096. item = this.get(id);
  2097. if (item) {
  2098. this.ids[id] = true;
  2099. added.push(id);
  2100. }
  2101. }
  2102. break;
  2103. case 'update':
  2104. // determine the event from the views viewpoint: an updated
  2105. // item can be added, updated, or removed from this view.
  2106. for (i = 0, len = ids.length; i < len; i++) {
  2107. id = ids[i];
  2108. item = this.get(id);
  2109. if (item) {
  2110. if (this.ids[id]) {
  2111. updated.push(id);
  2112. }
  2113. else {
  2114. this.ids[id] = true;
  2115. added.push(id);
  2116. }
  2117. }
  2118. else {
  2119. if (this.ids[id]) {
  2120. delete this.ids[id];
  2121. removed.push(id);
  2122. }
  2123. else {
  2124. // nothing interesting for me :-(
  2125. }
  2126. }
  2127. }
  2128. break;
  2129. case 'remove':
  2130. // filter the ids of the removed items
  2131. for (i = 0, len = ids.length; i < len; i++) {
  2132. id = ids[i];
  2133. if (this.ids[id]) {
  2134. delete this.ids[id];
  2135. removed.push(id);
  2136. }
  2137. }
  2138. break;
  2139. }
  2140. if (added.length) {
  2141. this._trigger('add', {items: added}, senderId);
  2142. }
  2143. if (updated.length) {
  2144. this._trigger('update', {items: updated}, senderId);
  2145. }
  2146. if (removed.length) {
  2147. this._trigger('remove', {items: removed}, senderId);
  2148. }
  2149. }
  2150. };
  2151. // copy subscription functionality from DataSet
  2152. DataView.prototype.subscribe = DataSet.prototype.subscribe;
  2153. DataView.prototype.unsubscribe = DataSet.prototype.unsubscribe;
  2154. DataView.prototype._trigger = DataSet.prototype._trigger;
  2155. /**
  2156. * @constructor TimeStep
  2157. * The class TimeStep is an iterator for dates. You provide a start date and an
  2158. * end date. The class itself determines the best scale (step size) based on the
  2159. * provided start Date, end Date, and minimumStep.
  2160. *
  2161. * If minimumStep is provided, the step size is chosen as close as possible
  2162. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2163. * provided, the scale is set to 1 DAY.
  2164. * The minimumStep should correspond with the onscreen size of about 6 characters
  2165. *
  2166. * Alternatively, you can set a scale by hand.
  2167. * After creation, you can initialize the class by executing first(). Then you
  2168. * can iterate from the start date to the end date via next(). You can check if
  2169. * the end date is reached with the function hasNext(). After each step, you can
  2170. * retrieve the current date via getCurrent().
  2171. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2172. * days, to years.
  2173. *
  2174. * Version: 1.2
  2175. *
  2176. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2177. * or new Date(2010, 9, 21, 23, 45, 00)
  2178. * @param {Date} [end] The end date
  2179. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2180. */
  2181. TimeStep = function(start, end, minimumStep) {
  2182. // variables
  2183. this.current = new Date();
  2184. this._start = new Date();
  2185. this._end = new Date();
  2186. this.autoScale = true;
  2187. this.scale = TimeStep.SCALE.DAY;
  2188. this.step = 1;
  2189. // initialize the range
  2190. this.setRange(start, end, minimumStep);
  2191. };
  2192. /// enum scale
  2193. TimeStep.SCALE = {
  2194. MILLISECOND: 1,
  2195. SECOND: 2,
  2196. MINUTE: 3,
  2197. HOUR: 4,
  2198. DAY: 5,
  2199. WEEKDAY: 6,
  2200. MONTH: 7,
  2201. YEAR: 8
  2202. };
  2203. /**
  2204. * Set a new range
  2205. * If minimumStep is provided, the step size is chosen as close as possible
  2206. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2207. * provided, the scale is set to 1 DAY.
  2208. * The minimumStep should correspond with the onscreen size of about 6 characters
  2209. * @param {Date} [start] The start date and time.
  2210. * @param {Date} [end] The end date and time.
  2211. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2212. */
  2213. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2214. if (!(start instanceof Date) || !(end instanceof Date)) {
  2215. throw "No legal start or end date in method setRange";
  2216. }
  2217. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2218. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2219. if (this.autoScale) {
  2220. this.setMinimumStep(minimumStep);
  2221. }
  2222. };
  2223. /**
  2224. * Set the range iterator to the start date.
  2225. */
  2226. TimeStep.prototype.first = function() {
  2227. this.current = new Date(this._start.valueOf());
  2228. this.roundToMinor();
  2229. };
  2230. /**
  2231. * Round the current date to the first minor date value
  2232. * This must be executed once when the current date is set to start Date
  2233. */
  2234. TimeStep.prototype.roundToMinor = function() {
  2235. // round to floor
  2236. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2237. //noinspection FallthroughInSwitchStatementJS
  2238. switch (this.scale) {
  2239. case TimeStep.SCALE.YEAR:
  2240. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2241. this.current.setMonth(0);
  2242. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2243. case TimeStep.SCALE.DAY: // intentional fall through
  2244. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2245. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2246. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2247. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2248. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2249. }
  2250. if (this.step != 1) {
  2251. // round down to the first minor value that is a multiple of the current step size
  2252. switch (this.scale) {
  2253. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2254. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2255. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2256. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2257. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2258. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2259. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2260. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2261. default: break;
  2262. }
  2263. }
  2264. };
  2265. /**
  2266. * Check if the there is a next step
  2267. * @return {boolean} true if the current date has not passed the end date
  2268. */
  2269. TimeStep.prototype.hasNext = function () {
  2270. return (this.current.valueOf() <= this._end.valueOf());
  2271. };
  2272. /**
  2273. * Do the next step
  2274. */
  2275. TimeStep.prototype.next = function() {
  2276. var prev = this.current.valueOf();
  2277. // Two cases, needed to prevent issues with switching daylight savings
  2278. // (end of March and end of October)
  2279. if (this.current.getMonth() < 6) {
  2280. switch (this.scale) {
  2281. case TimeStep.SCALE.MILLISECOND:
  2282. this.current = new Date(this.current.valueOf() + this.step); break;
  2283. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2284. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2285. case TimeStep.SCALE.HOUR:
  2286. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2287. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2288. var h = this.current.getHours();
  2289. this.current.setHours(h - (h % this.step));
  2290. break;
  2291. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2292. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2293. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2294. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2295. default: break;
  2296. }
  2297. }
  2298. else {
  2299. switch (this.scale) {
  2300. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2301. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2302. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2303. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2304. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2305. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2306. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2307. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2308. default: break;
  2309. }
  2310. }
  2311. if (this.step != 1) {
  2312. // round down to the correct major value
  2313. switch (this.scale) {
  2314. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2315. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2316. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2317. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2318. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2319. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2320. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2321. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2322. default: break;
  2323. }
  2324. }
  2325. // safety mechanism: if current time is still unchanged, move to the end
  2326. if (this.current.valueOf() == prev) {
  2327. this.current = new Date(this._end.valueOf());
  2328. }
  2329. };
  2330. /**
  2331. * Get the current datetime
  2332. * @return {Date} current The current date
  2333. */
  2334. TimeStep.prototype.getCurrent = function() {
  2335. return this.current;
  2336. };
  2337. /**
  2338. * Set a custom scale. Autoscaling will be disabled.
  2339. * For example setScale(SCALE.MINUTES, 5) will result
  2340. * in minor steps of 5 minutes, and major steps of an hour.
  2341. *
  2342. * @param {TimeStep.SCALE} newScale
  2343. * A scale. Choose from SCALE.MILLISECOND,
  2344. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2345. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2346. * SCALE.YEAR.
  2347. * @param {Number} newStep A step size, by default 1. Choose for
  2348. * example 1, 2, 5, or 10.
  2349. */
  2350. TimeStep.prototype.setScale = function(newScale, newStep) {
  2351. this.scale = newScale;
  2352. if (newStep > 0) {
  2353. this.step = newStep;
  2354. }
  2355. this.autoScale = false;
  2356. };
  2357. /**
  2358. * Enable or disable autoscaling
  2359. * @param {boolean} enable If true, autoascaling is set true
  2360. */
  2361. TimeStep.prototype.setAutoScale = function (enable) {
  2362. this.autoScale = enable;
  2363. };
  2364. /**
  2365. * Automatically determine the scale that bests fits the provided minimum step
  2366. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2367. */
  2368. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2369. if (minimumStep == undefined) {
  2370. return;
  2371. }
  2372. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2373. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2374. var stepDay = (1000 * 60 * 60 * 24);
  2375. var stepHour = (1000 * 60 * 60);
  2376. var stepMinute = (1000 * 60);
  2377. var stepSecond = (1000);
  2378. var stepMillisecond= (1);
  2379. // find the smallest step that is larger than the provided minimumStep
  2380. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2381. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2382. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2383. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2384. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2385. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2386. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2387. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2388. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2389. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2390. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2391. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2392. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2393. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2394. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2395. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2396. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2397. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2398. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2399. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2400. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2401. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2402. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2403. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2404. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2405. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2406. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2407. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2408. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2409. };
  2410. /**
  2411. * Snap a date to a rounded value. The snap intervals are dependent on the
  2412. * current scale and step.
  2413. * @param {Date} date the date to be snapped
  2414. */
  2415. TimeStep.prototype.snap = function(date) {
  2416. if (this.scale == TimeStep.SCALE.YEAR) {
  2417. var year = date.getFullYear() + Math.round(date.getMonth() / 12);
  2418. date.setFullYear(Math.round(year / this.step) * this.step);
  2419. date.setMonth(0);
  2420. date.setDate(0);
  2421. date.setHours(0);
  2422. date.setMinutes(0);
  2423. date.setSeconds(0);
  2424. date.setMilliseconds(0);
  2425. }
  2426. else if (this.scale == TimeStep.SCALE.MONTH) {
  2427. if (date.getDate() > 15) {
  2428. date.setDate(1);
  2429. date.setMonth(date.getMonth() + 1);
  2430. // important: first set Date to 1, after that change the month.
  2431. }
  2432. else {
  2433. date.setDate(1);
  2434. }
  2435. date.setHours(0);
  2436. date.setMinutes(0);
  2437. date.setSeconds(0);
  2438. date.setMilliseconds(0);
  2439. }
  2440. else if (this.scale == TimeStep.SCALE.DAY ||
  2441. this.scale == TimeStep.SCALE.WEEKDAY) {
  2442. //noinspection FallthroughInSwitchStatementJS
  2443. switch (this.step) {
  2444. case 5:
  2445. case 2:
  2446. date.setHours(Math.round(date.getHours() / 24) * 24); break;
  2447. default:
  2448. date.setHours(Math.round(date.getHours() / 12) * 12); break;
  2449. }
  2450. date.setMinutes(0);
  2451. date.setSeconds(0);
  2452. date.setMilliseconds(0);
  2453. }
  2454. else if (this.scale == TimeStep.SCALE.HOUR) {
  2455. switch (this.step) {
  2456. case 4:
  2457. date.setMinutes(Math.round(date.getMinutes() / 60) * 60); break;
  2458. default:
  2459. date.setMinutes(Math.round(date.getMinutes() / 30) * 30); break;
  2460. }
  2461. date.setSeconds(0);
  2462. date.setMilliseconds(0);
  2463. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2464. //noinspection FallthroughInSwitchStatementJS
  2465. switch (this.step) {
  2466. case 15:
  2467. case 10:
  2468. date.setMinutes(Math.round(date.getMinutes() / 5) * 5);
  2469. date.setSeconds(0);
  2470. break;
  2471. case 5:
  2472. date.setSeconds(Math.round(date.getSeconds() / 60) * 60); break;
  2473. default:
  2474. date.setSeconds(Math.round(date.getSeconds() / 30) * 30); break;
  2475. }
  2476. date.setMilliseconds(0);
  2477. }
  2478. else if (this.scale == TimeStep.SCALE.SECOND) {
  2479. //noinspection FallthroughInSwitchStatementJS
  2480. switch (this.step) {
  2481. case 15:
  2482. case 10:
  2483. date.setSeconds(Math.round(date.getSeconds() / 5) * 5);
  2484. date.setMilliseconds(0);
  2485. break;
  2486. case 5:
  2487. date.setMilliseconds(Math.round(date.getMilliseconds() / 1000) * 1000); break;
  2488. default:
  2489. date.setMilliseconds(Math.round(date.getMilliseconds() / 500) * 500); break;
  2490. }
  2491. }
  2492. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2493. var step = this.step > 5 ? this.step / 2 : 1;
  2494. date.setMilliseconds(Math.round(date.getMilliseconds() / step) * step);
  2495. }
  2496. };
  2497. /**
  2498. * Check if the current value is a major value (for example when the step
  2499. * is DAY, a major value is each first day of the MONTH)
  2500. * @return {boolean} true if current date is major, else false.
  2501. */
  2502. TimeStep.prototype.isMajor = function() {
  2503. switch (this.scale) {
  2504. case TimeStep.SCALE.MILLISECOND:
  2505. return (this.current.getMilliseconds() == 0);
  2506. case TimeStep.SCALE.SECOND:
  2507. return (this.current.getSeconds() == 0);
  2508. case TimeStep.SCALE.MINUTE:
  2509. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2510. // Note: this is no bug. Major label is equal for both minute and hour scale
  2511. case TimeStep.SCALE.HOUR:
  2512. return (this.current.getHours() == 0);
  2513. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2514. case TimeStep.SCALE.DAY:
  2515. return (this.current.getDate() == 1);
  2516. case TimeStep.SCALE.MONTH:
  2517. return (this.current.getMonth() == 0);
  2518. case TimeStep.SCALE.YEAR:
  2519. return false;
  2520. default:
  2521. return false;
  2522. }
  2523. };
  2524. /**
  2525. * Returns formatted text for the minor axislabel, depending on the current
  2526. * date and the scale. For example when scale is MINUTE, the current time is
  2527. * formatted as "hh:mm".
  2528. * @param {Date} [date] custom date. if not provided, current date is taken
  2529. */
  2530. TimeStep.prototype.getLabelMinor = function(date) {
  2531. if (date == undefined) {
  2532. date = this.current;
  2533. }
  2534. switch (this.scale) {
  2535. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2536. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2537. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2538. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2539. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2540. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2541. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2542. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2543. default: return '';
  2544. }
  2545. };
  2546. /**
  2547. * Returns formatted text for the major axis label, depending on the current
  2548. * date and the scale. For example when scale is MINUTE, the major scale is
  2549. * hours, and the hour will be formatted as "hh".
  2550. * @param {Date} [date] custom date. if not provided, current date is taken
  2551. */
  2552. TimeStep.prototype.getLabelMajor = function(date) {
  2553. if (date == undefined) {
  2554. date = this.current;
  2555. }
  2556. //noinspection FallthroughInSwitchStatementJS
  2557. switch (this.scale) {
  2558. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2559. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2560. case TimeStep.SCALE.MINUTE:
  2561. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2562. case TimeStep.SCALE.WEEKDAY:
  2563. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2564. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2565. case TimeStep.SCALE.YEAR: return '';
  2566. default: return '';
  2567. }
  2568. };
  2569. /**
  2570. * @constructor Stack
  2571. * Stacks items on top of each other.
  2572. * @param {ItemSet} parent
  2573. * @param {Object} [options]
  2574. */
  2575. function Stack (parent, options) {
  2576. this.parent = parent;
  2577. this.options = options || {};
  2578. this.defaultOptions = {
  2579. order: function (a, b) {
  2580. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  2581. // Order: ranges over non-ranges, ranged ordered by width, and
  2582. // lastly ordered by start.
  2583. if (a instanceof ItemRange) {
  2584. if (b instanceof ItemRange) {
  2585. var aInt = (a.data.end - a.data.start);
  2586. var bInt = (b.data.end - b.data.start);
  2587. return (aInt - bInt) || (a.data.start - b.data.start);
  2588. }
  2589. else {
  2590. return -1;
  2591. }
  2592. }
  2593. else {
  2594. if (b instanceof ItemRange) {
  2595. return 1;
  2596. }
  2597. else {
  2598. return (a.data.start - b.data.start);
  2599. }
  2600. }
  2601. },
  2602. margin: {
  2603. item: 10
  2604. }
  2605. };
  2606. this.ordered = []; // ordered items
  2607. }
  2608. /**
  2609. * Set options for the stack
  2610. * @param {Object} options Available options:
  2611. * {ItemSet} parent
  2612. * {Number} margin
  2613. * {function} order Stacking order
  2614. */
  2615. Stack.prototype.setOptions = function setOptions (options) {
  2616. util.extend(this.options, options);
  2617. // TODO: register on data changes at the connected parent itemset, and update the changed part only and immediately
  2618. };
  2619. /**
  2620. * Stack the items such that they don't overlap. The items will have a minimal
  2621. * distance equal to options.margin.item.
  2622. */
  2623. Stack.prototype.update = function update() {
  2624. this._order();
  2625. this._stack();
  2626. };
  2627. /**
  2628. * Order the items. The items are ordered by width first, and by left position
  2629. * second.
  2630. * If a custom order function has been provided via the options, then this will
  2631. * be used.
  2632. * @private
  2633. */
  2634. Stack.prototype._order = function _order () {
  2635. var items = this.parent.items;
  2636. if (!items) {
  2637. throw new Error('Cannot stack items: parent does not contain items');
  2638. }
  2639. // TODO: store the sorted items, to have less work later on
  2640. var ordered = [];
  2641. var index = 0;
  2642. // items is a map (no array)
  2643. util.forEach(items, function (item) {
  2644. if (item.visible) {
  2645. ordered[index] = item;
  2646. index++;
  2647. }
  2648. });
  2649. //if a customer stack order function exists, use it.
  2650. var order = this.options.order || this.defaultOptions.order;
  2651. if (!(typeof order === 'function')) {
  2652. throw new Error('Option order must be a function');
  2653. }
  2654. ordered.sort(order);
  2655. this.ordered = ordered;
  2656. };
  2657. /**
  2658. * Adjust vertical positions of the events such that they don't overlap each
  2659. * other.
  2660. * @private
  2661. */
  2662. Stack.prototype._stack = function _stack () {
  2663. var i,
  2664. iMax,
  2665. ordered = this.ordered,
  2666. options = this.options,
  2667. orientation = options.orientation || this.defaultOptions.orientation,
  2668. axisOnTop = (orientation == 'top'),
  2669. margin;
  2670. if (options.margin && options.margin.item !== undefined) {
  2671. margin = options.margin.item;
  2672. }
  2673. else {
  2674. margin = this.defaultOptions.margin.item
  2675. }
  2676. // calculate new, non-overlapping positions
  2677. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  2678. var item = ordered[i];
  2679. var collidingItem = null;
  2680. do {
  2681. // TODO: optimize checking for overlap. when there is a gap without items,
  2682. // you only need to check for items from the next item on, not from zero
  2683. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  2684. if (collidingItem != null) {
  2685. // There is a collision. Reposition the event above the colliding element
  2686. if (axisOnTop) {
  2687. item.top = collidingItem.top + collidingItem.height + margin;
  2688. }
  2689. else {
  2690. item.top = collidingItem.top - item.height - margin;
  2691. }
  2692. }
  2693. } while (collidingItem);
  2694. }
  2695. };
  2696. /**
  2697. * Check if the destiny position of given item overlaps with any
  2698. * of the other items from index itemStart to itemEnd.
  2699. * @param {Array} items Array with items
  2700. * @param {int} itemIndex Number of the item to be checked for overlap
  2701. * @param {int} itemStart First item to be checked.
  2702. * @param {int} itemEnd Last item to be checked.
  2703. * @return {Object | null} colliding item, or undefined when no collisions
  2704. * @param {Number} margin A minimum required margin.
  2705. * If margin is provided, the two items will be
  2706. * marked colliding when they overlap or
  2707. * when the margin between the two is smaller than
  2708. * the requested margin.
  2709. */
  2710. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  2711. itemStart, itemEnd, margin) {
  2712. var collision = this.collision;
  2713. // we loop from end to start, as we suppose that the chance of a
  2714. // collision is larger for items at the end, so check these first.
  2715. var a = items[itemIndex];
  2716. for (var i = itemEnd; i >= itemStart; i--) {
  2717. var b = items[i];
  2718. if (collision(a, b, margin)) {
  2719. if (i != itemIndex) {
  2720. return b;
  2721. }
  2722. }
  2723. }
  2724. return null;
  2725. };
  2726. /**
  2727. * Test if the two provided items collide
  2728. * The items must have parameters left, width, top, and height.
  2729. * @param {Component} a The first item
  2730. * @param {Component} b The second item
  2731. * @param {Number} margin A minimum required margin.
  2732. * If margin is provided, the two items will be
  2733. * marked colliding when they overlap or
  2734. * when the margin between the two is smaller than
  2735. * the requested margin.
  2736. * @return {boolean} true if a and b collide, else false
  2737. */
  2738. Stack.prototype.collision = function collision (a, b, margin) {
  2739. return ((a.left - margin) < (b.left + b.getWidth()) &&
  2740. (a.left + a.getWidth() + margin) > b.left &&
  2741. (a.top - margin) < (b.top + b.height) &&
  2742. (a.top + a.height + margin) > b.top);
  2743. };
  2744. /**
  2745. * @constructor Range
  2746. * A Range controls a numeric range with a start and end value.
  2747. * The Range adjusts the range based on mouse events or programmatic changes,
  2748. * and triggers events when the range is changing or has been changed.
  2749. * @param {Object} [options] See description at Range.setOptions
  2750. * @extends Controller
  2751. */
  2752. function Range(options) {
  2753. this.id = util.randomUUID();
  2754. this.start = null; // Number
  2755. this.end = null; // Number
  2756. this.options = options || {};
  2757. this.setOptions(options);
  2758. }
  2759. /**
  2760. * Set options for the range controller
  2761. * @param {Object} options Available options:
  2762. * {Number} min Minimum value for start
  2763. * {Number} max Maximum value for end
  2764. * {Number} zoomMin Set a minimum value for
  2765. * (end - start).
  2766. * {Number} zoomMax Set a maximum value for
  2767. * (end - start).
  2768. */
  2769. Range.prototype.setOptions = function (options) {
  2770. util.extend(this.options, options);
  2771. // re-apply range with new limitations
  2772. if (this.start !== null && this.end !== null) {
  2773. this.setRange(this.start, this.end);
  2774. }
  2775. };
  2776. /**
  2777. * Test whether direction has a valid value
  2778. * @param {String} direction 'horizontal' or 'vertical'
  2779. */
  2780. function validateDirection (direction) {
  2781. if (direction != 'horizontal' && direction != 'vertical') {
  2782. throw new TypeError('Unknown direction "' + direction + '". ' +
  2783. 'Choose "horizontal" or "vertical".');
  2784. }
  2785. }
  2786. /**
  2787. * Add listeners for mouse and touch events to the component
  2788. * @param {Component} component
  2789. * @param {String} event Available events: 'move', 'zoom'
  2790. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2791. */
  2792. Range.prototype.subscribe = function (component, event, direction) {
  2793. var me = this;
  2794. if (event == 'move') {
  2795. // drag start listener
  2796. component.on('dragstart', function (event) {
  2797. me._onDragStart(event, component);
  2798. });
  2799. // drag listener
  2800. component.on('drag', function (event) {
  2801. me._onDrag(event, component, direction);
  2802. });
  2803. // drag end listener
  2804. component.on('dragend', function (event) {
  2805. me._onDragEnd(event, component);
  2806. });
  2807. }
  2808. else if (event == 'zoom') {
  2809. // mouse wheel
  2810. function mousewheel (event) {
  2811. me._onMouseWheel(event, component, direction);
  2812. }
  2813. component.on('mousewheel', mousewheel);
  2814. component.on('DOMMouseScroll', mousewheel); // For FF
  2815. // pinch
  2816. component.on('touch', function (event) {
  2817. me._onTouch();
  2818. });
  2819. component.on('pinch', function (event) {
  2820. me._onPinch(event, component, direction);
  2821. });
  2822. }
  2823. else {
  2824. throw new TypeError('Unknown event "' + event + '". ' +
  2825. 'Choose "move" or "zoom".');
  2826. }
  2827. };
  2828. /**
  2829. * Add event listener
  2830. * @param {String} event Name of the event.
  2831. * Available events: 'rangechange', 'rangechanged'
  2832. * @param {function} callback Callback function, invoked as callback({start: Date, end: Date})
  2833. */
  2834. Range.prototype.on = function on (event, callback) {
  2835. var available = ['rangechange', 'rangechanged'];
  2836. if (available.indexOf(event) == -1) {
  2837. throw new Error('Unknown event "' + event + '". Choose from ' + available.join());
  2838. }
  2839. events.addListener(this, event, callback);
  2840. };
  2841. /**
  2842. * Remove an event listener
  2843. * @param {String} event name of the event
  2844. * @param {function} callback callback handler
  2845. */
  2846. Range.prototype.off = function off (event, callback) {
  2847. events.removeListener(this, event, callback);
  2848. };
  2849. /**
  2850. * Trigger an event
  2851. * @param {String} event name of the event, available events: 'rangechange',
  2852. * 'rangechanged'
  2853. * @private
  2854. */
  2855. Range.prototype._trigger = function (event) {
  2856. events.trigger(this, event, {
  2857. start: this.start,
  2858. end: this.end
  2859. });
  2860. };
  2861. /**
  2862. * Set a new start and end range
  2863. * @param {Number} [start]
  2864. * @param {Number} [end]
  2865. */
  2866. Range.prototype.setRange = function(start, end) {
  2867. var changed = this._applyRange(start, end);
  2868. if (changed) {
  2869. this._trigger('rangechange');
  2870. this._trigger('rangechanged');
  2871. }
  2872. };
  2873. /**
  2874. * Set a new start and end range. This method is the same as setRange, but
  2875. * does not trigger a range change and range changed event, and it returns
  2876. * true when the range is changed
  2877. * @param {Number} [start]
  2878. * @param {Number} [end]
  2879. * @return {Boolean} changed
  2880. * @private
  2881. */
  2882. Range.prototype._applyRange = function(start, end) {
  2883. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2884. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2885. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2886. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2887. diff;
  2888. // check for valid number
  2889. if (isNaN(newStart) || newStart === null) {
  2890. throw new Error('Invalid start "' + start + '"');
  2891. }
  2892. if (isNaN(newEnd) || newEnd === null) {
  2893. throw new Error('Invalid end "' + end + '"');
  2894. }
  2895. // prevent start < end
  2896. if (newEnd < newStart) {
  2897. newEnd = newStart;
  2898. }
  2899. // prevent start < min
  2900. if (min !== null) {
  2901. if (newStart < min) {
  2902. diff = (min - newStart);
  2903. newStart += diff;
  2904. newEnd += diff;
  2905. // prevent end > max
  2906. if (max != null) {
  2907. if (newEnd > max) {
  2908. newEnd = max;
  2909. }
  2910. }
  2911. }
  2912. }
  2913. // prevent end > max
  2914. if (max !== null) {
  2915. if (newEnd > max) {
  2916. diff = (newEnd - max);
  2917. newStart -= diff;
  2918. newEnd -= diff;
  2919. // prevent start < min
  2920. if (min != null) {
  2921. if (newStart < min) {
  2922. newStart = min;
  2923. }
  2924. }
  2925. }
  2926. }
  2927. // prevent (end-start) < zoomMin
  2928. if (this.options.zoomMin !== null) {
  2929. var zoomMin = parseFloat(this.options.zoomMin);
  2930. if (zoomMin < 0) {
  2931. zoomMin = 0;
  2932. }
  2933. if ((newEnd - newStart) < zoomMin) {
  2934. if ((this.end - this.start) === zoomMin) {
  2935. // ignore this action, we are already zoomed to the minimum
  2936. newStart = this.start;
  2937. newEnd = this.end;
  2938. }
  2939. else {
  2940. // zoom to the minimum
  2941. diff = (zoomMin - (newEnd - newStart));
  2942. newStart -= diff / 2;
  2943. newEnd += diff / 2;
  2944. }
  2945. }
  2946. }
  2947. // prevent (end-start) > zoomMax
  2948. if (this.options.zoomMax !== null) {
  2949. var zoomMax = parseFloat(this.options.zoomMax);
  2950. if (zoomMax < 0) {
  2951. zoomMax = 0;
  2952. }
  2953. if ((newEnd - newStart) > zoomMax) {
  2954. if ((this.end - this.start) === zoomMax) {
  2955. // ignore this action, we are already zoomed to the maximum
  2956. newStart = this.start;
  2957. newEnd = this.end;
  2958. }
  2959. else {
  2960. // zoom to the maximum
  2961. diff = ((newEnd - newStart) - zoomMax);
  2962. newStart += diff / 2;
  2963. newEnd -= diff / 2;
  2964. }
  2965. }
  2966. }
  2967. var changed = (this.start != newStart || this.end != newEnd);
  2968. this.start = newStart;
  2969. this.end = newEnd;
  2970. return changed;
  2971. };
  2972. /**
  2973. * Retrieve the current range.
  2974. * @return {Object} An object with start and end properties
  2975. */
  2976. Range.prototype.getRange = function() {
  2977. return {
  2978. start: this.start,
  2979. end: this.end
  2980. };
  2981. };
  2982. /**
  2983. * Calculate the conversion offset and scale for current range, based on
  2984. * the provided width
  2985. * @param {Number} width
  2986. * @returns {{offset: number, scale: number}} conversion
  2987. */
  2988. Range.prototype.conversion = function (width) {
  2989. return Range.conversion(this.start, this.end, width);
  2990. };
  2991. /**
  2992. * Static method to calculate the conversion offset and scale for a range,
  2993. * based on the provided start, end, and width
  2994. * @param {Number} start
  2995. * @param {Number} end
  2996. * @param {Number} width
  2997. * @returns {{offset: number, scale: number}} conversion
  2998. */
  2999. Range.conversion = function (start, end, width) {
  3000. if (width != 0 && (end - start != 0)) {
  3001. return {
  3002. offset: start,
  3003. scale: width / (end - start)
  3004. }
  3005. }
  3006. else {
  3007. return {
  3008. offset: 0,
  3009. scale: 1
  3010. };
  3011. }
  3012. };
  3013. // global (private) object to store drag params
  3014. var touchParams = {};
  3015. /**
  3016. * Start dragging horizontally or vertically
  3017. * @param {Event} event
  3018. * @param {Object} component
  3019. * @private
  3020. */
  3021. Range.prototype._onDragStart = function(event, component) {
  3022. // refuse to drag when we where pinching to prevent the timeline make a jump
  3023. // when releasing the fingers in opposite order from the touch screen
  3024. if (touchParams.pinching) return;
  3025. touchParams.start = this.start;
  3026. touchParams.end = this.end;
  3027. var frame = component.frame;
  3028. if (frame) {
  3029. frame.style.cursor = 'move';
  3030. }
  3031. };
  3032. /**
  3033. * Perform dragging operating.
  3034. * @param {Event} event
  3035. * @param {Component} component
  3036. * @param {String} direction 'horizontal' or 'vertical'
  3037. * @private
  3038. */
  3039. Range.prototype._onDrag = function (event, component, direction) {
  3040. validateDirection(direction);
  3041. // refuse to drag when we where pinching to prevent the timeline make a jump
  3042. // when releasing the fingers in opposite order from the touch screen
  3043. if (touchParams.pinching) return;
  3044. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  3045. interval = (touchParams.end - touchParams.start),
  3046. width = (direction == 'horizontal') ? component.width : component.height,
  3047. diffRange = -delta / width * interval;
  3048. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  3049. // fire a rangechange event
  3050. this._trigger('rangechange');
  3051. };
  3052. /**
  3053. * Stop dragging operating.
  3054. * @param {event} event
  3055. * @param {Component} component
  3056. * @private
  3057. */
  3058. Range.prototype._onDragEnd = function (event, component) {
  3059. // refuse to drag when we where pinching to prevent the timeline make a jump
  3060. // when releasing the fingers in opposite order from the touch screen
  3061. if (touchParams.pinching) return;
  3062. if (component.frame) {
  3063. component.frame.style.cursor = 'auto';
  3064. }
  3065. // fire a rangechanged event
  3066. this._trigger('rangechanged');
  3067. };
  3068. /**
  3069. * Event handler for mouse wheel event, used to zoom
  3070. * Code from http://adomas.org/javascript-mouse-wheel/
  3071. * @param {Event} event
  3072. * @param {Component} component
  3073. * @param {String} direction 'horizontal' or 'vertical'
  3074. * @private
  3075. */
  3076. Range.prototype._onMouseWheel = function(event, component, direction) {
  3077. validateDirection(direction);
  3078. // retrieve delta
  3079. var delta = 0;
  3080. if (event.wheelDelta) { /* IE/Opera. */
  3081. delta = event.wheelDelta / 120;
  3082. } else if (event.detail) { /* Mozilla case. */
  3083. // In Mozilla, sign of delta is different than in IE.
  3084. // Also, delta is multiple of 3.
  3085. delta = -event.detail / 3;
  3086. }
  3087. // If delta is nonzero, handle it.
  3088. // Basically, delta is now positive if wheel was scrolled up,
  3089. // and negative, if wheel was scrolled down.
  3090. if (delta) {
  3091. // perform the zoom action. Delta is normally 1 or -1
  3092. // adjust a negative delta such that zooming in with delta 0.1
  3093. // equals zooming out with a delta -0.1
  3094. var scale;
  3095. if (delta < 0) {
  3096. scale = 1 - (delta / 5);
  3097. }
  3098. else {
  3099. scale = 1 / (1 + (delta / 5)) ;
  3100. }
  3101. // calculate center, the date to zoom around
  3102. var gesture = util.fakeGesture(this, event),
  3103. pointer = getPointer(gesture.touches[0], component.frame),
  3104. pointerDate = this._pointerToDate(component, direction, pointer);
  3105. this.zoom(scale, pointerDate);
  3106. }
  3107. // Prevent default actions caused by mouse wheel
  3108. // (else the page and timeline both zoom and scroll)
  3109. util.preventDefault(event);
  3110. };
  3111. /**
  3112. * On start of a touch gesture, initialize scale to 1
  3113. * @private
  3114. */
  3115. Range.prototype._onTouch = function () {
  3116. touchParams.start = this.start;
  3117. touchParams.end = this.end;
  3118. touchParams.pinching = false;
  3119. touchParams.center = null;
  3120. };
  3121. /**
  3122. * Handle pinch event
  3123. * @param {Event} event
  3124. * @param {Component} component
  3125. * @param {String} direction 'horizontal' or 'vertical'
  3126. * @private
  3127. */
  3128. Range.prototype._onPinch = function (event, component, direction) {
  3129. touchParams.pinching = true;
  3130. if (event.gesture.touches.length > 1) {
  3131. if (!touchParams.center) {
  3132. touchParams.center = getPointer(event.gesture.center, component.frame);
  3133. }
  3134. var scale = 1 / event.gesture.scale,
  3135. initDate = this._pointerToDate(component, direction, touchParams.center),
  3136. center = getPointer(event.gesture.center, component.frame),
  3137. date = this._pointerToDate(component, direction, center),
  3138. delta = date - initDate; // TODO: utilize delta
  3139. // calculate new start and end
  3140. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3141. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3142. // apply new range
  3143. this.setRange(newStart, newEnd);
  3144. }
  3145. };
  3146. /**
  3147. * Helper function to calculate the center date for zooming
  3148. * @param {Component} component
  3149. * @param {{x: Number, y: Number}} pointer
  3150. * @param {String} direction 'horizontal' or 'vertical'
  3151. * @return {number} date
  3152. * @private
  3153. */
  3154. Range.prototype._pointerToDate = function (component, direction, pointer) {
  3155. var conversion;
  3156. if (direction == 'horizontal') {
  3157. var width = component.width;
  3158. conversion = this.conversion(width);
  3159. return pointer.x / conversion.scale + conversion.offset;
  3160. }
  3161. else {
  3162. var height = component.height;
  3163. conversion = this.conversion(height);
  3164. return pointer.y / conversion.scale + conversion.offset;
  3165. }
  3166. };
  3167. /**
  3168. * Get the pointer location relative to the location of the dom element
  3169. * @param {{pageX: Number, pageY: Number}} touch
  3170. * @param {Element} element HTML DOM element
  3171. * @return {{x: Number, y: Number}} pointer
  3172. * @private
  3173. */
  3174. function getPointer (touch, element) {
  3175. return {
  3176. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3177. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3178. };
  3179. }
  3180. /**
  3181. * Zoom the range the given scale in or out. Start and end date will
  3182. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3183. * date around which to zoom.
  3184. * For example, try scale = 0.9 or 1.1
  3185. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3186. * values below 1 will zoom in.
  3187. * @param {Number} [center] Value representing a date around which will
  3188. * be zoomed.
  3189. */
  3190. Range.prototype.zoom = function(scale, center) {
  3191. // if centerDate is not provided, take it half between start Date and end Date
  3192. if (center == null) {
  3193. center = (this.start + this.end) / 2;
  3194. }
  3195. // calculate new start and end
  3196. var newStart = center + (this.start - center) * scale;
  3197. var newEnd = center + (this.end - center) * scale;
  3198. this.setRange(newStart, newEnd);
  3199. };
  3200. /**
  3201. * Move the range with a given delta to the left or right. Start and end
  3202. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3203. * @param {Number} delta Moving amount. Positive value will move right,
  3204. * negative value will move left
  3205. */
  3206. Range.prototype.move = function(delta) {
  3207. // zoom start Date and end Date relative to the centerDate
  3208. var diff = (this.end - this.start);
  3209. // apply new values
  3210. var newStart = this.start + diff * delta;
  3211. var newEnd = this.end + diff * delta;
  3212. // TODO: reckon with min and max range
  3213. this.start = newStart;
  3214. this.end = newEnd;
  3215. };
  3216. /**
  3217. * Move the range to a new center point
  3218. * @param {Number} moveTo New center point of the range
  3219. */
  3220. Range.prototype.moveTo = function(moveTo) {
  3221. var center = (this.start + this.end) / 2;
  3222. var diff = center - moveTo;
  3223. // calculate new start and end
  3224. var newStart = this.start - diff;
  3225. var newEnd = this.end - diff;
  3226. this.setRange(newStart, newEnd);
  3227. };
  3228. /**
  3229. * @constructor Controller
  3230. *
  3231. * A Controller controls the reflows and repaints of all visual components
  3232. */
  3233. function Controller () {
  3234. this.id = util.randomUUID();
  3235. this.components = {};
  3236. this.repaintTimer = undefined;
  3237. this.reflowTimer = undefined;
  3238. }
  3239. /**
  3240. * Add a component to the controller
  3241. * @param {Component} component
  3242. */
  3243. Controller.prototype.add = function add(component) {
  3244. // validate the component
  3245. if (component.id == undefined) {
  3246. throw new Error('Component has no field id');
  3247. }
  3248. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3249. throw new TypeError('Component must be an instance of ' +
  3250. 'prototype Component or Controller');
  3251. }
  3252. // add the component
  3253. component.controller = this;
  3254. this.components[component.id] = component;
  3255. };
  3256. /**
  3257. * Remove a component from the controller
  3258. * @param {Component | String} component
  3259. */
  3260. Controller.prototype.remove = function remove(component) {
  3261. var id;
  3262. for (id in this.components) {
  3263. if (this.components.hasOwnProperty(id)) {
  3264. if (id == component || this.components[id] == component) {
  3265. break;
  3266. }
  3267. }
  3268. }
  3269. if (id) {
  3270. delete this.components[id];
  3271. }
  3272. };
  3273. /**
  3274. * Request a reflow. The controller will schedule a reflow
  3275. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3276. * is false.
  3277. */
  3278. Controller.prototype.requestReflow = function requestReflow(force) {
  3279. if (force) {
  3280. this.reflow();
  3281. }
  3282. else {
  3283. if (!this.reflowTimer) {
  3284. var me = this;
  3285. this.reflowTimer = setTimeout(function () {
  3286. me.reflowTimer = undefined;
  3287. me.reflow();
  3288. }, 0);
  3289. }
  3290. }
  3291. };
  3292. /**
  3293. * Request a repaint. The controller will schedule a repaint
  3294. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3295. * is false.
  3296. */
  3297. Controller.prototype.requestRepaint = function requestRepaint(force) {
  3298. if (force) {
  3299. this.repaint();
  3300. }
  3301. else {
  3302. if (!this.repaintTimer) {
  3303. var me = this;
  3304. this.repaintTimer = setTimeout(function () {
  3305. me.repaintTimer = undefined;
  3306. me.repaint();
  3307. }, 0);
  3308. }
  3309. }
  3310. };
  3311. /**
  3312. * Repaint all components
  3313. */
  3314. Controller.prototype.repaint = function repaint() {
  3315. var changed = false;
  3316. // cancel any running repaint request
  3317. if (this.repaintTimer) {
  3318. clearTimeout(this.repaintTimer);
  3319. this.repaintTimer = undefined;
  3320. }
  3321. var done = {};
  3322. function repaint(component, id) {
  3323. if (!(id in done)) {
  3324. // first repaint the components on which this component is dependent
  3325. if (component.depends) {
  3326. component.depends.forEach(function (dep) {
  3327. repaint(dep, dep.id);
  3328. });
  3329. }
  3330. if (component.parent) {
  3331. repaint(component.parent, component.parent.id);
  3332. }
  3333. // repaint the component itself and mark as done
  3334. changed = component.repaint() || changed;
  3335. done[id] = true;
  3336. }
  3337. }
  3338. util.forEach(this.components, repaint);
  3339. // immediately reflow when needed
  3340. if (changed) {
  3341. this.reflow();
  3342. }
  3343. // TODO: limit the number of nested reflows/repaints, prevent loop
  3344. };
  3345. /**
  3346. * Reflow all components
  3347. */
  3348. Controller.prototype.reflow = function reflow() {
  3349. var resized = false;
  3350. // cancel any running repaint request
  3351. if (this.reflowTimer) {
  3352. clearTimeout(this.reflowTimer);
  3353. this.reflowTimer = undefined;
  3354. }
  3355. var done = {};
  3356. function reflow(component, id) {
  3357. if (!(id in done)) {
  3358. // first reflow the components on which this component is dependent
  3359. if (component.depends) {
  3360. component.depends.forEach(function (dep) {
  3361. reflow(dep, dep.id);
  3362. });
  3363. }
  3364. if (component.parent) {
  3365. reflow(component.parent, component.parent.id);
  3366. }
  3367. // reflow the component itself and mark as done
  3368. resized = component.reflow() || resized;
  3369. done[id] = true;
  3370. }
  3371. }
  3372. util.forEach(this.components, reflow);
  3373. // immediately repaint when needed
  3374. if (resized) {
  3375. this.repaint();
  3376. }
  3377. // TODO: limit the number of nested reflows/repaints, prevent loop
  3378. };
  3379. /**
  3380. * Prototype for visual components
  3381. */
  3382. function Component () {
  3383. this.id = null;
  3384. this.parent = null;
  3385. this.depends = null;
  3386. this.controller = null;
  3387. this.options = null;
  3388. this.frame = null; // main DOM element
  3389. this.top = 0;
  3390. this.left = 0;
  3391. this.width = 0;
  3392. this.height = 0;
  3393. }
  3394. /**
  3395. * Set parameters for the frame. Parameters will be merged in current parameter
  3396. * set.
  3397. * @param {Object} options Available parameters:
  3398. * {String | function} [className]
  3399. * {EventBus} [eventBus]
  3400. * {String | Number | function} [left]
  3401. * {String | Number | function} [top]
  3402. * {String | Number | function} [width]
  3403. * {String | Number | function} [height]
  3404. */
  3405. Component.prototype.setOptions = function setOptions(options) {
  3406. if (options) {
  3407. util.extend(this.options, options);
  3408. if (this.controller) {
  3409. this.requestRepaint();
  3410. this.requestReflow();
  3411. }
  3412. }
  3413. };
  3414. /**
  3415. * Get an option value by name
  3416. * The function will first check this.options object, and else will check
  3417. * this.defaultOptions.
  3418. * @param {String} name
  3419. * @return {*} value
  3420. */
  3421. Component.prototype.getOption = function getOption(name) {
  3422. var value;
  3423. if (this.options) {
  3424. value = this.options[name];
  3425. }
  3426. if (value === undefined && this.defaultOptions) {
  3427. value = this.defaultOptions[name];
  3428. }
  3429. return value;
  3430. };
  3431. /**
  3432. * Get the container element of the component, which can be used by a child to
  3433. * add its own widgets. Not all components do have a container for childs, in
  3434. * that case null is returned.
  3435. * @returns {HTMLElement | null} container
  3436. */
  3437. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3438. Component.prototype.getContainer = function getContainer() {
  3439. // should be implemented by the component
  3440. return null;
  3441. };
  3442. /**
  3443. * Get the frame element of the component, the outer HTML DOM element.
  3444. * @returns {HTMLElement | null} frame
  3445. */
  3446. Component.prototype.getFrame = function getFrame() {
  3447. return this.frame;
  3448. };
  3449. /**
  3450. * Repaint the component
  3451. * @return {Boolean} changed
  3452. */
  3453. Component.prototype.repaint = function repaint() {
  3454. // should be implemented by the component
  3455. return false;
  3456. };
  3457. /**
  3458. * Reflow the component
  3459. * @return {Boolean} resized
  3460. */
  3461. Component.prototype.reflow = function reflow() {
  3462. // should be implemented by the component
  3463. return false;
  3464. };
  3465. /**
  3466. * Hide the component from the DOM
  3467. * @return {Boolean} changed
  3468. */
  3469. Component.prototype.hide = function hide() {
  3470. if (this.frame && this.frame.parentNode) {
  3471. this.frame.parentNode.removeChild(this.frame);
  3472. return true;
  3473. }
  3474. else {
  3475. return false;
  3476. }
  3477. };
  3478. /**
  3479. * Show the component in the DOM (when not already visible).
  3480. * A repaint will be executed when the component is not visible
  3481. * @return {Boolean} changed
  3482. */
  3483. Component.prototype.show = function show() {
  3484. if (!this.frame || !this.frame.parentNode) {
  3485. return this.repaint();
  3486. }
  3487. else {
  3488. return false;
  3489. }
  3490. };
  3491. /**
  3492. * Request a repaint. The controller will schedule a repaint
  3493. */
  3494. Component.prototype.requestRepaint = function requestRepaint() {
  3495. if (this.controller) {
  3496. this.controller.requestRepaint();
  3497. }
  3498. else {
  3499. throw new Error('Cannot request a repaint: no controller configured');
  3500. // TODO: just do a repaint when no parent is configured?
  3501. }
  3502. };
  3503. /**
  3504. * Request a reflow. The controller will schedule a reflow
  3505. */
  3506. Component.prototype.requestReflow = function requestReflow() {
  3507. if (this.controller) {
  3508. this.controller.requestReflow();
  3509. }
  3510. else {
  3511. throw new Error('Cannot request a reflow: no controller configured');
  3512. // TODO: just do a reflow when no parent is configured?
  3513. }
  3514. };
  3515. /**
  3516. * A panel can contain components
  3517. * @param {Component} [parent]
  3518. * @param {Component[]} [depends] Components on which this components depends
  3519. * (except for the parent)
  3520. * @param {Object} [options] Available parameters:
  3521. * {String | Number | function} [left]
  3522. * {String | Number | function} [top]
  3523. * {String | Number | function} [width]
  3524. * {String | Number | function} [height]
  3525. * {String | function} [className]
  3526. * @constructor Panel
  3527. * @extends Component
  3528. */
  3529. function Panel(parent, depends, options) {
  3530. this.id = util.randomUUID();
  3531. this.parent = parent;
  3532. this.depends = depends;
  3533. this.options = options || {};
  3534. }
  3535. Panel.prototype = new Component();
  3536. /**
  3537. * Set options. Will extend the current options.
  3538. * @param {Object} [options] Available parameters:
  3539. * {String | function} [className]
  3540. * {String | Number | function} [left]
  3541. * {String | Number | function} [top]
  3542. * {String | Number | function} [width]
  3543. * {String | Number | function} [height]
  3544. */
  3545. Panel.prototype.setOptions = Component.prototype.setOptions;
  3546. /**
  3547. * Get the container element of the panel, which can be used by a child to
  3548. * add its own widgets.
  3549. * @returns {HTMLElement} container
  3550. */
  3551. Panel.prototype.getContainer = function () {
  3552. return this.frame;
  3553. };
  3554. /**
  3555. * Repaint the component
  3556. * @return {Boolean} changed
  3557. */
  3558. Panel.prototype.repaint = function () {
  3559. var changed = 0,
  3560. update = util.updateProperty,
  3561. asSize = util.option.asSize,
  3562. options = this.options,
  3563. frame = this.frame;
  3564. if (!frame) {
  3565. frame = document.createElement('div');
  3566. frame.className = 'panel';
  3567. var className = options.className;
  3568. if (className) {
  3569. if (typeof className == 'function') {
  3570. util.addClassName(frame, String(className()));
  3571. }
  3572. else {
  3573. util.addClassName(frame, String(className));
  3574. }
  3575. }
  3576. this.frame = frame;
  3577. changed += 1;
  3578. }
  3579. if (!frame.parentNode) {
  3580. if (!this.parent) {
  3581. throw new Error('Cannot repaint panel: no parent attached');
  3582. }
  3583. var parentContainer = this.parent.getContainer();
  3584. if (!parentContainer) {
  3585. throw new Error('Cannot repaint panel: parent has no container element');
  3586. }
  3587. parentContainer.appendChild(frame);
  3588. changed += 1;
  3589. }
  3590. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3591. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3592. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3593. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3594. return (changed > 0);
  3595. };
  3596. /**
  3597. * Reflow the component
  3598. * @return {Boolean} resized
  3599. */
  3600. Panel.prototype.reflow = function () {
  3601. var changed = 0,
  3602. update = util.updateProperty,
  3603. frame = this.frame;
  3604. if (frame) {
  3605. changed += update(this, 'top', frame.offsetTop);
  3606. changed += update(this, 'left', frame.offsetLeft);
  3607. changed += update(this, 'width', frame.offsetWidth);
  3608. changed += update(this, 'height', frame.offsetHeight);
  3609. }
  3610. else {
  3611. changed += 1;
  3612. }
  3613. return (changed > 0);
  3614. };
  3615. /**
  3616. * A root panel can hold components. The root panel must be initialized with
  3617. * a DOM element as container.
  3618. * @param {HTMLElement} container
  3619. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3620. * @constructor RootPanel
  3621. * @extends Panel
  3622. */
  3623. function RootPanel(container, options) {
  3624. this.id = util.randomUUID();
  3625. this.container = container;
  3626. this.options = options || {};
  3627. this.defaultOptions = {
  3628. autoResize: true
  3629. };
  3630. this.listeners = {}; // event listeners
  3631. }
  3632. RootPanel.prototype = new Panel();
  3633. /**
  3634. * Set options. Will extend the current options.
  3635. * @param {Object} [options] Available parameters:
  3636. * {String | function} [className]
  3637. * {String | Number | function} [left]
  3638. * {String | Number | function} [top]
  3639. * {String | Number | function} [width]
  3640. * {String | Number | function} [height]
  3641. * {Boolean | function} [autoResize]
  3642. */
  3643. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3644. /**
  3645. * Repaint the component
  3646. * @return {Boolean} changed
  3647. */
  3648. RootPanel.prototype.repaint = function () {
  3649. var changed = 0,
  3650. update = util.updateProperty,
  3651. asSize = util.option.asSize,
  3652. options = this.options,
  3653. frame = this.frame;
  3654. if (!frame) {
  3655. frame = document.createElement('div');
  3656. this.frame = frame;
  3657. changed += 1;
  3658. }
  3659. if (!frame.parentNode) {
  3660. if (!this.container) {
  3661. throw new Error('Cannot repaint root panel: no container attached');
  3662. }
  3663. this.container.appendChild(frame);
  3664. changed += 1;
  3665. }
  3666. frame.className = 'vis timeline rootpanel ' + options.orientation;
  3667. var className = options.className;
  3668. if (className) {
  3669. util.addClassName(frame, util.option.asString(className));
  3670. }
  3671. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3672. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3673. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3674. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3675. this._updateEventEmitters();
  3676. this._updateWatch();
  3677. return (changed > 0);
  3678. };
  3679. /**
  3680. * Reflow the component
  3681. * @return {Boolean} resized
  3682. */
  3683. RootPanel.prototype.reflow = function () {
  3684. var changed = 0,
  3685. update = util.updateProperty,
  3686. frame = this.frame;
  3687. if (frame) {
  3688. changed += update(this, 'top', frame.offsetTop);
  3689. changed += update(this, 'left', frame.offsetLeft);
  3690. changed += update(this, 'width', frame.offsetWidth);
  3691. changed += update(this, 'height', frame.offsetHeight);
  3692. }
  3693. else {
  3694. changed += 1;
  3695. }
  3696. return (changed > 0);
  3697. };
  3698. /**
  3699. * Update watching for resize, depending on the current option
  3700. * @private
  3701. */
  3702. RootPanel.prototype._updateWatch = function () {
  3703. var autoResize = this.getOption('autoResize');
  3704. if (autoResize) {
  3705. this._watch();
  3706. }
  3707. else {
  3708. this._unwatch();
  3709. }
  3710. };
  3711. /**
  3712. * Watch for changes in the size of the frame. On resize, the Panel will
  3713. * automatically redraw itself.
  3714. * @private
  3715. */
  3716. RootPanel.prototype._watch = function () {
  3717. var me = this;
  3718. this._unwatch();
  3719. var checkSize = function () {
  3720. var autoResize = me.getOption('autoResize');
  3721. if (!autoResize) {
  3722. // stop watching when the option autoResize is changed to false
  3723. me._unwatch();
  3724. return;
  3725. }
  3726. if (me.frame) {
  3727. // check whether the frame is resized
  3728. if ((me.frame.clientWidth != me.width) ||
  3729. (me.frame.clientHeight != me.height)) {
  3730. me.requestReflow();
  3731. }
  3732. }
  3733. };
  3734. // TODO: automatically cleanup the event listener when the frame is deleted
  3735. util.addEventListener(window, 'resize', checkSize);
  3736. this.watchTimer = setInterval(checkSize, 1000);
  3737. };
  3738. /**
  3739. * Stop watching for a resize of the frame.
  3740. * @private
  3741. */
  3742. RootPanel.prototype._unwatch = function () {
  3743. if (this.watchTimer) {
  3744. clearInterval(this.watchTimer);
  3745. this.watchTimer = undefined;
  3746. }
  3747. // TODO: remove event listener on window.resize
  3748. };
  3749. /**
  3750. * Event handler
  3751. * @param {String} event name of the event, for example 'click', 'mousemove'
  3752. * @param {function} callback callback handler, invoked with the raw HTML Event
  3753. * as parameter.
  3754. */
  3755. RootPanel.prototype.on = function (event, callback) {
  3756. // register the listener at this component
  3757. var arr = this.listeners[event];
  3758. if (!arr) {
  3759. arr = [];
  3760. this.listeners[event] = arr;
  3761. }
  3762. arr.push(callback);
  3763. this._updateEventEmitters();
  3764. };
  3765. /**
  3766. * Update the event listeners for all event emitters
  3767. * @private
  3768. */
  3769. RootPanel.prototype._updateEventEmitters = function () {
  3770. if (this.listeners) {
  3771. var me = this;
  3772. util.forEach(this.listeners, function (listeners, event) {
  3773. if (!me.emitters) {
  3774. me.emitters = {};
  3775. }
  3776. if (!(event in me.emitters)) {
  3777. // create event
  3778. var frame = me.frame;
  3779. if (frame) {
  3780. //console.log('Created a listener for event ' + event + ' on component ' + me.id); // TODO: cleanup logging
  3781. var callback = function(event) {
  3782. listeners.forEach(function (listener) {
  3783. // TODO: filter on event target!
  3784. listener(event);
  3785. });
  3786. };
  3787. me.emitters[event] = callback;
  3788. if (!me.hammer) {
  3789. me.hammer = Hammer(frame, {
  3790. prevent_default: true
  3791. });
  3792. }
  3793. me.hammer.on(event, callback);
  3794. }
  3795. }
  3796. });
  3797. // TODO: be able to delete event listeners
  3798. // TODO: be able to move event listeners to a parent when available
  3799. }
  3800. };
  3801. /**
  3802. * A horizontal time axis
  3803. * @param {Component} parent
  3804. * @param {Component[]} [depends] Components on which this components depends
  3805. * (except for the parent)
  3806. * @param {Object} [options] See TimeAxis.setOptions for the available
  3807. * options.
  3808. * @constructor TimeAxis
  3809. * @extends Component
  3810. */
  3811. function TimeAxis (parent, depends, options) {
  3812. this.id = util.randomUUID();
  3813. this.parent = parent;
  3814. this.depends = depends;
  3815. this.dom = {
  3816. majorLines: [],
  3817. majorTexts: [],
  3818. minorLines: [],
  3819. minorTexts: [],
  3820. redundant: {
  3821. majorLines: [],
  3822. majorTexts: [],
  3823. minorLines: [],
  3824. minorTexts: []
  3825. }
  3826. };
  3827. this.props = {
  3828. range: {
  3829. start: 0,
  3830. end: 0,
  3831. minimumStep: 0
  3832. },
  3833. lineTop: 0
  3834. };
  3835. this.options = options || {};
  3836. this.defaultOptions = {
  3837. orientation: 'bottom', // supported: 'top', 'bottom'
  3838. // TODO: implement timeaxis orientations 'left' and 'right'
  3839. showMinorLabels: true,
  3840. showMajorLabels: true
  3841. };
  3842. this.conversion = null;
  3843. this.range = null;
  3844. }
  3845. TimeAxis.prototype = new Component();
  3846. // TODO: comment options
  3847. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3848. /**
  3849. * Set a range (start and end)
  3850. * @param {Range | Object} range A Range or an object containing start and end.
  3851. */
  3852. TimeAxis.prototype.setRange = function (range) {
  3853. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3854. throw new TypeError('Range must be an instance of Range, ' +
  3855. 'or an object containing start and end.');
  3856. }
  3857. this.range = range;
  3858. };
  3859. /**
  3860. * Convert a position on screen (pixels) to a datetime
  3861. * @param {int} x Position on the screen in pixels
  3862. * @return {Date} time The datetime the corresponds with given position x
  3863. */
  3864. TimeAxis.prototype.toTime = function(x) {
  3865. var conversion = this.conversion;
  3866. return new Date(x / conversion.scale + conversion.offset);
  3867. };
  3868. /**
  3869. * Convert a datetime (Date object) into a position on the screen
  3870. * @param {Date} time A date
  3871. * @return {int} x The position on the screen in pixels which corresponds
  3872. * with the given date.
  3873. * @private
  3874. */
  3875. TimeAxis.prototype.toScreen = function(time) {
  3876. var conversion = this.conversion;
  3877. return (time.valueOf() - conversion.offset) * conversion.scale;
  3878. };
  3879. /**
  3880. * Repaint the component
  3881. * @return {Boolean} changed
  3882. */
  3883. TimeAxis.prototype.repaint = function () {
  3884. var changed = 0,
  3885. update = util.updateProperty,
  3886. asSize = util.option.asSize,
  3887. options = this.options,
  3888. orientation = this.getOption('orientation'),
  3889. props = this.props,
  3890. step = this.step;
  3891. var frame = this.frame;
  3892. if (!frame) {
  3893. frame = document.createElement('div');
  3894. this.frame = frame;
  3895. changed += 1;
  3896. }
  3897. frame.className = 'axis';
  3898. // TODO: custom className?
  3899. if (!frame.parentNode) {
  3900. if (!this.parent) {
  3901. throw new Error('Cannot repaint time axis: no parent attached');
  3902. }
  3903. var parentContainer = this.parent.getContainer();
  3904. if (!parentContainer) {
  3905. throw new Error('Cannot repaint time axis: parent has no container element');
  3906. }
  3907. parentContainer.appendChild(frame);
  3908. changed += 1;
  3909. }
  3910. var parent = frame.parentNode;
  3911. if (parent) {
  3912. var beforeChild = frame.nextSibling;
  3913. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3914. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3915. (this.props.parentHeight - this.height) + 'px' :
  3916. '0px';
  3917. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3918. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3919. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3920. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3921. // get characters width and height
  3922. this._repaintMeasureChars();
  3923. if (this.step) {
  3924. this._repaintStart();
  3925. step.first();
  3926. var xFirstMajorLabel = undefined;
  3927. var max = 0;
  3928. while (step.hasNext() && max < 1000) {
  3929. max++;
  3930. var cur = step.getCurrent(),
  3931. x = this.toScreen(cur),
  3932. isMajor = step.isMajor();
  3933. // TODO: lines must have a width, such that we can create css backgrounds
  3934. if (this.getOption('showMinorLabels')) {
  3935. this._repaintMinorText(x, step.getLabelMinor());
  3936. }
  3937. if (isMajor && this.getOption('showMajorLabels')) {
  3938. if (x > 0) {
  3939. if (xFirstMajorLabel == undefined) {
  3940. xFirstMajorLabel = x;
  3941. }
  3942. this._repaintMajorText(x, step.getLabelMajor());
  3943. }
  3944. this._repaintMajorLine(x);
  3945. }
  3946. else {
  3947. this._repaintMinorLine(x);
  3948. }
  3949. step.next();
  3950. }
  3951. // create a major label on the left when needed
  3952. if (this.getOption('showMajorLabels')) {
  3953. var leftTime = this.toTime(0),
  3954. leftText = step.getLabelMajor(leftTime),
  3955. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3956. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3957. this._repaintMajorText(0, leftText);
  3958. }
  3959. }
  3960. this._repaintEnd();
  3961. }
  3962. this._repaintLine();
  3963. // put frame online again
  3964. if (beforeChild) {
  3965. parent.insertBefore(frame, beforeChild);
  3966. }
  3967. else {
  3968. parent.appendChild(frame)
  3969. }
  3970. }
  3971. return (changed > 0);
  3972. };
  3973. /**
  3974. * Start a repaint. Move all DOM elements to a redundant list, where they
  3975. * can be picked for re-use, or can be cleaned up in the end
  3976. * @private
  3977. */
  3978. TimeAxis.prototype._repaintStart = function () {
  3979. var dom = this.dom,
  3980. redundant = dom.redundant;
  3981. redundant.majorLines = dom.majorLines;
  3982. redundant.majorTexts = dom.majorTexts;
  3983. redundant.minorLines = dom.minorLines;
  3984. redundant.minorTexts = dom.minorTexts;
  3985. dom.majorLines = [];
  3986. dom.majorTexts = [];
  3987. dom.minorLines = [];
  3988. dom.minorTexts = [];
  3989. };
  3990. /**
  3991. * End a repaint. Cleanup leftover DOM elements in the redundant list
  3992. * @private
  3993. */
  3994. TimeAxis.prototype._repaintEnd = function () {
  3995. util.forEach(this.dom.redundant, function (arr) {
  3996. while (arr.length) {
  3997. var elem = arr.pop();
  3998. if (elem && elem.parentNode) {
  3999. elem.parentNode.removeChild(elem);
  4000. }
  4001. }
  4002. });
  4003. };
  4004. /**
  4005. * Create a minor label for the axis at position x
  4006. * @param {Number} x
  4007. * @param {String} text
  4008. * @private
  4009. */
  4010. TimeAxis.prototype._repaintMinorText = function (x, text) {
  4011. // reuse redundant label
  4012. var label = this.dom.redundant.minorTexts.shift();
  4013. if (!label) {
  4014. // create new label
  4015. var content = document.createTextNode('');
  4016. label = document.createElement('div');
  4017. label.appendChild(content);
  4018. label.className = 'text minor';
  4019. this.frame.appendChild(label);
  4020. }
  4021. this.dom.minorTexts.push(label);
  4022. label.childNodes[0].nodeValue = text;
  4023. label.style.left = x + 'px';
  4024. label.style.top = this.props.minorLabelTop + 'px';
  4025. //label.title = title; // TODO: this is a heavy operation
  4026. };
  4027. /**
  4028. * Create a Major label for the axis at position x
  4029. * @param {Number} x
  4030. * @param {String} text
  4031. * @private
  4032. */
  4033. TimeAxis.prototype._repaintMajorText = function (x, text) {
  4034. // reuse redundant label
  4035. var label = this.dom.redundant.majorTexts.shift();
  4036. if (!label) {
  4037. // create label
  4038. var content = document.createTextNode(text);
  4039. label = document.createElement('div');
  4040. label.className = 'text major';
  4041. label.appendChild(content);
  4042. this.frame.appendChild(label);
  4043. }
  4044. this.dom.majorTexts.push(label);
  4045. label.childNodes[0].nodeValue = text;
  4046. label.style.top = this.props.majorLabelTop + 'px';
  4047. label.style.left = x + 'px';
  4048. //label.title = title; // TODO: this is a heavy operation
  4049. };
  4050. /**
  4051. * Create a minor line for the axis at position x
  4052. * @param {Number} x
  4053. * @private
  4054. */
  4055. TimeAxis.prototype._repaintMinorLine = function (x) {
  4056. // reuse redundant line
  4057. var line = this.dom.redundant.minorLines.shift();
  4058. if (!line) {
  4059. // create vertical line
  4060. line = document.createElement('div');
  4061. line.className = 'grid vertical minor';
  4062. this.frame.appendChild(line);
  4063. }
  4064. this.dom.minorLines.push(line);
  4065. var props = this.props;
  4066. line.style.top = props.minorLineTop + 'px';
  4067. line.style.height = props.minorLineHeight + 'px';
  4068. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  4069. };
  4070. /**
  4071. * Create a Major line for the axis at position x
  4072. * @param {Number} x
  4073. * @private
  4074. */
  4075. TimeAxis.prototype._repaintMajorLine = function (x) {
  4076. // reuse redundant line
  4077. var line = this.dom.redundant.majorLines.shift();
  4078. if (!line) {
  4079. // create vertical line
  4080. line = document.createElement('DIV');
  4081. line.className = 'grid vertical major';
  4082. this.frame.appendChild(line);
  4083. }
  4084. this.dom.majorLines.push(line);
  4085. var props = this.props;
  4086. line.style.top = props.majorLineTop + 'px';
  4087. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4088. line.style.height = props.majorLineHeight + 'px';
  4089. };
  4090. /**
  4091. * Repaint the horizontal line for the axis
  4092. * @private
  4093. */
  4094. TimeAxis.prototype._repaintLine = function() {
  4095. var line = this.dom.line,
  4096. frame = this.frame,
  4097. options = this.options;
  4098. // line before all axis elements
  4099. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4100. if (line) {
  4101. // put this line at the end of all childs
  4102. frame.removeChild(line);
  4103. frame.appendChild(line);
  4104. }
  4105. else {
  4106. // create the axis line
  4107. line = document.createElement('div');
  4108. line.className = 'grid horizontal major';
  4109. frame.appendChild(line);
  4110. this.dom.line = line;
  4111. }
  4112. line.style.top = this.props.lineTop + 'px';
  4113. }
  4114. else {
  4115. if (line && line.parentElement) {
  4116. frame.removeChild(line.line);
  4117. delete this.dom.line;
  4118. }
  4119. }
  4120. };
  4121. /**
  4122. * Create characters used to determine the size of text on the axis
  4123. * @private
  4124. */
  4125. TimeAxis.prototype._repaintMeasureChars = function () {
  4126. // calculate the width and height of a single character
  4127. // this is used to calculate the step size, and also the positioning of the
  4128. // axis
  4129. var dom = this.dom,
  4130. text;
  4131. if (!dom.measureCharMinor) {
  4132. text = document.createTextNode('0');
  4133. var measureCharMinor = document.createElement('DIV');
  4134. measureCharMinor.className = 'text minor measure';
  4135. measureCharMinor.appendChild(text);
  4136. this.frame.appendChild(measureCharMinor);
  4137. dom.measureCharMinor = measureCharMinor;
  4138. }
  4139. if (!dom.measureCharMajor) {
  4140. text = document.createTextNode('0');
  4141. var measureCharMajor = document.createElement('DIV');
  4142. measureCharMajor.className = 'text major measure';
  4143. measureCharMajor.appendChild(text);
  4144. this.frame.appendChild(measureCharMajor);
  4145. dom.measureCharMajor = measureCharMajor;
  4146. }
  4147. };
  4148. /**
  4149. * Reflow the component
  4150. * @return {Boolean} resized
  4151. */
  4152. TimeAxis.prototype.reflow = function () {
  4153. var changed = 0,
  4154. update = util.updateProperty,
  4155. frame = this.frame,
  4156. range = this.range;
  4157. if (!range) {
  4158. throw new Error('Cannot repaint time axis: no range configured');
  4159. }
  4160. if (frame) {
  4161. changed += update(this, 'top', frame.offsetTop);
  4162. changed += update(this, 'left', frame.offsetLeft);
  4163. // calculate size of a character
  4164. var props = this.props,
  4165. showMinorLabels = this.getOption('showMinorLabels'),
  4166. showMajorLabels = this.getOption('showMajorLabels'),
  4167. measureCharMinor = this.dom.measureCharMinor,
  4168. measureCharMajor = this.dom.measureCharMajor;
  4169. if (measureCharMinor) {
  4170. props.minorCharHeight = measureCharMinor.clientHeight;
  4171. props.minorCharWidth = measureCharMinor.clientWidth;
  4172. }
  4173. if (measureCharMajor) {
  4174. props.majorCharHeight = measureCharMajor.clientHeight;
  4175. props.majorCharWidth = measureCharMajor.clientWidth;
  4176. }
  4177. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4178. if (parentHeight != props.parentHeight) {
  4179. props.parentHeight = parentHeight;
  4180. changed += 1;
  4181. }
  4182. switch (this.getOption('orientation')) {
  4183. case 'bottom':
  4184. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4185. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4186. props.minorLabelTop = 0;
  4187. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4188. props.minorLineTop = -this.top;
  4189. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4190. props.minorLineWidth = 1; // TODO: really calculate width
  4191. props.majorLineTop = -this.top;
  4192. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4193. props.majorLineWidth = 1; // TODO: really calculate width
  4194. props.lineTop = 0;
  4195. break;
  4196. case 'top':
  4197. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4198. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4199. props.majorLabelTop = 0;
  4200. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4201. props.minorLineTop = props.minorLabelTop;
  4202. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4203. props.minorLineWidth = 1; // TODO: really calculate width
  4204. props.majorLineTop = 0;
  4205. props.majorLineHeight = Math.max(parentHeight - this.top);
  4206. props.majorLineWidth = 1; // TODO: really calculate width
  4207. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4208. break;
  4209. default:
  4210. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4211. }
  4212. var height = props.minorLabelHeight + props.majorLabelHeight;
  4213. changed += update(this, 'width', frame.offsetWidth);
  4214. changed += update(this, 'height', height);
  4215. // calculate range and step
  4216. this._updateConversion();
  4217. var start = util.convert(range.start, 'Number'),
  4218. end = util.convert(range.end, 'Number'),
  4219. minimumStep = this.toTime((props.minorCharWidth || 10) * 5).valueOf()
  4220. -this.toTime(0).valueOf();
  4221. this.step = new TimeStep(new Date(start), new Date(end), minimumStep);
  4222. changed += update(props.range, 'start', start);
  4223. changed += update(props.range, 'end', end);
  4224. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4225. }
  4226. return (changed > 0);
  4227. };
  4228. /**
  4229. * Calculate the scale and offset to convert a position on screen to the
  4230. * corresponding date and vice versa.
  4231. * After the method _updateConversion is executed once, the methods toTime
  4232. * and toScreen can be used.
  4233. * @private
  4234. */
  4235. TimeAxis.prototype._updateConversion = function() {
  4236. var range = this.range;
  4237. if (!range) {
  4238. throw new Error('No range configured');
  4239. }
  4240. if (range.conversion) {
  4241. this.conversion = range.conversion(this.width);
  4242. }
  4243. else {
  4244. this.conversion = Range.conversion(range.start, range.end, this.width);
  4245. }
  4246. };
  4247. /**
  4248. * A current time bar
  4249. * @param {Component} parent
  4250. * @param {Component[]} [depends] Components on which this components depends
  4251. * (except for the parent)
  4252. * @param {Object} [options] Available parameters:
  4253. * {Boolean} [showCurrentTime]
  4254. * @constructor CurrentTime
  4255. * @extends Component
  4256. */
  4257. function CurrentTime (parent, depends, options) {
  4258. this.id = util.randomUUID();
  4259. this.parent = parent;
  4260. this.depends = depends;
  4261. this.options = options || {};
  4262. this.defaultOptions = {
  4263. showCurrentTime: false
  4264. };
  4265. }
  4266. CurrentTime.prototype = new Component();
  4267. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  4268. /**
  4269. * Get the container element of the bar, which can be used by a child to
  4270. * add its own widgets.
  4271. * @returns {HTMLElement} container
  4272. */
  4273. CurrentTime.prototype.getContainer = function () {
  4274. return this.frame;
  4275. };
  4276. /**
  4277. * Repaint the component
  4278. * @return {Boolean} changed
  4279. */
  4280. CurrentTime.prototype.repaint = function () {
  4281. var bar = this.frame,
  4282. parent = this.parent,
  4283. parentContainer = parent.parent.getContainer();
  4284. if (!parent) {
  4285. throw new Error('Cannot repaint bar: no parent attached');
  4286. }
  4287. if (!parentContainer) {
  4288. throw new Error('Cannot repaint bar: parent has no container element');
  4289. }
  4290. if (!this.getOption('showCurrentTime')) {
  4291. if (bar) {
  4292. parentContainer.removeChild(bar);
  4293. delete this.frame;
  4294. }
  4295. return;
  4296. }
  4297. if (!bar) {
  4298. bar = document.createElement('div');
  4299. bar.className = 'currenttime';
  4300. bar.style.position = 'absolute';
  4301. bar.style.top = '0px';
  4302. bar.style.height = '100%';
  4303. parentContainer.appendChild(bar);
  4304. this.frame = bar;
  4305. }
  4306. if (!parent.conversion) {
  4307. parent._updateConversion();
  4308. }
  4309. var now = new Date();
  4310. var x = parent.toScreen(now);
  4311. bar.style.left = x + 'px';
  4312. bar.title = 'Current time: ' + now;
  4313. // start a timer to adjust for the new time
  4314. if (this.currentTimeTimer !== undefined) {
  4315. clearTimeout(this.currentTimeTimer);
  4316. delete this.currentTimeTimer;
  4317. }
  4318. var timeline = this;
  4319. var interval = 1 / parent.conversion.scale / 2;
  4320. if (interval < 30) {
  4321. interval = 30;
  4322. }
  4323. this.currentTimeTimer = setTimeout(function() {
  4324. timeline.repaint();
  4325. }, interval);
  4326. return false;
  4327. };
  4328. /**
  4329. * A custom time bar
  4330. * @param {Component} parent
  4331. * @param {Component[]} [depends] Components on which this components depends
  4332. * (except for the parent)
  4333. * @param {Object} [options] Available parameters:
  4334. * {Boolean} [showCustomTime]
  4335. * @constructor CustomTime
  4336. * @extends Component
  4337. */
  4338. function CustomTime (parent, depends, options) {
  4339. this.id = util.randomUUID();
  4340. this.parent = parent;
  4341. this.depends = depends;
  4342. this.options = options || {};
  4343. this.defaultOptions = {
  4344. showCustomTime: false
  4345. };
  4346. this.listeners = [];
  4347. this.customTime = new Date();
  4348. }
  4349. CustomTime.prototype = new Component();
  4350. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4351. /**
  4352. * Get the container element of the bar, which can be used by a child to
  4353. * add its own widgets.
  4354. * @returns {HTMLElement} container
  4355. */
  4356. CustomTime.prototype.getContainer = function () {
  4357. return this.frame;
  4358. };
  4359. /**
  4360. * Repaint the component
  4361. * @return {Boolean} changed
  4362. */
  4363. CustomTime.prototype.repaint = function () {
  4364. var bar = this.frame,
  4365. parent = this.parent,
  4366. parentContainer = parent.parent.getContainer();
  4367. if (!parent) {
  4368. throw new Error('Cannot repaint bar: no parent attached');
  4369. }
  4370. if (!parentContainer) {
  4371. throw new Error('Cannot repaint bar: parent has no container element');
  4372. }
  4373. if (!this.getOption('showCustomTime')) {
  4374. if (bar) {
  4375. parentContainer.removeChild(bar);
  4376. delete this.frame;
  4377. }
  4378. return;
  4379. }
  4380. if (!bar) {
  4381. bar = document.createElement('div');
  4382. bar.className = 'customtime';
  4383. bar.style.position = 'absolute';
  4384. bar.style.top = '0px';
  4385. bar.style.height = '100%';
  4386. parentContainer.appendChild(bar);
  4387. var drag = document.createElement('div');
  4388. drag.style.position = 'relative';
  4389. drag.style.top = '0px';
  4390. drag.style.left = '-10px';
  4391. drag.style.height = '100%';
  4392. drag.style.width = '20px';
  4393. bar.appendChild(drag);
  4394. this.frame = bar;
  4395. this.subscribe(this, 'movetime');
  4396. }
  4397. if (!parent.conversion) {
  4398. parent._updateConversion();
  4399. }
  4400. var x = parent.toScreen(this.customTime);
  4401. bar.style.left = x + 'px';
  4402. bar.title = 'Time: ' + this.customTime;
  4403. return false;
  4404. };
  4405. /**
  4406. * Set custom time.
  4407. * @param {Date} time
  4408. */
  4409. CustomTime.prototype._setCustomTime = function(time) {
  4410. this.customTime = new Date(time.valueOf());
  4411. this.repaint();
  4412. };
  4413. /**
  4414. * Retrieve the current custom time.
  4415. * @return {Date} customTime
  4416. */
  4417. CustomTime.prototype._getCustomTime = function() {
  4418. return new Date(this.customTime.valueOf());
  4419. };
  4420. /**
  4421. * Add listeners for mouse and touch events to the component
  4422. * @param {Component} component
  4423. */
  4424. CustomTime.prototype.subscribe = function (component, event) {
  4425. var me = this;
  4426. var listener = {
  4427. component: component,
  4428. event: event,
  4429. callback: function (event) {
  4430. me._onMouseDown(event, listener);
  4431. },
  4432. params: {}
  4433. };
  4434. component.on('mousedown', listener.callback);
  4435. me.listeners.push(listener);
  4436. };
  4437. /**
  4438. * Event handler
  4439. * @param {String} event name of the event, for example 'click', 'mousemove'
  4440. * @param {function} callback callback handler, invoked with the raw HTML Event
  4441. * as parameter.
  4442. */
  4443. CustomTime.prototype.on = function (event, callback) {
  4444. var bar = this.frame;
  4445. if (!bar) {
  4446. throw new Error('Cannot add event listener: no parent attached');
  4447. }
  4448. events.addListener(this, event, callback);
  4449. util.addEventListener(bar, event, callback);
  4450. };
  4451. /**
  4452. * Start moving horizontally
  4453. * @param {Event} event
  4454. * @param {Object} listener Listener containing the component and params
  4455. * @private
  4456. */
  4457. CustomTime.prototype._onMouseDown = function(event, listener) {
  4458. event = event || window.event;
  4459. var params = listener.params;
  4460. // only react on left mouse button down
  4461. var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  4462. if (!leftButtonDown) {
  4463. return;
  4464. }
  4465. // get mouse position
  4466. params.mouseX = util.getPageX(event);
  4467. params.moved = false;
  4468. params.customTime = this.customTime;
  4469. // add event listeners to handle moving the custom time bar
  4470. var me = this;
  4471. if (!params.onMouseMove) {
  4472. params.onMouseMove = function (event) {
  4473. me._onMouseMove(event, listener);
  4474. };
  4475. util.addEventListener(document, 'mousemove', params.onMouseMove);
  4476. }
  4477. if (!params.onMouseUp) {
  4478. params.onMouseUp = function (event) {
  4479. me._onMouseUp(event, listener);
  4480. };
  4481. util.addEventListener(document, 'mouseup', params.onMouseUp);
  4482. }
  4483. util.stopPropagation(event);
  4484. util.preventDefault(event);
  4485. };
  4486. /**
  4487. * Perform moving operating.
  4488. * This function activated from within the funcion CustomTime._onMouseDown().
  4489. * @param {Event} event
  4490. * @param {Object} listener
  4491. * @private
  4492. */
  4493. CustomTime.prototype._onMouseMove = function (event, listener) {
  4494. event = event || window.event;
  4495. var params = listener.params;
  4496. var parent = this.parent;
  4497. // calculate change in mouse position
  4498. var mouseX = util.getPageX(event);
  4499. if (params.mouseX === undefined) {
  4500. params.mouseX = mouseX;
  4501. }
  4502. var diff = mouseX - params.mouseX;
  4503. // if mouse movement is big enough, register it as a "moved" event
  4504. if (Math.abs(diff) >= 1) {
  4505. params.moved = true;
  4506. }
  4507. var x = parent.toScreen(params.customTime);
  4508. var xnew = x + diff;
  4509. var time = parent.toTime(xnew);
  4510. this._setCustomTime(time);
  4511. // fire a timechange event
  4512. events.trigger(this, 'timechange', {customTime: this.customTime});
  4513. util.preventDefault(event);
  4514. };
  4515. /**
  4516. * Stop moving operating.
  4517. * This function activated from within the function CustomTime._onMouseDown().
  4518. * @param {event} event
  4519. * @param {Object} listener
  4520. * @private
  4521. */
  4522. CustomTime.prototype._onMouseUp = function (event, listener) {
  4523. event = event || window.event;
  4524. var params = listener.params;
  4525. // remove event listeners here, important for Safari
  4526. if (params.onMouseMove) {
  4527. util.removeEventListener(document, 'mousemove', params.onMouseMove);
  4528. params.onMouseMove = null;
  4529. }
  4530. if (params.onMouseUp) {
  4531. util.removeEventListener(document, 'mouseup', params.onMouseUp);
  4532. params.onMouseUp = null;
  4533. }
  4534. if (params.moved) {
  4535. // fire a timechanged event
  4536. events.trigger(this, 'timechanged', {customTime: this.customTime});
  4537. }
  4538. };
  4539. /**
  4540. * An ItemSet holds a set of items and ranges which can be displayed in a
  4541. * range. The width is determined by the parent of the ItemSet, and the height
  4542. * is determined by the size of the items.
  4543. * @param {Component} parent
  4544. * @param {Component[]} [depends] Components on which this components depends
  4545. * (except for the parent)
  4546. * @param {Object} [options] See ItemSet.setOptions for the available
  4547. * options.
  4548. * @constructor ItemSet
  4549. * @extends Panel
  4550. */
  4551. // TODO: improve performance by replacing all Array.forEach with a for loop
  4552. function ItemSet(parent, depends, options) {
  4553. this.id = util.randomUUID();
  4554. this.parent = parent;
  4555. this.depends = depends;
  4556. // one options object is shared by this itemset and all its items
  4557. this.options = options || {};
  4558. this.defaultOptions = {
  4559. type: 'box',
  4560. align: 'center',
  4561. orientation: 'bottom',
  4562. margin: {
  4563. axis: 20,
  4564. item: 10
  4565. },
  4566. padding: 5
  4567. };
  4568. this.dom = {};
  4569. var me = this;
  4570. this.itemsData = null; // DataSet
  4571. this.range = null; // Range or Object {start: number, end: number}
  4572. this.listeners = {
  4573. 'add': function (event, params, senderId) {
  4574. if (senderId != me.id) {
  4575. me._onAdd(params.items);
  4576. }
  4577. },
  4578. 'update': function (event, params, senderId) {
  4579. if (senderId != me.id) {
  4580. me._onUpdate(params.items);
  4581. }
  4582. },
  4583. 'remove': function (event, params, senderId) {
  4584. if (senderId != me.id) {
  4585. me._onRemove(params.items);
  4586. }
  4587. }
  4588. };
  4589. this.items = {}; // object with an Item for every data item
  4590. this.selection = []; // list with the ids of all selected nodes
  4591. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4592. this.stack = new Stack(this, Object.create(this.options));
  4593. this.conversion = null;
  4594. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4595. }
  4596. ItemSet.prototype = new Panel();
  4597. // available item types will be registered here
  4598. ItemSet.types = {
  4599. box: ItemBox,
  4600. range: ItemRange,
  4601. rangeoverflow: ItemRangeOverflow,
  4602. point: ItemPoint
  4603. };
  4604. /**
  4605. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4606. * @param {Object} [options] The following options are available:
  4607. * {String | function} [className]
  4608. * class name for the itemset
  4609. * {String} [type]
  4610. * Default type for the items. Choose from 'box'
  4611. * (default), 'point', or 'range'. The default
  4612. * Style can be overwritten by individual items.
  4613. * {String} align
  4614. * Alignment for the items, only applicable for
  4615. * ItemBox. Choose 'center' (default), 'left', or
  4616. * 'right'.
  4617. * {String} orientation
  4618. * Orientation of the item set. Choose 'top' or
  4619. * 'bottom' (default).
  4620. * {Number} margin.axis
  4621. * Margin between the axis and the items in pixels.
  4622. * Default is 20.
  4623. * {Number} margin.item
  4624. * Margin between items in pixels. Default is 10.
  4625. * {Number} padding
  4626. * Padding of the contents of an item in pixels.
  4627. * Must correspond with the items css. Default is 5.
  4628. */
  4629. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4630. /**
  4631. * Set range (start and end).
  4632. * @param {Range | Object} range A Range or an object containing start and end.
  4633. */
  4634. ItemSet.prototype.setRange = function setRange(range) {
  4635. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4636. throw new TypeError('Range must be an instance of Range, ' +
  4637. 'or an object containing start and end.');
  4638. }
  4639. this.range = range;
  4640. };
  4641. /**
  4642. * Set selected items by their id. Replaces the current selection
  4643. * Unknown id's are silently ignored.
  4644. * @param {Array} [ids] An array with zero or more id's of the items to be
  4645. * selected. If ids is an empty array, all items will be
  4646. * unselected.
  4647. */
  4648. ItemSet.prototype.setSelection = function setSelection(ids) {
  4649. var i, ii, id, item, selection;
  4650. if (ids) {
  4651. if (!Array.isArray(ids)) {
  4652. throw new TypeError('Array expected');
  4653. }
  4654. // unselect currently selected items
  4655. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4656. id = this.selection[i];
  4657. item = this.items[id];
  4658. if (item) item.unselect();
  4659. }
  4660. // select items
  4661. this.selection = [];
  4662. for (i = 0, ii = ids.length; i < ii; i++) {
  4663. id = ids[i];
  4664. item = this.items[id];
  4665. if (item) {
  4666. this.selection.push(id);
  4667. item.select();
  4668. }
  4669. }
  4670. // trigger a select event
  4671. selection = this.selection.concat([]);
  4672. events.trigger(this, 'select', {
  4673. ids: selection
  4674. });
  4675. if (this.controller) {
  4676. this.requestRepaint();
  4677. }
  4678. }
  4679. };
  4680. /**
  4681. * Get the selected items by their id
  4682. * @return {Array} ids The ids of the selected items
  4683. */
  4684. ItemSet.prototype.getSelection = function getSelection() {
  4685. return this.selection.concat([]);
  4686. };
  4687. /**
  4688. * Deselect a selected item
  4689. * @param {String | Number} id
  4690. * @private
  4691. */
  4692. ItemSet.prototype._deselect = function _deselect(id) {
  4693. var selection = this.selection;
  4694. for (var i = 0, ii = selection.length; i < ii; i++) {
  4695. if (selection[i] == id) { // non-strict comparison!
  4696. selection.splice(i, 1);
  4697. break;
  4698. }
  4699. }
  4700. };
  4701. /**
  4702. * Repaint the component
  4703. * @return {Boolean} changed
  4704. */
  4705. ItemSet.prototype.repaint = function repaint() {
  4706. var changed = 0,
  4707. update = util.updateProperty,
  4708. asSize = util.option.asSize,
  4709. options = this.options,
  4710. orientation = this.getOption('orientation'),
  4711. defaultOptions = this.defaultOptions,
  4712. frame = this.frame;
  4713. if (!frame) {
  4714. frame = document.createElement('div');
  4715. frame.className = 'itemset';
  4716. var className = options.className;
  4717. if (className) {
  4718. util.addClassName(frame, util.option.asString(className));
  4719. }
  4720. // create background panel
  4721. var background = document.createElement('div');
  4722. background.className = 'background';
  4723. frame.appendChild(background);
  4724. this.dom.background = background;
  4725. // create foreground panel
  4726. var foreground = document.createElement('div');
  4727. foreground.className = 'foreground';
  4728. frame.appendChild(foreground);
  4729. this.dom.foreground = foreground;
  4730. // create axis panel
  4731. var axis = document.createElement('div');
  4732. axis.className = 'itemset-axis';
  4733. //frame.appendChild(axis);
  4734. this.dom.axis = axis;
  4735. this.frame = frame;
  4736. changed += 1;
  4737. }
  4738. if (!this.parent) {
  4739. throw new Error('Cannot repaint itemset: no parent attached');
  4740. }
  4741. var parentContainer = this.parent.getContainer();
  4742. if (!parentContainer) {
  4743. throw new Error('Cannot repaint itemset: parent has no container element');
  4744. }
  4745. if (!frame.parentNode) {
  4746. parentContainer.appendChild(frame);
  4747. changed += 1;
  4748. }
  4749. if (!this.dom.axis.parentNode) {
  4750. parentContainer.appendChild(this.dom.axis);
  4751. changed += 1;
  4752. }
  4753. // reposition frame
  4754. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4755. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4756. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4757. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4758. // reposition axis
  4759. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4760. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4761. if (orientation == 'bottom') {
  4762. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4763. }
  4764. else { // orientation == 'top'
  4765. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4766. }
  4767. this._updateConversion();
  4768. var me = this,
  4769. queue = this.queue,
  4770. itemsData = this.itemsData,
  4771. items = this.items,
  4772. dataOptions = {
  4773. // TODO: cleanup
  4774. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  4775. };
  4776. // show/hide added/changed/removed items
  4777. for (var id in queue) {
  4778. if (queue.hasOwnProperty(id)) {
  4779. var entry = queue[id],
  4780. item = items[id],
  4781. action = entry.action;
  4782. //noinspection FallthroughInSwitchStatementJS
  4783. switch (action) {
  4784. case 'add':
  4785. case 'update':
  4786. var itemData = itemsData && itemsData.get(id, dataOptions);
  4787. if (itemData) {
  4788. var type = itemData.type ||
  4789. (itemData.start && itemData.end && 'range') ||
  4790. options.type ||
  4791. 'box';
  4792. var constructor = ItemSet.types[type];
  4793. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4794. if (item) {
  4795. // update item
  4796. if (!constructor || !(item instanceof constructor)) {
  4797. // item type has changed, hide and delete the item
  4798. changed += item.hide();
  4799. item = null;
  4800. }
  4801. else {
  4802. item.data = itemData; // TODO: create a method item.setData ?
  4803. changed++;
  4804. }
  4805. }
  4806. if (!item) {
  4807. // create item
  4808. if (constructor) {
  4809. item = new constructor(me, itemData, options, defaultOptions);
  4810. item.id = entry.id; // we take entry.id, as id itself is stringified
  4811. changed++;
  4812. }
  4813. else {
  4814. throw new TypeError('Unknown item type "' + type + '"');
  4815. }
  4816. }
  4817. // force a repaint (not only a reposition)
  4818. item.repaint();
  4819. items[id] = item;
  4820. }
  4821. // update queue
  4822. delete queue[id];
  4823. break;
  4824. case 'remove':
  4825. if (item) {
  4826. // remove the item from the set selected items
  4827. if (item.selected) {
  4828. me._deselect(id);
  4829. }
  4830. // remove DOM of the item
  4831. changed += item.hide();
  4832. }
  4833. // update lists
  4834. delete items[id];
  4835. delete queue[id];
  4836. break;
  4837. default:
  4838. console.log('Error: unknown action "' + action + '"');
  4839. }
  4840. }
  4841. }
  4842. // reposition all items. Show items only when in the visible area
  4843. util.forEach(this.items, function (item) {
  4844. if (item.visible) {
  4845. changed += item.show();
  4846. item.reposition();
  4847. }
  4848. else {
  4849. changed += item.hide();
  4850. }
  4851. });
  4852. return (changed > 0);
  4853. };
  4854. /**
  4855. * Get the foreground container element
  4856. * @return {HTMLElement} foreground
  4857. */
  4858. ItemSet.prototype.getForeground = function getForeground() {
  4859. return this.dom.foreground;
  4860. };
  4861. /**
  4862. * Get the background container element
  4863. * @return {HTMLElement} background
  4864. */
  4865. ItemSet.prototype.getBackground = function getBackground() {
  4866. return this.dom.background;
  4867. };
  4868. /**
  4869. * Get the axis container element
  4870. * @return {HTMLElement} axis
  4871. */
  4872. ItemSet.prototype.getAxis = function getAxis() {
  4873. return this.dom.axis;
  4874. };
  4875. /**
  4876. * Reflow the component
  4877. * @return {Boolean} resized
  4878. */
  4879. ItemSet.prototype.reflow = function reflow () {
  4880. var changed = 0,
  4881. options = this.options,
  4882. marginAxis = options.margin && options.margin.axis || this.defaultOptions.margin.axis,
  4883. marginItem = options.margin && options.margin.item || this.defaultOptions.margin.item,
  4884. update = util.updateProperty,
  4885. asNumber = util.option.asNumber,
  4886. asSize = util.option.asSize,
  4887. frame = this.frame;
  4888. if (frame) {
  4889. this._updateConversion();
  4890. util.forEach(this.items, function (item) {
  4891. changed += item.reflow();
  4892. });
  4893. // TODO: stack.update should be triggered via an event, in stack itself
  4894. // TODO: only update the stack when there are changed items
  4895. this.stack.update();
  4896. var maxHeight = asNumber(options.maxHeight);
  4897. var fixedHeight = (asSize(options.height) != null);
  4898. var height;
  4899. if (fixedHeight) {
  4900. height = frame.offsetHeight;
  4901. }
  4902. else {
  4903. // height is not specified, determine the height from the height and positioned items
  4904. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4905. if (visibleItems.length) {
  4906. var min = visibleItems[0].top;
  4907. var max = visibleItems[0].top + visibleItems[0].height;
  4908. util.forEach(visibleItems, function (item) {
  4909. min = Math.min(min, item.top);
  4910. max = Math.max(max, (item.top + item.height));
  4911. });
  4912. height = (max - min) + marginAxis + marginItem;
  4913. }
  4914. else {
  4915. height = marginAxis + marginItem;
  4916. }
  4917. }
  4918. if (maxHeight != null) {
  4919. height = Math.min(height, maxHeight);
  4920. }
  4921. changed += update(this, 'height', height);
  4922. // calculate height from items
  4923. changed += update(this, 'top', frame.offsetTop);
  4924. changed += update(this, 'left', frame.offsetLeft);
  4925. changed += update(this, 'width', frame.offsetWidth);
  4926. }
  4927. else {
  4928. changed += 1;
  4929. }
  4930. return (changed > 0);
  4931. };
  4932. /**
  4933. * Hide this component from the DOM
  4934. * @return {Boolean} changed
  4935. */
  4936. ItemSet.prototype.hide = function hide() {
  4937. var changed = false;
  4938. // remove the DOM
  4939. if (this.frame && this.frame.parentNode) {
  4940. this.frame.parentNode.removeChild(this.frame);
  4941. changed = true;
  4942. }
  4943. if (this.dom.axis && this.dom.axis.parentNode) {
  4944. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4945. changed = true;
  4946. }
  4947. return changed;
  4948. };
  4949. /**
  4950. * Set items
  4951. * @param {vis.DataSet | null} items
  4952. */
  4953. ItemSet.prototype.setItems = function setItems(items) {
  4954. var me = this,
  4955. ids,
  4956. oldItemsData = this.itemsData;
  4957. // replace the dataset
  4958. if (!items) {
  4959. this.itemsData = null;
  4960. }
  4961. else if (items instanceof DataSet || items instanceof DataView) {
  4962. this.itemsData = items;
  4963. }
  4964. else {
  4965. throw new TypeError('Data must be an instance of DataSet');
  4966. }
  4967. if (oldItemsData) {
  4968. // unsubscribe from old dataset
  4969. util.forEach(this.listeners, function (callback, event) {
  4970. oldItemsData.unsubscribe(event, callback);
  4971. });
  4972. // remove all drawn items
  4973. ids = oldItemsData.getIds();
  4974. this._onRemove(ids);
  4975. }
  4976. if (this.itemsData) {
  4977. // subscribe to new dataset
  4978. var id = this.id;
  4979. util.forEach(this.listeners, function (callback, event) {
  4980. me.itemsData.subscribe(event, callback, id);
  4981. });
  4982. // draw all new items
  4983. ids = this.itemsData.getIds();
  4984. this._onAdd(ids);
  4985. }
  4986. };
  4987. /**
  4988. * Get the current items items
  4989. * @returns {vis.DataSet | null}
  4990. */
  4991. ItemSet.prototype.getItems = function getItems() {
  4992. return this.itemsData;
  4993. };
  4994. /**
  4995. * Handle updated items
  4996. * @param {Number[]} ids
  4997. * @private
  4998. */
  4999. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  5000. this._toQueue('update', ids);
  5001. };
  5002. /**
  5003. * Handle changed items
  5004. * @param {Number[]} ids
  5005. * @private
  5006. */
  5007. ItemSet.prototype._onAdd = function _onAdd(ids) {
  5008. this._toQueue('add', ids);
  5009. };
  5010. /**
  5011. * Handle removed items
  5012. * @param {Number[]} ids
  5013. * @private
  5014. */
  5015. ItemSet.prototype._onRemove = function _onRemove(ids) {
  5016. this._toQueue('remove', ids);
  5017. };
  5018. /**
  5019. * Put items in the queue to be added/updated/remove
  5020. * @param {String} action can be 'add', 'update', 'remove'
  5021. * @param {Number[]} ids
  5022. */
  5023. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  5024. var queue = this.queue;
  5025. ids.forEach(function (id) {
  5026. queue[id] = {
  5027. id: id,
  5028. action: action
  5029. };
  5030. });
  5031. if (this.controller) {
  5032. //this.requestReflow();
  5033. this.requestRepaint();
  5034. }
  5035. };
  5036. /**
  5037. * Calculate the scale and offset to convert a position on screen to the
  5038. * corresponding date and vice versa.
  5039. * After the method _updateConversion is executed once, the methods toTime
  5040. * and toScreen can be used.
  5041. * @private
  5042. */
  5043. ItemSet.prototype._updateConversion = function _updateConversion() {
  5044. var range = this.range;
  5045. if (!range) {
  5046. throw new Error('No range configured');
  5047. }
  5048. if (range.conversion) {
  5049. this.conversion = range.conversion(this.width);
  5050. }
  5051. else {
  5052. this.conversion = Range.conversion(range.start, range.end, this.width);
  5053. }
  5054. };
  5055. /**
  5056. * Convert a position on screen (pixels) to a datetime
  5057. * Before this method can be used, the method _updateConversion must be
  5058. * executed once.
  5059. * @param {int} x Position on the screen in pixels
  5060. * @return {Date} time The datetime the corresponds with given position x
  5061. */
  5062. ItemSet.prototype.toTime = function toTime(x) {
  5063. var conversion = this.conversion;
  5064. return new Date(x / conversion.scale + conversion.offset);
  5065. };
  5066. /**
  5067. * Convert a datetime (Date object) into a position on the screen
  5068. * Before this method can be used, the method _updateConversion must be
  5069. * executed once.
  5070. * @param {Date} time A date
  5071. * @return {int} x The position on the screen in pixels which corresponds
  5072. * with the given date.
  5073. */
  5074. ItemSet.prototype.toScreen = function toScreen(time) {
  5075. var conversion = this.conversion;
  5076. return (time.valueOf() - conversion.offset) * conversion.scale;
  5077. };
  5078. /**
  5079. * @constructor Item
  5080. * @param {ItemSet} parent
  5081. * @param {Object} data Object containing (optional) parameters type,
  5082. * start, end, content, group, className.
  5083. * @param {Object} [options] Options to set initial property values
  5084. * @param {Object} [defaultOptions] default options
  5085. * // TODO: describe available options
  5086. */
  5087. function Item (parent, data, options, defaultOptions) {
  5088. this.parent = parent;
  5089. this.data = data;
  5090. this.dom = null;
  5091. this.options = options || {};
  5092. this.defaultOptions = defaultOptions || {};
  5093. this.selected = false;
  5094. this.visible = false;
  5095. this.top = 0;
  5096. this.left = 0;
  5097. this.width = 0;
  5098. this.height = 0;
  5099. }
  5100. /**
  5101. * Select current item
  5102. */
  5103. Item.prototype.select = function select() {
  5104. this.selected = true;
  5105. if (this.visible) this.repaint();
  5106. };
  5107. /**
  5108. * Unselect current item
  5109. */
  5110. Item.prototype.unselect = function unselect() {
  5111. this.selected = false;
  5112. if (this.visible) this.repaint();
  5113. };
  5114. /**
  5115. * Show the Item in the DOM (when not already visible)
  5116. * @return {Boolean} changed
  5117. */
  5118. Item.prototype.show = function show() {
  5119. return false;
  5120. };
  5121. /**
  5122. * Hide the Item from the DOM (when visible)
  5123. * @return {Boolean} changed
  5124. */
  5125. Item.prototype.hide = function hide() {
  5126. return false;
  5127. };
  5128. /**
  5129. * Repaint the item
  5130. * @return {Boolean} changed
  5131. */
  5132. Item.prototype.repaint = function repaint() {
  5133. // should be implemented by the item
  5134. return false;
  5135. };
  5136. /**
  5137. * Reflow the item
  5138. * @return {Boolean} resized
  5139. */
  5140. Item.prototype.reflow = function reflow() {
  5141. // should be implemented by the item
  5142. return false;
  5143. };
  5144. /**
  5145. * Return the items width
  5146. * @return {Integer} width
  5147. */
  5148. Item.prototype.getWidth = function getWidth() {
  5149. return this.width;
  5150. }
  5151. /**
  5152. * @constructor ItemBox
  5153. * @extends Item
  5154. * @param {ItemSet} parent
  5155. * @param {Object} data Object containing parameters start
  5156. * content, className.
  5157. * @param {Object} [options] Options to set initial property values
  5158. * @param {Object} [defaultOptions] default options
  5159. * // TODO: describe available options
  5160. */
  5161. function ItemBox (parent, data, options, defaultOptions) {
  5162. this.props = {
  5163. dot: {
  5164. left: 0,
  5165. top: 0,
  5166. width: 0,
  5167. height: 0
  5168. },
  5169. line: {
  5170. top: 0,
  5171. left: 0,
  5172. width: 0,
  5173. height: 0
  5174. }
  5175. };
  5176. Item.call(this, parent, data, options, defaultOptions);
  5177. }
  5178. ItemBox.prototype = new Item (null, null);
  5179. /**
  5180. * Repaint the item
  5181. * @return {Boolean} changed
  5182. */
  5183. ItemBox.prototype.repaint = function repaint() {
  5184. // TODO: make an efficient repaint
  5185. var changed = false;
  5186. var dom = this.dom;
  5187. if (!dom) {
  5188. this._create();
  5189. dom = this.dom;
  5190. changed = true;
  5191. }
  5192. if (dom) {
  5193. if (!this.parent) {
  5194. throw new Error('Cannot repaint item: no parent attached');
  5195. }
  5196. if (!dom.box.parentNode) {
  5197. var foreground = this.parent.getForeground();
  5198. if (!foreground) {
  5199. throw new Error('Cannot repaint time axis: ' +
  5200. 'parent has no foreground container element');
  5201. }
  5202. foreground.appendChild(dom.box);
  5203. changed = true;
  5204. }
  5205. if (!dom.line.parentNode) {
  5206. var background = this.parent.getBackground();
  5207. if (!background) {
  5208. throw new Error('Cannot repaint time axis: ' +
  5209. 'parent has no background container element');
  5210. }
  5211. background.appendChild(dom.line);
  5212. changed = true;
  5213. }
  5214. if (!dom.dot.parentNode) {
  5215. var axis = this.parent.getAxis();
  5216. if (!background) {
  5217. throw new Error('Cannot repaint time axis: ' +
  5218. 'parent has no axis container element');
  5219. }
  5220. axis.appendChild(dom.dot);
  5221. changed = true;
  5222. }
  5223. // update contents
  5224. if (this.data.content != this.content) {
  5225. this.content = this.data.content;
  5226. if (this.content instanceof Element) {
  5227. dom.content.innerHTML = '';
  5228. dom.content.appendChild(this.content);
  5229. }
  5230. else if (this.data.content != undefined) {
  5231. dom.content.innerHTML = this.content;
  5232. }
  5233. else {
  5234. throw new Error('Property "content" missing in item ' + this.data.id);
  5235. }
  5236. changed = true;
  5237. }
  5238. // update class
  5239. var className = (this.data.className? ' ' + this.data.className : '') +
  5240. (this.selected ? ' selected' : '');
  5241. if (this.className != className) {
  5242. this.className = className;
  5243. dom.box.className = 'item box' + className;
  5244. dom.line.className = 'item line' + className;
  5245. dom.dot.className = 'item dot' + className;
  5246. changed = true;
  5247. }
  5248. }
  5249. return changed;
  5250. };
  5251. /**
  5252. * Show the item in the DOM (when not already visible). The items DOM will
  5253. * be created when needed.
  5254. * @return {Boolean} changed
  5255. */
  5256. ItemBox.prototype.show = function show() {
  5257. if (!this.dom || !this.dom.box.parentNode) {
  5258. return this.repaint();
  5259. }
  5260. else {
  5261. return false;
  5262. }
  5263. };
  5264. /**
  5265. * Hide the item from the DOM (when visible)
  5266. * @return {Boolean} changed
  5267. */
  5268. ItemBox.prototype.hide = function hide() {
  5269. var changed = false,
  5270. dom = this.dom;
  5271. if (dom) {
  5272. if (dom.box.parentNode) {
  5273. dom.box.parentNode.removeChild(dom.box);
  5274. changed = true;
  5275. }
  5276. if (dom.line.parentNode) {
  5277. dom.line.parentNode.removeChild(dom.line);
  5278. }
  5279. if (dom.dot.parentNode) {
  5280. dom.dot.parentNode.removeChild(dom.dot);
  5281. }
  5282. }
  5283. return changed;
  5284. };
  5285. /**
  5286. * Reflow the item: calculate its actual size and position from the DOM
  5287. * @return {boolean} resized returns true if the axis is resized
  5288. * @override
  5289. */
  5290. ItemBox.prototype.reflow = function reflow() {
  5291. var changed = 0,
  5292. update,
  5293. dom,
  5294. props,
  5295. options,
  5296. margin,
  5297. start,
  5298. align,
  5299. orientation,
  5300. top,
  5301. left,
  5302. data,
  5303. range;
  5304. if (this.data.start == undefined) {
  5305. throw new Error('Property "start" missing in item ' + this.data.id);
  5306. }
  5307. data = this.data;
  5308. range = this.parent && this.parent.range;
  5309. if (data && range) {
  5310. // TODO: account for the width of the item
  5311. var interval = (range.end - range.start);
  5312. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  5313. }
  5314. else {
  5315. this.visible = false;
  5316. }
  5317. if (this.visible) {
  5318. dom = this.dom;
  5319. if (dom) {
  5320. update = util.updateProperty;
  5321. props = this.props;
  5322. options = this.options;
  5323. start = this.parent.toScreen(this.data.start);
  5324. align = options.align || this.defaultOptions.align;
  5325. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5326. orientation = options.orientation || this.defaultOptions.orientation;
  5327. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5328. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5329. changed += update(props.line, 'width', dom.line.offsetWidth);
  5330. changed += update(props.line, 'height', dom.line.offsetHeight);
  5331. changed += update(props.line, 'top', dom.line.offsetTop);
  5332. changed += update(this, 'width', dom.box.offsetWidth);
  5333. changed += update(this, 'height', dom.box.offsetHeight);
  5334. if (align == 'right') {
  5335. left = start - this.width;
  5336. }
  5337. else if (align == 'left') {
  5338. left = start;
  5339. }
  5340. else {
  5341. // default or 'center'
  5342. left = start - this.width / 2;
  5343. }
  5344. changed += update(this, 'left', left);
  5345. changed += update(props.line, 'left', start - props.line.width / 2);
  5346. changed += update(props.dot, 'left', start - props.dot.width / 2);
  5347. changed += update(props.dot, 'top', -props.dot.height / 2);
  5348. if (orientation == 'top') {
  5349. top = margin;
  5350. changed += update(this, 'top', top);
  5351. }
  5352. else {
  5353. // default or 'bottom'
  5354. var parentHeight = this.parent.height;
  5355. top = parentHeight - this.height - margin;
  5356. changed += update(this, 'top', top);
  5357. }
  5358. }
  5359. else {
  5360. changed += 1;
  5361. }
  5362. }
  5363. return (changed > 0);
  5364. };
  5365. /**
  5366. * Create an items DOM
  5367. * @private
  5368. */
  5369. ItemBox.prototype._create = function _create() {
  5370. var dom = this.dom;
  5371. if (!dom) {
  5372. this.dom = dom = {};
  5373. // create the box
  5374. dom.box = document.createElement('DIV');
  5375. // className is updated in repaint()
  5376. // contents box (inside the background box). used for making margins
  5377. dom.content = document.createElement('DIV');
  5378. dom.content.className = 'content';
  5379. dom.box.appendChild(dom.content);
  5380. // line to axis
  5381. dom.line = document.createElement('DIV');
  5382. dom.line.className = 'line';
  5383. // dot on axis
  5384. dom.dot = document.createElement('DIV');
  5385. dom.dot.className = 'dot';
  5386. // attach this item as attribute
  5387. dom.box['timeline-item'] = this;
  5388. }
  5389. };
  5390. /**
  5391. * Reposition the item, recalculate its left, top, and width, using the current
  5392. * range and size of the items itemset
  5393. * @override
  5394. */
  5395. ItemBox.prototype.reposition = function reposition() {
  5396. var dom = this.dom,
  5397. props = this.props,
  5398. orientation = this.options.orientation || this.defaultOptions.orientation;
  5399. if (dom) {
  5400. var box = dom.box,
  5401. line = dom.line,
  5402. dot = dom.dot;
  5403. box.style.left = this.left + 'px';
  5404. box.style.top = this.top + 'px';
  5405. line.style.left = props.line.left + 'px';
  5406. if (orientation == 'top') {
  5407. line.style.top = 0 + 'px';
  5408. line.style.height = this.top + 'px';
  5409. }
  5410. else {
  5411. // orientation 'bottom'
  5412. line.style.top = (this.top + this.height) + 'px';
  5413. line.style.height = Math.max(this.parent.height - this.top - this.height +
  5414. this.props.dot.height / 2, 0) + 'px';
  5415. }
  5416. dot.style.left = props.dot.left + 'px';
  5417. dot.style.top = props.dot.top + 'px';
  5418. }
  5419. };
  5420. /**
  5421. * @constructor ItemPoint
  5422. * @extends Item
  5423. * @param {ItemSet} parent
  5424. * @param {Object} data Object containing parameters start
  5425. * content, className.
  5426. * @param {Object} [options] Options to set initial property values
  5427. * @param {Object} [defaultOptions] default options
  5428. * // TODO: describe available options
  5429. */
  5430. function ItemPoint (parent, data, options, defaultOptions) {
  5431. this.props = {
  5432. dot: {
  5433. top: 0,
  5434. width: 0,
  5435. height: 0
  5436. },
  5437. content: {
  5438. height: 0,
  5439. marginLeft: 0
  5440. }
  5441. };
  5442. Item.call(this, parent, data, options, defaultOptions);
  5443. }
  5444. ItemPoint.prototype = new Item (null, null);
  5445. /**
  5446. * Repaint the item
  5447. * @return {Boolean} changed
  5448. */
  5449. ItemPoint.prototype.repaint = function repaint() {
  5450. // TODO: make an efficient repaint
  5451. var changed = false;
  5452. var dom = this.dom;
  5453. if (!dom) {
  5454. this._create();
  5455. dom = this.dom;
  5456. changed = true;
  5457. }
  5458. if (dom) {
  5459. if (!this.parent) {
  5460. throw new Error('Cannot repaint item: no parent attached');
  5461. }
  5462. var foreground = this.parent.getForeground();
  5463. if (!foreground) {
  5464. throw new Error('Cannot repaint time axis: ' +
  5465. 'parent has no foreground container element');
  5466. }
  5467. if (!dom.point.parentNode) {
  5468. foreground.appendChild(dom.point);
  5469. foreground.appendChild(dom.point);
  5470. changed = true;
  5471. }
  5472. // update contents
  5473. if (this.data.content != this.content) {
  5474. this.content = this.data.content;
  5475. if (this.content instanceof Element) {
  5476. dom.content.innerHTML = '';
  5477. dom.content.appendChild(this.content);
  5478. }
  5479. else if (this.data.content != undefined) {
  5480. dom.content.innerHTML = this.content;
  5481. }
  5482. else {
  5483. throw new Error('Property "content" missing in item ' + this.data.id);
  5484. }
  5485. changed = true;
  5486. }
  5487. // update class
  5488. var className = (this.data.className? ' ' + this.data.className : '') +
  5489. (this.selected ? ' selected' : '');
  5490. if (this.className != className) {
  5491. this.className = className;
  5492. dom.point.className = 'item point' + className;
  5493. changed = true;
  5494. }
  5495. }
  5496. return changed;
  5497. };
  5498. /**
  5499. * Show the item in the DOM (when not already visible). The items DOM will
  5500. * be created when needed.
  5501. * @return {Boolean} changed
  5502. */
  5503. ItemPoint.prototype.show = function show() {
  5504. if (!this.dom || !this.dom.point.parentNode) {
  5505. return this.repaint();
  5506. }
  5507. else {
  5508. return false;
  5509. }
  5510. };
  5511. /**
  5512. * Hide the item from the DOM (when visible)
  5513. * @return {Boolean} changed
  5514. */
  5515. ItemPoint.prototype.hide = function hide() {
  5516. var changed = false,
  5517. dom = this.dom;
  5518. if (dom) {
  5519. if (dom.point.parentNode) {
  5520. dom.point.parentNode.removeChild(dom.point);
  5521. changed = true;
  5522. }
  5523. }
  5524. return changed;
  5525. };
  5526. /**
  5527. * Reflow the item: calculate its actual size from the DOM
  5528. * @return {boolean} resized returns true if the axis is resized
  5529. * @override
  5530. */
  5531. ItemPoint.prototype.reflow = function reflow() {
  5532. var changed = 0,
  5533. update,
  5534. dom,
  5535. props,
  5536. options,
  5537. margin,
  5538. orientation,
  5539. start,
  5540. top,
  5541. data,
  5542. range;
  5543. if (this.data.start == undefined) {
  5544. throw new Error('Property "start" missing in item ' + this.data.id);
  5545. }
  5546. data = this.data;
  5547. range = this.parent && this.parent.range;
  5548. if (data && range) {
  5549. // TODO: account for the width of the item
  5550. var interval = (range.end - range.start);
  5551. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  5552. }
  5553. else {
  5554. this.visible = false;
  5555. }
  5556. if (this.visible) {
  5557. dom = this.dom;
  5558. if (dom) {
  5559. update = util.updateProperty;
  5560. props = this.props;
  5561. options = this.options;
  5562. orientation = options.orientation || this.defaultOptions.orientation;
  5563. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5564. start = this.parent.toScreen(this.data.start);
  5565. changed += update(this, 'width', dom.point.offsetWidth);
  5566. changed += update(this, 'height', dom.point.offsetHeight);
  5567. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5568. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5569. changed += update(props.content, 'height', dom.content.offsetHeight);
  5570. if (orientation == 'top') {
  5571. top = margin;
  5572. }
  5573. else {
  5574. // default or 'bottom'
  5575. var parentHeight = this.parent.height;
  5576. top = Math.max(parentHeight - this.height - margin, 0);
  5577. }
  5578. changed += update(this, 'top', top);
  5579. changed += update(this, 'left', start - props.dot.width / 2);
  5580. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5581. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5582. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5583. }
  5584. else {
  5585. changed += 1;
  5586. }
  5587. }
  5588. return (changed > 0);
  5589. };
  5590. /**
  5591. * Create an items DOM
  5592. * @private
  5593. */
  5594. ItemPoint.prototype._create = function _create() {
  5595. var dom = this.dom;
  5596. if (!dom) {
  5597. this.dom = dom = {};
  5598. // background box
  5599. dom.point = document.createElement('div');
  5600. // className is updated in repaint()
  5601. // contents box, right from the dot
  5602. dom.content = document.createElement('div');
  5603. dom.content.className = 'content';
  5604. dom.point.appendChild(dom.content);
  5605. // dot at start
  5606. dom.dot = document.createElement('div');
  5607. dom.dot.className = 'dot';
  5608. dom.point.appendChild(dom.dot);
  5609. // attach this item as attribute
  5610. dom.point['timeline-item'] = this;
  5611. }
  5612. };
  5613. /**
  5614. * Reposition the item, recalculate its left, top, and width, using the current
  5615. * range and size of the items itemset
  5616. * @override
  5617. */
  5618. ItemPoint.prototype.reposition = function reposition() {
  5619. var dom = this.dom,
  5620. props = this.props;
  5621. if (dom) {
  5622. dom.point.style.top = this.top + 'px';
  5623. dom.point.style.left = this.left + 'px';
  5624. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5625. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5626. dom.dot.style.top = props.dot.top + 'px';
  5627. }
  5628. };
  5629. /**
  5630. * @constructor ItemRange
  5631. * @extends Item
  5632. * @param {ItemSet} parent
  5633. * @param {Object} data Object containing parameters start, end
  5634. * content, className.
  5635. * @param {Object} [options] Options to set initial property values
  5636. * @param {Object} [defaultOptions] default options
  5637. * // TODO: describe available options
  5638. */
  5639. function ItemRange (parent, data, options, defaultOptions) {
  5640. this.props = {
  5641. content: {
  5642. left: 0,
  5643. width: 0
  5644. }
  5645. };
  5646. Item.call(this, parent, data, options, defaultOptions);
  5647. }
  5648. ItemRange.prototype = new Item (null, null);
  5649. /**
  5650. * Repaint the item
  5651. * @return {Boolean} changed
  5652. */
  5653. ItemRange.prototype.repaint = function repaint() {
  5654. // TODO: make an efficient repaint
  5655. var changed = false;
  5656. var dom = this.dom;
  5657. if (!dom) {
  5658. this._create();
  5659. dom = this.dom;
  5660. changed = true;
  5661. }
  5662. if (dom) {
  5663. if (!this.parent) {
  5664. throw new Error('Cannot repaint item: no parent attached');
  5665. }
  5666. var foreground = this.parent.getForeground();
  5667. if (!foreground) {
  5668. throw new Error('Cannot repaint time axis: ' +
  5669. 'parent has no foreground container element');
  5670. }
  5671. if (!dom.box.parentNode) {
  5672. foreground.appendChild(dom.box);
  5673. changed = true;
  5674. }
  5675. // update content
  5676. if (this.data.content != this.content) {
  5677. this.content = this.data.content;
  5678. if (this.content instanceof Element) {
  5679. dom.content.innerHTML = '';
  5680. dom.content.appendChild(this.content);
  5681. }
  5682. else if (this.data.content != undefined) {
  5683. dom.content.innerHTML = this.content;
  5684. }
  5685. else {
  5686. throw new Error('Property "content" missing in item ' + this.data.id);
  5687. }
  5688. changed = true;
  5689. }
  5690. // update class
  5691. var className = (this.data.className? ' ' + this.data.className : '') +
  5692. (this.selected ? ' selected' : '');
  5693. if (this.className != className) {
  5694. this.className = className;
  5695. dom.box.className = 'item range' + className;
  5696. changed = true;
  5697. }
  5698. }
  5699. return changed;
  5700. };
  5701. /**
  5702. * Show the item in the DOM (when not already visible). The items DOM will
  5703. * be created when needed.
  5704. * @return {Boolean} changed
  5705. */
  5706. ItemRange.prototype.show = function show() {
  5707. if (!this.dom || !this.dom.box.parentNode) {
  5708. return this.repaint();
  5709. }
  5710. else {
  5711. return false;
  5712. }
  5713. };
  5714. /**
  5715. * Hide the item from the DOM (when visible)
  5716. * @return {Boolean} changed
  5717. */
  5718. ItemRange.prototype.hide = function hide() {
  5719. var changed = false,
  5720. dom = this.dom;
  5721. if (dom) {
  5722. if (dom.box.parentNode) {
  5723. dom.box.parentNode.removeChild(dom.box);
  5724. changed = true;
  5725. }
  5726. }
  5727. return changed;
  5728. };
  5729. /**
  5730. * Reflow the item: calculate its actual size from the DOM
  5731. * @return {boolean} resized returns true if the axis is resized
  5732. * @override
  5733. */
  5734. ItemRange.prototype.reflow = function reflow() {
  5735. var changed = 0,
  5736. dom,
  5737. props,
  5738. options,
  5739. margin,
  5740. padding,
  5741. parent,
  5742. start,
  5743. end,
  5744. data,
  5745. range,
  5746. update,
  5747. box,
  5748. parentWidth,
  5749. contentLeft,
  5750. orientation,
  5751. top;
  5752. if (this.data.start == undefined) {
  5753. throw new Error('Property "start" missing in item ' + this.data.id);
  5754. }
  5755. if (this.data.end == undefined) {
  5756. throw new Error('Property "end" missing in item ' + this.data.id);
  5757. }
  5758. data = this.data;
  5759. range = this.parent && this.parent.range;
  5760. if (data && range) {
  5761. // TODO: account for the width of the item. Take some margin
  5762. this.visible = (data.start < range.end) && (data.end > range.start);
  5763. }
  5764. else {
  5765. this.visible = false;
  5766. }
  5767. if (this.visible) {
  5768. dom = this.dom;
  5769. if (dom) {
  5770. props = this.props;
  5771. options = this.options;
  5772. parent = this.parent;
  5773. start = parent.toScreen(this.data.start);
  5774. end = parent.toScreen(this.data.end);
  5775. update = util.updateProperty;
  5776. box = dom.box;
  5777. parentWidth = parent.width;
  5778. orientation = options.orientation || this.defaultOptions.orientation;
  5779. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5780. padding = options.padding || this.defaultOptions.padding;
  5781. changed += update(props.content, 'width', dom.content.offsetWidth);
  5782. changed += update(this, 'height', box.offsetHeight);
  5783. // limit the width of the this, as browsers cannot draw very wide divs
  5784. if (start < -parentWidth) {
  5785. start = -parentWidth;
  5786. }
  5787. if (end > 2 * parentWidth) {
  5788. end = 2 * parentWidth;
  5789. }
  5790. // when range exceeds left of the window, position the contents at the left of the visible area
  5791. if (start < 0) {
  5792. contentLeft = Math.min(-start,
  5793. (end - start - props.content.width - 2 * padding));
  5794. // TODO: remove the need for options.padding. it's terrible.
  5795. }
  5796. else {
  5797. contentLeft = 0;
  5798. }
  5799. changed += update(props.content, 'left', contentLeft);
  5800. if (orientation == 'top') {
  5801. top = margin;
  5802. changed += update(this, 'top', top);
  5803. }
  5804. else {
  5805. // default or 'bottom'
  5806. top = parent.height - this.height - margin;
  5807. changed += update(this, 'top', top);
  5808. }
  5809. changed += update(this, 'left', start);
  5810. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  5811. }
  5812. else {
  5813. changed += 1;
  5814. }
  5815. }
  5816. return (changed > 0);
  5817. };
  5818. /**
  5819. * Create an items DOM
  5820. * @private
  5821. */
  5822. ItemRange.prototype._create = function _create() {
  5823. var dom = this.dom;
  5824. if (!dom) {
  5825. this.dom = dom = {};
  5826. // background box
  5827. dom.box = document.createElement('div');
  5828. // className is updated in repaint()
  5829. // contents box
  5830. dom.content = document.createElement('div');
  5831. dom.content.className = 'content';
  5832. dom.box.appendChild(dom.content);
  5833. // attach this item as attribute
  5834. dom.box['timeline-item'] = this;
  5835. }
  5836. };
  5837. /**
  5838. * Reposition the item, recalculate its left, top, and width, using the current
  5839. * range and size of the items itemset
  5840. * @override
  5841. */
  5842. ItemRange.prototype.reposition = function reposition() {
  5843. var dom = this.dom,
  5844. props = this.props;
  5845. if (dom) {
  5846. dom.box.style.top = this.top + 'px';
  5847. dom.box.style.left = this.left + 'px';
  5848. dom.box.style.width = this.width + 'px';
  5849. dom.content.style.left = props.content.left + 'px';
  5850. }
  5851. };
  5852. /**
  5853. * @constructor ItemRangeOverflow
  5854. * @extends ItemRange
  5855. * @param {ItemSet} parent
  5856. * @param {Object} data Object containing parameters start, end
  5857. * content, className.
  5858. * @param {Object} [options] Options to set initial property values
  5859. * @param {Object} [defaultOptions] default options
  5860. * // TODO: describe available options
  5861. */
  5862. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  5863. this.props = {
  5864. content: {
  5865. left: 0,
  5866. width: 0
  5867. }
  5868. };
  5869. ItemRange.call(this, parent, data, options, defaultOptions);
  5870. }
  5871. ItemRangeOverflow.prototype = new ItemRange (null, null);
  5872. /**
  5873. * Repaint the item
  5874. * @return {Boolean} changed
  5875. */
  5876. ItemRangeOverflow.prototype.repaint = function repaint() {
  5877. // TODO: make an efficient repaint
  5878. var changed = false;
  5879. var dom = this.dom;
  5880. if (!dom) {
  5881. this._create();
  5882. dom = this.dom;
  5883. changed = true;
  5884. }
  5885. if (dom) {
  5886. if (!this.parent) {
  5887. throw new Error('Cannot repaint item: no parent attached');
  5888. }
  5889. var foreground = this.parent.getForeground();
  5890. if (!foreground) {
  5891. throw new Error('Cannot repaint time axis: ' +
  5892. 'parent has no foreground container element');
  5893. }
  5894. if (!dom.box.parentNode) {
  5895. foreground.appendChild(dom.box);
  5896. changed = true;
  5897. }
  5898. // update content
  5899. if (this.data.content != this.content) {
  5900. this.content = this.data.content;
  5901. if (this.content instanceof Element) {
  5902. dom.content.innerHTML = '';
  5903. dom.content.appendChild(this.content);
  5904. }
  5905. else if (this.data.content != undefined) {
  5906. dom.content.innerHTML = this.content;
  5907. }
  5908. else {
  5909. throw new Error('Property "content" missing in item ' + this.data.id);
  5910. }
  5911. changed = true;
  5912. }
  5913. // update class
  5914. var className = this.data.className ? (' ' + this.data.className) : '';
  5915. if (this.className != className) {
  5916. this.className = className;
  5917. dom.box.className = 'item rangeoverflow' + className;
  5918. changed = true;
  5919. }
  5920. }
  5921. return changed;
  5922. };
  5923. /**
  5924. * Return the items width
  5925. * @return {Number} width
  5926. */
  5927. ItemRangeOverflow.prototype.getWidth = function getWidth() {
  5928. if (this.props.content !== undefined && this.width < this.props.content.width)
  5929. return this.props.content.width;
  5930. else
  5931. return this.width;
  5932. };
  5933. /**
  5934. * @constructor Group
  5935. * @param {GroupSet} parent
  5936. * @param {Number | String} groupId
  5937. * @param {Object} [options] Options to set initial property values
  5938. * // TODO: describe available options
  5939. * @extends Component
  5940. */
  5941. function Group (parent, groupId, options) {
  5942. this.id = util.randomUUID();
  5943. this.parent = parent;
  5944. this.groupId = groupId;
  5945. this.itemset = null; // ItemSet
  5946. this.options = options || {};
  5947. this.options.top = 0;
  5948. this.props = {
  5949. label: {
  5950. width: 0,
  5951. height: 0
  5952. }
  5953. };
  5954. this.top = 0;
  5955. this.left = 0;
  5956. this.width = 0;
  5957. this.height = 0;
  5958. }
  5959. Group.prototype = new Component();
  5960. // TODO: comment
  5961. Group.prototype.setOptions = Component.prototype.setOptions;
  5962. /**
  5963. * Get the container element of the panel, which can be used by a child to
  5964. * add its own widgets.
  5965. * @returns {HTMLElement} container
  5966. */
  5967. Group.prototype.getContainer = function () {
  5968. return this.parent.getContainer();
  5969. };
  5970. /**
  5971. * Set item set for the group. The group will create a view on the itemset,
  5972. * filtered by the groups id.
  5973. * @param {DataSet | DataView} items
  5974. */
  5975. Group.prototype.setItems = function setItems(items) {
  5976. if (this.itemset) {
  5977. // remove current item set
  5978. this.itemset.hide();
  5979. this.itemset.setItems();
  5980. this.parent.controller.remove(this.itemset);
  5981. this.itemset = null;
  5982. }
  5983. if (items) {
  5984. var groupId = this.groupId;
  5985. var itemsetOptions = Object.create(this.options);
  5986. this.itemset = new ItemSet(this, null, itemsetOptions);
  5987. this.itemset.setRange(this.parent.range);
  5988. this.view = new DataView(items, {
  5989. filter: function (item) {
  5990. return item.group == groupId;
  5991. }
  5992. });
  5993. this.itemset.setItems(this.view);
  5994. this.parent.controller.add(this.itemset);
  5995. }
  5996. };
  5997. /**
  5998. * Set selected items by their id. Replaces the current selection.
  5999. * Unknown id's are silently ignored.
  6000. * @param {Array} [ids] An array with zero or more id's of the items to be
  6001. * selected. If ids is an empty array, all items will be
  6002. * unselected.
  6003. */
  6004. Group.prototype.setSelection = function setSelection(ids) {
  6005. if (this.itemset) this.itemset.setSelection(ids);
  6006. };
  6007. /**
  6008. * Get the selected items by their id
  6009. * @return {Array} ids The ids of the selected items
  6010. */
  6011. Group.prototype.getSelection = function getSelection() {
  6012. return this.itemset ? this.itemset.getSelection() : [];
  6013. };
  6014. /**
  6015. * Repaint the item
  6016. * @return {Boolean} changed
  6017. */
  6018. Group.prototype.repaint = function repaint() {
  6019. return false;
  6020. };
  6021. /**
  6022. * Reflow the item
  6023. * @return {Boolean} resized
  6024. */
  6025. Group.prototype.reflow = function reflow() {
  6026. var changed = 0,
  6027. update = util.updateProperty;
  6028. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  6029. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  6030. // TODO: reckon with the height of the group label
  6031. if (this.label) {
  6032. var inner = this.label.firstChild;
  6033. changed += update(this.props.label, 'width', inner.clientWidth);
  6034. changed += update(this.props.label, 'height', inner.clientHeight);
  6035. }
  6036. else {
  6037. changed += update(this.props.label, 'width', 0);
  6038. changed += update(this.props.label, 'height', 0);
  6039. }
  6040. return (changed > 0);
  6041. };
  6042. /**
  6043. * An GroupSet holds a set of groups
  6044. * @param {Component} parent
  6045. * @param {Component[]} [depends] Components on which this components depends
  6046. * (except for the parent)
  6047. * @param {Object} [options] See GroupSet.setOptions for the available
  6048. * options.
  6049. * @constructor GroupSet
  6050. * @extends Panel
  6051. */
  6052. function GroupSet(parent, depends, options) {
  6053. this.id = util.randomUUID();
  6054. this.parent = parent;
  6055. this.depends = depends;
  6056. this.options = options || {};
  6057. this.range = null; // Range or Object {start: number, end: number}
  6058. this.itemsData = null; // DataSet with items
  6059. this.groupsData = null; // DataSet with groups
  6060. this.groups = {}; // map with groups
  6061. this.dom = {};
  6062. this.props = {
  6063. labels: {
  6064. width: 0
  6065. }
  6066. };
  6067. // TODO: implement right orientation of the labels
  6068. // changes in groups are queued key/value map containing id/action
  6069. this.queue = {};
  6070. var me = this;
  6071. this.listeners = {
  6072. 'add': function (event, params) {
  6073. me._onAdd(params.items);
  6074. },
  6075. 'update': function (event, params) {
  6076. me._onUpdate(params.items);
  6077. },
  6078. 'remove': function (event, params) {
  6079. me._onRemove(params.items);
  6080. }
  6081. };
  6082. }
  6083. GroupSet.prototype = new Panel();
  6084. /**
  6085. * Set options for the GroupSet. Existing options will be extended/overwritten.
  6086. * @param {Object} [options] The following options are available:
  6087. * {String | function} groupsOrder
  6088. * TODO: describe options
  6089. */
  6090. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  6091. GroupSet.prototype.setRange = function (range) {
  6092. // TODO: implement setRange
  6093. };
  6094. /**
  6095. * Set items
  6096. * @param {vis.DataSet | null} items
  6097. */
  6098. GroupSet.prototype.setItems = function setItems(items) {
  6099. this.itemsData = items;
  6100. for (var id in this.groups) {
  6101. if (this.groups.hasOwnProperty(id)) {
  6102. var group = this.groups[id];
  6103. group.setItems(items);
  6104. }
  6105. }
  6106. };
  6107. /**
  6108. * Get items
  6109. * @return {vis.DataSet | null} items
  6110. */
  6111. GroupSet.prototype.getItems = function getItems() {
  6112. return this.itemsData;
  6113. };
  6114. /**
  6115. * Set range (start and end).
  6116. * @param {Range | Object} range A Range or an object containing start and end.
  6117. */
  6118. GroupSet.prototype.setRange = function setRange(range) {
  6119. this.range = range;
  6120. };
  6121. /**
  6122. * Set groups
  6123. * @param {vis.DataSet} groups
  6124. */
  6125. GroupSet.prototype.setGroups = function setGroups(groups) {
  6126. var me = this,
  6127. ids;
  6128. // unsubscribe from current dataset
  6129. if (this.groupsData) {
  6130. util.forEach(this.listeners, function (callback, event) {
  6131. me.groupsData.unsubscribe(event, callback);
  6132. });
  6133. // remove all drawn groups
  6134. ids = this.groupsData.getIds();
  6135. this._onRemove(ids);
  6136. }
  6137. // replace the dataset
  6138. if (!groups) {
  6139. this.groupsData = null;
  6140. }
  6141. else if (groups instanceof DataSet) {
  6142. this.groupsData = groups;
  6143. }
  6144. else {
  6145. this.groupsData = new DataSet({
  6146. convert: {
  6147. start: 'Date',
  6148. end: 'Date'
  6149. }
  6150. });
  6151. this.groupsData.add(groups);
  6152. }
  6153. if (this.groupsData) {
  6154. // subscribe to new dataset
  6155. var id = this.id;
  6156. util.forEach(this.listeners, function (callback, event) {
  6157. me.groupsData.subscribe(event, callback, id);
  6158. });
  6159. // draw all new groups
  6160. ids = this.groupsData.getIds();
  6161. this._onAdd(ids);
  6162. }
  6163. };
  6164. /**
  6165. * Get groups
  6166. * @return {vis.DataSet | null} groups
  6167. */
  6168. GroupSet.prototype.getGroups = function getGroups() {
  6169. return this.groupsData;
  6170. };
  6171. /**
  6172. * Set selected items by their id. Replaces the current selection.
  6173. * Unknown id's are silently ignored.
  6174. * @param {Array} [ids] An array with zero or more id's of the items to be
  6175. * selected. If ids is an empty array, all items will be
  6176. * unselected.
  6177. */
  6178. GroupSet.prototype.setSelection = function setSelection(ids) {
  6179. var selection = [],
  6180. groups = this.groups;
  6181. // iterate over each of the groups
  6182. for (var id in groups) {
  6183. if (groups.hasOwnProperty(id)) {
  6184. var group = groups[id];
  6185. group.setSelection(ids);
  6186. }
  6187. }
  6188. return selection;
  6189. };
  6190. /**
  6191. * Get the selected items by their id
  6192. * @return {Array} ids The ids of the selected items
  6193. */
  6194. GroupSet.prototype.getSelection = function getSelection() {
  6195. var selection = [],
  6196. groups = this.groups;
  6197. // iterate over each of the groups
  6198. for (var id in groups) {
  6199. if (groups.hasOwnProperty(id)) {
  6200. var group = groups[id];
  6201. selection = selection.concat(group.getSelection());
  6202. }
  6203. }
  6204. return selection;
  6205. };
  6206. /**
  6207. * Repaint the component
  6208. * @return {Boolean} changed
  6209. */
  6210. GroupSet.prototype.repaint = function repaint() {
  6211. var changed = 0,
  6212. i, id, group, label,
  6213. update = util.updateProperty,
  6214. asSize = util.option.asSize,
  6215. asElement = util.option.asElement,
  6216. options = this.options,
  6217. frame = this.dom.frame,
  6218. labels = this.dom.labels,
  6219. labelSet = this.dom.labelSet;
  6220. // create frame
  6221. if (!this.parent) {
  6222. throw new Error('Cannot repaint groupset: no parent attached');
  6223. }
  6224. var parentContainer = this.parent.getContainer();
  6225. if (!parentContainer) {
  6226. throw new Error('Cannot repaint groupset: parent has no container element');
  6227. }
  6228. if (!frame) {
  6229. frame = document.createElement('div');
  6230. frame.className = 'groupset';
  6231. this.dom.frame = frame;
  6232. var className = options.className;
  6233. if (className) {
  6234. util.addClassName(frame, util.option.asString(className));
  6235. }
  6236. changed += 1;
  6237. }
  6238. if (!frame.parentNode) {
  6239. parentContainer.appendChild(frame);
  6240. changed += 1;
  6241. }
  6242. // create labels
  6243. var labelContainer = asElement(options.labelContainer);
  6244. if (!labelContainer) {
  6245. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  6246. }
  6247. if (!labels) {
  6248. labels = document.createElement('div');
  6249. labels.className = 'labels';
  6250. this.dom.labels = labels;
  6251. }
  6252. if (!labelSet) {
  6253. labelSet = document.createElement('div');
  6254. labelSet.className = 'label-set';
  6255. labels.appendChild(labelSet);
  6256. this.dom.labelSet = labelSet;
  6257. }
  6258. if (!labels.parentNode || labels.parentNode != labelContainer) {
  6259. if (labels.parentNode) {
  6260. labels.parentNode.removeChild(labels.parentNode);
  6261. }
  6262. labelContainer.appendChild(labels);
  6263. }
  6264. // reposition frame
  6265. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  6266. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6267. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6268. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6269. // reposition labels
  6270. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  6271. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  6272. var me = this,
  6273. queue = this.queue,
  6274. groups = this.groups,
  6275. groupsData = this.groupsData;
  6276. // show/hide added/changed/removed groups
  6277. var ids = Object.keys(queue);
  6278. if (ids.length) {
  6279. ids.forEach(function (id) {
  6280. var action = queue[id];
  6281. var group = groups[id];
  6282. //noinspection FallthroughInSwitchStatementJS
  6283. switch (action) {
  6284. case 'add':
  6285. case 'update':
  6286. if (!group) {
  6287. var groupOptions = Object.create(me.options);
  6288. util.extend(groupOptions, {
  6289. height: null,
  6290. maxHeight: null
  6291. });
  6292. group = new Group(me, id, groupOptions);
  6293. group.setItems(me.itemsData); // attach items data
  6294. groups[id] = group;
  6295. me.controller.add(group);
  6296. }
  6297. // TODO: update group data
  6298. group.data = groupsData.get(id);
  6299. delete queue[id];
  6300. break;
  6301. case 'remove':
  6302. if (group) {
  6303. group.setItems(); // detach items data
  6304. delete groups[id];
  6305. me.controller.remove(group);
  6306. }
  6307. // update lists
  6308. delete queue[id];
  6309. break;
  6310. default:
  6311. console.log('Error: unknown action "' + action + '"');
  6312. }
  6313. });
  6314. // the groupset depends on each of the groups
  6315. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  6316. // TODO: apply dependencies of the groupset
  6317. // update the top positions of the groups in the correct order
  6318. var orderedGroups = this.groupsData.getIds({
  6319. order: this.options.groupOrder
  6320. });
  6321. for (i = 0; i < orderedGroups.length; i++) {
  6322. (function (group, prevGroup) {
  6323. var top = 0;
  6324. if (prevGroup) {
  6325. top = function () {
  6326. // TODO: top must reckon with options.maxHeight
  6327. return prevGroup.top + prevGroup.height;
  6328. }
  6329. }
  6330. group.setOptions({
  6331. top: top
  6332. });
  6333. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  6334. }
  6335. // (re)create the labels
  6336. while (labelSet.firstChild) {
  6337. labelSet.removeChild(labelSet.firstChild);
  6338. }
  6339. for (i = 0; i < orderedGroups.length; i++) {
  6340. id = orderedGroups[i];
  6341. label = this._createLabel(id);
  6342. labelSet.appendChild(label);
  6343. }
  6344. changed++;
  6345. }
  6346. // reposition the labels
  6347. // TODO: labels are not displayed correctly when orientation=='top'
  6348. // TODO: width of labelPanel is not immediately updated on a change in groups
  6349. for (id in groups) {
  6350. if (groups.hasOwnProperty(id)) {
  6351. group = groups[id];
  6352. label = group.label;
  6353. if (label) {
  6354. label.style.top = group.top + 'px';
  6355. label.style.height = group.height + 'px';
  6356. }
  6357. }
  6358. }
  6359. return (changed > 0);
  6360. };
  6361. /**
  6362. * Create a label for group with given id
  6363. * @param {Number} id
  6364. * @return {Element} label
  6365. * @private
  6366. */
  6367. GroupSet.prototype._createLabel = function(id) {
  6368. var group = this.groups[id];
  6369. var label = document.createElement('div');
  6370. label.className = 'label';
  6371. var inner = document.createElement('div');
  6372. inner.className = 'inner';
  6373. label.appendChild(inner);
  6374. var content = group.data && group.data.content;
  6375. if (content instanceof Element) {
  6376. inner.appendChild(content);
  6377. }
  6378. else if (content != undefined) {
  6379. inner.innerHTML = content;
  6380. }
  6381. var className = group.data && group.data.className;
  6382. if (className) {
  6383. util.addClassName(label, className);
  6384. }
  6385. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  6386. return label;
  6387. };
  6388. /**
  6389. * Get container element
  6390. * @return {HTMLElement} container
  6391. */
  6392. GroupSet.prototype.getContainer = function getContainer() {
  6393. return this.dom.frame;
  6394. };
  6395. /**
  6396. * Get the width of the group labels
  6397. * @return {Number} width
  6398. */
  6399. GroupSet.prototype.getLabelsWidth = function getContainer() {
  6400. return this.props.labels.width;
  6401. };
  6402. /**
  6403. * Reflow the component
  6404. * @return {Boolean} resized
  6405. */
  6406. GroupSet.prototype.reflow = function reflow() {
  6407. var changed = 0,
  6408. id, group,
  6409. options = this.options,
  6410. update = util.updateProperty,
  6411. asNumber = util.option.asNumber,
  6412. asSize = util.option.asSize,
  6413. frame = this.dom.frame;
  6414. if (frame) {
  6415. var maxHeight = asNumber(options.maxHeight);
  6416. var fixedHeight = (asSize(options.height) != null);
  6417. var height;
  6418. if (fixedHeight) {
  6419. height = frame.offsetHeight;
  6420. }
  6421. else {
  6422. // height is not specified, calculate the sum of the height of all groups
  6423. height = 0;
  6424. for (id in this.groups) {
  6425. if (this.groups.hasOwnProperty(id)) {
  6426. group = this.groups[id];
  6427. height += group.height;
  6428. }
  6429. }
  6430. }
  6431. if (maxHeight != null) {
  6432. height = Math.min(height, maxHeight);
  6433. }
  6434. changed += update(this, 'height', height);
  6435. changed += update(this, 'top', frame.offsetTop);
  6436. changed += update(this, 'left', frame.offsetLeft);
  6437. changed += update(this, 'width', frame.offsetWidth);
  6438. }
  6439. // calculate the maximum width of the labels
  6440. var width = 0;
  6441. for (id in this.groups) {
  6442. if (this.groups.hasOwnProperty(id)) {
  6443. group = this.groups[id];
  6444. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  6445. width = Math.max(width, labelWidth);
  6446. }
  6447. }
  6448. changed += update(this.props.labels, 'width', width);
  6449. return (changed > 0);
  6450. };
  6451. /**
  6452. * Hide the component from the DOM
  6453. * @return {Boolean} changed
  6454. */
  6455. GroupSet.prototype.hide = function hide() {
  6456. if (this.dom.frame && this.dom.frame.parentNode) {
  6457. this.dom.frame.parentNode.removeChild(this.dom.frame);
  6458. return true;
  6459. }
  6460. else {
  6461. return false;
  6462. }
  6463. };
  6464. /**
  6465. * Show the component in the DOM (when not already visible).
  6466. * A repaint will be executed when the component is not visible
  6467. * @return {Boolean} changed
  6468. */
  6469. GroupSet.prototype.show = function show() {
  6470. if (!this.dom.frame || !this.dom.frame.parentNode) {
  6471. return this.repaint();
  6472. }
  6473. else {
  6474. return false;
  6475. }
  6476. };
  6477. /**
  6478. * Handle updated groups
  6479. * @param {Number[]} ids
  6480. * @private
  6481. */
  6482. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  6483. this._toQueue(ids, 'update');
  6484. };
  6485. /**
  6486. * Handle changed groups
  6487. * @param {Number[]} ids
  6488. * @private
  6489. */
  6490. GroupSet.prototype._onAdd = function _onAdd(ids) {
  6491. this._toQueue(ids, 'add');
  6492. };
  6493. /**
  6494. * Handle removed groups
  6495. * @param {Number[]} ids
  6496. * @private
  6497. */
  6498. GroupSet.prototype._onRemove = function _onRemove(ids) {
  6499. this._toQueue(ids, 'remove');
  6500. };
  6501. /**
  6502. * Put groups in the queue to be added/updated/remove
  6503. * @param {Number[]} ids
  6504. * @param {String} action can be 'add', 'update', 'remove'
  6505. */
  6506. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  6507. var queue = this.queue;
  6508. ids.forEach(function (id) {
  6509. queue[id] = action;
  6510. });
  6511. if (this.controller) {
  6512. //this.requestReflow();
  6513. this.requestRepaint();
  6514. }
  6515. };
  6516. /**
  6517. * Create a timeline visualization
  6518. * @param {HTMLElement} container
  6519. * @param {vis.DataSet | Array | DataTable} [items]
  6520. * @param {Object} [options] See Timeline.setOptions for the available options.
  6521. * @constructor
  6522. */
  6523. function Timeline (container, items, options) {
  6524. var me = this;
  6525. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6526. this.options = {
  6527. orientation: 'bottom',
  6528. min: null,
  6529. max: null,
  6530. zoomMin: 10, // milliseconds
  6531. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6532. // moveable: true, // TODO: option moveable
  6533. // zoomable: true, // TODO: option zoomable
  6534. showMinorLabels: true,
  6535. showMajorLabels: true,
  6536. showCurrentTime: false,
  6537. showCustomTime: false,
  6538. autoResize: false
  6539. };
  6540. // controller
  6541. this.controller = new Controller();
  6542. // root panel
  6543. if (!container) {
  6544. throw new Error('No container element provided');
  6545. }
  6546. var rootOptions = Object.create(this.options);
  6547. rootOptions.height = function () {
  6548. // TODO: change to height
  6549. if (me.options.height) {
  6550. // fixed height
  6551. return me.options.height;
  6552. }
  6553. else {
  6554. // auto height
  6555. return (me.timeaxis.height + me.content.height) + 'px';
  6556. }
  6557. };
  6558. this.rootPanel = new RootPanel(container, rootOptions);
  6559. this.controller.add(this.rootPanel);
  6560. // item panel
  6561. var itemOptions = Object.create(this.options);
  6562. itemOptions.left = function () {
  6563. return me.labelPanel.width;
  6564. };
  6565. itemOptions.width = function () {
  6566. return me.rootPanel.width - me.labelPanel.width;
  6567. };
  6568. itemOptions.top = null;
  6569. itemOptions.height = null;
  6570. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  6571. this.controller.add(this.itemPanel);
  6572. // label panel
  6573. var labelOptions = Object.create(this.options);
  6574. labelOptions.top = null;
  6575. labelOptions.left = null;
  6576. labelOptions.height = null;
  6577. labelOptions.width = function () {
  6578. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  6579. return me.content.getLabelsWidth();
  6580. }
  6581. else {
  6582. return 0;
  6583. }
  6584. };
  6585. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  6586. this.controller.add(this.labelPanel);
  6587. // range
  6588. var rangeOptions = Object.create(this.options);
  6589. this.range = new Range(rangeOptions);
  6590. this.range.setRange(
  6591. now.clone().add('days', -3).valueOf(),
  6592. now.clone().add('days', 4).valueOf()
  6593. );
  6594. // TODO: reckon with options moveable and zoomable
  6595. // TODO: put the listeners in setOptions, be able to dynamically change with options moveable and zoomable
  6596. this.range.subscribe(this.rootPanel, 'move', 'horizontal');
  6597. this.range.subscribe(this.rootPanel, 'zoom', 'horizontal');
  6598. this.range.on('rangechange', function (properties) {
  6599. var force = true;
  6600. me.controller.requestReflow(force);
  6601. me._trigger('rangechange', properties);
  6602. });
  6603. this.range.on('rangechanged', function (properties) {
  6604. var force = true;
  6605. me.controller.requestReflow(force);
  6606. me._trigger('rangechanged', properties);
  6607. });
  6608. // single select (or unselect) when tapping an item
  6609. // TODO: implement ctrl+click
  6610. this.rootPanel.on('tap', this._onSelectItem.bind(this));
  6611. // multi select when holding mouse/touch, or on ctrl+click
  6612. this.rootPanel.on('hold', this._onMultiSelectItem.bind(this));
  6613. // time axis
  6614. var timeaxisOptions = Object.create(rootOptions);
  6615. timeaxisOptions.range = this.range;
  6616. timeaxisOptions.left = null;
  6617. timeaxisOptions.top = null;
  6618. timeaxisOptions.width = '100%';
  6619. timeaxisOptions.height = null;
  6620. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6621. this.timeaxis.setRange(this.range);
  6622. this.controller.add(this.timeaxis);
  6623. // current time bar
  6624. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  6625. this.controller.add(this.currenttime);
  6626. // custom time bar
  6627. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  6628. this.controller.add(this.customtime);
  6629. // create groupset
  6630. this.setGroups(null);
  6631. this.itemsData = null; // DataSet
  6632. this.groupsData = null; // DataSet
  6633. // apply options
  6634. if (options) {
  6635. this.setOptions(options);
  6636. }
  6637. // create itemset and groupset
  6638. if (items) {
  6639. this.setItems(items);
  6640. }
  6641. }
  6642. /**
  6643. * Set options
  6644. * @param {Object} options TODO: describe the available options
  6645. */
  6646. Timeline.prototype.setOptions = function (options) {
  6647. util.extend(this.options, options);
  6648. // force update of range (apply new min/max etc.)
  6649. // both start and end are optional
  6650. this.range.setRange(options.start, options.end);
  6651. this.controller.reflow();
  6652. this.controller.repaint();
  6653. };
  6654. /**
  6655. * Set a custom time bar
  6656. * @param {Date} time
  6657. */
  6658. Timeline.prototype.setCustomTime = function (time) {
  6659. this.customtime._setCustomTime(time);
  6660. };
  6661. /**
  6662. * Retrieve the current custom time.
  6663. * @return {Date} customTime
  6664. */
  6665. Timeline.prototype.getCustomTime = function() {
  6666. return new Date(this.customtime.customTime.valueOf());
  6667. };
  6668. /**
  6669. * Set items
  6670. * @param {vis.DataSet | Array | DataTable | null} items
  6671. */
  6672. Timeline.prototype.setItems = function(items) {
  6673. var initialLoad = (this.itemsData == null);
  6674. // convert to type DataSet when needed
  6675. var newItemSet;
  6676. if (!items) {
  6677. newItemSet = null;
  6678. }
  6679. else if (items instanceof DataSet) {
  6680. newItemSet = items;
  6681. }
  6682. if (!(items instanceof DataSet)) {
  6683. newItemSet = new DataSet({
  6684. convert: {
  6685. start: 'Date',
  6686. end: 'Date'
  6687. }
  6688. });
  6689. newItemSet.add(items);
  6690. }
  6691. // set items
  6692. this.itemsData = newItemSet;
  6693. this.content.setItems(newItemSet);
  6694. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6695. // apply the data range as range
  6696. var dataRange = this.getItemRange();
  6697. // add 5% space on both sides
  6698. var start = dataRange.min;
  6699. var end = dataRange.max;
  6700. if (start != null && end != null) {
  6701. var interval = (end.valueOf() - start.valueOf());
  6702. if (interval <= 0) {
  6703. // prevent an empty interval
  6704. interval = 24 * 60 * 60 * 1000; // 1 day
  6705. }
  6706. start = new Date(start.valueOf() - interval * 0.05);
  6707. end = new Date(end.valueOf() + interval * 0.05);
  6708. }
  6709. // override specified start and/or end date
  6710. if (this.options.start != undefined) {
  6711. start = util.convert(this.options.start, 'Date');
  6712. }
  6713. if (this.options.end != undefined) {
  6714. end = util.convert(this.options.end, 'Date');
  6715. }
  6716. // apply range if there is a min or max available
  6717. if (start != null || end != null) {
  6718. this.range.setRange(start, end);
  6719. }
  6720. }
  6721. };
  6722. /**
  6723. * Set groups
  6724. * @param {vis.DataSet | Array | DataTable} groups
  6725. */
  6726. Timeline.prototype.setGroups = function(groups) {
  6727. var me = this;
  6728. this.groupsData = groups;
  6729. // switch content type between ItemSet or GroupSet when needed
  6730. var Type = this.groupsData ? GroupSet : ItemSet;
  6731. if (!(this.content instanceof Type)) {
  6732. // remove old content set
  6733. if (this.content) {
  6734. this.content.hide();
  6735. if (this.content.setItems) {
  6736. this.content.setItems(); // disconnect from items
  6737. }
  6738. if (this.content.setGroups) {
  6739. this.content.setGroups(); // disconnect from groups
  6740. }
  6741. this.controller.remove(this.content);
  6742. }
  6743. // create new content set
  6744. var options = Object.create(this.options);
  6745. util.extend(options, {
  6746. top: function () {
  6747. if (me.options.orientation == 'top') {
  6748. return me.timeaxis.height;
  6749. }
  6750. else {
  6751. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  6752. }
  6753. },
  6754. left: null,
  6755. width: '100%',
  6756. height: function () {
  6757. if (me.options.height) {
  6758. // fixed height
  6759. return me.itemPanel.height - me.timeaxis.height;
  6760. }
  6761. else {
  6762. // auto height
  6763. return null;
  6764. }
  6765. },
  6766. maxHeight: function () {
  6767. // TODO: change maxHeight to be a css string like '100%' or '300px'
  6768. if (me.options.maxHeight) {
  6769. if (!util.isNumber(me.options.maxHeight)) {
  6770. throw new TypeError('Number expected for property maxHeight');
  6771. }
  6772. return me.options.maxHeight - me.timeaxis.height;
  6773. }
  6774. else {
  6775. return null;
  6776. }
  6777. },
  6778. labelContainer: function () {
  6779. return me.labelPanel.getContainer();
  6780. }
  6781. });
  6782. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  6783. if (this.content.setRange) {
  6784. this.content.setRange(this.range);
  6785. }
  6786. if (this.content.setItems) {
  6787. this.content.setItems(this.itemsData);
  6788. }
  6789. if (this.content.setGroups) {
  6790. this.content.setGroups(this.groupsData);
  6791. }
  6792. this.controller.add(this.content);
  6793. }
  6794. };
  6795. /**
  6796. * Get the data range of the item set.
  6797. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6798. * When no minimum is found, min==null
  6799. * When no maximum is found, max==null
  6800. */
  6801. Timeline.prototype.getItemRange = function getItemRange() {
  6802. // calculate min from start filed
  6803. var itemsData = this.itemsData,
  6804. min = null,
  6805. max = null;
  6806. if (itemsData) {
  6807. // calculate the minimum value of the field 'start'
  6808. var minItem = itemsData.min('start');
  6809. min = minItem ? minItem.start.valueOf() : null;
  6810. // calculate maximum value of fields 'start' and 'end'
  6811. var maxStartItem = itemsData.max('start');
  6812. if (maxStartItem) {
  6813. max = maxStartItem.start.valueOf();
  6814. }
  6815. var maxEndItem = itemsData.max('end');
  6816. if (maxEndItem) {
  6817. if (max == null) {
  6818. max = maxEndItem.end.valueOf();
  6819. }
  6820. else {
  6821. max = Math.max(max, maxEndItem.end.valueOf());
  6822. }
  6823. }
  6824. }
  6825. return {
  6826. min: (min != null) ? new Date(min) : null,
  6827. max: (max != null) ? new Date(max) : null
  6828. };
  6829. };
  6830. /**
  6831. * Set selected items by their id. Replaces the current selection
  6832. * Unknown id's are silently ignored.
  6833. * @param {Array} [ids] An array with zero or more id's of the items to be
  6834. * selected. If ids is an empty array, all items will be
  6835. * unselected.
  6836. */
  6837. Timeline.prototype.setSelection = function setSelection (ids) {
  6838. if (this.content) this.content.setSelection(ids);
  6839. };
  6840. /**
  6841. * Get the selected items by their id
  6842. * @return {Array} ids The ids of the selected items
  6843. */
  6844. Timeline.prototype.getSelection = function getSelection() {
  6845. return this.content ? this.content.getSelection() : [];
  6846. };
  6847. /**
  6848. * Add event listener
  6849. * @param {String} event Event name. Available events:
  6850. * 'rangechange', 'rangechanged', 'select'
  6851. * @param {function} callback Callback function, invoked as callback(properties)
  6852. * where properties is an optional object containing
  6853. * event specific properties.
  6854. */
  6855. Timeline.prototype.on = function on (event, callback) {
  6856. var available = ['rangechange', 'rangechanged', 'select'];
  6857. if (available.indexOf(event) == -1) {
  6858. throw new Error('Unknown event "' + event + '". Choose from ' + available.join());
  6859. }
  6860. events.addListener(this, event, callback);
  6861. };
  6862. /**
  6863. * Remove an event listener
  6864. * @param {String} event Event name
  6865. * @param {function} callback Callback function
  6866. */
  6867. Timeline.prototype.off = function off (event, callback) {
  6868. events.removeListener(this, event, callback);
  6869. };
  6870. /**
  6871. * Trigger an event
  6872. * @param {String} event Event name, available events: 'rangechange',
  6873. * 'rangechanged', 'select'
  6874. * @param {Object} [properties] Event specific properties
  6875. * @private
  6876. */
  6877. Timeline.prototype._trigger = function _trigger(event, properties) {
  6878. events.trigger(this, event, properties || {});
  6879. };
  6880. /**
  6881. * Handle selecting/deselecting an item when tapping it
  6882. * @param {Event} event
  6883. * @private
  6884. */
  6885. Timeline.prototype._onSelectItem = function (event) {
  6886. var item = this._itemFromTarget(event);
  6887. var selection = item ? [item.id] : [];
  6888. this.setSelection(selection);
  6889. this._trigger('select', {
  6890. items: this.getSelection()
  6891. });
  6892. event.stopPropagation();
  6893. };
  6894. /**
  6895. * Handle selecting/deselecting multiple items when holding an item
  6896. * @param {Event} event
  6897. * @private
  6898. */
  6899. Timeline.prototype._onMultiSelectItem = function (event) {
  6900. var selection,
  6901. item = this._itemFromTarget(event);
  6902. if (!item) {
  6903. // do nothing...
  6904. return;
  6905. }
  6906. selection = this.getSelection(); // current selection
  6907. var index = selection.indexOf(item.id);
  6908. if (index == -1) {
  6909. // item is not yet selected -> select it
  6910. selection.push(item.id);
  6911. }
  6912. else {
  6913. // item is already selected -> deselect it
  6914. selection.splice(index, 1);
  6915. }
  6916. this.setSelection(selection);
  6917. this._trigger('select', {
  6918. items: this.getSelection()
  6919. });
  6920. event.stopPropagation();
  6921. };
  6922. /**
  6923. * Find an item from an event target:
  6924. * searches for the attribute 'timeline-item' in the event target's element tree
  6925. * @param {Event} event
  6926. * @return {Item | null| item
  6927. * @private
  6928. */
  6929. Timeline.prototype._itemFromTarget = function _itemFromTarget (event) {
  6930. var target = event.target;
  6931. while (target) {
  6932. if (target.hasOwnProperty('timeline-item')) {
  6933. return target['timeline-item'];
  6934. }
  6935. target = target.parentNode;
  6936. }
  6937. return null;
  6938. };
  6939. (function(exports) {
  6940. /**
  6941. * Parse a text source containing data in DOT language into a JSON object.
  6942. * The object contains two lists: one with nodes and one with edges.
  6943. *
  6944. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6945. *
  6946. * @param {String} data Text containing a graph in DOT-notation
  6947. * @return {Object} graph An object containing two parameters:
  6948. * {Object[]} nodes
  6949. * {Object[]} edges
  6950. */
  6951. function parseDOT (data) {
  6952. dot = data;
  6953. return parseGraph();
  6954. }
  6955. // token types enumeration
  6956. var TOKENTYPE = {
  6957. NULL : 0,
  6958. DELIMITER : 1,
  6959. IDENTIFIER: 2,
  6960. UNKNOWN : 3
  6961. };
  6962. // map with all delimiters
  6963. var DELIMITERS = {
  6964. '{': true,
  6965. '}': true,
  6966. '[': true,
  6967. ']': true,
  6968. ';': true,
  6969. '=': true,
  6970. ',': true,
  6971. '->': true,
  6972. '--': true
  6973. };
  6974. var dot = ''; // current dot file
  6975. var index = 0; // current index in dot file
  6976. var c = ''; // current token character in expr
  6977. var token = ''; // current token
  6978. var tokenType = TOKENTYPE.NULL; // type of the token
  6979. /**
  6980. * Get the first character from the dot file.
  6981. * The character is stored into the char c. If the end of the dot file is
  6982. * reached, the function puts an empty string in c.
  6983. */
  6984. function first() {
  6985. index = 0;
  6986. c = dot.charAt(0);
  6987. }
  6988. /**
  6989. * Get the next character from the dot file.
  6990. * The character is stored into the char c. If the end of the dot file is
  6991. * reached, the function puts an empty string in c.
  6992. */
  6993. function next() {
  6994. index++;
  6995. c = dot.charAt(index);
  6996. }
  6997. /**
  6998. * Preview the next character from the dot file.
  6999. * @return {String} cNext
  7000. */
  7001. function nextPreview() {
  7002. return dot.charAt(index + 1);
  7003. }
  7004. /**
  7005. * Test whether given character is alphabetic or numeric
  7006. * @param {String} c
  7007. * @return {Boolean} isAlphaNumeric
  7008. */
  7009. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  7010. function isAlphaNumeric(c) {
  7011. return regexAlphaNumeric.test(c);
  7012. }
  7013. /**
  7014. * Merge all properties of object b into object b
  7015. * @param {Object} a
  7016. * @param {Object} b
  7017. * @return {Object} a
  7018. */
  7019. function merge (a, b) {
  7020. if (!a) {
  7021. a = {};
  7022. }
  7023. if (b) {
  7024. for (var name in b) {
  7025. if (b.hasOwnProperty(name)) {
  7026. a[name] = b[name];
  7027. }
  7028. }
  7029. }
  7030. return a;
  7031. }
  7032. /**
  7033. * Set a value in an object, where the provided parameter name can be a
  7034. * path with nested parameters. For example:
  7035. *
  7036. * var obj = {a: 2};
  7037. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  7038. *
  7039. * @param {Object} obj
  7040. * @param {String} path A parameter name or dot-separated parameter path,
  7041. * like "color.highlight.border".
  7042. * @param {*} value
  7043. */
  7044. function setValue(obj, path, value) {
  7045. var keys = path.split('.');
  7046. var o = obj;
  7047. while (keys.length) {
  7048. var key = keys.shift();
  7049. if (keys.length) {
  7050. // this isn't the end point
  7051. if (!o[key]) {
  7052. o[key] = {};
  7053. }
  7054. o = o[key];
  7055. }
  7056. else {
  7057. // this is the end point
  7058. o[key] = value;
  7059. }
  7060. }
  7061. }
  7062. /**
  7063. * Add a node to a graph object. If there is already a node with
  7064. * the same id, their attributes will be merged.
  7065. * @param {Object} graph
  7066. * @param {Object} node
  7067. */
  7068. function addNode(graph, node) {
  7069. var i, len;
  7070. var current = null;
  7071. // find root graph (in case of subgraph)
  7072. var graphs = [graph]; // list with all graphs from current graph to root graph
  7073. var root = graph;
  7074. while (root.parent) {
  7075. graphs.push(root.parent);
  7076. root = root.parent;
  7077. }
  7078. // find existing node (at root level) by its id
  7079. if (root.nodes) {
  7080. for (i = 0, len = root.nodes.length; i < len; i++) {
  7081. if (node.id === root.nodes[i].id) {
  7082. current = root.nodes[i];
  7083. break;
  7084. }
  7085. }
  7086. }
  7087. if (!current) {
  7088. // this is a new node
  7089. current = {
  7090. id: node.id
  7091. };
  7092. if (graph.node) {
  7093. // clone default attributes
  7094. current.attr = merge(current.attr, graph.node);
  7095. }
  7096. }
  7097. // add node to this (sub)graph and all its parent graphs
  7098. for (i = graphs.length - 1; i >= 0; i--) {
  7099. var g = graphs[i];
  7100. if (!g.nodes) {
  7101. g.nodes = [];
  7102. }
  7103. if (g.nodes.indexOf(current) == -1) {
  7104. g.nodes.push(current);
  7105. }
  7106. }
  7107. // merge attributes
  7108. if (node.attr) {
  7109. current.attr = merge(current.attr, node.attr);
  7110. }
  7111. }
  7112. /**
  7113. * Add an edge to a graph object
  7114. * @param {Object} graph
  7115. * @param {Object} edge
  7116. */
  7117. function addEdge(graph, edge) {
  7118. if (!graph.edges) {
  7119. graph.edges = [];
  7120. }
  7121. graph.edges.push(edge);
  7122. if (graph.edge) {
  7123. var attr = merge({}, graph.edge); // clone default attributes
  7124. edge.attr = merge(attr, edge.attr); // merge attributes
  7125. }
  7126. }
  7127. /**
  7128. * Create an edge to a graph object
  7129. * @param {Object} graph
  7130. * @param {String | Number | Object} from
  7131. * @param {String | Number | Object} to
  7132. * @param {String} type
  7133. * @param {Object | null} attr
  7134. * @return {Object} edge
  7135. */
  7136. function createEdge(graph, from, to, type, attr) {
  7137. var edge = {
  7138. from: from,
  7139. to: to,
  7140. type: type
  7141. };
  7142. if (graph.edge) {
  7143. edge.attr = merge({}, graph.edge); // clone default attributes
  7144. }
  7145. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7146. return edge;
  7147. }
  7148. /**
  7149. * Get next token in the current dot file.
  7150. * The token and token type are available as token and tokenType
  7151. */
  7152. function getToken() {
  7153. tokenType = TOKENTYPE.NULL;
  7154. token = '';
  7155. // skip over whitespaces
  7156. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7157. next();
  7158. }
  7159. do {
  7160. var isComment = false;
  7161. // skip comment
  7162. if (c == '#') {
  7163. // find the previous non-space character
  7164. var i = index - 1;
  7165. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7166. i--;
  7167. }
  7168. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7169. // the # is at the start of a line, this is indeed a line comment
  7170. while (c != '' && c != '\n') {
  7171. next();
  7172. }
  7173. isComment = true;
  7174. }
  7175. }
  7176. if (c == '/' && nextPreview() == '/') {
  7177. // skip line comment
  7178. while (c != '' && c != '\n') {
  7179. next();
  7180. }
  7181. isComment = true;
  7182. }
  7183. if (c == '/' && nextPreview() == '*') {
  7184. // skip block comment
  7185. while (c != '') {
  7186. if (c == '*' && nextPreview() == '/') {
  7187. // end of block comment found. skip these last two characters
  7188. next();
  7189. next();
  7190. break;
  7191. }
  7192. else {
  7193. next();
  7194. }
  7195. }
  7196. isComment = true;
  7197. }
  7198. // skip over whitespaces
  7199. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7200. next();
  7201. }
  7202. }
  7203. while (isComment);
  7204. // check for end of dot file
  7205. if (c == '') {
  7206. // token is still empty
  7207. tokenType = TOKENTYPE.DELIMITER;
  7208. return;
  7209. }
  7210. // check for delimiters consisting of 2 characters
  7211. var c2 = c + nextPreview();
  7212. if (DELIMITERS[c2]) {
  7213. tokenType = TOKENTYPE.DELIMITER;
  7214. token = c2;
  7215. next();
  7216. next();
  7217. return;
  7218. }
  7219. // check for delimiters consisting of 1 character
  7220. if (DELIMITERS[c]) {
  7221. tokenType = TOKENTYPE.DELIMITER;
  7222. token = c;
  7223. next();
  7224. return;
  7225. }
  7226. // check for an identifier (number or string)
  7227. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7228. if (isAlphaNumeric(c) || c == '-') {
  7229. token += c;
  7230. next();
  7231. while (isAlphaNumeric(c)) {
  7232. token += c;
  7233. next();
  7234. }
  7235. if (token == 'false') {
  7236. token = false; // convert to boolean
  7237. }
  7238. else if (token == 'true') {
  7239. token = true; // convert to boolean
  7240. }
  7241. else if (!isNaN(Number(token))) {
  7242. token = Number(token); // convert to number
  7243. }
  7244. tokenType = TOKENTYPE.IDENTIFIER;
  7245. return;
  7246. }
  7247. // check for a string enclosed by double quotes
  7248. if (c == '"') {
  7249. next();
  7250. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7251. token += c;
  7252. if (c == '"') { // skip the escape character
  7253. next();
  7254. }
  7255. next();
  7256. }
  7257. if (c != '"') {
  7258. throw newSyntaxError('End of string " expected');
  7259. }
  7260. next();
  7261. tokenType = TOKENTYPE.IDENTIFIER;
  7262. return;
  7263. }
  7264. // something unknown is found, wrong characters, a syntax error
  7265. tokenType = TOKENTYPE.UNKNOWN;
  7266. while (c != '') {
  7267. token += c;
  7268. next();
  7269. }
  7270. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7271. }
  7272. /**
  7273. * Parse a graph.
  7274. * @returns {Object} graph
  7275. */
  7276. function parseGraph() {
  7277. var graph = {};
  7278. first();
  7279. getToken();
  7280. // optional strict keyword
  7281. if (token == 'strict') {
  7282. graph.strict = true;
  7283. getToken();
  7284. }
  7285. // graph or digraph keyword
  7286. if (token == 'graph' || token == 'digraph') {
  7287. graph.type = token;
  7288. getToken();
  7289. }
  7290. // optional graph id
  7291. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7292. graph.id = token;
  7293. getToken();
  7294. }
  7295. // open angle bracket
  7296. if (token != '{') {
  7297. throw newSyntaxError('Angle bracket { expected');
  7298. }
  7299. getToken();
  7300. // statements
  7301. parseStatements(graph);
  7302. // close angle bracket
  7303. if (token != '}') {
  7304. throw newSyntaxError('Angle bracket } expected');
  7305. }
  7306. getToken();
  7307. // end of file
  7308. if (token !== '') {
  7309. throw newSyntaxError('End of file expected');
  7310. }
  7311. getToken();
  7312. // remove temporary default properties
  7313. delete graph.node;
  7314. delete graph.edge;
  7315. delete graph.graph;
  7316. return graph;
  7317. }
  7318. /**
  7319. * Parse a list with statements.
  7320. * @param {Object} graph
  7321. */
  7322. function parseStatements (graph) {
  7323. while (token !== '' && token != '}') {
  7324. parseStatement(graph);
  7325. if (token == ';') {
  7326. getToken();
  7327. }
  7328. }
  7329. }
  7330. /**
  7331. * Parse a single statement. Can be a an attribute statement, node
  7332. * statement, a series of node statements and edge statements, or a
  7333. * parameter.
  7334. * @param {Object} graph
  7335. */
  7336. function parseStatement(graph) {
  7337. // parse subgraph
  7338. var subgraph = parseSubgraph(graph);
  7339. if (subgraph) {
  7340. // edge statements
  7341. parseEdge(graph, subgraph);
  7342. return;
  7343. }
  7344. // parse an attribute statement
  7345. var attr = parseAttributeStatement(graph);
  7346. if (attr) {
  7347. return;
  7348. }
  7349. // parse node
  7350. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7351. throw newSyntaxError('Identifier expected');
  7352. }
  7353. var id = token; // id can be a string or a number
  7354. getToken();
  7355. if (token == '=') {
  7356. // id statement
  7357. getToken();
  7358. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7359. throw newSyntaxError('Identifier expected');
  7360. }
  7361. graph[id] = token;
  7362. getToken();
  7363. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7364. }
  7365. else {
  7366. parseNodeStatement(graph, id);
  7367. }
  7368. }
  7369. /**
  7370. * Parse a subgraph
  7371. * @param {Object} graph parent graph object
  7372. * @return {Object | null} subgraph
  7373. */
  7374. function parseSubgraph (graph) {
  7375. var subgraph = null;
  7376. // optional subgraph keyword
  7377. if (token == 'subgraph') {
  7378. subgraph = {};
  7379. subgraph.type = 'subgraph';
  7380. getToken();
  7381. // optional graph id
  7382. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7383. subgraph.id = token;
  7384. getToken();
  7385. }
  7386. }
  7387. // open angle bracket
  7388. if (token == '{') {
  7389. getToken();
  7390. if (!subgraph) {
  7391. subgraph = {};
  7392. }
  7393. subgraph.parent = graph;
  7394. subgraph.node = graph.node;
  7395. subgraph.edge = graph.edge;
  7396. subgraph.graph = graph.graph;
  7397. // statements
  7398. parseStatements(subgraph);
  7399. // close angle bracket
  7400. if (token != '}') {
  7401. throw newSyntaxError('Angle bracket } expected');
  7402. }
  7403. getToken();
  7404. // remove temporary default properties
  7405. delete subgraph.node;
  7406. delete subgraph.edge;
  7407. delete subgraph.graph;
  7408. delete subgraph.parent;
  7409. // register at the parent graph
  7410. if (!graph.subgraphs) {
  7411. graph.subgraphs = [];
  7412. }
  7413. graph.subgraphs.push(subgraph);
  7414. }
  7415. return subgraph;
  7416. }
  7417. /**
  7418. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7419. * Available keywords are 'node', 'edge', 'graph'.
  7420. * The previous list with default attributes will be replaced
  7421. * @param {Object} graph
  7422. * @returns {String | null} keyword Returns the name of the parsed attribute
  7423. * (node, edge, graph), or null if nothing
  7424. * is parsed.
  7425. */
  7426. function parseAttributeStatement (graph) {
  7427. // attribute statements
  7428. if (token == 'node') {
  7429. getToken();
  7430. // node attributes
  7431. graph.node = parseAttributeList();
  7432. return 'node';
  7433. }
  7434. else if (token == 'edge') {
  7435. getToken();
  7436. // edge attributes
  7437. graph.edge = parseAttributeList();
  7438. return 'edge';
  7439. }
  7440. else if (token == 'graph') {
  7441. getToken();
  7442. // graph attributes
  7443. graph.graph = parseAttributeList();
  7444. return 'graph';
  7445. }
  7446. return null;
  7447. }
  7448. /**
  7449. * parse a node statement
  7450. * @param {Object} graph
  7451. * @param {String | Number} id
  7452. */
  7453. function parseNodeStatement(graph, id) {
  7454. // node statement
  7455. var node = {
  7456. id: id
  7457. };
  7458. var attr = parseAttributeList();
  7459. if (attr) {
  7460. node.attr = attr;
  7461. }
  7462. addNode(graph, node);
  7463. // edge statements
  7464. parseEdge(graph, id);
  7465. }
  7466. /**
  7467. * Parse an edge or a series of edges
  7468. * @param {Object} graph
  7469. * @param {String | Number} from Id of the from node
  7470. */
  7471. function parseEdge(graph, from) {
  7472. while (token == '->' || token == '--') {
  7473. var to;
  7474. var type = token;
  7475. getToken();
  7476. var subgraph = parseSubgraph(graph);
  7477. if (subgraph) {
  7478. to = subgraph;
  7479. }
  7480. else {
  7481. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7482. throw newSyntaxError('Identifier or subgraph expected');
  7483. }
  7484. to = token;
  7485. addNode(graph, {
  7486. id: to
  7487. });
  7488. getToken();
  7489. }
  7490. // parse edge attributes
  7491. var attr = parseAttributeList();
  7492. // create edge
  7493. var edge = createEdge(graph, from, to, type, attr);
  7494. addEdge(graph, edge);
  7495. from = to;
  7496. }
  7497. }
  7498. /**
  7499. * Parse a set with attributes,
  7500. * for example [label="1.000", shape=solid]
  7501. * @return {Object | null} attr
  7502. */
  7503. function parseAttributeList() {
  7504. var attr = null;
  7505. while (token == '[') {
  7506. getToken();
  7507. attr = {};
  7508. while (token !== '' && token != ']') {
  7509. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7510. throw newSyntaxError('Attribute name expected');
  7511. }
  7512. var name = token;
  7513. getToken();
  7514. if (token != '=') {
  7515. throw newSyntaxError('Equal sign = expected');
  7516. }
  7517. getToken();
  7518. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7519. throw newSyntaxError('Attribute value expected');
  7520. }
  7521. var value = token;
  7522. setValue(attr, name, value); // name can be a path
  7523. getToken();
  7524. if (token ==',') {
  7525. getToken();
  7526. }
  7527. }
  7528. if (token != ']') {
  7529. throw newSyntaxError('Bracket ] expected');
  7530. }
  7531. getToken();
  7532. }
  7533. return attr;
  7534. }
  7535. /**
  7536. * Create a syntax error with extra information on current token and index.
  7537. * @param {String} message
  7538. * @returns {SyntaxError} err
  7539. */
  7540. function newSyntaxError(message) {
  7541. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7542. }
  7543. /**
  7544. * Chop off text after a maximum length
  7545. * @param {String} text
  7546. * @param {Number} maxLength
  7547. * @returns {String}
  7548. */
  7549. function chop (text, maxLength) {
  7550. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7551. }
  7552. /**
  7553. * Execute a function fn for each pair of elements in two arrays
  7554. * @param {Array | *} array1
  7555. * @param {Array | *} array2
  7556. * @param {function} fn
  7557. */
  7558. function forEach2(array1, array2, fn) {
  7559. if (array1 instanceof Array) {
  7560. array1.forEach(function (elem1) {
  7561. if (array2 instanceof Array) {
  7562. array2.forEach(function (elem2) {
  7563. fn(elem1, elem2);
  7564. });
  7565. }
  7566. else {
  7567. fn(elem1, array2);
  7568. }
  7569. });
  7570. }
  7571. else {
  7572. if (array2 instanceof Array) {
  7573. array2.forEach(function (elem2) {
  7574. fn(array1, elem2);
  7575. });
  7576. }
  7577. else {
  7578. fn(array1, array2);
  7579. }
  7580. }
  7581. }
  7582. /**
  7583. * Convert a string containing a graph in DOT language into a map containing
  7584. * with nodes and edges in the format of graph.
  7585. * @param {String} data Text containing a graph in DOT-notation
  7586. * @return {Object} graphData
  7587. */
  7588. function DOTToGraph (data) {
  7589. // parse the DOT file
  7590. var dotData = parseDOT(data);
  7591. var graphData = {
  7592. nodes: [],
  7593. edges: [],
  7594. options: {}
  7595. };
  7596. // copy the nodes
  7597. if (dotData.nodes) {
  7598. dotData.nodes.forEach(function (dotNode) {
  7599. var graphNode = {
  7600. id: dotNode.id,
  7601. label: String(dotNode.label || dotNode.id)
  7602. };
  7603. merge(graphNode, dotNode.attr);
  7604. if (graphNode.image) {
  7605. graphNode.shape = 'image';
  7606. }
  7607. graphData.nodes.push(graphNode);
  7608. });
  7609. }
  7610. // copy the edges
  7611. if (dotData.edges) {
  7612. /**
  7613. * Convert an edge in DOT format to an edge with VisGraph format
  7614. * @param {Object} dotEdge
  7615. * @returns {Object} graphEdge
  7616. */
  7617. function convertEdge(dotEdge) {
  7618. var graphEdge = {
  7619. from: dotEdge.from,
  7620. to: dotEdge.to
  7621. };
  7622. merge(graphEdge, dotEdge.attr);
  7623. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  7624. return graphEdge;
  7625. }
  7626. dotData.edges.forEach(function (dotEdge) {
  7627. var from, to;
  7628. if (dotEdge.from instanceof Object) {
  7629. from = dotEdge.from.nodes;
  7630. }
  7631. else {
  7632. from = {
  7633. id: dotEdge.from
  7634. }
  7635. }
  7636. if (dotEdge.to instanceof Object) {
  7637. to = dotEdge.to.nodes;
  7638. }
  7639. else {
  7640. to = {
  7641. id: dotEdge.to
  7642. }
  7643. }
  7644. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  7645. dotEdge.from.edges.forEach(function (subEdge) {
  7646. var graphEdge = convertEdge(subEdge);
  7647. graphData.edges.push(graphEdge);
  7648. });
  7649. }
  7650. forEach2(from, to, function (from, to) {
  7651. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  7652. var graphEdge = convertEdge(subEdge);
  7653. graphData.edges.push(graphEdge);
  7654. });
  7655. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  7656. dotEdge.to.edges.forEach(function (subEdge) {
  7657. var graphEdge = convertEdge(subEdge);
  7658. graphData.edges.push(graphEdge);
  7659. });
  7660. }
  7661. });
  7662. }
  7663. // copy the options
  7664. if (dotData.attr) {
  7665. graphData.options = dotData.attr;
  7666. }
  7667. return graphData;
  7668. }
  7669. // exports
  7670. exports.parseDOT = parseDOT;
  7671. exports.DOTToGraph = DOTToGraph;
  7672. })(typeof util !== 'undefined' ? util : exports);
  7673. /**
  7674. * Canvas shapes used by the Graph
  7675. */
  7676. if (typeof CanvasRenderingContext2D !== 'undefined') {
  7677. /**
  7678. * Draw a circle shape
  7679. */
  7680. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  7681. this.beginPath();
  7682. this.arc(x, y, r, 0, 2*Math.PI, false);
  7683. };
  7684. /**
  7685. * Draw a square shape
  7686. * @param {Number} x horizontal center
  7687. * @param {Number} y vertical center
  7688. * @param {Number} r size, width and height of the square
  7689. */
  7690. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  7691. this.beginPath();
  7692. this.rect(x - r, y - r, r * 2, r * 2);
  7693. };
  7694. /**
  7695. * Draw a triangle shape
  7696. * @param {Number} x horizontal center
  7697. * @param {Number} y vertical center
  7698. * @param {Number} r radius, half the length of the sides of the triangle
  7699. */
  7700. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  7701. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7702. this.beginPath();
  7703. var s = r * 2;
  7704. var s2 = s / 2;
  7705. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7706. var h = Math.sqrt(s * s - s2 * s2); // height
  7707. this.moveTo(x, y - (h - ir));
  7708. this.lineTo(x + s2, y + ir);
  7709. this.lineTo(x - s2, y + ir);
  7710. this.lineTo(x, y - (h - ir));
  7711. this.closePath();
  7712. };
  7713. /**
  7714. * Draw a triangle shape in downward orientation
  7715. * @param {Number} x horizontal center
  7716. * @param {Number} y vertical center
  7717. * @param {Number} r radius
  7718. */
  7719. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  7720. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7721. this.beginPath();
  7722. var s = r * 2;
  7723. var s2 = s / 2;
  7724. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7725. var h = Math.sqrt(s * s - s2 * s2); // height
  7726. this.moveTo(x, y + (h - ir));
  7727. this.lineTo(x + s2, y - ir);
  7728. this.lineTo(x - s2, y - ir);
  7729. this.lineTo(x, y + (h - ir));
  7730. this.closePath();
  7731. };
  7732. /**
  7733. * Draw a star shape, a star with 5 points
  7734. * @param {Number} x horizontal center
  7735. * @param {Number} y vertical center
  7736. * @param {Number} r radius, half the length of the sides of the triangle
  7737. */
  7738. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  7739. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  7740. this.beginPath();
  7741. for (var n = 0; n < 10; n++) {
  7742. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  7743. this.lineTo(
  7744. x + radius * Math.sin(n * 2 * Math.PI / 10),
  7745. y - radius * Math.cos(n * 2 * Math.PI / 10)
  7746. );
  7747. }
  7748. this.closePath();
  7749. };
  7750. /**
  7751. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7752. */
  7753. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7754. var r2d = Math.PI/180;
  7755. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7756. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7757. this.beginPath();
  7758. this.moveTo(x+r,y);
  7759. this.lineTo(x+w-r,y);
  7760. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7761. this.lineTo(x+w,y+h-r);
  7762. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7763. this.lineTo(x+r,y+h);
  7764. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7765. this.lineTo(x,y+r);
  7766. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7767. };
  7768. /**
  7769. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7770. */
  7771. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7772. var kappa = .5522848,
  7773. ox = (w / 2) * kappa, // control point offset horizontal
  7774. oy = (h / 2) * kappa, // control point offset vertical
  7775. xe = x + w, // x-end
  7776. ye = y + h, // y-end
  7777. xm = x + w / 2, // x-middle
  7778. ym = y + h / 2; // y-middle
  7779. this.beginPath();
  7780. this.moveTo(x, ym);
  7781. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7782. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7783. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7784. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7785. };
  7786. /**
  7787. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7788. */
  7789. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7790. var f = 1/3;
  7791. var wEllipse = w;
  7792. var hEllipse = h * f;
  7793. var kappa = .5522848,
  7794. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7795. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7796. xe = x + wEllipse, // x-end
  7797. ye = y + hEllipse, // y-end
  7798. xm = x + wEllipse / 2, // x-middle
  7799. ym = y + hEllipse / 2, // y-middle
  7800. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7801. yeb = y + h; // y-end, bottom ellipse
  7802. this.beginPath();
  7803. this.moveTo(xe, ym);
  7804. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7805. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7806. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7807. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7808. this.lineTo(xe, ymb);
  7809. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7810. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7811. this.lineTo(x, ym);
  7812. };
  7813. /**
  7814. * Draw an arrow point (no line)
  7815. */
  7816. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  7817. // tail
  7818. var xt = x - length * Math.cos(angle);
  7819. var yt = y - length * Math.sin(angle);
  7820. // inner tail
  7821. // TODO: allow to customize different shapes
  7822. var xi = x - length * 0.9 * Math.cos(angle);
  7823. var yi = y - length * 0.9 * Math.sin(angle);
  7824. // left
  7825. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  7826. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  7827. // right
  7828. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  7829. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  7830. this.beginPath();
  7831. this.moveTo(x, y);
  7832. this.lineTo(xl, yl);
  7833. this.lineTo(xi, yi);
  7834. this.lineTo(xr, yr);
  7835. this.closePath();
  7836. };
  7837. /**
  7838. * Sets up the dashedLine functionality for drawing
  7839. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  7840. * @author David Jordan
  7841. * @date 2012-08-08
  7842. */
  7843. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  7844. if (!dashArray) dashArray=[10,5];
  7845. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  7846. var dashCount = dashArray.length;
  7847. this.moveTo(x, y);
  7848. var dx = (x2-x), dy = (y2-y);
  7849. var slope = dy/dx;
  7850. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  7851. var dashIndex=0, draw=true;
  7852. while (distRemaining>=0.1){
  7853. var dashLength = dashArray[dashIndex++%dashCount];
  7854. if (dashLength > distRemaining) dashLength = distRemaining;
  7855. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  7856. if (dx<0) xStep = -xStep;
  7857. x += xStep;
  7858. y += slope*xStep;
  7859. this[draw ? 'lineTo' : 'moveTo'](x,y);
  7860. distRemaining -= dashLength;
  7861. draw = !draw;
  7862. }
  7863. };
  7864. // TODO: add diamond shape
  7865. }
  7866. /**
  7867. * @class Node
  7868. * A node. A node can be connected to other nodes via one or multiple edges.
  7869. * @param {object} properties An object containing properties for the node. All
  7870. * properties are optional, except for the id.
  7871. * {number} id Id of the node. Required
  7872. * {string} label Text label for the node
  7873. * {number} x Horizontal position of the node
  7874. * {number} y Vertical position of the node
  7875. * {string} shape Node shape, available:
  7876. * "database", "circle", "ellipse",
  7877. * "box", "image", "text", "dot",
  7878. * "star", "triangle", "triangleDown",
  7879. * "square"
  7880. * {string} image An image url
  7881. * {string} title An title text, can be HTML
  7882. * {anytype} group A group name or number
  7883. * @param {Graph.Images} imagelist A list with images. Only needed
  7884. * when the node has an image
  7885. * @param {Graph.Groups} grouplist A list with groups. Needed for
  7886. * retrieving group properties
  7887. * @param {Object} constants An object with default values for
  7888. * example for the color
  7889. */
  7890. function Node(properties, imagelist, grouplist, constants) {
  7891. this.selected = false;
  7892. this.edges = []; // all edges connected to this node
  7893. this.dynamicEdges = [];
  7894. this.reroutedEdges = {};
  7895. this.group = constants.nodes.group;
  7896. this.fontSize = constants.nodes.fontSize;
  7897. this.fontFace = constants.nodes.fontFace;
  7898. this.fontColor = constants.nodes.fontColor;
  7899. this.color = constants.nodes.color;
  7900. // set defaults for the properties
  7901. this.id = undefined;
  7902. this.shape = constants.nodes.shape;
  7903. this.image = constants.nodes.image;
  7904. this.x = 0;
  7905. this.y = 0;
  7906. this.xFixed = false;
  7907. this.yFixed = false;
  7908. this.horizontalAlignLeft = true; // these are for the navigation controls
  7909. this.verticalAlignTop = true; // these are for the navigation controls
  7910. this.radius = constants.nodes.radius;
  7911. this.baseRadiusValue = constants.nodes.radius;
  7912. this.radiusFixed = false;
  7913. this.radiusMin = constants.nodes.radiusMin;
  7914. this.radiusMax = constants.nodes.radiusMax;
  7915. this.imagelist = imagelist;
  7916. this.grouplist = grouplist;
  7917. this.setProperties(properties, constants);
  7918. // creating the variables for clustering
  7919. this.resetCluster();
  7920. this.dynamicEdgesLength = 0;
  7921. this.clusterSession = 0;
  7922. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  7923. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  7924. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  7925. // mass, force, velocity
  7926. this.mass = 1; // kg (mass is adjusted for the number of connected edges)
  7927. this.fx = 0.0; // external force x
  7928. this.fy = 0.0; // external force y
  7929. this.vx = 0.0; // velocity x
  7930. this.vy = 0.0; // velocity y
  7931. this.minForce = constants.minForce;
  7932. this.damping = 0.9;
  7933. this.dampingFactor = 75;
  7934. this.graphScaleInv = 1;
  7935. this.canvasTopLeft = {"x": -300, "y": -300};
  7936. this.canvasBottomRight = {"x": 300, "y": 300};
  7937. }
  7938. /**
  7939. * (re)setting the clustering variables and objects
  7940. */
  7941. Node.prototype.resetCluster = function() {
  7942. // clustering variables
  7943. this.formationScale = undefined; // this is used to determine when to open the cluster
  7944. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  7945. this.containedNodes = {};
  7946. this.containedEdges = {};
  7947. this.clusterSessions = [];
  7948. };
  7949. /**
  7950. * Attach a edge to the node
  7951. * @param {Edge} edge
  7952. */
  7953. Node.prototype.attachEdge = function(edge) {
  7954. if (this.edges.indexOf(edge) == -1) {
  7955. this.edges.push(edge);
  7956. }
  7957. if (this.dynamicEdges.indexOf(edge) == -1) {
  7958. this.dynamicEdges.push(edge);
  7959. }
  7960. this.dynamicEdgesLength = this.dynamicEdges.length;
  7961. this._updateMass();
  7962. };
  7963. /**
  7964. * Detach a edge from the node
  7965. * @param {Edge} edge
  7966. */
  7967. Node.prototype.detachEdge = function(edge) {
  7968. var index = this.edges.indexOf(edge);
  7969. if (index != -1) {
  7970. this.edges.splice(index, 1);
  7971. this.dynamicEdges.splice(index, 1);
  7972. }
  7973. this.dynamicEdgesLength = this.dynamicEdges.length;
  7974. this._updateMass();
  7975. };
  7976. /**
  7977. * Update the nodes mass, which is determined by the number of edges connecting
  7978. * to it (more edges -> heavier node).
  7979. * @private
  7980. */
  7981. Node.prototype._updateMass = function() {
  7982. this.mass = 1 + 0.6 * this.edges.length; // kg
  7983. };
  7984. /**
  7985. * Set or overwrite properties for the node
  7986. * @param {Object} properties an object with properties
  7987. * @param {Object} constants and object with default, global properties
  7988. */
  7989. Node.prototype.setProperties = function(properties, constants) {
  7990. if (!properties) {
  7991. return;
  7992. }
  7993. this.originalLabel = undefined;
  7994. // basic properties
  7995. if (properties.id !== undefined) {this.id = properties.id;}
  7996. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  7997. if (properties.title !== undefined) {this.title = properties.title;}
  7998. if (properties.group !== undefined) {this.group = properties.group;}
  7999. if (properties.x !== undefined) {this.x = properties.x;}
  8000. if (properties.y !== undefined) {this.y = properties.y;}
  8001. if (properties.value !== undefined) {this.value = properties.value;}
  8002. // navigation controls properties
  8003. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  8004. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  8005. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  8006. if (this.id === undefined) {
  8007. throw "Node must have an id";
  8008. }
  8009. // copy group properties
  8010. if (this.group) {
  8011. var groupObj = this.grouplist.get(this.group);
  8012. for (var prop in groupObj) {
  8013. if (groupObj.hasOwnProperty(prop)) {
  8014. this[prop] = groupObj[prop];
  8015. }
  8016. }
  8017. }
  8018. // individual shape properties
  8019. if (properties.shape !== undefined) {this.shape = properties.shape;}
  8020. if (properties.image !== undefined) {this.image = properties.image;}
  8021. if (properties.radius !== undefined) {this.radius = properties.radius;}
  8022. if (properties.color !== undefined) {this.color = Node.parseColor(properties.color);}
  8023. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8024. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8025. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8026. if (this.image !== undefined) {
  8027. if (this.imagelist) {
  8028. this.imageObj = this.imagelist.load(this.image);
  8029. }
  8030. else {
  8031. throw "No imagelist provided";
  8032. }
  8033. }
  8034. this.xFixed = this.xFixed || (properties.x !== undefined);
  8035. this.yFixed = this.yFixed || (properties.y !== undefined);
  8036. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  8037. if (this.shape == 'image') {
  8038. this.radiusMin = constants.nodes.widthMin;
  8039. this.radiusMax = constants.nodes.widthMax;
  8040. }
  8041. // choose draw method depending on the shape
  8042. switch (this.shape) {
  8043. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  8044. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  8045. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  8046. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8047. // TODO: add diamond shape
  8048. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  8049. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  8050. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  8051. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  8052. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  8053. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  8054. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  8055. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8056. }
  8057. // reset the size of the node, this can be changed
  8058. this._reset();
  8059. };
  8060. /**
  8061. * Parse a color property into an object with border, background, and
  8062. * hightlight colors
  8063. * @param {Object | String} color
  8064. * @return {Object} colorObject
  8065. */
  8066. Node.parseColor = function(color) {
  8067. var c;
  8068. if (util.isString(color)) {
  8069. c = {
  8070. border: color,
  8071. background: color,
  8072. highlight: {
  8073. border: color,
  8074. background: color
  8075. }
  8076. };
  8077. // TODO: automatically generate a nice highlight color
  8078. }
  8079. else {
  8080. c = {};
  8081. c.background = color.background || 'white';
  8082. c.border = color.border || c.background;
  8083. if (util.isString(color.highlight)) {
  8084. c.highlight = {
  8085. border: color.highlight,
  8086. background: color.highlight
  8087. }
  8088. }
  8089. else {
  8090. c.highlight = {};
  8091. c.highlight.background = color.highlight && color.highlight.background || c.background;
  8092. c.highlight.border = color.highlight && color.highlight.border || c.border;
  8093. }
  8094. }
  8095. return c;
  8096. };
  8097. /**
  8098. * select this node
  8099. */
  8100. Node.prototype.select = function() {
  8101. this.selected = true;
  8102. this._reset();
  8103. };
  8104. /**
  8105. * unselect this node
  8106. */
  8107. Node.prototype.unselect = function() {
  8108. this.selected = false;
  8109. this._reset();
  8110. };
  8111. /**
  8112. * Reset the calculated size of the node, forces it to recalculate its size
  8113. */
  8114. Node.prototype.clearSizeCache = function() {
  8115. this._reset();
  8116. };
  8117. /**
  8118. * Reset the calculated size of the node, forces it to recalculate its size
  8119. * @private
  8120. */
  8121. Node.prototype._reset = function() {
  8122. this.width = undefined;
  8123. this.height = undefined;
  8124. };
  8125. /**
  8126. * get the title of this node.
  8127. * @return {string} title The title of the node, or undefined when no title
  8128. * has been set.
  8129. */
  8130. Node.prototype.getTitle = function() {
  8131. return this.title;
  8132. };
  8133. /**
  8134. * Calculate the distance to the border of the Node
  8135. * @param {CanvasRenderingContext2D} ctx
  8136. * @param {Number} angle Angle in radians
  8137. * @returns {number} distance Distance to the border in pixels
  8138. */
  8139. Node.prototype.distanceToBorder = function (ctx, angle) {
  8140. var borderWidth = 1;
  8141. if (!this.width) {
  8142. this.resize(ctx);
  8143. }
  8144. //noinspection FallthroughInSwitchStatementJS
  8145. switch (this.shape) {
  8146. case 'circle':
  8147. case 'dot':
  8148. return this.radius + borderWidth;
  8149. case 'ellipse':
  8150. var a = this.width / 2;
  8151. var b = this.height / 2;
  8152. var w = (Math.sin(angle) * a);
  8153. var h = (Math.cos(angle) * b);
  8154. return a * b / Math.sqrt(w * w + h * h);
  8155. // TODO: implement distanceToBorder for database
  8156. // TODO: implement distanceToBorder for triangle
  8157. // TODO: implement distanceToBorder for triangleDown
  8158. case 'box':
  8159. case 'image':
  8160. case 'text':
  8161. default:
  8162. if (this.width) {
  8163. return Math.min(
  8164. Math.abs(this.width / 2 / Math.cos(angle)),
  8165. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8166. // TODO: reckon with border radius too in case of box
  8167. }
  8168. else {
  8169. return 0;
  8170. }
  8171. }
  8172. // TODO: implement calculation of distance to border for all shapes
  8173. };
  8174. /**
  8175. * Set forces acting on the node
  8176. * @param {number} fx Force in horizontal direction
  8177. * @param {number} fy Force in vertical direction
  8178. */
  8179. Node.prototype._setForce = function(fx, fy) {
  8180. this.fx = fx;
  8181. this.fy = fy;
  8182. };
  8183. /**
  8184. * Add forces acting on the node
  8185. * @param {number} fx Force in horizontal direction
  8186. * @param {number} fy Force in vertical direction
  8187. * @private
  8188. */
  8189. Node.prototype._addForce = function(fx, fy) {
  8190. this.fx += fx;
  8191. this.fy += fy;
  8192. };
  8193. /**
  8194. * Perform one discrete step for the node
  8195. * @param {number} interval Time interval in seconds
  8196. */
  8197. Node.prototype.discreteStep = function(interval) {
  8198. if (!this.xFixed) {
  8199. var dx = -this.damping * this.vx; // damping force
  8200. var ax = (this.fx + dx) / this.mass; // acceleration
  8201. this.vx += ax * interval; // velocity
  8202. this.x += this.vx * interval; // position
  8203. }
  8204. if (!this.yFixed) {
  8205. var dy = -this.damping * this.vy; // damping force
  8206. var ay = (this.fy + dy) / this.mass; // acceleration
  8207. this.vy += ay * interval; // velocity
  8208. this.y += this.vy * interval; // position
  8209. }
  8210. };
  8211. /**
  8212. * Check if this node has a fixed x and y position
  8213. * @return {boolean} true if fixed, false if not
  8214. */
  8215. Node.prototype.isFixed = function() {
  8216. return (this.xFixed && this.yFixed);
  8217. };
  8218. /**
  8219. * Check if this node is moving
  8220. * @param {number} vmin the minimum velocity considered as "moving"
  8221. * @return {boolean} true if moving, false if it has no velocity
  8222. */
  8223. // TODO: replace this method with calculating the kinetic energy
  8224. Node.prototype.isMoving = function(vmin) {
  8225. if (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin) {
  8226. // console.log(vmin,this.vx,this.vy);
  8227. return true;
  8228. }
  8229. else {
  8230. this.vx = 0; this.vy = 0;
  8231. return false;
  8232. }
  8233. //return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8234. };
  8235. /**
  8236. * check if this node is selecte
  8237. * @return {boolean} selected True if node is selected, else false
  8238. */
  8239. Node.prototype.isSelected = function() {
  8240. return this.selected;
  8241. };
  8242. /**
  8243. * Retrieve the value of the node. Can be undefined
  8244. * @return {Number} value
  8245. */
  8246. Node.prototype.getValue = function() {
  8247. return this.value;
  8248. };
  8249. /**
  8250. * Calculate the distance from the nodes location to the given location (x,y)
  8251. * @param {Number} x
  8252. * @param {Number} y
  8253. * @return {Number} value
  8254. */
  8255. Node.prototype.getDistance = function(x, y) {
  8256. var dx = this.x - x,
  8257. dy = this.y - y;
  8258. return Math.sqrt(dx * dx + dy * dy);
  8259. };
  8260. /**
  8261. * Adjust the value range of the node. The node will adjust it's radius
  8262. * based on its value.
  8263. * @param {Number} min
  8264. * @param {Number} max
  8265. */
  8266. Node.prototype.setValueRange = function(min, max) {
  8267. if (!this.radiusFixed && this.value !== undefined) {
  8268. if (max == min) {
  8269. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8270. }
  8271. else {
  8272. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8273. this.radius = (this.value - min) * scale + this.radiusMin;
  8274. }
  8275. }
  8276. this.baseRadiusValue = this.radius;
  8277. };
  8278. /**
  8279. * Draw this node in the given canvas
  8280. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8281. * @param {CanvasRenderingContext2D} ctx
  8282. */
  8283. Node.prototype.draw = function(ctx) {
  8284. throw "Draw method not initialized for node";
  8285. };
  8286. /**
  8287. * Recalculate the size of this node in the given canvas
  8288. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8289. * @param {CanvasRenderingContext2D} ctx
  8290. */
  8291. Node.prototype.resize = function(ctx) {
  8292. throw "Resize method not initialized for node";
  8293. };
  8294. /**
  8295. * Check if this object is overlapping with the provided object
  8296. * @param {Object} obj an object with parameters left, top, right, bottom
  8297. * @return {boolean} True if location is located on node
  8298. */
  8299. Node.prototype.isOverlappingWith = function(obj) {
  8300. return (this.left < obj.right &&
  8301. this.left + this.width > obj.left &&
  8302. this.top < obj.bottom &&
  8303. this.top + this.height > obj.top);
  8304. };
  8305. Node.prototype._resizeImage = function (ctx) {
  8306. // TODO: pre calculate the image size
  8307. if (!this.width || !this.height) { // undefined or 0
  8308. var width, height;
  8309. if (this.value) {
  8310. this.radius = this.baseRadiusValue;
  8311. var scale = this.imageObj.height / this.imageObj.width;
  8312. if (scale !== undefined) {
  8313. width = this.radius || this.imageObj.width;
  8314. height = this.radius * scale || this.imageObj.height;
  8315. }
  8316. else {
  8317. width = 0;
  8318. height = 0;
  8319. }
  8320. }
  8321. else {
  8322. width = this.imageObj.width;
  8323. height = this.imageObj.height;
  8324. }
  8325. this.width = width;
  8326. this.height = height;
  8327. if (this.width > 0 && this.height > 0) {
  8328. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8329. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8330. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8331. }
  8332. }
  8333. };
  8334. Node.prototype._drawImage = function (ctx) {
  8335. this._resizeImage(ctx);
  8336. this.left = this.x - this.width / 2;
  8337. this.top = this.y - this.height / 2;
  8338. var yLabel;
  8339. if (this.imageObj.width != 0 ) {
  8340. // draw the shade
  8341. if (this.clusterSize > 1) {
  8342. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8343. lineWidth *= this.graphScaleInv;
  8344. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8345. ctx.globalAlpha = 0.5;
  8346. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8347. }
  8348. // draw the image
  8349. ctx.globalAlpha = 1.0;
  8350. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8351. yLabel = this.y + this.height / 2;
  8352. }
  8353. else {
  8354. // image still loading... just draw the label for now
  8355. yLabel = this.y;
  8356. }
  8357. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8358. };
  8359. Node.prototype._resizeBox = function (ctx) {
  8360. if (!this.width) {
  8361. var margin = 5;
  8362. var textSize = this.getTextSize(ctx);
  8363. this.width = textSize.width + 2 * margin;
  8364. this.height = textSize.height + 2 * margin;
  8365. this.width += (this.clusterSize - 1) * 0.5 * this.clusterSizeWidthFactor;
  8366. this.height += (this.clusterSize - 1) * 0.5 * this.clusterSizeHeightFactor;
  8367. // this.radius += (this.clusterSize - 1) * 0.5 * this.clusterSizeRadiusFactor;
  8368. }
  8369. };
  8370. Node.prototype._drawBox = function (ctx) {
  8371. this._resizeBox(ctx);
  8372. this.left = this.x - this.width / 2;
  8373. this.top = this.y - this.height / 2;
  8374. var clusterLineWidth = 2.5;
  8375. var selectionLineWidth = 2;
  8376. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8377. // draw the outer border
  8378. if (this.clusterSize > 1) {
  8379. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8380. ctx.lineWidth *= this.graphScaleInv;
  8381. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8382. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8383. ctx.stroke();
  8384. }
  8385. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8386. ctx.lineWidth *= this.graphScaleInv;
  8387. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8388. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8389. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8390. ctx.fill();
  8391. ctx.stroke();
  8392. this._label(ctx, this.label, this.x, this.y);
  8393. };
  8394. Node.prototype._resizeDatabase = function (ctx) {
  8395. if (!this.width) {
  8396. var margin = 5;
  8397. var textSize = this.getTextSize(ctx);
  8398. var size = textSize.width + 2 * margin;
  8399. this.width = size;
  8400. this.height = size;
  8401. // scaling used for clustering
  8402. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8403. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8404. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8405. }
  8406. };
  8407. Node.prototype._drawDatabase = function (ctx) {
  8408. this._resizeDatabase(ctx);
  8409. this.left = this.x - this.width / 2;
  8410. this.top = this.y - this.height / 2;
  8411. var clusterLineWidth = 2.5;
  8412. var selectionLineWidth = 2;
  8413. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8414. // draw the outer border
  8415. if (this.clusterSize > 1) {
  8416. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8417. ctx.lineWidth *= this.graphScaleInv;
  8418. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8419. ctx.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);
  8420. ctx.stroke();
  8421. }
  8422. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8423. ctx.lineWidth *= this.graphScaleInv;
  8424. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8425. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8426. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8427. ctx.fill();
  8428. ctx.stroke();
  8429. this._label(ctx, this.label, this.x, this.y);
  8430. };
  8431. Node.prototype._resizeCircle = function (ctx) {
  8432. if (!this.width) {
  8433. var margin = 5;
  8434. var textSize = this.getTextSize(ctx);
  8435. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8436. this.radius = diameter / 2;
  8437. this.width = diameter;
  8438. this.height = diameter;
  8439. // scaling used for clustering
  8440. // this.width += (this.clusterSize - 1) * 0.5 * this.clusterSizeWidthFactor;
  8441. // this.height += (this.clusterSize - 1) * 0.5 * this.clusterSizeHeightFactor;
  8442. this.radius += (this.clusterSize - 1) * 0.5 * this.clusterSizeRadiusFactor;
  8443. }
  8444. };
  8445. Node.prototype._drawCircle = function (ctx) {
  8446. this._resizeCircle(ctx);
  8447. this.left = this.x - this.width / 2;
  8448. this.top = this.y - this.height / 2;
  8449. var clusterLineWidth = 2.5;
  8450. var selectionLineWidth = 2;
  8451. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8452. // draw the outer border
  8453. if (this.clusterSize > 1) {
  8454. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8455. ctx.lineWidth *= this.graphScaleInv;
  8456. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8457. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8458. ctx.stroke();
  8459. }
  8460. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8461. ctx.lineWidth *= this.graphScaleInv;
  8462. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8463. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8464. ctx.circle(this.x, this.y, this.radius);
  8465. ctx.fill();
  8466. ctx.stroke();
  8467. this._label(ctx, this.label, this.x, this.y);
  8468. };
  8469. Node.prototype._resizeEllipse = function (ctx) {
  8470. if (!this.width) {
  8471. var textSize = this.getTextSize(ctx);
  8472. this.width = textSize.width * 1.5;
  8473. this.height = textSize.height * 2;
  8474. if (this.width < this.height) {
  8475. this.width = this.height;
  8476. }
  8477. // scaling used for clustering
  8478. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8479. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8480. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8481. }
  8482. };
  8483. Node.prototype._drawEllipse = function (ctx) {
  8484. this._resizeEllipse(ctx);
  8485. this.left = this.x - this.width / 2;
  8486. this.top = this.y - this.height / 2;
  8487. var clusterLineWidth = 2.5;
  8488. var selectionLineWidth = 2;
  8489. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8490. // draw the outer border
  8491. if (this.clusterSize > 1) {
  8492. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8493. ctx.lineWidth *= this.graphScaleInv;
  8494. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8495. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8496. ctx.stroke();
  8497. }
  8498. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8499. ctx.lineWidth *= this.graphScaleInv;
  8500. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8501. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8502. ctx.ellipse(this.left, this.top, this.width, this.height);
  8503. ctx.fill();
  8504. ctx.stroke();
  8505. this._label(ctx, this.label, this.x, this.y);
  8506. };
  8507. Node.prototype._drawDot = function (ctx) {
  8508. this._drawShape(ctx, 'circle');
  8509. };
  8510. Node.prototype._drawTriangle = function (ctx) {
  8511. this._drawShape(ctx, 'triangle');
  8512. };
  8513. Node.prototype._drawTriangleDown = function (ctx) {
  8514. this._drawShape(ctx, 'triangleDown');
  8515. };
  8516. Node.prototype._drawSquare = function (ctx) {
  8517. this._drawShape(ctx, 'square');
  8518. };
  8519. Node.prototype._drawStar = function (ctx) {
  8520. this._drawShape(ctx, 'star');
  8521. };
  8522. Node.prototype._resizeShape = function (ctx) {
  8523. if (!this.width) {
  8524. this.radius = this.baseRadiusValue;
  8525. var size = 2 * this.radius;
  8526. this.width = size;
  8527. this.height = size;
  8528. // scaling used for clustering
  8529. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8530. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8531. this.radius += (this.clusterSize - 1) * 0.5 * this.clusterSizeRadiusFactor;
  8532. }
  8533. };
  8534. Node.prototype._drawShape = function (ctx, shape) {
  8535. this._resizeShape(ctx);
  8536. this.left = this.x - this.width / 2;
  8537. this.top = this.y - this.height / 2;
  8538. var clusterLineWidth = 2.5;
  8539. var selectionLineWidth = 2;
  8540. var radiusMultiplier = 2;
  8541. // choose draw method depending on the shape
  8542. switch (shape) {
  8543. case 'dot': radiusMultiplier = 2; break;
  8544. case 'square': radiusMultiplier = 2; break;
  8545. case 'triangle': radiusMultiplier = 3; break;
  8546. case 'triangleDown': radiusMultiplier = 3; break;
  8547. case 'star': radiusMultiplier = 4; break;
  8548. }
  8549. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8550. // draw the outer border
  8551. if (this.clusterSize > 1) {
  8552. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8553. ctx.lineWidth *= this.graphScaleInv;
  8554. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8555. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8556. ctx.stroke();
  8557. }
  8558. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8559. ctx.lineWidth *= this.graphScaleInv;
  8560. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8561. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8562. ctx[shape](this.x, this.y, this.radius);
  8563. ctx.fill();
  8564. ctx.stroke();
  8565. if (this.label) {
  8566. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8567. }
  8568. };
  8569. Node.prototype._resizeText = function (ctx) {
  8570. if (!this.width) {
  8571. var margin = 5;
  8572. var textSize = this.getTextSize(ctx);
  8573. this.width = textSize.width + 2 * margin;
  8574. this.height = textSize.height + 2 * margin;
  8575. // scaling used for clustering
  8576. this.width += (this.clusterSize - 1) * this.clusterSizeWidthFactor;
  8577. this.height += (this.clusterSize - 1) * this.clusterSizeHeightFactor;
  8578. this.radius += (this.clusterSize - 1) * this.clusterSizeRadiusFactor;
  8579. }
  8580. };
  8581. Node.prototype._drawText = function (ctx) {
  8582. this._resizeText(ctx);
  8583. this.left = this.x - this.width / 2;
  8584. this.top = this.y - this.height / 2;
  8585. this._label(ctx, this.label, this.x, this.y);
  8586. };
  8587. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  8588. if (text) {
  8589. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8590. ctx.fillStyle = this.fontColor || "black";
  8591. ctx.textAlign = align || "center";
  8592. ctx.textBaseline = baseline || "middle";
  8593. var lines = text.split('\n'),
  8594. lineCount = lines.length,
  8595. fontSize = (this.fontSize + 4),
  8596. yLine = y + (1 - lineCount) / 2 * fontSize;
  8597. for (var i = 0; i < lineCount; i++) {
  8598. ctx.fillText(lines[i], x, yLine);
  8599. yLine += fontSize;
  8600. }
  8601. }
  8602. };
  8603. Node.prototype.getTextSize = function(ctx) {
  8604. if (this.label !== undefined) {
  8605. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8606. var lines = this.label.split('\n'),
  8607. height = (this.fontSize + 4) * lines.length,
  8608. width = 0;
  8609. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  8610. width = Math.max(width, ctx.measureText(lines[i]).width);
  8611. }
  8612. return {"width": width, "height": height};
  8613. }
  8614. else {
  8615. return {"width": 0, "height": 0};
  8616. }
  8617. };
  8618. /**
  8619. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  8620. * there is a safety margin of 0.3 * width;
  8621. *
  8622. * @returns {boolean}
  8623. */
  8624. Node.prototype.inArea = function() {
  8625. if (this.width !== undefined) {
  8626. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  8627. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  8628. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  8629. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  8630. }
  8631. else {
  8632. return true;
  8633. }
  8634. }
  8635. /**
  8636. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  8637. * @returns {boolean}
  8638. */
  8639. Node.prototype.inView = function() {
  8640. return (this.x >= this.canvasTopLeft.x &&
  8641. this.x < this.canvasBottomRight.x &&
  8642. this.y >= this.canvasTopLeft.y &&
  8643. this.y < this.canvasBottomRight.y);
  8644. }
  8645. /**
  8646. * This allows the zoom level of the graph to influence the rendering
  8647. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  8648. *
  8649. * @param scale
  8650. * @param canvasTopLeft
  8651. * @param canvasBottomRight
  8652. */
  8653. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  8654. this.graphScaleInv = 1.0/scale;
  8655. this.canvasTopLeft = canvasTopLeft;
  8656. this.canvasBottomRight = canvasBottomRight;
  8657. };
  8658. /**
  8659. * This allows the zoom level of the graph to influence the rendering
  8660. *
  8661. * @param scale
  8662. */
  8663. Node.prototype.setScale = function(scale) {
  8664. this.graphScaleInv = 1.0/scale;
  8665. };
  8666. /**
  8667. * This function updates the damping parameter for clusters, based ont he
  8668. *
  8669. * @param {Number} numberOfNodes
  8670. */
  8671. Node.prototype.updateDamping = function(numberOfNodes) {
  8672. this.damping = (0.8 + 0.1*this.clusterSize * (1 + Math.pow(numberOfNodes,-2)));
  8673. this.damping *= this.dampingFactor;
  8674. };
  8675. /**
  8676. * set the velocity at 0. Is called when this node is contained in another during clustering
  8677. */
  8678. Node.prototype.clearVelocity = function() {
  8679. this.vx = 0;
  8680. this.vy = 0;
  8681. };
  8682. /**
  8683. * Basic preservation of (kinectic) energy
  8684. *
  8685. * @param massBeforeClustering
  8686. */
  8687. Node.prototype.updateVelocity = function(massBeforeClustering) {
  8688. var energyBefore = this.vx * this.vx * massBeforeClustering;
  8689. this.vx = Math.sqrt(energyBefore/this.mass);
  8690. energyBefore = this.vy * this.vy * massBeforeClustering;
  8691. this.vy = Math.sqrt(energyBefore/this.mass);
  8692. };
  8693. /**
  8694. * @class Edge
  8695. *
  8696. * A edge connects two nodes
  8697. * @param {Object} properties Object with properties. Must contain
  8698. * At least properties from and to.
  8699. * Available properties: from (number),
  8700. * to (number), label (string, color (string),
  8701. * width (number), style (string),
  8702. * length (number), title (string)
  8703. * @param {Graph} graph A graph object, used to find and edge to
  8704. * nodes.
  8705. * @param {Object} constants An object with default values for
  8706. * example for the color
  8707. */
  8708. function Edge (properties, graph, constants) {
  8709. if (!graph) {
  8710. throw "No graph provided";
  8711. }
  8712. this.graph = graph;
  8713. // initialize constants
  8714. this.widthMin = constants.edges.widthMin;
  8715. this.widthMax = constants.edges.widthMax;
  8716. // initialize variables
  8717. this.id = undefined;
  8718. this.fromId = undefined;
  8719. this.toId = undefined;
  8720. this.style = constants.edges.style;
  8721. this.title = undefined;
  8722. this.width = constants.edges.width;
  8723. this.value = undefined;
  8724. this.length = constants.edges.length;
  8725. this.from = null; // a node
  8726. this.to = null; // a node
  8727. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  8728. // by storing the original information we can revert to the original connection when the cluser is opened.
  8729. this.originalFromId = [];
  8730. this.originalToId = [];
  8731. this.connected = false;
  8732. // Added to support dashed lines
  8733. // David Jordan
  8734. // 2012-08-08
  8735. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  8736. this.stiffness = undefined; // depends on the length of the edge
  8737. this.color = constants.edges.color;
  8738. this.widthFixed = false;
  8739. this.lengthFixed = false;
  8740. this.setProperties(properties, constants);
  8741. }
  8742. /**
  8743. * Set or overwrite properties for the edge
  8744. * @param {Object} properties an object with properties
  8745. * @param {Object} constants and object with default, global properties
  8746. */
  8747. Edge.prototype.setProperties = function(properties, constants) {
  8748. if (!properties) {
  8749. return;
  8750. }
  8751. if (properties.from !== undefined) {this.fromId = properties.from;}
  8752. if (properties.to !== undefined) {this.toId = properties.to;}
  8753. if (properties.id !== undefined) {this.id = properties.id;}
  8754. if (properties.style !== undefined) {this.style = properties.style;}
  8755. if (properties.label !== undefined) {this.label = properties.label;}
  8756. if (this.label) {
  8757. this.fontSize = constants.edges.fontSize;
  8758. this.fontFace = constants.edges.fontFace;
  8759. this.fontColor = constants.edges.fontColor;
  8760. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8761. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8762. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8763. }
  8764. if (properties.title !== undefined) {this.title = properties.title;}
  8765. if (properties.width !== undefined) {this.width = properties.width;}
  8766. if (properties.value !== undefined) {this.value = properties.value;}
  8767. if (properties.length !== undefined) {this.length = properties.length;}
  8768. // Added to support dashed lines
  8769. // David Jordan
  8770. // 2012-08-08
  8771. if (properties.dash) {
  8772. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  8773. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  8774. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  8775. }
  8776. if (properties.color !== undefined) {this.color = properties.color;}
  8777. // A node is connected when it has a from and to node.
  8778. this.connect();
  8779. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  8780. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  8781. this.stiffness = 1 / this.length;
  8782. // set draw method based on style
  8783. switch (this.style) {
  8784. case 'line': this.draw = this._drawLine; break;
  8785. case 'arrow': this.draw = this._drawArrow; break;
  8786. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  8787. case 'dash-line': this.draw = this._drawDashLine; break;
  8788. default: this.draw = this._drawLine; break;
  8789. }
  8790. };
  8791. /**
  8792. * Connect an edge to its nodes
  8793. */
  8794. Edge.prototype.connect = function () {
  8795. this.disconnect();
  8796. this.from = this.graph.nodes[this.fromId] || null;
  8797. this.to = this.graph.nodes[this.toId] || null;
  8798. this.connected = (this.from && this.to);
  8799. if (this.connected) {
  8800. this.from.attachEdge(this);
  8801. this.to.attachEdge(this);
  8802. }
  8803. else {
  8804. if (this.from) {
  8805. this.from.detachEdge(this);
  8806. }
  8807. if (this.to) {
  8808. this.to.detachEdge(this);
  8809. }
  8810. }
  8811. };
  8812. /**
  8813. * Disconnect an edge from its nodes
  8814. */
  8815. Edge.prototype.disconnect = function () {
  8816. if (this.from) {
  8817. this.from.detachEdge(this);
  8818. this.from = null;
  8819. }
  8820. if (this.to) {
  8821. this.to.detachEdge(this);
  8822. this.to = null;
  8823. }
  8824. this.connected = false;
  8825. };
  8826. /**
  8827. * get the title of this edge.
  8828. * @return {string} title The title of the edge, or undefined when no title
  8829. * has been set.
  8830. */
  8831. Edge.prototype.getTitle = function() {
  8832. return this.title;
  8833. };
  8834. /**
  8835. * Retrieve the value of the edge. Can be undefined
  8836. * @return {Number} value
  8837. */
  8838. Edge.prototype.getValue = function() {
  8839. return this.value;
  8840. };
  8841. /**
  8842. * Adjust the value range of the edge. The edge will adjust it's width
  8843. * based on its value.
  8844. * @param {Number} min
  8845. * @param {Number} max
  8846. */
  8847. Edge.prototype.setValueRange = function(min, max) {
  8848. if (!this.widthFixed && this.value !== undefined) {
  8849. var scale = (this.widthMax - this.widthMin) / (max - min);
  8850. this.width = (this.value - min) * scale + this.widthMin;
  8851. }
  8852. };
  8853. /**
  8854. * Redraw a edge
  8855. * Draw this edge in the given canvas
  8856. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8857. * @param {CanvasRenderingContext2D} ctx
  8858. */
  8859. Edge.prototype.draw = function(ctx) {
  8860. throw "Method draw not initialized in edge";
  8861. };
  8862. /**
  8863. * Check if this object is overlapping with the provided object
  8864. * @param {Object} obj an object with parameters left, top
  8865. * @return {boolean} True if location is located on the edge
  8866. */
  8867. Edge.prototype.isOverlappingWith = function(obj) {
  8868. var distMax = 10;
  8869. var xFrom = this.from.x;
  8870. var yFrom = this.from.y;
  8871. var xTo = this.to.x;
  8872. var yTo = this.to.y;
  8873. var xObj = obj.left;
  8874. var yObj = obj.top;
  8875. var dist = Edge._dist(xFrom, yFrom, xTo, yTo, xObj, yObj);
  8876. return (dist < distMax);
  8877. };
  8878. /**
  8879. * Redraw a edge as a line
  8880. * Draw this edge in the given canvas
  8881. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8882. * @param {CanvasRenderingContext2D} ctx
  8883. * @private
  8884. */
  8885. Edge.prototype._drawLine = function(ctx) {
  8886. // set style
  8887. ctx.strokeStyle = this.color;
  8888. ctx.lineWidth = this._getLineWidth();
  8889. var point;
  8890. if (this.from != this.to) {
  8891. // draw line
  8892. this._line(ctx);
  8893. // draw label
  8894. if (this.label) {
  8895. point = this._pointOnLine(0.5);
  8896. this._label(ctx, this.label, point.x, point.y);
  8897. }
  8898. }
  8899. else {
  8900. var x, y;
  8901. var radius = this.length / 4;
  8902. var node = this.from;
  8903. if (!node.width) {
  8904. node.resize(ctx);
  8905. }
  8906. if (node.width > node.height) {
  8907. x = node.x + node.width / 2;
  8908. y = node.y - radius;
  8909. }
  8910. else {
  8911. x = node.x + radius;
  8912. y = node.y - node.height / 2;
  8913. }
  8914. this._circle(ctx, x, y, radius);
  8915. point = this._pointOnCircle(x, y, radius, 0.5);
  8916. this._label(ctx, this.label, point.x, point.y);
  8917. }
  8918. };
  8919. /**
  8920. * Get the line width of the edge. Depends on width and whether one of the
  8921. * connected nodes is selected.
  8922. * @return {Number} width
  8923. * @private
  8924. */
  8925. Edge.prototype._getLineWidth = function() {
  8926. if (this.from.selected || this.to.selected) {
  8927. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  8928. }
  8929. else {
  8930. return this.width*this.graphScaleInv;
  8931. }
  8932. };
  8933. /**
  8934. * Draw a line between two nodes
  8935. * @param {CanvasRenderingContext2D} ctx
  8936. * @private
  8937. */
  8938. Edge.prototype._line = function (ctx) {
  8939. // draw a straight line
  8940. ctx.beginPath();
  8941. ctx.moveTo(this.from.x, this.from.y);
  8942. ctx.lineTo(this.to.x, this.to.y);
  8943. ctx.stroke();
  8944. };
  8945. /**
  8946. * Draw a line from a node to itself, a circle
  8947. * @param {CanvasRenderingContext2D} ctx
  8948. * @param {Number} x
  8949. * @param {Number} y
  8950. * @param {Number} radius
  8951. * @private
  8952. */
  8953. Edge.prototype._circle = function (ctx, x, y, radius) {
  8954. // draw a circle
  8955. ctx.beginPath();
  8956. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  8957. ctx.stroke();
  8958. };
  8959. /**
  8960. * Draw label with white background and with the middle at (x, y)
  8961. * @param {CanvasRenderingContext2D} ctx
  8962. * @param {String} text
  8963. * @param {Number} x
  8964. * @param {Number} y
  8965. * @private
  8966. */
  8967. Edge.prototype._label = function (ctx, text, x, y) {
  8968. if (text) {
  8969. // TODO: cache the calculated size
  8970. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  8971. this.fontSize + "px " + this.fontFace;
  8972. ctx.fillStyle = 'white';
  8973. var width = ctx.measureText(text).width;
  8974. var height = this.fontSize;
  8975. var left = x - width / 2;
  8976. var top = y - height / 2;
  8977. ctx.fillRect(left, top, width, height);
  8978. // draw text
  8979. ctx.fillStyle = this.fontColor || "black";
  8980. ctx.textAlign = "left";
  8981. ctx.textBaseline = "top";
  8982. ctx.fillText(text, left, top);
  8983. }
  8984. };
  8985. /**
  8986. * Redraw a edge as a dashed line
  8987. * Draw this edge in the given canvas
  8988. * @author David Jordan
  8989. * @date 2012-08-08
  8990. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8991. * @param {CanvasRenderingContext2D} ctx
  8992. * @private
  8993. */
  8994. Edge.prototype._drawDashLine = function(ctx) {
  8995. // set style
  8996. ctx.strokeStyle = this.color;
  8997. ctx.lineWidth = this._getLineWidth();
  8998. // draw dashed line
  8999. ctx.beginPath();
  9000. ctx.lineCap = 'round';
  9001. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9002. {
  9003. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9004. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9005. }
  9006. 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
  9007. {
  9008. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9009. [this.dash.length,this.dash.gap]);
  9010. }
  9011. else //If all else fails draw a line
  9012. {
  9013. ctx.moveTo(this.from.x, this.from.y);
  9014. ctx.lineTo(this.to.x, this.to.y);
  9015. }
  9016. ctx.stroke();
  9017. // draw label
  9018. if (this.label) {
  9019. var point = this._pointOnLine(0.5);
  9020. this._label(ctx, this.label, point.x, point.y);
  9021. }
  9022. };
  9023. /**
  9024. * Get a point on a line
  9025. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9026. * @return {Object} point
  9027. * @private
  9028. */
  9029. Edge.prototype._pointOnLine = function (percentage) {
  9030. return {
  9031. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9032. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9033. }
  9034. };
  9035. /**
  9036. * Get a point on a circle
  9037. * @param {Number} x
  9038. * @param {Number} y
  9039. * @param {Number} radius
  9040. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9041. * @return {Object} point
  9042. * @private
  9043. */
  9044. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9045. var angle = (percentage - 3/8) * 2 * Math.PI;
  9046. return {
  9047. x: x + radius * Math.cos(angle),
  9048. y: y - radius * Math.sin(angle)
  9049. }
  9050. };
  9051. /**
  9052. * Redraw a edge as a line with an arrow halfway the line
  9053. * Draw this edge in the given canvas
  9054. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9055. * @param {CanvasRenderingContext2D} ctx
  9056. * @private
  9057. */
  9058. Edge.prototype._drawArrowCenter = function(ctx) {
  9059. var point;
  9060. // set style
  9061. ctx.strokeStyle = this.color;
  9062. ctx.fillStyle = this.color;
  9063. ctx.lineWidth = this._getLineWidth();
  9064. if (this.from != this.to) {
  9065. // draw line
  9066. this._line(ctx);
  9067. // draw an arrow halfway the line
  9068. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9069. var length = 10 + 5 * this.width; // TODO: make customizable?
  9070. point = this._pointOnLine(0.5);
  9071. ctx.arrow(point.x, point.y, angle, length);
  9072. ctx.fill();
  9073. ctx.stroke();
  9074. // draw label
  9075. if (this.label) {
  9076. point = this._pointOnLine(0.5);
  9077. this._label(ctx, this.label, point.x, point.y);
  9078. }
  9079. }
  9080. else {
  9081. // draw circle
  9082. var x, y;
  9083. var radius = this.length / 4;
  9084. var node = this.from;
  9085. if (!node.width) {
  9086. node.resize(ctx);
  9087. }
  9088. if (node.width > node.height) {
  9089. x = node.x + node.width / 2;
  9090. y = node.y - radius;
  9091. }
  9092. else {
  9093. x = node.x + radius;
  9094. y = node.y - node.height / 2;
  9095. }
  9096. this._circle(ctx, x, y, radius);
  9097. // draw all arrows
  9098. var angle = 0.2 * Math.PI;
  9099. var length = 10 + 5 * this.width; // TODO: make customizable?
  9100. point = this._pointOnCircle(x, y, radius, 0.5);
  9101. ctx.arrow(point.x, point.y, angle, length);
  9102. ctx.fill();
  9103. ctx.stroke();
  9104. // draw label
  9105. if (this.label) {
  9106. point = this._pointOnCircle(x, y, radius, 0.5);
  9107. this._label(ctx, this.label, point.x, point.y);
  9108. }
  9109. }
  9110. };
  9111. /**
  9112. * Redraw a edge as a line with an arrow
  9113. * Draw this edge in the given canvas
  9114. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9115. * @param {CanvasRenderingContext2D} ctx
  9116. * @private
  9117. */
  9118. Edge.prototype._drawArrow = function(ctx) {
  9119. // set style
  9120. ctx.strokeStyle = this.color;
  9121. ctx.fillStyle = this.color;
  9122. ctx.lineWidth = this._getLineWidth();
  9123. // draw line
  9124. var angle, length;
  9125. if (this.from != this.to) {
  9126. // calculate length and angle of the line
  9127. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9128. var dx = (this.to.x - this.from.x);
  9129. var dy = (this.to.y - this.from.y);
  9130. var lEdge = Math.sqrt(dx * dx + dy * dy);
  9131. var lFrom = this.from.distanceToBorder(ctx, angle + Math.PI);
  9132. var pFrom = (lEdge - lFrom) / lEdge;
  9133. var xFrom = (pFrom) * this.from.x + (1 - pFrom) * this.to.x;
  9134. var yFrom = (pFrom) * this.from.y + (1 - pFrom) * this.to.y;
  9135. var lTo = this.to.distanceToBorder(ctx, angle);
  9136. var pTo = (lEdge - lTo) / lEdge;
  9137. var xTo = (1 - pTo) * this.from.x + pTo * this.to.x;
  9138. var yTo = (1 - pTo) * this.from.y + pTo * this.to.y;
  9139. ctx.beginPath();
  9140. ctx.moveTo(xFrom, yFrom);
  9141. ctx.lineTo(xTo, yTo);
  9142. ctx.stroke();
  9143. // draw arrow at the end of the line
  9144. length = 10 + 5 * this.width; // TODO: make customizable?
  9145. ctx.arrow(xTo, yTo, angle, length);
  9146. ctx.fill();
  9147. ctx.stroke();
  9148. // draw label
  9149. if (this.label) {
  9150. var point = this._pointOnLine(0.5);
  9151. this._label(ctx, this.label, point.x, point.y);
  9152. }
  9153. }
  9154. else {
  9155. // draw circle
  9156. var node = this.from;
  9157. var x, y, arrow;
  9158. var radius = this.length / 4;
  9159. if (!node.width) {
  9160. node.resize(ctx);
  9161. }
  9162. if (node.width > node.height) {
  9163. x = node.x + node.width / 2;
  9164. y = node.y - radius;
  9165. arrow = {
  9166. x: x,
  9167. y: node.y,
  9168. angle: 0.9 * Math.PI
  9169. };
  9170. }
  9171. else {
  9172. x = node.x + radius;
  9173. y = node.y - node.height / 2;
  9174. arrow = {
  9175. x: node.x,
  9176. y: y,
  9177. angle: 0.6 * Math.PI
  9178. };
  9179. }
  9180. ctx.beginPath();
  9181. // TODO: do not draw a circle, but an arc
  9182. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9183. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9184. ctx.stroke();
  9185. // draw all arrows
  9186. length = 10 + 5 * this.width; // TODO: make customizable?
  9187. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9188. ctx.fill();
  9189. ctx.stroke();
  9190. // draw label
  9191. if (this.label) {
  9192. point = this._pointOnCircle(x, y, radius, 0.5);
  9193. this._label(ctx, this.label, point.x, point.y);
  9194. }
  9195. }
  9196. };
  9197. /**
  9198. * Calculate the distance between a point (x3,y3) and a line segment from
  9199. * (x1,y1) to (x2,y2).
  9200. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9201. * @param {number} x1
  9202. * @param {number} y1
  9203. * @param {number} x2
  9204. * @param {number} y2
  9205. * @param {number} x3
  9206. * @param {number} y3
  9207. * @private
  9208. */
  9209. Edge._dist = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9210. var px = x2-x1,
  9211. py = y2-y1,
  9212. something = px*px + py*py,
  9213. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9214. if (u > 1) {
  9215. u = 1;
  9216. }
  9217. else if (u < 0) {
  9218. u = 0;
  9219. }
  9220. var x = x1 + u * px,
  9221. y = y1 + u * py,
  9222. dx = x - x3,
  9223. dy = y - y3;
  9224. //# Note: If the actual distance does not matter,
  9225. //# if you only want to compare what this function
  9226. //# returns to other results of this function, you
  9227. //# can just return the squared distance instead
  9228. //# (i.e. remove the sqrt) to gain a little performance
  9229. return Math.sqrt(dx*dx + dy*dy);
  9230. };
  9231. /**
  9232. * This allows the zoom level of the graph to influence the rendering
  9233. *
  9234. * @param scale
  9235. */
  9236. Edge.prototype.setScale = function(scale) {
  9237. this.graphScaleInv = 1.0/scale;
  9238. };
  9239. /**
  9240. * Popup is a class to create a popup window with some text
  9241. * @param {Element} container The container object.
  9242. * @param {Number} [x]
  9243. * @param {Number} [y]
  9244. * @param {String} [text]
  9245. */
  9246. function Popup(container, x, y, text) {
  9247. if (container) {
  9248. this.container = container;
  9249. }
  9250. else {
  9251. this.container = document.body;
  9252. }
  9253. this.x = 0;
  9254. this.y = 0;
  9255. this.padding = 5;
  9256. if (x !== undefined && y !== undefined ) {
  9257. this.setPosition(x, y);
  9258. }
  9259. if (text !== undefined) {
  9260. this.setText(text);
  9261. }
  9262. // create the frame
  9263. this.frame = document.createElement("div");
  9264. var style = this.frame.style;
  9265. style.position = "absolute";
  9266. style.visibility = "hidden";
  9267. style.border = "1px solid #666";
  9268. style.color = "black";
  9269. style.padding = this.padding + "px";
  9270. style.backgroundColor = "#FFFFC6";
  9271. style.borderRadius = "3px";
  9272. style.MozBorderRadius = "3px";
  9273. style.WebkitBorderRadius = "3px";
  9274. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9275. style.whiteSpace = "nowrap";
  9276. this.container.appendChild(this.frame);
  9277. }
  9278. /**
  9279. * @param {number} x Horizontal position of the popup window
  9280. * @param {number} y Vertical position of the popup window
  9281. */
  9282. Popup.prototype.setPosition = function(x, y) {
  9283. this.x = parseInt(x);
  9284. this.y = parseInt(y);
  9285. };
  9286. /**
  9287. * Set the text for the popup window. This can be HTML code
  9288. * @param {string} text
  9289. */
  9290. Popup.prototype.setText = function(text) {
  9291. this.frame.innerHTML = text;
  9292. };
  9293. /**
  9294. * Show the popup window
  9295. * @param {boolean} show Optional. Show or hide the window
  9296. */
  9297. Popup.prototype.show = function (show) {
  9298. if (show === undefined) {
  9299. show = true;
  9300. }
  9301. if (show) {
  9302. var height = this.frame.clientHeight;
  9303. var width = this.frame.clientWidth;
  9304. var maxHeight = this.frame.parentNode.clientHeight;
  9305. var maxWidth = this.frame.parentNode.clientWidth;
  9306. var top = (this.y - height);
  9307. if (top + height + this.padding > maxHeight) {
  9308. top = maxHeight - height - this.padding;
  9309. }
  9310. if (top < this.padding) {
  9311. top = this.padding;
  9312. }
  9313. var left = this.x;
  9314. if (left + width + this.padding > maxWidth) {
  9315. left = maxWidth - width - this.padding;
  9316. }
  9317. if (left < this.padding) {
  9318. left = this.padding;
  9319. }
  9320. this.frame.style.left = left + "px";
  9321. this.frame.style.top = top + "px";
  9322. this.frame.style.visibility = "visible";
  9323. }
  9324. else {
  9325. this.hide();
  9326. }
  9327. };
  9328. /**
  9329. * Hide the popup window
  9330. */
  9331. Popup.prototype.hide = function () {
  9332. this.frame.style.visibility = "hidden";
  9333. };
  9334. /**
  9335. * @class Groups
  9336. * This class can store groups and properties specific for groups.
  9337. */
  9338. Groups = function () {
  9339. this.clear();
  9340. this.defaultIndex = 0;
  9341. };
  9342. /**
  9343. * default constants for group colors
  9344. */
  9345. Groups.DEFAULT = [
  9346. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9347. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9348. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9349. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9350. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9351. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9352. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9353. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9354. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9355. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9356. ];
  9357. /**
  9358. * Clear all groups
  9359. */
  9360. Groups.prototype.clear = function () {
  9361. this.groups = {};
  9362. this.groups.length = function()
  9363. {
  9364. var i = 0;
  9365. for ( var p in this ) {
  9366. if (this.hasOwnProperty(p)) {
  9367. i++;
  9368. }
  9369. }
  9370. return i;
  9371. }
  9372. };
  9373. /**
  9374. * get group properties of a groupname. If groupname is not found, a new group
  9375. * is added.
  9376. * @param {*} groupname Can be a number, string, Date, etc.
  9377. * @return {Object} group The created group, containing all group properties
  9378. */
  9379. Groups.prototype.get = function (groupname) {
  9380. var group = this.groups[groupname];
  9381. if (group == undefined) {
  9382. // create new group
  9383. var index = this.defaultIndex % Groups.DEFAULT.length;
  9384. this.defaultIndex++;
  9385. group = {};
  9386. group.color = Groups.DEFAULT[index];
  9387. this.groups[groupname] = group;
  9388. }
  9389. return group;
  9390. };
  9391. /**
  9392. * Add a custom group style
  9393. * @param {String} groupname
  9394. * @param {Object} style An object containing borderColor,
  9395. * backgroundColor, etc.
  9396. * @return {Object} group The created group object
  9397. */
  9398. Groups.prototype.add = function (groupname, style) {
  9399. this.groups[groupname] = style;
  9400. if (style.color) {
  9401. style.color = Node.parseColor(style.color);
  9402. }
  9403. return style;
  9404. };
  9405. /**
  9406. * @class Images
  9407. * This class loads images and keeps them stored.
  9408. */
  9409. Images = function () {
  9410. this.images = {};
  9411. this.callback = undefined;
  9412. };
  9413. /**
  9414. * Set an onload callback function. This will be called each time an image
  9415. * is loaded
  9416. * @param {function} callback
  9417. */
  9418. Images.prototype.setOnloadCallback = function(callback) {
  9419. this.callback = callback;
  9420. };
  9421. /**
  9422. *
  9423. * @param {string} url Url of the image
  9424. * @return {Image} img The image object
  9425. */
  9426. Images.prototype.load = function(url) {
  9427. var img = this.images[url];
  9428. if (img == undefined) {
  9429. // create the image
  9430. var images = this;
  9431. img = new Image();
  9432. this.images[url] = img;
  9433. img.onload = function() {
  9434. if (images.callback) {
  9435. images.callback(this);
  9436. }
  9437. };
  9438. img.src = url;
  9439. }
  9440. return img;
  9441. };
  9442. /**
  9443. * Creation of the SectorMixin var.
  9444. *
  9445. * This contains all the functions the Graph object can use to employ the sector system.
  9446. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  9447. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  9448. *
  9449. * Alex de Mulder
  9450. * 21-01-2013
  9451. */
  9452. var SectorMixin = {
  9453. /**
  9454. * This function is only called by the setData function of the Graph object.
  9455. * This loads the global references into the active sector. This initializes the sector.
  9456. *
  9457. * @private
  9458. */
  9459. _putDataInSector : function() {
  9460. this.sectors["active"][this._sector()].nodes = this.nodes;
  9461. this.sectors["active"][this._sector()].edges = this.edges;
  9462. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  9463. },
  9464. /**
  9465. * /**
  9466. * This function sets the global references to nodes, edges and nodeIndices back to
  9467. * those of the supplied (active) sector. If a type is defined, do the specific type
  9468. *
  9469. * @param {String} sectorId
  9470. * @param {String} [sectorType] | "active" or "frozen"
  9471. * @private
  9472. */
  9473. _switchToSector : function(sectorId, sectorType) {
  9474. if (sectorType === undefined || sectorType == "active") {
  9475. this._switchToActiveSector(sectorId);
  9476. }
  9477. else {
  9478. this._switchToFrozenSector(sectorId);
  9479. }
  9480. },
  9481. /**
  9482. * This function sets the global references to nodes, edges and nodeIndices back to
  9483. * those of the supplied active sector.
  9484. *
  9485. * @param sectorId
  9486. * @private
  9487. */
  9488. _switchToActiveSector : function(sectorId) {
  9489. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  9490. this.nodes = this.sectors["active"][sectorId]["nodes"];
  9491. this.edges = this.sectors["active"][sectorId]["edges"];
  9492. },
  9493. /**
  9494. * This function sets the global references to nodes, edges and nodeIndices back to
  9495. * those of the supplied frozen sector.
  9496. *
  9497. * @param sectorId
  9498. * @private
  9499. */
  9500. _switchToFrozenSector : function(sectorId) {
  9501. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  9502. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  9503. this.edges = this.sectors["frozen"][sectorId]["edges"];
  9504. },
  9505. /**
  9506. * This function sets the global references to nodes, edges and nodeIndices to
  9507. * those of the navigation controls sector.
  9508. *
  9509. * @private
  9510. */
  9511. _switchToNavigationSector : function() {
  9512. this.nodeIndices = this.sectors["navigation"]["nodeIndices"];
  9513. this.nodes = this.sectors["navigation"]["nodes"];
  9514. this.edges = this.sectors["navigation"]["edges"];
  9515. },
  9516. /**
  9517. * This function sets the global references to nodes, edges and nodeIndices back to
  9518. * those of the currently active sector.
  9519. *
  9520. * @private
  9521. */
  9522. _loadLatestSector : function() {
  9523. this._switchToSector(this._sector());
  9524. },
  9525. /**
  9526. * This function returns the currently active sector Id
  9527. *
  9528. * @returns {String}
  9529. * @private
  9530. */
  9531. _sector : function() {
  9532. return this.activeSector[this.activeSector.length-1];
  9533. },
  9534. /**
  9535. * This function returns the previously active sector Id
  9536. *
  9537. * @returns {String}
  9538. * @private
  9539. */
  9540. _previousSector : function() {
  9541. if (this.activeSector.length > 1) {
  9542. return this.activeSector[this.activeSector.length-2];
  9543. }
  9544. else {
  9545. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  9546. }
  9547. },
  9548. /**
  9549. * We add the active sector at the end of the this.activeSector array
  9550. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  9551. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  9552. *
  9553. * @param newId
  9554. * @private
  9555. */
  9556. _setActiveSector : function(newId) {
  9557. this.activeSector.push(newId);
  9558. },
  9559. /**
  9560. * We remove the currently active sector id from the active sector stack. This happens when
  9561. * we reactivate the previously active sector
  9562. *
  9563. * @private
  9564. */
  9565. _forgetLastSector : function() {
  9566. this.activeSector.pop();
  9567. },
  9568. /**
  9569. * This function creates a new active sector with the supplied newId. This newId
  9570. * is the expanding node id.
  9571. *
  9572. * @param {String} newId | Id of the new active sector
  9573. * @private
  9574. */
  9575. _createNewSector : function(newId) {
  9576. // create the new sector
  9577. this.sectors["active"][newId] = {"nodes":{},
  9578. "edges":{},
  9579. "nodeIndices":[],
  9580. "formationScale": this.scale,
  9581. "drawingNode": undefined};
  9582. // create the new sector render node. This gives visual feedback that you are in a new sector.
  9583. this.sectors["active"][newId]['drawingNode'] = new Node(
  9584. {id:newId,
  9585. color: {
  9586. background: "#eaefef",
  9587. border: "495c5e"
  9588. }
  9589. },{},{},this.constants);
  9590. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  9591. },
  9592. /**
  9593. * This function removes the currently active sector. This is called when we create a new
  9594. * active sector.
  9595. *
  9596. * @param {String} sectorId | Id of the active sector that will be removed
  9597. * @private
  9598. */
  9599. _deleteActiveSector : function(sectorId) {
  9600. delete this.sectors["active"][sectorId];
  9601. },
  9602. /**
  9603. * This function removes the currently active sector. This is called when we reactivate
  9604. * the previously active sector.
  9605. *
  9606. * @param {String} sectorId | Id of the active sector that will be removed
  9607. * @private
  9608. */
  9609. _deleteFrozenSector : function(sectorId) {
  9610. delete this.sectors["frozen"][sectorId];
  9611. },
  9612. /**
  9613. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  9614. * We copy the references, then delete the active entree.
  9615. *
  9616. * @param sectorId
  9617. * @private
  9618. */
  9619. _freezeSector : function(sectorId) {
  9620. // we move the set references from the active to the frozen stack.
  9621. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  9622. // we have moved the sector data into the frozen set, we now remove it from the active set
  9623. this._deleteActiveSector(sectorId);
  9624. },
  9625. /**
  9626. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  9627. * object to the "active" object.
  9628. *
  9629. * @param sectorId
  9630. * @private
  9631. */
  9632. _activateSector : function(sectorId) {
  9633. // we move the set references from the frozen to the active stack.
  9634. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  9635. // we have moved the sector data into the active set, we now remove it from the frozen stack
  9636. this._deleteFrozenSector(sectorId);
  9637. },
  9638. /**
  9639. * This function merges the data from the currently active sector with a frozen sector. This is used
  9640. * in the process of reverting back to the previously active sector.
  9641. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  9642. * upon the creation of a new active sector.
  9643. *
  9644. * @param sectorId
  9645. * @private
  9646. */
  9647. _mergeThisWithFrozen : function(sectorId) {
  9648. // copy all nodes
  9649. for (var nodeId in this.nodes) {
  9650. if (this.nodes.hasOwnProperty(nodeId)) {
  9651. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  9652. }
  9653. }
  9654. // copy all edges (if not fully clustered, else there are no edges)
  9655. for (var edgeId in this.edges) {
  9656. if (this.edges.hasOwnProperty(edgeId)) {
  9657. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  9658. }
  9659. }
  9660. // merge the nodeIndices
  9661. for (var i = 0; i < this.nodeIndices.length; i++) {
  9662. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  9663. }
  9664. },
  9665. /**
  9666. * This clusters the sector to one cluster. It was a single cluster before this process started so
  9667. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  9668. *
  9669. * @private
  9670. */
  9671. _collapseThisToSingleCluster : function() {
  9672. this.clusterToFit(1,false);
  9673. },
  9674. /**
  9675. * We create a new active sector from the node that we want to open.
  9676. *
  9677. * @param node
  9678. * @private
  9679. */
  9680. _addSector : function(node) {
  9681. // this is the currently active sector
  9682. var sector = this._sector();
  9683. // // this should allow me to select nodes from a frozen set.
  9684. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  9685. // console.log("the node is part of the active sector");
  9686. // }
  9687. // else {
  9688. // console.log("I dont know what the fuck happened!!");
  9689. // }
  9690. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  9691. delete this.nodes[node.id];
  9692. var unqiueIdentifier = util.randomUUID();
  9693. // we fully freeze the currently active sector
  9694. this._freezeSector(sector);
  9695. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  9696. this._createNewSector(unqiueIdentifier);
  9697. // we add the active sector to the sectors array to be able to revert these steps later on
  9698. this._setActiveSector(unqiueIdentifier);
  9699. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  9700. this._switchToSector(this._sector());
  9701. // finally we add the node we removed from our previous active sector to the new active sector
  9702. this.nodes[node.id] = node;
  9703. },
  9704. /**
  9705. * We close the sector that is currently open and revert back to the one before.
  9706. * If the active sector is the "default" sector, nothing happens.
  9707. *
  9708. * @private
  9709. */
  9710. _collapseSector : function() {
  9711. // the currently active sector
  9712. var sector = this._sector();
  9713. // we cannot collapse the default sector
  9714. if (sector != "default") {
  9715. if ((this.nodeIndices.length == 1) ||
  9716. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  9717. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  9718. var previousSector = this._previousSector();
  9719. // we collapse the sector back to a single cluster
  9720. this._collapseThisToSingleCluster();
  9721. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  9722. // This previous sector is the one we will reactivate
  9723. this._mergeThisWithFrozen(previousSector);
  9724. // the previously active (frozen) sector now has all the data from the currently active sector.
  9725. // we can now delete the active sector.
  9726. this._deleteActiveSector(sector);
  9727. // we activate the previously active (and currently frozen) sector.
  9728. this._activateSector(previousSector);
  9729. // we load the references from the newly active sector into the global references
  9730. this._switchToSector(previousSector);
  9731. // we forget the previously active sector because we reverted to the one before
  9732. this._forgetLastSector();
  9733. // finally, we update the node index list.
  9734. this._updateNodeIndexList();
  9735. }
  9736. }
  9737. },
  9738. /**
  9739. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  9740. *
  9741. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9742. * | we dont pass the function itself because then the "this" is the window object
  9743. * | instead of the Graph object
  9744. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9745. * @private
  9746. */
  9747. _doInAllActiveSectors : function(runFunction,argument) {
  9748. if (argument === undefined) {
  9749. for (var sector in this.sectors["active"]) {
  9750. if (this.sectors["active"].hasOwnProperty(sector)) {
  9751. // switch the global references to those of this sector
  9752. this._switchToActiveSector(sector);
  9753. this[runFunction]();
  9754. }
  9755. }
  9756. }
  9757. else {
  9758. for (var sector in this.sectors["active"]) {
  9759. if (this.sectors["active"].hasOwnProperty(sector)) {
  9760. // switch the global references to those of this sector
  9761. this._switchToActiveSector(sector);
  9762. var args = Array.prototype.splice.call(arguments, 1);
  9763. if (args.length > 1) {
  9764. this[runFunction](args[0],args[1]);
  9765. }
  9766. else {
  9767. this[runFunction](argument);
  9768. }
  9769. }
  9770. }
  9771. }
  9772. // we revert the global references back to our active sector
  9773. this._loadLatestSector();
  9774. },
  9775. /**
  9776. * This runs a function in all frozen sectors. This is used in the _redraw().
  9777. *
  9778. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9779. * | we don't pass the function itself because then the "this" is the window object
  9780. * | instead of the Graph object
  9781. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9782. * @private
  9783. */
  9784. _doInAllFrozenSectors : function(runFunction,argument) {
  9785. if (argument === undefined) {
  9786. for (var sector in this.sectors["frozen"]) {
  9787. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  9788. // switch the global references to those of this sector
  9789. this._switchToFrozenSector(sector);
  9790. this[runFunction]();
  9791. }
  9792. }
  9793. }
  9794. else {
  9795. for (var sector in this.sectors["frozen"]) {
  9796. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  9797. // switch the global references to those of this sector
  9798. this._switchToFrozenSector(sector);
  9799. var args = Array.prototype.splice.call(arguments, 1);
  9800. if (args.length > 1) {
  9801. this[runFunction](args[0],args[1]);
  9802. }
  9803. else {
  9804. this[runFunction](argument);
  9805. }
  9806. }
  9807. }
  9808. }
  9809. this._loadLatestSector();
  9810. },
  9811. /**
  9812. * This runs a function in the navigation controls sector.
  9813. *
  9814. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9815. * | we don't pass the function itself because then the "this" is the window object
  9816. * | instead of the Graph object
  9817. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9818. * @private
  9819. */
  9820. _doInNavigationSector : function(runFunction,argument) {
  9821. this._switchToNavigationSector();
  9822. if (argument === undefined) {
  9823. this[runFunction]();
  9824. }
  9825. else {
  9826. var args = Array.prototype.splice.call(arguments, 1);
  9827. if (args.length > 1) {
  9828. this[runFunction](args[0],args[1]);
  9829. }
  9830. else {
  9831. this[runFunction](argument);
  9832. }
  9833. }
  9834. this._loadLatestSector();
  9835. },
  9836. /**
  9837. * This runs a function in all sectors. This is used in the _redraw().
  9838. *
  9839. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  9840. * | we don't pass the function itself because then the "this" is the window object
  9841. * | instead of the Graph object
  9842. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  9843. * @private
  9844. */
  9845. _doInAllSectors : function(runFunction,argument) {
  9846. var args = Array.prototype.splice.call(arguments, 1);
  9847. if (argument === undefined) {
  9848. this._doInAllActiveSectors(runFunction);
  9849. this._doInAllFrozenSectors(runFunction);
  9850. }
  9851. else {
  9852. if (args.length > 1) {
  9853. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  9854. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  9855. }
  9856. else {
  9857. this._doInAllActiveSectors(runFunction,argument);
  9858. this._doInAllFrozenSectors(runFunction,argument);
  9859. }
  9860. }
  9861. },
  9862. /**
  9863. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  9864. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  9865. *
  9866. * @private
  9867. */
  9868. _clearNodeIndexList : function() {
  9869. var sector = this._sector();
  9870. this.sectors["active"][sector]["nodeIndices"] = [];
  9871. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  9872. },
  9873. /**
  9874. * Draw the encompassing sector node
  9875. *
  9876. * @param ctx
  9877. * @param sectorType
  9878. * @private
  9879. */
  9880. _drawSectorNodes : function(ctx,sectorType) {
  9881. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  9882. for (var sector in this.sectors[sectorType]) {
  9883. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  9884. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  9885. this._switchToSector(sector,sectorType);
  9886. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  9887. for (var nodeId in this.nodes) {
  9888. if (this.nodes.hasOwnProperty(nodeId)) {
  9889. node = this.nodes[nodeId];
  9890. node.resize(ctx);
  9891. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  9892. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  9893. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  9894. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  9895. }
  9896. }
  9897. node = this.sectors[sectorType][sector]["drawingNode"];
  9898. node.x = 0.5 * (maxX + minX);
  9899. node.y = 0.5 * (maxY + minY);
  9900. node.width = 2 * (node.x - minX);
  9901. node.height = 2 * (node.y - minY);
  9902. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  9903. node.setScale(this.scale);
  9904. node._drawCircle(ctx);
  9905. }
  9906. }
  9907. }
  9908. },
  9909. _drawAllSectorNodes : function(ctx) {
  9910. this._drawSectorNodes(ctx,"frozen");
  9911. this._drawSectorNodes(ctx,"active");
  9912. this._loadLatestSector();
  9913. }
  9914. };
  9915. /**
  9916. * Creation of the ClusterMixin var.
  9917. *
  9918. * This contains all the functions the Graph object can use to employ clustering
  9919. *
  9920. * Alex de Mulder
  9921. * 21-01-2013
  9922. */
  9923. var ClusterMixin = {
  9924. /**
  9925. * This is only called in the constructor of the graph object
  9926. * */
  9927. startWithClustering : function() {
  9928. // cluster if the data set is big
  9929. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  9930. // updates the lables after clustering
  9931. this.updateLabels();
  9932. // this is called here because if clusterin is disabled, the start and stabilize are called in
  9933. // the setData function.
  9934. if (this.stabilize) {
  9935. this._doStabilize();
  9936. }
  9937. this.start();
  9938. },
  9939. /**
  9940. * This function clusters until the initialMaxNodes has been reached
  9941. *
  9942. * @param {Number} maxNumberOfNodes
  9943. * @param {Boolean} reposition
  9944. */
  9945. clusterToFit : function(maxNumberOfNodes, reposition) {
  9946. var numberOfNodes = this.nodeIndices.length;
  9947. var maxLevels = 50;
  9948. var level = 0;
  9949. // we first cluster the hubs, then we pull in the outliers, repeat
  9950. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  9951. if (level % 3 == 0) {
  9952. this.forceAggregateHubs();
  9953. }
  9954. else {
  9955. this.increaseClusterLevel();
  9956. }
  9957. numberOfNodes = this.nodeIndices.length;
  9958. level += 1;
  9959. }
  9960. // after the clustering we reposition the nodes to reduce the initial chaos
  9961. if (level > 1 && reposition == true) {
  9962. this.repositionNodes();
  9963. }
  9964. },
  9965. /**
  9966. * This function can be called to open up a specific cluster. It is only called by
  9967. * It will unpack the cluster back one level.
  9968. *
  9969. * @param node | Node object: cluster to open.
  9970. */
  9971. openCluster : function(node) {
  9972. var isMovingBeforeClustering = this.moving;
  9973. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  9974. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  9975. this._addSector(node);
  9976. var level = 0;
  9977. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  9978. this.decreaseClusterLevel();
  9979. level += 1;
  9980. }
  9981. }
  9982. else {
  9983. this._expandClusterNode(node,false,true);
  9984. // update the index list, dynamic edges and labels
  9985. this._updateNodeIndexList();
  9986. this._updateDynamicEdges();
  9987. this.updateLabels();
  9988. }
  9989. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  9990. if (this.moving != isMovingBeforeClustering) {
  9991. this.start();
  9992. }
  9993. },
  9994. /**
  9995. * This calls the updateClustes with default arguments
  9996. */
  9997. updateClustersDefault : function() {
  9998. if (this.constants.clustering.enabled == true) {
  9999. this.updateClusters(0,false,false);
  10000. }
  10001. },
  10002. /**
  10003. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  10004. * be clustered with their connected node. This can be repeated as many times as needed.
  10005. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  10006. */
  10007. increaseClusterLevel : function() {
  10008. this.updateClusters(-1,false,true);
  10009. },
  10010. /**
  10011. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  10012. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  10013. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  10014. */
  10015. decreaseClusterLevel : function() {
  10016. this.updateClusters(1,false,true);
  10017. },
  10018. /**
  10019. * This is the main clustering function. It clusters and declusters on zoom or forced
  10020. * This function clusters on zoom, it can be called with a predefined zoom direction
  10021. * If out, check if we can form clusters, if in, check if we can open clusters.
  10022. * This function is only called from _zoom()
  10023. *
  10024. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  10025. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  10026. * @param {Boolean} force | enabled or disable forcing
  10027. *
  10028. */
  10029. updateClusters : function(zoomDirection,recursive,force) {
  10030. var isMovingBeforeClustering = this.moving;
  10031. var amountOfNodes = this.nodeIndices.length;
  10032. // on zoom out collapse the sector if the scale is at the level the sector was made
  10033. if (this.previousScale > this.scale && zoomDirection == 0) {
  10034. this._collapseSector();
  10035. }
  10036. // check if we zoom in or out
  10037. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  10038. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  10039. // outer nodes determines if it is being clustered
  10040. this._formClusters(force);
  10041. }
  10042. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  10043. if (force == true) {
  10044. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  10045. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  10046. this._openClusters(recursive,force);
  10047. }
  10048. else {
  10049. // if a cluster takes up a set percentage of the active window
  10050. this._openClustersBySize();
  10051. }
  10052. }
  10053. this._updateNodeIndexList();
  10054. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  10055. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  10056. this._aggregateHubs(force);
  10057. this._updateNodeIndexList();
  10058. }
  10059. // we now reduce chains.
  10060. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  10061. this.handleChains();
  10062. this._updateNodeIndexList();
  10063. }
  10064. this.previousScale = this.scale;
  10065. // rest of the update the index list, dynamic edges and labels
  10066. this._updateDynamicEdges();
  10067. this.updateLabels();
  10068. // if a cluster was formed, we increase the clusterSession
  10069. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  10070. this.clusterSession += 1;
  10071. }
  10072. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  10073. if (this.moving != isMovingBeforeClustering) {
  10074. this.start();
  10075. }
  10076. },
  10077. /**
  10078. * This function handles the chains. It is called on every updateClusters().
  10079. */
  10080. handleChains : function() {
  10081. // after clustering we check how many chains there are
  10082. var chainPercentage = this._getChainFraction();
  10083. if (chainPercentage > this.constants.clustering.chainThreshold) {
  10084. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  10085. }
  10086. },
  10087. /**
  10088. * this functions starts clustering by hubs
  10089. * The minimum hub threshold is set globally
  10090. *
  10091. * @private
  10092. */
  10093. _aggregateHubs : function(force) {
  10094. this._getHubSize();
  10095. this._formClustersByHub(force,false);
  10096. },
  10097. /**
  10098. * This function is fired by keypress. It forces hubs to form.
  10099. *
  10100. */
  10101. forceAggregateHubs : function() {
  10102. var isMovingBeforeClustering = this.moving;
  10103. var amountOfNodes = this.nodeIndices.length;
  10104. this._aggregateHubs(true);
  10105. // update the index list, dynamic edges and labels
  10106. this._updateNodeIndexList();
  10107. this._updateDynamicEdges();
  10108. this.updateLabels();
  10109. // if a cluster was formed, we increase the clusterSession
  10110. if (this.nodeIndices.length != amountOfNodes) {
  10111. this.clusterSession += 1;
  10112. }
  10113. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  10114. if (this.moving != isMovingBeforeClustering) {
  10115. this.start();
  10116. }
  10117. },
  10118. /**
  10119. * If a cluster takes up more than a set percentage of the screen, open the cluster
  10120. *
  10121. * @private
  10122. */
  10123. _openClustersBySize : function() {
  10124. for (var nodeId in this.nodes) {
  10125. if (this.nodes.hasOwnProperty(nodeId)) {
  10126. var node = this.nodes[nodeId];
  10127. if (node.inView() == true) {
  10128. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  10129. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  10130. this.openCluster(node);
  10131. }
  10132. }
  10133. }
  10134. }
  10135. },
  10136. /**
  10137. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  10138. * has to be opened based on the current zoom level.
  10139. *
  10140. * @private
  10141. */
  10142. _openClusters : function(recursive,force) {
  10143. for (var i = 0; i < this.nodeIndices.length; i++) {
  10144. var node = this.nodes[this.nodeIndices[i]];
  10145. this._expandClusterNode(node,recursive,force);
  10146. }
  10147. },
  10148. /**
  10149. * This function checks if a node has to be opened. This is done by checking the zoom level.
  10150. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  10151. * This recursive behaviour is optional and can be set by the recursive argument.
  10152. *
  10153. * @param {Node} parentNode | to check for cluster and expand
  10154. * @param {Boolean} recursive | enabled or disable recursive calling
  10155. * @param {Boolean} force | enabled or disable forcing
  10156. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  10157. * @private
  10158. */
  10159. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  10160. // first check if node is a cluster
  10161. if (parentNode.clusterSize > 1) {
  10162. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  10163. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  10164. openAll = true;
  10165. }
  10166. recursive = openAll ? true : recursive;
  10167. // if the last child has been added on a smaller scale than current scale decluster
  10168. if (parentNode.formationScale < this.scale || force == true) {
  10169. // we will check if any of the contained child nodes should be removed from the cluster
  10170. for (var containedNodeId in parentNode.containedNodes) {
  10171. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  10172. var childNode = parentNode.containedNodes[containedNodeId];
  10173. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  10174. // the largest cluster is the one that comes from outside
  10175. if (force == true) {
  10176. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  10177. || openAll) {
  10178. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  10179. }
  10180. }
  10181. else {
  10182. if (this._nodeInActiveArea(parentNode)) {
  10183. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  10184. }
  10185. }
  10186. }
  10187. }
  10188. }
  10189. }
  10190. },
  10191. /**
  10192. * ONLY CALLED FROM _expandClusterNode
  10193. *
  10194. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  10195. * the child node from the parent contained_node object and put it back into the global nodes object.
  10196. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  10197. *
  10198. * @param {Node} parentNode | the parent node
  10199. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  10200. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  10201. * With force and recursive both true, the entire cluster is unpacked
  10202. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  10203. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  10204. * @private
  10205. */
  10206. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  10207. var childNode = parentNode.containedNodes[containedNodeId];
  10208. // if child node has been added on smaller scale than current, kick out
  10209. if (childNode.formationScale < this.scale || force == true) {
  10210. // put the child node back in the global nodes object
  10211. this.nodes[containedNodeId] = childNode;
  10212. // release the contained edges from this childNode back into the global edges
  10213. this._releaseContainedEdges(parentNode,childNode);
  10214. // reconnect rerouted edges to the childNode
  10215. this._connectEdgeBackToChild(parentNode,childNode);
  10216. // validate all edges in dynamicEdges
  10217. this._validateEdges(parentNode);
  10218. // undo the changes from the clustering operation on the parent node
  10219. parentNode.mass -= this.constants.clustering.massTransferCoefficient * childNode.mass;
  10220. parentNode.fontSize -= this.constants.clustering.fontSizeMultiplier * childNode.clusterSize;
  10221. parentNode.clusterSize -= childNode.clusterSize;
  10222. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  10223. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  10224. childNode.x = parentNode.x + this.constants.edges.length * 0.3 * (0.5 - Math.random()) * parentNode.clusterSize;
  10225. childNode.y = parentNode.y + this.constants.edges.length * 0.3 * (0.5 - Math.random()) * parentNode.clusterSize;
  10226. // remove node from the list
  10227. delete parentNode.containedNodes[containedNodeId];
  10228. // check if there are other childs with this clusterSession in the parent.
  10229. var othersPresent = false;
  10230. for (var childNodeId in parentNode.containedNodes) {
  10231. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  10232. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  10233. othersPresent = true;
  10234. break;
  10235. }
  10236. }
  10237. }
  10238. // if there are no others, remove the cluster session from the list
  10239. if (othersPresent == false) {
  10240. parentNode.clusterSessions.pop();
  10241. }
  10242. // remove the clusterSession from the child node
  10243. childNode.clusterSession = 0;
  10244. // restart the simulation to reorganise all nodes
  10245. this.moving = true;
  10246. // recalculate the size of the node on the next time the node is rendered
  10247. parentNode.clearSizeCache();
  10248. }
  10249. // check if a further expansion step is possible if recursivity is enabled
  10250. if (recursive == true) {
  10251. this._expandClusterNode(childNode,recursive,force,openAll);
  10252. }
  10253. },
  10254. /**
  10255. * This function checks if any nodes at the end of their trees have edges below a threshold length
  10256. * This function is called only from updateClusters()
  10257. * forceLevelCollapse ignores the length of the edge and collapses one level
  10258. * This means that a node with only one edge will be clustered with its connected node
  10259. *
  10260. * @private
  10261. * @param {Boolean} force
  10262. */
  10263. _formClusters : function(force) {
  10264. if (force == false) {
  10265. this._formClustersByZoom();
  10266. }
  10267. else {
  10268. this._forceClustersByZoom();
  10269. }
  10270. },
  10271. /**
  10272. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  10273. *
  10274. * @private
  10275. */
  10276. _formClustersByZoom : function() {
  10277. var dx,dy,length,
  10278. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  10279. // check if any edges are shorter than minLength and start the clustering
  10280. // the clustering favours the node with the larger mass
  10281. for (var edgeId in this.edges) {
  10282. if (this.edges.hasOwnProperty(edgeId)) {
  10283. var edge = this.edges[edgeId];
  10284. if (edge.connected) {
  10285. if (edge.toId != edge.fromId) {
  10286. dx = (edge.to.x - edge.from.x);
  10287. dy = (edge.to.y - edge.from.y);
  10288. length = Math.sqrt(dx * dx + dy * dy);
  10289. if (length < minLength) {
  10290. // first check which node is larger
  10291. var parentNode = edge.from;
  10292. var childNode = edge.to;
  10293. if (edge.to.mass > edge.from.mass) {
  10294. parentNode = edge.to;
  10295. childNode = edge.from;
  10296. }
  10297. if (childNode.dynamicEdgesLength == 1) {
  10298. this._addToCluster(parentNode,childNode,false);
  10299. }
  10300. else if (parentNode.dynamicEdgesLength == 1) {
  10301. this._addToCluster(childNode,parentNode,false);
  10302. }
  10303. }
  10304. }
  10305. }
  10306. }
  10307. }
  10308. },
  10309. /**
  10310. * This function forces the graph to cluster all nodes with only one connecting edge to their
  10311. * connected node.
  10312. *
  10313. * @private
  10314. */
  10315. _forceClustersByZoom : function() {
  10316. for (var nodeId in this.nodes) {
  10317. // another node could have absorbed this child.
  10318. if (this.nodes.hasOwnProperty(nodeId)) {
  10319. var childNode = this.nodes[nodeId];
  10320. // the edges can be swallowed by another decrease
  10321. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  10322. var edge = childNode.dynamicEdges[0];
  10323. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  10324. // group to the largest node
  10325. if (childNode.id != parentNode.id) {
  10326. if (parentNode.mass > childNode.mass) {
  10327. this._addToCluster(parentNode,childNode,true);
  10328. }
  10329. else {
  10330. this._addToCluster(childNode,parentNode,true);
  10331. }
  10332. }
  10333. }
  10334. }
  10335. }
  10336. },
  10337. /**
  10338. * This function forms clusters from hubs, it loops over all nodes
  10339. *
  10340. * @param {Boolean} force | Disregard zoom level
  10341. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  10342. * @private
  10343. */
  10344. _formClustersByHub : function(force, onlyEqual) {
  10345. // we loop over all nodes in the list
  10346. for (var nodeId in this.nodes) {
  10347. // we check if it is still available since it can be used by the clustering in this loop
  10348. if (this.nodes.hasOwnProperty(nodeId)) {
  10349. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  10350. }
  10351. }
  10352. },
  10353. /**
  10354. * This function forms a cluster from a specific preselected hub node
  10355. *
  10356. * @param {Node} hubNode | the node we will cluster as a hub
  10357. * @param {Boolean} force | Disregard zoom level
  10358. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  10359. * @param {Number} [absorptionSizeOffset] |
  10360. * @private
  10361. */
  10362. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  10363. if (absorptionSizeOffset === undefined) {
  10364. absorptionSizeOffset = 0;
  10365. }
  10366. // we decide if the node is a hub
  10367. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  10368. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  10369. // initialize variables
  10370. var dx,dy,length;
  10371. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  10372. var allowCluster = false;
  10373. // we create a list of edges because the dynamicEdges change over the course of this loop
  10374. var edgesIdarray = [];
  10375. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  10376. for (var j = 0; j < amountOfInitialEdges; j++) {
  10377. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  10378. }
  10379. // if the hub clustering is not forces, we check if one of the edges connected
  10380. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  10381. if (force == false) {
  10382. allowCluster = false;
  10383. for (j = 0; j < amountOfInitialEdges; j++) {
  10384. var edge = this.edges[edgesIdarray[j]];
  10385. if (edge !== undefined) {
  10386. if (edge.connected) {
  10387. if (edge.toId != edge.fromId) {
  10388. dx = (edge.to.x - edge.from.x);
  10389. dy = (edge.to.y - edge.from.y);
  10390. length = Math.sqrt(dx * dx + dy * dy);
  10391. if (length < minLength) {
  10392. allowCluster = true;
  10393. break;
  10394. }
  10395. }
  10396. }
  10397. }
  10398. }
  10399. }
  10400. // start the clustering if allowed
  10401. if ((!force && allowCluster) || force) {
  10402. // we loop over all edges INITIALLY connected to this hub
  10403. for (j = 0; j < amountOfInitialEdges; j++) {
  10404. edge = this.edges[edgesIdarray[j]];
  10405. // the edge can be clustered by this function in a previous loop
  10406. if (edge !== undefined) {
  10407. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  10408. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  10409. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  10410. (childNode.id != hubNode.id)) {
  10411. this._addToCluster(hubNode,childNode,force);
  10412. }
  10413. }
  10414. }
  10415. }
  10416. }
  10417. },
  10418. /**
  10419. * This function adds the child node to the parent node, creating a cluster if it is not already.
  10420. *
  10421. * @param {Node} parentNode | this is the node that will house the child node
  10422. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  10423. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  10424. * @private
  10425. */
  10426. _addToCluster : function(parentNode, childNode, force) {
  10427. // join child node in the parent node
  10428. parentNode.containedNodes[childNode.id] = childNode;
  10429. // manage all the edges connected to the child and parent nodes
  10430. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  10431. var edge = childNode.dynamicEdges[i];
  10432. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  10433. this._addToContainedEdges(parentNode,childNode,edge);
  10434. }
  10435. else {
  10436. this._connectEdgeToCluster(parentNode,childNode,edge);
  10437. }
  10438. }
  10439. // a contained node has no dynamic edges.
  10440. childNode.dynamicEdges = [];
  10441. // remove circular edges from clusters
  10442. this._containCircularEdgesFromNode(parentNode,childNode);
  10443. // remove the childNode from the global nodes object
  10444. delete this.nodes[childNode.id];
  10445. // update the properties of the child and parent
  10446. var massBefore = parentNode.mass;
  10447. childNode.clusterSession = this.clusterSession;
  10448. parentNode.mass += this.constants.clustering.massTransferCoefficient * childNode.mass;
  10449. parentNode.clusterSize += childNode.clusterSize;
  10450. parentNode.fontSize += this.constants.clustering.fontSizeMultiplier * childNode.clusterSize;
  10451. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  10452. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  10453. parentNode.clusterSessions.push(this.clusterSession);
  10454. }
  10455. // forced clusters only open from screen size and double tap
  10456. if (force == true) {
  10457. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  10458. parentNode.formationScale = 0;
  10459. }
  10460. else {
  10461. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  10462. }
  10463. // recalculate the size of the node on the next time the node is rendered
  10464. parentNode.clearSizeCache();
  10465. // set the pop-out scale for the childnode
  10466. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  10467. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  10468. childNode.clearVelocity();
  10469. // the mass has altered, preservation of energy dictates the velocity to be updated
  10470. parentNode.updateVelocity(massBefore);
  10471. // restart the simulation to reorganise all nodes
  10472. this.moving = true;
  10473. },
  10474. /**
  10475. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  10476. * This is a seperate function to allow for level-wise collapsing of the node tree.
  10477. * It has to be called if a level is collapsed. It is called by _formClusters().
  10478. * @private
  10479. */
  10480. _updateDynamicEdges : function() {
  10481. for (var i = 0; i < this.nodeIndices.length; i++) {
  10482. var node = this.nodes[this.nodeIndices[i]];
  10483. node.dynamicEdgesLength = node.dynamicEdges.length;
  10484. // this corrects for multiple edges pointing at the same other node
  10485. var correction = 0;
  10486. if (node.dynamicEdgesLength > 1) {
  10487. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  10488. var edgeToId = node.dynamicEdges[j].toId;
  10489. var edgeFromId = node.dynamicEdges[j].fromId;
  10490. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  10491. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  10492. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  10493. correction += 1;
  10494. }
  10495. }
  10496. }
  10497. }
  10498. node.dynamicEdgesLength -= correction;
  10499. }
  10500. },
  10501. /**
  10502. * This adds an edge from the childNode to the contained edges of the parent node
  10503. *
  10504. * @param parentNode | Node object
  10505. * @param childNode | Node object
  10506. * @param edge | Edge object
  10507. * @private
  10508. */
  10509. _addToContainedEdges : function(parentNode, childNode, edge) {
  10510. // create an array object if it does not yet exist for this childNode
  10511. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  10512. parentNode.containedEdges[childNode.id] = []
  10513. }
  10514. // add this edge to the list
  10515. parentNode.containedEdges[childNode.id].push(edge);
  10516. // remove the edge from the global edges object
  10517. delete this.edges[edge.id];
  10518. // remove the edge from the parent object
  10519. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  10520. if (parentNode.dynamicEdges[i].id == edge.id) {
  10521. parentNode.dynamicEdges.splice(i,1);
  10522. break;
  10523. }
  10524. }
  10525. },
  10526. /**
  10527. * This function connects an edge that was connected to a child node to the parent node.
  10528. * It keeps track of which nodes it has been connected to with the originalId array.
  10529. *
  10530. * @param {Node} parentNode | Node object
  10531. * @param {Node} childNode | Node object
  10532. * @param {Edge} edge | Edge object
  10533. * @private
  10534. */
  10535. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  10536. // handle circular edges
  10537. if (edge.toId == edge.fromId) {
  10538. this._addToContainedEdges(parentNode, childNode, edge);
  10539. }
  10540. else {
  10541. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  10542. edge.originalToId.push(childNode.id);
  10543. edge.to = parentNode;
  10544. edge.toId = parentNode.id;
  10545. }
  10546. else { // edge connected to other node with the "from" side
  10547. edge.originalFromId.push(childNode.id);
  10548. edge.from = parentNode;
  10549. edge.fromId = parentNode.id;
  10550. }
  10551. this._addToReroutedEdges(parentNode,childNode,edge);
  10552. }
  10553. },
  10554. _containCircularEdgesFromNode : function(parentNode, childNode) {
  10555. // manage all the edges connected to the child and parent nodes
  10556. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  10557. var edge = parentNode.dynamicEdges[i];
  10558. // handle circular edges
  10559. if (edge.toId == edge.fromId) {
  10560. this._addToContainedEdges(parentNode, childNode, edge);
  10561. }
  10562. }
  10563. },
  10564. /**
  10565. * This adds an edge from the childNode to the rerouted edges of the parent node
  10566. *
  10567. * @param parentNode | Node object
  10568. * @param childNode | Node object
  10569. * @param edge | Edge object
  10570. * @private
  10571. */
  10572. _addToReroutedEdges : function(parentNode, childNode, edge) {
  10573. // create an array object if it does not yet exist for this childNode
  10574. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  10575. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  10576. parentNode.reroutedEdges[childNode.id] = [];
  10577. }
  10578. parentNode.reroutedEdges[childNode.id].push(edge);
  10579. // this edge becomes part of the dynamicEdges of the cluster node
  10580. parentNode.dynamicEdges.push(edge);
  10581. },
  10582. /**
  10583. * This function connects an edge that was connected to a cluster node back to the child node.
  10584. *
  10585. * @param parentNode | Node object
  10586. * @param childNode | Node object
  10587. * @private
  10588. */
  10589. _connectEdgeBackToChild : function(parentNode, childNode) {
  10590. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  10591. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  10592. var edge = parentNode.reroutedEdges[childNode.id][i];
  10593. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  10594. edge.originalFromId.pop();
  10595. edge.fromId = childNode.id;
  10596. edge.from = childNode;
  10597. }
  10598. else {
  10599. edge.originalToId.pop();
  10600. edge.toId = childNode.id;
  10601. edge.to = childNode;
  10602. }
  10603. // append this edge to the list of edges connecting to the childnode
  10604. childNode.dynamicEdges.push(edge);
  10605. // remove the edge from the parent object
  10606. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  10607. if (parentNode.dynamicEdges[j].id == edge.id) {
  10608. parentNode.dynamicEdges.splice(j,1);
  10609. break;
  10610. }
  10611. }
  10612. }
  10613. // remove the entry from the rerouted edges
  10614. delete parentNode.reroutedEdges[childNode.id];
  10615. }
  10616. },
  10617. /**
  10618. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  10619. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  10620. * parentNode
  10621. *
  10622. * @param parentNode | Node object
  10623. * @private
  10624. */
  10625. _validateEdges : function(parentNode) {
  10626. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  10627. var edge = parentNode.dynamicEdges[i];
  10628. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  10629. parentNode.dynamicEdges.splice(i,1);
  10630. }
  10631. }
  10632. },
  10633. /**
  10634. * This function released the contained edges back into the global domain and puts them back into the
  10635. * dynamic edges of both parent and child.
  10636. *
  10637. * @param {Node} parentNode |
  10638. * @param {Node} childNode |
  10639. * @private
  10640. */
  10641. _releaseContainedEdges : function(parentNode, childNode) {
  10642. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  10643. var edge = parentNode.containedEdges[childNode.id][i];
  10644. // put the edge back in the global edges object
  10645. this.edges[edge.id] = edge;
  10646. // put the edge back in the dynamic edges of the child and parent
  10647. childNode.dynamicEdges.push(edge);
  10648. parentNode.dynamicEdges.push(edge);
  10649. }
  10650. // remove the entry from the contained edges
  10651. delete parentNode.containedEdges[childNode.id];
  10652. },
  10653. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  10654. /**
  10655. * This updates the node labels for all nodes (for debugging purposes)
  10656. */
  10657. updateLabels : function() {
  10658. var nodeId;
  10659. // update node labels
  10660. for (nodeId in this.nodes) {
  10661. if (this.nodes.hasOwnProperty(nodeId)) {
  10662. var node = this.nodes[nodeId];
  10663. if (node.clusterSize > 1) {
  10664. node.label = "[".concat(String(node.clusterSize),"]");
  10665. }
  10666. }
  10667. }
  10668. // update node labels
  10669. for (nodeId in this.nodes) {
  10670. if (this.nodes.hasOwnProperty(nodeId)) {
  10671. node = this.nodes[nodeId];
  10672. if (node.clusterSize == 1) {
  10673. if (node.originalLabel !== undefined) {
  10674. node.label = node.originalLabel;
  10675. }
  10676. else {
  10677. node.label = String(node.id);
  10678. }
  10679. }
  10680. }
  10681. }
  10682. /* Debug Override */
  10683. // for (nodeId in this.nodes) {
  10684. // if (this.nodes.hasOwnProperty(nodeId)) {
  10685. // node = this.nodes[nodeId];
  10686. // node.label = String(Math.round(node.width)).concat(":",Math.round(node.width*this.scale));
  10687. // }
  10688. // }
  10689. },
  10690. /**
  10691. * This function determines if the cluster we want to decluster is in the active area
  10692. * this means around the zoom center
  10693. *
  10694. * @param {Node} node
  10695. * @returns {boolean}
  10696. * @private
  10697. */
  10698. _nodeInActiveArea : function(node) {
  10699. return (
  10700. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  10701. &&
  10702. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  10703. )
  10704. },
  10705. /**
  10706. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  10707. * It puts large clusters away from the center and randomizes the order.
  10708. *
  10709. */
  10710. repositionNodes : function() {
  10711. for (var i = 0; i < this.nodeIndices.length; i++) {
  10712. var node = this.nodes[this.nodeIndices[i]];
  10713. if (!node.isFixed()) {
  10714. var radius = this.constants.edges.length * (1 + 0.6*node.clusterSize);
  10715. var angle = 2 * Math.PI * Math.random();
  10716. node.x = radius * Math.cos(angle);
  10717. node.y = radius * Math.sin(angle);
  10718. }
  10719. }
  10720. },
  10721. /**
  10722. * We determine how many connections denote an important hub.
  10723. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  10724. *
  10725. * @private
  10726. */
  10727. _getHubSize : function() {
  10728. var average = 0;
  10729. var averageSquared = 0;
  10730. var hubCounter = 0;
  10731. var largestHub = 0;
  10732. for (var i = 0; i < this.nodeIndices.length; i++) {
  10733. var node = this.nodes[this.nodeIndices[i]];
  10734. if (node.dynamicEdgesLength > largestHub) {
  10735. largestHub = node.dynamicEdgesLength;
  10736. }
  10737. average += node.dynamicEdgesLength;
  10738. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  10739. hubCounter += 1;
  10740. }
  10741. average = average / hubCounter;
  10742. averageSquared = averageSquared / hubCounter;
  10743. var variance = averageSquared - Math.pow(average,2);
  10744. var standardDeviation = Math.sqrt(variance);
  10745. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  10746. // always have at least one to cluster
  10747. if (this.hubThreshold > largestHub) {
  10748. this.hubThreshold = largestHub;
  10749. }
  10750. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  10751. // console.log("hubThreshold:",this.hubThreshold);
  10752. },
  10753. /**
  10754. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  10755. * with this amount we can cluster specifically on these chains.
  10756. *
  10757. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  10758. * @private
  10759. */
  10760. _reduceAmountOfChains : function(fraction) {
  10761. this.hubThreshold = 2;
  10762. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  10763. for (var nodeId in this.nodes) {
  10764. if (this.nodes.hasOwnProperty(nodeId)) {
  10765. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  10766. if (reduceAmount > 0) {
  10767. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  10768. reduceAmount -= 1;
  10769. }
  10770. }
  10771. }
  10772. }
  10773. },
  10774. /**
  10775. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  10776. * with this amount we can cluster specifically on these chains.
  10777. *
  10778. * @private
  10779. */
  10780. _getChainFraction : function() {
  10781. var chains = 0;
  10782. var total = 0;
  10783. for (var nodeId in this.nodes) {
  10784. if (this.nodes.hasOwnProperty(nodeId)) {
  10785. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  10786. chains += 1;
  10787. }
  10788. total += 1;
  10789. }
  10790. }
  10791. return chains/total;
  10792. }
  10793. };
  10794. var SelectionMixin = {
  10795. /**
  10796. * This function can be called from the _doInAllSectors function
  10797. *
  10798. * @param object
  10799. * @param overlappingNodes
  10800. * @private
  10801. */
  10802. _getNodesOverlappingWith : function(object, overlappingNodes) {
  10803. var nodes = this.nodes;
  10804. for (var nodeId in nodes) {
  10805. if (nodes.hasOwnProperty(nodeId)) {
  10806. if (nodes[nodeId].isOverlappingWith(object)) {
  10807. overlappingNodes.push(nodeId);
  10808. }
  10809. }
  10810. }
  10811. },
  10812. /**
  10813. * retrieve all nodes overlapping with given object
  10814. * @param {Object} object An object with parameters left, top, right, bottom
  10815. * @return {Number[]} An array with id's of the overlapping nodes
  10816. * @private
  10817. */
  10818. _getAllNodesOverlappingWith : function (object) {
  10819. var overlappingNodes = [];
  10820. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  10821. return overlappingNodes;
  10822. },
  10823. /**
  10824. * retrieve all nodes in the navigation controls overlapping with given object
  10825. * @param {Object} object An object with parameters left, top, right, bottom
  10826. * @return {Number[]} An array with id's of the overlapping nodes
  10827. * @private
  10828. */
  10829. _getAllNavigationNodesOverlappingWith : function (object) {
  10830. var overlappingNodes = [];
  10831. this._doInNavigationSector("_getNodesOverlappingWith",object,overlappingNodes);
  10832. return overlappingNodes;
  10833. },
  10834. /**
  10835. * Return a position object in canvasspace from a single point in screenspace
  10836. *
  10837. * @param pointer
  10838. * @returns {{left: number, top: number, right: number, bottom: number}}
  10839. * @private
  10840. */
  10841. _pointerToPositionObject : function(pointer) {
  10842. var x = this._canvasToX(pointer.x);
  10843. var y = this._canvasToY(pointer.y);
  10844. return {left: x,
  10845. top: y,
  10846. right: x,
  10847. bottom: y};
  10848. },
  10849. /**
  10850. * Return a position object in canvasspace from a single point in screenspace
  10851. *
  10852. * @param pointer
  10853. * @returns {{left: number, top: number, right: number, bottom: number}}
  10854. * @private
  10855. */
  10856. _pointerToScreenPositionObject : function(pointer) {
  10857. var x = pointer.x;
  10858. var y = pointer.y;
  10859. return {left: x,
  10860. top: y,
  10861. right: x,
  10862. bottom: y};
  10863. },
  10864. /**
  10865. * Get the top navigation controls node at the a specific point (like a click)
  10866. *
  10867. * @param {{x: Number, y: Number}} pointer
  10868. * @return {Node | null} node
  10869. * @private
  10870. */
  10871. _getNavigationNodeAt : function (pointer) {
  10872. var screenPositionObject = this._pointerToScreenPositionObject(pointer);
  10873. var overlappingNodes = this._getAllNavigationNodesOverlappingWith(screenPositionObject);
  10874. if (overlappingNodes.length > 0) {
  10875. return this.sectors["navigation"]["nodes"][overlappingNodes[overlappingNodes.length - 1]];
  10876. }
  10877. else {
  10878. return null;
  10879. }
  10880. },
  10881. /**
  10882. * Get the top node at the a specific point (like a click)
  10883. *
  10884. * @param {{x: Number, y: Number}} pointer
  10885. * @return {Node | null} node
  10886. * @private
  10887. */
  10888. _getNodeAt : function (pointer) {
  10889. // we first check if this is an navigation controls element
  10890. var positionObject = this._pointerToPositionObject(pointer);
  10891. overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  10892. // if there are overlapping nodes, select the last one, this is the
  10893. // one which is drawn on top of the others
  10894. if (overlappingNodes.length > 0) {
  10895. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  10896. }
  10897. else {
  10898. return null;
  10899. }
  10900. },
  10901. /**
  10902. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  10903. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  10904. *
  10905. * @param pointer
  10906. * @returns {null}
  10907. * @private
  10908. */
  10909. _getEdgeAt : function(pointer) {
  10910. return null;
  10911. },
  10912. /**
  10913. * Add object to the selection array. The this.selection id array may not be needed.
  10914. *
  10915. * @param obj
  10916. * @private
  10917. */
  10918. _addToSelection : function(obj) {
  10919. this.selection.push(obj.id);
  10920. this.selectionObj[obj.id] = obj;
  10921. },
  10922. /**
  10923. * Remove a single option from selection.
  10924. *
  10925. * @param obj
  10926. * @private
  10927. */
  10928. _removeFromSelection : function(obj) {
  10929. for (var i = 0; i < this.selection.length; i++) {
  10930. if (obj.id == this.selection[i]) {
  10931. this.selection.splice(i,1);
  10932. break;
  10933. }
  10934. }
  10935. delete this.selectionObj[obj.id];
  10936. },
  10937. /**
  10938. * Unselect all. The selectionObj is useful for this.
  10939. *
  10940. * @param {Boolean} [doNotTrigger] | ignore trigger
  10941. * @private
  10942. */
  10943. _unselectAll : function(doNotTrigger) {
  10944. if (doNotTrigger === undefined) {
  10945. doNotTrigger = false;
  10946. }
  10947. this.selection = [];
  10948. for (var objId in this.selectionObj) {
  10949. if (this.selectionObj.hasOwnProperty(objId)) {
  10950. this.selectionObj[objId].unselect();
  10951. }
  10952. }
  10953. this.selectionObj = {};
  10954. if (doNotTrigger == false) {
  10955. this._trigger('select', {
  10956. nodes: this.getSelection()
  10957. });
  10958. }
  10959. },
  10960. /**
  10961. * Check if anything is selected
  10962. *
  10963. * @returns {boolean}
  10964. * @private
  10965. */
  10966. _selectionIsEmpty : function() {
  10967. if (this.selection.length == 0) {
  10968. return true;
  10969. }
  10970. else {
  10971. return false;
  10972. }
  10973. },
  10974. /**
  10975. * This is called when someone clicks on a node. either select or deselect it.
  10976. * If there is an existing selection and we don't want to append to it, clear the existing selection
  10977. *
  10978. * @param {Node} node
  10979. * @param {Boolean} append
  10980. * @param {Boolean} [doNotTrigger] | ignore trigger
  10981. * @private
  10982. */
  10983. _selectNode : function(node, append, doNotTrigger) {
  10984. if (doNotTrigger === undefined) {
  10985. doNotTrigger = false;
  10986. }
  10987. if (this._selectionIsEmpty() == false && append == false) {
  10988. this._unselectAll(true);
  10989. }
  10990. if (node.selected == false) {
  10991. node.select();
  10992. this._addToSelection(node);
  10993. }
  10994. else {
  10995. node.unselect();
  10996. this._removeFromSelection(node);
  10997. }
  10998. if (doNotTrigger == false) {
  10999. this._trigger('select', {
  11000. nodes: this.getSelection()
  11001. });
  11002. }
  11003. },
  11004. /**
  11005. * handles the selection part of the touch, only for navigation controls elements;
  11006. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  11007. * This is the most responsive solution
  11008. *
  11009. * @param {Object} pointer
  11010. * @private
  11011. */
  11012. _handleTouch : function(pointer) {
  11013. if (this.constants.navigation.enabled == true) {
  11014. var node = this._getNavigationNodeAt(pointer);
  11015. if (node != null) {
  11016. if (this[node.triggerFunction] !== undefined) {
  11017. this[node.triggerFunction]();
  11018. }
  11019. }
  11020. }
  11021. },
  11022. /**
  11023. * handles the selection part of the tap;
  11024. *
  11025. * @param {Object} pointer
  11026. * @private
  11027. */
  11028. _handleTap : function(pointer) {
  11029. var node = this._getNodeAt(pointer);
  11030. if (node != null) {
  11031. this._selectNode(node,false);
  11032. }
  11033. else {
  11034. this._unselectAll();
  11035. }
  11036. this._redraw();
  11037. },
  11038. /**
  11039. * handles the selection part of the double tap and opens a cluster if needed
  11040. *
  11041. * @param {Object} pointer
  11042. * @private
  11043. */
  11044. _handleDoubleTap : function(pointer) {
  11045. var node = this._getNodeAt(pointer);
  11046. if (node != null && node !== undefined) {
  11047. // we reset the areaCenter here so the opening of the node will occur
  11048. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  11049. "y" : this._canvasToY(pointer.y)};
  11050. this.openCluster(node);
  11051. }
  11052. },
  11053. /**
  11054. * Handle the onHold selection part
  11055. *
  11056. * @param pointer
  11057. * @private
  11058. */
  11059. _handleOnHold : function(pointer) {
  11060. var node = this._getNodeAt(pointer);
  11061. if (node != null) {
  11062. this._selectNode(node,true);
  11063. }
  11064. this._redraw();
  11065. },
  11066. /**
  11067. * handle the onRelease event. These functions are here for the navigation controls module.
  11068. *
  11069. * @private
  11070. */
  11071. _handleOnRelease : function() {
  11072. this.xIncrement = 0;
  11073. this.yIncrement = 0;
  11074. this.zoomIncrement = 0;
  11075. this._unHighlightAll();
  11076. },
  11077. /**
  11078. *
  11079. * retrieve the currently selected nodes
  11080. * @return {Number[] | String[]} selection An array with the ids of the
  11081. * selected nodes.
  11082. */
  11083. getSelection : function() {
  11084. return this.selection.concat([]);
  11085. },
  11086. /**
  11087. *
  11088. * retrieve the currently selected nodes as objects
  11089. * @return {Objects} selection An array with the ids of the
  11090. * selected nodes.
  11091. */
  11092. getSelectionObjects : function() {
  11093. return this.selectionObj;
  11094. },
  11095. /**
  11096. * // TODO: rework this function, it is from the old system
  11097. *
  11098. * select zero or more nodes
  11099. * @param {Number[] | String[]} selection An array with the ids of the
  11100. * selected nodes.
  11101. */
  11102. setSelection : function(selection) {
  11103. var i, iMax, id;
  11104. if (!selection || (selection.length == undefined))
  11105. throw 'Selection must be an array with ids';
  11106. // first unselect any selected node
  11107. this._unselectAll(true);
  11108. for (i = 0, iMax = selection.length; i < iMax; i++) {
  11109. id = selection[i];
  11110. var node = this.nodes[id];
  11111. if (!node) {
  11112. throw new RangeError('Node with id "' + id + '" not found');
  11113. }
  11114. this._selectNode(node,true,true);
  11115. }
  11116. this.redraw();
  11117. },
  11118. /**
  11119. * TODO: rework this function, it is from the old system
  11120. *
  11121. * Validate the selection: remove ids of nodes which no longer exist
  11122. * @private
  11123. */
  11124. _updateSelection : function () {
  11125. var i = 0;
  11126. while (i < this.selection.length) {
  11127. var nodeId = this.selection[i];
  11128. if (!this.nodes.hasOwnProperty(nodeId)) {
  11129. this.selection.splice(i, 1);
  11130. delete this.selectionObj[nodeId];
  11131. }
  11132. else {
  11133. i++;
  11134. }
  11135. }
  11136. }
  11137. /**
  11138. * Unselect selected nodes. If no selection array is provided, all nodes
  11139. * are unselected
  11140. * @param {Object[]} selection Array with selection objects, each selection
  11141. * object has a parameter row. Optional
  11142. * @param {Boolean} triggerSelect If true (default), the select event
  11143. * is triggered when nodes are unselected
  11144. * @return {Boolean} changed True if the selection is changed
  11145. * @private
  11146. */
  11147. /* _unselectNodes : function(selection, triggerSelect) {
  11148. var changed = false;
  11149. var i, iMax, id;
  11150. if (selection) {
  11151. // remove provided selections
  11152. for (i = 0, iMax = selection.length; i < iMax; i++) {
  11153. id = selection[i];
  11154. if (this.nodes.hasOwnProperty(id)) {
  11155. this.nodes[id].unselect();
  11156. }
  11157. var j = 0;
  11158. while (j < this.selection.length) {
  11159. if (this.selection[j] == id) {
  11160. this.selection.splice(j, 1);
  11161. changed = true;
  11162. }
  11163. else {
  11164. j++;
  11165. }
  11166. }
  11167. }
  11168. }
  11169. else if (this.selection && this.selection.length) {
  11170. // remove all selections
  11171. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  11172. id = this.selection[i];
  11173. if (this.nodes.hasOwnProperty(id)) {
  11174. this.nodes[id].unselect();
  11175. }
  11176. changed = true;
  11177. }
  11178. this.selection = [];
  11179. }
  11180. if (changed && (triggerSelect == true || triggerSelect == undefined)) {
  11181. // fire the select event
  11182. this._trigger('select', {
  11183. nodes: this.getSelection()
  11184. });
  11185. }
  11186. return changed;
  11187. },
  11188. */
  11189. /**
  11190. * select all nodes on given location x, y
  11191. * @param {Array} selection an array with node ids
  11192. * @param {boolean} append If true, the new selection will be appended to the
  11193. * current selection (except for duplicate entries)
  11194. * @return {Boolean} changed True if the selection is changed
  11195. * @private
  11196. */
  11197. /* _selectNodes : function(selection, append) {
  11198. var changed = false;
  11199. var i, iMax;
  11200. // TODO: the selectNodes method is a little messy, rework this
  11201. // check if the current selection equals the desired selection
  11202. var selectionAlreadyThere = true;
  11203. if (selection.length != this.selection.length) {
  11204. selectionAlreadyThere = false;
  11205. }
  11206. else {
  11207. for (i = 0, iMax = Math.min(selection.length, this.selection.length); i < iMax; i++) {
  11208. if (selection[i] != this.selection[i]) {
  11209. selectionAlreadyThere = false;
  11210. break;
  11211. }
  11212. }
  11213. }
  11214. if (selectionAlreadyThere) {
  11215. return changed;
  11216. }
  11217. if (append == undefined || append == false) {
  11218. // first deselect any selected node
  11219. var triggerSelect = false;
  11220. changed = this._unselectNodes(undefined, triggerSelect);
  11221. }
  11222. for (i = 0, iMax = selection.length; i < iMax; i++) {
  11223. // add each of the new selections, but only when they are not duplicate
  11224. var id = selection[i];
  11225. var isDuplicate = (this.selection.indexOf(id) != -1);
  11226. if (!isDuplicate) {
  11227. this.nodes[id].select();
  11228. this.selection.push(id);
  11229. changed = true;
  11230. }
  11231. }
  11232. if (changed) {
  11233. // fire the select event
  11234. this._trigger('select', {
  11235. nodes: this.getSelection()
  11236. });
  11237. }
  11238. return changed;
  11239. },
  11240. */
  11241. };
  11242. /**
  11243. * Created by Alex on 1/22/14.
  11244. */
  11245. var NavigationMixin = {
  11246. /**
  11247. * This function moves the navigation controls if the canvas size has been changed. If the arugments
  11248. * verticaAlignTop and horizontalAlignLeft are false, the correction will be made
  11249. *
  11250. * @private
  11251. */
  11252. _relocateNavigation : function() {
  11253. if (this.sectors !== undefined) {
  11254. var xOffset = this.navigationClientWidth - this.frame.canvas.clientWidth;
  11255. var yOffset = this.navigationClientHeight - this.frame.canvas.clientHeight;
  11256. this.navigationClientWidth = this.frame.canvas.clientWidth;
  11257. this.navigationClientHeight = this.frame.canvas.clientHeight;
  11258. var node = null;
  11259. for (var nodeId in this.sectors["navigation"]["nodes"]) {
  11260. if (this.sectors["navigation"]["nodes"].hasOwnProperty(nodeId)) {
  11261. node = this.sectors["navigation"]["nodes"][nodeId];
  11262. if (!node.horizontalAlignLeft) {
  11263. node.x -= xOffset;
  11264. }
  11265. if (!node.verticalAlignTop) {
  11266. node.y -= yOffset;
  11267. }
  11268. }
  11269. }
  11270. }
  11271. },
  11272. /**
  11273. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  11274. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  11275. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  11276. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  11277. *
  11278. * @private
  11279. */
  11280. _loadNavigationElements : function() {
  11281. var DIR = this.constants.navigation.iconPath;
  11282. this.navigationClientWidth = this.frame.canvas.clientWidth;
  11283. this.navigationClientHeight = this.frame.canvas.clientHeight;
  11284. if (this.navigationClientWidth === undefined) {
  11285. this.navigationClientWidth = 0;
  11286. this.navigationClientHeight = 0;
  11287. }
  11288. var offset = 15;
  11289. var intermediateOffset = 7;
  11290. var navigationNodes = [
  11291. {id: 'navigation_up', shape: 'image', image: DIR + '/uparrow.png', triggerFunction: "_moveUp",
  11292. verticalAlignTop: false, x: 45 + offset + intermediateOffset, y: this.navigationClientHeight - 45 - offset - intermediateOffset},
  11293. {id: 'navigation_down', shape: 'image', image: DIR + '/downarrow.png', triggerFunction: "_moveDown",
  11294. verticalAlignTop: false, x: 45 + offset + intermediateOffset, y: this.navigationClientHeight - 15 - offset},
  11295. {id: 'navigation_left', shape: 'image', image: DIR + '/leftarrow.png', triggerFunction: "_moveLeft",
  11296. verticalAlignTop: false, x: 15 + offset, y: this.navigationClientHeight - 15 - offset},
  11297. {id: 'navigation_right', shape: 'image', image: DIR + '/rightarrow.png',triggerFunction: "_moveRight",
  11298. verticalAlignTop: false, x: 75 + offset + 2 * intermediateOffset, y: this.navigationClientHeight - 15 - offset},
  11299. {id: 'navigation_plus', shape: 'image', image: DIR + '/plus.png', triggerFunction: "_zoomIn",
  11300. verticalAlignTop: false, horizontalAlignLeft: false,
  11301. x: this.navigationClientWidth - 45 - offset - intermediateOffset, y: this.navigationClientHeight - 15 - offset},
  11302. {id: 'navigation_min', shape: 'image', image: DIR + '/minus.png', triggerFunction: "_zoomOut",
  11303. verticalAlignTop: false, horizontalAlignLeft: false,
  11304. x: this.navigationClientWidth - 15 - offset, y: this.navigationClientHeight - 15 - offset},
  11305. {id: 'navigation_zoomExtends', shape: 'image', image: DIR + '/zoomExtends.png', triggerFunction: "zoomToFit",
  11306. verticalAlignTop: false, horizontalAlignLeft: false,
  11307. x: this.navigationClientWidth - 15 - offset, y: this.navigationClientHeight - 45 - offset - intermediateOffset}
  11308. ];
  11309. var nodeObj = null;
  11310. for (var i = 0; i < navigationNodes.length; i++) {
  11311. nodeObj = this.sectors["navigation"]['nodes'];
  11312. nodeObj[navigationNodes[i]['id']] = new Node(navigationNodes[i], this.images, this.groups, this.constants);
  11313. }
  11314. },
  11315. /**
  11316. * By setting the clustersize to be larger than 1, we use the clustering drawing method
  11317. * to illustrate the buttons are presed. We call this highlighting.
  11318. *
  11319. * @param {String} elementId
  11320. * @private
  11321. */
  11322. _highlightNavigationElement : function(elementId) {
  11323. if (this.sectors["navigation"]["nodes"].hasOwnProperty(elementId)) {
  11324. this.sectors["navigation"]["nodes"][elementId].clusterSize = 2;
  11325. }
  11326. },
  11327. /**
  11328. * Reverting back to a normal button
  11329. *
  11330. * @param {String} elementId
  11331. * @private
  11332. */
  11333. _unHighlightNavigationElement : function(elementId) {
  11334. if (this.sectors["navigation"]["nodes"].hasOwnProperty(elementId)) {
  11335. this.sectors["navigation"]["nodes"][elementId].clusterSize = 1;
  11336. }
  11337. },
  11338. /**
  11339. * un-highlight (for lack of a better term) all navigation controls elements
  11340. * @private
  11341. */
  11342. _unHighlightAll : function() {
  11343. for (var nodeId in this.sectors['navigation']['nodes']) {
  11344. if (this.sectors['navigation']['nodes'].hasOwnProperty(nodeId)) {
  11345. this._unHighlightNavigationElement(nodeId);
  11346. }
  11347. }
  11348. },
  11349. _preventDefault : function(event) {
  11350. if (event !== undefined) {
  11351. if (event.preventDefault) {
  11352. event.preventDefault();
  11353. } else {
  11354. event.returnValue = false;
  11355. }
  11356. }
  11357. },
  11358. /**
  11359. * move the screen up
  11360. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  11361. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  11362. * To avoid this behaviour, we do the translation in the start loop.
  11363. *
  11364. * @private
  11365. */
  11366. _moveUp : function(event) {
  11367. this._highlightNavigationElement("navigation_up");
  11368. this.yIncrement = this.constants.keyboard.speed.y;
  11369. this.start(); // if there is no node movement, the calculation wont be done
  11370. this._preventDefault(event);
  11371. },
  11372. /**
  11373. * move the screen down
  11374. * @private
  11375. */
  11376. _moveDown : function(event) {
  11377. this._highlightNavigationElement("navigation_down");
  11378. this.yIncrement = -this.constants.keyboard.speed.y;
  11379. this.start(); // if there is no node movement, the calculation wont be done
  11380. this._preventDefault(event);
  11381. },
  11382. /**
  11383. * move the screen left
  11384. * @private
  11385. */
  11386. _moveLeft : function(event) {
  11387. this._highlightNavigationElement("navigation_left");
  11388. this.xIncrement = this.constants.keyboard.speed.x;
  11389. this.start(); // if there is no node movement, the calculation wont be done
  11390. this._preventDefault(event);
  11391. },
  11392. /**
  11393. * move the screen right
  11394. * @private
  11395. */
  11396. _moveRight : function(event) {
  11397. this._highlightNavigationElement("navigation_right");
  11398. this.xIncrement = -this.constants.keyboard.speed.y;
  11399. this.start(); // if there is no node movement, the calculation wont be done
  11400. this._preventDefault(event);
  11401. },
  11402. /**
  11403. * Zoom in, using the same method as the movement.
  11404. * @private
  11405. */
  11406. _zoomIn : function(event) {
  11407. this._highlightNavigationElement("navigation_plus");
  11408. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  11409. this.start(); // if there is no node movement, the calculation wont be done
  11410. this._preventDefault(event);
  11411. },
  11412. /**
  11413. * Zoom out
  11414. * @private
  11415. */
  11416. _zoomOut : function() {
  11417. this._highlightNavigationElement("navigation_min");
  11418. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  11419. this.start(); // if there is no node movement, the calculation wont be done
  11420. this._preventDefault(event);
  11421. },
  11422. /**
  11423. * Stop zooming and unhighlight the zoom controls
  11424. * @private
  11425. */
  11426. _stopZoom : function() {
  11427. this._unHighlightNavigationElement("navigation_plus");
  11428. this._unHighlightNavigationElement("navigation_min");
  11429. this.zoomIncrement = 0;
  11430. },
  11431. /**
  11432. * Stop moving in the Y direction and unHighlight the up and down
  11433. * @private
  11434. */
  11435. _yStopMoving : function() {
  11436. this._unHighlightNavigationElement("navigation_up");
  11437. this._unHighlightNavigationElement("navigation_down");
  11438. this.yIncrement = 0;
  11439. },
  11440. /**
  11441. * Stop moving in the X direction and unHighlight left and right.
  11442. * @private
  11443. */
  11444. _xStopMoving : function() {
  11445. this._unHighlightNavigationElement("navigation_left");
  11446. this._unHighlightNavigationElement("navigation_right");
  11447. this.xIncrement = 0;
  11448. }
  11449. };
  11450. /**
  11451. * @constructor Graph
  11452. * Create a graph visualization, displaying nodes and edges.
  11453. *
  11454. * @param {Element} container The DOM element in which the Graph will
  11455. * be created. Normally a div element.
  11456. * @param {Object} data An object containing parameters
  11457. * {Array} nodes
  11458. * {Array} edges
  11459. * @param {Object} options Options
  11460. */
  11461. function Graph (container, data, options) {
  11462. // create variables and set default values
  11463. this.containerElement = container;
  11464. this.width = '100%';
  11465. this.height = '100%';
  11466. // to give everything a nice fluidity, we seperate the rendering and calculating of the forces
  11467. this.renderRefreshRate = 60; // hz (fps)
  11468. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  11469. this.stabilize = true; // stabilize before displaying the graph
  11470. this.selectable = true;
  11471. this.forceFactor = 50000;
  11472. // set constant values
  11473. this.constants = {
  11474. nodes: {
  11475. radiusMin: 5,
  11476. radiusMax: 20,
  11477. radius: 5,
  11478. distance: 100, // px
  11479. shape: 'ellipse',
  11480. image: undefined,
  11481. widthMin: 16, // px
  11482. widthMax: 64, // px
  11483. fontColor: 'black',
  11484. fontSize: 14, // px
  11485. //fontFace: verdana,
  11486. fontFace: 'arial',
  11487. color: {
  11488. border: '#2B7CE9',
  11489. background: '#97C2FC',
  11490. highlight: {
  11491. border: '#2B7CE9',
  11492. background: '#D2E5FF'
  11493. }
  11494. },
  11495. borderColor: '#2B7CE9',
  11496. backgroundColor: '#97C2FC',
  11497. highlightColor: '#D2E5FF',
  11498. group: undefined
  11499. },
  11500. edges: {
  11501. widthMin: 1,
  11502. widthMax: 15,
  11503. width: 1,
  11504. style: 'line',
  11505. color: '#343434',
  11506. fontColor: '#343434',
  11507. fontSize: 14, // px
  11508. fontFace: 'arial',
  11509. //distance: 100, //px
  11510. length: 100, // px
  11511. dash: {
  11512. length: 10,
  11513. gap: 5,
  11514. altLength: undefined
  11515. }
  11516. },
  11517. clustering: { // Per Node in Cluster = PNiC
  11518. enabled: false, // (Boolean) | global on/off switch for clustering.
  11519. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  11520. 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
  11521. 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
  11522. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  11523. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  11524. sectorThreshold: 50, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  11525. 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.
  11526. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  11527. forceAmplification: 0.6, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  11528. distanceAmplification: 0.2, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  11529. edgeGrowth: 11, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  11530. nodeScaling: {width: 10, // (px PNiC) | growth of the width per node in cluster.
  11531. height: 10, // (px PNiC) | growth of the height per node in cluster.
  11532. radius: 10}, // (px PNiC) | growth of the radius per node in cluster.
  11533. activeAreaBoxSize: 100, // (px) | box area around the curser where clusters are popped open.
  11534. massTransferCoefficient: 1 // (multiplier) | parent.mass += massTransferCoefficient * child.mass
  11535. },
  11536. navigation: {
  11537. enabled: false,
  11538. iconPath: this._getScriptPath() + '/img'
  11539. },
  11540. keyboard: {
  11541. enabled: false,
  11542. speed: {x: 10, y: 10, zoom: 0.02}
  11543. },
  11544. minVelocity: 2, // px/s
  11545. maxIterations: 1000 // maximum number of iteration to stabilize
  11546. };
  11547. // Node variables
  11548. this.groups = new Groups(); // object with groups
  11549. this.images = new Images(); // object with images
  11550. this.images.setOnloadCallback(function () {
  11551. graph._redraw();
  11552. });
  11553. // navigation variables
  11554. this.xIncrement = 0;
  11555. this.yIncrement = 0;
  11556. this.zoomIncrement = 0;
  11557. // create a frame and canvas
  11558. this._create();
  11559. // load the sector system. (mandatory, fully integrated with Graph)
  11560. this._loadSectorSystem();
  11561. // apply options
  11562. this.setOptions(options);
  11563. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  11564. this._loadClusterSystem();
  11565. // load the selection system. (mandatory, required by Graph)
  11566. this._loadSelectionSystem();
  11567. // other vars
  11568. var graph = this;
  11569. this.freezeSimulation = false;// freeze the simulation
  11570. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  11571. this.nodes = {}; // object with Node objects
  11572. this.edges = {}; // object with Edge objects
  11573. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  11574. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  11575. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  11576. this.scale = 1; // defining the global scale variable in the constructor
  11577. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  11578. // TODO: create a counter to keep track on the number of nodes having values
  11579. // TODO: create a counter to keep track on the number of nodes currently moving
  11580. // TODO: create a counter to keep track on the number of edges having values
  11581. this.nodesData = null; // A DataSet or DataView
  11582. this.edgesData = null; // A DataSet or DataView
  11583. // create event listeners used to subscribe on the DataSets of the nodes and edges
  11584. var me = this;
  11585. this.nodesListeners = {
  11586. 'add': function (event, params) {
  11587. me._addNodes(params.items);
  11588. me.start();
  11589. },
  11590. 'update': function (event, params) {
  11591. me._updateNodes(params.items);
  11592. me.start();
  11593. },
  11594. 'remove': function (event, params) {
  11595. me._removeNodes(params.items);
  11596. me.start();
  11597. }
  11598. };
  11599. this.edgesListeners = {
  11600. 'add': function (event, params) {
  11601. me._addEdges(params.items);
  11602. me.start();
  11603. },
  11604. 'update': function (event, params) {
  11605. me._updateEdges(params.items);
  11606. me.start();
  11607. },
  11608. 'remove': function (event, params) {
  11609. me._removeEdges(params.items);
  11610. me.start();
  11611. }
  11612. };
  11613. // properties of the data
  11614. this.moving = false; // True if any of the nodes have an undefined position
  11615. this.timer = undefined;
  11616. // load data (the disable start variable will be the same as the enabled clustering)
  11617. this.setData(data,this.constants.clustering.enabled);
  11618. // zoom so all data will fit on the screen
  11619. this.zoomToFit(true);
  11620. // if clustering is disabled, the simulation will have started in the setData function
  11621. if (this.constants.clustering.enabled) {
  11622. this.startWithClustering();
  11623. }
  11624. }
  11625. /**
  11626. * Get the script path where the vis.js library is located
  11627. *
  11628. * @returns {string | null} path Path or null when not found. Path does not
  11629. * end with a slash.
  11630. * @private
  11631. */
  11632. Graph.prototype._getScriptPath = function() {
  11633. var scripts = document.getElementsByTagName( 'script' );
  11634. // find script named vis.js or vis.min.js
  11635. for (var i = 0; i < scripts.length; i++) {
  11636. var src = scripts[i].src;
  11637. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  11638. if (match) {
  11639. // return path without the script name
  11640. return src.substring(0, src.length - match[0].length);
  11641. }
  11642. }
  11643. return null;
  11644. };
  11645. /**
  11646. * Find the center position of the graph
  11647. * @private
  11648. */
  11649. Graph.prototype._getRange = function() {
  11650. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11651. for (var i = 0; i < this.nodeIndices.length; i++) {
  11652. node = this.nodes[this.nodeIndices[i]];
  11653. if (minX > (node.x - node.width)) {minX = node.x - node.width;}
  11654. if (maxX < (node.x + node.width)) {maxX = node.x + node.width;}
  11655. if (minY > (node.y - node.height)) {minY = node.y - node.height;}
  11656. if (maxY < (node.y + node.height)) {maxY = node.y + node.height;}
  11657. }
  11658. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  11659. };
  11660. /**
  11661. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  11662. * @returns {{x: number, y: number}}
  11663. * @private
  11664. */
  11665. Graph.prototype._findCenter = function(range) {
  11666. var center = {x: (0.5 * (range.maxX + range.minX)),
  11667. y: (0.5 * (range.maxY + range.minY))};
  11668. return center;
  11669. };
  11670. /**
  11671. * center the graph
  11672. *
  11673. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  11674. */
  11675. Graph.prototype._centerGraph = function(range) {
  11676. var center = this._findCenter(range);
  11677. center.x *= this.scale;
  11678. center.y *= this.scale;
  11679. center.x -= 0.5 * this.frame.canvas.clientWidth;
  11680. center.y -= 0.5 * this.frame.canvas.clientHeight;
  11681. this._setTranslation(-center.x,-center.y); // set at 0,0
  11682. };
  11683. /**
  11684. * This function zooms out to fit all data on screen based on amount of nodes
  11685. *
  11686. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  11687. */
  11688. Graph.prototype.zoomToFit = function(initialZoom) {
  11689. if (initialZoom === undefined) {
  11690. initialZoom = false;
  11691. }
  11692. var numberOfNodes = this.nodeIndices.length;
  11693. var range = this._getRange();
  11694. if (initialZoom == true) {
  11695. if (this.constants.clustering.enabled == true &&
  11696. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  11697. 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.
  11698. }
  11699. else {
  11700. 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.
  11701. }
  11702. }
  11703. else {
  11704. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  11705. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  11706. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  11707. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  11708. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  11709. }
  11710. if (zoomLevel > 1.0) {
  11711. zoomLevel = 1.0;
  11712. }
  11713. this.pinch.mousewheelScale = zoomLevel;
  11714. this._setScale(zoomLevel);
  11715. this._centerGraph(range);
  11716. this.start();
  11717. };
  11718. /**
  11719. * Update the this.nodeIndices with the most recent node index list
  11720. * @private
  11721. */
  11722. Graph.prototype._updateNodeIndexList = function() {
  11723. this._clearNodeIndexList();
  11724. for (var idx in this.nodes) {
  11725. if (this.nodes.hasOwnProperty(idx)) {
  11726. this.nodeIndices.push(idx);
  11727. }
  11728. }
  11729. };
  11730. /**
  11731. * Set nodes and edges, and optionally options as well.
  11732. *
  11733. * @param {Object} data Object containing parameters:
  11734. * {Array | DataSet | DataView} [nodes] Array with nodes
  11735. * {Array | DataSet | DataView} [edges] Array with edges
  11736. * {String} [dot] String containing data in DOT format
  11737. * {Options} [options] Object with options
  11738. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  11739. */
  11740. Graph.prototype.setData = function(data, disableStart) {
  11741. if (disableStart === undefined) {
  11742. disableStart = false;
  11743. }
  11744. if (data && data.dot && (data.nodes || data.edges)) {
  11745. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  11746. ' parameter pair "nodes" and "edges", but not both.');
  11747. }
  11748. // set options
  11749. this.setOptions(data && data.options);
  11750. // set all data
  11751. if (data && data.dot) {
  11752. // parse DOT file
  11753. if(data && data.dot) {
  11754. var dotData = vis.util.DOTToGraph(data.dot);
  11755. this.setData(dotData);
  11756. return;
  11757. }
  11758. }
  11759. else {
  11760. this._setNodes(data && data.nodes);
  11761. this._setEdges(data && data.edges);
  11762. }
  11763. this._putDataInSector();
  11764. if (!disableStart) {
  11765. // find a stable position or start animating to a stable position
  11766. if (this.stabilize) {
  11767. this._doStabilize();
  11768. }
  11769. this.moving = true;
  11770. this.start();
  11771. }
  11772. };
  11773. /**
  11774. * Set options
  11775. * @param {Object} options
  11776. */
  11777. Graph.prototype.setOptions = function (options) {
  11778. if (options) {
  11779. // retrieve parameter values
  11780. if (options.width !== undefined) {this.width = options.width;}
  11781. if (options.height !== undefined) {this.height = options.height;}
  11782. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  11783. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  11784. if (options.clustering) {
  11785. this.constants.clustering.enabled = true;
  11786. for (var prop in options.clustering) {
  11787. if (options.clustering.hasOwnProperty(prop)) {
  11788. this.constants.clustering[prop] = options.clustering[prop];
  11789. }
  11790. }
  11791. }
  11792. else if (options.clustering !== undefined) {
  11793. this.constants.clustering.enabled = false;
  11794. }
  11795. if (options.navigation) {
  11796. this.constants.navigation.enabled = true;
  11797. for (var prop in options.navigation) {
  11798. if (options.navigation.hasOwnProperty(prop)) {
  11799. this.constants.navigation[prop] = options.navigation[prop];
  11800. }
  11801. }
  11802. }
  11803. else if (options.navigation !== undefined) {
  11804. this.constants.navigation.enabled = false;
  11805. }
  11806. if (options.keyboard) {
  11807. this.constants.keyboard.enabled = true;
  11808. for (var prop in options.keyboard) {
  11809. if (options.keyboard.hasOwnProperty(prop)) {
  11810. this.constants.keyboard[prop] = options.keyboard[prop];
  11811. }
  11812. }
  11813. }
  11814. else if (options.keyboard !== undefined) {
  11815. this.constants.keyboard.enabled = false;
  11816. }
  11817. // TODO: work out these options and document them
  11818. if (options.edges) {
  11819. for (prop in options.edges) {
  11820. if (options.edges.hasOwnProperty(prop)) {
  11821. this.constants.edges[prop] = options.edges[prop];
  11822. }
  11823. }
  11824. if (options.edges.length !== undefined &&
  11825. options.nodes && options.nodes.distance === undefined) {
  11826. this.constants.edges.length = options.edges.length;
  11827. this.constants.nodes.distance = options.edges.length * 1.25;
  11828. }
  11829. if (!options.edges.fontColor) {
  11830. this.constants.edges.fontColor = options.edges.color;
  11831. }
  11832. // Added to support dashed lines
  11833. // David Jordan
  11834. // 2012-08-08
  11835. if (options.edges.dash) {
  11836. if (options.edges.dash.length !== undefined) {
  11837. this.constants.edges.dash.length = options.edges.dash.length;
  11838. }
  11839. if (options.edges.dash.gap !== undefined) {
  11840. this.constants.edges.dash.gap = options.edges.dash.gap;
  11841. }
  11842. if (options.edges.dash.altLength !== undefined) {
  11843. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  11844. }
  11845. }
  11846. }
  11847. if (options.nodes) {
  11848. for (prop in options.nodes) {
  11849. if (options.nodes.hasOwnProperty(prop)) {
  11850. this.constants.nodes[prop] = options.nodes[prop];
  11851. }
  11852. }
  11853. if (options.nodes.color) {
  11854. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  11855. }
  11856. /*
  11857. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  11858. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  11859. */
  11860. }
  11861. if (options.groups) {
  11862. for (var groupname in options.groups) {
  11863. if (options.groups.hasOwnProperty(groupname)) {
  11864. var group = options.groups[groupname];
  11865. this.groups.add(groupname, group);
  11866. }
  11867. }
  11868. }
  11869. }
  11870. this.setSize(this.width, this.height);
  11871. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  11872. this._setScale(1);
  11873. // load the navigation system.
  11874. this._loadNavigationControls();
  11875. // bind keys. If disabled, this will not do anything;
  11876. this._createKeyBinds();
  11877. this._redraw();
  11878. };
  11879. /**
  11880. * Add event listener
  11881. * @param {String} event Event name. Available events:
  11882. * 'select'
  11883. * @param {function} callback Callback function, invoked as callback(properties)
  11884. * where properties is an optional object containing
  11885. * event specific properties.
  11886. */
  11887. Graph.prototype.on = function on (event, callback) {
  11888. var available = ['select'];
  11889. if (available.indexOf(event) == -1) {
  11890. throw new Error('Unknown event "' + event + '". Choose from ' + available.join());
  11891. }
  11892. events.addListener(this, event, callback);
  11893. };
  11894. /**
  11895. * Remove an event listener
  11896. * @param {String} event Event name
  11897. * @param {function} callback Callback function
  11898. */
  11899. Graph.prototype.off = function off (event, callback) {
  11900. events.removeListener(this, event, callback);
  11901. };
  11902. /**
  11903. * fire an event
  11904. * @param {String} event The name of an event, for example 'select'
  11905. * @param {Object} params Optional object with event parameters
  11906. * @private
  11907. */
  11908. Graph.prototype._trigger = function (event, params) {
  11909. events.trigger(this, event, params);
  11910. };
  11911. /**
  11912. * Create the main frame for the Graph.
  11913. * This function is executed once when a Graph object is created. The frame
  11914. * contains a canvas, and this canvas contains all objects like the axis and
  11915. * nodes.
  11916. * @private
  11917. */
  11918. Graph.prototype._create = function () {
  11919. // remove all elements from the container element.
  11920. while (this.containerElement.hasChildNodes()) {
  11921. this.containerElement.removeChild(this.containerElement.firstChild);
  11922. }
  11923. this.frame = document.createElement('div');
  11924. this.frame.className = 'graph-frame';
  11925. this.frame.style.position = 'relative';
  11926. this.frame.style.overflow = 'hidden';
  11927. // create the graph canvas (HTML canvas element)
  11928. this.frame.canvas = document.createElement( 'canvas' );
  11929. this.frame.canvas.style.position = 'relative';
  11930. this.frame.appendChild(this.frame.canvas);
  11931. if (!this.frame.canvas.getContext) {
  11932. var noCanvas = document.createElement( 'DIV' );
  11933. noCanvas.style.color = 'red';
  11934. noCanvas.style.fontWeight = 'bold' ;
  11935. noCanvas.style.padding = '10px';
  11936. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  11937. this.frame.canvas.appendChild(noCanvas);
  11938. }
  11939. var me = this;
  11940. this.drag = {};
  11941. this.pinch = {};
  11942. this.hammer = Hammer(this.frame.canvas, {
  11943. prevent_default: true
  11944. });
  11945. this.hammer.on('tap', me._onTap.bind(me) );
  11946. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  11947. this.hammer.on('hold', me._onHold.bind(me) );
  11948. this.hammer.on('pinch', me._onPinch.bind(me) );
  11949. this.hammer.on('touch', me._onTouch.bind(me) );
  11950. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  11951. this.hammer.on('drag', me._onDrag.bind(me) );
  11952. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  11953. this.hammer.on('release', me._onRelease.bind(me) );
  11954. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  11955. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  11956. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  11957. // add the frame to the container element
  11958. this.containerElement.appendChild(this.frame);
  11959. };
  11960. /**
  11961. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  11962. * @private
  11963. */
  11964. Graph.prototype._createKeyBinds = function() {
  11965. var me = this;
  11966. this.mousetrap = mousetrap;
  11967. this.mousetrap.reset();
  11968. if (this.constants.keyboard.enabled == true) {
  11969. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  11970. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  11971. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  11972. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  11973. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  11974. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  11975. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  11976. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  11977. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  11978. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  11979. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  11980. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  11981. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  11982. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  11983. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  11984. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  11985. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  11986. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  11987. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  11988. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  11989. }
  11990. /*
  11991. this.mousetrap.bind("=",this.decreaseClusterLevel.bind(me));
  11992. this.mousetrap.bind("-",this.increaseClusterLevel.bind(me));
  11993. this.mousetrap.bind("s",this.singleStep.bind(me));
  11994. this.mousetrap.bind("h",this.updateClustersDefault.bind(me));
  11995. this.mousetrap.bind("c",this._collapseSector.bind(me));
  11996. this.mousetrap.bind("f",this.toggleFreeze.bind(me));
  11997. */
  11998. }
  11999. /**
  12000. * Get the pointer location from a touch location
  12001. * @param {{pageX: Number, pageY: Number}} touch
  12002. * @return {{x: Number, y: Number}} pointer
  12003. * @private
  12004. */
  12005. Graph.prototype._getPointer = function (touch) {
  12006. return {
  12007. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  12008. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  12009. };
  12010. };
  12011. /**
  12012. * On start of a touch gesture, store the pointer
  12013. * @param event
  12014. * @private
  12015. */
  12016. Graph.prototype._onTouch = function (event) {
  12017. this.drag.pointer = this._getPointer(event.gesture.touches[0]);
  12018. this.drag.pinched = false;
  12019. this.pinch.scale = this._getScale();
  12020. this._handleTouch(this.drag.pointer);
  12021. };
  12022. /**
  12023. * handle drag start event
  12024. * @private
  12025. */
  12026. Graph.prototype._onDragStart = function () {
  12027. var drag = this.drag;
  12028. var node = this._getNodeAt(drag.pointer);
  12029. // note: drag.pointer is set in _onTouch to get the initial touch location
  12030. drag.dragging = true;
  12031. drag.selection = [];
  12032. drag.translation = this._getTranslation();
  12033. drag.nodeId = null;
  12034. if (node != null) {
  12035. drag.nodeId = node.id;
  12036. // select the clicked node if not yet selected
  12037. if (!node.isSelected()) {
  12038. this._selectNode(node,false);
  12039. }
  12040. // create an array with the selected nodes and their original location and status
  12041. var me = this;
  12042. this.selection.forEach(function (id) {
  12043. var node = me.nodes[id];
  12044. if (node) {
  12045. var s = {
  12046. id: id,
  12047. node: node,
  12048. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  12049. x: node.x,
  12050. y: node.y,
  12051. xFixed: node.xFixed,
  12052. yFixed: node.yFixed
  12053. };
  12054. node.xFixed = true;
  12055. node.yFixed = true;
  12056. drag.selection.push(s);
  12057. }
  12058. });
  12059. }
  12060. };
  12061. /**
  12062. * handle drag event
  12063. * @private
  12064. */
  12065. Graph.prototype._onDrag = function (event) {
  12066. if (this.drag.pinched) {
  12067. return;
  12068. }
  12069. var pointer = this._getPointer(event.gesture.touches[0]);
  12070. var me = this,
  12071. drag = this.drag,
  12072. selection = drag.selection;
  12073. if (selection && selection.length) {
  12074. // calculate delta's and new location
  12075. var deltaX = pointer.x - drag.pointer.x,
  12076. deltaY = pointer.y - drag.pointer.y;
  12077. // update position of all selected nodes
  12078. selection.forEach(function (s) {
  12079. var node = s.node;
  12080. if (!s.xFixed) {
  12081. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  12082. }
  12083. if (!s.yFixed) {
  12084. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  12085. }
  12086. });
  12087. // start animation if not yet running
  12088. if (!this.moving) {
  12089. this.moving = true;
  12090. this.start();
  12091. }
  12092. }
  12093. else {
  12094. // move the graph
  12095. var diffX = pointer.x - this.drag.pointer.x;
  12096. var diffY = pointer.y - this.drag.pointer.y;
  12097. this._setTranslation(
  12098. this.drag.translation.x + diffX,
  12099. this.drag.translation.y + diffY);
  12100. this._redraw();
  12101. this.moved = true;
  12102. }
  12103. };
  12104. /**
  12105. * handle drag start event
  12106. * @private
  12107. */
  12108. Graph.prototype._onDragEnd = function () {
  12109. this.drag.dragging = false;
  12110. var selection = this.drag.selection;
  12111. if (selection) {
  12112. selection.forEach(function (s) {
  12113. // restore original xFixed and yFixed
  12114. s.node.xFixed = s.xFixed;
  12115. s.node.yFixed = s.yFixed;
  12116. });
  12117. }
  12118. };
  12119. /**
  12120. * handle tap/click event: select/unselect a node
  12121. * @private
  12122. */
  12123. Graph.prototype._onTap = function (event) {
  12124. var pointer = this._getPointer(event.gesture.touches[0]);
  12125. this._handleTap(pointer);
  12126. };
  12127. /**
  12128. * handle doubletap event
  12129. * @private
  12130. */
  12131. Graph.prototype._onDoubleTap = function (event) {
  12132. var pointer = this._getPointer(event.gesture.touches[0]);
  12133. this._handleDoubleTap(pointer);
  12134. };
  12135. /**
  12136. * handle long tap event: multi select nodes
  12137. * @private
  12138. */
  12139. Graph.prototype._onHold = function (event) {
  12140. var pointer = this._getPointer(event.gesture.touches[0]);
  12141. this._handleOnHold(pointer);
  12142. };
  12143. /**
  12144. * handle the release of the screen
  12145. *
  12146. * @param event
  12147. * @private
  12148. */
  12149. Graph.prototype._onRelease = function (event) {
  12150. this._handleOnRelease();
  12151. };
  12152. /**
  12153. * Handle pinch event
  12154. * @param event
  12155. * @private
  12156. */
  12157. Graph.prototype._onPinch = function (event) {
  12158. var pointer = this._getPointer(event.gesture.center);
  12159. this.drag.pinched = true;
  12160. if (!('scale' in this.pinch)) {
  12161. this.pinch.scale = 1;
  12162. }
  12163. // TODO: enabled moving while pinching?
  12164. var scale = this.pinch.scale * event.gesture.scale;
  12165. this._zoom(scale, pointer)
  12166. };
  12167. /**
  12168. * Zoom the graph in or out
  12169. * @param {Number} scale a number around 1, and between 0.01 and 10
  12170. * @param {{x: Number, y: Number}} pointer Position on screen
  12171. * @return {Number} appliedScale scale is limited within the boundaries
  12172. * @private
  12173. */
  12174. Graph.prototype._zoom = function(scale, pointer) {
  12175. var scaleOld = this._getScale();
  12176. if (scale < 0.00001) {
  12177. scale = 0.00001;
  12178. }
  12179. if (scale > 10) {
  12180. scale = 10;
  12181. }
  12182. // + this.frame.canvas.clientHeight / 2
  12183. var translation = this._getTranslation();
  12184. var scaleFrac = scale / scaleOld;
  12185. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  12186. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  12187. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  12188. "y" : this._canvasToY(pointer.y)};
  12189. // this.areaCenter = {"x" : pointer.x,"y" : pointer.y };
  12190. // console.log(translation.x,translation.y,pointer.x,pointer.y,scale);
  12191. this.pinch.mousewheelScale = scale;
  12192. this._setScale(scale);
  12193. this._setTranslation(tx, ty);
  12194. this.updateClustersDefault();
  12195. this._redraw();
  12196. return scale;
  12197. };
  12198. /**
  12199. * Event handler for mouse wheel event, used to zoom the timeline
  12200. * See http://adomas.org/javascript-mouse-wheel/
  12201. * https://github.com/EightMedia/hammer.js/issues/256
  12202. * @param {MouseEvent} event
  12203. * @private
  12204. */
  12205. Graph.prototype._onMouseWheel = function(event) {
  12206. // retrieve delta
  12207. var delta = 0;
  12208. if (event.wheelDelta) { /* IE/Opera. */
  12209. delta = event.wheelDelta/120;
  12210. } else if (event.detail) { /* Mozilla case. */
  12211. // In Mozilla, sign of delta is different than in IE.
  12212. // Also, delta is multiple of 3.
  12213. delta = -event.detail/3;
  12214. }
  12215. // If delta is nonzero, handle it.
  12216. // Basically, delta is now positive if wheel was scrolled up,
  12217. // and negative, if wheel was scrolled down.
  12218. if (delta) {
  12219. if (!('mousewheelScale' in this.pinch)) {
  12220. this.pinch.mousewheelScale = 1;
  12221. }
  12222. // calculate the new scale
  12223. var scale = this.pinch.mousewheelScale;
  12224. var zoom = delta / 10;
  12225. if (delta < 0) {
  12226. zoom = zoom / (1 - zoom);
  12227. }
  12228. scale *= (1 + zoom);
  12229. // calculate the pointer location
  12230. var gesture = util.fakeGesture(this, event);
  12231. var pointer = this._getPointer(gesture.center);
  12232. // apply the new scale
  12233. scale = this._zoom(scale, pointer);
  12234. // store the new, applied scale -- this is now done in _zoom
  12235. // this.pinch.mousewheelScale = scale;
  12236. }
  12237. // Prevent default actions caused by mouse wheel.
  12238. event.preventDefault();
  12239. };
  12240. /**
  12241. * Mouse move handler for checking whether the title moves over a node with a title.
  12242. * @param {Event} event
  12243. * @private
  12244. */
  12245. Graph.prototype._onMouseMoveTitle = function (event) {
  12246. var gesture = util.fakeGesture(this, event);
  12247. var pointer = this._getPointer(gesture.center);
  12248. // check if the previously selected node is still selected
  12249. if (this.popupNode) {
  12250. this._checkHidePopup(pointer);
  12251. }
  12252. // start a timeout that will check if the mouse is positioned above
  12253. // an element
  12254. var me = this;
  12255. var checkShow = function() {
  12256. me._checkShowPopup(pointer);
  12257. };
  12258. if (this.popupTimer) {
  12259. clearInterval(this.popupTimer); // stop any running calculationTimer
  12260. }
  12261. if (!this.drag.dragging) {
  12262. this.popupTimer = setTimeout(checkShow, 300);
  12263. }
  12264. };
  12265. /**
  12266. * Check if there is an element on the given position in the graph
  12267. * (a node or edge). If so, and if this element has a title,
  12268. * show a popup window with its title.
  12269. *
  12270. * @param {{x:Number, y:Number}} pointer
  12271. * @private
  12272. */
  12273. Graph.prototype._checkShowPopup = function (pointer) {
  12274. var obj = {
  12275. left: this._canvasToX(pointer.x),
  12276. top: this._canvasToY(pointer.y),
  12277. right: this._canvasToX(pointer.x),
  12278. bottom: this._canvasToY(pointer.y)
  12279. };
  12280. var id;
  12281. var lastPopupNode = this.popupNode;
  12282. if (this.popupNode == undefined) {
  12283. // search the nodes for overlap, select the top one in case of multiple nodes
  12284. var nodes = this.nodes;
  12285. for (id in nodes) {
  12286. if (nodes.hasOwnProperty(id)) {
  12287. var node = nodes[id];
  12288. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  12289. this.popupNode = node;
  12290. break;
  12291. }
  12292. }
  12293. }
  12294. }
  12295. if (this.popupNode === undefined) {
  12296. // search the edges for overlap
  12297. var edges = this.edges;
  12298. for (id in edges) {
  12299. if (edges.hasOwnProperty(id)) {
  12300. var edge = edges[id];
  12301. if (edge.connected && (edge.getTitle() !== undefined) &&
  12302. edge.isOverlappingWith(obj)) {
  12303. this.popupNode = edge;
  12304. break;
  12305. }
  12306. }
  12307. }
  12308. }
  12309. if (this.popupNode) {
  12310. // show popup message window
  12311. if (this.popupNode != lastPopupNode) {
  12312. var me = this;
  12313. if (!me.popup) {
  12314. me.popup = new Popup(me.frame);
  12315. }
  12316. // adjust a small offset such that the mouse cursor is located in the
  12317. // bottom left location of the popup, and you can easily move over the
  12318. // popup area
  12319. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  12320. me.popup.setText(me.popupNode.getTitle());
  12321. me.popup.show();
  12322. }
  12323. }
  12324. else {
  12325. if (this.popup) {
  12326. this.popup.hide();
  12327. }
  12328. }
  12329. };
  12330. /**
  12331. * Check if the popup must be hided, which is the case when the mouse is no
  12332. * longer hovering on the object
  12333. * @param {{x:Number, y:Number}} pointer
  12334. * @private
  12335. */
  12336. Graph.prototype._checkHidePopup = function (pointer) {
  12337. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  12338. this.popupNode = undefined;
  12339. if (this.popup) {
  12340. this.popup.hide();
  12341. }
  12342. }
  12343. };
  12344. /**
  12345. * Temporary method to test calculating a hub value for the nodes
  12346. * @param {number} level Maximum number edges between two nodes in order
  12347. * to call them connected. Optional, 1 by default
  12348. * @return {Number[]} connectioncount array with the connection count
  12349. * for each node
  12350. * @private
  12351. */
  12352. Graph.prototype._getConnectionCount = function(level) {
  12353. if (level == undefined) {
  12354. level = 1;
  12355. }
  12356. // get the nodes connected to given nodes
  12357. function getConnectedNodes(nodes) {
  12358. var connectedNodes = [];
  12359. for (var j = 0, jMax = nodes.length; j < jMax; j++) {
  12360. var node = nodes[j];
  12361. // find all nodes connected to this node
  12362. var edges = node.edges;
  12363. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  12364. var edge = edges[i];
  12365. var other = null;
  12366. // check if connected
  12367. if (edge.from == node)
  12368. other = edge.to;
  12369. else if (edge.to == node)
  12370. other = edge.from;
  12371. // check if the other node is not already in the list with nodes
  12372. var k, kMax;
  12373. if (other) {
  12374. for (k = 0, kMax = nodes.length; k < kMax; k++) {
  12375. if (nodes[k] == other) {
  12376. other = null;
  12377. break;
  12378. }
  12379. }
  12380. }
  12381. if (other) {
  12382. for (k = 0, kMax = connectedNodes.length; k < kMax; k++) {
  12383. if (connectedNodes[k] == other) {
  12384. other = null;
  12385. break;
  12386. }
  12387. }
  12388. }
  12389. if (other)
  12390. connectedNodes.push(other);
  12391. }
  12392. }
  12393. return connectedNodes;
  12394. }
  12395. var connections = [];
  12396. var nodes = this.nodes;
  12397. for (var id in nodes) {
  12398. if (nodes.hasOwnProperty(id)) {
  12399. var c = [nodes[id]];
  12400. for (var l = 0; l < level; l++) {
  12401. c = c.concat(getConnectedNodes(c));
  12402. }
  12403. connections.push(c);
  12404. }
  12405. }
  12406. var hubs = [];
  12407. for (var i = 0, len = connections.length; i < len; i++) {
  12408. hubs.push(connections[i].length);
  12409. }
  12410. return hubs;
  12411. };
  12412. /**
  12413. * Set a new size for the graph
  12414. * @param {string} width Width in pixels or percentage (for example '800px'
  12415. * or '50%')
  12416. * @param {string} height Height in pixels or percentage (for example '400px'
  12417. * or '30%')
  12418. */
  12419. Graph.prototype.setSize = function(width, height) {
  12420. this.frame.style.width = width;
  12421. this.frame.style.height = height;
  12422. this.frame.canvas.style.width = '100%';
  12423. this.frame.canvas.style.height = '100%';
  12424. this.frame.canvas.width = this.frame.canvas.clientWidth;
  12425. this.frame.canvas.height = this.frame.canvas.clientHeight;
  12426. if (this.constants.navigation.enabled == true) {
  12427. this._relocateNavigation();
  12428. }
  12429. };
  12430. /**
  12431. * Set a data set with nodes for the graph
  12432. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  12433. * @private
  12434. */
  12435. Graph.prototype._setNodes = function(nodes) {
  12436. var oldNodesData = this.nodesData;
  12437. if (nodes instanceof DataSet || nodes instanceof DataView) {
  12438. this.nodesData = nodes;
  12439. }
  12440. else if (nodes instanceof Array) {
  12441. this.nodesData = new DataSet();
  12442. this.nodesData.add(nodes);
  12443. }
  12444. else if (!nodes) {
  12445. this.nodesData = new DataSet();
  12446. }
  12447. else {
  12448. throw new TypeError('Array or DataSet expected');
  12449. }
  12450. if (oldNodesData) {
  12451. // unsubscribe from old dataset
  12452. util.forEach(this.nodesListeners, function (callback, event) {
  12453. oldNodesData.unsubscribe(event, callback);
  12454. });
  12455. }
  12456. // remove drawn nodes
  12457. this.nodes = {};
  12458. if (this.nodesData) {
  12459. // subscribe to new dataset
  12460. var me = this;
  12461. util.forEach(this.nodesListeners, function (callback, event) {
  12462. me.nodesData.subscribe(event, callback);
  12463. });
  12464. // draw all new nodes
  12465. var ids = this.nodesData.getIds();
  12466. this._addNodes(ids);
  12467. }
  12468. this._updateSelection();
  12469. };
  12470. /**
  12471. * Add nodes
  12472. * @param {Number[] | String[]} ids
  12473. * @private
  12474. */
  12475. Graph.prototype._addNodes = function(ids) {
  12476. var id;
  12477. for (var i = 0, len = ids.length; i < len; i++) {
  12478. id = ids[i];
  12479. var data = this.nodesData.get(id);
  12480. var node = new Node(data, this.images, this.groups, this.constants);
  12481. this.nodes[id] = node; // note: this may replace an existing node
  12482. if (!node.isFixed()) {
  12483. // TODO: position new nodes in a smarter way!
  12484. var radius = this.constants.edges.length * 2;
  12485. var count = ids.length;
  12486. var angle = 2 * Math.PI * (i / count);
  12487. node.x = radius * Math.cos(angle);
  12488. node.y = radius * Math.sin(angle);
  12489. // note: no not use node.isMoving() here, as that gives the current
  12490. // velocity of the node, which is zero after creation of the node.
  12491. this.moving = true;
  12492. }
  12493. }
  12494. this._updateNodeIndexList();
  12495. this._reconnectEdges();
  12496. this._updateValueRange(this.nodes);
  12497. };
  12498. /**
  12499. * Update existing nodes, or create them when not yet existing
  12500. * @param {Number[] | String[]} ids
  12501. * @private
  12502. */
  12503. Graph.prototype._updateNodes = function(ids) {
  12504. var nodes = this.nodes,
  12505. nodesData = this.nodesData;
  12506. for (var i = 0, len = ids.length; i < len; i++) {
  12507. var id = ids[i];
  12508. var node = nodes[id];
  12509. var data = nodesData.get(id);
  12510. if (node) {
  12511. // update node
  12512. node.setProperties(data, this.constants);
  12513. }
  12514. else {
  12515. // create node
  12516. node = new Node(properties, this.images, this.groups, this.constants);
  12517. nodes[id] = node;
  12518. if (!node.isFixed()) {
  12519. this.moving = true;
  12520. }
  12521. }
  12522. }
  12523. this._updateNodeIndexList();
  12524. this._reconnectEdges();
  12525. this._updateValueRange(nodes);
  12526. };
  12527. /**
  12528. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  12529. * @param {Number[] | String[]} ids
  12530. * @private
  12531. */
  12532. Graph.prototype._removeNodes = function(ids) {
  12533. var nodes = this.nodes;
  12534. for (var i = 0, len = ids.length; i < len; i++) {
  12535. var id = ids[i];
  12536. delete nodes[id];
  12537. }
  12538. this._updateNodeIndexList();
  12539. this._reconnectEdges();
  12540. this._updateSelection();
  12541. this._updateValueRange(nodes);
  12542. };
  12543. /**
  12544. * Load edges by reading the data table
  12545. * @param {Array | DataSet | DataView} edges The data containing the edges.
  12546. * @private
  12547. * @private
  12548. */
  12549. Graph.prototype._setEdges = function(edges) {
  12550. var oldEdgesData = this.edgesData;
  12551. if (edges instanceof DataSet || edges instanceof DataView) {
  12552. this.edgesData = edges;
  12553. }
  12554. else if (edges instanceof Array) {
  12555. this.edgesData = new DataSet();
  12556. this.edgesData.add(edges);
  12557. }
  12558. else if (!edges) {
  12559. this.edgesData = new DataSet();
  12560. }
  12561. else {
  12562. throw new TypeError('Array or DataSet expected');
  12563. }
  12564. if (oldEdgesData) {
  12565. // unsubscribe from old dataset
  12566. util.forEach(this.edgesListeners, function (callback, event) {
  12567. oldEdgesData.unsubscribe(event, callback);
  12568. });
  12569. }
  12570. // remove drawn edges
  12571. this.edges = {};
  12572. if (this.edgesData) {
  12573. // subscribe to new dataset
  12574. var me = this;
  12575. util.forEach(this.edgesListeners, function (callback, event) {
  12576. me.edgesData.subscribe(event, callback);
  12577. });
  12578. // draw all new nodes
  12579. var ids = this.edgesData.getIds();
  12580. this._addEdges(ids);
  12581. }
  12582. this._reconnectEdges();
  12583. };
  12584. /**
  12585. * Add edges
  12586. * @param {Number[] | String[]} ids
  12587. * @private
  12588. */
  12589. Graph.prototype._addEdges = function (ids) {
  12590. var edges = this.edges,
  12591. edgesData = this.edgesData;
  12592. for (var i = 0, len = ids.length; i < len; i++) {
  12593. var id = ids[i];
  12594. var oldEdge = edges[id];
  12595. if (oldEdge) {
  12596. oldEdge.disconnect();
  12597. }
  12598. var data = edgesData.get(id, {"showInternalIds" : true});
  12599. edges[id] = new Edge(data, this, this.constants);
  12600. }
  12601. this.moving = true;
  12602. this._updateValueRange(edges);
  12603. };
  12604. /**
  12605. * Update existing edges, or create them when not yet existing
  12606. * @param {Number[] | String[]} ids
  12607. * @private
  12608. */
  12609. Graph.prototype._updateEdges = function (ids) {
  12610. var edges = this.edges,
  12611. edgesData = this.edgesData;
  12612. for (var i = 0, len = ids.length; i < len; i++) {
  12613. var id = ids[i];
  12614. var data = edgesData.get(id);
  12615. var edge = edges[id];
  12616. if (edge) {
  12617. // update edge
  12618. edge.disconnect();
  12619. edge.setProperties(data, this.constants);
  12620. edge.connect();
  12621. }
  12622. else {
  12623. // create edge
  12624. edge = new Edge(data, this, this.constants);
  12625. this.edges[id] = edge;
  12626. }
  12627. }
  12628. this.moving = true;
  12629. this._updateValueRange(edges);
  12630. };
  12631. /**
  12632. * Remove existing edges. Non existing ids will be ignored
  12633. * @param {Number[] | String[]} ids
  12634. * @private
  12635. */
  12636. Graph.prototype._removeEdges = function (ids) {
  12637. var edges = this.edges;
  12638. for (var i = 0, len = ids.length; i < len; i++) {
  12639. var id = ids[i];
  12640. var edge = edges[id];
  12641. if (edge) {
  12642. edge.disconnect();
  12643. delete edges[id];
  12644. }
  12645. }
  12646. this.moving = true;
  12647. this._updateValueRange(edges);
  12648. };
  12649. /**
  12650. * Reconnect all edges
  12651. * @private
  12652. */
  12653. Graph.prototype._reconnectEdges = function() {
  12654. var id,
  12655. nodes = this.nodes,
  12656. edges = this.edges;
  12657. for (id in nodes) {
  12658. if (nodes.hasOwnProperty(id)) {
  12659. nodes[id].edges = [];
  12660. }
  12661. }
  12662. for (id in edges) {
  12663. if (edges.hasOwnProperty(id)) {
  12664. var edge = edges[id];
  12665. edge.from = null;
  12666. edge.to = null;
  12667. edge.connect();
  12668. }
  12669. }
  12670. };
  12671. /**
  12672. * Update the values of all object in the given array according to the current
  12673. * value range of the objects in the array.
  12674. * @param {Object} obj An object containing a set of Edges or Nodes
  12675. * The objects must have a method getValue() and
  12676. * setValueRange(min, max).
  12677. * @private
  12678. */
  12679. Graph.prototype._updateValueRange = function(obj) {
  12680. var id;
  12681. // determine the range of the objects
  12682. var valueMin = undefined;
  12683. var valueMax = undefined;
  12684. for (id in obj) {
  12685. if (obj.hasOwnProperty(id)) {
  12686. var value = obj[id].getValue();
  12687. if (value !== undefined) {
  12688. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  12689. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  12690. }
  12691. }
  12692. }
  12693. // adjust the range of all objects
  12694. if (valueMin !== undefined && valueMax !== undefined) {
  12695. for (id in obj) {
  12696. if (obj.hasOwnProperty(id)) {
  12697. obj[id].setValueRange(valueMin, valueMax);
  12698. }
  12699. }
  12700. }
  12701. };
  12702. /**
  12703. * Redraw the graph with the current data
  12704. * chart will be resized too.
  12705. */
  12706. Graph.prototype.redraw = function() {
  12707. this.setSize(this.width, this.height);
  12708. this._redraw();
  12709. };
  12710. /**
  12711. * Redraw the graph with the current data
  12712. * @private
  12713. */
  12714. Graph.prototype._redraw = function() {
  12715. var ctx = this.frame.canvas.getContext('2d');
  12716. // clear the canvas
  12717. var w = this.frame.canvas.width;
  12718. var h = this.frame.canvas.height;
  12719. ctx.clearRect(0, 0, w, h);
  12720. // set scaling and translation
  12721. ctx.save();
  12722. ctx.translate(this.translation.x, this.translation.y);
  12723. ctx.scale(this.scale, this.scale);
  12724. this.canvasTopLeft = {
  12725. "x": this._canvasToX(0),
  12726. "y": this._canvasToY(0)
  12727. };
  12728. this.canvasBottomRight = {
  12729. "x": this._canvasToX(this.frame.canvas.clientWidth),
  12730. "y": this._canvasToY(this.frame.canvas.clientHeight)
  12731. };
  12732. this._doInAllSectors("_drawAllSectorNodes",ctx);
  12733. this._doInAllSectors("_drawEdges",ctx);
  12734. this._doInAllSectors("_drawNodes",ctx);
  12735. // restore original scaling and translation
  12736. ctx.restore();
  12737. if (this.constants.navigation.enabled == true) {
  12738. this._doInNavigationSector("_drawNodes",ctx,true);
  12739. }
  12740. };
  12741. /**
  12742. * Set the translation of the graph
  12743. * @param {Number} offsetX Horizontal offset
  12744. * @param {Number} offsetY Vertical offset
  12745. * @private
  12746. */
  12747. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  12748. if (this.translation === undefined) {
  12749. this.translation = {
  12750. x: 0,
  12751. y: 0
  12752. };
  12753. }
  12754. if (offsetX !== undefined) {
  12755. this.translation.x = offsetX;
  12756. }
  12757. if (offsetY !== undefined) {
  12758. this.translation.y = offsetY;
  12759. }
  12760. };
  12761. /**
  12762. * Get the translation of the graph
  12763. * @return {Object} translation An object with parameters x and y, both a number
  12764. * @private
  12765. */
  12766. Graph.prototype._getTranslation = function() {
  12767. return {
  12768. x: this.translation.x,
  12769. y: this.translation.y
  12770. };
  12771. };
  12772. /**
  12773. * Scale the graph
  12774. * @param {Number} scale Scaling factor 1.0 is unscaled
  12775. * @private
  12776. */
  12777. Graph.prototype._setScale = function(scale) {
  12778. this.scale = scale;
  12779. };
  12780. /**
  12781. * Get the current scale of the graph
  12782. * @return {Number} scale Scaling factor 1.0 is unscaled
  12783. * @private
  12784. */
  12785. Graph.prototype._getScale = function() {
  12786. return this.scale;
  12787. };
  12788. /**
  12789. * Convert a horizontal point on the HTML canvas to the x-value of the model
  12790. * @param {number} x
  12791. * @returns {number}
  12792. * @private
  12793. */
  12794. Graph.prototype._canvasToX = function(x) {
  12795. return (x - this.translation.x) / this.scale;
  12796. };
  12797. /**
  12798. * Convert an x-value in the model to a horizontal point on the HTML canvas
  12799. * @param {number} x
  12800. * @returns {number}
  12801. * @private
  12802. */
  12803. Graph.prototype._xToCanvas = function(x) {
  12804. return x * this.scale + this.translation.x;
  12805. };
  12806. /**
  12807. * Convert a vertical point on the HTML canvas to the y-value of the model
  12808. * @param {number} y
  12809. * @returns {number}
  12810. * @private
  12811. */
  12812. Graph.prototype._canvasToY = function(y) {
  12813. return (y - this.translation.y) / this.scale;
  12814. };
  12815. /**
  12816. * Convert an y-value in the model to a vertical point on the HTML canvas
  12817. * @param {number} y
  12818. * @returns {number}
  12819. * @private
  12820. */
  12821. Graph.prototype._yToCanvas = function(y) {
  12822. return y * this.scale + this.translation.y ;
  12823. };
  12824. /**
  12825. * Redraw all nodes
  12826. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  12827. * @param {CanvasRenderingContext2D} ctx
  12828. * @param {Boolean} [alwaysShow]
  12829. * @private
  12830. */
  12831. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  12832. if (alwaysShow === undefined) {
  12833. alwaysShow = false;
  12834. }
  12835. // first draw the unselected nodes
  12836. var nodes = this.nodes;
  12837. var selected = [];
  12838. for (var id in nodes) {
  12839. if (nodes.hasOwnProperty(id)) {
  12840. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  12841. if (nodes[id].isSelected()) {
  12842. selected.push(id);
  12843. }
  12844. else {
  12845. if (nodes[id].inArea() || alwaysShow) {
  12846. nodes[id].draw(ctx);
  12847. }
  12848. }
  12849. }
  12850. }
  12851. // draw the selected nodes on top
  12852. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  12853. if (nodes[selected[s]].inArea() || alwaysShow) {
  12854. nodes[selected[s]].draw(ctx);
  12855. }
  12856. }
  12857. };
  12858. /**
  12859. * Redraw all edges
  12860. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  12861. * @param {CanvasRenderingContext2D} ctx
  12862. * @private
  12863. */
  12864. Graph.prototype._drawEdges = function(ctx) {
  12865. var edges = this.edges;
  12866. for (var id in edges) {
  12867. if (edges.hasOwnProperty(id)) {
  12868. var edge = edges[id];
  12869. edge.setScale(this.scale);
  12870. if (edge.connected) {
  12871. edges[id].draw(ctx);
  12872. }
  12873. }
  12874. }
  12875. };
  12876. /**
  12877. * Find a stable position for all nodes
  12878. * @private
  12879. */
  12880. Graph.prototype._doStabilize = function() {
  12881. //var start = new Date();
  12882. // find stable position
  12883. var count = 0;
  12884. var vmin = this.constants.minVelocity;
  12885. var stable = false;
  12886. while (!stable && count < this.constants.maxIterations) {
  12887. this._initializeForceCalculation();
  12888. this._discreteStepNodes();
  12889. stable = !this._isMoving(vmin);
  12890. count++;
  12891. }
  12892. this.zoomToFit();
  12893. // var end = new Date();
  12894. // console.log('Stabilized in ' + (end-start) + ' ms, ' + count + ' iterations' ); // TODO: cleanup
  12895. };
  12896. /**
  12897. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  12898. * if there is more than one node. If it is just one node, we dont calculate anything.
  12899. *
  12900. * @private
  12901. */
  12902. Graph.prototype._initializeForceCalculation = function() {
  12903. // stop calculation if there is only one node
  12904. if (this.nodeIndices.length == 1) {
  12905. this.nodes[this.nodeIndices[0]]._setForce(0,0);
  12906. }
  12907. else {
  12908. // if there are too many nodes on screen, we cluster without repositioning
  12909. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  12910. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  12911. }
  12912. // we now start the force calculation
  12913. this._calculateForces();
  12914. }
  12915. };
  12916. /**
  12917. * Calculate the external forces acting on the nodes
  12918. * Forces are caused by: edges, repulsing forces between nodes, gravity
  12919. * @private
  12920. */
  12921. Graph.prototype._calculateForces = function() {
  12922. // var screenCenterPos = {"x":(0.5*(this.canvasTopLeft.x + this.canvasBottomRight.x)),
  12923. // "y":(0.5*(this.canvasTopLeft.y + this.canvasBottomRight.y))}
  12924. // create a local edge to the nodes and edges, that is faster
  12925. var dx, dy, angle, distance, fx, fy,
  12926. repulsingForce, springForce, length, edgeLength,
  12927. node, node1, node2, edge, edgeId, i, j, nodeId, xCenter, yCenter;
  12928. var clusterSize;
  12929. var nodes = this.nodes;
  12930. var edges = this.edges;
  12931. // Gravity is required to keep separated groups from floating off
  12932. // the forces are reset to zero in this loop by using _setForce instead
  12933. // of _addForce
  12934. var gravity = 0.08 * this.forceFactor;
  12935. for (i = 0; i < this.nodeIndices.length; i++) {
  12936. node = nodes[this.nodeIndices[i]];
  12937. // gravity does not apply when we are in a pocket sector
  12938. if (this._sector() == "default") {
  12939. dx = -node.x;// + screenCenterPos.x;
  12940. dy = -node.y;// + screenCenterPos.y;
  12941. angle = Math.atan2(dy, dx);
  12942. fx = Math.cos(angle) * gravity;
  12943. fy = Math.sin(angle) * gravity;
  12944. }
  12945. else {
  12946. fx = 0;
  12947. fy = 0;
  12948. }
  12949. node._setForce(fx, fy);
  12950. node.updateDamping(this.nodeIndices.length);
  12951. }
  12952. // repulsing forces between nodes
  12953. var minimumDistance = this.constants.nodes.distance,
  12954. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  12955. // we loop from i over all but the last entree in the array
  12956. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  12957. for (i = 0; i < this.nodeIndices.length-1; i++) {
  12958. node1 = nodes[this.nodeIndices[i]];
  12959. for (j = i+1; j < this.nodeIndices.length; j++) {
  12960. node2 = nodes[this.nodeIndices[j]];
  12961. clusterSize = (node1.clusterSize + node2.clusterSize - 2);
  12962. dx = node2.x - node1.x;
  12963. dy = node2.y - node1.y;
  12964. distance = Math.sqrt(dx * dx + dy * dy);
  12965. // clusters have a larger region of influence
  12966. minimumDistance = (clusterSize == 0) ? this.constants.nodes.distance : (this.constants.nodes.distance * (1 + clusterSize * this.constants.clustering.distanceAmplification));
  12967. if (distance < 2*minimumDistance) { // at 2.0 * the minimum distance, the force is 0.000045
  12968. angle = Math.atan2(dy, dx);
  12969. if (distance < 0.5*minimumDistance) { // at 0.5 * the minimum distance, the force is 0.993307
  12970. repulsingForce = 1.0;
  12971. }
  12972. else {
  12973. // TODO: correct factor for repulsing force
  12974. //repulsingForce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12975. //repulsingForce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  12976. repulsingForce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)); // TODO: customize the repulsing force
  12977. }
  12978. // amplify the repulsion for clusters.
  12979. repulsingForce *= (clusterSize == 0) ? 1 : 1 + clusterSize * this.constants.clustering.forceAmplification;
  12980. repulsingForce *= this.forceFactor;
  12981. fx = Math.cos(angle) * repulsingForce;
  12982. fy = Math.sin(angle) * repulsingForce ;
  12983. node1._addForce(-fx, -fy);
  12984. node2._addForce(fx, fy);
  12985. }
  12986. }
  12987. }
  12988. /*
  12989. // repulsion of the edges on the nodes and
  12990. for (var nodeId in nodes) {
  12991. if (nodes.hasOwnProperty(nodeId)) {
  12992. node = nodes[nodeId];
  12993. for(var edgeId in edges) {
  12994. if (edges.hasOwnProperty(edgeId)) {
  12995. edge = edges[edgeId];
  12996. // get the center of the edge
  12997. xCenter = edge.from.x+(edge.to.x - edge.from.x)/2;
  12998. yCenter = edge.from.y+(edge.to.y - edge.from.y)/2;
  12999. // calculate normally distributed force
  13000. dx = node.x - xCenter;
  13001. dy = node.y - yCenter;
  13002. distance = Math.sqrt(dx * dx + dy * dy);
  13003. if (distance < 2*minimumDistance) { // at 2.0 * the minimum distance, the force is 0.000045
  13004. angle = Math.atan2(dy, dx);
  13005. if (distance < 0.5*minimumDistance) { // at 0.5 * the minimum distance, the force is 0.993307
  13006. repulsingForce = 1.0;
  13007. }
  13008. else {
  13009. // TODO: correct factor for repulsing force
  13010. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  13011. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  13012. repulsingForce = 1 / (1 + Math.exp((distance / (minimumDistance / 2) - 1) * steepness)); // TODO: customize the repulsing force
  13013. }
  13014. fx = Math.cos(angle) * repulsingForce;
  13015. fy = Math.sin(angle) * repulsingForce;
  13016. node._addForce(fx, fy);
  13017. edge.from._addForce(-fx/2,-fy/2);
  13018. edge.to._addForce(-fx/2,-fy/2);
  13019. }
  13020. }
  13021. }
  13022. }
  13023. }
  13024. */
  13025. // forces caused by the edges, modelled as springs
  13026. for (edgeId in edges) {
  13027. if (edges.hasOwnProperty(edgeId)) {
  13028. edge = edges[edgeId];
  13029. if (edge.connected) {
  13030. // only calculate forces if nodes are in the same sector
  13031. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  13032. clusterSize = (edge.to.clusterSize + edge.from.clusterSize - 2);
  13033. dx = (edge.to.x - edge.from.x);
  13034. dy = (edge.to.y - edge.from.y);
  13035. //edgeLength = (edge.from.width + edge.from.height + edge.to.width + edge.to.height)/2 || edge.length; // TODO: dmin
  13036. //edgeLength = (edge.from.width + edge.to.width)/2 || edge.length; // TODO: dmin
  13037. //edgeLength = 20 + ((edge.from.width + edge.to.width) || 0) / 2;
  13038. edgeLength = edge.length;
  13039. // this implies that the edges between big clusters are longer
  13040. edgeLength += clusterSize * this.constants.clustering.edgeGrowth;
  13041. length = Math.sqrt(dx * dx + dy * dy);
  13042. angle = Math.atan2(dy, dx);
  13043. springForce = edge.stiffness * (edgeLength - length) * this.forceFactor;
  13044. fx = Math.cos(angle) * springForce;
  13045. fy = Math.sin(angle) * springForce;
  13046. edge.from._addForce(-fx, -fy);
  13047. edge.to._addForce(fx, fy);
  13048. }
  13049. }
  13050. }
  13051. }
  13052. /*
  13053. // TODO: re-implement repulsion of edges
  13054. // repulsing forces between edges
  13055. var minimumDistance = this.constants.edges.distance,
  13056. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  13057. for (var l = 0; l < edges.length; l++) {
  13058. //Keep distance from other edge centers
  13059. for (var l2 = l + 1; l2 < this.edges.length; l2++) {
  13060. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  13061. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  13062. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  13063. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  13064. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  13065. l2x = edges[l2].from.x+(edges[l2].to.x - edges[l2].from.x)/2,
  13066. l2y = edges[l2].from.y+(edges[l2].to.y - edges[l2].from.y)/2,
  13067. // calculate normally distributed force
  13068. dx = l2x - lx,
  13069. dy = l2y - ly,
  13070. distance = Math.sqrt(dx * dx + dy * dy),
  13071. angle = Math.atan2(dy, dx),
  13072. // TODO: correct factor for repulsing force
  13073. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  13074. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  13075. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  13076. fx = Math.cos(angle) * repulsingforce,
  13077. fy = Math.sin(angle) * repulsingforce;
  13078. edges[l].from._addForce(-fx, -fy);
  13079. edges[l].to._addForce(-fx, -fy);
  13080. edges[l2].from._addForce(fx, fy);
  13081. edges[l2].to._addForce(fx, fy);
  13082. }
  13083. }
  13084. */
  13085. };
  13086. /**
  13087. * Check if any of the nodes is still moving
  13088. * @param {number} vmin the minimum velocity considered as 'moving'
  13089. * @return {boolean} true if moving, false if non of the nodes is moving
  13090. * @private
  13091. */
  13092. Graph.prototype._isMoving = function(vmin) {
  13093. var vminCorrected = vmin / this.scale;
  13094. var nodes = this.nodes;
  13095. for (var id in nodes) {
  13096. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vminCorrected)) {
  13097. return true;
  13098. }
  13099. }
  13100. return false;
  13101. };
  13102. /**
  13103. * /**
  13104. * Perform one discrete step for all nodes
  13105. *
  13106. * @param interval
  13107. * @private
  13108. */
  13109. Graph.prototype._discreteStepNodes = function() {
  13110. var interval = 0.01;
  13111. var nodes = this.nodes;
  13112. for (var id in nodes) {
  13113. if (nodes.hasOwnProperty(id)) {
  13114. nodes[id].discreteStep(interval);
  13115. }
  13116. }
  13117. var vmin = this.constants.minVelocity;
  13118. this.moving = this._isMoving(vmin);
  13119. };
  13120. /**
  13121. * Start animating nodes and edges
  13122. *
  13123. * @poram {Boolean} runCalculationStep
  13124. */
  13125. Graph.prototype.start = function() {
  13126. if (!this.freezeSimulation) {
  13127. if (this.moving) {
  13128. this._doInAllActiveSectors("_initializeForceCalculation");
  13129. this._doInAllActiveSectors("_discreteStepNodes");
  13130. this._findCenter(this._getRange())
  13131. }
  13132. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  13133. // start animation. only start calculationTimer if it is not already running
  13134. if (!this.timer) {
  13135. var graph = this;
  13136. this.timer = window.setTimeout(function () {
  13137. graph.timer = undefined;
  13138. // keyboad movement
  13139. if (graph.xIncrement != 0 || graph.yIncrement != 0) {
  13140. var translation = graph._getTranslation();
  13141. graph._setTranslation(translation.x+graph.xIncrement, translation.y+graph.yIncrement);
  13142. }
  13143. if (graph.zoomIncrement != 0) {
  13144. var center = {
  13145. x: graph.frame.canvas.clientWidth / 2,
  13146. y: graph.frame.canvas.clientHeight / 2
  13147. };
  13148. graph._zoom(graph.scale*(1 + graph.zoomIncrement), center);
  13149. }
  13150. graph.start();
  13151. graph._redraw();
  13152. //this.end = window.performance.now();
  13153. //this.time = this.end - this.startTime;
  13154. //console.log('refresh time: ' + this.time);
  13155. //this.startTime = window.performance.now();
  13156. }, this.renderTimestep);
  13157. }
  13158. }
  13159. else {
  13160. this._redraw();
  13161. }
  13162. }
  13163. };
  13164. Graph.prototype.singleStep = function() {
  13165. if (this.moving) {
  13166. this._initializeForceCalculation();
  13167. this._discreteStepNodes();
  13168. var vmin = this.constants.minVelocity;
  13169. this.moving = this._isMoving(vmin);
  13170. this._redraw();
  13171. }
  13172. };
  13173. /**
  13174. * Freeze the animation
  13175. */
  13176. Graph.prototype.toggleFreeze = function() {
  13177. if (this.freezeSimulation == false) {
  13178. this.freezeSimulation = true;
  13179. }
  13180. else {
  13181. this.freezeSimulation = false;
  13182. this.start();
  13183. }
  13184. };
  13185. /**
  13186. * Mixin the cluster system and initialize the parameters required.
  13187. *
  13188. * @private
  13189. */
  13190. Graph.prototype._loadClusterSystem = function() {
  13191. this.clusterSession = 0;
  13192. this.hubThreshold = 5;
  13193. for (var mixinFunction in ClusterMixin) {
  13194. if (ClusterMixin.hasOwnProperty(mixinFunction)) {
  13195. Graph.prototype[mixinFunction] = ClusterMixin[mixinFunction];
  13196. }
  13197. }
  13198. }
  13199. /**
  13200. * Mixin the sector system and initialize the parameters required
  13201. *
  13202. * @private
  13203. */
  13204. Graph.prototype._loadSectorSystem = function() {
  13205. this.sectors = {};
  13206. this.activeSector = ["default"];
  13207. this.sectors["active"] = {};
  13208. this.sectors["active"]["default"] = {"nodes":{},
  13209. "edges":{},
  13210. "nodeIndices":[],
  13211. "formationScale": 1.0,
  13212. "drawingNode": undefined};
  13213. this.sectors["frozen"] = {};
  13214. this.sectors["navigation"] = {"nodes":{},
  13215. "edges":{},
  13216. "nodeIndices":[],
  13217. "formationScale": 1.0,
  13218. "drawingNode": undefined};
  13219. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13220. for (var mixinFunction in SectorMixin) {
  13221. if (SectorMixin.hasOwnProperty(mixinFunction)) {
  13222. Graph.prototype[mixinFunction] = SectorMixin[mixinFunction];
  13223. }
  13224. }
  13225. };
  13226. /**
  13227. * Mixin the selection system and initialize the parameters required
  13228. *
  13229. * @private
  13230. */
  13231. Graph.prototype._loadSelectionSystem = function() {
  13232. this.selection = [];
  13233. this.selectionObj = {};
  13234. for (var mixinFunction in SelectionMixin) {
  13235. if (SelectionMixin.hasOwnProperty(mixinFunction)) {
  13236. Graph.prototype[mixinFunction] = SelectionMixin[mixinFunction];
  13237. }
  13238. }
  13239. }
  13240. /**
  13241. * Mixin the navigation (User Interface) system and initialize the parameters required
  13242. *
  13243. * @private
  13244. */
  13245. Graph.prototype._loadNavigationControls = function() {
  13246. for (var mixinFunction in NavigationMixin) {
  13247. if (NavigationMixin.hasOwnProperty(mixinFunction)) {
  13248. Graph.prototype[mixinFunction] = NavigationMixin[mixinFunction];
  13249. }
  13250. }
  13251. if (this.constants.navigation.enabled == true) {
  13252. this._loadNavigationElements();
  13253. }
  13254. }
  13255. /**
  13256. * this function exists to avoid errors when not loading the navigation system
  13257. */
  13258. Graph.prototype._relocateNavigation = function() {
  13259. // empty, is overloaded by navigation system
  13260. }
  13261. /**
  13262. * * this function exists to avoid errors when not loading the navigation system
  13263. */
  13264. Graph.prototype._unHighlightAll = function() {
  13265. // empty, is overloaded by the navigation system
  13266. }
  13267. /**
  13268. * vis.js module exports
  13269. */
  13270. var vis = {
  13271. util: util,
  13272. events: events,
  13273. Controller: Controller,
  13274. DataSet: DataSet,
  13275. DataView: DataView,
  13276. Range: Range,
  13277. Stack: Stack,
  13278. TimeStep: TimeStep,
  13279. EventBus: EventBus,
  13280. components: {
  13281. items: {
  13282. Item: Item,
  13283. ItemBox: ItemBox,
  13284. ItemPoint: ItemPoint,
  13285. ItemRange: ItemRange
  13286. },
  13287. Component: Component,
  13288. Panel: Panel,
  13289. RootPanel: RootPanel,
  13290. ItemSet: ItemSet,
  13291. TimeAxis: TimeAxis
  13292. },
  13293. graph: {
  13294. Node: Node,
  13295. Edge: Edge,
  13296. Popup: Popup,
  13297. Groups: Groups,
  13298. Images: Images
  13299. },
  13300. Timeline: Timeline,
  13301. Graph: Graph
  13302. };
  13303. /**
  13304. * CommonJS module exports
  13305. */
  13306. if (typeof exports !== 'undefined') {
  13307. exports = vis;
  13308. }
  13309. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  13310. module.exports = vis;
  13311. }
  13312. /**
  13313. * AMD module exports
  13314. */
  13315. if (typeof(define) === 'function') {
  13316. define(function () {
  13317. return vis;
  13318. });
  13319. }
  13320. /**
  13321. * Window exports
  13322. */
  13323. if (typeof window !== 'undefined') {
  13324. // attach the module to the window, load as a regular javascript file
  13325. window['vis'] = vis;
  13326. }
  13327. },{"hammerjs":2,"moment":3,"mousetrap":4}],2:[function(require,module,exports){
  13328. /*! Hammer.JS - v1.0.5 - 2013-04-07
  13329. * http://eightmedia.github.com/hammer.js
  13330. *
  13331. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  13332. * Licensed under the MIT license */
  13333. (function(window, undefined) {
  13334. 'use strict';
  13335. /**
  13336. * Hammer
  13337. * use this to create instances
  13338. * @param {HTMLElement} element
  13339. * @param {Object} options
  13340. * @returns {Hammer.Instance}
  13341. * @constructor
  13342. */
  13343. var Hammer = function(element, options) {
  13344. return new Hammer.Instance(element, options || {});
  13345. };
  13346. // default settings
  13347. Hammer.defaults = {
  13348. // add styles and attributes to the element to prevent the browser from doing
  13349. // its native behavior. this doesnt prevent the scrolling, but cancels
  13350. // the contextmenu, tap highlighting etc
  13351. // set to false to disable this
  13352. stop_browser_behavior: {
  13353. // this also triggers onselectstart=false for IE
  13354. userSelect: 'none',
  13355. // this makes the element blocking in IE10 >, you could experiment with the value
  13356. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  13357. touchAction: 'none',
  13358. touchCallout: 'none',
  13359. contentZooming: 'none',
  13360. userDrag: 'none',
  13361. tapHighlightColor: 'rgba(0,0,0,0)'
  13362. }
  13363. // more settings are defined per gesture at gestures.js
  13364. };
  13365. // detect touchevents
  13366. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  13367. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  13368. // dont use mouseevents on mobile devices
  13369. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  13370. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  13371. // eventtypes per touchevent (start, move, end)
  13372. // are filled by Hammer.event.determineEventTypes on setup
  13373. Hammer.EVENT_TYPES = {};
  13374. // direction defines
  13375. Hammer.DIRECTION_DOWN = 'down';
  13376. Hammer.DIRECTION_LEFT = 'left';
  13377. Hammer.DIRECTION_UP = 'up';
  13378. Hammer.DIRECTION_RIGHT = 'right';
  13379. // pointer type
  13380. Hammer.POINTER_MOUSE = 'mouse';
  13381. Hammer.POINTER_TOUCH = 'touch';
  13382. Hammer.POINTER_PEN = 'pen';
  13383. // touch event defines
  13384. Hammer.EVENT_START = 'start';
  13385. Hammer.EVENT_MOVE = 'move';
  13386. Hammer.EVENT_END = 'end';
  13387. // hammer document where the base events are added at
  13388. Hammer.DOCUMENT = document;
  13389. // plugins namespace
  13390. Hammer.plugins = {};
  13391. // if the window events are set...
  13392. Hammer.READY = false;
  13393. /**
  13394. * setup events to detect gestures on the document
  13395. */
  13396. function setup() {
  13397. if(Hammer.READY) {
  13398. return;
  13399. }
  13400. // find what eventtypes we add listeners to
  13401. Hammer.event.determineEventTypes();
  13402. // Register all gestures inside Hammer.gestures
  13403. for(var name in Hammer.gestures) {
  13404. if(Hammer.gestures.hasOwnProperty(name)) {
  13405. Hammer.detection.register(Hammer.gestures[name]);
  13406. }
  13407. }
  13408. // Add touch events on the document
  13409. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  13410. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  13411. // Hammer is ready...!
  13412. Hammer.READY = true;
  13413. }
  13414. /**
  13415. * create new hammer instance
  13416. * all methods should return the instance itself, so it is chainable.
  13417. * @param {HTMLElement} element
  13418. * @param {Object} [options={}]
  13419. * @returns {Hammer.Instance}
  13420. * @constructor
  13421. */
  13422. Hammer.Instance = function(element, options) {
  13423. var self = this;
  13424. // setup HammerJS window events and register all gestures
  13425. // this also sets up the default options
  13426. setup();
  13427. this.element = element;
  13428. // start/stop detection option
  13429. this.enabled = true;
  13430. // merge options
  13431. this.options = Hammer.utils.extend(
  13432. Hammer.utils.extend({}, Hammer.defaults),
  13433. options || {});
  13434. // add some css to the element to prevent the browser from doing its native behavoir
  13435. if(this.options.stop_browser_behavior) {
  13436. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  13437. }
  13438. // start detection on touchstart
  13439. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  13440. if(self.enabled) {
  13441. Hammer.detection.startDetect(self, ev);
  13442. }
  13443. });
  13444. // return instance
  13445. return this;
  13446. };
  13447. Hammer.Instance.prototype = {
  13448. /**
  13449. * bind events to the instance
  13450. * @param {String} gesture
  13451. * @param {Function} handler
  13452. * @returns {Hammer.Instance}
  13453. */
  13454. on: function onEvent(gesture, handler){
  13455. var gestures = gesture.split(' ');
  13456. for(var t=0; t<gestures.length; t++) {
  13457. this.element.addEventListener(gestures[t], handler, false);
  13458. }
  13459. return this;
  13460. },
  13461. /**
  13462. * unbind events to the instance
  13463. * @param {String} gesture
  13464. * @param {Function} handler
  13465. * @returns {Hammer.Instance}
  13466. */
  13467. off: function offEvent(gesture, handler){
  13468. var gestures = gesture.split(' ');
  13469. for(var t=0; t<gestures.length; t++) {
  13470. this.element.removeEventListener(gestures[t], handler, false);
  13471. }
  13472. return this;
  13473. },
  13474. /**
  13475. * trigger gesture event
  13476. * @param {String} gesture
  13477. * @param {Object} eventData
  13478. * @returns {Hammer.Instance}
  13479. */
  13480. trigger: function triggerEvent(gesture, eventData){
  13481. // create DOM event
  13482. var event = Hammer.DOCUMENT.createEvent('Event');
  13483. event.initEvent(gesture, true, true);
  13484. event.gesture = eventData;
  13485. // trigger on the target if it is in the instance element,
  13486. // this is for event delegation tricks
  13487. var element = this.element;
  13488. if(Hammer.utils.hasParent(eventData.target, element)) {
  13489. element = eventData.target;
  13490. }
  13491. element.dispatchEvent(event);
  13492. return this;
  13493. },
  13494. /**
  13495. * enable of disable hammer.js detection
  13496. * @param {Boolean} state
  13497. * @returns {Hammer.Instance}
  13498. */
  13499. enable: function enable(state) {
  13500. this.enabled = state;
  13501. return this;
  13502. }
  13503. };
  13504. /**
  13505. * this holds the last move event,
  13506. * used to fix empty touchend issue
  13507. * see the onTouch event for an explanation
  13508. * @type {Object}
  13509. */
  13510. var last_move_event = null;
  13511. /**
  13512. * when the mouse is hold down, this is true
  13513. * @type {Boolean}
  13514. */
  13515. var enable_detect = false;
  13516. /**
  13517. * when touch events have been fired, this is true
  13518. * @type {Boolean}
  13519. */
  13520. var touch_triggered = false;
  13521. Hammer.event = {
  13522. /**
  13523. * simple addEventListener
  13524. * @param {HTMLElement} element
  13525. * @param {String} type
  13526. * @param {Function} handler
  13527. */
  13528. bindDom: function(element, type, handler) {
  13529. var types = type.split(' ');
  13530. for(var t=0; t<types.length; t++) {
  13531. element.addEventListener(types[t], handler, false);
  13532. }
  13533. },
  13534. /**
  13535. * touch events with mouse fallback
  13536. * @param {HTMLElement} element
  13537. * @param {String} eventType like Hammer.EVENT_MOVE
  13538. * @param {Function} handler
  13539. */
  13540. onTouch: function onTouch(element, eventType, handler) {
  13541. var self = this;
  13542. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  13543. var sourceEventType = ev.type.toLowerCase();
  13544. // onmouseup, but when touchend has been fired we do nothing.
  13545. // this is for touchdevices which also fire a mouseup on touchend
  13546. if(sourceEventType.match(/mouse/) && touch_triggered) {
  13547. return;
  13548. }
  13549. // mousebutton must be down or a touch event
  13550. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  13551. sourceEventType.match(/pointerdown/) || // pointerevents touch
  13552. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  13553. ){
  13554. enable_detect = true;
  13555. }
  13556. // we are in a touch event, set the touch triggered bool to true,
  13557. // this for the conflicts that may occur on ios and android
  13558. if(sourceEventType.match(/touch|pointer/)) {
  13559. touch_triggered = true;
  13560. }
  13561. // count the total touches on the screen
  13562. var count_touches = 0;
  13563. // when touch has been triggered in this detection session
  13564. // and we are now handling a mouse event, we stop that to prevent conflicts
  13565. if(enable_detect) {
  13566. // update pointerevent
  13567. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  13568. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  13569. }
  13570. // touch
  13571. else if(sourceEventType.match(/touch/)) {
  13572. count_touches = ev.touches.length;
  13573. }
  13574. // mouse
  13575. else if(!touch_triggered) {
  13576. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  13577. }
  13578. // if we are in a end event, but when we remove one touch and
  13579. // we still have enough, set eventType to move
  13580. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  13581. eventType = Hammer.EVENT_MOVE;
  13582. }
  13583. // no touches, force the end event
  13584. else if(!count_touches) {
  13585. eventType = Hammer.EVENT_END;
  13586. }
  13587. // because touchend has no touches, and we often want to use these in our gestures,
  13588. // we send the last move event as our eventData in touchend
  13589. if(!count_touches && last_move_event !== null) {
  13590. ev = last_move_event;
  13591. }
  13592. // store the last move event
  13593. else {
  13594. last_move_event = ev;
  13595. }
  13596. // trigger the handler
  13597. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  13598. // remove pointerevent from list
  13599. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  13600. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  13601. }
  13602. }
  13603. //debug(sourceEventType +" "+ eventType);
  13604. // on the end we reset everything
  13605. if(!count_touches) {
  13606. last_move_event = null;
  13607. enable_detect = false;
  13608. touch_triggered = false;
  13609. Hammer.PointerEvent.reset();
  13610. }
  13611. });
  13612. },
  13613. /**
  13614. * we have different events for each device/browser
  13615. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  13616. */
  13617. determineEventTypes: function determineEventTypes() {
  13618. // determine the eventtype we want to set
  13619. var types;
  13620. // pointerEvents magic
  13621. if(Hammer.HAS_POINTEREVENTS) {
  13622. types = Hammer.PointerEvent.getEvents();
  13623. }
  13624. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  13625. else if(Hammer.NO_MOUSEEVENTS) {
  13626. types = [
  13627. 'touchstart',
  13628. 'touchmove',
  13629. 'touchend touchcancel'];
  13630. }
  13631. // for non pointer events browsers and mixed browsers,
  13632. // like chrome on windows8 touch laptop
  13633. else {
  13634. types = [
  13635. 'touchstart mousedown',
  13636. 'touchmove mousemove',
  13637. 'touchend touchcancel mouseup'];
  13638. }
  13639. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  13640. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  13641. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  13642. },
  13643. /**
  13644. * create touchlist depending on the event
  13645. * @param {Object} ev
  13646. * @param {String} eventType used by the fakemultitouch plugin
  13647. */
  13648. getTouchList: function getTouchList(ev/*, eventType*/) {
  13649. // get the fake pointerEvent touchlist
  13650. if(Hammer.HAS_POINTEREVENTS) {
  13651. return Hammer.PointerEvent.getTouchList();
  13652. }
  13653. // get the touchlist
  13654. else if(ev.touches) {
  13655. return ev.touches;
  13656. }
  13657. // make fake touchlist from mouse position
  13658. else {
  13659. return [{
  13660. identifier: 1,
  13661. pageX: ev.pageX,
  13662. pageY: ev.pageY,
  13663. target: ev.target
  13664. }];
  13665. }
  13666. },
  13667. /**
  13668. * collect event data for Hammer js
  13669. * @param {HTMLElement} element
  13670. * @param {String} eventType like Hammer.EVENT_MOVE
  13671. * @param {Object} eventData
  13672. */
  13673. collectEventData: function collectEventData(element, eventType, ev) {
  13674. var touches = this.getTouchList(ev, eventType);
  13675. // find out pointerType
  13676. var pointerType = Hammer.POINTER_TOUCH;
  13677. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  13678. pointerType = Hammer.POINTER_MOUSE;
  13679. }
  13680. return {
  13681. center : Hammer.utils.getCenter(touches),
  13682. timeStamp : new Date().getTime(),
  13683. target : ev.target,
  13684. touches : touches,
  13685. eventType : eventType,
  13686. pointerType : pointerType,
  13687. srcEvent : ev,
  13688. /**
  13689. * prevent the browser default actions
  13690. * mostly used to disable scrolling of the browser
  13691. */
  13692. preventDefault: function() {
  13693. if(this.srcEvent.preventManipulation) {
  13694. this.srcEvent.preventManipulation();
  13695. }
  13696. if(this.srcEvent.preventDefault) {
  13697. this.srcEvent.preventDefault();
  13698. }
  13699. },
  13700. /**
  13701. * stop bubbling the event up to its parents
  13702. */
  13703. stopPropagation: function() {
  13704. this.srcEvent.stopPropagation();
  13705. },
  13706. /**
  13707. * immediately stop gesture detection
  13708. * might be useful after a swipe was detected
  13709. * @return {*}
  13710. */
  13711. stopDetect: function() {
  13712. return Hammer.detection.stopDetect();
  13713. }
  13714. };
  13715. }
  13716. };
  13717. Hammer.PointerEvent = {
  13718. /**
  13719. * holds all pointers
  13720. * @type {Object}
  13721. */
  13722. pointers: {},
  13723. /**
  13724. * get a list of pointers
  13725. * @returns {Array} touchlist
  13726. */
  13727. getTouchList: function() {
  13728. var self = this;
  13729. var touchlist = [];
  13730. // we can use forEach since pointerEvents only is in IE10
  13731. Object.keys(self.pointers).sort().forEach(function(id) {
  13732. touchlist.push(self.pointers[id]);
  13733. });
  13734. return touchlist;
  13735. },
  13736. /**
  13737. * update the position of a pointer
  13738. * @param {String} type Hammer.EVENT_END
  13739. * @param {Object} pointerEvent
  13740. */
  13741. updatePointer: function(type, pointerEvent) {
  13742. if(type == Hammer.EVENT_END) {
  13743. this.pointers = {};
  13744. }
  13745. else {
  13746. pointerEvent.identifier = pointerEvent.pointerId;
  13747. this.pointers[pointerEvent.pointerId] = pointerEvent;
  13748. }
  13749. return Object.keys(this.pointers).length;
  13750. },
  13751. /**
  13752. * check if ev matches pointertype
  13753. * @param {String} pointerType Hammer.POINTER_MOUSE
  13754. * @param {PointerEvent} ev
  13755. */
  13756. matchType: function(pointerType, ev) {
  13757. if(!ev.pointerType) {
  13758. return false;
  13759. }
  13760. var types = {};
  13761. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  13762. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  13763. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  13764. return types[pointerType];
  13765. },
  13766. /**
  13767. * get events
  13768. */
  13769. getEvents: function() {
  13770. return [
  13771. 'pointerdown MSPointerDown',
  13772. 'pointermove MSPointerMove',
  13773. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  13774. ];
  13775. },
  13776. /**
  13777. * reset the list
  13778. */
  13779. reset: function() {
  13780. this.pointers = {};
  13781. }
  13782. };
  13783. Hammer.utils = {
  13784. /**
  13785. * extend method,
  13786. * also used for cloning when dest is an empty object
  13787. * @param {Object} dest
  13788. * @param {Object} src
  13789. * @parm {Boolean} merge do a merge
  13790. * @returns {Object} dest
  13791. */
  13792. extend: function extend(dest, src, merge) {
  13793. for (var key in src) {
  13794. if(dest[key] !== undefined && merge) {
  13795. continue;
  13796. }
  13797. dest[key] = src[key];
  13798. }
  13799. return dest;
  13800. },
  13801. /**
  13802. * find if a node is in the given parent
  13803. * used for event delegation tricks
  13804. * @param {HTMLElement} node
  13805. * @param {HTMLElement} parent
  13806. * @returns {boolean} has_parent
  13807. */
  13808. hasParent: function(node, parent) {
  13809. while(node){
  13810. if(node == parent) {
  13811. return true;
  13812. }
  13813. node = node.parentNode;
  13814. }
  13815. return false;
  13816. },
  13817. /**
  13818. * get the center of all the touches
  13819. * @param {Array} touches
  13820. * @returns {Object} center
  13821. */
  13822. getCenter: function getCenter(touches) {
  13823. var valuesX = [], valuesY = [];
  13824. for(var t= 0,len=touches.length; t<len; t++) {
  13825. valuesX.push(touches[t].pageX);
  13826. valuesY.push(touches[t].pageY);
  13827. }
  13828. return {
  13829. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  13830. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  13831. };
  13832. },
  13833. /**
  13834. * calculate the velocity between two points
  13835. * @param {Number} delta_time
  13836. * @param {Number} delta_x
  13837. * @param {Number} delta_y
  13838. * @returns {Object} velocity
  13839. */
  13840. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  13841. return {
  13842. x: Math.abs(delta_x / delta_time) || 0,
  13843. y: Math.abs(delta_y / delta_time) || 0
  13844. };
  13845. },
  13846. /**
  13847. * calculate the angle between two coordinates
  13848. * @param {Touch} touch1
  13849. * @param {Touch} touch2
  13850. * @returns {Number} angle
  13851. */
  13852. getAngle: function getAngle(touch1, touch2) {
  13853. var y = touch2.pageY - touch1.pageY,
  13854. x = touch2.pageX - touch1.pageX;
  13855. return Math.atan2(y, x) * 180 / Math.PI;
  13856. },
  13857. /**
  13858. * angle to direction define
  13859. * @param {Touch} touch1
  13860. * @param {Touch} touch2
  13861. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  13862. */
  13863. getDirection: function getDirection(touch1, touch2) {
  13864. var x = Math.abs(touch1.pageX - touch2.pageX),
  13865. y = Math.abs(touch1.pageY - touch2.pageY);
  13866. if(x >= y) {
  13867. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  13868. }
  13869. else {
  13870. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  13871. }
  13872. },
  13873. /**
  13874. * calculate the distance between two touches
  13875. * @param {Touch} touch1
  13876. * @param {Touch} touch2
  13877. * @returns {Number} distance
  13878. */
  13879. getDistance: function getDistance(touch1, touch2) {
  13880. var x = touch2.pageX - touch1.pageX,
  13881. y = touch2.pageY - touch1.pageY;
  13882. return Math.sqrt((x*x) + (y*y));
  13883. },
  13884. /**
  13885. * calculate the scale factor between two touchLists (fingers)
  13886. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  13887. * @param {Array} start
  13888. * @param {Array} end
  13889. * @returns {Number} scale
  13890. */
  13891. getScale: function getScale(start, end) {
  13892. // need two fingers...
  13893. if(start.length >= 2 && end.length >= 2) {
  13894. return this.getDistance(end[0], end[1]) /
  13895. this.getDistance(start[0], start[1]);
  13896. }
  13897. return 1;
  13898. },
  13899. /**
  13900. * calculate the rotation degrees between two touchLists (fingers)
  13901. * @param {Array} start
  13902. * @param {Array} end
  13903. * @returns {Number} rotation
  13904. */
  13905. getRotation: function getRotation(start, end) {
  13906. // need two fingers
  13907. if(start.length >= 2 && end.length >= 2) {
  13908. return this.getAngle(end[1], end[0]) -
  13909. this.getAngle(start[1], start[0]);
  13910. }
  13911. return 0;
  13912. },
  13913. /**
  13914. * boolean if the direction is vertical
  13915. * @param {String} direction
  13916. * @returns {Boolean} is_vertical
  13917. */
  13918. isVertical: function isVertical(direction) {
  13919. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  13920. },
  13921. /**
  13922. * stop browser default behavior with css props
  13923. * @param {HtmlElement} element
  13924. * @param {Object} css_props
  13925. */
  13926. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  13927. var prop,
  13928. vendors = ['webkit','khtml','moz','ms','o',''];
  13929. if(!css_props || !element.style) {
  13930. return;
  13931. }
  13932. // with css properties for modern browsers
  13933. for(var i = 0; i < vendors.length; i++) {
  13934. for(var p in css_props) {
  13935. if(css_props.hasOwnProperty(p)) {
  13936. prop = p;
  13937. // vender prefix at the property
  13938. if(vendors[i]) {
  13939. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  13940. }
  13941. // set the style
  13942. element.style[prop] = css_props[p];
  13943. }
  13944. }
  13945. }
  13946. // also the disable onselectstart
  13947. if(css_props.userSelect == 'none') {
  13948. element.onselectstart = function() {
  13949. return false;
  13950. };
  13951. }
  13952. }
  13953. };
  13954. Hammer.detection = {
  13955. // contains all registred Hammer.gestures in the correct order
  13956. gestures: [],
  13957. // data of the current Hammer.gesture detection session
  13958. current: null,
  13959. // the previous Hammer.gesture session data
  13960. // is a full clone of the previous gesture.current object
  13961. previous: null,
  13962. // when this becomes true, no gestures are fired
  13963. stopped: false,
  13964. /**
  13965. * start Hammer.gesture detection
  13966. * @param {Hammer.Instance} inst
  13967. * @param {Object} eventData
  13968. */
  13969. startDetect: function startDetect(inst, eventData) {
  13970. // already busy with a Hammer.gesture detection on an element
  13971. if(this.current) {
  13972. return;
  13973. }
  13974. this.stopped = false;
  13975. this.current = {
  13976. inst : inst, // reference to HammerInstance we're working for
  13977. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  13978. lastEvent : false, // last eventData
  13979. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  13980. };
  13981. this.detect(eventData);
  13982. },
  13983. /**
  13984. * Hammer.gesture detection
  13985. * @param {Object} eventData
  13986. * @param {Object} eventData
  13987. */
  13988. detect: function detect(eventData) {
  13989. if(!this.current || this.stopped) {
  13990. return;
  13991. }
  13992. // extend event data with calculations about scale, distance etc
  13993. eventData = this.extendEventData(eventData);
  13994. // instance options
  13995. var inst_options = this.current.inst.options;
  13996. // call Hammer.gesture handlers
  13997. for(var g=0,len=this.gestures.length; g<len; g++) {
  13998. var gesture = this.gestures[g];
  13999. // only when the instance options have enabled this gesture
  14000. if(!this.stopped && inst_options[gesture.name] !== false) {
  14001. // if a handler returns false, we stop with the detection
  14002. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  14003. this.stopDetect();
  14004. break;
  14005. }
  14006. }
  14007. }
  14008. // store as previous event event
  14009. if(this.current) {
  14010. this.current.lastEvent = eventData;
  14011. }
  14012. // endevent, but not the last touch, so dont stop
  14013. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  14014. this.stopDetect();
  14015. }
  14016. return eventData;
  14017. },
  14018. /**
  14019. * clear the Hammer.gesture vars
  14020. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  14021. * to stop other Hammer.gestures from being fired
  14022. */
  14023. stopDetect: function stopDetect() {
  14024. // clone current data to the store as the previous gesture
  14025. // used for the double tap gesture, since this is an other gesture detect session
  14026. this.previous = Hammer.utils.extend({}, this.current);
  14027. // reset the current
  14028. this.current = null;
  14029. // stopped!
  14030. this.stopped = true;
  14031. },
  14032. /**
  14033. * extend eventData for Hammer.gestures
  14034. * @param {Object} ev
  14035. * @returns {Object} ev
  14036. */
  14037. extendEventData: function extendEventData(ev) {
  14038. var startEv = this.current.startEvent;
  14039. // if the touches change, set the new touches over the startEvent touches
  14040. // this because touchevents don't have all the touches on touchstart, or the
  14041. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  14042. // but, sometimes it happens that both fingers are touching at the EXACT same time
  14043. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  14044. // extend 1 level deep to get the touchlist with the touch objects
  14045. startEv.touches = [];
  14046. for(var i=0,len=ev.touches.length; i<len; i++) {
  14047. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  14048. }
  14049. }
  14050. var delta_time = ev.timeStamp - startEv.timeStamp,
  14051. delta_x = ev.center.pageX - startEv.center.pageX,
  14052. delta_y = ev.center.pageY - startEv.center.pageY,
  14053. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  14054. Hammer.utils.extend(ev, {
  14055. deltaTime : delta_time,
  14056. deltaX : delta_x,
  14057. deltaY : delta_y,
  14058. velocityX : velocity.x,
  14059. velocityY : velocity.y,
  14060. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  14061. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  14062. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  14063. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  14064. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  14065. startEvent : startEv
  14066. });
  14067. return ev;
  14068. },
  14069. /**
  14070. * register new gesture
  14071. * @param {Object} gesture object, see gestures.js for documentation
  14072. * @returns {Array} gestures
  14073. */
  14074. register: function register(gesture) {
  14075. // add an enable gesture options if there is no given
  14076. var options = gesture.defaults || {};
  14077. if(options[gesture.name] === undefined) {
  14078. options[gesture.name] = true;
  14079. }
  14080. // extend Hammer default options with the Hammer.gesture options
  14081. Hammer.utils.extend(Hammer.defaults, options, true);
  14082. // set its index
  14083. gesture.index = gesture.index || 1000;
  14084. // add Hammer.gesture to the list
  14085. this.gestures.push(gesture);
  14086. // sort the list by index
  14087. this.gestures.sort(function(a, b) {
  14088. if (a.index < b.index) {
  14089. return -1;
  14090. }
  14091. if (a.index > b.index) {
  14092. return 1;
  14093. }
  14094. return 0;
  14095. });
  14096. return this.gestures;
  14097. }
  14098. };
  14099. Hammer.gestures = Hammer.gestures || {};
  14100. /**
  14101. * Custom gestures
  14102. * ==============================
  14103. *
  14104. * Gesture object
  14105. * --------------------
  14106. * The object structure of a gesture:
  14107. *
  14108. * { name: 'mygesture',
  14109. * index: 1337,
  14110. * defaults: {
  14111. * mygesture_option: true
  14112. * }
  14113. * handler: function(type, ev, inst) {
  14114. * // trigger gesture event
  14115. * inst.trigger(this.name, ev);
  14116. * }
  14117. * }
  14118. * @param {String} name
  14119. * this should be the name of the gesture, lowercase
  14120. * it is also being used to disable/enable the gesture per instance config.
  14121. *
  14122. * @param {Number} [index=1000]
  14123. * the index of the gesture, where it is going to be in the stack of gestures detection
  14124. * like when you build an gesture that depends on the drag gesture, it is a good
  14125. * idea to place it after the index of the drag gesture.
  14126. *
  14127. * @param {Object} [defaults={}]
  14128. * the default settings of the gesture. these are added to the instance settings,
  14129. * and can be overruled per instance. you can also add the name of the gesture,
  14130. * but this is also added by default (and set to true).
  14131. *
  14132. * @param {Function} handler
  14133. * this handles the gesture detection of your custom gesture and receives the
  14134. * following arguments:
  14135. *
  14136. * @param {Object} eventData
  14137. * event data containing the following properties:
  14138. * timeStamp {Number} time the event occurred
  14139. * target {HTMLElement} target element
  14140. * touches {Array} touches (fingers, pointers, mouse) on the screen
  14141. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  14142. * center {Object} center position of the touches. contains pageX and pageY
  14143. * deltaTime {Number} the total time of the touches in the screen
  14144. * deltaX {Number} the delta on x axis we haved moved
  14145. * deltaY {Number} the delta on y axis we haved moved
  14146. * velocityX {Number} the velocity on the x
  14147. * velocityY {Number} the velocity on y
  14148. * angle {Number} the angle we are moving
  14149. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  14150. * distance {Number} the distance we haved moved
  14151. * scale {Number} scaling of the touches, needs 2 touches
  14152. * rotation {Number} rotation of the touches, needs 2 touches *
  14153. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  14154. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  14155. * startEvent {Object} contains the same properties as above,
  14156. * but from the first touch. this is used to calculate
  14157. * distances, deltaTime, scaling etc
  14158. *
  14159. * @param {Hammer.Instance} inst
  14160. * the instance we are doing the detection for. you can get the options from
  14161. * the inst.options object and trigger the gesture event by calling inst.trigger
  14162. *
  14163. *
  14164. * Handle gestures
  14165. * --------------------
  14166. * inside the handler you can get/set Hammer.detection.current. This is the current
  14167. * detection session. It has the following properties
  14168. * @param {String} name
  14169. * contains the name of the gesture we have detected. it has not a real function,
  14170. * only to check in other gestures if something is detected.
  14171. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  14172. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  14173. *
  14174. * @readonly
  14175. * @param {Hammer.Instance} inst
  14176. * the instance we do the detection for
  14177. *
  14178. * @readonly
  14179. * @param {Object} startEvent
  14180. * contains the properties of the first gesture detection in this session.
  14181. * Used for calculations about timing, distance, etc.
  14182. *
  14183. * @readonly
  14184. * @param {Object} lastEvent
  14185. * contains all the properties of the last gesture detect in this session.
  14186. *
  14187. * after the gesture detection session has been completed (user has released the screen)
  14188. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  14189. * this is usefull for gestures like doubletap, where you need to know if the
  14190. * previous gesture was a tap
  14191. *
  14192. * options that have been set by the instance can be received by calling inst.options
  14193. *
  14194. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  14195. * The first param is the name of your gesture, the second the event argument
  14196. *
  14197. *
  14198. * Register gestures
  14199. * --------------------
  14200. * When an gesture is added to the Hammer.gestures object, it is auto registered
  14201. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  14202. * manually and pass your gesture object as a param
  14203. *
  14204. */
  14205. /**
  14206. * Hold
  14207. * Touch stays at the same place for x time
  14208. * @events hold
  14209. */
  14210. Hammer.gestures.Hold = {
  14211. name: 'hold',
  14212. index: 10,
  14213. defaults: {
  14214. hold_timeout : 500,
  14215. hold_threshold : 1
  14216. },
  14217. timer: null,
  14218. handler: function holdGesture(ev, inst) {
  14219. switch(ev.eventType) {
  14220. case Hammer.EVENT_START:
  14221. // clear any running timers
  14222. clearTimeout(this.timer);
  14223. // set the gesture so we can check in the timeout if it still is
  14224. Hammer.detection.current.name = this.name;
  14225. // set timer and if after the timeout it still is hold,
  14226. // we trigger the hold event
  14227. this.timer = setTimeout(function() {
  14228. if(Hammer.detection.current.name == 'hold') {
  14229. inst.trigger('hold', ev);
  14230. }
  14231. }, inst.options.hold_timeout);
  14232. break;
  14233. // when you move or end we clear the timer
  14234. case Hammer.EVENT_MOVE:
  14235. if(ev.distance > inst.options.hold_threshold) {
  14236. clearTimeout(this.timer);
  14237. }
  14238. break;
  14239. case Hammer.EVENT_END:
  14240. clearTimeout(this.timer);
  14241. break;
  14242. }
  14243. }
  14244. };
  14245. /**
  14246. * Tap/DoubleTap
  14247. * Quick touch at a place or double at the same place
  14248. * @events tap, doubletap
  14249. */
  14250. Hammer.gestures.Tap = {
  14251. name: 'tap',
  14252. index: 100,
  14253. defaults: {
  14254. tap_max_touchtime : 250,
  14255. tap_max_distance : 10,
  14256. tap_always : true,
  14257. doubletap_distance : 20,
  14258. doubletap_interval : 300
  14259. },
  14260. handler: function tapGesture(ev, inst) {
  14261. if(ev.eventType == Hammer.EVENT_END) {
  14262. // previous gesture, for the double tap since these are two different gesture detections
  14263. var prev = Hammer.detection.previous,
  14264. did_doubletap = false;
  14265. // when the touchtime is higher then the max touch time
  14266. // or when the moving distance is too much
  14267. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  14268. ev.distance > inst.options.tap_max_distance) {
  14269. return;
  14270. }
  14271. // check if double tap
  14272. if(prev && prev.name == 'tap' &&
  14273. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  14274. ev.distance < inst.options.doubletap_distance) {
  14275. inst.trigger('doubletap', ev);
  14276. did_doubletap = true;
  14277. }
  14278. // do a single tap
  14279. if(!did_doubletap || inst.options.tap_always) {
  14280. Hammer.detection.current.name = 'tap';
  14281. inst.trigger(Hammer.detection.current.name, ev);
  14282. }
  14283. }
  14284. }
  14285. };
  14286. /**
  14287. * Swipe
  14288. * triggers swipe events when the end velocity is above the threshold
  14289. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  14290. */
  14291. Hammer.gestures.Swipe = {
  14292. name: 'swipe',
  14293. index: 40,
  14294. defaults: {
  14295. // set 0 for unlimited, but this can conflict with transform
  14296. swipe_max_touches : 1,
  14297. swipe_velocity : 0.7
  14298. },
  14299. handler: function swipeGesture(ev, inst) {
  14300. if(ev.eventType == Hammer.EVENT_END) {
  14301. // max touches
  14302. if(inst.options.swipe_max_touches > 0 &&
  14303. ev.touches.length > inst.options.swipe_max_touches) {
  14304. return;
  14305. }
  14306. // when the distance we moved is too small we skip this gesture
  14307. // or we can be already in dragging
  14308. if(ev.velocityX > inst.options.swipe_velocity ||
  14309. ev.velocityY > inst.options.swipe_velocity) {
  14310. // trigger swipe events
  14311. inst.trigger(this.name, ev);
  14312. inst.trigger(this.name + ev.direction, ev);
  14313. }
  14314. }
  14315. }
  14316. };
  14317. /**
  14318. * Drag
  14319. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  14320. * moving left and right is a good practice. When all the drag events are blocking
  14321. * you disable scrolling on that area.
  14322. * @events drag, drapleft, dragright, dragup, dragdown
  14323. */
  14324. Hammer.gestures.Drag = {
  14325. name: 'drag',
  14326. index: 50,
  14327. defaults: {
  14328. drag_min_distance : 10,
  14329. // set 0 for unlimited, but this can conflict with transform
  14330. drag_max_touches : 1,
  14331. // prevent default browser behavior when dragging occurs
  14332. // be careful with it, it makes the element a blocking element
  14333. // when you are using the drag gesture, it is a good practice to set this true
  14334. drag_block_horizontal : false,
  14335. drag_block_vertical : false,
  14336. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  14337. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  14338. drag_lock_to_axis : false,
  14339. // drag lock only kicks in when distance > drag_lock_min_distance
  14340. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  14341. drag_lock_min_distance : 25
  14342. },
  14343. triggered: false,
  14344. handler: function dragGesture(ev, inst) {
  14345. // current gesture isnt drag, but dragged is true
  14346. // this means an other gesture is busy. now call dragend
  14347. if(Hammer.detection.current.name != this.name && this.triggered) {
  14348. inst.trigger(this.name +'end', ev);
  14349. this.triggered = false;
  14350. return;
  14351. }
  14352. // max touches
  14353. if(inst.options.drag_max_touches > 0 &&
  14354. ev.touches.length > inst.options.drag_max_touches) {
  14355. return;
  14356. }
  14357. switch(ev.eventType) {
  14358. case Hammer.EVENT_START:
  14359. this.triggered = false;
  14360. break;
  14361. case Hammer.EVENT_MOVE:
  14362. // when the distance we moved is too small we skip this gesture
  14363. // or we can be already in dragging
  14364. if(ev.distance < inst.options.drag_min_distance &&
  14365. Hammer.detection.current.name != this.name) {
  14366. return;
  14367. }
  14368. // we are dragging!
  14369. Hammer.detection.current.name = this.name;
  14370. // lock drag to axis?
  14371. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  14372. ev.drag_locked_to_axis = true;
  14373. }
  14374. var last_direction = Hammer.detection.current.lastEvent.direction;
  14375. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  14376. // keep direction on the axis that the drag gesture started on
  14377. if(Hammer.utils.isVertical(last_direction)) {
  14378. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  14379. }
  14380. else {
  14381. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  14382. }
  14383. }
  14384. // first time, trigger dragstart event
  14385. if(!this.triggered) {
  14386. inst.trigger(this.name +'start', ev);
  14387. this.triggered = true;
  14388. }
  14389. // trigger normal event
  14390. inst.trigger(this.name, ev);
  14391. // direction event, like dragdown
  14392. inst.trigger(this.name + ev.direction, ev);
  14393. // block the browser events
  14394. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  14395. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  14396. ev.preventDefault();
  14397. }
  14398. break;
  14399. case Hammer.EVENT_END:
  14400. // trigger dragend
  14401. if(this.triggered) {
  14402. inst.trigger(this.name +'end', ev);
  14403. }
  14404. this.triggered = false;
  14405. break;
  14406. }
  14407. }
  14408. };
  14409. /**
  14410. * Transform
  14411. * User want to scale or rotate with 2 fingers
  14412. * @events transform, pinch, pinchin, pinchout, rotate
  14413. */
  14414. Hammer.gestures.Transform = {
  14415. name: 'transform',
  14416. index: 45,
  14417. defaults: {
  14418. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  14419. transform_min_scale : 0.01,
  14420. // rotation in degrees
  14421. transform_min_rotation : 1,
  14422. // prevent default browser behavior when two touches are on the screen
  14423. // but it makes the element a blocking element
  14424. // when you are using the transform gesture, it is a good practice to set this true
  14425. transform_always_block : false
  14426. },
  14427. triggered: false,
  14428. handler: function transformGesture(ev, inst) {
  14429. // current gesture isnt drag, but dragged is true
  14430. // this means an other gesture is busy. now call dragend
  14431. if(Hammer.detection.current.name != this.name && this.triggered) {
  14432. inst.trigger(this.name +'end', ev);
  14433. this.triggered = false;
  14434. return;
  14435. }
  14436. // atleast multitouch
  14437. if(ev.touches.length < 2) {
  14438. return;
  14439. }
  14440. // prevent default when two fingers are on the screen
  14441. if(inst.options.transform_always_block) {
  14442. ev.preventDefault();
  14443. }
  14444. switch(ev.eventType) {
  14445. case Hammer.EVENT_START:
  14446. this.triggered = false;
  14447. break;
  14448. case Hammer.EVENT_MOVE:
  14449. var scale_threshold = Math.abs(1-ev.scale);
  14450. var rotation_threshold = Math.abs(ev.rotation);
  14451. // when the distance we moved is too small we skip this gesture
  14452. // or we can be already in dragging
  14453. if(scale_threshold < inst.options.transform_min_scale &&
  14454. rotation_threshold < inst.options.transform_min_rotation) {
  14455. return;
  14456. }
  14457. // we are transforming!
  14458. Hammer.detection.current.name = this.name;
  14459. // first time, trigger dragstart event
  14460. if(!this.triggered) {
  14461. inst.trigger(this.name +'start', ev);
  14462. this.triggered = true;
  14463. }
  14464. inst.trigger(this.name, ev); // basic transform event
  14465. // trigger rotate event
  14466. if(rotation_threshold > inst.options.transform_min_rotation) {
  14467. inst.trigger('rotate', ev);
  14468. }
  14469. // trigger pinch event
  14470. if(scale_threshold > inst.options.transform_min_scale) {
  14471. inst.trigger('pinch', ev);
  14472. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  14473. }
  14474. break;
  14475. case Hammer.EVENT_END:
  14476. // trigger dragend
  14477. if(this.triggered) {
  14478. inst.trigger(this.name +'end', ev);
  14479. }
  14480. this.triggered = false;
  14481. break;
  14482. }
  14483. }
  14484. };
  14485. /**
  14486. * Touch
  14487. * Called as first, tells the user has touched the screen
  14488. * @events touch
  14489. */
  14490. Hammer.gestures.Touch = {
  14491. name: 'touch',
  14492. index: -Infinity,
  14493. defaults: {
  14494. // call preventDefault at touchstart, and makes the element blocking by
  14495. // disabling the scrolling of the page, but it improves gestures like
  14496. // transforming and dragging.
  14497. // be careful with using this, it can be very annoying for users to be stuck
  14498. // on the page
  14499. prevent_default: false,
  14500. // disable mouse events, so only touch (or pen!) input triggers events
  14501. prevent_mouseevents: false
  14502. },
  14503. handler: function touchGesture(ev, inst) {
  14504. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  14505. ev.stopDetect();
  14506. return;
  14507. }
  14508. if(inst.options.prevent_default) {
  14509. ev.preventDefault();
  14510. }
  14511. if(ev.eventType == Hammer.EVENT_START) {
  14512. inst.trigger(this.name, ev);
  14513. }
  14514. }
  14515. };
  14516. /**
  14517. * Release
  14518. * Called as last, tells the user has released the screen
  14519. * @events release
  14520. */
  14521. Hammer.gestures.Release = {
  14522. name: 'release',
  14523. index: Infinity,
  14524. handler: function releaseGesture(ev, inst) {
  14525. if(ev.eventType == Hammer.EVENT_END) {
  14526. inst.trigger(this.name, ev);
  14527. }
  14528. }
  14529. };
  14530. // node export
  14531. if(typeof module === 'object' && typeof module.exports === 'object'){
  14532. module.exports = Hammer;
  14533. }
  14534. // just window export
  14535. else {
  14536. window.Hammer = Hammer;
  14537. // requireJS module definition
  14538. if(typeof window.define === 'function' && window.define.amd) {
  14539. window.define('hammer', [], function() {
  14540. return Hammer;
  14541. });
  14542. }
  14543. }
  14544. })(this);
  14545. },{}],3:[function(require,module,exports){
  14546. //! moment.js
  14547. //! version : 2.5.1
  14548. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  14549. //! license : MIT
  14550. //! momentjs.com
  14551. (function (undefined) {
  14552. /************************************
  14553. Constants
  14554. ************************************/
  14555. var moment,
  14556. VERSION = "2.5.1",
  14557. global = this,
  14558. round = Math.round,
  14559. i,
  14560. YEAR = 0,
  14561. MONTH = 1,
  14562. DATE = 2,
  14563. HOUR = 3,
  14564. MINUTE = 4,
  14565. SECOND = 5,
  14566. MILLISECOND = 6,
  14567. // internal storage for language config files
  14568. languages = {},
  14569. // moment internal properties
  14570. momentProperties = {
  14571. _isAMomentObject: null,
  14572. _i : null,
  14573. _f : null,
  14574. _l : null,
  14575. _strict : null,
  14576. _isUTC : null,
  14577. _offset : null, // optional. Combine with _isUTC
  14578. _pf : null,
  14579. _lang : null // optional
  14580. },
  14581. // check for nodeJS
  14582. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  14583. // ASP.NET json date format regex
  14584. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  14585. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  14586. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  14587. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  14588. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  14589. // format tokens
  14590. 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,
  14591. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  14592. // parsing token regexes
  14593. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  14594. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  14595. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  14596. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  14597. parseTokenDigits = /\d+/, // nonzero number of digits
  14598. 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.
  14599. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  14600. parseTokenT = /T/i, // T (ISO separator)
  14601. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  14602. //strict parsing regexes
  14603. parseTokenOneDigit = /\d/, // 0 - 9
  14604. parseTokenTwoDigits = /\d\d/, // 00 - 99
  14605. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  14606. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  14607. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  14608. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  14609. // iso 8601 regex
  14610. // 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)
  14611. 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)?)?$/,
  14612. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  14613. isoDates = [
  14614. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  14615. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  14616. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  14617. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  14618. ['YYYY-DDD', /\d{4}-\d{3}/]
  14619. ],
  14620. // iso time formats and regexes
  14621. isoTimes = [
  14622. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  14623. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  14624. ['HH:mm', /(T| )\d\d:\d\d/],
  14625. ['HH', /(T| )\d\d/]
  14626. ],
  14627. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  14628. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  14629. // getter and setter names
  14630. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  14631. unitMillisecondFactors = {
  14632. 'Milliseconds' : 1,
  14633. 'Seconds' : 1e3,
  14634. 'Minutes' : 6e4,
  14635. 'Hours' : 36e5,
  14636. 'Days' : 864e5,
  14637. 'Months' : 2592e6,
  14638. 'Years' : 31536e6
  14639. },
  14640. unitAliases = {
  14641. ms : 'millisecond',
  14642. s : 'second',
  14643. m : 'minute',
  14644. h : 'hour',
  14645. d : 'day',
  14646. D : 'date',
  14647. w : 'week',
  14648. W : 'isoWeek',
  14649. M : 'month',
  14650. y : 'year',
  14651. DDD : 'dayOfYear',
  14652. e : 'weekday',
  14653. E : 'isoWeekday',
  14654. gg: 'weekYear',
  14655. GG: 'isoWeekYear'
  14656. },
  14657. camelFunctions = {
  14658. dayofyear : 'dayOfYear',
  14659. isoweekday : 'isoWeekday',
  14660. isoweek : 'isoWeek',
  14661. weekyear : 'weekYear',
  14662. isoweekyear : 'isoWeekYear'
  14663. },
  14664. // format function strings
  14665. formatFunctions = {},
  14666. // tokens to ordinalize and pad
  14667. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  14668. paddedTokens = 'M D H h m s w W'.split(' '),
  14669. formatTokenFunctions = {
  14670. M : function () {
  14671. return this.month() + 1;
  14672. },
  14673. MMM : function (format) {
  14674. return this.lang().monthsShort(this, format);
  14675. },
  14676. MMMM : function (format) {
  14677. return this.lang().months(this, format);
  14678. },
  14679. D : function () {
  14680. return this.date();
  14681. },
  14682. DDD : function () {
  14683. return this.dayOfYear();
  14684. },
  14685. d : function () {
  14686. return this.day();
  14687. },
  14688. dd : function (format) {
  14689. return this.lang().weekdaysMin(this, format);
  14690. },
  14691. ddd : function (format) {
  14692. return this.lang().weekdaysShort(this, format);
  14693. },
  14694. dddd : function (format) {
  14695. return this.lang().weekdays(this, format);
  14696. },
  14697. w : function () {
  14698. return this.week();
  14699. },
  14700. W : function () {
  14701. return this.isoWeek();
  14702. },
  14703. YY : function () {
  14704. return leftZeroFill(this.year() % 100, 2);
  14705. },
  14706. YYYY : function () {
  14707. return leftZeroFill(this.year(), 4);
  14708. },
  14709. YYYYY : function () {
  14710. return leftZeroFill(this.year(), 5);
  14711. },
  14712. YYYYYY : function () {
  14713. var y = this.year(), sign = y >= 0 ? '+' : '-';
  14714. return sign + leftZeroFill(Math.abs(y), 6);
  14715. },
  14716. gg : function () {
  14717. return leftZeroFill(this.weekYear() % 100, 2);
  14718. },
  14719. gggg : function () {
  14720. return leftZeroFill(this.weekYear(), 4);
  14721. },
  14722. ggggg : function () {
  14723. return leftZeroFill(this.weekYear(), 5);
  14724. },
  14725. GG : function () {
  14726. return leftZeroFill(this.isoWeekYear() % 100, 2);
  14727. },
  14728. GGGG : function () {
  14729. return leftZeroFill(this.isoWeekYear(), 4);
  14730. },
  14731. GGGGG : function () {
  14732. return leftZeroFill(this.isoWeekYear(), 5);
  14733. },
  14734. e : function () {
  14735. return this.weekday();
  14736. },
  14737. E : function () {
  14738. return this.isoWeekday();
  14739. },
  14740. a : function () {
  14741. return this.lang().meridiem(this.hours(), this.minutes(), true);
  14742. },
  14743. A : function () {
  14744. return this.lang().meridiem(this.hours(), this.minutes(), false);
  14745. },
  14746. H : function () {
  14747. return this.hours();
  14748. },
  14749. h : function () {
  14750. return this.hours() % 12 || 12;
  14751. },
  14752. m : function () {
  14753. return this.minutes();
  14754. },
  14755. s : function () {
  14756. return this.seconds();
  14757. },
  14758. S : function () {
  14759. return toInt(this.milliseconds() / 100);
  14760. },
  14761. SS : function () {
  14762. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  14763. },
  14764. SSS : function () {
  14765. return leftZeroFill(this.milliseconds(), 3);
  14766. },
  14767. SSSS : function () {
  14768. return leftZeroFill(this.milliseconds(), 3);
  14769. },
  14770. Z : function () {
  14771. var a = -this.zone(),
  14772. b = "+";
  14773. if (a < 0) {
  14774. a = -a;
  14775. b = "-";
  14776. }
  14777. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  14778. },
  14779. ZZ : function () {
  14780. var a = -this.zone(),
  14781. b = "+";
  14782. if (a < 0) {
  14783. a = -a;
  14784. b = "-";
  14785. }
  14786. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  14787. },
  14788. z : function () {
  14789. return this.zoneAbbr();
  14790. },
  14791. zz : function () {
  14792. return this.zoneName();
  14793. },
  14794. X : function () {
  14795. return this.unix();
  14796. },
  14797. Q : function () {
  14798. return this.quarter();
  14799. }
  14800. },
  14801. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  14802. function defaultParsingFlags() {
  14803. // We need to deep clone this object, and es5 standard is not very
  14804. // helpful.
  14805. return {
  14806. empty : false,
  14807. unusedTokens : [],
  14808. unusedInput : [],
  14809. overflow : -2,
  14810. charsLeftOver : 0,
  14811. nullInput : false,
  14812. invalidMonth : null,
  14813. invalidFormat : false,
  14814. userInvalidated : false,
  14815. iso: false
  14816. };
  14817. }
  14818. function padToken(func, count) {
  14819. return function (a) {
  14820. return leftZeroFill(func.call(this, a), count);
  14821. };
  14822. }
  14823. function ordinalizeToken(func, period) {
  14824. return function (a) {
  14825. return this.lang().ordinal(func.call(this, a), period);
  14826. };
  14827. }
  14828. while (ordinalizeTokens.length) {
  14829. i = ordinalizeTokens.pop();
  14830. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  14831. }
  14832. while (paddedTokens.length) {
  14833. i = paddedTokens.pop();
  14834. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  14835. }
  14836. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  14837. /************************************
  14838. Constructors
  14839. ************************************/
  14840. function Language() {
  14841. }
  14842. // Moment prototype object
  14843. function Moment(config) {
  14844. checkOverflow(config);
  14845. extend(this, config);
  14846. }
  14847. // Duration Constructor
  14848. function Duration(duration) {
  14849. var normalizedInput = normalizeObjectUnits(duration),
  14850. years = normalizedInput.year || 0,
  14851. months = normalizedInput.month || 0,
  14852. weeks = normalizedInput.week || 0,
  14853. days = normalizedInput.day || 0,
  14854. hours = normalizedInput.hour || 0,
  14855. minutes = normalizedInput.minute || 0,
  14856. seconds = normalizedInput.second || 0,
  14857. milliseconds = normalizedInput.millisecond || 0;
  14858. // representation for dateAddRemove
  14859. this._milliseconds = +milliseconds +
  14860. seconds * 1e3 + // 1000
  14861. minutes * 6e4 + // 1000 * 60
  14862. hours * 36e5; // 1000 * 60 * 60
  14863. // Because of dateAddRemove treats 24 hours as different from a
  14864. // day when working around DST, we need to store them separately
  14865. this._days = +days +
  14866. weeks * 7;
  14867. // It is impossible translate months into days without knowing
  14868. // which months you are are talking about, so we have to store
  14869. // it separately.
  14870. this._months = +months +
  14871. years * 12;
  14872. this._data = {};
  14873. this._bubble();
  14874. }
  14875. /************************************
  14876. Helpers
  14877. ************************************/
  14878. function extend(a, b) {
  14879. for (var i in b) {
  14880. if (b.hasOwnProperty(i)) {
  14881. a[i] = b[i];
  14882. }
  14883. }
  14884. if (b.hasOwnProperty("toString")) {
  14885. a.toString = b.toString;
  14886. }
  14887. if (b.hasOwnProperty("valueOf")) {
  14888. a.valueOf = b.valueOf;
  14889. }
  14890. return a;
  14891. }
  14892. function cloneMoment(m) {
  14893. var result = {}, i;
  14894. for (i in m) {
  14895. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  14896. result[i] = m[i];
  14897. }
  14898. }
  14899. return result;
  14900. }
  14901. function absRound(number) {
  14902. if (number < 0) {
  14903. return Math.ceil(number);
  14904. } else {
  14905. return Math.floor(number);
  14906. }
  14907. }
  14908. // left zero fill a number
  14909. // see http://jsperf.com/left-zero-filling for performance comparison
  14910. function leftZeroFill(number, targetLength, forceSign) {
  14911. var output = '' + Math.abs(number),
  14912. sign = number >= 0;
  14913. while (output.length < targetLength) {
  14914. output = '0' + output;
  14915. }
  14916. return (sign ? (forceSign ? '+' : '') : '-') + output;
  14917. }
  14918. // helper function for _.addTime and _.subtractTime
  14919. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  14920. var milliseconds = duration._milliseconds,
  14921. days = duration._days,
  14922. months = duration._months,
  14923. minutes,
  14924. hours;
  14925. if (milliseconds) {
  14926. mom._d.setTime(+mom._d + milliseconds * isAdding);
  14927. }
  14928. // store the minutes and hours so we can restore them
  14929. if (days || months) {
  14930. minutes = mom.minute();
  14931. hours = mom.hour();
  14932. }
  14933. if (days) {
  14934. mom.date(mom.date() + days * isAdding);
  14935. }
  14936. if (months) {
  14937. mom.month(mom.month() + months * isAdding);
  14938. }
  14939. if (milliseconds && !ignoreUpdateOffset) {
  14940. moment.updateOffset(mom);
  14941. }
  14942. // restore the minutes and hours after possibly changing dst
  14943. if (days || months) {
  14944. mom.minute(minutes);
  14945. mom.hour(hours);
  14946. }
  14947. }
  14948. // check if is an array
  14949. function isArray(input) {
  14950. return Object.prototype.toString.call(input) === '[object Array]';
  14951. }
  14952. function isDate(input) {
  14953. return Object.prototype.toString.call(input) === '[object Date]' ||
  14954. input instanceof Date;
  14955. }
  14956. // compare two arrays, return the number of differences
  14957. function compareArrays(array1, array2, dontConvert) {
  14958. var len = Math.min(array1.length, array2.length),
  14959. lengthDiff = Math.abs(array1.length - array2.length),
  14960. diffs = 0,
  14961. i;
  14962. for (i = 0; i < len; i++) {
  14963. if ((dontConvert && array1[i] !== array2[i]) ||
  14964. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  14965. diffs++;
  14966. }
  14967. }
  14968. return diffs + lengthDiff;
  14969. }
  14970. function normalizeUnits(units) {
  14971. if (units) {
  14972. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  14973. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  14974. }
  14975. return units;
  14976. }
  14977. function normalizeObjectUnits(inputObject) {
  14978. var normalizedInput = {},
  14979. normalizedProp,
  14980. prop;
  14981. for (prop in inputObject) {
  14982. if (inputObject.hasOwnProperty(prop)) {
  14983. normalizedProp = normalizeUnits(prop);
  14984. if (normalizedProp) {
  14985. normalizedInput[normalizedProp] = inputObject[prop];
  14986. }
  14987. }
  14988. }
  14989. return normalizedInput;
  14990. }
  14991. function makeList(field) {
  14992. var count, setter;
  14993. if (field.indexOf('week') === 0) {
  14994. count = 7;
  14995. setter = 'day';
  14996. }
  14997. else if (field.indexOf('month') === 0) {
  14998. count = 12;
  14999. setter = 'month';
  15000. }
  15001. else {
  15002. return;
  15003. }
  15004. moment[field] = function (format, index) {
  15005. var i, getter,
  15006. method = moment.fn._lang[field],
  15007. results = [];
  15008. if (typeof format === 'number') {
  15009. index = format;
  15010. format = undefined;
  15011. }
  15012. getter = function (i) {
  15013. var m = moment().utc().set(setter, i);
  15014. return method.call(moment.fn._lang, m, format || '');
  15015. };
  15016. if (index != null) {
  15017. return getter(index);
  15018. }
  15019. else {
  15020. for (i = 0; i < count; i++) {
  15021. results.push(getter(i));
  15022. }
  15023. return results;
  15024. }
  15025. };
  15026. }
  15027. function toInt(argumentForCoercion) {
  15028. var coercedNumber = +argumentForCoercion,
  15029. value = 0;
  15030. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  15031. if (coercedNumber >= 0) {
  15032. value = Math.floor(coercedNumber);
  15033. } else {
  15034. value = Math.ceil(coercedNumber);
  15035. }
  15036. }
  15037. return value;
  15038. }
  15039. function daysInMonth(year, month) {
  15040. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  15041. }
  15042. function daysInYear(year) {
  15043. return isLeapYear(year) ? 366 : 365;
  15044. }
  15045. function isLeapYear(year) {
  15046. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  15047. }
  15048. function checkOverflow(m) {
  15049. var overflow;
  15050. if (m._a && m._pf.overflow === -2) {
  15051. overflow =
  15052. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  15053. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  15054. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  15055. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  15056. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  15057. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  15058. -1;
  15059. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  15060. overflow = DATE;
  15061. }
  15062. m._pf.overflow = overflow;
  15063. }
  15064. }
  15065. function isValid(m) {
  15066. if (m._isValid == null) {
  15067. m._isValid = !isNaN(m._d.getTime()) &&
  15068. m._pf.overflow < 0 &&
  15069. !m._pf.empty &&
  15070. !m._pf.invalidMonth &&
  15071. !m._pf.nullInput &&
  15072. !m._pf.invalidFormat &&
  15073. !m._pf.userInvalidated;
  15074. if (m._strict) {
  15075. m._isValid = m._isValid &&
  15076. m._pf.charsLeftOver === 0 &&
  15077. m._pf.unusedTokens.length === 0;
  15078. }
  15079. }
  15080. return m._isValid;
  15081. }
  15082. function normalizeLanguage(key) {
  15083. return key ? key.toLowerCase().replace('_', '-') : key;
  15084. }
  15085. // Return a moment from input, that is local/utc/zone equivalent to model.
  15086. function makeAs(input, model) {
  15087. return model._isUTC ? moment(input).zone(model._offset || 0) :
  15088. moment(input).local();
  15089. }
  15090. /************************************
  15091. Languages
  15092. ************************************/
  15093. extend(Language.prototype, {
  15094. set : function (config) {
  15095. var prop, i;
  15096. for (i in config) {
  15097. prop = config[i];
  15098. if (typeof prop === 'function') {
  15099. this[i] = prop;
  15100. } else {
  15101. this['_' + i] = prop;
  15102. }
  15103. }
  15104. },
  15105. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  15106. months : function (m) {
  15107. return this._months[m.month()];
  15108. },
  15109. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  15110. monthsShort : function (m) {
  15111. return this._monthsShort[m.month()];
  15112. },
  15113. monthsParse : function (monthName) {
  15114. var i, mom, regex;
  15115. if (!this._monthsParse) {
  15116. this._monthsParse = [];
  15117. }
  15118. for (i = 0; i < 12; i++) {
  15119. // make the regex if we don't have it already
  15120. if (!this._monthsParse[i]) {
  15121. mom = moment.utc([2000, i]);
  15122. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  15123. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  15124. }
  15125. // test the regex
  15126. if (this._monthsParse[i].test(monthName)) {
  15127. return i;
  15128. }
  15129. }
  15130. },
  15131. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  15132. weekdays : function (m) {
  15133. return this._weekdays[m.day()];
  15134. },
  15135. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  15136. weekdaysShort : function (m) {
  15137. return this._weekdaysShort[m.day()];
  15138. },
  15139. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  15140. weekdaysMin : function (m) {
  15141. return this._weekdaysMin[m.day()];
  15142. },
  15143. weekdaysParse : function (weekdayName) {
  15144. var i, mom, regex;
  15145. if (!this._weekdaysParse) {
  15146. this._weekdaysParse = [];
  15147. }
  15148. for (i = 0; i < 7; i++) {
  15149. // make the regex if we don't have it already
  15150. if (!this._weekdaysParse[i]) {
  15151. mom = moment([2000, 1]).day(i);
  15152. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  15153. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  15154. }
  15155. // test the regex
  15156. if (this._weekdaysParse[i].test(weekdayName)) {
  15157. return i;
  15158. }
  15159. }
  15160. },
  15161. _longDateFormat : {
  15162. LT : "h:mm A",
  15163. L : "MM/DD/YYYY",
  15164. LL : "MMMM D YYYY",
  15165. LLL : "MMMM D YYYY LT",
  15166. LLLL : "dddd, MMMM D YYYY LT"
  15167. },
  15168. longDateFormat : function (key) {
  15169. var output = this._longDateFormat[key];
  15170. if (!output && this._longDateFormat[key.toUpperCase()]) {
  15171. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  15172. return val.slice(1);
  15173. });
  15174. this._longDateFormat[key] = output;
  15175. }
  15176. return output;
  15177. },
  15178. isPM : function (input) {
  15179. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  15180. // Using charAt should be more compatible.
  15181. return ((input + '').toLowerCase().charAt(0) === 'p');
  15182. },
  15183. _meridiemParse : /[ap]\.?m?\.?/i,
  15184. meridiem : function (hours, minutes, isLower) {
  15185. if (hours > 11) {
  15186. return isLower ? 'pm' : 'PM';
  15187. } else {
  15188. return isLower ? 'am' : 'AM';
  15189. }
  15190. },
  15191. _calendar : {
  15192. sameDay : '[Today at] LT',
  15193. nextDay : '[Tomorrow at] LT',
  15194. nextWeek : 'dddd [at] LT',
  15195. lastDay : '[Yesterday at] LT',
  15196. lastWeek : '[Last] dddd [at] LT',
  15197. sameElse : 'L'
  15198. },
  15199. calendar : function (key, mom) {
  15200. var output = this._calendar[key];
  15201. return typeof output === 'function' ? output.apply(mom) : output;
  15202. },
  15203. _relativeTime : {
  15204. future : "in %s",
  15205. past : "%s ago",
  15206. s : "a few seconds",
  15207. m : "a minute",
  15208. mm : "%d minutes",
  15209. h : "an hour",
  15210. hh : "%d hours",
  15211. d : "a day",
  15212. dd : "%d days",
  15213. M : "a month",
  15214. MM : "%d months",
  15215. y : "a year",
  15216. yy : "%d years"
  15217. },
  15218. relativeTime : function (number, withoutSuffix, string, isFuture) {
  15219. var output = this._relativeTime[string];
  15220. return (typeof output === 'function') ?
  15221. output(number, withoutSuffix, string, isFuture) :
  15222. output.replace(/%d/i, number);
  15223. },
  15224. pastFuture : function (diff, output) {
  15225. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  15226. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  15227. },
  15228. ordinal : function (number) {
  15229. return this._ordinal.replace("%d", number);
  15230. },
  15231. _ordinal : "%d",
  15232. preparse : function (string) {
  15233. return string;
  15234. },
  15235. postformat : function (string) {
  15236. return string;
  15237. },
  15238. week : function (mom) {
  15239. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  15240. },
  15241. _week : {
  15242. dow : 0, // Sunday is the first day of the week.
  15243. doy : 6 // The week that contains Jan 1st is the first week of the year.
  15244. },
  15245. _invalidDate: 'Invalid date',
  15246. invalidDate: function () {
  15247. return this._invalidDate;
  15248. }
  15249. });
  15250. // Loads a language definition into the `languages` cache. The function
  15251. // takes a key and optionally values. If not in the browser and no values
  15252. // are provided, it will load the language file module. As a convenience,
  15253. // this function also returns the language values.
  15254. function loadLang(key, values) {
  15255. values.abbr = key;
  15256. if (!languages[key]) {
  15257. languages[key] = new Language();
  15258. }
  15259. languages[key].set(values);
  15260. return languages[key];
  15261. }
  15262. // Remove a language from the `languages` cache. Mostly useful in tests.
  15263. function unloadLang(key) {
  15264. delete languages[key];
  15265. }
  15266. // Determines which language definition to use and returns it.
  15267. //
  15268. // With no parameters, it will return the global language. If you
  15269. // pass in a language key, such as 'en', it will return the
  15270. // definition for 'en', so long as 'en' has already been loaded using
  15271. // moment.lang.
  15272. function getLangDefinition(key) {
  15273. var i = 0, j, lang, next, split,
  15274. get = function (k) {
  15275. if (!languages[k] && hasModule) {
  15276. try {
  15277. require('./lang/' + k);
  15278. } catch (e) { }
  15279. }
  15280. return languages[k];
  15281. };
  15282. if (!key) {
  15283. return moment.fn._lang;
  15284. }
  15285. if (!isArray(key)) {
  15286. //short-circuit everything else
  15287. lang = get(key);
  15288. if (lang) {
  15289. return lang;
  15290. }
  15291. key = [key];
  15292. }
  15293. //pick the language from the array
  15294. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  15295. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  15296. while (i < key.length) {
  15297. split = normalizeLanguage(key[i]).split('-');
  15298. j = split.length;
  15299. next = normalizeLanguage(key[i + 1]);
  15300. next = next ? next.split('-') : null;
  15301. while (j > 0) {
  15302. lang = get(split.slice(0, j).join('-'));
  15303. if (lang) {
  15304. return lang;
  15305. }
  15306. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  15307. //the next array item is better than a shallower substring of this one
  15308. break;
  15309. }
  15310. j--;
  15311. }
  15312. i++;
  15313. }
  15314. return moment.fn._lang;
  15315. }
  15316. /************************************
  15317. Formatting
  15318. ************************************/
  15319. function removeFormattingTokens(input) {
  15320. if (input.match(/\[[\s\S]/)) {
  15321. return input.replace(/^\[|\]$/g, "");
  15322. }
  15323. return input.replace(/\\/g, "");
  15324. }
  15325. function makeFormatFunction(format) {
  15326. var array = format.match(formattingTokens), i, length;
  15327. for (i = 0, length = array.length; i < length; i++) {
  15328. if (formatTokenFunctions[array[i]]) {
  15329. array[i] = formatTokenFunctions[array[i]];
  15330. } else {
  15331. array[i] = removeFormattingTokens(array[i]);
  15332. }
  15333. }
  15334. return function (mom) {
  15335. var output = "";
  15336. for (i = 0; i < length; i++) {
  15337. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  15338. }
  15339. return output;
  15340. };
  15341. }
  15342. // format date using native date object
  15343. function formatMoment(m, format) {
  15344. if (!m.isValid()) {
  15345. return m.lang().invalidDate();
  15346. }
  15347. format = expandFormat(format, m.lang());
  15348. if (!formatFunctions[format]) {
  15349. formatFunctions[format] = makeFormatFunction(format);
  15350. }
  15351. return formatFunctions[format](m);
  15352. }
  15353. function expandFormat(format, lang) {
  15354. var i = 5;
  15355. function replaceLongDateFormatTokens(input) {
  15356. return lang.longDateFormat(input) || input;
  15357. }
  15358. localFormattingTokens.lastIndex = 0;
  15359. while (i >= 0 && localFormattingTokens.test(format)) {
  15360. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  15361. localFormattingTokens.lastIndex = 0;
  15362. i -= 1;
  15363. }
  15364. return format;
  15365. }
  15366. /************************************
  15367. Parsing
  15368. ************************************/
  15369. // get the regex to find the next token
  15370. function getParseRegexForToken(token, config) {
  15371. var a, strict = config._strict;
  15372. switch (token) {
  15373. case 'DDDD':
  15374. return parseTokenThreeDigits;
  15375. case 'YYYY':
  15376. case 'GGGG':
  15377. case 'gggg':
  15378. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  15379. case 'Y':
  15380. case 'G':
  15381. case 'g':
  15382. return parseTokenSignedNumber;
  15383. case 'YYYYYY':
  15384. case 'YYYYY':
  15385. case 'GGGGG':
  15386. case 'ggggg':
  15387. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  15388. case 'S':
  15389. if (strict) { return parseTokenOneDigit; }
  15390. /* falls through */
  15391. case 'SS':
  15392. if (strict) { return parseTokenTwoDigits; }
  15393. /* falls through */
  15394. case 'SSS':
  15395. if (strict) { return parseTokenThreeDigits; }
  15396. /* falls through */
  15397. case 'DDD':
  15398. return parseTokenOneToThreeDigits;
  15399. case 'MMM':
  15400. case 'MMMM':
  15401. case 'dd':
  15402. case 'ddd':
  15403. case 'dddd':
  15404. return parseTokenWord;
  15405. case 'a':
  15406. case 'A':
  15407. return getLangDefinition(config._l)._meridiemParse;
  15408. case 'X':
  15409. return parseTokenTimestampMs;
  15410. case 'Z':
  15411. case 'ZZ':
  15412. return parseTokenTimezone;
  15413. case 'T':
  15414. return parseTokenT;
  15415. case 'SSSS':
  15416. return parseTokenDigits;
  15417. case 'MM':
  15418. case 'DD':
  15419. case 'YY':
  15420. case 'GG':
  15421. case 'gg':
  15422. case 'HH':
  15423. case 'hh':
  15424. case 'mm':
  15425. case 'ss':
  15426. case 'ww':
  15427. case 'WW':
  15428. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  15429. case 'M':
  15430. case 'D':
  15431. case 'd':
  15432. case 'H':
  15433. case 'h':
  15434. case 'm':
  15435. case 's':
  15436. case 'w':
  15437. case 'W':
  15438. case 'e':
  15439. case 'E':
  15440. return parseTokenOneOrTwoDigits;
  15441. default :
  15442. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  15443. return a;
  15444. }
  15445. }
  15446. function timezoneMinutesFromString(string) {
  15447. string = string || "";
  15448. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  15449. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  15450. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  15451. minutes = +(parts[1] * 60) + toInt(parts[2]);
  15452. return parts[0] === '+' ? -minutes : minutes;
  15453. }
  15454. // function to convert string input to date
  15455. function addTimeToArrayFromToken(token, input, config) {
  15456. var a, datePartArray = config._a;
  15457. switch (token) {
  15458. // MONTH
  15459. case 'M' : // fall through to MM
  15460. case 'MM' :
  15461. if (input != null) {
  15462. datePartArray[MONTH] = toInt(input) - 1;
  15463. }
  15464. break;
  15465. case 'MMM' : // fall through to MMMM
  15466. case 'MMMM' :
  15467. a = getLangDefinition(config._l).monthsParse(input);
  15468. // if we didn't find a month name, mark the date as invalid.
  15469. if (a != null) {
  15470. datePartArray[MONTH] = a;
  15471. } else {
  15472. config._pf.invalidMonth = input;
  15473. }
  15474. break;
  15475. // DAY OF MONTH
  15476. case 'D' : // fall through to DD
  15477. case 'DD' :
  15478. if (input != null) {
  15479. datePartArray[DATE] = toInt(input);
  15480. }
  15481. break;
  15482. // DAY OF YEAR
  15483. case 'DDD' : // fall through to DDDD
  15484. case 'DDDD' :
  15485. if (input != null) {
  15486. config._dayOfYear = toInt(input);
  15487. }
  15488. break;
  15489. // YEAR
  15490. case 'YY' :
  15491. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  15492. break;
  15493. case 'YYYY' :
  15494. case 'YYYYY' :
  15495. case 'YYYYYY' :
  15496. datePartArray[YEAR] = toInt(input);
  15497. break;
  15498. // AM / PM
  15499. case 'a' : // fall through to A
  15500. case 'A' :
  15501. config._isPm = getLangDefinition(config._l).isPM(input);
  15502. break;
  15503. // 24 HOUR
  15504. case 'H' : // fall through to hh
  15505. case 'HH' : // fall through to hh
  15506. case 'h' : // fall through to hh
  15507. case 'hh' :
  15508. datePartArray[HOUR] = toInt(input);
  15509. break;
  15510. // MINUTE
  15511. case 'm' : // fall through to mm
  15512. case 'mm' :
  15513. datePartArray[MINUTE] = toInt(input);
  15514. break;
  15515. // SECOND
  15516. case 's' : // fall through to ss
  15517. case 'ss' :
  15518. datePartArray[SECOND] = toInt(input);
  15519. break;
  15520. // MILLISECOND
  15521. case 'S' :
  15522. case 'SS' :
  15523. case 'SSS' :
  15524. case 'SSSS' :
  15525. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  15526. break;
  15527. // UNIX TIMESTAMP WITH MS
  15528. case 'X':
  15529. config._d = new Date(parseFloat(input) * 1000);
  15530. break;
  15531. // TIMEZONE
  15532. case 'Z' : // fall through to ZZ
  15533. case 'ZZ' :
  15534. config._useUTC = true;
  15535. config._tzm = timezoneMinutesFromString(input);
  15536. break;
  15537. case 'w':
  15538. case 'ww':
  15539. case 'W':
  15540. case 'WW':
  15541. case 'd':
  15542. case 'dd':
  15543. case 'ddd':
  15544. case 'dddd':
  15545. case 'e':
  15546. case 'E':
  15547. token = token.substr(0, 1);
  15548. /* falls through */
  15549. case 'gg':
  15550. case 'gggg':
  15551. case 'GG':
  15552. case 'GGGG':
  15553. case 'GGGGG':
  15554. token = token.substr(0, 2);
  15555. if (input) {
  15556. config._w = config._w || {};
  15557. config._w[token] = input;
  15558. }
  15559. break;
  15560. }
  15561. }
  15562. // convert an array to a date.
  15563. // the array should mirror the parameters below
  15564. // note: all values past the year are optional and will default to the lowest possible value.
  15565. // [year, month, day , hour, minute, second, millisecond]
  15566. function dateFromConfig(config) {
  15567. var i, date, input = [], currentDate,
  15568. yearToUse, fixYear, w, temp, lang, weekday, week;
  15569. if (config._d) {
  15570. return;
  15571. }
  15572. currentDate = currentDateArray(config);
  15573. //compute day of the year from weeks and weekdays
  15574. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  15575. fixYear = function (val) {
  15576. var int_val = parseInt(val, 10);
  15577. return val ?
  15578. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  15579. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  15580. };
  15581. w = config._w;
  15582. if (w.GG != null || w.W != null || w.E != null) {
  15583. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  15584. }
  15585. else {
  15586. lang = getLangDefinition(config._l);
  15587. weekday = w.d != null ? parseWeekday(w.d, lang) :
  15588. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  15589. week = parseInt(w.w, 10) || 1;
  15590. //if we're parsing 'd', then the low day numbers may be next week
  15591. if (w.d != null && weekday < lang._week.dow) {
  15592. week++;
  15593. }
  15594. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  15595. }
  15596. config._a[YEAR] = temp.year;
  15597. config._dayOfYear = temp.dayOfYear;
  15598. }
  15599. //if the day of the year is set, figure out what it is
  15600. if (config._dayOfYear) {
  15601. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  15602. if (config._dayOfYear > daysInYear(yearToUse)) {
  15603. config._pf._overflowDayOfYear = true;
  15604. }
  15605. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  15606. config._a[MONTH] = date.getUTCMonth();
  15607. config._a[DATE] = date.getUTCDate();
  15608. }
  15609. // Default to current date.
  15610. // * if no year, month, day of month are given, default to today
  15611. // * if day of month is given, default month and year
  15612. // * if month is given, default only year
  15613. // * if year is given, don't default anything
  15614. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  15615. config._a[i] = input[i] = currentDate[i];
  15616. }
  15617. // Zero out whatever was not defaulted, including time
  15618. for (; i < 7; i++) {
  15619. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  15620. }
  15621. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  15622. input[HOUR] += toInt((config._tzm || 0) / 60);
  15623. input[MINUTE] += toInt((config._tzm || 0) % 60);
  15624. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  15625. }
  15626. function dateFromObject(config) {
  15627. var normalizedInput;
  15628. if (config._d) {
  15629. return;
  15630. }
  15631. normalizedInput = normalizeObjectUnits(config._i);
  15632. config._a = [
  15633. normalizedInput.year,
  15634. normalizedInput.month,
  15635. normalizedInput.day,
  15636. normalizedInput.hour,
  15637. normalizedInput.minute,
  15638. normalizedInput.second,
  15639. normalizedInput.millisecond
  15640. ];
  15641. dateFromConfig(config);
  15642. }
  15643. function currentDateArray(config) {
  15644. var now = new Date();
  15645. if (config._useUTC) {
  15646. return [
  15647. now.getUTCFullYear(),
  15648. now.getUTCMonth(),
  15649. now.getUTCDate()
  15650. ];
  15651. } else {
  15652. return [now.getFullYear(), now.getMonth(), now.getDate()];
  15653. }
  15654. }
  15655. // date from string and format string
  15656. function makeDateFromStringAndFormat(config) {
  15657. config._a = [];
  15658. config._pf.empty = true;
  15659. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  15660. var lang = getLangDefinition(config._l),
  15661. string = '' + config._i,
  15662. i, parsedInput, tokens, token, skipped,
  15663. stringLength = string.length,
  15664. totalParsedInputLength = 0;
  15665. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  15666. for (i = 0; i < tokens.length; i++) {
  15667. token = tokens[i];
  15668. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  15669. if (parsedInput) {
  15670. skipped = string.substr(0, string.indexOf(parsedInput));
  15671. if (skipped.length > 0) {
  15672. config._pf.unusedInput.push(skipped);
  15673. }
  15674. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  15675. totalParsedInputLength += parsedInput.length;
  15676. }
  15677. // don't parse if it's not a known token
  15678. if (formatTokenFunctions[token]) {
  15679. if (parsedInput) {
  15680. config._pf.empty = false;
  15681. }
  15682. else {
  15683. config._pf.unusedTokens.push(token);
  15684. }
  15685. addTimeToArrayFromToken(token, parsedInput, config);
  15686. }
  15687. else if (config._strict && !parsedInput) {
  15688. config._pf.unusedTokens.push(token);
  15689. }
  15690. }
  15691. // add remaining unparsed input length to the string
  15692. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  15693. if (string.length > 0) {
  15694. config._pf.unusedInput.push(string);
  15695. }
  15696. // handle am pm
  15697. if (config._isPm && config._a[HOUR] < 12) {
  15698. config._a[HOUR] += 12;
  15699. }
  15700. // if is 12 am, change hours to 0
  15701. if (config._isPm === false && config._a[HOUR] === 12) {
  15702. config._a[HOUR] = 0;
  15703. }
  15704. dateFromConfig(config);
  15705. checkOverflow(config);
  15706. }
  15707. function unescapeFormat(s) {
  15708. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  15709. return p1 || p2 || p3 || p4;
  15710. });
  15711. }
  15712. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  15713. function regexpEscape(s) {
  15714. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  15715. }
  15716. // date from string and array of format strings
  15717. function makeDateFromStringAndArray(config) {
  15718. var tempConfig,
  15719. bestMoment,
  15720. scoreToBeat,
  15721. i,
  15722. currentScore;
  15723. if (config._f.length === 0) {
  15724. config._pf.invalidFormat = true;
  15725. config._d = new Date(NaN);
  15726. return;
  15727. }
  15728. for (i = 0; i < config._f.length; i++) {
  15729. currentScore = 0;
  15730. tempConfig = extend({}, config);
  15731. tempConfig._pf = defaultParsingFlags();
  15732. tempConfig._f = config._f[i];
  15733. makeDateFromStringAndFormat(tempConfig);
  15734. if (!isValid(tempConfig)) {
  15735. continue;
  15736. }
  15737. // if there is any input that was not parsed add a penalty for that format
  15738. currentScore += tempConfig._pf.charsLeftOver;
  15739. //or tokens
  15740. currentScore += tempConfig._pf.unusedTokens.length * 10;
  15741. tempConfig._pf.score = currentScore;
  15742. if (scoreToBeat == null || currentScore < scoreToBeat) {
  15743. scoreToBeat = currentScore;
  15744. bestMoment = tempConfig;
  15745. }
  15746. }
  15747. extend(config, bestMoment || tempConfig);
  15748. }
  15749. // date from iso format
  15750. function makeDateFromString(config) {
  15751. var i, l,
  15752. string = config._i,
  15753. match = isoRegex.exec(string);
  15754. if (match) {
  15755. config._pf.iso = true;
  15756. for (i = 0, l = isoDates.length; i < l; i++) {
  15757. if (isoDates[i][1].exec(string)) {
  15758. // match[5] should be "T" or undefined
  15759. config._f = isoDates[i][0] + (match[6] || " ");
  15760. break;
  15761. }
  15762. }
  15763. for (i = 0, l = isoTimes.length; i < l; i++) {
  15764. if (isoTimes[i][1].exec(string)) {
  15765. config._f += isoTimes[i][0];
  15766. break;
  15767. }
  15768. }
  15769. if (string.match(parseTokenTimezone)) {
  15770. config._f += "Z";
  15771. }
  15772. makeDateFromStringAndFormat(config);
  15773. }
  15774. else {
  15775. config._d = new Date(string);
  15776. }
  15777. }
  15778. function makeDateFromInput(config) {
  15779. var input = config._i,
  15780. matched = aspNetJsonRegex.exec(input);
  15781. if (input === undefined) {
  15782. config._d = new Date();
  15783. } else if (matched) {
  15784. config._d = new Date(+matched[1]);
  15785. } else if (typeof input === 'string') {
  15786. makeDateFromString(config);
  15787. } else if (isArray(input)) {
  15788. config._a = input.slice(0);
  15789. dateFromConfig(config);
  15790. } else if (isDate(input)) {
  15791. config._d = new Date(+input);
  15792. } else if (typeof(input) === 'object') {
  15793. dateFromObject(config);
  15794. } else {
  15795. config._d = new Date(input);
  15796. }
  15797. }
  15798. function makeDate(y, m, d, h, M, s, ms) {
  15799. //can't just apply() to create a date:
  15800. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  15801. var date = new Date(y, m, d, h, M, s, ms);
  15802. //the date constructor doesn't accept years < 1970
  15803. if (y < 1970) {
  15804. date.setFullYear(y);
  15805. }
  15806. return date;
  15807. }
  15808. function makeUTCDate(y) {
  15809. var date = new Date(Date.UTC.apply(null, arguments));
  15810. if (y < 1970) {
  15811. date.setUTCFullYear(y);
  15812. }
  15813. return date;
  15814. }
  15815. function parseWeekday(input, language) {
  15816. if (typeof input === 'string') {
  15817. if (!isNaN(input)) {
  15818. input = parseInt(input, 10);
  15819. }
  15820. else {
  15821. input = language.weekdaysParse(input);
  15822. if (typeof input !== 'number') {
  15823. return null;
  15824. }
  15825. }
  15826. }
  15827. return input;
  15828. }
  15829. /************************************
  15830. Relative Time
  15831. ************************************/
  15832. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  15833. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  15834. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  15835. }
  15836. function relativeTime(milliseconds, withoutSuffix, lang) {
  15837. var seconds = round(Math.abs(milliseconds) / 1000),
  15838. minutes = round(seconds / 60),
  15839. hours = round(minutes / 60),
  15840. days = round(hours / 24),
  15841. years = round(days / 365),
  15842. args = seconds < 45 && ['s', seconds] ||
  15843. minutes === 1 && ['m'] ||
  15844. minutes < 45 && ['mm', minutes] ||
  15845. hours === 1 && ['h'] ||
  15846. hours < 22 && ['hh', hours] ||
  15847. days === 1 && ['d'] ||
  15848. days <= 25 && ['dd', days] ||
  15849. days <= 45 && ['M'] ||
  15850. days < 345 && ['MM', round(days / 30)] ||
  15851. years === 1 && ['y'] || ['yy', years];
  15852. args[2] = withoutSuffix;
  15853. args[3] = milliseconds > 0;
  15854. args[4] = lang;
  15855. return substituteTimeAgo.apply({}, args);
  15856. }
  15857. /************************************
  15858. Week of Year
  15859. ************************************/
  15860. // firstDayOfWeek 0 = sun, 6 = sat
  15861. // the day of the week that starts the week
  15862. // (usually sunday or monday)
  15863. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  15864. // the first week is the week that contains the first
  15865. // of this day of the week
  15866. // (eg. ISO weeks use thursday (4))
  15867. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  15868. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  15869. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  15870. adjustedMoment;
  15871. if (daysToDayOfWeek > end) {
  15872. daysToDayOfWeek -= 7;
  15873. }
  15874. if (daysToDayOfWeek < end - 7) {
  15875. daysToDayOfWeek += 7;
  15876. }
  15877. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  15878. return {
  15879. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  15880. year: adjustedMoment.year()
  15881. };
  15882. }
  15883. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  15884. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  15885. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  15886. weekday = weekday != null ? weekday : firstDayOfWeek;
  15887. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  15888. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  15889. return {
  15890. year: dayOfYear > 0 ? year : year - 1,
  15891. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  15892. };
  15893. }
  15894. /************************************
  15895. Top Level Functions
  15896. ************************************/
  15897. function makeMoment(config) {
  15898. var input = config._i,
  15899. format = config._f;
  15900. if (input === null) {
  15901. return moment.invalid({nullInput: true});
  15902. }
  15903. if (typeof input === 'string') {
  15904. config._i = input = getLangDefinition().preparse(input);
  15905. }
  15906. if (moment.isMoment(input)) {
  15907. config = cloneMoment(input);
  15908. config._d = new Date(+input._d);
  15909. } else if (format) {
  15910. if (isArray(format)) {
  15911. makeDateFromStringAndArray(config);
  15912. } else {
  15913. makeDateFromStringAndFormat(config);
  15914. }
  15915. } else {
  15916. makeDateFromInput(config);
  15917. }
  15918. return new Moment(config);
  15919. }
  15920. moment = function (input, format, lang, strict) {
  15921. var c;
  15922. if (typeof(lang) === "boolean") {
  15923. strict = lang;
  15924. lang = undefined;
  15925. }
  15926. // object construction must be done this way.
  15927. // https://github.com/moment/moment/issues/1423
  15928. c = {};
  15929. c._isAMomentObject = true;
  15930. c._i = input;
  15931. c._f = format;
  15932. c._l = lang;
  15933. c._strict = strict;
  15934. c._isUTC = false;
  15935. c._pf = defaultParsingFlags();
  15936. return makeMoment(c);
  15937. };
  15938. // creating with utc
  15939. moment.utc = function (input, format, lang, strict) {
  15940. var c;
  15941. if (typeof(lang) === "boolean") {
  15942. strict = lang;
  15943. lang = undefined;
  15944. }
  15945. // object construction must be done this way.
  15946. // https://github.com/moment/moment/issues/1423
  15947. c = {};
  15948. c._isAMomentObject = true;
  15949. c._useUTC = true;
  15950. c._isUTC = true;
  15951. c._l = lang;
  15952. c._i = input;
  15953. c._f = format;
  15954. c._strict = strict;
  15955. c._pf = defaultParsingFlags();
  15956. return makeMoment(c).utc();
  15957. };
  15958. // creating with unix timestamp (in seconds)
  15959. moment.unix = function (input) {
  15960. return moment(input * 1000);
  15961. };
  15962. // duration
  15963. moment.duration = function (input, key) {
  15964. var duration = input,
  15965. // matching against regexp is expensive, do it on demand
  15966. match = null,
  15967. sign,
  15968. ret,
  15969. parseIso;
  15970. if (moment.isDuration(input)) {
  15971. duration = {
  15972. ms: input._milliseconds,
  15973. d: input._days,
  15974. M: input._months
  15975. };
  15976. } else if (typeof input === 'number') {
  15977. duration = {};
  15978. if (key) {
  15979. duration[key] = input;
  15980. } else {
  15981. duration.milliseconds = input;
  15982. }
  15983. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  15984. sign = (match[1] === "-") ? -1 : 1;
  15985. duration = {
  15986. y: 0,
  15987. d: toInt(match[DATE]) * sign,
  15988. h: toInt(match[HOUR]) * sign,
  15989. m: toInt(match[MINUTE]) * sign,
  15990. s: toInt(match[SECOND]) * sign,
  15991. ms: toInt(match[MILLISECOND]) * sign
  15992. };
  15993. } else if (!!(match = isoDurationRegex.exec(input))) {
  15994. sign = (match[1] === "-") ? -1 : 1;
  15995. parseIso = function (inp) {
  15996. // We'd normally use ~~inp for this, but unfortunately it also
  15997. // converts floats to ints.
  15998. // inp may be undefined, so careful calling replace on it.
  15999. var res = inp && parseFloat(inp.replace(',', '.'));
  16000. // apply sign while we're at it
  16001. return (isNaN(res) ? 0 : res) * sign;
  16002. };
  16003. duration = {
  16004. y: parseIso(match[2]),
  16005. M: parseIso(match[3]),
  16006. d: parseIso(match[4]),
  16007. h: parseIso(match[5]),
  16008. m: parseIso(match[6]),
  16009. s: parseIso(match[7]),
  16010. w: parseIso(match[8])
  16011. };
  16012. }
  16013. ret = new Duration(duration);
  16014. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  16015. ret._lang = input._lang;
  16016. }
  16017. return ret;
  16018. };
  16019. // version number
  16020. moment.version = VERSION;
  16021. // default format
  16022. moment.defaultFormat = isoFormat;
  16023. // This function will be called whenever a moment is mutated.
  16024. // It is intended to keep the offset in sync with the timezone.
  16025. moment.updateOffset = function () {};
  16026. // This function will load languages and then set the global language. If
  16027. // no arguments are passed in, it will simply return the current global
  16028. // language key.
  16029. moment.lang = function (key, values) {
  16030. var r;
  16031. if (!key) {
  16032. return moment.fn._lang._abbr;
  16033. }
  16034. if (values) {
  16035. loadLang(normalizeLanguage(key), values);
  16036. } else if (values === null) {
  16037. unloadLang(key);
  16038. key = 'en';
  16039. } else if (!languages[key]) {
  16040. getLangDefinition(key);
  16041. }
  16042. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  16043. return r._abbr;
  16044. };
  16045. // returns language data
  16046. moment.langData = function (key) {
  16047. if (key && key._lang && key._lang._abbr) {
  16048. key = key._lang._abbr;
  16049. }
  16050. return getLangDefinition(key);
  16051. };
  16052. // compare moment object
  16053. moment.isMoment = function (obj) {
  16054. return obj instanceof Moment ||
  16055. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  16056. };
  16057. // for typechecking Duration objects
  16058. moment.isDuration = function (obj) {
  16059. return obj instanceof Duration;
  16060. };
  16061. for (i = lists.length - 1; i >= 0; --i) {
  16062. makeList(lists[i]);
  16063. }
  16064. moment.normalizeUnits = function (units) {
  16065. return normalizeUnits(units);
  16066. };
  16067. moment.invalid = function (flags) {
  16068. var m = moment.utc(NaN);
  16069. if (flags != null) {
  16070. extend(m._pf, flags);
  16071. }
  16072. else {
  16073. m._pf.userInvalidated = true;
  16074. }
  16075. return m;
  16076. };
  16077. moment.parseZone = function (input) {
  16078. return moment(input).parseZone();
  16079. };
  16080. /************************************
  16081. Moment Prototype
  16082. ************************************/
  16083. extend(moment.fn = Moment.prototype, {
  16084. clone : function () {
  16085. return moment(this);
  16086. },
  16087. valueOf : function () {
  16088. return +this._d + ((this._offset || 0) * 60000);
  16089. },
  16090. unix : function () {
  16091. return Math.floor(+this / 1000);
  16092. },
  16093. toString : function () {
  16094. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  16095. },
  16096. toDate : function () {
  16097. return this._offset ? new Date(+this) : this._d;
  16098. },
  16099. toISOString : function () {
  16100. var m = moment(this).utc();
  16101. if (0 < m.year() && m.year() <= 9999) {
  16102. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  16103. } else {
  16104. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  16105. }
  16106. },
  16107. toArray : function () {
  16108. var m = this;
  16109. return [
  16110. m.year(),
  16111. m.month(),
  16112. m.date(),
  16113. m.hours(),
  16114. m.minutes(),
  16115. m.seconds(),
  16116. m.milliseconds()
  16117. ];
  16118. },
  16119. isValid : function () {
  16120. return isValid(this);
  16121. },
  16122. isDSTShifted : function () {
  16123. if (this._a) {
  16124. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  16125. }
  16126. return false;
  16127. },
  16128. parsingFlags : function () {
  16129. return extend({}, this._pf);
  16130. },
  16131. invalidAt: function () {
  16132. return this._pf.overflow;
  16133. },
  16134. utc : function () {
  16135. return this.zone(0);
  16136. },
  16137. local : function () {
  16138. this.zone(0);
  16139. this._isUTC = false;
  16140. return this;
  16141. },
  16142. format : function (inputString) {
  16143. var output = formatMoment(this, inputString || moment.defaultFormat);
  16144. return this.lang().postformat(output);
  16145. },
  16146. add : function (input, val) {
  16147. var dur;
  16148. // switch args to support add('s', 1) and add(1, 's')
  16149. if (typeof input === 'string') {
  16150. dur = moment.duration(+val, input);
  16151. } else {
  16152. dur = moment.duration(input, val);
  16153. }
  16154. addOrSubtractDurationFromMoment(this, dur, 1);
  16155. return this;
  16156. },
  16157. subtract : function (input, val) {
  16158. var dur;
  16159. // switch args to support subtract('s', 1) and subtract(1, 's')
  16160. if (typeof input === 'string') {
  16161. dur = moment.duration(+val, input);
  16162. } else {
  16163. dur = moment.duration(input, val);
  16164. }
  16165. addOrSubtractDurationFromMoment(this, dur, -1);
  16166. return this;
  16167. },
  16168. diff : function (input, units, asFloat) {
  16169. var that = makeAs(input, this),
  16170. zoneDiff = (this.zone() - that.zone()) * 6e4,
  16171. diff, output;
  16172. units = normalizeUnits(units);
  16173. if (units === 'year' || units === 'month') {
  16174. // average number of days in the months in the given dates
  16175. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  16176. // difference in months
  16177. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  16178. // adjust by taking difference in days, average number of days
  16179. // and dst in the given months.
  16180. output += ((this - moment(this).startOf('month')) -
  16181. (that - moment(that).startOf('month'))) / diff;
  16182. // same as above but with zones, to negate all dst
  16183. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  16184. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  16185. if (units === 'year') {
  16186. output = output / 12;
  16187. }
  16188. } else {
  16189. diff = (this - that);
  16190. output = units === 'second' ? diff / 1e3 : // 1000
  16191. units === 'minute' ? diff / 6e4 : // 1000 * 60
  16192. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  16193. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  16194. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  16195. diff;
  16196. }
  16197. return asFloat ? output : absRound(output);
  16198. },
  16199. from : function (time, withoutSuffix) {
  16200. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  16201. },
  16202. fromNow : function (withoutSuffix) {
  16203. return this.from(moment(), withoutSuffix);
  16204. },
  16205. calendar : function () {
  16206. // We want to compare the start of today, vs this.
  16207. // Getting start-of-today depends on whether we're zone'd or not.
  16208. var sod = makeAs(moment(), this).startOf('day'),
  16209. diff = this.diff(sod, 'days', true),
  16210. format = diff < -6 ? 'sameElse' :
  16211. diff < -1 ? 'lastWeek' :
  16212. diff < 0 ? 'lastDay' :
  16213. diff < 1 ? 'sameDay' :
  16214. diff < 2 ? 'nextDay' :
  16215. diff < 7 ? 'nextWeek' : 'sameElse';
  16216. return this.format(this.lang().calendar(format, this));
  16217. },
  16218. isLeapYear : function () {
  16219. return isLeapYear(this.year());
  16220. },
  16221. isDST : function () {
  16222. return (this.zone() < this.clone().month(0).zone() ||
  16223. this.zone() < this.clone().month(5).zone());
  16224. },
  16225. day : function (input) {
  16226. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  16227. if (input != null) {
  16228. input = parseWeekday(input, this.lang());
  16229. return this.add({ d : input - day });
  16230. } else {
  16231. return day;
  16232. }
  16233. },
  16234. month : function (input) {
  16235. var utc = this._isUTC ? 'UTC' : '',
  16236. dayOfMonth;
  16237. if (input != null) {
  16238. if (typeof input === 'string') {
  16239. input = this.lang().monthsParse(input);
  16240. if (typeof input !== 'number') {
  16241. return this;
  16242. }
  16243. }
  16244. dayOfMonth = this.date();
  16245. this.date(1);
  16246. this._d['set' + utc + 'Month'](input);
  16247. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  16248. moment.updateOffset(this);
  16249. return this;
  16250. } else {
  16251. return this._d['get' + utc + 'Month']();
  16252. }
  16253. },
  16254. startOf: function (units) {
  16255. units = normalizeUnits(units);
  16256. // the following switch intentionally omits break keywords
  16257. // to utilize falling through the cases.
  16258. switch (units) {
  16259. case 'year':
  16260. this.month(0);
  16261. /* falls through */
  16262. case 'month':
  16263. this.date(1);
  16264. /* falls through */
  16265. case 'week':
  16266. case 'isoWeek':
  16267. case 'day':
  16268. this.hours(0);
  16269. /* falls through */
  16270. case 'hour':
  16271. this.minutes(0);
  16272. /* falls through */
  16273. case 'minute':
  16274. this.seconds(0);
  16275. /* falls through */
  16276. case 'second':
  16277. this.milliseconds(0);
  16278. /* falls through */
  16279. }
  16280. // weeks are a special case
  16281. if (units === 'week') {
  16282. this.weekday(0);
  16283. } else if (units === 'isoWeek') {
  16284. this.isoWeekday(1);
  16285. }
  16286. return this;
  16287. },
  16288. endOf: function (units) {
  16289. units = normalizeUnits(units);
  16290. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  16291. },
  16292. isAfter: function (input, units) {
  16293. units = typeof units !== 'undefined' ? units : 'millisecond';
  16294. return +this.clone().startOf(units) > +moment(input).startOf(units);
  16295. },
  16296. isBefore: function (input, units) {
  16297. units = typeof units !== 'undefined' ? units : 'millisecond';
  16298. return +this.clone().startOf(units) < +moment(input).startOf(units);
  16299. },
  16300. isSame: function (input, units) {
  16301. units = units || 'ms';
  16302. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  16303. },
  16304. min: function (other) {
  16305. other = moment.apply(null, arguments);
  16306. return other < this ? this : other;
  16307. },
  16308. max: function (other) {
  16309. other = moment.apply(null, arguments);
  16310. return other > this ? this : other;
  16311. },
  16312. zone : function (input) {
  16313. var offset = this._offset || 0;
  16314. if (input != null) {
  16315. if (typeof input === "string") {
  16316. input = timezoneMinutesFromString(input);
  16317. }
  16318. if (Math.abs(input) < 16) {
  16319. input = input * 60;
  16320. }
  16321. this._offset = input;
  16322. this._isUTC = true;
  16323. if (offset !== input) {
  16324. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  16325. }
  16326. } else {
  16327. return this._isUTC ? offset : this._d.getTimezoneOffset();
  16328. }
  16329. return this;
  16330. },
  16331. zoneAbbr : function () {
  16332. return this._isUTC ? "UTC" : "";
  16333. },
  16334. zoneName : function () {
  16335. return this._isUTC ? "Coordinated Universal Time" : "";
  16336. },
  16337. parseZone : function () {
  16338. if (this._tzm) {
  16339. this.zone(this._tzm);
  16340. } else if (typeof this._i === 'string') {
  16341. this.zone(this._i);
  16342. }
  16343. return this;
  16344. },
  16345. hasAlignedHourOffset : function (input) {
  16346. if (!input) {
  16347. input = 0;
  16348. }
  16349. else {
  16350. input = moment(input).zone();
  16351. }
  16352. return (this.zone() - input) % 60 === 0;
  16353. },
  16354. daysInMonth : function () {
  16355. return daysInMonth(this.year(), this.month());
  16356. },
  16357. dayOfYear : function (input) {
  16358. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  16359. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  16360. },
  16361. quarter : function () {
  16362. return Math.ceil((this.month() + 1.0) / 3.0);
  16363. },
  16364. weekYear : function (input) {
  16365. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  16366. return input == null ? year : this.add("y", (input - year));
  16367. },
  16368. isoWeekYear : function (input) {
  16369. var year = weekOfYear(this, 1, 4).year;
  16370. return input == null ? year : this.add("y", (input - year));
  16371. },
  16372. week : function (input) {
  16373. var week = this.lang().week(this);
  16374. return input == null ? week : this.add("d", (input - week) * 7);
  16375. },
  16376. isoWeek : function (input) {
  16377. var week = weekOfYear(this, 1, 4).week;
  16378. return input == null ? week : this.add("d", (input - week) * 7);
  16379. },
  16380. weekday : function (input) {
  16381. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  16382. return input == null ? weekday : this.add("d", input - weekday);
  16383. },
  16384. isoWeekday : function (input) {
  16385. // behaves the same as moment#day except
  16386. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  16387. // as a setter, sunday should belong to the previous week.
  16388. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  16389. },
  16390. get : function (units) {
  16391. units = normalizeUnits(units);
  16392. return this[units]();
  16393. },
  16394. set : function (units, value) {
  16395. units = normalizeUnits(units);
  16396. if (typeof this[units] === 'function') {
  16397. this[units](value);
  16398. }
  16399. return this;
  16400. },
  16401. // If passed a language key, it will set the language for this
  16402. // instance. Otherwise, it will return the language configuration
  16403. // variables for this instance.
  16404. lang : function (key) {
  16405. if (key === undefined) {
  16406. return this._lang;
  16407. } else {
  16408. this._lang = getLangDefinition(key);
  16409. return this;
  16410. }
  16411. }
  16412. });
  16413. // helper for adding shortcuts
  16414. function makeGetterAndSetter(name, key) {
  16415. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  16416. var utc = this._isUTC ? 'UTC' : '';
  16417. if (input != null) {
  16418. this._d['set' + utc + key](input);
  16419. moment.updateOffset(this);
  16420. return this;
  16421. } else {
  16422. return this._d['get' + utc + key]();
  16423. }
  16424. };
  16425. }
  16426. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  16427. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  16428. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  16429. }
  16430. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  16431. makeGetterAndSetter('year', 'FullYear');
  16432. // add plural methods
  16433. moment.fn.days = moment.fn.day;
  16434. moment.fn.months = moment.fn.month;
  16435. moment.fn.weeks = moment.fn.week;
  16436. moment.fn.isoWeeks = moment.fn.isoWeek;
  16437. // add aliased format methods
  16438. moment.fn.toJSON = moment.fn.toISOString;
  16439. /************************************
  16440. Duration Prototype
  16441. ************************************/
  16442. extend(moment.duration.fn = Duration.prototype, {
  16443. _bubble : function () {
  16444. var milliseconds = this._milliseconds,
  16445. days = this._days,
  16446. months = this._months,
  16447. data = this._data,
  16448. seconds, minutes, hours, years;
  16449. // The following code bubbles up values, see the tests for
  16450. // examples of what that means.
  16451. data.milliseconds = milliseconds % 1000;
  16452. seconds = absRound(milliseconds / 1000);
  16453. data.seconds = seconds % 60;
  16454. minutes = absRound(seconds / 60);
  16455. data.minutes = minutes % 60;
  16456. hours = absRound(minutes / 60);
  16457. data.hours = hours % 24;
  16458. days += absRound(hours / 24);
  16459. data.days = days % 30;
  16460. months += absRound(days / 30);
  16461. data.months = months % 12;
  16462. years = absRound(months / 12);
  16463. data.years = years;
  16464. },
  16465. weeks : function () {
  16466. return absRound(this.days() / 7);
  16467. },
  16468. valueOf : function () {
  16469. return this._milliseconds +
  16470. this._days * 864e5 +
  16471. (this._months % 12) * 2592e6 +
  16472. toInt(this._months / 12) * 31536e6;
  16473. },
  16474. humanize : function (withSuffix) {
  16475. var difference = +this,
  16476. output = relativeTime(difference, !withSuffix, this.lang());
  16477. if (withSuffix) {
  16478. output = this.lang().pastFuture(difference, output);
  16479. }
  16480. return this.lang().postformat(output);
  16481. },
  16482. add : function (input, val) {
  16483. // supports only 2.0-style add(1, 's') or add(moment)
  16484. var dur = moment.duration(input, val);
  16485. this._milliseconds += dur._milliseconds;
  16486. this._days += dur._days;
  16487. this._months += dur._months;
  16488. this._bubble();
  16489. return this;
  16490. },
  16491. subtract : function (input, val) {
  16492. var dur = moment.duration(input, val);
  16493. this._milliseconds -= dur._milliseconds;
  16494. this._days -= dur._days;
  16495. this._months -= dur._months;
  16496. this._bubble();
  16497. return this;
  16498. },
  16499. get : function (units) {
  16500. units = normalizeUnits(units);
  16501. return this[units.toLowerCase() + 's']();
  16502. },
  16503. as : function (units) {
  16504. units = normalizeUnits(units);
  16505. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  16506. },
  16507. lang : moment.fn.lang,
  16508. toIsoString : function () {
  16509. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  16510. var years = Math.abs(this.years()),
  16511. months = Math.abs(this.months()),
  16512. days = Math.abs(this.days()),
  16513. hours = Math.abs(this.hours()),
  16514. minutes = Math.abs(this.minutes()),
  16515. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  16516. if (!this.asSeconds()) {
  16517. // this is the same as C#'s (Noda) and python (isodate)...
  16518. // but not other JS (goog.date)
  16519. return 'P0D';
  16520. }
  16521. return (this.asSeconds() < 0 ? '-' : '') +
  16522. 'P' +
  16523. (years ? years + 'Y' : '') +
  16524. (months ? months + 'M' : '') +
  16525. (days ? days + 'D' : '') +
  16526. ((hours || minutes || seconds) ? 'T' : '') +
  16527. (hours ? hours + 'H' : '') +
  16528. (minutes ? minutes + 'M' : '') +
  16529. (seconds ? seconds + 'S' : '');
  16530. }
  16531. });
  16532. function makeDurationGetter(name) {
  16533. moment.duration.fn[name] = function () {
  16534. return this._data[name];
  16535. };
  16536. }
  16537. function makeDurationAsGetter(name, factor) {
  16538. moment.duration.fn['as' + name] = function () {
  16539. return +this / factor;
  16540. };
  16541. }
  16542. for (i in unitMillisecondFactors) {
  16543. if (unitMillisecondFactors.hasOwnProperty(i)) {
  16544. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  16545. makeDurationGetter(i.toLowerCase());
  16546. }
  16547. }
  16548. makeDurationAsGetter('Weeks', 6048e5);
  16549. moment.duration.fn.asMonths = function () {
  16550. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  16551. };
  16552. /************************************
  16553. Default Lang
  16554. ************************************/
  16555. // Set default language, other languages will inherit from English.
  16556. moment.lang('en', {
  16557. ordinal : function (number) {
  16558. var b = number % 10,
  16559. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  16560. (b === 1) ? 'st' :
  16561. (b === 2) ? 'nd' :
  16562. (b === 3) ? 'rd' : 'th';
  16563. return number + output;
  16564. }
  16565. });
  16566. /* EMBED_LANGUAGES */
  16567. /************************************
  16568. Exposing Moment
  16569. ************************************/
  16570. function makeGlobal(deprecate) {
  16571. var warned = false, local_moment = moment;
  16572. /*global ender:false */
  16573. if (typeof ender !== 'undefined') {
  16574. return;
  16575. }
  16576. // here, `this` means `window` in the browser, or `global` on the server
  16577. // add `moment` as a global object via a string identifier,
  16578. // for Closure Compiler "advanced" mode
  16579. if (deprecate) {
  16580. global.moment = function () {
  16581. if (!warned && console && console.warn) {
  16582. warned = true;
  16583. console.warn(
  16584. "Accessing Moment through the global scope is " +
  16585. "deprecated, and will be removed in an upcoming " +
  16586. "release.");
  16587. }
  16588. return local_moment.apply(null, arguments);
  16589. };
  16590. extend(global.moment, local_moment);
  16591. } else {
  16592. global['moment'] = moment;
  16593. }
  16594. }
  16595. // CommonJS module is defined
  16596. if (hasModule) {
  16597. module.exports = moment;
  16598. makeGlobal(true);
  16599. } else if (typeof define === "function" && define.amd) {
  16600. define("moment", function (require, exports, module) {
  16601. if (module.config && module.config() && module.config().noGlobal !== true) {
  16602. // If user provided noGlobal, he is aware of global
  16603. makeGlobal(module.config().noGlobal === undefined);
  16604. }
  16605. return moment;
  16606. });
  16607. } else {
  16608. makeGlobal();
  16609. }
  16610. }).call(this);
  16611. },{}],4:[function(require,module,exports){
  16612. /**
  16613. * Copyright 2012 Craig Campbell
  16614. *
  16615. * Licensed under the Apache License, Version 2.0 (the "License");
  16616. * you may not use this file except in compliance with the License.
  16617. * You may obtain a copy of the License at
  16618. *
  16619. * http://www.apache.org/licenses/LICENSE-2.0
  16620. *
  16621. * Unless required by applicable law or agreed to in writing, software
  16622. * distributed under the License is distributed on an "AS IS" BASIS,
  16623. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16624. * See the License for the specific language governing permissions and
  16625. * limitations under the License.
  16626. *
  16627. * Mousetrap is a simple keyboard shortcut library for Javascript with
  16628. * no external dependencies
  16629. *
  16630. * @version 1.1.2
  16631. * @url craig.is/killing/mice
  16632. */
  16633. /**
  16634. * mapping of special keycodes to their corresponding keys
  16635. *
  16636. * everything in this dictionary cannot use keypress events
  16637. * so it has to be here to map to the correct keycodes for
  16638. * keyup/keydown events
  16639. *
  16640. * @type {Object}
  16641. */
  16642. var _MAP = {
  16643. 8: 'backspace',
  16644. 9: 'tab',
  16645. 13: 'enter',
  16646. 16: 'shift',
  16647. 17: 'ctrl',
  16648. 18: 'alt',
  16649. 20: 'capslock',
  16650. 27: 'esc',
  16651. 32: 'space',
  16652. 33: 'pageup',
  16653. 34: 'pagedown',
  16654. 35: 'end',
  16655. 36: 'home',
  16656. 37: 'left',
  16657. 38: 'up',
  16658. 39: 'right',
  16659. 40: 'down',
  16660. 45: 'ins',
  16661. 46: 'del',
  16662. 91: 'meta',
  16663. 93: 'meta',
  16664. 224: 'meta'
  16665. },
  16666. /**
  16667. * mapping for special characters so they can support
  16668. *
  16669. * this dictionary is only used incase you want to bind a
  16670. * keyup or keydown event to one of these keys
  16671. *
  16672. * @type {Object}
  16673. */
  16674. _KEYCODE_MAP = {
  16675. 106: '*',
  16676. 107: '+',
  16677. 109: '-',
  16678. 110: '.',
  16679. 111 : '/',
  16680. 186: ';',
  16681. 187: '=',
  16682. 188: ',',
  16683. 189: '-',
  16684. 190: '.',
  16685. 191: '/',
  16686. 192: '`',
  16687. 219: '[',
  16688. 220: '\\',
  16689. 221: ']',
  16690. 222: '\''
  16691. },
  16692. /**
  16693. * this is a mapping of keys that require shift on a US keypad
  16694. * back to the non shift equivelents
  16695. *
  16696. * this is so you can use keyup events with these keys
  16697. *
  16698. * note that this will only work reliably on US keyboards
  16699. *
  16700. * @type {Object}
  16701. */
  16702. _SHIFT_MAP = {
  16703. '~': '`',
  16704. '!': '1',
  16705. '@': '2',
  16706. '#': '3',
  16707. '$': '4',
  16708. '%': '5',
  16709. '^': '6',
  16710. '&': '7',
  16711. '*': '8',
  16712. '(': '9',
  16713. ')': '0',
  16714. '_': '-',
  16715. '+': '=',
  16716. ':': ';',
  16717. '\"': '\'',
  16718. '<': ',',
  16719. '>': '.',
  16720. '?': '/',
  16721. '|': '\\'
  16722. },
  16723. /**
  16724. * this is a list of special strings you can use to map
  16725. * to modifier keys when you specify your keyboard shortcuts
  16726. *
  16727. * @type {Object}
  16728. */
  16729. _SPECIAL_ALIASES = {
  16730. 'option': 'alt',
  16731. 'command': 'meta',
  16732. 'return': 'enter',
  16733. 'escape': 'esc'
  16734. },
  16735. /**
  16736. * variable to store the flipped version of _MAP from above
  16737. * needed to check if we should use keypress or not when no action
  16738. * is specified
  16739. *
  16740. * @type {Object|undefined}
  16741. */
  16742. _REVERSE_MAP,
  16743. /**
  16744. * a list of all the callbacks setup via Mousetrap.bind()
  16745. *
  16746. * @type {Object}
  16747. */
  16748. _callbacks = {},
  16749. /**
  16750. * direct map of string combinations to callbacks used for trigger()
  16751. *
  16752. * @type {Object}
  16753. */
  16754. _direct_map = {},
  16755. /**
  16756. * keeps track of what level each sequence is at since multiple
  16757. * sequences can start out with the same sequence
  16758. *
  16759. * @type {Object}
  16760. */
  16761. _sequence_levels = {},
  16762. /**
  16763. * variable to store the setTimeout call
  16764. *
  16765. * @type {null|number}
  16766. */
  16767. _reset_timer,
  16768. /**
  16769. * temporary state where we will ignore the next keyup
  16770. *
  16771. * @type {boolean|string}
  16772. */
  16773. _ignore_next_keyup = false,
  16774. /**
  16775. * are we currently inside of a sequence?
  16776. * type of action ("keyup" or "keydown" or "keypress") or false
  16777. *
  16778. * @type {boolean|string}
  16779. */
  16780. _inside_sequence = false;
  16781. /**
  16782. * loop through the f keys, f1 to f19 and add them to the map
  16783. * programatically
  16784. */
  16785. for (var i = 1; i < 20; ++i) {
  16786. _MAP[111 + i] = 'f' + i;
  16787. }
  16788. /**
  16789. * loop through to map numbers on the numeric keypad
  16790. */
  16791. for (i = 0; i <= 9; ++i) {
  16792. _MAP[i + 96] = i;
  16793. }
  16794. /**
  16795. * cross browser add event method
  16796. *
  16797. * @param {Element|HTMLDocument} object
  16798. * @param {string} type
  16799. * @param {Function} callback
  16800. * @returns void
  16801. */
  16802. function _addEvent(object, type, callback) {
  16803. if (object.addEventListener) {
  16804. return object.addEventListener(type, callback, false);
  16805. }
  16806. object.attachEvent('on' + type, callback);
  16807. }
  16808. /**
  16809. * takes the event and returns the key character
  16810. *
  16811. * @param {Event} e
  16812. * @return {string}
  16813. */
  16814. function _characterFromEvent(e) {
  16815. // for keypress events we should return the character as is
  16816. if (e.type == 'keypress') {
  16817. return String.fromCharCode(e.which);
  16818. }
  16819. // for non keypress events the special maps are needed
  16820. if (_MAP[e.which]) {
  16821. return _MAP[e.which];
  16822. }
  16823. if (_KEYCODE_MAP[e.which]) {
  16824. return _KEYCODE_MAP[e.which];
  16825. }
  16826. // if it is not in the special map
  16827. return String.fromCharCode(e.which).toLowerCase();
  16828. }
  16829. /**
  16830. * should we stop this event before firing off callbacks
  16831. *
  16832. * @param {Event} e
  16833. * @return {boolean}
  16834. */
  16835. function _stop(e) {
  16836. var element = e.target || e.srcElement,
  16837. tag_name = element.tagName;
  16838. // if the element has the class "mousetrap" then no need to stop
  16839. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  16840. return false;
  16841. }
  16842. // stop for input, select, and textarea
  16843. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  16844. }
  16845. /**
  16846. * checks if two arrays are equal
  16847. *
  16848. * @param {Array} modifiers1
  16849. * @param {Array} modifiers2
  16850. * @returns {boolean}
  16851. */
  16852. function _modifiersMatch(modifiers1, modifiers2) {
  16853. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  16854. }
  16855. /**
  16856. * resets all sequence counters except for the ones passed in
  16857. *
  16858. * @param {Object} do_not_reset
  16859. * @returns void
  16860. */
  16861. function _resetSequences(do_not_reset) {
  16862. do_not_reset = do_not_reset || {};
  16863. var active_sequences = false,
  16864. key;
  16865. for (key in _sequence_levels) {
  16866. if (do_not_reset[key]) {
  16867. active_sequences = true;
  16868. continue;
  16869. }
  16870. _sequence_levels[key] = 0;
  16871. }
  16872. if (!active_sequences) {
  16873. _inside_sequence = false;
  16874. }
  16875. }
  16876. /**
  16877. * finds all callbacks that match based on the keycode, modifiers,
  16878. * and action
  16879. *
  16880. * @param {string} character
  16881. * @param {Array} modifiers
  16882. * @param {string} action
  16883. * @param {boolean=} remove - should we remove any matches
  16884. * @param {string=} combination
  16885. * @returns {Array}
  16886. */
  16887. function _getMatches(character, modifiers, action, remove, combination) {
  16888. var i,
  16889. callback,
  16890. matches = [];
  16891. // if there are no events related to this keycode
  16892. if (!_callbacks[character]) {
  16893. return [];
  16894. }
  16895. // if a modifier key is coming up on its own we should allow it
  16896. if (action == 'keyup' && _isModifier(character)) {
  16897. modifiers = [character];
  16898. }
  16899. // loop through all callbacks for the key that was pressed
  16900. // and see if any of them match
  16901. for (i = 0; i < _callbacks[character].length; ++i) {
  16902. callback = _callbacks[character][i];
  16903. // if this is a sequence but it is not at the right level
  16904. // then move onto the next match
  16905. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  16906. continue;
  16907. }
  16908. // if the action we are looking for doesn't match the action we got
  16909. // then we should keep going
  16910. if (action != callback.action) {
  16911. continue;
  16912. }
  16913. // if this is a keypress event that means that we need to only
  16914. // look at the character, otherwise check the modifiers as
  16915. // well
  16916. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  16917. // remove is used so if you change your mind and call bind a
  16918. // second time with a new function the first one is overwritten
  16919. if (remove && callback.combo == combination) {
  16920. _callbacks[character].splice(i, 1);
  16921. }
  16922. matches.push(callback);
  16923. }
  16924. }
  16925. return matches;
  16926. }
  16927. /**
  16928. * takes a key event and figures out what the modifiers are
  16929. *
  16930. * @param {Event} e
  16931. * @returns {Array}
  16932. */
  16933. function _eventModifiers(e) {
  16934. var modifiers = [];
  16935. if (e.shiftKey) {
  16936. modifiers.push('shift');
  16937. }
  16938. if (e.altKey) {
  16939. modifiers.push('alt');
  16940. }
  16941. if (e.ctrlKey) {
  16942. modifiers.push('ctrl');
  16943. }
  16944. if (e.metaKey) {
  16945. modifiers.push('meta');
  16946. }
  16947. return modifiers;
  16948. }
  16949. /**
  16950. * actually calls the callback function
  16951. *
  16952. * if your callback function returns false this will use the jquery
  16953. * convention - prevent default and stop propogation on the event
  16954. *
  16955. * @param {Function} callback
  16956. * @param {Event} e
  16957. * @returns void
  16958. */
  16959. function _fireCallback(callback, e) {
  16960. if (callback(e) === false) {
  16961. if (e.preventDefault) {
  16962. e.preventDefault();
  16963. }
  16964. if (e.stopPropagation) {
  16965. e.stopPropagation();
  16966. }
  16967. e.returnValue = false;
  16968. e.cancelBubble = true;
  16969. }
  16970. }
  16971. /**
  16972. * handles a character key event
  16973. *
  16974. * @param {string} character
  16975. * @param {Event} e
  16976. * @returns void
  16977. */
  16978. function _handleCharacter(character, e) {
  16979. // if this event should not happen stop here
  16980. if (_stop(e)) {
  16981. return;
  16982. }
  16983. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  16984. i,
  16985. do_not_reset = {},
  16986. processed_sequence_callback = false;
  16987. // loop through matching callbacks for this key event
  16988. for (i = 0; i < callbacks.length; ++i) {
  16989. // fire for all sequence callbacks
  16990. // this is because if for example you have multiple sequences
  16991. // bound such as "g i" and "g t" they both need to fire the
  16992. // callback for matching g cause otherwise you can only ever
  16993. // match the first one
  16994. if (callbacks[i].seq) {
  16995. processed_sequence_callback = true;
  16996. // keep a list of which sequences were matches for later
  16997. do_not_reset[callbacks[i].seq] = 1;
  16998. _fireCallback(callbacks[i].callback, e);
  16999. continue;
  17000. }
  17001. // if there were no sequence matches but we are still here
  17002. // that means this is a regular match so we should fire that
  17003. if (!processed_sequence_callback && !_inside_sequence) {
  17004. _fireCallback(callbacks[i].callback, e);
  17005. }
  17006. }
  17007. // if you are inside of a sequence and the key you are pressing
  17008. // is not a modifier key then we should reset all sequences
  17009. // that were not matched by this key event
  17010. if (e.type == _inside_sequence && !_isModifier(character)) {
  17011. _resetSequences(do_not_reset);
  17012. }
  17013. }
  17014. /**
  17015. * handles a keydown event
  17016. *
  17017. * @param {Event} e
  17018. * @returns void
  17019. */
  17020. function _handleKey(e) {
  17021. // normalize e.which for key events
  17022. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  17023. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  17024. var character = _characterFromEvent(e);
  17025. // no character found then stop
  17026. if (!character) {
  17027. return;
  17028. }
  17029. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  17030. _ignore_next_keyup = false;
  17031. return;
  17032. }
  17033. _handleCharacter(character, e);
  17034. }
  17035. /**
  17036. * determines if the keycode specified is a modifier key or not
  17037. *
  17038. * @param {string} key
  17039. * @returns {boolean}
  17040. */
  17041. function _isModifier(key) {
  17042. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  17043. }
  17044. /**
  17045. * called to set a 1 second timeout on the specified sequence
  17046. *
  17047. * this is so after each key press in the sequence you have 1 second
  17048. * to press the next key before you have to start over
  17049. *
  17050. * @returns void
  17051. */
  17052. function _resetSequenceTimer() {
  17053. clearTimeout(_reset_timer);
  17054. _reset_timer = setTimeout(_resetSequences, 1000);
  17055. }
  17056. /**
  17057. * reverses the map lookup so that we can look for specific keys
  17058. * to see what can and can't use keypress
  17059. *
  17060. * @return {Object}
  17061. */
  17062. function _getReverseMap() {
  17063. if (!_REVERSE_MAP) {
  17064. _REVERSE_MAP = {};
  17065. for (var key in _MAP) {
  17066. // pull out the numeric keypad from here cause keypress should
  17067. // be able to detect the keys from the character
  17068. if (key > 95 && key < 112) {
  17069. continue;
  17070. }
  17071. if (_MAP.hasOwnProperty(key)) {
  17072. _REVERSE_MAP[_MAP[key]] = key;
  17073. }
  17074. }
  17075. }
  17076. return _REVERSE_MAP;
  17077. }
  17078. /**
  17079. * picks the best action based on the key combination
  17080. *
  17081. * @param {string} key - character for key
  17082. * @param {Array} modifiers
  17083. * @param {string=} action passed in
  17084. */
  17085. function _pickBestAction(key, modifiers, action) {
  17086. // if no action was picked in we should try to pick the one
  17087. // that we think would work best for this key
  17088. if (!action) {
  17089. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  17090. }
  17091. // modifier keys don't work as expected with keypress,
  17092. // switch to keydown
  17093. if (action == 'keypress' && modifiers.length) {
  17094. action = 'keydown';
  17095. }
  17096. return action;
  17097. }
  17098. /**
  17099. * binds a key sequence to an event
  17100. *
  17101. * @param {string} combo - combo specified in bind call
  17102. * @param {Array} keys
  17103. * @param {Function} callback
  17104. * @param {string=} action
  17105. * @returns void
  17106. */
  17107. function _bindSequence(combo, keys, callback, action) {
  17108. // start off by adding a sequence level record for this combination
  17109. // and setting the level to 0
  17110. _sequence_levels[combo] = 0;
  17111. // if there is no action pick the best one for the first key
  17112. // in the sequence
  17113. if (!action) {
  17114. action = _pickBestAction(keys[0], []);
  17115. }
  17116. /**
  17117. * callback to increase the sequence level for this sequence and reset
  17118. * all other sequences that were active
  17119. *
  17120. * @param {Event} e
  17121. * @returns void
  17122. */
  17123. var _increaseSequence = function(e) {
  17124. _inside_sequence = action;
  17125. ++_sequence_levels[combo];
  17126. _resetSequenceTimer();
  17127. },
  17128. /**
  17129. * wraps the specified callback inside of another function in order
  17130. * to reset all sequence counters as soon as this sequence is done
  17131. *
  17132. * @param {Event} e
  17133. * @returns void
  17134. */
  17135. _callbackAndReset = function(e) {
  17136. _fireCallback(callback, e);
  17137. // we should ignore the next key up if the action is key down
  17138. // or keypress. this is so if you finish a sequence and
  17139. // release the key the final key will not trigger a keyup
  17140. if (action !== 'keyup') {
  17141. _ignore_next_keyup = _characterFromEvent(e);
  17142. }
  17143. // weird race condition if a sequence ends with the key
  17144. // another sequence begins with
  17145. setTimeout(_resetSequences, 10);
  17146. },
  17147. i;
  17148. // loop through keys one at a time and bind the appropriate callback
  17149. // function. for any key leading up to the final one it should
  17150. // increase the sequence. after the final, it should reset all sequences
  17151. for (i = 0; i < keys.length; ++i) {
  17152. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  17153. }
  17154. }
  17155. /**
  17156. * binds a single keyboard combination
  17157. *
  17158. * @param {string} combination
  17159. * @param {Function} callback
  17160. * @param {string=} action
  17161. * @param {string=} sequence_name - name of sequence if part of sequence
  17162. * @param {number=} level - what part of the sequence the command is
  17163. * @returns void
  17164. */
  17165. function _bindSingle(combination, callback, action, sequence_name, level) {
  17166. // make sure multiple spaces in a row become a single space
  17167. combination = combination.replace(/\s+/g, ' ');
  17168. var sequence = combination.split(' '),
  17169. i,
  17170. key,
  17171. keys,
  17172. modifiers = [];
  17173. // if this pattern is a sequence of keys then run through this method
  17174. // to reprocess each pattern one key at a time
  17175. if (sequence.length > 1) {
  17176. return _bindSequence(combination, sequence, callback, action);
  17177. }
  17178. // take the keys from this pattern and figure out what the actual
  17179. // pattern is all about
  17180. keys = combination === '+' ? ['+'] : combination.split('+');
  17181. for (i = 0; i < keys.length; ++i) {
  17182. key = keys[i];
  17183. // normalize key names
  17184. if (_SPECIAL_ALIASES[key]) {
  17185. key = _SPECIAL_ALIASES[key];
  17186. }
  17187. // if this is not a keypress event then we should
  17188. // be smart about using shift keys
  17189. // this will only work for US keyboards however
  17190. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  17191. key = _SHIFT_MAP[key];
  17192. modifiers.push('shift');
  17193. }
  17194. // if this key is a modifier then add it to the list of modifiers
  17195. if (_isModifier(key)) {
  17196. modifiers.push(key);
  17197. }
  17198. }
  17199. // depending on what the key combination is
  17200. // we will try to pick the best event for it
  17201. action = _pickBestAction(key, modifiers, action);
  17202. // make sure to initialize array if this is the first time
  17203. // a callback is added for this key
  17204. if (!_callbacks[key]) {
  17205. _callbacks[key] = [];
  17206. }
  17207. // remove an existing match if there is one
  17208. _getMatches(key, modifiers, action, !sequence_name, combination);
  17209. // add this call back to the array
  17210. // if it is a sequence put it at the beginning
  17211. // if not put it at the end
  17212. //
  17213. // this is important because the way these are processed expects
  17214. // the sequence ones to come first
  17215. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  17216. callback: callback,
  17217. modifiers: modifiers,
  17218. action: action,
  17219. seq: sequence_name,
  17220. level: level,
  17221. combo: combination
  17222. });
  17223. }
  17224. /**
  17225. * binds multiple combinations to the same callback
  17226. *
  17227. * @param {Array} combinations
  17228. * @param {Function} callback
  17229. * @param {string|undefined} action
  17230. * @returns void
  17231. */
  17232. function _bindMultiple(combinations, callback, action) {
  17233. for (var i = 0; i < combinations.length; ++i) {
  17234. _bindSingle(combinations[i], callback, action);
  17235. }
  17236. }
  17237. // start!
  17238. _addEvent(document, 'keypress', _handleKey);
  17239. _addEvent(document, 'keydown', _handleKey);
  17240. _addEvent(document, 'keyup', _handleKey);
  17241. var mousetrap = {
  17242. /**
  17243. * binds an event to mousetrap
  17244. *
  17245. * can be a single key, a combination of keys separated with +,
  17246. * a comma separated list of keys, an array of keys, or
  17247. * a sequence of keys separated by spaces
  17248. *
  17249. * be sure to list the modifier keys first to make sure that the
  17250. * correct key ends up getting bound (the last key in the pattern)
  17251. *
  17252. * @param {string|Array} keys
  17253. * @param {Function} callback
  17254. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  17255. * @returns void
  17256. */
  17257. bind: function(keys, callback, action) {
  17258. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  17259. _direct_map[keys + ':' + action] = callback;
  17260. return this;
  17261. },
  17262. /**
  17263. * unbinds an event to mousetrap
  17264. *
  17265. * the unbinding sets the callback function of the specified key combo
  17266. * to an empty function and deletes the corresponding key in the
  17267. * _direct_map dict.
  17268. *
  17269. * the keycombo+action has to be exactly the same as
  17270. * it was defined in the bind method
  17271. *
  17272. * TODO: actually remove this from the _callbacks dictionary instead
  17273. * of binding an empty function
  17274. *
  17275. * @param {string|Array} keys
  17276. * @param {string} action
  17277. * @returns void
  17278. */
  17279. unbind: function(keys, action) {
  17280. if (_direct_map[keys + ':' + action]) {
  17281. delete _direct_map[keys + ':' + action];
  17282. this.bind(keys, function() {}, action);
  17283. }
  17284. return this;
  17285. },
  17286. /**
  17287. * triggers an event that has already been bound
  17288. *
  17289. * @param {string} keys
  17290. * @param {string=} action
  17291. * @returns void
  17292. */
  17293. trigger: function(keys, action) {
  17294. _direct_map[keys + ':' + action]();
  17295. return this;
  17296. },
  17297. /**
  17298. * resets the library back to its initial state. this is useful
  17299. * if you want to clear out the current keyboard shortcuts and bind
  17300. * new ones - for example if you switch to another page
  17301. *
  17302. * @returns void
  17303. */
  17304. reset: function() {
  17305. _callbacks = {};
  17306. _direct_map = {};
  17307. return this;
  17308. }
  17309. };
  17310. module.exports = mousetrap;
  17311. },{}]},{},[1])
  17312. (1)
  17313. });