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.

18327 lines
522 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version @@version
  8. * @date @@date
  9. *
  10. * @license
  11. * Copyright (C) 2011-2014 Almende B.V, http://almende.com
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  14. * use this file except in compliance with the License. You may obtain a copy
  15. * of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  22. * License for the specific language governing permissions and limitations under
  23. * the License.
  24. */
  25. !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.vis=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  26. /**
  27. * vis.js module imports
  28. */
  29. // Try to load dependencies from the global window object.
  30. // If not available there, load via require.
  31. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment');
  32. var Hammer;
  33. if (typeof window !== 'undefined') {
  34. // load hammer.js only when running in a browser (where window is available)
  35. Hammer = window['Hammer'] || require('hammerjs');
  36. }
  37. else {
  38. Hammer = function () {
  39. throw Error('hammer.js is only available in a browser, not in node.js.');
  40. }
  41. }
  42. var mouseTrap;
  43. if (typeof window !== 'undefined') {
  44. // load mousetrap.js only when running in a browser (where window is available)
  45. mouseTrap = window['mouseTrap'] || require('mouseTrap');
  46. }
  47. else {
  48. mouseTrap = function () {
  49. throw Error('mouseTrap is only available in a browser, not in node.js.');
  50. }
  51. }
  52. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  53. // it here in that case.
  54. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  55. if(!Array.prototype.indexOf) {
  56. Array.prototype.indexOf = function(obj){
  57. for(var i = 0; i < this.length; i++){
  58. if(this[i] == obj){
  59. return i;
  60. }
  61. }
  62. return -1;
  63. };
  64. try {
  65. console.log("Warning: Ancient browser detected. Please update your browser");
  66. }
  67. catch (err) {
  68. }
  69. }
  70. // Internet Explorer 8 and older does not support Array.forEach, so we define
  71. // it here in that case.
  72. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  73. if (!Array.prototype.forEach) {
  74. Array.prototype.forEach = function(fn, scope) {
  75. for(var i = 0, len = this.length; i < len; ++i) {
  76. fn.call(scope || this, this[i], i, this);
  77. }
  78. }
  79. }
  80. // Internet Explorer 8 and older does not support Array.map, so we define it
  81. // here in that case.
  82. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  83. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  84. // Reference: http://es5.github.com/#x15.4.4.19
  85. if (!Array.prototype.map) {
  86. Array.prototype.map = function(callback, thisArg) {
  87. var T, A, k;
  88. if (this == null) {
  89. throw new TypeError(" this is null or not defined");
  90. }
  91. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  92. var O = Object(this);
  93. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  94. // 3. Let len be ToUint32(lenValue).
  95. var len = O.length >>> 0;
  96. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  97. // See: http://es5.github.com/#x9.11
  98. if (typeof callback !== "function") {
  99. throw new TypeError(callback + " is not a function");
  100. }
  101. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  102. if (thisArg) {
  103. T = thisArg;
  104. }
  105. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  106. // the standard built-in constructor with that name and len is the value of len.
  107. A = new Array(len);
  108. // 7. Let k be 0
  109. k = 0;
  110. // 8. Repeat, while k < len
  111. while(k < len) {
  112. var kValue, mappedValue;
  113. // a. Let Pk be ToString(k).
  114. // This is implicit for LHS operands of the in operator
  115. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  116. // This step can be combined with c
  117. // c. If kPresent is true, then
  118. if (k in O) {
  119. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  120. kValue = O[ k ];
  121. // ii. Let mappedValue be the result of calling the Call internal method of callback
  122. // with T as the this value and argument list containing kValue, k, and O.
  123. mappedValue = callback.call(T, kValue, k, O);
  124. // iii. Call the DefineOwnProperty internal method of A with arguments
  125. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  126. // and false.
  127. // In browsers that support Object.defineProperty, use the following:
  128. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  129. // For best browser support, use the following:
  130. A[ k ] = mappedValue;
  131. }
  132. // d. Increase k by 1.
  133. k++;
  134. }
  135. // 9. return A
  136. return A;
  137. };
  138. }
  139. // Internet Explorer 8 and older does not support Array.filter, so we define it
  140. // here in that case.
  141. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  142. if (!Array.prototype.filter) {
  143. Array.prototype.filter = function(fun /*, thisp */) {
  144. "use strict";
  145. if (this == null) {
  146. throw new TypeError();
  147. }
  148. var t = Object(this);
  149. var len = t.length >>> 0;
  150. if (typeof fun != "function") {
  151. throw new TypeError();
  152. }
  153. var res = [];
  154. var thisp = arguments[1];
  155. for (var i = 0; i < len; i++) {
  156. if (i in t) {
  157. var val = t[i]; // in case fun mutates this
  158. if (fun.call(thisp, val, i, t))
  159. res.push(val);
  160. }
  161. }
  162. return res;
  163. };
  164. }
  165. // Internet Explorer 8 and older does not support Object.keys, so we define it
  166. // here in that case.
  167. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  168. if (!Object.keys) {
  169. Object.keys = (function () {
  170. var hasOwnProperty = Object.prototype.hasOwnProperty,
  171. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  172. dontEnums = [
  173. 'toString',
  174. 'toLocaleString',
  175. 'valueOf',
  176. 'hasOwnProperty',
  177. 'isPrototypeOf',
  178. 'propertyIsEnumerable',
  179. 'constructor'
  180. ],
  181. dontEnumsLength = dontEnums.length;
  182. return function (obj) {
  183. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  184. throw new TypeError('Object.keys called on non-object');
  185. }
  186. var result = [];
  187. for (var prop in obj) {
  188. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  189. }
  190. if (hasDontEnumBug) {
  191. for (var i=0; i < dontEnumsLength; i++) {
  192. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  193. }
  194. }
  195. return result;
  196. }
  197. })()
  198. }
  199. // Internet Explorer 8 and older does not support Array.isArray,
  200. // so we define it here in that case.
  201. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  202. if(!Array.isArray) {
  203. Array.isArray = function (vArg) {
  204. return Object.prototype.toString.call(vArg) === "[object Array]";
  205. };
  206. }
  207. // Internet Explorer 8 and older does not support Function.bind,
  208. // so we define it here in that case.
  209. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  210. if (!Function.prototype.bind) {
  211. Function.prototype.bind = function (oThis) {
  212. if (typeof this !== "function") {
  213. // closest thing possible to the ECMAScript 5 internal IsCallable function
  214. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  215. }
  216. var aArgs = Array.prototype.slice.call(arguments, 1),
  217. fToBind = this,
  218. fNOP = function () {},
  219. fBound = function () {
  220. return fToBind.apply(this instanceof fNOP && oThis
  221. ? this
  222. : oThis,
  223. aArgs.concat(Array.prototype.slice.call(arguments)));
  224. };
  225. fNOP.prototype = this.prototype;
  226. fBound.prototype = new fNOP();
  227. return fBound;
  228. };
  229. }
  230. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  231. if (!Object.create) {
  232. Object.create = function (o) {
  233. if (arguments.length > 1) {
  234. throw new Error('Object.create implementation only accepts the first parameter.');
  235. }
  236. function F() {}
  237. F.prototype = o;
  238. return new F();
  239. };
  240. }
  241. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  242. if (!Function.prototype.bind) {
  243. Function.prototype.bind = function (oThis) {
  244. if (typeof this !== "function") {
  245. // closest thing possible to the ECMAScript 5 internal IsCallable function
  246. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  247. }
  248. var aArgs = Array.prototype.slice.call(arguments, 1),
  249. fToBind = this,
  250. fNOP = function () {},
  251. fBound = function () {
  252. return fToBind.apply(this instanceof fNOP && oThis
  253. ? this
  254. : oThis,
  255. aArgs.concat(Array.prototype.slice.call(arguments)));
  256. };
  257. fNOP.prototype = this.prototype;
  258. fBound.prototype = new fNOP();
  259. return fBound;
  260. };
  261. }
  262. /**
  263. * utility functions
  264. */
  265. var util = {};
  266. /**
  267. * Test whether given object is a number
  268. * @param {*} object
  269. * @return {Boolean} isNumber
  270. */
  271. util.isNumber = function isNumber(object) {
  272. return (object instanceof Number || typeof object == 'number');
  273. };
  274. /**
  275. * Test whether given object is a string
  276. * @param {*} object
  277. * @return {Boolean} isString
  278. */
  279. util.isString = function isString(object) {
  280. return (object instanceof String || typeof object == 'string');
  281. };
  282. /**
  283. * Test whether given object is a Date, or a String containing a Date
  284. * @param {Date | String} object
  285. * @return {Boolean} isDate
  286. */
  287. util.isDate = function isDate(object) {
  288. if (object instanceof Date) {
  289. return true;
  290. }
  291. else if (util.isString(object)) {
  292. // test whether this string contains a date
  293. var match = ASPDateRegex.exec(object);
  294. if (match) {
  295. return true;
  296. }
  297. else if (!isNaN(Date.parse(object))) {
  298. return true;
  299. }
  300. }
  301. return false;
  302. };
  303. /**
  304. * Test whether given object is an instance of google.visualization.DataTable
  305. * @param {*} object
  306. * @return {Boolean} isDataTable
  307. */
  308. util.isDataTable = function isDataTable(object) {
  309. return (typeof (google) !== 'undefined') &&
  310. (google.visualization) &&
  311. (google.visualization.DataTable) &&
  312. (object instanceof google.visualization.DataTable);
  313. };
  314. /**
  315. * Create a semi UUID
  316. * source: http://stackoverflow.com/a/105074/1262753
  317. * @return {String} uuid
  318. */
  319. util.randomUUID = function randomUUID () {
  320. var S4 = function () {
  321. return Math.floor(
  322. Math.random() * 0x10000 /* 65536 */
  323. ).toString(16);
  324. };
  325. return (
  326. S4() + S4() + '-' +
  327. S4() + '-' +
  328. S4() + '-' +
  329. S4() + '-' +
  330. S4() + S4() + S4()
  331. );
  332. };
  333. /**
  334. * Extend object a with the properties of object b or a series of objects
  335. * Only properties with defined values are copied
  336. * @param {Object} a
  337. * @param {... Object} b
  338. * @return {Object} a
  339. */
  340. util.extend = function (a, b) {
  341. for (var i = 1, len = arguments.length; i < len; i++) {
  342. var other = arguments[i];
  343. for (var prop in other) {
  344. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  345. a[prop] = other[prop];
  346. }
  347. }
  348. }
  349. return a;
  350. };
  351. /**
  352. * Convert an object to another type
  353. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  354. * @param {String | undefined} type Name of the type. Available types:
  355. * 'Boolean', 'Number', 'String',
  356. * 'Date', 'Moment', ISODate', 'ASPDate'.
  357. * @return {*} object
  358. * @throws Error
  359. */
  360. util.convert = function convert(object, type) {
  361. var match;
  362. if (object === undefined) {
  363. return undefined;
  364. }
  365. if (object === null) {
  366. return null;
  367. }
  368. if (!type) {
  369. return object;
  370. }
  371. if (!(typeof type === 'string') && !(type instanceof String)) {
  372. throw new Error('Type must be a string');
  373. }
  374. //noinspection FallthroughInSwitchStatementJS
  375. switch (type) {
  376. case 'boolean':
  377. case 'Boolean':
  378. return Boolean(object);
  379. case 'number':
  380. case 'Number':
  381. return Number(object.valueOf());
  382. case 'string':
  383. case 'String':
  384. return String(object);
  385. case 'Date':
  386. if (util.isNumber(object)) {
  387. return new Date(object);
  388. }
  389. if (object instanceof Date) {
  390. return new Date(object.valueOf());
  391. }
  392. else if (moment.isMoment(object)) {
  393. return new Date(object.valueOf());
  394. }
  395. if (util.isString(object)) {
  396. match = ASPDateRegex.exec(object);
  397. if (match) {
  398. // object is an ASP date
  399. return new Date(Number(match[1])); // parse number
  400. }
  401. else {
  402. return moment(object).toDate(); // parse string
  403. }
  404. }
  405. else {
  406. throw new Error(
  407. 'Cannot convert object of type ' + util.getType(object) +
  408. ' to type Date');
  409. }
  410. case 'Moment':
  411. if (util.isNumber(object)) {
  412. return moment(object);
  413. }
  414. if (object instanceof Date) {
  415. return moment(object.valueOf());
  416. }
  417. else if (moment.isMoment(object)) {
  418. return moment(object);
  419. }
  420. if (util.isString(object)) {
  421. match = ASPDateRegex.exec(object);
  422. if (match) {
  423. // object is an ASP date
  424. return moment(Number(match[1])); // parse number
  425. }
  426. else {
  427. return moment(object); // parse string
  428. }
  429. }
  430. else {
  431. throw new Error(
  432. 'Cannot convert object of type ' + util.getType(object) +
  433. ' to type Date');
  434. }
  435. case 'ISODate':
  436. if (util.isNumber(object)) {
  437. return new Date(object);
  438. }
  439. else if (object instanceof Date) {
  440. return object.toISOString();
  441. }
  442. else if (moment.isMoment(object)) {
  443. return object.toDate().toISOString();
  444. }
  445. else if (util.isString(object)) {
  446. match = ASPDateRegex.exec(object);
  447. if (match) {
  448. // object is an ASP date
  449. return new Date(Number(match[1])).toISOString(); // parse number
  450. }
  451. else {
  452. return new Date(object).toISOString(); // parse string
  453. }
  454. }
  455. else {
  456. throw new Error(
  457. 'Cannot convert object of type ' + util.getType(object) +
  458. ' to type ISODate');
  459. }
  460. case 'ASPDate':
  461. if (util.isNumber(object)) {
  462. return '/Date(' + object + ')/';
  463. }
  464. else if (object instanceof Date) {
  465. return '/Date(' + object.valueOf() + ')/';
  466. }
  467. else if (util.isString(object)) {
  468. match = ASPDateRegex.exec(object);
  469. var value;
  470. if (match) {
  471. // object is an ASP date
  472. value = new Date(Number(match[1])).valueOf(); // parse number
  473. }
  474. else {
  475. value = new Date(object).valueOf(); // parse string
  476. }
  477. return '/Date(' + value + ')/';
  478. }
  479. else {
  480. throw new Error(
  481. 'Cannot convert object of type ' + util.getType(object) +
  482. ' to type ASPDate');
  483. }
  484. default:
  485. throw new Error('Cannot convert object of type ' + util.getType(object) +
  486. ' to type "' + type + '"');
  487. }
  488. };
  489. // parse ASP.Net Date pattern,
  490. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  491. // code from http://momentjs.com/
  492. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  493. /**
  494. * Get the type of an object, for example util.getType([]) returns 'Array'
  495. * @param {*} object
  496. * @return {String} type
  497. */
  498. util.getType = function getType(object) {
  499. var type = typeof object;
  500. if (type == 'object') {
  501. if (object == null) {
  502. return 'null';
  503. }
  504. if (object instanceof Boolean) {
  505. return 'Boolean';
  506. }
  507. if (object instanceof Number) {
  508. return 'Number';
  509. }
  510. if (object instanceof String) {
  511. return 'String';
  512. }
  513. if (object instanceof Array) {
  514. return 'Array';
  515. }
  516. if (object instanceof Date) {
  517. return 'Date';
  518. }
  519. return 'Object';
  520. }
  521. else if (type == 'number') {
  522. return 'Number';
  523. }
  524. else if (type == 'boolean') {
  525. return 'Boolean';
  526. }
  527. else if (type == 'string') {
  528. return 'String';
  529. }
  530. return type;
  531. };
  532. /**
  533. * Retrieve the absolute left value of a DOM element
  534. * @param {Element} elem A dom element, for example a div
  535. * @return {number} left The absolute left position of this element
  536. * in the browser page.
  537. */
  538. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  539. var doc = document.documentElement;
  540. var body = document.body;
  541. var left = elem.offsetLeft;
  542. var e = elem.offsetParent;
  543. while (e != null && e != body && e != doc) {
  544. left += e.offsetLeft;
  545. left -= e.scrollLeft;
  546. e = e.offsetParent;
  547. }
  548. return left;
  549. };
  550. /**
  551. * Retrieve the absolute top value of a DOM element
  552. * @param {Element} elem A dom element, for example a div
  553. * @return {number} top The absolute top position of this element
  554. * in the browser page.
  555. */
  556. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  557. var doc = document.documentElement;
  558. var body = document.body;
  559. var top = elem.offsetTop;
  560. var e = elem.offsetParent;
  561. while (e != null && e != body && e != doc) {
  562. top += e.offsetTop;
  563. top -= e.scrollTop;
  564. e = e.offsetParent;
  565. }
  566. return top;
  567. };
  568. /**
  569. * Get the absolute, vertical mouse position from an event.
  570. * @param {Event} event
  571. * @return {Number} pageY
  572. */
  573. util.getPageY = function getPageY (event) {
  574. if ('pageY' in event) {
  575. return event.pageY;
  576. }
  577. else {
  578. var clientY;
  579. if (('targetTouches' in event) && event.targetTouches.length) {
  580. clientY = event.targetTouches[0].clientY;
  581. }
  582. else {
  583. clientY = event.clientY;
  584. }
  585. var doc = document.documentElement;
  586. var body = document.body;
  587. return clientY +
  588. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  589. ( doc && doc.clientTop || body && body.clientTop || 0 );
  590. }
  591. };
  592. /**
  593. * Get the absolute, horizontal mouse position from an event.
  594. * @param {Event} event
  595. * @return {Number} pageX
  596. */
  597. util.getPageX = function getPageX (event) {
  598. if ('pageY' in event) {
  599. return event.pageX;
  600. }
  601. else {
  602. var clientX;
  603. if (('targetTouches' in event) && event.targetTouches.length) {
  604. clientX = event.targetTouches[0].clientX;
  605. }
  606. else {
  607. clientX = event.clientX;
  608. }
  609. var doc = document.documentElement;
  610. var body = document.body;
  611. return clientX +
  612. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  613. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  614. }
  615. };
  616. /**
  617. * add a className to the given elements style
  618. * @param {Element} elem
  619. * @param {String} className
  620. */
  621. util.addClassName = function addClassName(elem, className) {
  622. var classes = elem.className.split(' ');
  623. if (classes.indexOf(className) == -1) {
  624. classes.push(className); // add the class to the array
  625. elem.className = classes.join(' ');
  626. }
  627. };
  628. /**
  629. * add a className to the given elements style
  630. * @param {Element} elem
  631. * @param {String} className
  632. */
  633. util.removeClassName = function removeClassname(elem, className) {
  634. var classes = elem.className.split(' ');
  635. var index = classes.indexOf(className);
  636. if (index != -1) {
  637. classes.splice(index, 1); // remove the class from the array
  638. elem.className = classes.join(' ');
  639. }
  640. };
  641. /**
  642. * For each method for both arrays and objects.
  643. * In case of an array, the built-in Array.forEach() is applied.
  644. * In case of an Object, the method loops over all properties of the object.
  645. * @param {Object | Array} object An Object or Array
  646. * @param {function} callback Callback method, called for each item in
  647. * the object or array with three parameters:
  648. * callback(value, index, object)
  649. */
  650. util.forEach = function forEach (object, callback) {
  651. var i,
  652. len;
  653. if (object instanceof Array) {
  654. // array
  655. for (i = 0, len = object.length; i < len; i++) {
  656. callback(object[i], i, object);
  657. }
  658. }
  659. else {
  660. // object
  661. for (i in object) {
  662. if (object.hasOwnProperty(i)) {
  663. callback(object[i], i, object);
  664. }
  665. }
  666. }
  667. };
  668. /**
  669. * Update a property in an object
  670. * @param {Object} object
  671. * @param {String} key
  672. * @param {*} value
  673. * @return {Boolean} changed
  674. */
  675. util.updateProperty = function updateProp (object, key, value) {
  676. if (object[key] !== value) {
  677. object[key] = value;
  678. return true;
  679. }
  680. else {
  681. return false;
  682. }
  683. };
  684. /**
  685. * Add and event listener. Works for all browsers
  686. * @param {Element} element An html element
  687. * @param {string} action The action, for example "click",
  688. * without the prefix "on"
  689. * @param {function} listener The callback function to be executed
  690. * @param {boolean} [useCapture]
  691. */
  692. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  693. if (element.addEventListener) {
  694. if (useCapture === undefined)
  695. useCapture = false;
  696. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  697. action = "DOMMouseScroll"; // For Firefox
  698. }
  699. element.addEventListener(action, listener, useCapture);
  700. } else {
  701. element.attachEvent("on" + action, listener); // IE browsers
  702. }
  703. };
  704. /**
  705. * Remove an event listener from an element
  706. * @param {Element} element An html dom element
  707. * @param {string} action The name of the event, for example "mousedown"
  708. * @param {function} listener The listener function
  709. * @param {boolean} [useCapture]
  710. */
  711. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  712. if (element.removeEventListener) {
  713. // non-IE browsers
  714. if (useCapture === undefined)
  715. useCapture = false;
  716. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  717. action = "DOMMouseScroll"; // For Firefox
  718. }
  719. element.removeEventListener(action, listener, useCapture);
  720. } else {
  721. // IE browsers
  722. element.detachEvent("on" + action, listener);
  723. }
  724. };
  725. /**
  726. * Get HTML element which is the target of the event
  727. * @param {Event} event
  728. * @return {Element} target element
  729. */
  730. util.getTarget = function getTarget(event) {
  731. // code from http://www.quirksmode.org/js/events_properties.html
  732. if (!event) {
  733. event = window.event;
  734. }
  735. var target;
  736. if (event.target) {
  737. target = event.target;
  738. }
  739. else if (event.srcElement) {
  740. target = event.srcElement;
  741. }
  742. if (target.nodeType != undefined && target.nodeType == 3) {
  743. // defeat Safari bug
  744. target = target.parentNode;
  745. }
  746. return target;
  747. };
  748. /**
  749. * Stop event propagation
  750. */
  751. util.stopPropagation = function stopPropagation(event) {
  752. if (!event)
  753. event = window.event;
  754. if (event.stopPropagation) {
  755. event.stopPropagation(); // non-IE browsers
  756. }
  757. else {
  758. event.cancelBubble = true; // IE browsers
  759. }
  760. };
  761. /**
  762. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  763. * @param {Element} element
  764. * @param {Event} event
  765. */
  766. util.fakeGesture = function fakeGesture (element, event) {
  767. var eventType = null;
  768. // for hammer.js 1.0.5
  769. return Hammer.event.collectEventData(this, eventType, event);
  770. // for hammer.js 1.0.6
  771. //var touches = Hammer.event.getTouchList(event, eventType);
  772. //return Hammer.event.collectEventData(this, eventType, touches, event);
  773. };
  774. /**
  775. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  776. */
  777. util.preventDefault = function preventDefault (event) {
  778. if (!event)
  779. event = window.event;
  780. if (event.preventDefault) {
  781. event.preventDefault(); // non-IE browsers
  782. }
  783. else {
  784. event.returnValue = false; // IE browsers
  785. }
  786. };
  787. util.option = {};
  788. /**
  789. * Convert a value into a boolean
  790. * @param {Boolean | function | undefined} value
  791. * @param {Boolean} [defaultValue]
  792. * @returns {Boolean} bool
  793. */
  794. util.option.asBoolean = function (value, defaultValue) {
  795. if (typeof value == 'function') {
  796. value = value();
  797. }
  798. if (value != null) {
  799. return (value != false);
  800. }
  801. return defaultValue || null;
  802. };
  803. /**
  804. * Convert a value into a number
  805. * @param {Boolean | function | undefined} value
  806. * @param {Number} [defaultValue]
  807. * @returns {Number} number
  808. */
  809. util.option.asNumber = function (value, defaultValue) {
  810. if (typeof value == 'function') {
  811. value = value();
  812. }
  813. if (value != null) {
  814. return Number(value) || defaultValue || null;
  815. }
  816. return defaultValue || null;
  817. };
  818. /**
  819. * Convert a value into a string
  820. * @param {String | function | undefined} value
  821. * @param {String} [defaultValue]
  822. * @returns {String} str
  823. */
  824. util.option.asString = function (value, defaultValue) {
  825. if (typeof value == 'function') {
  826. value = value();
  827. }
  828. if (value != null) {
  829. return String(value);
  830. }
  831. return defaultValue || null;
  832. };
  833. /**
  834. * Convert a size or location into a string with pixels or a percentage
  835. * @param {String | Number | function | undefined} value
  836. * @param {String} [defaultValue]
  837. * @returns {String} size
  838. */
  839. util.option.asSize = function (value, defaultValue) {
  840. if (typeof value == 'function') {
  841. value = value();
  842. }
  843. if (util.isString(value)) {
  844. return value;
  845. }
  846. else if (util.isNumber(value)) {
  847. return value + 'px';
  848. }
  849. else {
  850. return defaultValue || null;
  851. }
  852. };
  853. /**
  854. * Convert a value into a DOM element
  855. * @param {HTMLElement | function | undefined} value
  856. * @param {HTMLElement} [defaultValue]
  857. * @returns {HTMLElement | null} dom
  858. */
  859. util.option.asElement = function (value, defaultValue) {
  860. if (typeof value == 'function') {
  861. value = value();
  862. }
  863. return value || defaultValue || null;
  864. };
  865. /**
  866. * Event listener (singleton)
  867. */
  868. // TODO: replace usage of the event listener for the EventBus
  869. var events = {
  870. 'listeners': [],
  871. /**
  872. * Find a single listener by its object
  873. * @param {Object} object
  874. * @return {Number} index -1 when not found
  875. */
  876. 'indexOf': function (object) {
  877. var listeners = this.listeners;
  878. for (var i = 0, iMax = this.listeners.length; i < iMax; i++) {
  879. var listener = listeners[i];
  880. if (listener && listener.object == object) {
  881. return i;
  882. }
  883. }
  884. return -1;
  885. },
  886. /**
  887. * Add an event listener
  888. * @param {Object} object
  889. * @param {String} event The name of an event, for example 'select'
  890. * @param {function} callback The callback method, called when the
  891. * event takes place
  892. */
  893. 'addListener': function (object, event, callback) {
  894. var index = this.indexOf(object);
  895. var listener = this.listeners[index];
  896. if (!listener) {
  897. listener = {
  898. 'object': object,
  899. 'events': {}
  900. };
  901. this.listeners.push(listener);
  902. }
  903. var callbacks = listener.events[event];
  904. if (!callbacks) {
  905. callbacks = [];
  906. listener.events[event] = callbacks;
  907. }
  908. // add the callback if it does not yet exist
  909. if (callbacks.indexOf(callback) == -1) {
  910. callbacks.push(callback);
  911. }
  912. },
  913. /**
  914. * Remove an event listener
  915. * @param {Object} object
  916. * @param {String} event The name of an event, for example 'select'
  917. * @param {function} callback The registered callback method
  918. */
  919. 'removeListener': function (object, event, callback) {
  920. var index = this.indexOf(object);
  921. var listener = this.listeners[index];
  922. if (listener) {
  923. var callbacks = listener.events[event];
  924. if (callbacks) {
  925. index = callbacks.indexOf(callback);
  926. if (index != -1) {
  927. callbacks.splice(index, 1);
  928. }
  929. // remove the array when empty
  930. if (callbacks.length == 0) {
  931. delete listener.events[event];
  932. }
  933. }
  934. // count the number of registered events. remove listener when empty
  935. var count = 0;
  936. var events = listener.events;
  937. for (var e in events) {
  938. if (events.hasOwnProperty(e)) {
  939. count++;
  940. }
  941. }
  942. if (count == 0) {
  943. delete this.listeners[index];
  944. }
  945. }
  946. },
  947. /**
  948. * Remove all registered event listeners
  949. */
  950. 'removeAllListeners': function () {
  951. this.listeners = [];
  952. },
  953. /**
  954. * Trigger an event. All registered event handlers will be called
  955. * @param {Object} object
  956. * @param {String} event
  957. * @param {Object} properties (optional)
  958. */
  959. 'trigger': function (object, event, properties) {
  960. var index = this.indexOf(object);
  961. var listener = this.listeners[index];
  962. if (listener) {
  963. var callbacks = listener.events[event];
  964. if (callbacks) {
  965. for (var i = 0, iMax = callbacks.length; i < iMax; i++) {
  966. callbacks[i](properties);
  967. }
  968. }
  969. }
  970. }
  971. };
  972. /**
  973. * An event bus can be used to emit events, and to subscribe to events
  974. * @constructor EventBus
  975. */
  976. function EventBus() {
  977. this.subscriptions = [];
  978. }
  979. /**
  980. * Subscribe to an event
  981. * @param {String | RegExp} event The event can be a regular expression, or
  982. * a string with wildcards, like 'server.*'.
  983. * @param {function} callback. Callback are called with three parameters:
  984. * {String} event, {*} [data], {*} [source]
  985. * @param {*} [target]
  986. * @returns {String} id A subscription id
  987. */
  988. EventBus.prototype.on = function (event, callback, target) {
  989. var regexp = (event instanceof RegExp) ?
  990. event :
  991. new RegExp(event.replace('*', '\\w+'));
  992. var subscription = {
  993. id: util.randomUUID(),
  994. event: event,
  995. regexp: regexp,
  996. callback: (typeof callback === 'function') ? callback : null,
  997. target: target
  998. };
  999. this.subscriptions.push(subscription);
  1000. return subscription.id;
  1001. };
  1002. /**
  1003. * Unsubscribe from an event
  1004. * @param {String | Object} filter Filter for subscriptions to be removed
  1005. * Filter can be a string containing a
  1006. * subscription id, or an object containing
  1007. * one or more of the fields id, event,
  1008. * callback, and target.
  1009. */
  1010. EventBus.prototype.off = function (filter) {
  1011. var i = 0;
  1012. while (i < this.subscriptions.length) {
  1013. var subscription = this.subscriptions[i];
  1014. var match = true;
  1015. if (filter instanceof Object) {
  1016. // filter is an object. All fields must match
  1017. for (var prop in filter) {
  1018. if (filter.hasOwnProperty(prop)) {
  1019. if (filter[prop] !== subscription[prop]) {
  1020. match = false;
  1021. }
  1022. }
  1023. }
  1024. }
  1025. else {
  1026. // filter is a string, filter on id
  1027. match = (subscription.id == filter);
  1028. }
  1029. if (match) {
  1030. this.subscriptions.splice(i, 1);
  1031. }
  1032. else {
  1033. i++;
  1034. }
  1035. }
  1036. };
  1037. /**
  1038. * Emit an event
  1039. * @param {String} event
  1040. * @param {*} [data]
  1041. * @param {*} [source]
  1042. */
  1043. EventBus.prototype.emit = function (event, data, source) {
  1044. for (var i =0; i < this.subscriptions.length; i++) {
  1045. var subscription = this.subscriptions[i];
  1046. if (subscription.regexp.test(event)) {
  1047. if (subscription.callback) {
  1048. subscription.callback(event, data, source);
  1049. }
  1050. }
  1051. }
  1052. };
  1053. /**
  1054. * DataSet
  1055. *
  1056. * Usage:
  1057. * var dataSet = new DataSet({
  1058. * fieldId: '_id',
  1059. * convert: {
  1060. * // ...
  1061. * }
  1062. * });
  1063. *
  1064. * dataSet.add(item);
  1065. * dataSet.add(data);
  1066. * dataSet.update(item);
  1067. * dataSet.update(data);
  1068. * dataSet.remove(id);
  1069. * dataSet.remove(ids);
  1070. * var data = dataSet.get();
  1071. * var data = dataSet.get(id);
  1072. * var data = dataSet.get(ids);
  1073. * var data = dataSet.get(ids, options, data);
  1074. * dataSet.clear();
  1075. *
  1076. * A data set can:
  1077. * - add/remove/update data
  1078. * - gives triggers upon changes in the data
  1079. * - can import/export data in various data formats
  1080. *
  1081. * @param {Object} [options] Available options:
  1082. * {String} fieldId Field name of the id in the
  1083. * items, 'id' by default.
  1084. * {Object.<String, String} convert
  1085. * A map with field names as key,
  1086. * and the field type as value.
  1087. * @constructor DataSet
  1088. */
  1089. // TODO: add a DataSet constructor DataSet(data, options)
  1090. function DataSet (options) {
  1091. this.id = util.randomUUID();
  1092. this.options = options || {};
  1093. this.data = {}; // map with data indexed by id
  1094. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1095. this.convert = {}; // field types by field name
  1096. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1097. if (this.options.convert) {
  1098. for (var field in this.options.convert) {
  1099. if (this.options.convert.hasOwnProperty(field)) {
  1100. var value = this.options.convert[field];
  1101. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1102. this.convert[field] = 'Date';
  1103. }
  1104. else {
  1105. this.convert[field] = value;
  1106. }
  1107. }
  1108. }
  1109. }
  1110. // event subscribers
  1111. this.subscribers = {};
  1112. this.internalIds = {}; // internally generated id's
  1113. }
  1114. /**
  1115. * Subscribe to an event, add an event listener
  1116. * @param {String} event Event name. Available events: 'put', 'update',
  1117. * 'remove'
  1118. * @param {function} callback Callback method. Called with three parameters:
  1119. * {String} event
  1120. * {Object | null} params
  1121. * {String | Number} senderId
  1122. */
  1123. DataSet.prototype.subscribe = function (event, callback) {
  1124. var subscribers = this.subscribers[event];
  1125. if (!subscribers) {
  1126. subscribers = [];
  1127. this.subscribers[event] = subscribers;
  1128. }
  1129. subscribers.push({
  1130. callback: callback
  1131. });
  1132. };
  1133. /**
  1134. * Unsubscribe from an event, remove an event listener
  1135. * @param {String} event
  1136. * @param {function} callback
  1137. */
  1138. DataSet.prototype.unsubscribe = function (event, callback) {
  1139. var subscribers = this.subscribers[event];
  1140. if (subscribers) {
  1141. this.subscribers[event] = subscribers.filter(function (listener) {
  1142. return (listener.callback != callback);
  1143. });
  1144. }
  1145. };
  1146. /**
  1147. * Trigger an event
  1148. * @param {String} event
  1149. * @param {Object | null} params
  1150. * @param {String} [senderId] Optional id of the sender.
  1151. * @private
  1152. */
  1153. DataSet.prototype._trigger = function (event, params, senderId) {
  1154. if (event == '*') {
  1155. throw new Error('Cannot trigger event *');
  1156. }
  1157. var subscribers = [];
  1158. if (event in this.subscribers) {
  1159. subscribers = subscribers.concat(this.subscribers[event]);
  1160. }
  1161. if ('*' in this.subscribers) {
  1162. subscribers = subscribers.concat(this.subscribers['*']);
  1163. }
  1164. for (var i = 0; i < subscribers.length; i++) {
  1165. var subscriber = subscribers[i];
  1166. if (subscriber.callback) {
  1167. subscriber.callback(event, params, senderId || null);
  1168. }
  1169. }
  1170. };
  1171. /**
  1172. * Add data.
  1173. * Adding an item will fail when there already is an item with the same id.
  1174. * @param {Object | Array | DataTable} data
  1175. * @param {String} [senderId] Optional sender id
  1176. * @return {Array} addedIds Array with the ids of the added items
  1177. */
  1178. DataSet.prototype.add = function (data, senderId) {
  1179. var addedIds = [],
  1180. id,
  1181. me = this;
  1182. if (data instanceof Array) {
  1183. // Array
  1184. for (var i = 0, len = data.length; i < len; i++) {
  1185. id = me._addItem(data[i]);
  1186. addedIds.push(id);
  1187. }
  1188. }
  1189. else if (util.isDataTable(data)) {
  1190. // Google DataTable
  1191. var columns = this._getColumnNames(data);
  1192. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1193. var item = {};
  1194. for (var col = 0, cols = columns.length; col < cols; col++) {
  1195. var field = columns[col];
  1196. item[field] = data.getValue(row, col);
  1197. }
  1198. id = me._addItem(item);
  1199. addedIds.push(id);
  1200. }
  1201. }
  1202. else if (data instanceof Object) {
  1203. // Single item
  1204. id = me._addItem(data);
  1205. addedIds.push(id);
  1206. }
  1207. else {
  1208. throw new Error('Unknown dataType');
  1209. }
  1210. if (addedIds.length) {
  1211. this._trigger('add', {items: addedIds}, senderId);
  1212. }
  1213. return addedIds;
  1214. };
  1215. /**
  1216. * Update existing items. When an item does not exist, it will be created
  1217. * @param {Object | Array | DataTable} data
  1218. * @param {String} [senderId] Optional sender id
  1219. * @return {Array} updatedIds The ids of the added or updated items
  1220. */
  1221. DataSet.prototype.update = function (data, senderId) {
  1222. var addedIds = [],
  1223. updatedIds = [],
  1224. me = this,
  1225. fieldId = me.fieldId;
  1226. var addOrUpdate = function (item) {
  1227. var id = item[fieldId];
  1228. if (me.data[id]) {
  1229. // update item
  1230. id = me._updateItem(item);
  1231. updatedIds.push(id);
  1232. }
  1233. else {
  1234. // add new item
  1235. id = me._addItem(item);
  1236. addedIds.push(id);
  1237. }
  1238. };
  1239. if (data instanceof Array) {
  1240. // Array
  1241. for (var i = 0, len = data.length; i < len; i++) {
  1242. addOrUpdate(data[i]);
  1243. }
  1244. }
  1245. else if (util.isDataTable(data)) {
  1246. // Google DataTable
  1247. var columns = this._getColumnNames(data);
  1248. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1249. var item = {};
  1250. for (var col = 0, cols = columns.length; col < cols; col++) {
  1251. var field = columns[col];
  1252. item[field] = data.getValue(row, col);
  1253. }
  1254. addOrUpdate(item);
  1255. }
  1256. }
  1257. else if (data instanceof Object) {
  1258. // Single item
  1259. addOrUpdate(data);
  1260. }
  1261. else {
  1262. throw new Error('Unknown dataType');
  1263. }
  1264. if (addedIds.length) {
  1265. this._trigger('add', {items: addedIds}, senderId);
  1266. }
  1267. if (updatedIds.length) {
  1268. this._trigger('update', {items: updatedIds}, senderId);
  1269. }
  1270. return addedIds.concat(updatedIds);
  1271. };
  1272. /**
  1273. * Get a data item or multiple items.
  1274. *
  1275. * Usage:
  1276. *
  1277. * get()
  1278. * get(options: Object)
  1279. * get(options: Object, data: Array | DataTable)
  1280. *
  1281. * get(id: Number | String)
  1282. * get(id: Number | String, options: Object)
  1283. * get(id: Number | String, options: Object, data: Array | DataTable)
  1284. *
  1285. * get(ids: Number[] | String[])
  1286. * get(ids: Number[] | String[], options: Object)
  1287. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1288. *
  1289. * Where:
  1290. *
  1291. * {Number | String} id The id of an item
  1292. * {Number[] | String{}} ids An array with ids of items
  1293. * {Object} options An Object with options. Available options:
  1294. * {String} [type] Type of data to be returned. Can
  1295. * be 'DataTable' or 'Array' (default)
  1296. * {Object.<String, String>} [convert]
  1297. * {String[]} [fields] field names to be returned
  1298. * {function} [filter] filter items
  1299. * {String | function} [order] Order the items by
  1300. * a field name or custom sort function.
  1301. * {Array | DataTable} [data] If provided, items will be appended to this
  1302. * array or table. Required in case of Google
  1303. * DataTable.
  1304. *
  1305. * @throws Error
  1306. */
  1307. DataSet.prototype.get = function (args) {
  1308. var me = this;
  1309. var globalShowInternalIds = this.showInternalIds;
  1310. // parse the arguments
  1311. var id, ids, options, data;
  1312. var firstType = util.getType(arguments[0]);
  1313. if (firstType == 'String' || firstType == 'Number') {
  1314. // get(id [, options] [, data])
  1315. id = arguments[0];
  1316. options = arguments[1];
  1317. data = arguments[2];
  1318. }
  1319. else if (firstType == 'Array') {
  1320. // get(ids [, options] [, data])
  1321. ids = arguments[0];
  1322. options = arguments[1];
  1323. data = arguments[2];
  1324. }
  1325. else {
  1326. // get([, options] [, data])
  1327. options = arguments[0];
  1328. data = arguments[1];
  1329. }
  1330. // determine the return type
  1331. var type;
  1332. if (options && options.type) {
  1333. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1334. if (data && (type != util.getType(data))) {
  1335. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1336. 'does not correspond with specified options.type (' + options.type + ')');
  1337. }
  1338. if (type == 'DataTable' && !util.isDataTable(data)) {
  1339. throw new Error('Parameter "data" must be a DataTable ' +
  1340. 'when options.type is "DataTable"');
  1341. }
  1342. }
  1343. else if (data) {
  1344. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1345. }
  1346. else {
  1347. type = 'Array';
  1348. }
  1349. // we allow the setting of this value for a single get request.
  1350. if (options != undefined) {
  1351. if (options.showInternalIds != undefined) {
  1352. this.showInternalIds = options.showInternalIds;
  1353. }
  1354. }
  1355. // build options
  1356. var convert = options && options.convert || this.options.convert;
  1357. var filter = options && options.filter;
  1358. var items = [], item, itemId, i, len;
  1359. // convert items
  1360. if (id != undefined) {
  1361. // return a single item
  1362. item = me._getItem(id, convert);
  1363. if (filter && !filter(item)) {
  1364. item = null;
  1365. }
  1366. }
  1367. else if (ids != undefined) {
  1368. // return a subset of items
  1369. for (i = 0, len = ids.length; i < len; i++) {
  1370. item = me._getItem(ids[i], convert);
  1371. if (!filter || filter(item)) {
  1372. items.push(item);
  1373. }
  1374. }
  1375. }
  1376. else {
  1377. // return all items
  1378. for (itemId in this.data) {
  1379. if (this.data.hasOwnProperty(itemId)) {
  1380. item = me._getItem(itemId, convert);
  1381. if (!filter || filter(item)) {
  1382. items.push(item);
  1383. }
  1384. }
  1385. }
  1386. }
  1387. // restore the global value of showInternalIds
  1388. this.showInternalIds = globalShowInternalIds;
  1389. // order the results
  1390. if (options && options.order && id == undefined) {
  1391. this._sort(items, options.order);
  1392. }
  1393. // filter fields of the items
  1394. if (options && options.fields) {
  1395. var fields = options.fields;
  1396. if (id != undefined) {
  1397. item = this._filterFields(item, fields);
  1398. }
  1399. else {
  1400. for (i = 0, len = items.length; i < len; i++) {
  1401. items[i] = this._filterFields(items[i], fields);
  1402. }
  1403. }
  1404. }
  1405. // return the results
  1406. if (type == 'DataTable') {
  1407. var columns = this._getColumnNames(data);
  1408. if (id != undefined) {
  1409. // append a single item to the data table
  1410. me._appendRow(data, columns, item);
  1411. }
  1412. else {
  1413. // copy the items to the provided data table
  1414. for (i = 0, len = items.length; i < len; i++) {
  1415. me._appendRow(data, columns, items[i]);
  1416. }
  1417. }
  1418. return data;
  1419. }
  1420. else {
  1421. // return an array
  1422. if (id != undefined) {
  1423. // a single item
  1424. return item;
  1425. }
  1426. else {
  1427. // multiple items
  1428. if (data) {
  1429. // copy the items to the provided array
  1430. for (i = 0, len = items.length; i < len; i++) {
  1431. data.push(items[i]);
  1432. }
  1433. return data;
  1434. }
  1435. else {
  1436. // just return our array
  1437. return items;
  1438. }
  1439. }
  1440. }
  1441. };
  1442. /**
  1443. * Get ids of all items or from a filtered set of items.
  1444. * @param {Object} [options] An Object with options. Available options:
  1445. * {function} [filter] filter items
  1446. * {String | function} [order] Order the items by
  1447. * a field name or custom sort function.
  1448. * @return {Array} ids
  1449. */
  1450. DataSet.prototype.getIds = function (options) {
  1451. var data = this.data,
  1452. filter = options && options.filter,
  1453. order = options && options.order,
  1454. convert = options && options.convert || this.options.convert,
  1455. i,
  1456. len,
  1457. id,
  1458. item,
  1459. items,
  1460. ids = [];
  1461. if (filter) {
  1462. // get filtered items
  1463. if (order) {
  1464. // create ordered list
  1465. items = [];
  1466. for (id in data) {
  1467. if (data.hasOwnProperty(id)) {
  1468. item = this._getItem(id, convert);
  1469. if (filter(item)) {
  1470. items.push(item);
  1471. }
  1472. }
  1473. }
  1474. this._sort(items, order);
  1475. for (i = 0, len = items.length; i < len; i++) {
  1476. ids[i] = items[i][this.fieldId];
  1477. }
  1478. }
  1479. else {
  1480. // create unordered list
  1481. for (id in data) {
  1482. if (data.hasOwnProperty(id)) {
  1483. item = this._getItem(id, convert);
  1484. if (filter(item)) {
  1485. ids.push(item[this.fieldId]);
  1486. }
  1487. }
  1488. }
  1489. }
  1490. }
  1491. else {
  1492. // get all items
  1493. if (order) {
  1494. // create an ordered list
  1495. items = [];
  1496. for (id in data) {
  1497. if (data.hasOwnProperty(id)) {
  1498. items.push(data[id]);
  1499. }
  1500. }
  1501. this._sort(items, order);
  1502. for (i = 0, len = items.length; i < len; i++) {
  1503. ids[i] = items[i][this.fieldId];
  1504. }
  1505. }
  1506. else {
  1507. // create unordered list
  1508. for (id in data) {
  1509. if (data.hasOwnProperty(id)) {
  1510. item = data[id];
  1511. ids.push(item[this.fieldId]);
  1512. }
  1513. }
  1514. }
  1515. }
  1516. return ids;
  1517. };
  1518. /**
  1519. * Execute a callback function for every item in the dataset.
  1520. * The order of the items is not determined.
  1521. * @param {function} callback
  1522. * @param {Object} [options] Available options:
  1523. * {Object.<String, String>} [convert]
  1524. * {String[]} [fields] filter fields
  1525. * {function} [filter] filter items
  1526. * {String | function} [order] Order the items by
  1527. * a field name or custom sort function.
  1528. */
  1529. DataSet.prototype.forEach = function (callback, options) {
  1530. var filter = options && options.filter,
  1531. convert = options && options.convert || this.options.convert,
  1532. data = this.data,
  1533. item,
  1534. id;
  1535. if (options && options.order) {
  1536. // execute forEach on ordered list
  1537. var items = this.get(options);
  1538. for (var i = 0, len = items.length; i < len; i++) {
  1539. item = items[i];
  1540. id = item[this.fieldId];
  1541. callback(item, id);
  1542. }
  1543. }
  1544. else {
  1545. // unordered
  1546. for (id in data) {
  1547. if (data.hasOwnProperty(id)) {
  1548. item = this._getItem(id, convert);
  1549. if (!filter || filter(item)) {
  1550. callback(item, id);
  1551. }
  1552. }
  1553. }
  1554. }
  1555. };
  1556. /**
  1557. * Map every item in the dataset.
  1558. * @param {function} callback
  1559. * @param {Object} [options] Available options:
  1560. * {Object.<String, String>} [convert]
  1561. * {String[]} [fields] filter fields
  1562. * {function} [filter] filter items
  1563. * {String | function} [order] Order the items by
  1564. * a field name or custom sort function.
  1565. * @return {Object[]} mappedItems
  1566. */
  1567. DataSet.prototype.map = function (callback, options) {
  1568. var filter = options && options.filter,
  1569. convert = options && options.convert || this.options.convert,
  1570. mappedItems = [],
  1571. data = this.data,
  1572. item;
  1573. // convert and filter items
  1574. for (var id in data) {
  1575. if (data.hasOwnProperty(id)) {
  1576. item = this._getItem(id, convert);
  1577. if (!filter || filter(item)) {
  1578. mappedItems.push(callback(item, id));
  1579. }
  1580. }
  1581. }
  1582. // order items
  1583. if (options && options.order) {
  1584. this._sort(mappedItems, options.order);
  1585. }
  1586. return mappedItems;
  1587. };
  1588. /**
  1589. * Filter the fields of an item
  1590. * @param {Object} item
  1591. * @param {String[]} fields Field names
  1592. * @return {Object} filteredItem
  1593. * @private
  1594. */
  1595. DataSet.prototype._filterFields = function (item, fields) {
  1596. var filteredItem = {};
  1597. for (var field in item) {
  1598. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1599. filteredItem[field] = item[field];
  1600. }
  1601. }
  1602. return filteredItem;
  1603. };
  1604. /**
  1605. * Sort the provided array with items
  1606. * @param {Object[]} items
  1607. * @param {String | function} order A field name or custom sort function.
  1608. * @private
  1609. */
  1610. DataSet.prototype._sort = function (items, order) {
  1611. if (util.isString(order)) {
  1612. // order by provided field name
  1613. var name = order; // field name
  1614. items.sort(function (a, b) {
  1615. var av = a[name];
  1616. var bv = b[name];
  1617. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1618. });
  1619. }
  1620. else if (typeof order === 'function') {
  1621. // order by sort function
  1622. items.sort(order);
  1623. }
  1624. // TODO: extend order by an Object {field:String, direction:String}
  1625. // where direction can be 'asc' or 'desc'
  1626. else {
  1627. throw new TypeError('Order must be a function or a string');
  1628. }
  1629. };
  1630. /**
  1631. * Remove an object by pointer or by id
  1632. * @param {String | Number | Object | Array} id Object or id, or an array with
  1633. * objects or ids to be removed
  1634. * @param {String} [senderId] Optional sender id
  1635. * @return {Array} removedIds
  1636. */
  1637. DataSet.prototype.remove = function (id, senderId) {
  1638. var removedIds = [],
  1639. i, len, removedId;
  1640. if (id instanceof Array) {
  1641. for (i = 0, len = id.length; i < len; i++) {
  1642. removedId = this._remove(id[i]);
  1643. if (removedId != null) {
  1644. removedIds.push(removedId);
  1645. }
  1646. }
  1647. }
  1648. else {
  1649. removedId = this._remove(id);
  1650. if (removedId != null) {
  1651. removedIds.push(removedId);
  1652. }
  1653. }
  1654. if (removedIds.length) {
  1655. this._trigger('remove', {items: removedIds}, senderId);
  1656. }
  1657. return removedIds;
  1658. };
  1659. /**
  1660. * Remove an item by its id
  1661. * @param {Number | String | Object} id id or item
  1662. * @returns {Number | String | null} id
  1663. * @private
  1664. */
  1665. DataSet.prototype._remove = function (id) {
  1666. if (util.isNumber(id) || util.isString(id)) {
  1667. if (this.data[id]) {
  1668. delete this.data[id];
  1669. delete this.internalIds[id];
  1670. return id;
  1671. }
  1672. }
  1673. else if (id instanceof Object) {
  1674. var itemId = id[this.fieldId];
  1675. if (itemId && this.data[itemId]) {
  1676. delete this.data[itemId];
  1677. delete this.internalIds[itemId];
  1678. return itemId;
  1679. }
  1680. }
  1681. return null;
  1682. };
  1683. /**
  1684. * Clear the data
  1685. * @param {String} [senderId] Optional sender id
  1686. * @return {Array} removedIds The ids of all removed items
  1687. */
  1688. DataSet.prototype.clear = function (senderId) {
  1689. var ids = Object.keys(this.data);
  1690. this.data = {};
  1691. this.internalIds = {};
  1692. this._trigger('remove', {items: ids}, senderId);
  1693. return ids;
  1694. };
  1695. /**
  1696. * Find the item with maximum value of a specified field
  1697. * @param {String} field
  1698. * @return {Object | null} item Item containing max value, or null if no items
  1699. */
  1700. DataSet.prototype.max = function (field) {
  1701. var data = this.data,
  1702. max = null,
  1703. maxField = null;
  1704. for (var id in data) {
  1705. if (data.hasOwnProperty(id)) {
  1706. var item = data[id];
  1707. var itemField = item[field];
  1708. if (itemField != null && (!max || itemField > maxField)) {
  1709. max = item;
  1710. maxField = itemField;
  1711. }
  1712. }
  1713. }
  1714. return max;
  1715. };
  1716. /**
  1717. * Find the item with minimum value of a specified field
  1718. * @param {String} field
  1719. * @return {Object | null} item Item containing max value, or null if no items
  1720. */
  1721. DataSet.prototype.min = function (field) {
  1722. var data = this.data,
  1723. min = null,
  1724. minField = null;
  1725. for (var id in data) {
  1726. if (data.hasOwnProperty(id)) {
  1727. var item = data[id];
  1728. var itemField = item[field];
  1729. if (itemField != null && (!min || itemField < minField)) {
  1730. min = item;
  1731. minField = itemField;
  1732. }
  1733. }
  1734. }
  1735. return min;
  1736. };
  1737. /**
  1738. * Find all distinct values of a specified field
  1739. * @param {String} field
  1740. * @return {Array} values Array containing all distinct values. If the data
  1741. * items do not contain the specified field, an array
  1742. * containing a single value undefined is returned.
  1743. * The returned array is unordered.
  1744. */
  1745. DataSet.prototype.distinct = function (field) {
  1746. var data = this.data,
  1747. values = [],
  1748. fieldType = this.options.convert[field],
  1749. count = 0;
  1750. for (var prop in data) {
  1751. if (data.hasOwnProperty(prop)) {
  1752. var item = data[prop];
  1753. var value = util.convert(item[field], fieldType);
  1754. var exists = false;
  1755. for (var i = 0; i < count; i++) {
  1756. if (values[i] == value) {
  1757. exists = true;
  1758. break;
  1759. }
  1760. }
  1761. if (!exists) {
  1762. values[count] = value;
  1763. count++;
  1764. }
  1765. }
  1766. }
  1767. return values;
  1768. };
  1769. /**
  1770. * Add a single item. Will fail when an item with the same id already exists.
  1771. * @param {Object} item
  1772. * @return {String} id
  1773. * @private
  1774. */
  1775. DataSet.prototype._addItem = function (item) {
  1776. var id = item[this.fieldId];
  1777. if (id != undefined) {
  1778. // check whether this id is already taken
  1779. if (this.data[id]) {
  1780. // item already exists
  1781. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1782. }
  1783. }
  1784. else {
  1785. // generate an id
  1786. id = util.randomUUID();
  1787. item[this.fieldId] = id;
  1788. this.internalIds[id] = item;
  1789. }
  1790. var d = {};
  1791. for (var field in item) {
  1792. if (item.hasOwnProperty(field)) {
  1793. var fieldType = this.convert[field]; // type may be undefined
  1794. d[field] = util.convert(item[field], fieldType);
  1795. }
  1796. }
  1797. this.data[id] = d;
  1798. return id;
  1799. };
  1800. /**
  1801. * Get an item. Fields can be converted to a specific type
  1802. * @param {String} id
  1803. * @param {Object.<String, String>} [convert] field types to convert
  1804. * @return {Object | null} item
  1805. * @private
  1806. */
  1807. DataSet.prototype._getItem = function (id, convert) {
  1808. var field, value;
  1809. // get the item from the dataset
  1810. var raw = this.data[id];
  1811. if (!raw) {
  1812. return null;
  1813. }
  1814. // convert the items field types
  1815. var converted = {},
  1816. fieldId = this.fieldId,
  1817. internalIds = this.internalIds;
  1818. if (convert) {
  1819. for (field in raw) {
  1820. if (raw.hasOwnProperty(field)) {
  1821. value = raw[field];
  1822. // output all fields, except internal ids
  1823. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1824. converted[field] = util.convert(value, convert[field]);
  1825. }
  1826. }
  1827. }
  1828. }
  1829. else {
  1830. // no field types specified, no converting needed
  1831. for (field in raw) {
  1832. if (raw.hasOwnProperty(field)) {
  1833. value = raw[field];
  1834. // output all fields, except internal ids
  1835. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1836. converted[field] = value;
  1837. }
  1838. }
  1839. }
  1840. }
  1841. return converted;
  1842. };
  1843. /**
  1844. * Update a single item: merge with existing item.
  1845. * Will fail when the item has no id, or when there does not exist an item
  1846. * with the same id.
  1847. * @param {Object} item
  1848. * @return {String} id
  1849. * @private
  1850. */
  1851. DataSet.prototype._updateItem = function (item) {
  1852. var id = item[this.fieldId];
  1853. if (id == undefined) {
  1854. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1855. }
  1856. var d = this.data[id];
  1857. if (!d) {
  1858. // item doesn't exist
  1859. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1860. }
  1861. // merge with current item
  1862. for (var field in item) {
  1863. if (item.hasOwnProperty(field)) {
  1864. var fieldType = this.convert[field]; // type may be undefined
  1865. d[field] = util.convert(item[field], fieldType);
  1866. }
  1867. }
  1868. return id;
  1869. };
  1870. /**
  1871. * check if an id is an internal or external id
  1872. * @param id
  1873. * @returns {boolean}
  1874. * @private
  1875. */
  1876. DataSet.prototype.isInternalId = function(id) {
  1877. return (id in this.internalIds);
  1878. };
  1879. /**
  1880. * Get an array with the column names of a Google DataTable
  1881. * @param {DataTable} dataTable
  1882. * @return {String[]} columnNames
  1883. * @private
  1884. */
  1885. DataSet.prototype._getColumnNames = function (dataTable) {
  1886. var columns = [];
  1887. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1888. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1889. }
  1890. return columns;
  1891. };
  1892. /**
  1893. * Append an item as a row to the dataTable
  1894. * @param dataTable
  1895. * @param columns
  1896. * @param item
  1897. * @private
  1898. */
  1899. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1900. var row = dataTable.addRow();
  1901. for (var col = 0, cols = columns.length; col < cols; col++) {
  1902. var field = columns[col];
  1903. dataTable.setValue(row, col, item[field]);
  1904. }
  1905. };
  1906. /**
  1907. * DataView
  1908. *
  1909. * a dataview offers a filtered view on a dataset or an other dataview.
  1910. *
  1911. * @param {DataSet | DataView} data
  1912. * @param {Object} [options] Available options: see method get
  1913. *
  1914. * @constructor DataView
  1915. */
  1916. function DataView (data, options) {
  1917. this.id = util.randomUUID();
  1918. this.data = null;
  1919. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1920. this.options = options || {};
  1921. this.fieldId = 'id'; // name of the field containing id
  1922. this.subscribers = {}; // event subscribers
  1923. var me = this;
  1924. this.listener = function () {
  1925. me._onEvent.apply(me, arguments);
  1926. };
  1927. this.setData(data);
  1928. }
  1929. // TODO: implement a function .config() to dynamically update things like configured filter
  1930. // and trigger changes accordingly
  1931. /**
  1932. * Set a data source for the view
  1933. * @param {DataSet | DataView} data
  1934. */
  1935. DataView.prototype.setData = function (data) {
  1936. var ids, dataItems, i, len;
  1937. if (this.data) {
  1938. // unsubscribe from current dataset
  1939. if (this.data.unsubscribe) {
  1940. this.data.unsubscribe('*', this.listener);
  1941. }
  1942. // trigger a remove of all items in memory
  1943. ids = [];
  1944. for (var id in this.ids) {
  1945. if (this.ids.hasOwnProperty(id)) {
  1946. ids.push(id);
  1947. }
  1948. }
  1949. this.ids = {};
  1950. this._trigger('remove', {items: ids});
  1951. }
  1952. this.data = data;
  1953. if (this.data) {
  1954. // update fieldId
  1955. this.fieldId = this.options.fieldId ||
  1956. (this.data && this.data.options && this.data.options.fieldId) ||
  1957. 'id';
  1958. // trigger an add of all added items
  1959. ids = this.data.getIds({filter: this.options && this.options.filter});
  1960. for (i = 0, len = ids.length; i < len; i++) {
  1961. id = ids[i];
  1962. this.ids[id] = true;
  1963. }
  1964. this._trigger('add', {items: ids});
  1965. // subscribe to new dataset
  1966. if (this.data.subscribe) {
  1967. this.data.subscribe('*', this.listener);
  1968. }
  1969. }
  1970. };
  1971. /**
  1972. * Get data from the data view
  1973. *
  1974. * Usage:
  1975. *
  1976. * get()
  1977. * get(options: Object)
  1978. * get(options: Object, data: Array | DataTable)
  1979. *
  1980. * get(id: Number)
  1981. * get(id: Number, options: Object)
  1982. * get(id: Number, options: Object, data: Array | DataTable)
  1983. *
  1984. * get(ids: Number[])
  1985. * get(ids: Number[], options: Object)
  1986. * get(ids: Number[], options: Object, data: Array | DataTable)
  1987. *
  1988. * Where:
  1989. *
  1990. * {Number | String} id The id of an item
  1991. * {Number[] | String{}} ids An array with ids of items
  1992. * {Object} options An Object with options. Available options:
  1993. * {String} [type] Type of data to be returned. Can
  1994. * be 'DataTable' or 'Array' (default)
  1995. * {Object.<String, String>} [convert]
  1996. * {String[]} [fields] field names to be returned
  1997. * {function} [filter] filter items
  1998. * {String | function} [order] Order the items by
  1999. * a field name or custom sort function.
  2000. * {Array | DataTable} [data] If provided, items will be appended to this
  2001. * array or table. Required in case of Google
  2002. * DataTable.
  2003. * @param args
  2004. */
  2005. DataView.prototype.get = function (args) {
  2006. var me = this;
  2007. // parse the arguments
  2008. var ids, options, data;
  2009. var firstType = util.getType(arguments[0]);
  2010. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2011. // get(id(s) [, options] [, data])
  2012. ids = arguments[0]; // can be a single id or an array with ids
  2013. options = arguments[1];
  2014. data = arguments[2];
  2015. }
  2016. else {
  2017. // get([, options] [, data])
  2018. options = arguments[0];
  2019. data = arguments[1];
  2020. }
  2021. // extend the options with the default options and provided options
  2022. var viewOptions = util.extend({}, this.options, options);
  2023. // create a combined filter method when needed
  2024. if (this.options.filter && options && options.filter) {
  2025. viewOptions.filter = function (item) {
  2026. return me.options.filter(item) && options.filter(item);
  2027. }
  2028. }
  2029. // build up the call to the linked data set
  2030. var getArguments = [];
  2031. if (ids != undefined) {
  2032. getArguments.push(ids);
  2033. }
  2034. getArguments.push(viewOptions);
  2035. getArguments.push(data);
  2036. return this.data && this.data.get.apply(this.data, getArguments);
  2037. };
  2038. /**
  2039. * Get ids of all items or from a filtered set of items.
  2040. * @param {Object} [options] An Object with options. Available options:
  2041. * {function} [filter] filter items
  2042. * {String | function} [order] Order the items by
  2043. * a field name or custom sort function.
  2044. * @return {Array} ids
  2045. */
  2046. DataView.prototype.getIds = function (options) {
  2047. var ids;
  2048. if (this.data) {
  2049. var defaultFilter = this.options.filter;
  2050. var filter;
  2051. if (options && options.filter) {
  2052. if (defaultFilter) {
  2053. filter = function (item) {
  2054. return defaultFilter(item) && options.filter(item);
  2055. }
  2056. }
  2057. else {
  2058. filter = options.filter;
  2059. }
  2060. }
  2061. else {
  2062. filter = defaultFilter;
  2063. }
  2064. ids = this.data.getIds({
  2065. filter: filter,
  2066. order: options && options.order
  2067. });
  2068. }
  2069. else {
  2070. ids = [];
  2071. }
  2072. return ids;
  2073. };
  2074. /**
  2075. * Event listener. Will propagate all events from the connected data set to
  2076. * the subscribers of the DataView, but will filter the items and only trigger
  2077. * when there are changes in the filtered data set.
  2078. * @param {String} event
  2079. * @param {Object | null} params
  2080. * @param {String} senderId
  2081. * @private
  2082. */
  2083. DataView.prototype._onEvent = function (event, params, senderId) {
  2084. var i, len, id, item,
  2085. ids = params && params.items,
  2086. data = this.data,
  2087. added = [],
  2088. updated = [],
  2089. removed = [];
  2090. if (ids && data) {
  2091. switch (event) {
  2092. case 'add':
  2093. // filter the ids of the added items
  2094. for (i = 0, len = ids.length; i < len; i++) {
  2095. id = ids[i];
  2096. item = this.get(id);
  2097. if (item) {
  2098. this.ids[id] = true;
  2099. added.push(id);
  2100. }
  2101. }
  2102. break;
  2103. case 'update':
  2104. // determine the event from the views viewpoint: an updated
  2105. // item can be added, updated, or removed from this view.
  2106. for (i = 0, len = ids.length; i < len; i++) {
  2107. id = ids[i];
  2108. item = this.get(id);
  2109. if (item) {
  2110. if (this.ids[id]) {
  2111. updated.push(id);
  2112. }
  2113. else {
  2114. this.ids[id] = true;
  2115. added.push(id);
  2116. }
  2117. }
  2118. else {
  2119. if (this.ids[id]) {
  2120. delete this.ids[id];
  2121. removed.push(id);
  2122. }
  2123. else {
  2124. // nothing interesting for me :-(
  2125. }
  2126. }
  2127. }
  2128. break;
  2129. case 'remove':
  2130. // filter the ids of the removed items
  2131. for (i = 0, len = ids.length; i < len; i++) {
  2132. id = ids[i];
  2133. if (this.ids[id]) {
  2134. delete this.ids[id];
  2135. removed.push(id);
  2136. }
  2137. }
  2138. break;
  2139. }
  2140. if (added.length) {
  2141. this._trigger('add', {items: added}, senderId);
  2142. }
  2143. if (updated.length) {
  2144. this._trigger('update', {items: updated}, senderId);
  2145. }
  2146. if (removed.length) {
  2147. this._trigger('remove', {items: removed}, senderId);
  2148. }
  2149. }
  2150. };
  2151. // copy subscription functionality from DataSet
  2152. DataView.prototype.subscribe = DataSet.prototype.subscribe;
  2153. DataView.prototype.unsubscribe = DataSet.prototype.unsubscribe;
  2154. DataView.prototype._trigger = DataSet.prototype._trigger;
  2155. /**
  2156. * @constructor TimeStep
  2157. * The class TimeStep is an iterator for dates. You provide a start date and an
  2158. * end date. The class itself determines the best scale (step size) based on the
  2159. * provided start Date, end Date, and minimumStep.
  2160. *
  2161. * If minimumStep is provided, the step size is chosen as close as possible
  2162. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2163. * provided, the scale is set to 1 DAY.
  2164. * The minimumStep should correspond with the onscreen size of about 6 characters
  2165. *
  2166. * Alternatively, you can set a scale by hand.
  2167. * After creation, you can initialize the class by executing first(). Then you
  2168. * can iterate from the start date to the end date via next(). You can check if
  2169. * the end date is reached with the function hasNext(). After each step, you can
  2170. * retrieve the current date via getCurrent().
  2171. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2172. * days, to years.
  2173. *
  2174. * Version: 1.2
  2175. *
  2176. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2177. * or new Date(2010, 9, 21, 23, 45, 00)
  2178. * @param {Date} [end] The end date
  2179. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2180. */
  2181. TimeStep = function(start, end, minimumStep) {
  2182. // variables
  2183. this.current = new Date();
  2184. this._start = new Date();
  2185. this._end = new Date();
  2186. this.autoScale = true;
  2187. this.scale = TimeStep.SCALE.DAY;
  2188. this.step = 1;
  2189. // initialize the range
  2190. this.setRange(start, end, minimumStep);
  2191. };
  2192. /// enum scale
  2193. TimeStep.SCALE = {
  2194. MILLISECOND: 1,
  2195. SECOND: 2,
  2196. MINUTE: 3,
  2197. HOUR: 4,
  2198. DAY: 5,
  2199. WEEKDAY: 6,
  2200. MONTH: 7,
  2201. YEAR: 8
  2202. };
  2203. /**
  2204. * Set a new range
  2205. * If minimumStep is provided, the step size is chosen as close as possible
  2206. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2207. * provided, the scale is set to 1 DAY.
  2208. * The minimumStep should correspond with the onscreen size of about 6 characters
  2209. * @param {Date} [start] The start date and time.
  2210. * @param {Date} [end] The end date and time.
  2211. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2212. */
  2213. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2214. if (!(start instanceof Date) || !(end instanceof Date)) {
  2215. throw "No legal start or end date in method setRange";
  2216. }
  2217. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2218. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2219. if (this.autoScale) {
  2220. this.setMinimumStep(minimumStep);
  2221. }
  2222. };
  2223. /**
  2224. * Set the range iterator to the start date.
  2225. */
  2226. TimeStep.prototype.first = function() {
  2227. this.current = new Date(this._start.valueOf());
  2228. this.roundToMinor();
  2229. };
  2230. /**
  2231. * Round the current date to the first minor date value
  2232. * This must be executed once when the current date is set to start Date
  2233. */
  2234. TimeStep.prototype.roundToMinor = function() {
  2235. // round to floor
  2236. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2237. //noinspection FallthroughInSwitchStatementJS
  2238. switch (this.scale) {
  2239. case TimeStep.SCALE.YEAR:
  2240. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2241. this.current.setMonth(0);
  2242. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2243. case TimeStep.SCALE.DAY: // intentional fall through
  2244. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2245. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2246. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2247. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2248. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2249. }
  2250. if (this.step != 1) {
  2251. // round down to the first minor value that is a multiple of the current step size
  2252. switch (this.scale) {
  2253. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2254. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2255. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2256. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2257. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2258. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2259. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2260. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2261. default: break;
  2262. }
  2263. }
  2264. };
  2265. /**
  2266. * Check if the there is a next step
  2267. * @return {boolean} true if the current date has not passed the end date
  2268. */
  2269. TimeStep.prototype.hasNext = function () {
  2270. return (this.current.valueOf() <= this._end.valueOf());
  2271. };
  2272. /**
  2273. * Do the next step
  2274. */
  2275. TimeStep.prototype.next = function() {
  2276. var prev = this.current.valueOf();
  2277. // Two cases, needed to prevent issues with switching daylight savings
  2278. // (end of March and end of October)
  2279. if (this.current.getMonth() < 6) {
  2280. switch (this.scale) {
  2281. case TimeStep.SCALE.MILLISECOND:
  2282. this.current = new Date(this.current.valueOf() + this.step); break;
  2283. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2284. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2285. case TimeStep.SCALE.HOUR:
  2286. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2287. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2288. var h = this.current.getHours();
  2289. this.current.setHours(h - (h % this.step));
  2290. break;
  2291. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2292. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2293. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2294. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2295. default: break;
  2296. }
  2297. }
  2298. else {
  2299. switch (this.scale) {
  2300. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2301. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2302. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2303. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2304. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2305. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2306. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2307. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2308. default: break;
  2309. }
  2310. }
  2311. if (this.step != 1) {
  2312. // round down to the correct major value
  2313. switch (this.scale) {
  2314. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2315. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2316. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2317. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2318. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2319. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2320. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2321. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2322. default: break;
  2323. }
  2324. }
  2325. // safety mechanism: if current time is still unchanged, move to the end
  2326. if (this.current.valueOf() == prev) {
  2327. this.current = new Date(this._end.valueOf());
  2328. }
  2329. };
  2330. /**
  2331. * Get the current datetime
  2332. * @return {Date} current The current date
  2333. */
  2334. TimeStep.prototype.getCurrent = function() {
  2335. return this.current;
  2336. };
  2337. /**
  2338. * Set a custom scale. Autoscaling will be disabled.
  2339. * For example setScale(SCALE.MINUTES, 5) will result
  2340. * in minor steps of 5 minutes, and major steps of an hour.
  2341. *
  2342. * @param {TimeStep.SCALE} newScale
  2343. * A scale. Choose from SCALE.MILLISECOND,
  2344. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2345. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2346. * SCALE.YEAR.
  2347. * @param {Number} newStep A step size, by default 1. Choose for
  2348. * example 1, 2, 5, or 10.
  2349. */
  2350. TimeStep.prototype.setScale = function(newScale, newStep) {
  2351. this.scale = newScale;
  2352. if (newStep > 0) {
  2353. this.step = newStep;
  2354. }
  2355. this.autoScale = false;
  2356. };
  2357. /**
  2358. * Enable or disable autoscaling
  2359. * @param {boolean} enable If true, autoascaling is set true
  2360. */
  2361. TimeStep.prototype.setAutoScale = function (enable) {
  2362. this.autoScale = enable;
  2363. };
  2364. /**
  2365. * Automatically determine the scale that bests fits the provided minimum step
  2366. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2367. */
  2368. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2369. if (minimumStep == undefined) {
  2370. return;
  2371. }
  2372. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2373. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2374. var stepDay = (1000 * 60 * 60 * 24);
  2375. var stepHour = (1000 * 60 * 60);
  2376. var stepMinute = (1000 * 60);
  2377. var stepSecond = (1000);
  2378. var stepMillisecond= (1);
  2379. // find the smallest step that is larger than the provided minimumStep
  2380. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2381. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2382. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2383. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2384. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2385. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2386. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2387. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2388. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2389. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2390. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2391. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2392. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2393. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2394. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2395. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2396. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2397. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2398. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2399. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2400. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2401. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2402. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2403. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2404. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2405. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2406. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2407. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2408. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2409. };
  2410. /**
  2411. * Snap a date to a rounded value. The snap intervals are dependent on the
  2412. * current scale and step.
  2413. * @param {Date} date the date to be snapped
  2414. */
  2415. TimeStep.prototype.snap = function(date) {
  2416. if (this.scale == TimeStep.SCALE.YEAR) {
  2417. var year = date.getFullYear() + Math.round(date.getMonth() / 12);
  2418. date.setFullYear(Math.round(year / this.step) * this.step);
  2419. date.setMonth(0);
  2420. date.setDate(0);
  2421. date.setHours(0);
  2422. date.setMinutes(0);
  2423. date.setSeconds(0);
  2424. date.setMilliseconds(0);
  2425. }
  2426. else if (this.scale == TimeStep.SCALE.MONTH) {
  2427. if (date.getDate() > 15) {
  2428. date.setDate(1);
  2429. date.setMonth(date.getMonth() + 1);
  2430. // important: first set Date to 1, after that change the month.
  2431. }
  2432. else {
  2433. date.setDate(1);
  2434. }
  2435. date.setHours(0);
  2436. date.setMinutes(0);
  2437. date.setSeconds(0);
  2438. date.setMilliseconds(0);
  2439. }
  2440. else if (this.scale == TimeStep.SCALE.DAY ||
  2441. this.scale == TimeStep.SCALE.WEEKDAY) {
  2442. //noinspection FallthroughInSwitchStatementJS
  2443. switch (this.step) {
  2444. case 5:
  2445. case 2:
  2446. date.setHours(Math.round(date.getHours() / 24) * 24); break;
  2447. default:
  2448. date.setHours(Math.round(date.getHours() / 12) * 12); break;
  2449. }
  2450. date.setMinutes(0);
  2451. date.setSeconds(0);
  2452. date.setMilliseconds(0);
  2453. }
  2454. else if (this.scale == TimeStep.SCALE.HOUR) {
  2455. switch (this.step) {
  2456. case 4:
  2457. date.setMinutes(Math.round(date.getMinutes() / 60) * 60); break;
  2458. default:
  2459. date.setMinutes(Math.round(date.getMinutes() / 30) * 30); break;
  2460. }
  2461. date.setSeconds(0);
  2462. date.setMilliseconds(0);
  2463. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2464. //noinspection FallthroughInSwitchStatementJS
  2465. switch (this.step) {
  2466. case 15:
  2467. case 10:
  2468. date.setMinutes(Math.round(date.getMinutes() / 5) * 5);
  2469. date.setSeconds(0);
  2470. break;
  2471. case 5:
  2472. date.setSeconds(Math.round(date.getSeconds() / 60) * 60); break;
  2473. default:
  2474. date.setSeconds(Math.round(date.getSeconds() / 30) * 30); break;
  2475. }
  2476. date.setMilliseconds(0);
  2477. }
  2478. else if (this.scale == TimeStep.SCALE.SECOND) {
  2479. //noinspection FallthroughInSwitchStatementJS
  2480. switch (this.step) {
  2481. case 15:
  2482. case 10:
  2483. date.setSeconds(Math.round(date.getSeconds() / 5) * 5);
  2484. date.setMilliseconds(0);
  2485. break;
  2486. case 5:
  2487. date.setMilliseconds(Math.round(date.getMilliseconds() / 1000) * 1000); break;
  2488. default:
  2489. date.setMilliseconds(Math.round(date.getMilliseconds() / 500) * 500); break;
  2490. }
  2491. }
  2492. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2493. var step = this.step > 5 ? this.step / 2 : 1;
  2494. date.setMilliseconds(Math.round(date.getMilliseconds() / step) * step);
  2495. }
  2496. };
  2497. /**
  2498. * Check if the current value is a major value (for example when the step
  2499. * is DAY, a major value is each first day of the MONTH)
  2500. * @return {boolean} true if current date is major, else false.
  2501. */
  2502. TimeStep.prototype.isMajor = function() {
  2503. switch (this.scale) {
  2504. case TimeStep.SCALE.MILLISECOND:
  2505. return (this.current.getMilliseconds() == 0);
  2506. case TimeStep.SCALE.SECOND:
  2507. return (this.current.getSeconds() == 0);
  2508. case TimeStep.SCALE.MINUTE:
  2509. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2510. // Note: this is no bug. Major label is equal for both minute and hour scale
  2511. case TimeStep.SCALE.HOUR:
  2512. return (this.current.getHours() == 0);
  2513. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2514. case TimeStep.SCALE.DAY:
  2515. return (this.current.getDate() == 1);
  2516. case TimeStep.SCALE.MONTH:
  2517. return (this.current.getMonth() == 0);
  2518. case TimeStep.SCALE.YEAR:
  2519. return false;
  2520. default:
  2521. return false;
  2522. }
  2523. };
  2524. /**
  2525. * Returns formatted text for the minor axislabel, depending on the current
  2526. * date and the scale. For example when scale is MINUTE, the current time is
  2527. * formatted as "hh:mm".
  2528. * @param {Date} [date] custom date. if not provided, current date is taken
  2529. */
  2530. TimeStep.prototype.getLabelMinor = function(date) {
  2531. if (date == undefined) {
  2532. date = this.current;
  2533. }
  2534. switch (this.scale) {
  2535. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2536. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2537. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2538. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2539. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2540. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2541. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2542. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2543. default: return '';
  2544. }
  2545. };
  2546. /**
  2547. * Returns formatted text for the major axis label, depending on the current
  2548. * date and the scale. For example when scale is MINUTE, the major scale is
  2549. * hours, and the hour will be formatted as "hh".
  2550. * @param {Date} [date] custom date. if not provided, current date is taken
  2551. */
  2552. TimeStep.prototype.getLabelMajor = function(date) {
  2553. if (date == undefined) {
  2554. date = this.current;
  2555. }
  2556. //noinspection FallthroughInSwitchStatementJS
  2557. switch (this.scale) {
  2558. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2559. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2560. case TimeStep.SCALE.MINUTE:
  2561. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2562. case TimeStep.SCALE.WEEKDAY:
  2563. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2564. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2565. case TimeStep.SCALE.YEAR: return '';
  2566. default: return '';
  2567. }
  2568. };
  2569. /**
  2570. * @constructor Stack
  2571. * Stacks items on top of each other.
  2572. * @param {ItemSet} parent
  2573. * @param {Object} [options]
  2574. */
  2575. function Stack (parent, options) {
  2576. this.parent = parent;
  2577. this.options = options || {};
  2578. this.defaultOptions = {
  2579. order: function (a, b) {
  2580. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  2581. // Order: ranges over non-ranges, ranged ordered by width, and
  2582. // lastly ordered by start.
  2583. if (a instanceof ItemRange) {
  2584. if (b instanceof ItemRange) {
  2585. var aInt = (a.data.end - a.data.start);
  2586. var bInt = (b.data.end - b.data.start);
  2587. return (aInt - bInt) || (a.data.start - b.data.start);
  2588. }
  2589. else {
  2590. return -1;
  2591. }
  2592. }
  2593. else {
  2594. if (b instanceof ItemRange) {
  2595. return 1;
  2596. }
  2597. else {
  2598. return (a.data.start - b.data.start);
  2599. }
  2600. }
  2601. },
  2602. margin: {
  2603. item: 10
  2604. }
  2605. };
  2606. this.ordered = []; // ordered items
  2607. }
  2608. /**
  2609. * Set options for the stack
  2610. * @param {Object} options Available options:
  2611. * {ItemSet} parent
  2612. * {Number} margin
  2613. * {function} order Stacking order
  2614. */
  2615. Stack.prototype.setOptions = function setOptions (options) {
  2616. util.extend(this.options, options);
  2617. // TODO: register on data changes at the connected parent itemset, and update the changed part only and immediately
  2618. };
  2619. /**
  2620. * Stack the items such that they don't overlap. The items will have a minimal
  2621. * distance equal to options.margin.item.
  2622. */
  2623. Stack.prototype.update = function update() {
  2624. this._order();
  2625. this._stack();
  2626. };
  2627. /**
  2628. * Order the items. The items are ordered by width first, and by left position
  2629. * second.
  2630. * If a custom order function has been provided via the options, then this will
  2631. * be used.
  2632. * @private
  2633. */
  2634. Stack.prototype._order = function _order () {
  2635. var items = this.parent.items;
  2636. if (!items) {
  2637. throw new Error('Cannot stack items: parent does not contain items');
  2638. }
  2639. // TODO: store the sorted items, to have less work later on
  2640. var ordered = [];
  2641. var index = 0;
  2642. // items is a map (no array)
  2643. util.forEach(items, function (item) {
  2644. if (item.visible) {
  2645. ordered[index] = item;
  2646. index++;
  2647. }
  2648. });
  2649. //if a customer stack order function exists, use it.
  2650. var order = this.options.order || this.defaultOptions.order;
  2651. if (!(typeof order === 'function')) {
  2652. throw new Error('Option order must be a function');
  2653. }
  2654. ordered.sort(order);
  2655. this.ordered = ordered;
  2656. };
  2657. /**
  2658. * Adjust vertical positions of the events such that they don't overlap each
  2659. * other.
  2660. * @private
  2661. */
  2662. Stack.prototype._stack = function _stack () {
  2663. var i,
  2664. iMax,
  2665. ordered = this.ordered,
  2666. options = this.options,
  2667. orientation = options.orientation || this.defaultOptions.orientation,
  2668. axisOnTop = (orientation == 'top'),
  2669. margin;
  2670. if (options.margin && options.margin.item !== undefined) {
  2671. margin = options.margin.item;
  2672. }
  2673. else {
  2674. margin = this.defaultOptions.margin.item
  2675. }
  2676. // calculate new, non-overlapping positions
  2677. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  2678. var item = ordered[i];
  2679. var collidingItem = null;
  2680. do {
  2681. // TODO: optimize checking for overlap. when there is a gap without items,
  2682. // you only need to check for items from the next item on, not from zero
  2683. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  2684. if (collidingItem != null) {
  2685. // There is a collision. Reposition the event above the colliding element
  2686. if (axisOnTop) {
  2687. item.top = collidingItem.top + collidingItem.height + margin;
  2688. }
  2689. else {
  2690. item.top = collidingItem.top - item.height - margin;
  2691. }
  2692. }
  2693. } while (collidingItem);
  2694. }
  2695. };
  2696. /**
  2697. * Check if the destiny position of given item overlaps with any
  2698. * of the other items from index itemStart to itemEnd.
  2699. * @param {Array} items Array with items
  2700. * @param {int} itemIndex Number of the item to be checked for overlap
  2701. * @param {int} itemStart First item to be checked.
  2702. * @param {int} itemEnd Last item to be checked.
  2703. * @return {Object | null} colliding item, or undefined when no collisions
  2704. * @param {Number} margin A minimum required margin.
  2705. * If margin is provided, the two items will be
  2706. * marked colliding when they overlap or
  2707. * when the margin between the two is smaller than
  2708. * the requested margin.
  2709. */
  2710. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  2711. itemStart, itemEnd, margin) {
  2712. var collision = this.collision;
  2713. // we loop from end to start, as we suppose that the chance of a
  2714. // collision is larger for items at the end, so check these first.
  2715. var a = items[itemIndex];
  2716. for (var i = itemEnd; i >= itemStart; i--) {
  2717. var b = items[i];
  2718. if (collision(a, b, margin)) {
  2719. if (i != itemIndex) {
  2720. return b;
  2721. }
  2722. }
  2723. }
  2724. return null;
  2725. };
  2726. /**
  2727. * Test if the two provided items collide
  2728. * The items must have parameters left, width, top, and height.
  2729. * @param {Component} a The first item
  2730. * @param {Component} b The second item
  2731. * @param {Number} margin A minimum required margin.
  2732. * If margin is provided, the two items will be
  2733. * marked colliding when they overlap or
  2734. * when the margin between the two is smaller than
  2735. * the requested margin.
  2736. * @return {boolean} true if a and b collide, else false
  2737. */
  2738. Stack.prototype.collision = function collision (a, b, margin) {
  2739. return ((a.left - margin) < (b.left + b.getWidth()) &&
  2740. (a.left + a.getWidth() + margin) > b.left &&
  2741. (a.top - margin) < (b.top + b.height) &&
  2742. (a.top + a.height + margin) > b.top);
  2743. };
  2744. /**
  2745. * @constructor Range
  2746. * A Range controls a numeric range with a start and end value.
  2747. * The Range adjusts the range based on mouse events or programmatic changes,
  2748. * and triggers events when the range is changing or has been changed.
  2749. * @param {Object} [options] See description at Range.setOptions
  2750. * @extends Controller
  2751. */
  2752. function Range(options) {
  2753. this.id = util.randomUUID();
  2754. this.start = null; // Number
  2755. this.end = null; // Number
  2756. this.options = options || {};
  2757. this.setOptions(options);
  2758. }
  2759. /**
  2760. * Set options for the range controller
  2761. * @param {Object} options Available options:
  2762. * {Number} min Minimum value for start
  2763. * {Number} max Maximum value for end
  2764. * {Number} zoomMin Set a minimum value for
  2765. * (end - start).
  2766. * {Number} zoomMax Set a maximum value for
  2767. * (end - start).
  2768. */
  2769. Range.prototype.setOptions = function (options) {
  2770. util.extend(this.options, options);
  2771. // re-apply range with new limitations
  2772. if (this.start !== null && this.end !== null) {
  2773. this.setRange(this.start, this.end);
  2774. }
  2775. };
  2776. /**
  2777. * Test whether direction has a valid value
  2778. * @param {String} direction 'horizontal' or 'vertical'
  2779. */
  2780. function validateDirection (direction) {
  2781. if (direction != 'horizontal' && direction != 'vertical') {
  2782. throw new TypeError('Unknown direction "' + direction + '". ' +
  2783. 'Choose "horizontal" or "vertical".');
  2784. }
  2785. }
  2786. /**
  2787. * Add listeners for mouse and touch events to the component
  2788. * @param {Component} component
  2789. * @param {String} event Available events: 'move', 'zoom'
  2790. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2791. */
  2792. Range.prototype.subscribe = function (component, event, direction) {
  2793. var me = this;
  2794. if (event == 'move') {
  2795. // drag start listener
  2796. component.on('dragstart', function (event) {
  2797. me._onDragStart(event, component);
  2798. });
  2799. // drag listener
  2800. component.on('drag', function (event) {
  2801. me._onDrag(event, component, direction);
  2802. });
  2803. // drag end listener
  2804. component.on('dragend', function (event) {
  2805. me._onDragEnd(event, component);
  2806. });
  2807. }
  2808. else if (event == 'zoom') {
  2809. // mouse wheel
  2810. function mousewheel (event) {
  2811. me._onMouseWheel(event, component, direction);
  2812. }
  2813. component.on('mousewheel', mousewheel);
  2814. component.on('DOMMouseScroll', mousewheel); // For FF
  2815. // pinch
  2816. component.on('touch', function (event) {
  2817. me._onTouch();
  2818. });
  2819. component.on('pinch', function (event) {
  2820. me._onPinch(event, component, direction);
  2821. });
  2822. }
  2823. else {
  2824. throw new TypeError('Unknown event "' + event + '". ' +
  2825. 'Choose "move" or "zoom".');
  2826. }
  2827. };
  2828. /**
  2829. * Event handler
  2830. * @param {String} event name of the event, for example 'click', 'mousemove'
  2831. * @param {function} callback callback handler, invoked with the raw HTML Event
  2832. * as parameter.
  2833. */
  2834. Range.prototype.on = function (event, callback) {
  2835. events.addListener(this, event, callback);
  2836. };
  2837. /**
  2838. * Trigger an event
  2839. * @param {String} event name of the event, available events: 'rangechange',
  2840. * 'rangechanged'
  2841. * @private
  2842. */
  2843. Range.prototype._trigger = function (event) {
  2844. events.trigger(this, event, {
  2845. start: this.start,
  2846. end: this.end
  2847. });
  2848. };
  2849. /**
  2850. * Set a new start and end range
  2851. * @param {Number} [start]
  2852. * @param {Number} [end]
  2853. */
  2854. Range.prototype.setRange = function(start, end) {
  2855. var changed = this._applyRange(start, end);
  2856. if (changed) {
  2857. this._trigger('rangechange');
  2858. this._trigger('rangechanged');
  2859. }
  2860. };
  2861. /**
  2862. * Set a new start and end range. This method is the same as setRange, but
  2863. * does not trigger a range change and range changed event, and it returns
  2864. * true when the range is changed
  2865. * @param {Number} [start]
  2866. * @param {Number} [end]
  2867. * @return {Boolean} changed
  2868. * @private
  2869. */
  2870. Range.prototype._applyRange = function(start, end) {
  2871. var newStart = (start != null) ? util.convert(start, 'Number') : this.start,
  2872. newEnd = (end != null) ? util.convert(end, 'Number') : this.end,
  2873. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2874. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2875. diff;
  2876. // check for valid number
  2877. if (isNaN(newStart) || newStart === null) {
  2878. throw new Error('Invalid start "' + start + '"');
  2879. }
  2880. if (isNaN(newEnd) || newEnd === null) {
  2881. throw new Error('Invalid end "' + end + '"');
  2882. }
  2883. // prevent start < end
  2884. if (newEnd < newStart) {
  2885. newEnd = newStart;
  2886. }
  2887. // prevent start < min
  2888. if (min !== null) {
  2889. if (newStart < min) {
  2890. diff = (min - newStart);
  2891. newStart += diff;
  2892. newEnd += diff;
  2893. // prevent end > max
  2894. if (max != null) {
  2895. if (newEnd > max) {
  2896. newEnd = max;
  2897. }
  2898. }
  2899. }
  2900. }
  2901. // prevent end > max
  2902. if (max !== null) {
  2903. if (newEnd > max) {
  2904. diff = (newEnd - max);
  2905. newStart -= diff;
  2906. newEnd -= diff;
  2907. // prevent start < min
  2908. if (min != null) {
  2909. if (newStart < min) {
  2910. newStart = min;
  2911. }
  2912. }
  2913. }
  2914. }
  2915. // prevent (end-start) < zoomMin
  2916. if (this.options.zoomMin !== null) {
  2917. var zoomMin = parseFloat(this.options.zoomMin);
  2918. if (zoomMin < 0) {
  2919. zoomMin = 0;
  2920. }
  2921. if ((newEnd - newStart) < zoomMin) {
  2922. if ((this.end - this.start) === zoomMin) {
  2923. // ignore this action, we are already zoomed to the minimum
  2924. newStart = this.start;
  2925. newEnd = this.end;
  2926. }
  2927. else {
  2928. // zoom to the minimum
  2929. diff = (zoomMin - (newEnd - newStart));
  2930. newStart -= diff / 2;
  2931. newEnd += diff / 2;
  2932. }
  2933. }
  2934. }
  2935. // prevent (end-start) > zoomMax
  2936. if (this.options.zoomMax !== null) {
  2937. var zoomMax = parseFloat(this.options.zoomMax);
  2938. if (zoomMax < 0) {
  2939. zoomMax = 0;
  2940. }
  2941. if ((newEnd - newStart) > zoomMax) {
  2942. if ((this.end - this.start) === zoomMax) {
  2943. // ignore this action, we are already zoomed to the maximum
  2944. newStart = this.start;
  2945. newEnd = this.end;
  2946. }
  2947. else {
  2948. // zoom to the maximum
  2949. diff = ((newEnd - newStart) - zoomMax);
  2950. newStart += diff / 2;
  2951. newEnd -= diff / 2;
  2952. }
  2953. }
  2954. }
  2955. var changed = (this.start != newStart || this.end != newEnd);
  2956. this.start = newStart;
  2957. this.end = newEnd;
  2958. return changed;
  2959. };
  2960. /**
  2961. * Retrieve the current range.
  2962. * @return {Object} An object with start and end properties
  2963. */
  2964. Range.prototype.getRange = function() {
  2965. return {
  2966. start: this.start,
  2967. end: this.end
  2968. };
  2969. };
  2970. /**
  2971. * Calculate the conversion offset and scale for current range, based on
  2972. * the provided width
  2973. * @param {Number} width
  2974. * @returns {{offset: number, scale: number}} conversion
  2975. */
  2976. Range.prototype.conversion = function (width) {
  2977. return Range.conversion(this.start, this.end, width);
  2978. };
  2979. /**
  2980. * Static method to calculate the conversion offset and scale for a range,
  2981. * based on the provided start, end, and width
  2982. * @param {Number} start
  2983. * @param {Number} end
  2984. * @param {Number} width
  2985. * @returns {{offset: number, scale: number}} conversion
  2986. */
  2987. Range.conversion = function (start, end, width) {
  2988. if (width != 0 && (end - start != 0)) {
  2989. return {
  2990. offset: start,
  2991. scale: width / (end - start)
  2992. }
  2993. }
  2994. else {
  2995. return {
  2996. offset: 0,
  2997. scale: 1
  2998. };
  2999. }
  3000. };
  3001. // global (private) object to store drag params
  3002. var touchParams = {};
  3003. /**
  3004. * Start dragging horizontally or vertically
  3005. * @param {Event} event
  3006. * @param {Object} component
  3007. * @private
  3008. */
  3009. Range.prototype._onDragStart = function(event, component) {
  3010. // refuse to drag when we where pinching to prevent the timeline make a jump
  3011. // when releasing the fingers in opposite order from the touch screen
  3012. if (touchParams.pinching) return;
  3013. touchParams.start = this.start;
  3014. touchParams.end = this.end;
  3015. var frame = component.frame;
  3016. if (frame) {
  3017. frame.style.cursor = 'move';
  3018. }
  3019. };
  3020. /**
  3021. * Perform dragging operating.
  3022. * @param {Event} event
  3023. * @param {Component} component
  3024. * @param {String} direction 'horizontal' or 'vertical'
  3025. * @private
  3026. */
  3027. Range.prototype._onDrag = function (event, component, direction) {
  3028. validateDirection(direction);
  3029. // refuse to drag when we where pinching to prevent the timeline make a jump
  3030. // when releasing the fingers in opposite order from the touch screen
  3031. if (touchParams.pinching) return;
  3032. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  3033. interval = (touchParams.end - touchParams.start),
  3034. width = (direction == 'horizontal') ? component.width : component.height,
  3035. diffRange = -delta / width * interval;
  3036. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  3037. // fire a rangechange event
  3038. this._trigger('rangechange');
  3039. };
  3040. /**
  3041. * Stop dragging operating.
  3042. * @param {event} event
  3043. * @param {Component} component
  3044. * @private
  3045. */
  3046. Range.prototype._onDragEnd = function (event, component) {
  3047. // refuse to drag when we where pinching to prevent the timeline make a jump
  3048. // when releasing the fingers in opposite order from the touch screen
  3049. if (touchParams.pinching) return;
  3050. if (component.frame) {
  3051. component.frame.style.cursor = 'auto';
  3052. }
  3053. // fire a rangechanged event
  3054. this._trigger('rangechanged');
  3055. };
  3056. /**
  3057. * Event handler for mouse wheel event, used to zoom
  3058. * Code from http://adomas.org/javascript-mouse-wheel/
  3059. * @param {Event} event
  3060. * @param {Component} component
  3061. * @param {String} direction 'horizontal' or 'vertical'
  3062. * @private
  3063. */
  3064. Range.prototype._onMouseWheel = function(event, component, direction) {
  3065. validateDirection(direction);
  3066. // retrieve delta
  3067. var delta = 0;
  3068. if (event.wheelDelta) { /* IE/Opera. */
  3069. delta = event.wheelDelta / 120;
  3070. } else if (event.detail) { /* Mozilla case. */
  3071. // In Mozilla, sign of delta is different than in IE.
  3072. // Also, delta is multiple of 3.
  3073. delta = -event.detail / 3;
  3074. }
  3075. // If delta is nonzero, handle it.
  3076. // Basically, delta is now positive if wheel was scrolled up,
  3077. // and negative, if wheel was scrolled down.
  3078. if (delta) {
  3079. // perform the zoom action. Delta is normally 1 or -1
  3080. // adjust a negative delta such that zooming in with delta 0.1
  3081. // equals zooming out with a delta -0.1
  3082. var scale;
  3083. if (delta < 0) {
  3084. scale = 1 - (delta / 5);
  3085. }
  3086. else {
  3087. scale = 1 / (1 + (delta / 5)) ;
  3088. }
  3089. // calculate center, the date to zoom around
  3090. var gesture = util.fakeGesture(this, event),
  3091. pointer = getPointer(gesture.touches[0], component.frame),
  3092. pointerDate = this._pointerToDate(component, direction, pointer);
  3093. this.zoom(scale, pointerDate);
  3094. }
  3095. // Prevent default actions caused by mouse wheel
  3096. // (else the page and timeline both zoom and scroll)
  3097. util.preventDefault(event);
  3098. };
  3099. /**
  3100. * On start of a touch gesture, initialize scale to 1
  3101. * @private
  3102. */
  3103. Range.prototype._onTouch = function () {
  3104. touchParams.start = this.start;
  3105. touchParams.end = this.end;
  3106. touchParams.pinching = false;
  3107. touchParams.center = null;
  3108. };
  3109. /**
  3110. * Handle pinch event
  3111. * @param {Event} event
  3112. * @param {Component} component
  3113. * @param {String} direction 'horizontal' or 'vertical'
  3114. * @private
  3115. */
  3116. Range.prototype._onPinch = function (event, component, direction) {
  3117. touchParams.pinching = true;
  3118. if (event.gesture.touches.length > 1) {
  3119. if (!touchParams.center) {
  3120. touchParams.center = getPointer(event.gesture.center, component.frame);
  3121. }
  3122. var scale = 1 / event.gesture.scale,
  3123. initDate = this._pointerToDate(component, direction, touchParams.center),
  3124. center = getPointer(event.gesture.center, component.frame),
  3125. date = this._pointerToDate(component, direction, center),
  3126. delta = date - initDate; // TODO: utilize delta
  3127. // calculate new start and end
  3128. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3129. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3130. // apply new range
  3131. this.setRange(newStart, newEnd);
  3132. }
  3133. };
  3134. /**
  3135. * Helper function to calculate the center date for zooming
  3136. * @param {Component} component
  3137. * @param {{x: Number, y: Number}} pointer
  3138. * @param {String} direction 'horizontal' or 'vertical'
  3139. * @return {number} date
  3140. * @private
  3141. */
  3142. Range.prototype._pointerToDate = function (component, direction, pointer) {
  3143. var conversion;
  3144. if (direction == 'horizontal') {
  3145. var width = component.width;
  3146. conversion = this.conversion(width);
  3147. return pointer.x / conversion.scale + conversion.offset;
  3148. }
  3149. else {
  3150. var height = component.height;
  3151. conversion = this.conversion(height);
  3152. return pointer.y / conversion.scale + conversion.offset;
  3153. }
  3154. };
  3155. /**
  3156. * Get the pointer location relative to the location of the dom element
  3157. * @param {{pageX: Number, pageY: Number}} touch
  3158. * @param {Element} element HTML DOM element
  3159. * @return {{x: Number, y: Number}} pointer
  3160. * @private
  3161. */
  3162. function getPointer (touch, element) {
  3163. return {
  3164. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3165. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3166. };
  3167. }
  3168. /**
  3169. * Zoom the range the given scale in or out. Start and end date will
  3170. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3171. * date around which to zoom.
  3172. * For example, try scale = 0.9 or 1.1
  3173. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3174. * values below 1 will zoom in.
  3175. * @param {Number} [center] Value representing a date around which will
  3176. * be zoomed.
  3177. */
  3178. Range.prototype.zoom = function(scale, center) {
  3179. // if centerDate is not provided, take it half between start Date and end Date
  3180. if (center == null) {
  3181. center = (this.start + this.end) / 2;
  3182. }
  3183. // calculate new start and end
  3184. var newStart = center + (this.start - center) * scale;
  3185. var newEnd = center + (this.end - center) * scale;
  3186. this.setRange(newStart, newEnd);
  3187. };
  3188. /**
  3189. * Move the range with a given delta to the left or right. Start and end
  3190. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3191. * @param {Number} delta Moving amount. Positive value will move right,
  3192. * negative value will move left
  3193. */
  3194. Range.prototype.move = function(delta) {
  3195. // zoom start Date and end Date relative to the centerDate
  3196. var diff = (this.end - this.start);
  3197. // apply new values
  3198. var newStart = this.start + diff * delta;
  3199. var newEnd = this.end + diff * delta;
  3200. // TODO: reckon with min and max range
  3201. this.start = newStart;
  3202. this.end = newEnd;
  3203. };
  3204. /**
  3205. * Move the range to a new center point
  3206. * @param {Number} moveTo New center point of the range
  3207. */
  3208. Range.prototype.moveTo = function(moveTo) {
  3209. var center = (this.start + this.end) / 2;
  3210. var diff = center - moveTo;
  3211. // calculate new start and end
  3212. var newStart = this.start - diff;
  3213. var newEnd = this.end - diff;
  3214. this.setRange(newStart, newEnd);
  3215. };
  3216. /**
  3217. * @constructor Controller
  3218. *
  3219. * A Controller controls the reflows and repaints of all visual components
  3220. */
  3221. function Controller () {
  3222. this.id = util.randomUUID();
  3223. this.components = {};
  3224. this.repaintTimer = undefined;
  3225. this.reflowTimer = undefined;
  3226. }
  3227. /**
  3228. * Add a component to the controller
  3229. * @param {Component} component
  3230. */
  3231. Controller.prototype.add = function add(component) {
  3232. // validate the component
  3233. if (component.id == undefined) {
  3234. throw new Error('Component has no field id');
  3235. }
  3236. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3237. throw new TypeError('Component must be an instance of ' +
  3238. 'prototype Component or Controller');
  3239. }
  3240. // add the component
  3241. component.controller = this;
  3242. this.components[component.id] = component;
  3243. };
  3244. /**
  3245. * Remove a component from the controller
  3246. * @param {Component | String} component
  3247. */
  3248. Controller.prototype.remove = function remove(component) {
  3249. var id;
  3250. for (id in this.components) {
  3251. if (this.components.hasOwnProperty(id)) {
  3252. if (id == component || this.components[id] == component) {
  3253. break;
  3254. }
  3255. }
  3256. }
  3257. if (id) {
  3258. delete this.components[id];
  3259. }
  3260. };
  3261. /**
  3262. * Request a reflow. The controller will schedule a reflow
  3263. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3264. * is false.
  3265. */
  3266. Controller.prototype.requestReflow = function requestReflow(force) {
  3267. if (force) {
  3268. this.reflow();
  3269. }
  3270. else {
  3271. if (!this.reflowTimer) {
  3272. var me = this;
  3273. this.reflowTimer = setTimeout(function () {
  3274. me.reflowTimer = undefined;
  3275. me.reflow();
  3276. }, 0);
  3277. }
  3278. }
  3279. };
  3280. /**
  3281. * Request a repaint. The controller will schedule a repaint
  3282. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3283. * is false.
  3284. */
  3285. Controller.prototype.requestRepaint = function requestRepaint(force) {
  3286. if (force) {
  3287. this.repaint();
  3288. }
  3289. else {
  3290. if (!this.repaintTimer) {
  3291. var me = this;
  3292. this.repaintTimer = setTimeout(function () {
  3293. me.repaintTimer = undefined;
  3294. me.repaint();
  3295. }, 0);
  3296. }
  3297. }
  3298. };
  3299. /**
  3300. * Repaint all components
  3301. */
  3302. Controller.prototype.repaint = function repaint() {
  3303. var changed = false;
  3304. // cancel any running repaint request
  3305. if (this.repaintTimer) {
  3306. clearTimeout(this.repaintTimer);
  3307. this.repaintTimer = undefined;
  3308. }
  3309. var done = {};
  3310. function repaint(component, id) {
  3311. if (!(id in done)) {
  3312. // first repaint the components on which this component is dependent
  3313. if (component.depends) {
  3314. component.depends.forEach(function (dep) {
  3315. repaint(dep, dep.id);
  3316. });
  3317. }
  3318. if (component.parent) {
  3319. repaint(component.parent, component.parent.id);
  3320. }
  3321. // repaint the component itself and mark as done
  3322. changed = component.repaint() || changed;
  3323. done[id] = true;
  3324. }
  3325. }
  3326. util.forEach(this.components, repaint);
  3327. // immediately reflow when needed
  3328. if (changed) {
  3329. this.reflow();
  3330. }
  3331. // TODO: limit the number of nested reflows/repaints, prevent loop
  3332. };
  3333. /**
  3334. * Reflow all components
  3335. */
  3336. Controller.prototype.reflow = function reflow() {
  3337. var resized = false;
  3338. // cancel any running repaint request
  3339. if (this.reflowTimer) {
  3340. clearTimeout(this.reflowTimer);
  3341. this.reflowTimer = undefined;
  3342. }
  3343. var done = {};
  3344. function reflow(component, id) {
  3345. if (!(id in done)) {
  3346. // first reflow the components on which this component is dependent
  3347. if (component.depends) {
  3348. component.depends.forEach(function (dep) {
  3349. reflow(dep, dep.id);
  3350. });
  3351. }
  3352. if (component.parent) {
  3353. reflow(component.parent, component.parent.id);
  3354. }
  3355. // reflow the component itself and mark as done
  3356. resized = component.reflow() || resized;
  3357. done[id] = true;
  3358. }
  3359. }
  3360. util.forEach(this.components, reflow);
  3361. // immediately repaint when needed
  3362. if (resized) {
  3363. this.repaint();
  3364. }
  3365. // TODO: limit the number of nested reflows/repaints, prevent loop
  3366. };
  3367. /**
  3368. * Prototype for visual components
  3369. */
  3370. function Component () {
  3371. this.id = null;
  3372. this.parent = null;
  3373. this.depends = null;
  3374. this.controller = null;
  3375. this.options = null;
  3376. this.frame = null; // main DOM element
  3377. this.top = 0;
  3378. this.left = 0;
  3379. this.width = 0;
  3380. this.height = 0;
  3381. }
  3382. /**
  3383. * Set parameters for the frame. Parameters will be merged in current parameter
  3384. * set.
  3385. * @param {Object} options Available parameters:
  3386. * {String | function} [className]
  3387. * {EventBus} [eventBus]
  3388. * {String | Number | function} [left]
  3389. * {String | Number | function} [top]
  3390. * {String | Number | function} [width]
  3391. * {String | Number | function} [height]
  3392. */
  3393. Component.prototype.setOptions = function setOptions(options) {
  3394. if (options) {
  3395. util.extend(this.options, options);
  3396. if (this.controller) {
  3397. this.requestRepaint();
  3398. this.requestReflow();
  3399. }
  3400. }
  3401. };
  3402. /**
  3403. * Get an option value by name
  3404. * The function will first check this.options object, and else will check
  3405. * this.defaultOptions.
  3406. * @param {String} name
  3407. * @return {*} value
  3408. */
  3409. Component.prototype.getOption = function getOption(name) {
  3410. var value;
  3411. if (this.options) {
  3412. value = this.options[name];
  3413. }
  3414. if (value === undefined && this.defaultOptions) {
  3415. value = this.defaultOptions[name];
  3416. }
  3417. return value;
  3418. };
  3419. /**
  3420. * Get the container element of the component, which can be used by a child to
  3421. * add its own widgets. Not all components do have a container for childs, in
  3422. * that case null is returned.
  3423. * @returns {HTMLElement | null} container
  3424. */
  3425. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3426. Component.prototype.getContainer = function getContainer() {
  3427. // should be implemented by the component
  3428. return null;
  3429. };
  3430. /**
  3431. * Get the frame element of the component, the outer HTML DOM element.
  3432. * @returns {HTMLElement | null} frame
  3433. */
  3434. Component.prototype.getFrame = function getFrame() {
  3435. return this.frame;
  3436. };
  3437. /**
  3438. * Repaint the component
  3439. * @return {Boolean} changed
  3440. */
  3441. Component.prototype.repaint = function repaint() {
  3442. // should be implemented by the component
  3443. return false;
  3444. };
  3445. /**
  3446. * Reflow the component
  3447. * @return {Boolean} resized
  3448. */
  3449. Component.prototype.reflow = function reflow() {
  3450. // should be implemented by the component
  3451. return false;
  3452. };
  3453. /**
  3454. * Hide the component from the DOM
  3455. * @return {Boolean} changed
  3456. */
  3457. Component.prototype.hide = function hide() {
  3458. if (this.frame && this.frame.parentNode) {
  3459. this.frame.parentNode.removeChild(this.frame);
  3460. return true;
  3461. }
  3462. else {
  3463. return false;
  3464. }
  3465. };
  3466. /**
  3467. * Show the component in the DOM (when not already visible).
  3468. * A repaint will be executed when the component is not visible
  3469. * @return {Boolean} changed
  3470. */
  3471. Component.prototype.show = function show() {
  3472. if (!this.frame || !this.frame.parentNode) {
  3473. return this.repaint();
  3474. }
  3475. else {
  3476. return false;
  3477. }
  3478. };
  3479. /**
  3480. * Request a repaint. The controller will schedule a repaint
  3481. */
  3482. Component.prototype.requestRepaint = function requestRepaint() {
  3483. if (this.controller) {
  3484. this.controller.requestRepaint();
  3485. }
  3486. else {
  3487. throw new Error('Cannot request a repaint: no controller configured');
  3488. // TODO: just do a repaint when no parent is configured?
  3489. }
  3490. };
  3491. /**
  3492. * Request a reflow. The controller will schedule a reflow
  3493. */
  3494. Component.prototype.requestReflow = function requestReflow() {
  3495. if (this.controller) {
  3496. this.controller.requestReflow();
  3497. }
  3498. else {
  3499. throw new Error('Cannot request a reflow: no controller configured');
  3500. // TODO: just do a reflow when no parent is configured?
  3501. }
  3502. };
  3503. /**
  3504. * A panel can contain components
  3505. * @param {Component} [parent]
  3506. * @param {Component[]} [depends] Components on which this components depends
  3507. * (except for the parent)
  3508. * @param {Object} [options] Available parameters:
  3509. * {String | Number | function} [left]
  3510. * {String | Number | function} [top]
  3511. * {String | Number | function} [width]
  3512. * {String | Number | function} [height]
  3513. * {String | function} [className]
  3514. * @constructor Panel
  3515. * @extends Component
  3516. */
  3517. function Panel(parent, depends, options) {
  3518. this.id = util.randomUUID();
  3519. this.parent = parent;
  3520. this.depends = depends;
  3521. this.options = options || {};
  3522. }
  3523. Panel.prototype = new Component();
  3524. /**
  3525. * Set options. Will extend the current options.
  3526. * @param {Object} [options] Available parameters:
  3527. * {String | function} [className]
  3528. * {String | Number | function} [left]
  3529. * {String | Number | function} [top]
  3530. * {String | Number | function} [width]
  3531. * {String | Number | function} [height]
  3532. */
  3533. Panel.prototype.setOptions = Component.prototype.setOptions;
  3534. /**
  3535. * Get the container element of the panel, which can be used by a child to
  3536. * add its own widgets.
  3537. * @returns {HTMLElement} container
  3538. */
  3539. Panel.prototype.getContainer = function () {
  3540. return this.frame;
  3541. };
  3542. /**
  3543. * Repaint the component
  3544. * @return {Boolean} changed
  3545. */
  3546. Panel.prototype.repaint = function () {
  3547. var changed = 0,
  3548. update = util.updateProperty,
  3549. asSize = util.option.asSize,
  3550. options = this.options,
  3551. frame = this.frame;
  3552. if (!frame) {
  3553. frame = document.createElement('div');
  3554. frame.className = 'panel';
  3555. var className = options.className;
  3556. if (className) {
  3557. if (typeof className == 'function') {
  3558. util.addClassName(frame, String(className()));
  3559. }
  3560. else {
  3561. util.addClassName(frame, String(className));
  3562. }
  3563. }
  3564. this.frame = frame;
  3565. changed += 1;
  3566. }
  3567. if (!frame.parentNode) {
  3568. if (!this.parent) {
  3569. throw new Error('Cannot repaint panel: no parent attached');
  3570. }
  3571. var parentContainer = this.parent.getContainer();
  3572. if (!parentContainer) {
  3573. throw new Error('Cannot repaint panel: parent has no container element');
  3574. }
  3575. parentContainer.appendChild(frame);
  3576. changed += 1;
  3577. }
  3578. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3579. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3580. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3581. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3582. return (changed > 0);
  3583. };
  3584. /**
  3585. * Reflow the component
  3586. * @return {Boolean} resized
  3587. */
  3588. Panel.prototype.reflow = function () {
  3589. var changed = 0,
  3590. update = util.updateProperty,
  3591. frame = this.frame;
  3592. if (frame) {
  3593. changed += update(this, 'top', frame.offsetTop);
  3594. changed += update(this, 'left', frame.offsetLeft);
  3595. changed += update(this, 'width', frame.offsetWidth);
  3596. changed += update(this, 'height', frame.offsetHeight);
  3597. }
  3598. else {
  3599. changed += 1;
  3600. }
  3601. return (changed > 0);
  3602. };
  3603. /**
  3604. * A root panel can hold components. The root panel must be initialized with
  3605. * a DOM element as container.
  3606. * @param {HTMLElement} container
  3607. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3608. * @constructor RootPanel
  3609. * @extends Panel
  3610. */
  3611. function RootPanel(container, options) {
  3612. this.id = util.randomUUID();
  3613. this.container = container;
  3614. this.options = options || {};
  3615. this.defaultOptions = {
  3616. autoResize: true
  3617. };
  3618. this.listeners = {}; // event listeners
  3619. }
  3620. RootPanel.prototype = new Panel();
  3621. /**
  3622. * Set options. Will extend the current options.
  3623. * @param {Object} [options] Available parameters:
  3624. * {String | function} [className]
  3625. * {String | Number | function} [left]
  3626. * {String | Number | function} [top]
  3627. * {String | Number | function} [width]
  3628. * {String | Number | function} [height]
  3629. * {Boolean | function} [autoResize]
  3630. */
  3631. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3632. /**
  3633. * Repaint the component
  3634. * @return {Boolean} changed
  3635. */
  3636. RootPanel.prototype.repaint = function () {
  3637. var changed = 0,
  3638. update = util.updateProperty,
  3639. asSize = util.option.asSize,
  3640. options = this.options,
  3641. frame = this.frame;
  3642. if (!frame) {
  3643. frame = document.createElement('div');
  3644. this.frame = frame;
  3645. changed += 1;
  3646. }
  3647. if (!frame.parentNode) {
  3648. if (!this.container) {
  3649. throw new Error('Cannot repaint root panel: no container attached');
  3650. }
  3651. this.container.appendChild(frame);
  3652. changed += 1;
  3653. }
  3654. frame.className = 'vis timeline rootpanel ' + options.orientation;
  3655. var className = options.className;
  3656. if (className) {
  3657. util.addClassName(frame, util.option.asString(className));
  3658. }
  3659. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3660. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3661. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3662. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3663. this._updateEventEmitters();
  3664. this._updateWatch();
  3665. return (changed > 0);
  3666. };
  3667. /**
  3668. * Reflow the component
  3669. * @return {Boolean} resized
  3670. */
  3671. RootPanel.prototype.reflow = function () {
  3672. var changed = 0,
  3673. update = util.updateProperty,
  3674. frame = this.frame;
  3675. if (frame) {
  3676. changed += update(this, 'top', frame.offsetTop);
  3677. changed += update(this, 'left', frame.offsetLeft);
  3678. changed += update(this, 'width', frame.offsetWidth);
  3679. changed += update(this, 'height', frame.offsetHeight);
  3680. }
  3681. else {
  3682. changed += 1;
  3683. }
  3684. return (changed > 0);
  3685. };
  3686. /**
  3687. * Update watching for resize, depending on the current option
  3688. * @private
  3689. */
  3690. RootPanel.prototype._updateWatch = function () {
  3691. var autoResize = this.getOption('autoResize');
  3692. if (autoResize) {
  3693. this._watch();
  3694. }
  3695. else {
  3696. this._unwatch();
  3697. }
  3698. };
  3699. /**
  3700. * Watch for changes in the size of the frame. On resize, the Panel will
  3701. * automatically redraw itself.
  3702. * @private
  3703. */
  3704. RootPanel.prototype._watch = function () {
  3705. var me = this;
  3706. this._unwatch();
  3707. var checkSize = function () {
  3708. var autoResize = me.getOption('autoResize');
  3709. if (!autoResize) {
  3710. // stop watching when the option autoResize is changed to false
  3711. me._unwatch();
  3712. return;
  3713. }
  3714. if (me.frame) {
  3715. // check whether the frame is resized
  3716. if ((me.frame.clientWidth != me.width) ||
  3717. (me.frame.clientHeight != me.height)) {
  3718. me.requestReflow();
  3719. }
  3720. }
  3721. };
  3722. // TODO: automatically cleanup the event listener when the frame is deleted
  3723. util.addEventListener(window, 'resize', checkSize);
  3724. this.watchTimer = setInterval(checkSize, 1000);
  3725. };
  3726. /**
  3727. * Stop watching for a resize of the frame.
  3728. * @private
  3729. */
  3730. RootPanel.prototype._unwatch = function () {
  3731. if (this.watchTimer) {
  3732. clearInterval(this.watchTimer);
  3733. this.watchTimer = undefined;
  3734. }
  3735. // TODO: remove event listener on window.resize
  3736. };
  3737. /**
  3738. * Event handler
  3739. * @param {String} event name of the event, for example 'click', 'mousemove'
  3740. * @param {function} callback callback handler, invoked with the raw HTML Event
  3741. * as parameter.
  3742. */
  3743. RootPanel.prototype.on = function (event, callback) {
  3744. // register the listener at this component
  3745. var arr = this.listeners[event];
  3746. if (!arr) {
  3747. arr = [];
  3748. this.listeners[event] = arr;
  3749. }
  3750. arr.push(callback);
  3751. this._updateEventEmitters();
  3752. };
  3753. /**
  3754. * Update the event listeners for all event emitters
  3755. * @private
  3756. */
  3757. RootPanel.prototype._updateEventEmitters = function () {
  3758. if (this.listeners) {
  3759. var me = this;
  3760. util.forEach(this.listeners, function (listeners, event) {
  3761. if (!me.emitters) {
  3762. me.emitters = {};
  3763. }
  3764. if (!(event in me.emitters)) {
  3765. // create event
  3766. var frame = me.frame;
  3767. if (frame) {
  3768. //console.log('Created a listener for event ' + event + ' on component ' + me.id); // TODO: cleanup logging
  3769. var callback = function(event) {
  3770. listeners.forEach(function (listener) {
  3771. // TODO: filter on event target!
  3772. listener(event);
  3773. });
  3774. };
  3775. me.emitters[event] = callback;
  3776. if (!me.hammer) {
  3777. me.hammer = Hammer(frame, {
  3778. prevent_default: true
  3779. });
  3780. }
  3781. me.hammer.on(event, callback);
  3782. }
  3783. }
  3784. });
  3785. // TODO: be able to delete event listeners
  3786. // TODO: be able to move event listeners to a parent when available
  3787. }
  3788. };
  3789. /**
  3790. * A horizontal time axis
  3791. * @param {Component} parent
  3792. * @param {Component[]} [depends] Components on which this components depends
  3793. * (except for the parent)
  3794. * @param {Object} [options] See TimeAxis.setOptions for the available
  3795. * options.
  3796. * @constructor TimeAxis
  3797. * @extends Component
  3798. */
  3799. function TimeAxis (parent, depends, options) {
  3800. this.id = util.randomUUID();
  3801. this.parent = parent;
  3802. this.depends = depends;
  3803. this.dom = {
  3804. majorLines: [],
  3805. majorTexts: [],
  3806. minorLines: [],
  3807. minorTexts: [],
  3808. redundant: {
  3809. majorLines: [],
  3810. majorTexts: [],
  3811. minorLines: [],
  3812. minorTexts: []
  3813. }
  3814. };
  3815. this.props = {
  3816. range: {
  3817. start: 0,
  3818. end: 0,
  3819. minimumStep: 0
  3820. },
  3821. lineTop: 0
  3822. };
  3823. this.options = options || {};
  3824. this.defaultOptions = {
  3825. orientation: 'bottom', // supported: 'top', 'bottom'
  3826. // TODO: implement timeaxis orientations 'left' and 'right'
  3827. showMinorLabels: true,
  3828. showMajorLabels: true
  3829. };
  3830. this.conversion = null;
  3831. this.range = null;
  3832. }
  3833. TimeAxis.prototype = new Component();
  3834. // TODO: comment options
  3835. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3836. /**
  3837. * Set a range (start and end)
  3838. * @param {Range | Object} range A Range or an object containing start and end.
  3839. */
  3840. TimeAxis.prototype.setRange = function (range) {
  3841. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3842. throw new TypeError('Range must be an instance of Range, ' +
  3843. 'or an object containing start and end.');
  3844. }
  3845. this.range = range;
  3846. };
  3847. /**
  3848. * Convert a position on screen (pixels) to a datetime
  3849. * @param {int} x Position on the screen in pixels
  3850. * @return {Date} time The datetime the corresponds with given position x
  3851. */
  3852. TimeAxis.prototype.toTime = function(x) {
  3853. var conversion = this.conversion;
  3854. return new Date(x / conversion.scale + conversion.offset);
  3855. };
  3856. /**
  3857. * Convert a datetime (Date object) into a position on the screen
  3858. * @param {Date} time A date
  3859. * @return {int} x The position on the screen in pixels which corresponds
  3860. * with the given date.
  3861. * @private
  3862. */
  3863. TimeAxis.prototype.toScreen = function(time) {
  3864. var conversion = this.conversion;
  3865. return (time.valueOf() - conversion.offset) * conversion.scale;
  3866. };
  3867. /**
  3868. * Repaint the component
  3869. * @return {Boolean} changed
  3870. */
  3871. TimeAxis.prototype.repaint = function () {
  3872. var changed = 0,
  3873. update = util.updateProperty,
  3874. asSize = util.option.asSize,
  3875. options = this.options,
  3876. orientation = this.getOption('orientation'),
  3877. props = this.props,
  3878. step = this.step;
  3879. var frame = this.frame;
  3880. if (!frame) {
  3881. frame = document.createElement('div');
  3882. this.frame = frame;
  3883. changed += 1;
  3884. }
  3885. frame.className = 'axis';
  3886. // TODO: custom className?
  3887. if (!frame.parentNode) {
  3888. if (!this.parent) {
  3889. throw new Error('Cannot repaint time axis: no parent attached');
  3890. }
  3891. var parentContainer = this.parent.getContainer();
  3892. if (!parentContainer) {
  3893. throw new Error('Cannot repaint time axis: parent has no container element');
  3894. }
  3895. parentContainer.appendChild(frame);
  3896. changed += 1;
  3897. }
  3898. var parent = frame.parentNode;
  3899. if (parent) {
  3900. var beforeChild = frame.nextSibling;
  3901. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3902. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3903. (this.props.parentHeight - this.height) + 'px' :
  3904. '0px';
  3905. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3906. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3907. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3908. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3909. // get characters width and height
  3910. this._repaintMeasureChars();
  3911. if (this.step) {
  3912. this._repaintStart();
  3913. step.first();
  3914. var xFirstMajorLabel = undefined;
  3915. var max = 0;
  3916. while (step.hasNext() && max < 1000) {
  3917. max++;
  3918. var cur = step.getCurrent(),
  3919. x = this.toScreen(cur),
  3920. isMajor = step.isMajor();
  3921. // TODO: lines must have a width, such that we can create css backgrounds
  3922. if (this.getOption('showMinorLabels')) {
  3923. this._repaintMinorText(x, step.getLabelMinor());
  3924. }
  3925. if (isMajor && this.getOption('showMajorLabels')) {
  3926. if (x > 0) {
  3927. if (xFirstMajorLabel == undefined) {
  3928. xFirstMajorLabel = x;
  3929. }
  3930. this._repaintMajorText(x, step.getLabelMajor());
  3931. }
  3932. this._repaintMajorLine(x);
  3933. }
  3934. else {
  3935. this._repaintMinorLine(x);
  3936. }
  3937. step.next();
  3938. }
  3939. // create a major label on the left when needed
  3940. if (this.getOption('showMajorLabels')) {
  3941. var leftTime = this.toTime(0),
  3942. leftText = step.getLabelMajor(leftTime),
  3943. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3944. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3945. this._repaintMajorText(0, leftText);
  3946. }
  3947. }
  3948. this._repaintEnd();
  3949. }
  3950. this._repaintLine();
  3951. // put frame online again
  3952. if (beforeChild) {
  3953. parent.insertBefore(frame, beforeChild);
  3954. }
  3955. else {
  3956. parent.appendChild(frame)
  3957. }
  3958. }
  3959. return (changed > 0);
  3960. };
  3961. /**
  3962. * Start a repaint. Move all DOM elements to a redundant list, where they
  3963. * can be picked for re-use, or can be cleaned up in the end
  3964. * @private
  3965. */
  3966. TimeAxis.prototype._repaintStart = function () {
  3967. var dom = this.dom,
  3968. redundant = dom.redundant;
  3969. redundant.majorLines = dom.majorLines;
  3970. redundant.majorTexts = dom.majorTexts;
  3971. redundant.minorLines = dom.minorLines;
  3972. redundant.minorTexts = dom.minorTexts;
  3973. dom.majorLines = [];
  3974. dom.majorTexts = [];
  3975. dom.minorLines = [];
  3976. dom.minorTexts = [];
  3977. };
  3978. /**
  3979. * End a repaint. Cleanup leftover DOM elements in the redundant list
  3980. * @private
  3981. */
  3982. TimeAxis.prototype._repaintEnd = function () {
  3983. util.forEach(this.dom.redundant, function (arr) {
  3984. while (arr.length) {
  3985. var elem = arr.pop();
  3986. if (elem && elem.parentNode) {
  3987. elem.parentNode.removeChild(elem);
  3988. }
  3989. }
  3990. });
  3991. };
  3992. /**
  3993. * Create a minor label for the axis at position x
  3994. * @param {Number} x
  3995. * @param {String} text
  3996. * @private
  3997. */
  3998. TimeAxis.prototype._repaintMinorText = function (x, text) {
  3999. // reuse redundant label
  4000. var label = this.dom.redundant.minorTexts.shift();
  4001. if (!label) {
  4002. // create new label
  4003. var content = document.createTextNode('');
  4004. label = document.createElement('div');
  4005. label.appendChild(content);
  4006. label.className = 'text minor';
  4007. this.frame.appendChild(label);
  4008. }
  4009. this.dom.minorTexts.push(label);
  4010. label.childNodes[0].nodeValue = text;
  4011. label.style.left = x + 'px';
  4012. label.style.top = this.props.minorLabelTop + 'px';
  4013. //label.title = title; // TODO: this is a heavy operation
  4014. };
  4015. /**
  4016. * Create a Major label for the axis at position x
  4017. * @param {Number} x
  4018. * @param {String} text
  4019. * @private
  4020. */
  4021. TimeAxis.prototype._repaintMajorText = function (x, text) {
  4022. // reuse redundant label
  4023. var label = this.dom.redundant.majorTexts.shift();
  4024. if (!label) {
  4025. // create label
  4026. var content = document.createTextNode(text);
  4027. label = document.createElement('div');
  4028. label.className = 'text major';
  4029. label.appendChild(content);
  4030. this.frame.appendChild(label);
  4031. }
  4032. this.dom.majorTexts.push(label);
  4033. label.childNodes[0].nodeValue = text;
  4034. label.style.top = this.props.majorLabelTop + 'px';
  4035. label.style.left = x + 'px';
  4036. //label.title = title; // TODO: this is a heavy operation
  4037. };
  4038. /**
  4039. * Create a minor line for the axis at position x
  4040. * @param {Number} x
  4041. * @private
  4042. */
  4043. TimeAxis.prototype._repaintMinorLine = function (x) {
  4044. // reuse redundant line
  4045. var line = this.dom.redundant.minorLines.shift();
  4046. if (!line) {
  4047. // create vertical line
  4048. line = document.createElement('div');
  4049. line.className = 'grid vertical minor';
  4050. this.frame.appendChild(line);
  4051. }
  4052. this.dom.minorLines.push(line);
  4053. var props = this.props;
  4054. line.style.top = props.minorLineTop + 'px';
  4055. line.style.height = props.minorLineHeight + 'px';
  4056. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  4057. };
  4058. /**
  4059. * Create a Major line for the axis at position x
  4060. * @param {Number} x
  4061. * @private
  4062. */
  4063. TimeAxis.prototype._repaintMajorLine = function (x) {
  4064. // reuse redundant line
  4065. var line = this.dom.redundant.majorLines.shift();
  4066. if (!line) {
  4067. // create vertical line
  4068. line = document.createElement('DIV');
  4069. line.className = 'grid vertical major';
  4070. this.frame.appendChild(line);
  4071. }
  4072. this.dom.majorLines.push(line);
  4073. var props = this.props;
  4074. line.style.top = props.majorLineTop + 'px';
  4075. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4076. line.style.height = props.majorLineHeight + 'px';
  4077. };
  4078. /**
  4079. * Repaint the horizontal line for the axis
  4080. * @private
  4081. */
  4082. TimeAxis.prototype._repaintLine = function() {
  4083. var line = this.dom.line,
  4084. frame = this.frame,
  4085. options = this.options;
  4086. // line before all axis elements
  4087. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4088. if (line) {
  4089. // put this line at the end of all childs
  4090. frame.removeChild(line);
  4091. frame.appendChild(line);
  4092. }
  4093. else {
  4094. // create the axis line
  4095. line = document.createElement('div');
  4096. line.className = 'grid horizontal major';
  4097. frame.appendChild(line);
  4098. this.dom.line = line;
  4099. }
  4100. line.style.top = this.props.lineTop + 'px';
  4101. }
  4102. else {
  4103. if (line && line.parentElement) {
  4104. frame.removeChild(line.line);
  4105. delete this.dom.line;
  4106. }
  4107. }
  4108. };
  4109. /**
  4110. * Create characters used to determine the size of text on the axis
  4111. * @private
  4112. */
  4113. TimeAxis.prototype._repaintMeasureChars = function () {
  4114. // calculate the width and height of a single character
  4115. // this is used to calculate the step size, and also the positioning of the
  4116. // axis
  4117. var dom = this.dom,
  4118. text;
  4119. if (!dom.measureCharMinor) {
  4120. text = document.createTextNode('0');
  4121. var measureCharMinor = document.createElement('DIV');
  4122. measureCharMinor.className = 'text minor measure';
  4123. measureCharMinor.appendChild(text);
  4124. this.frame.appendChild(measureCharMinor);
  4125. dom.measureCharMinor = measureCharMinor;
  4126. }
  4127. if (!dom.measureCharMajor) {
  4128. text = document.createTextNode('0');
  4129. var measureCharMajor = document.createElement('DIV');
  4130. measureCharMajor.className = 'text major measure';
  4131. measureCharMajor.appendChild(text);
  4132. this.frame.appendChild(measureCharMajor);
  4133. dom.measureCharMajor = measureCharMajor;
  4134. }
  4135. };
  4136. /**
  4137. * Reflow the component
  4138. * @return {Boolean} resized
  4139. */
  4140. TimeAxis.prototype.reflow = function () {
  4141. var changed = 0,
  4142. update = util.updateProperty,
  4143. frame = this.frame,
  4144. range = this.range;
  4145. if (!range) {
  4146. throw new Error('Cannot repaint time axis: no range configured');
  4147. }
  4148. if (frame) {
  4149. changed += update(this, 'top', frame.offsetTop);
  4150. changed += update(this, 'left', frame.offsetLeft);
  4151. // calculate size of a character
  4152. var props = this.props,
  4153. showMinorLabels = this.getOption('showMinorLabels'),
  4154. showMajorLabels = this.getOption('showMajorLabels'),
  4155. measureCharMinor = this.dom.measureCharMinor,
  4156. measureCharMajor = this.dom.measureCharMajor;
  4157. if (measureCharMinor) {
  4158. props.minorCharHeight = measureCharMinor.clientHeight;
  4159. props.minorCharWidth = measureCharMinor.clientWidth;
  4160. }
  4161. if (measureCharMajor) {
  4162. props.majorCharHeight = measureCharMajor.clientHeight;
  4163. props.majorCharWidth = measureCharMajor.clientWidth;
  4164. }
  4165. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4166. if (parentHeight != props.parentHeight) {
  4167. props.parentHeight = parentHeight;
  4168. changed += 1;
  4169. }
  4170. switch (this.getOption('orientation')) {
  4171. case 'bottom':
  4172. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4173. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4174. props.minorLabelTop = 0;
  4175. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4176. props.minorLineTop = -this.top;
  4177. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4178. props.minorLineWidth = 1; // TODO: really calculate width
  4179. props.majorLineTop = -this.top;
  4180. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4181. props.majorLineWidth = 1; // TODO: really calculate width
  4182. props.lineTop = 0;
  4183. break;
  4184. case 'top':
  4185. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4186. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4187. props.majorLabelTop = 0;
  4188. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4189. props.minorLineTop = props.minorLabelTop;
  4190. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4191. props.minorLineWidth = 1; // TODO: really calculate width
  4192. props.majorLineTop = 0;
  4193. props.majorLineHeight = Math.max(parentHeight - this.top);
  4194. props.majorLineWidth = 1; // TODO: really calculate width
  4195. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4196. break;
  4197. default:
  4198. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4199. }
  4200. var height = props.minorLabelHeight + props.majorLabelHeight;
  4201. changed += update(this, 'width', frame.offsetWidth);
  4202. changed += update(this, 'height', height);
  4203. // calculate range and step
  4204. this._updateConversion();
  4205. var start = util.convert(range.start, 'Number'),
  4206. end = util.convert(range.end, 'Number'),
  4207. minimumStep = this.toTime((props.minorCharWidth || 10) * 5).valueOf()
  4208. -this.toTime(0).valueOf();
  4209. this.step = new TimeStep(new Date(start), new Date(end), minimumStep);
  4210. changed += update(props.range, 'start', start);
  4211. changed += update(props.range, 'end', end);
  4212. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4213. }
  4214. return (changed > 0);
  4215. };
  4216. /**
  4217. * Calculate the scale and offset to convert a position on screen to the
  4218. * corresponding date and vice versa.
  4219. * After the method _updateConversion is executed once, the methods toTime
  4220. * and toScreen can be used.
  4221. * @private
  4222. */
  4223. TimeAxis.prototype._updateConversion = function() {
  4224. var range = this.range;
  4225. if (!range) {
  4226. throw new Error('No range configured');
  4227. }
  4228. if (range.conversion) {
  4229. this.conversion = range.conversion(this.width);
  4230. }
  4231. else {
  4232. this.conversion = Range.conversion(range.start, range.end, this.width);
  4233. }
  4234. };
  4235. /**
  4236. * A current time bar
  4237. * @param {Component} parent
  4238. * @param {Component[]} [depends] Components on which this components depends
  4239. * (except for the parent)
  4240. * @param {Object} [options] Available parameters:
  4241. * {Boolean} [showCurrentTime]
  4242. * @constructor CurrentTime
  4243. * @extends Component
  4244. */
  4245. function CurrentTime (parent, depends, options) {
  4246. this.id = util.randomUUID();
  4247. this.parent = parent;
  4248. this.depends = depends;
  4249. this.options = options || {};
  4250. this.defaultOptions = {
  4251. showCurrentTime: false
  4252. };
  4253. }
  4254. CurrentTime.prototype = new Component();
  4255. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  4256. /**
  4257. * Get the container element of the bar, which can be used by a child to
  4258. * add its own widgets.
  4259. * @returns {HTMLElement} container
  4260. */
  4261. CurrentTime.prototype.getContainer = function () {
  4262. return this.frame;
  4263. };
  4264. /**
  4265. * Repaint the component
  4266. * @return {Boolean} changed
  4267. */
  4268. CurrentTime.prototype.repaint = function () {
  4269. var bar = this.frame,
  4270. parent = this.parent,
  4271. parentContainer = parent.parent.getContainer();
  4272. if (!parent) {
  4273. throw new Error('Cannot repaint bar: no parent attached');
  4274. }
  4275. if (!parentContainer) {
  4276. throw new Error('Cannot repaint bar: parent has no container element');
  4277. }
  4278. if (!this.getOption('showCurrentTime')) {
  4279. if (bar) {
  4280. parentContainer.removeChild(bar);
  4281. delete this.frame;
  4282. }
  4283. return;
  4284. }
  4285. if (!bar) {
  4286. bar = document.createElement('div');
  4287. bar.className = 'currenttime';
  4288. bar.style.position = 'absolute';
  4289. bar.style.top = '0px';
  4290. bar.style.height = '100%';
  4291. parentContainer.appendChild(bar);
  4292. this.frame = bar;
  4293. }
  4294. if (!parent.conversion) {
  4295. parent._updateConversion();
  4296. }
  4297. var now = new Date();
  4298. var x = parent.toScreen(now);
  4299. bar.style.left = x + 'px';
  4300. bar.title = 'Current time: ' + now;
  4301. // start a timer to adjust for the new time
  4302. if (this.currentTimeTimer !== undefined) {
  4303. clearTimeout(this.currentTimeTimer);
  4304. delete this.currentTimeTimer;
  4305. }
  4306. var timeline = this;
  4307. var interval = 1 / parent.conversion.scale / 2;
  4308. if (interval < 30) {
  4309. interval = 30;
  4310. }
  4311. this.currentTimeTimer = setTimeout(function() {
  4312. timeline.repaint();
  4313. }, interval);
  4314. return false;
  4315. };
  4316. /**
  4317. * A custom time bar
  4318. * @param {Component} parent
  4319. * @param {Component[]} [depends] Components on which this components depends
  4320. * (except for the parent)
  4321. * @param {Object} [options] Available parameters:
  4322. * {Boolean} [showCustomTime]
  4323. * @constructor CustomTime
  4324. * @extends Component
  4325. */
  4326. function CustomTime (parent, depends, options) {
  4327. this.id = util.randomUUID();
  4328. this.parent = parent;
  4329. this.depends = depends;
  4330. this.options = options || {};
  4331. this.defaultOptions = {
  4332. showCustomTime: false
  4333. };
  4334. this.listeners = [];
  4335. this.customTime = new Date();
  4336. }
  4337. CustomTime.prototype = new Component();
  4338. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4339. /**
  4340. * Get the container element of the bar, which can be used by a child to
  4341. * add its own widgets.
  4342. * @returns {HTMLElement} container
  4343. */
  4344. CustomTime.prototype.getContainer = function () {
  4345. return this.frame;
  4346. };
  4347. /**
  4348. * Repaint the component
  4349. * @return {Boolean} changed
  4350. */
  4351. CustomTime.prototype.repaint = function () {
  4352. var bar = this.frame,
  4353. parent = this.parent,
  4354. parentContainer = parent.parent.getContainer();
  4355. if (!parent) {
  4356. throw new Error('Cannot repaint bar: no parent attached');
  4357. }
  4358. if (!parentContainer) {
  4359. throw new Error('Cannot repaint bar: parent has no container element');
  4360. }
  4361. if (!this.getOption('showCustomTime')) {
  4362. if (bar) {
  4363. parentContainer.removeChild(bar);
  4364. delete this.frame;
  4365. }
  4366. return;
  4367. }
  4368. if (!bar) {
  4369. bar = document.createElement('div');
  4370. bar.className = 'customtime';
  4371. bar.style.position = 'absolute';
  4372. bar.style.top = '0px';
  4373. bar.style.height = '100%';
  4374. parentContainer.appendChild(bar);
  4375. var drag = document.createElement('div');
  4376. drag.style.position = 'relative';
  4377. drag.style.top = '0px';
  4378. drag.style.left = '-10px';
  4379. drag.style.height = '100%';
  4380. drag.style.width = '20px';
  4381. bar.appendChild(drag);
  4382. this.frame = bar;
  4383. this.subscribe(this, 'movetime');
  4384. }
  4385. if (!parent.conversion) {
  4386. parent._updateConversion();
  4387. }
  4388. var x = parent.toScreen(this.customTime);
  4389. bar.style.left = x + 'px';
  4390. bar.title = 'Time: ' + this.customTime;
  4391. return false;
  4392. };
  4393. /**
  4394. * Set custom time.
  4395. * @param {Date} time
  4396. */
  4397. CustomTime.prototype._setCustomTime = function(time) {
  4398. this.customTime = new Date(time.valueOf());
  4399. this.repaint();
  4400. };
  4401. /**
  4402. * Retrieve the current custom time.
  4403. * @return {Date} customTime
  4404. */
  4405. CustomTime.prototype._getCustomTime = function() {
  4406. return new Date(this.customTime.valueOf());
  4407. };
  4408. /**
  4409. * Add listeners for mouse and touch events to the component
  4410. * @param {Component} component
  4411. */
  4412. CustomTime.prototype.subscribe = function (component, event) {
  4413. var me = this;
  4414. var listener = {
  4415. component: component,
  4416. event: event,
  4417. callback: function (event) {
  4418. me._onMouseDown(event, listener);
  4419. },
  4420. params: {}
  4421. };
  4422. component.on('mousedown', listener.callback);
  4423. me.listeners.push(listener);
  4424. };
  4425. /**
  4426. * Event handler
  4427. * @param {String} event name of the event, for example 'click', 'mousemove'
  4428. * @param {function} callback callback handler, invoked with the raw HTML Event
  4429. * as parameter.
  4430. */
  4431. CustomTime.prototype.on = function (event, callback) {
  4432. var bar = this.frame;
  4433. if (!bar) {
  4434. throw new Error('Cannot add event listener: no parent attached');
  4435. }
  4436. events.addListener(this, event, callback);
  4437. util.addEventListener(bar, event, callback);
  4438. };
  4439. /**
  4440. * Start moving horizontally
  4441. * @param {Event} event
  4442. * @param {Object} listener Listener containing the component and params
  4443. * @private
  4444. */
  4445. CustomTime.prototype._onMouseDown = function(event, listener) {
  4446. event = event || window.event;
  4447. var params = listener.params;
  4448. // only react on left mouse button down
  4449. var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  4450. if (!leftButtonDown) {
  4451. return;
  4452. }
  4453. // get mouse position
  4454. params.mouseX = util.getPageX(event);
  4455. params.moved = false;
  4456. params.customTime = this.customTime;
  4457. // add event listeners to handle moving the custom time bar
  4458. var me = this;
  4459. if (!params.onMouseMove) {
  4460. params.onMouseMove = function (event) {
  4461. me._onMouseMove(event, listener);
  4462. };
  4463. util.addEventListener(document, 'mousemove', params.onMouseMove);
  4464. }
  4465. if (!params.onMouseUp) {
  4466. params.onMouseUp = function (event) {
  4467. me._onMouseUp(event, listener);
  4468. };
  4469. util.addEventListener(document, 'mouseup', params.onMouseUp);
  4470. }
  4471. util.stopPropagation(event);
  4472. util.preventDefault(event);
  4473. };
  4474. /**
  4475. * Perform moving operating.
  4476. * This function activated from within the funcion CustomTime._onMouseDown().
  4477. * @param {Event} event
  4478. * @param {Object} listener
  4479. * @private
  4480. */
  4481. CustomTime.prototype._onMouseMove = function (event, listener) {
  4482. event = event || window.event;
  4483. var params = listener.params;
  4484. var parent = this.parent;
  4485. // calculate change in mouse position
  4486. var mouseX = util.getPageX(event);
  4487. if (params.mouseX === undefined) {
  4488. params.mouseX = mouseX;
  4489. }
  4490. var diff = mouseX - params.mouseX;
  4491. // if mouse movement is big enough, register it as a "moved" event
  4492. if (Math.abs(diff) >= 1) {
  4493. params.moved = true;
  4494. }
  4495. var x = parent.toScreen(params.customTime);
  4496. var xnew = x + diff;
  4497. var time = parent.toTime(xnew);
  4498. this._setCustomTime(time);
  4499. // fire a timechange event
  4500. events.trigger(this, 'timechange', {customTime: this.customTime});
  4501. util.preventDefault(event);
  4502. };
  4503. /**
  4504. * Stop moving operating.
  4505. * This function activated from within the function CustomTime._onMouseDown().
  4506. * @param {event} event
  4507. * @param {Object} listener
  4508. * @private
  4509. */
  4510. CustomTime.prototype._onMouseUp = function (event, listener) {
  4511. event = event || window.event;
  4512. var params = listener.params;
  4513. // remove event listeners here, important for Safari
  4514. if (params.onMouseMove) {
  4515. util.removeEventListener(document, 'mousemove', params.onMouseMove);
  4516. params.onMouseMove = null;
  4517. }
  4518. if (params.onMouseUp) {
  4519. util.removeEventListener(document, 'mouseup', params.onMouseUp);
  4520. params.onMouseUp = null;
  4521. }
  4522. if (params.moved) {
  4523. // fire a timechanged event
  4524. events.trigger(this, 'timechanged', {customTime: this.customTime});
  4525. }
  4526. };
  4527. /**
  4528. * An ItemSet holds a set of items and ranges which can be displayed in a
  4529. * range. The width is determined by the parent of the ItemSet, and the height
  4530. * is determined by the size of the items.
  4531. * @param {Component} parent
  4532. * @param {Component[]} [depends] Components on which this components depends
  4533. * (except for the parent)
  4534. * @param {Object} [options] See ItemSet.setOptions for the available
  4535. * options.
  4536. * @constructor ItemSet
  4537. * @extends Panel
  4538. */
  4539. // TODO: improve performance by replacing all Array.forEach with a for loop
  4540. function ItemSet(parent, depends, options) {
  4541. this.id = util.randomUUID();
  4542. this.parent = parent;
  4543. this.depends = depends;
  4544. // one options object is shared by this itemset and all its items
  4545. this.options = options || {};
  4546. this.defaultOptions = {
  4547. type: 'box',
  4548. align: 'center',
  4549. orientation: 'bottom',
  4550. margin: {
  4551. axis: 20,
  4552. item: 10
  4553. },
  4554. padding: 5
  4555. };
  4556. this.dom = {};
  4557. var me = this;
  4558. this.itemsData = null; // DataSet
  4559. this.range = null; // Range or Object {start: number, end: number}
  4560. this.listeners = {
  4561. 'add': function (event, params, senderId) {
  4562. if (senderId != me.id) {
  4563. me._onAdd(params.items);
  4564. }
  4565. },
  4566. 'update': function (event, params, senderId) {
  4567. if (senderId != me.id) {
  4568. me._onUpdate(params.items);
  4569. }
  4570. },
  4571. 'remove': function (event, params, senderId) {
  4572. if (senderId != me.id) {
  4573. me._onRemove(params.items);
  4574. }
  4575. }
  4576. };
  4577. this.items = {}; // object with an Item for every data item
  4578. this.selection = []; // list with the ids of all selected nodes
  4579. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4580. this.stack = new Stack(this, Object.create(this.options));
  4581. this.conversion = null;
  4582. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4583. }
  4584. ItemSet.prototype = new Panel();
  4585. // available item types will be registered here
  4586. ItemSet.types = {
  4587. box: ItemBox,
  4588. range: ItemRange,
  4589. rangeoverflow: ItemRangeOverflow,
  4590. point: ItemPoint
  4591. };
  4592. /**
  4593. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4594. * @param {Object} [options] The following options are available:
  4595. * {String | function} [className]
  4596. * class name for the itemset
  4597. * {String} [type]
  4598. * Default type for the items. Choose from 'box'
  4599. * (default), 'point', or 'range'. The default
  4600. * Style can be overwritten by individual items.
  4601. * {String} align
  4602. * Alignment for the items, only applicable for
  4603. * ItemBox. Choose 'center' (default), 'left', or
  4604. * 'right'.
  4605. * {String} orientation
  4606. * Orientation of the item set. Choose 'top' or
  4607. * 'bottom' (default).
  4608. * {Number} margin.axis
  4609. * Margin between the axis and the items in pixels.
  4610. * Default is 20.
  4611. * {Number} margin.item
  4612. * Margin between items in pixels. Default is 10.
  4613. * {Number} padding
  4614. * Padding of the contents of an item in pixels.
  4615. * Must correspond with the items css. Default is 5.
  4616. */
  4617. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4618. /**
  4619. * Set range (start and end).
  4620. * @param {Range | Object} range A Range or an object containing start and end.
  4621. */
  4622. ItemSet.prototype.setRange = function setRange(range) {
  4623. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4624. throw new TypeError('Range must be an instance of Range, ' +
  4625. 'or an object containing start and end.');
  4626. }
  4627. this.range = range;
  4628. };
  4629. /**
  4630. * Change the item selection, and/or get currently selected items
  4631. * @param {Array} [ids] An array with zero or more ids of the items to be selected.
  4632. * @return {Array} ids The ids of the selected items
  4633. */
  4634. ItemSet.prototype.select = function select(ids) {
  4635. var i, ii, id, item, selection;
  4636. if (ids) {
  4637. if (!Array.isArray(ids)) {
  4638. throw new TypeError('Array expected');
  4639. }
  4640. // unselect currently selected items
  4641. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4642. id = this.selection[i];
  4643. item = this.items[id];
  4644. if (item) item.unselect();
  4645. }
  4646. // select items
  4647. this.selection = [];
  4648. for (i = 0, ii = ids.length; i < ii; i++) {
  4649. id = ids[i];
  4650. item = this.items[id];
  4651. if (item) {
  4652. this.selection.push(id);
  4653. item.select();
  4654. }
  4655. }
  4656. // trigger a select event
  4657. selection = this.selection.concat([]);
  4658. events.trigger(this, 'select', {
  4659. ids: selection
  4660. });
  4661. if (this.controller) {
  4662. this.requestRepaint();
  4663. }
  4664. }
  4665. else {
  4666. selection = this.selection.concat([]);
  4667. }
  4668. return selection;
  4669. };
  4670. /**
  4671. * Deselect a selected item
  4672. * @param {String | Number} id
  4673. * @private
  4674. */
  4675. ItemSet.prototype._deselect = function _deselect(id) {
  4676. var selection = this.selection;
  4677. for (var i = 0, ii = selection.length; i < ii; i++) {
  4678. if (selection[i] == id) { // non-strict comparison!
  4679. selection.splice(i, 1);
  4680. break;
  4681. }
  4682. }
  4683. };
  4684. /**
  4685. * Repaint the component
  4686. * @return {Boolean} changed
  4687. */
  4688. ItemSet.prototype.repaint = function repaint() {
  4689. var changed = 0,
  4690. update = util.updateProperty,
  4691. asSize = util.option.asSize,
  4692. options = this.options,
  4693. orientation = this.getOption('orientation'),
  4694. defaultOptions = this.defaultOptions,
  4695. frame = this.frame;
  4696. if (!frame) {
  4697. frame = document.createElement('div');
  4698. frame.className = 'itemset';
  4699. var className = options.className;
  4700. if (className) {
  4701. util.addClassName(frame, util.option.asString(className));
  4702. }
  4703. // create background panel
  4704. var background = document.createElement('div');
  4705. background.className = 'background';
  4706. frame.appendChild(background);
  4707. this.dom.background = background;
  4708. // create foreground panel
  4709. var foreground = document.createElement('div');
  4710. foreground.className = 'foreground';
  4711. frame.appendChild(foreground);
  4712. this.dom.foreground = foreground;
  4713. // create axis panel
  4714. var axis = document.createElement('div');
  4715. axis.className = 'itemset-axis';
  4716. //frame.appendChild(axis);
  4717. this.dom.axis = axis;
  4718. this.frame = frame;
  4719. changed += 1;
  4720. }
  4721. if (!this.parent) {
  4722. throw new Error('Cannot repaint itemset: no parent attached');
  4723. }
  4724. var parentContainer = this.parent.getContainer();
  4725. if (!parentContainer) {
  4726. throw new Error('Cannot repaint itemset: parent has no container element');
  4727. }
  4728. if (!frame.parentNode) {
  4729. parentContainer.appendChild(frame);
  4730. changed += 1;
  4731. }
  4732. if (!this.dom.axis.parentNode) {
  4733. parentContainer.appendChild(this.dom.axis);
  4734. changed += 1;
  4735. }
  4736. // reposition frame
  4737. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4738. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4739. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4740. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4741. // reposition axis
  4742. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4743. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4744. if (orientation == 'bottom') {
  4745. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4746. }
  4747. else { // orientation == 'top'
  4748. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4749. }
  4750. this._updateConversion();
  4751. var me = this,
  4752. queue = this.queue,
  4753. itemsData = this.itemsData,
  4754. items = this.items,
  4755. dataOptions = {
  4756. // TODO: cleanup
  4757. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  4758. };
  4759. // show/hide added/changed/removed items
  4760. Object.keys(queue).forEach(function (id) {
  4761. //var entry = queue[id];
  4762. var action = queue[id];
  4763. var item = items[id];
  4764. //var item = entry.item;
  4765. //noinspection FallthroughInSwitchStatementJS
  4766. switch (action) {
  4767. case 'add':
  4768. case 'update':
  4769. var itemData = itemsData && itemsData.get(id, dataOptions);
  4770. if (itemData) {
  4771. var type = itemData.type ||
  4772. (itemData.start && itemData.end && 'range') ||
  4773. options.type ||
  4774. 'box';
  4775. var constructor = ItemSet.types[type];
  4776. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4777. if (item) {
  4778. // update item
  4779. if (!constructor || !(item instanceof constructor)) {
  4780. // item type has changed, hide and delete the item
  4781. changed += item.hide();
  4782. item = null;
  4783. }
  4784. else {
  4785. item.data = itemData; // TODO: create a method item.setData ?
  4786. changed++;
  4787. }
  4788. }
  4789. if (!item) {
  4790. // create item
  4791. if (constructor) {
  4792. item = new constructor(me, itemData, options, defaultOptions);
  4793. item.id = id;
  4794. changed++;
  4795. }
  4796. else {
  4797. throw new TypeError('Unknown item type "' + type + '"');
  4798. }
  4799. }
  4800. // force a repaint (not only a reposition)
  4801. item.repaint();
  4802. items[id] = item;
  4803. }
  4804. // update queue
  4805. delete queue[id];
  4806. break;
  4807. case 'remove':
  4808. if (item) {
  4809. // remove the item from the set selected items
  4810. if (item.selected) {
  4811. me._deselect(id);
  4812. }
  4813. // remove DOM of the item
  4814. changed += item.hide();
  4815. }
  4816. // update lists
  4817. delete items[id];
  4818. delete queue[id];
  4819. break;
  4820. default:
  4821. console.log('Error: unknown action "' + action + '"');
  4822. }
  4823. });
  4824. // reposition all items. Show items only when in the visible area
  4825. util.forEach(this.items, function (item) {
  4826. if (item.visible) {
  4827. changed += item.show();
  4828. item.reposition();
  4829. }
  4830. else {
  4831. changed += item.hide();
  4832. }
  4833. });
  4834. return (changed > 0);
  4835. };
  4836. /**
  4837. * Get the foreground container element
  4838. * @return {HTMLElement} foreground
  4839. */
  4840. ItemSet.prototype.getForeground = function getForeground() {
  4841. return this.dom.foreground;
  4842. };
  4843. /**
  4844. * Get the background container element
  4845. * @return {HTMLElement} background
  4846. */
  4847. ItemSet.prototype.getBackground = function getBackground() {
  4848. return this.dom.background;
  4849. };
  4850. /**
  4851. * Get the axis container element
  4852. * @return {HTMLElement} axis
  4853. */
  4854. ItemSet.prototype.getAxis = function getAxis() {
  4855. return this.dom.axis;
  4856. };
  4857. /**
  4858. * Reflow the component
  4859. * @return {Boolean} resized
  4860. */
  4861. ItemSet.prototype.reflow = function reflow () {
  4862. var changed = 0,
  4863. options = this.options,
  4864. marginAxis = options.margin && options.margin.axis || this.defaultOptions.margin.axis,
  4865. marginItem = options.margin && options.margin.item || this.defaultOptions.margin.item,
  4866. update = util.updateProperty,
  4867. asNumber = util.option.asNumber,
  4868. asSize = util.option.asSize,
  4869. frame = this.frame;
  4870. if (frame) {
  4871. this._updateConversion();
  4872. util.forEach(this.items, function (item) {
  4873. changed += item.reflow();
  4874. });
  4875. // TODO: stack.update should be triggered via an event, in stack itself
  4876. // TODO: only update the stack when there are changed items
  4877. this.stack.update();
  4878. var maxHeight = asNumber(options.maxHeight);
  4879. var fixedHeight = (asSize(options.height) != null);
  4880. var height;
  4881. if (fixedHeight) {
  4882. height = frame.offsetHeight;
  4883. }
  4884. else {
  4885. // height is not specified, determine the height from the height and positioned items
  4886. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4887. if (visibleItems.length) {
  4888. var min = visibleItems[0].top;
  4889. var max = visibleItems[0].top + visibleItems[0].height;
  4890. util.forEach(visibleItems, function (item) {
  4891. min = Math.min(min, item.top);
  4892. max = Math.max(max, (item.top + item.height));
  4893. });
  4894. height = (max - min) + marginAxis + marginItem;
  4895. }
  4896. else {
  4897. height = marginAxis + marginItem;
  4898. }
  4899. }
  4900. if (maxHeight != null) {
  4901. height = Math.min(height, maxHeight);
  4902. }
  4903. changed += update(this, 'height', height);
  4904. // calculate height from items
  4905. changed += update(this, 'top', frame.offsetTop);
  4906. changed += update(this, 'left', frame.offsetLeft);
  4907. changed += update(this, 'width', frame.offsetWidth);
  4908. }
  4909. else {
  4910. changed += 1;
  4911. }
  4912. return (changed > 0);
  4913. };
  4914. /**
  4915. * Hide this component from the DOM
  4916. * @return {Boolean} changed
  4917. */
  4918. ItemSet.prototype.hide = function hide() {
  4919. var changed = false;
  4920. // remove the DOM
  4921. if (this.frame && this.frame.parentNode) {
  4922. this.frame.parentNode.removeChild(this.frame);
  4923. changed = true;
  4924. }
  4925. if (this.dom.axis && this.dom.axis.parentNode) {
  4926. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4927. changed = true;
  4928. }
  4929. return changed;
  4930. };
  4931. /**
  4932. * Set items
  4933. * @param {vis.DataSet | null} items
  4934. */
  4935. ItemSet.prototype.setItems = function setItems(items) {
  4936. var me = this,
  4937. ids,
  4938. oldItemsData = this.itemsData;
  4939. // replace the dataset
  4940. if (!items) {
  4941. this.itemsData = null;
  4942. }
  4943. else if (items instanceof DataSet || items instanceof DataView) {
  4944. this.itemsData = items;
  4945. }
  4946. else {
  4947. throw new TypeError('Data must be an instance of DataSet');
  4948. }
  4949. if (oldItemsData) {
  4950. // unsubscribe from old dataset
  4951. util.forEach(this.listeners, function (callback, event) {
  4952. oldItemsData.unsubscribe(event, callback);
  4953. });
  4954. // remove all drawn items
  4955. ids = oldItemsData.getIds();
  4956. this._onRemove(ids);
  4957. }
  4958. if (this.itemsData) {
  4959. // subscribe to new dataset
  4960. var id = this.id;
  4961. util.forEach(this.listeners, function (callback, event) {
  4962. me.itemsData.subscribe(event, callback, id);
  4963. });
  4964. // draw all new items
  4965. ids = this.itemsData.getIds();
  4966. this._onAdd(ids);
  4967. }
  4968. };
  4969. /**
  4970. * Get the current items items
  4971. * @returns {vis.DataSet | null}
  4972. */
  4973. ItemSet.prototype.getItems = function getItems() {
  4974. return this.itemsData;
  4975. };
  4976. /**
  4977. * Handle updated items
  4978. * @param {Number[]} ids
  4979. * @private
  4980. */
  4981. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4982. this._toQueue('update', ids);
  4983. };
  4984. /**
  4985. * Handle changed items
  4986. * @param {Number[]} ids
  4987. * @private
  4988. */
  4989. ItemSet.prototype._onAdd = function _onAdd(ids) {
  4990. this._toQueue('add', ids);
  4991. };
  4992. /**
  4993. * Handle removed items
  4994. * @param {Number[]} ids
  4995. * @private
  4996. */
  4997. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4998. this._toQueue('remove', ids);
  4999. };
  5000. /**
  5001. * Put items in the queue to be added/updated/remove
  5002. * @param {String} action can be 'add', 'update', 'remove'
  5003. * @param {Number[]} ids
  5004. */
  5005. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  5006. var queue = this.queue;
  5007. ids.forEach(function (id) {
  5008. queue[id] = action;
  5009. });
  5010. if (this.controller) {
  5011. //this.requestReflow();
  5012. this.requestRepaint();
  5013. }
  5014. };
  5015. /**
  5016. * Calculate the scale and offset to convert a position on screen to the
  5017. * corresponding date and vice versa.
  5018. * After the method _updateConversion is executed once, the methods toTime
  5019. * and toScreen can be used.
  5020. * @private
  5021. */
  5022. ItemSet.prototype._updateConversion = function _updateConversion() {
  5023. var range = this.range;
  5024. if (!range) {
  5025. throw new Error('No range configured');
  5026. }
  5027. if (range.conversion) {
  5028. this.conversion = range.conversion(this.width);
  5029. }
  5030. else {
  5031. this.conversion = Range.conversion(range.start, range.end, this.width);
  5032. }
  5033. };
  5034. /**
  5035. * Convert a position on screen (pixels) to a datetime
  5036. * Before this method can be used, the method _updateConversion must be
  5037. * executed once.
  5038. * @param {int} x Position on the screen in pixels
  5039. * @return {Date} time The datetime the corresponds with given position x
  5040. */
  5041. ItemSet.prototype.toTime = function toTime(x) {
  5042. var conversion = this.conversion;
  5043. return new Date(x / conversion.scale + conversion.offset);
  5044. };
  5045. /**
  5046. * Convert a datetime (Date object) into a position on the screen
  5047. * Before this method can be used, the method _updateConversion must be
  5048. * executed once.
  5049. * @param {Date} time A date
  5050. * @return {int} x The position on the screen in pixels which corresponds
  5051. * with the given date.
  5052. */
  5053. ItemSet.prototype.toScreen = function toScreen(time) {
  5054. var conversion = this.conversion;
  5055. return (time.valueOf() - conversion.offset) * conversion.scale;
  5056. };
  5057. /**
  5058. * @constructor Item
  5059. * @param {ItemSet} parent
  5060. * @param {Object} data Object containing (optional) parameters type,
  5061. * start, end, content, group, className.
  5062. * @param {Object} [options] Options to set initial property values
  5063. * @param {Object} [defaultOptions] default options
  5064. * // TODO: describe available options
  5065. */
  5066. function Item (parent, data, options, defaultOptions) {
  5067. this.parent = parent;
  5068. this.data = data;
  5069. this.dom = null;
  5070. this.options = options || {};
  5071. this.defaultOptions = defaultOptions || {};
  5072. this.selected = false;
  5073. this.visible = false;
  5074. this.top = 0;
  5075. this.left = 0;
  5076. this.width = 0;
  5077. this.height = 0;
  5078. }
  5079. /**
  5080. * Select current item
  5081. */
  5082. Item.prototype.select = function select() {
  5083. this.selected = true;
  5084. if (this.visible) this.repaint();
  5085. };
  5086. /**
  5087. * Unselect current item
  5088. */
  5089. Item.prototype.unselect = function unselect() {
  5090. this.selected = false;
  5091. if (this.visible) this.repaint();
  5092. };
  5093. /**
  5094. * Show the Item in the DOM (when not already visible)
  5095. * @return {Boolean} changed
  5096. */
  5097. Item.prototype.show = function show() {
  5098. return false;
  5099. };
  5100. /**
  5101. * Hide the Item from the DOM (when visible)
  5102. * @return {Boolean} changed
  5103. */
  5104. Item.prototype.hide = function hide() {
  5105. return false;
  5106. };
  5107. /**
  5108. * Repaint the item
  5109. * @return {Boolean} changed
  5110. */
  5111. Item.prototype.repaint = function repaint() {
  5112. // should be implemented by the item
  5113. return false;
  5114. };
  5115. /**
  5116. * Reflow the item
  5117. * @return {Boolean} resized
  5118. */
  5119. Item.prototype.reflow = function reflow() {
  5120. // should be implemented by the item
  5121. return false;
  5122. };
  5123. /**
  5124. * Return the items width
  5125. * @return {Integer} width
  5126. */
  5127. Item.prototype.getWidth = function getWidth() {
  5128. return this.width;
  5129. }
  5130. /**
  5131. * @constructor ItemBox
  5132. * @extends Item
  5133. * @param {ItemSet} parent
  5134. * @param {Object} data Object containing parameters start
  5135. * content, className.
  5136. * @param {Object} [options] Options to set initial property values
  5137. * @param {Object} [defaultOptions] default options
  5138. * // TODO: describe available options
  5139. */
  5140. function ItemBox (parent, data, options, defaultOptions) {
  5141. this.props = {
  5142. dot: {
  5143. left: 0,
  5144. top: 0,
  5145. width: 0,
  5146. height: 0
  5147. },
  5148. line: {
  5149. top: 0,
  5150. left: 0,
  5151. width: 0,
  5152. height: 0
  5153. }
  5154. };
  5155. Item.call(this, parent, data, options, defaultOptions);
  5156. }
  5157. ItemBox.prototype = new Item (null, null);
  5158. /**
  5159. * Repaint the item
  5160. * @return {Boolean} changed
  5161. */
  5162. ItemBox.prototype.repaint = function repaint() {
  5163. // TODO: make an efficient repaint
  5164. var changed = false;
  5165. var dom = this.dom;
  5166. if (!dom) {
  5167. this._create();
  5168. dom = this.dom;
  5169. changed = true;
  5170. }
  5171. if (dom) {
  5172. if (!this.parent) {
  5173. throw new Error('Cannot repaint item: no parent attached');
  5174. }
  5175. if (!dom.box.parentNode) {
  5176. var foreground = this.parent.getForeground();
  5177. if (!foreground) {
  5178. throw new Error('Cannot repaint time axis: ' +
  5179. 'parent has no foreground container element');
  5180. }
  5181. foreground.appendChild(dom.box);
  5182. changed = true;
  5183. }
  5184. if (!dom.line.parentNode) {
  5185. var background = this.parent.getBackground();
  5186. if (!background) {
  5187. throw new Error('Cannot repaint time axis: ' +
  5188. 'parent has no background container element');
  5189. }
  5190. background.appendChild(dom.line);
  5191. changed = true;
  5192. }
  5193. if (!dom.dot.parentNode) {
  5194. var axis = this.parent.getAxis();
  5195. if (!background) {
  5196. throw new Error('Cannot repaint time axis: ' +
  5197. 'parent has no axis container element');
  5198. }
  5199. axis.appendChild(dom.dot);
  5200. changed = true;
  5201. }
  5202. // update contents
  5203. if (this.data.content != this.content) {
  5204. this.content = this.data.content;
  5205. if (this.content instanceof Element) {
  5206. dom.content.innerHTML = '';
  5207. dom.content.appendChild(this.content);
  5208. }
  5209. else if (this.data.content != undefined) {
  5210. dom.content.innerHTML = this.content;
  5211. }
  5212. else {
  5213. throw new Error('Property "content" missing in item ' + this.data.id);
  5214. }
  5215. changed = true;
  5216. }
  5217. // update class
  5218. var className = (this.data.className? ' ' + this.data.className : '') +
  5219. (this.selected ? ' selected' : '');
  5220. if (this.className != className) {
  5221. this.className = className;
  5222. dom.box.className = 'item box' + className;
  5223. dom.line.className = 'item line' + className;
  5224. dom.dot.className = 'item dot' + className;
  5225. changed = true;
  5226. }
  5227. }
  5228. return changed;
  5229. };
  5230. /**
  5231. * Show the item in the DOM (when not already visible). The items DOM will
  5232. * be created when needed.
  5233. * @return {Boolean} changed
  5234. */
  5235. ItemBox.prototype.show = function show() {
  5236. if (!this.dom || !this.dom.box.parentNode) {
  5237. return this.repaint();
  5238. }
  5239. else {
  5240. return false;
  5241. }
  5242. };
  5243. /**
  5244. * Hide the item from the DOM (when visible)
  5245. * @return {Boolean} changed
  5246. */
  5247. ItemBox.prototype.hide = function hide() {
  5248. var changed = false,
  5249. dom = this.dom;
  5250. if (dom) {
  5251. if (dom.box.parentNode) {
  5252. dom.box.parentNode.removeChild(dom.box);
  5253. changed = true;
  5254. }
  5255. if (dom.line.parentNode) {
  5256. dom.line.parentNode.removeChild(dom.line);
  5257. }
  5258. if (dom.dot.parentNode) {
  5259. dom.dot.parentNode.removeChild(dom.dot);
  5260. }
  5261. }
  5262. return changed;
  5263. };
  5264. /**
  5265. * Reflow the item: calculate its actual size and position from the DOM
  5266. * @return {boolean} resized returns true if the axis is resized
  5267. * @override
  5268. */
  5269. ItemBox.prototype.reflow = function reflow() {
  5270. var changed = 0,
  5271. update,
  5272. dom,
  5273. props,
  5274. options,
  5275. margin,
  5276. start,
  5277. align,
  5278. orientation,
  5279. top,
  5280. left,
  5281. data,
  5282. range;
  5283. if (this.data.start == undefined) {
  5284. throw new Error('Property "start" missing in item ' + this.data.id);
  5285. }
  5286. data = this.data;
  5287. range = this.parent && this.parent.range;
  5288. if (data && range) {
  5289. // TODO: account for the width of the item
  5290. var interval = (range.end - range.start);
  5291. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  5292. }
  5293. else {
  5294. this.visible = false;
  5295. }
  5296. if (this.visible) {
  5297. dom = this.dom;
  5298. if (dom) {
  5299. update = util.updateProperty;
  5300. props = this.props;
  5301. options = this.options;
  5302. start = this.parent.toScreen(this.data.start);
  5303. align = options.align || this.defaultOptions.align;
  5304. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5305. orientation = options.orientation || this.defaultOptions.orientation;
  5306. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5307. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5308. changed += update(props.line, 'width', dom.line.offsetWidth);
  5309. changed += update(props.line, 'height', dom.line.offsetHeight);
  5310. changed += update(props.line, 'top', dom.line.offsetTop);
  5311. changed += update(this, 'width', dom.box.offsetWidth);
  5312. changed += update(this, 'height', dom.box.offsetHeight);
  5313. if (align == 'right') {
  5314. left = start - this.width;
  5315. }
  5316. else if (align == 'left') {
  5317. left = start;
  5318. }
  5319. else {
  5320. // default or 'center'
  5321. left = start - this.width / 2;
  5322. }
  5323. changed += update(this, 'left', left);
  5324. changed += update(props.line, 'left', start - props.line.width / 2);
  5325. changed += update(props.dot, 'left', start - props.dot.width / 2);
  5326. changed += update(props.dot, 'top', -props.dot.height / 2);
  5327. if (orientation == 'top') {
  5328. top = margin;
  5329. changed += update(this, 'top', top);
  5330. }
  5331. else {
  5332. // default or 'bottom'
  5333. var parentHeight = this.parent.height;
  5334. top = parentHeight - this.height - margin;
  5335. changed += update(this, 'top', top);
  5336. }
  5337. }
  5338. else {
  5339. changed += 1;
  5340. }
  5341. }
  5342. return (changed > 0);
  5343. };
  5344. /**
  5345. * Create an items DOM
  5346. * @private
  5347. */
  5348. ItemBox.prototype._create = function _create() {
  5349. var dom = this.dom;
  5350. if (!dom) {
  5351. this.dom = dom = {};
  5352. // create the box
  5353. dom.box = document.createElement('DIV');
  5354. // className is updated in repaint()
  5355. // contents box (inside the background box). used for making margins
  5356. dom.content = document.createElement('DIV');
  5357. dom.content.className = 'content';
  5358. dom.box.appendChild(dom.content);
  5359. // line to axis
  5360. dom.line = document.createElement('DIV');
  5361. dom.line.className = 'line';
  5362. // dot on axis
  5363. dom.dot = document.createElement('DIV');
  5364. dom.dot.className = 'dot';
  5365. }
  5366. };
  5367. /**
  5368. * Reposition the item, recalculate its left, top, and width, using the current
  5369. * range and size of the items itemset
  5370. * @override
  5371. */
  5372. ItemBox.prototype.reposition = function reposition() {
  5373. var dom = this.dom,
  5374. props = this.props,
  5375. orientation = this.options.orientation || this.defaultOptions.orientation;
  5376. if (dom) {
  5377. var box = dom.box,
  5378. line = dom.line,
  5379. dot = dom.dot;
  5380. box.style.left = this.left + 'px';
  5381. box.style.top = this.top + 'px';
  5382. line.style.left = props.line.left + 'px';
  5383. if (orientation == 'top') {
  5384. line.style.top = 0 + 'px';
  5385. line.style.height = this.top + 'px';
  5386. }
  5387. else {
  5388. // orientation 'bottom'
  5389. line.style.top = (this.top + this.height) + 'px';
  5390. line.style.height = Math.max(this.parent.height - this.top - this.height +
  5391. this.props.dot.height / 2, 0) + 'px';
  5392. }
  5393. dot.style.left = props.dot.left + 'px';
  5394. dot.style.top = props.dot.top + 'px';
  5395. }
  5396. };
  5397. /**
  5398. * @constructor ItemPoint
  5399. * @extends Item
  5400. * @param {ItemSet} parent
  5401. * @param {Object} data Object containing parameters start
  5402. * content, className.
  5403. * @param {Object} [options] Options to set initial property values
  5404. * @param {Object} [defaultOptions] default options
  5405. * // TODO: describe available options
  5406. */
  5407. function ItemPoint (parent, data, options, defaultOptions) {
  5408. this.props = {
  5409. dot: {
  5410. top: 0,
  5411. width: 0,
  5412. height: 0
  5413. },
  5414. content: {
  5415. height: 0,
  5416. marginLeft: 0
  5417. }
  5418. };
  5419. Item.call(this, parent, data, options, defaultOptions);
  5420. }
  5421. ItemPoint.prototype = new Item (null, null);
  5422. /**
  5423. * Repaint the item
  5424. * @return {Boolean} changed
  5425. */
  5426. ItemPoint.prototype.repaint = function repaint() {
  5427. // TODO: make an efficient repaint
  5428. var changed = false;
  5429. var dom = this.dom;
  5430. if (!dom) {
  5431. this._create();
  5432. dom = this.dom;
  5433. changed = true;
  5434. }
  5435. if (dom) {
  5436. if (!this.parent) {
  5437. throw new Error('Cannot repaint item: no parent attached');
  5438. }
  5439. var foreground = this.parent.getForeground();
  5440. if (!foreground) {
  5441. throw new Error('Cannot repaint time axis: ' +
  5442. 'parent has no foreground container element');
  5443. }
  5444. if (!dom.point.parentNode) {
  5445. foreground.appendChild(dom.point);
  5446. foreground.appendChild(dom.point);
  5447. changed = true;
  5448. }
  5449. // update contents
  5450. if (this.data.content != this.content) {
  5451. this.content = this.data.content;
  5452. if (this.content instanceof Element) {
  5453. dom.content.innerHTML = '';
  5454. dom.content.appendChild(this.content);
  5455. }
  5456. else if (this.data.content != undefined) {
  5457. dom.content.innerHTML = this.content;
  5458. }
  5459. else {
  5460. throw new Error('Property "content" missing in item ' + this.data.id);
  5461. }
  5462. changed = true;
  5463. }
  5464. // update class
  5465. var className = (this.data.className? ' ' + this.data.className : '') +
  5466. (this.selected ? ' selected' : '');
  5467. if (this.className != className) {
  5468. this.className = className;
  5469. dom.point.className = 'item point' + className;
  5470. changed = true;
  5471. }
  5472. }
  5473. return changed;
  5474. };
  5475. /**
  5476. * Show the item in the DOM (when not already visible). The items DOM will
  5477. * be created when needed.
  5478. * @return {Boolean} changed
  5479. */
  5480. ItemPoint.prototype.show = function show() {
  5481. if (!this.dom || !this.dom.point.parentNode) {
  5482. return this.repaint();
  5483. }
  5484. else {
  5485. return false;
  5486. }
  5487. };
  5488. /**
  5489. * Hide the item from the DOM (when visible)
  5490. * @return {Boolean} changed
  5491. */
  5492. ItemPoint.prototype.hide = function hide() {
  5493. var changed = false,
  5494. dom = this.dom;
  5495. if (dom) {
  5496. if (dom.point.parentNode) {
  5497. dom.point.parentNode.removeChild(dom.point);
  5498. changed = true;
  5499. }
  5500. }
  5501. return changed;
  5502. };
  5503. /**
  5504. * Reflow the item: calculate its actual size from the DOM
  5505. * @return {boolean} resized returns true if the axis is resized
  5506. * @override
  5507. */
  5508. ItemPoint.prototype.reflow = function reflow() {
  5509. var changed = 0,
  5510. update,
  5511. dom,
  5512. props,
  5513. options,
  5514. margin,
  5515. orientation,
  5516. start,
  5517. top,
  5518. data,
  5519. range;
  5520. if (this.data.start == undefined) {
  5521. throw new Error('Property "start" missing in item ' + this.data.id);
  5522. }
  5523. data = this.data;
  5524. range = this.parent && this.parent.range;
  5525. if (data && range) {
  5526. // TODO: account for the width of the item
  5527. var interval = (range.end - range.start);
  5528. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  5529. }
  5530. else {
  5531. this.visible = false;
  5532. }
  5533. if (this.visible) {
  5534. dom = this.dom;
  5535. if (dom) {
  5536. update = util.updateProperty;
  5537. props = this.props;
  5538. options = this.options;
  5539. orientation = options.orientation || this.defaultOptions.orientation;
  5540. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5541. start = this.parent.toScreen(this.data.start);
  5542. changed += update(this, 'width', dom.point.offsetWidth);
  5543. changed += update(this, 'height', dom.point.offsetHeight);
  5544. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5545. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5546. changed += update(props.content, 'height', dom.content.offsetHeight);
  5547. if (orientation == 'top') {
  5548. top = margin;
  5549. }
  5550. else {
  5551. // default or 'bottom'
  5552. var parentHeight = this.parent.height;
  5553. top = Math.max(parentHeight - this.height - margin, 0);
  5554. }
  5555. changed += update(this, 'top', top);
  5556. changed += update(this, 'left', start - props.dot.width / 2);
  5557. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5558. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5559. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5560. }
  5561. else {
  5562. changed += 1;
  5563. }
  5564. }
  5565. return (changed > 0);
  5566. };
  5567. /**
  5568. * Create an items DOM
  5569. * @private
  5570. */
  5571. ItemPoint.prototype._create = function _create() {
  5572. var dom = this.dom;
  5573. if (!dom) {
  5574. this.dom = dom = {};
  5575. // background box
  5576. dom.point = document.createElement('div');
  5577. // className is updated in repaint()
  5578. // contents box, right from the dot
  5579. dom.content = document.createElement('div');
  5580. dom.content.className = 'content';
  5581. dom.point.appendChild(dom.content);
  5582. // dot at start
  5583. dom.dot = document.createElement('div');
  5584. dom.dot.className = 'dot';
  5585. dom.point.appendChild(dom.dot);
  5586. }
  5587. };
  5588. /**
  5589. * Reposition the item, recalculate its left, top, and width, using the current
  5590. * range and size of the items itemset
  5591. * @override
  5592. */
  5593. ItemPoint.prototype.reposition = function reposition() {
  5594. var dom = this.dom,
  5595. props = this.props;
  5596. if (dom) {
  5597. dom.point.style.top = this.top + 'px';
  5598. dom.point.style.left = this.left + 'px';
  5599. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5600. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5601. dom.dot.style.top = props.dot.top + 'px';
  5602. }
  5603. };
  5604. /**
  5605. * @constructor ItemRange
  5606. * @extends Item
  5607. * @param {ItemSet} parent
  5608. * @param {Object} data Object containing parameters start, end
  5609. * content, className.
  5610. * @param {Object} [options] Options to set initial property values
  5611. * @param {Object} [defaultOptions] default options
  5612. * // TODO: describe available options
  5613. */
  5614. function ItemRange (parent, data, options, defaultOptions) {
  5615. this.props = {
  5616. content: {
  5617. left: 0,
  5618. width: 0
  5619. }
  5620. };
  5621. Item.call(this, parent, data, options, defaultOptions);
  5622. }
  5623. ItemRange.prototype = new Item (null, null);
  5624. /**
  5625. * Repaint the item
  5626. * @return {Boolean} changed
  5627. */
  5628. ItemRange.prototype.repaint = function repaint() {
  5629. // TODO: make an efficient repaint
  5630. var changed = false;
  5631. var dom = this.dom;
  5632. if (!dom) {
  5633. this._create();
  5634. dom = this.dom;
  5635. changed = true;
  5636. }
  5637. if (dom) {
  5638. if (!this.parent) {
  5639. throw new Error('Cannot repaint item: no parent attached');
  5640. }
  5641. var foreground = this.parent.getForeground();
  5642. if (!foreground) {
  5643. throw new Error('Cannot repaint time axis: ' +
  5644. 'parent has no foreground container element');
  5645. }
  5646. if (!dom.box.parentNode) {
  5647. foreground.appendChild(dom.box);
  5648. changed = true;
  5649. }
  5650. // update content
  5651. if (this.data.content != this.content) {
  5652. this.content = this.data.content;
  5653. if (this.content instanceof Element) {
  5654. dom.content.innerHTML = '';
  5655. dom.content.appendChild(this.content);
  5656. }
  5657. else if (this.data.content != undefined) {
  5658. dom.content.innerHTML = this.content;
  5659. }
  5660. else {
  5661. throw new Error('Property "content" missing in item ' + this.data.id);
  5662. }
  5663. changed = true;
  5664. }
  5665. // update class
  5666. var className = (this.data.className? ' ' + this.data.className : '') +
  5667. (this.selected ? ' selected' : '');
  5668. if (this.className != className) {
  5669. this.className = className;
  5670. dom.box.className = 'item range' + className;
  5671. changed = true;
  5672. }
  5673. }
  5674. return changed;
  5675. };
  5676. /**
  5677. * Show the item in the DOM (when not already visible). The items DOM will
  5678. * be created when needed.
  5679. * @return {Boolean} changed
  5680. */
  5681. ItemRange.prototype.show = function show() {
  5682. if (!this.dom || !this.dom.box.parentNode) {
  5683. return this.repaint();
  5684. }
  5685. else {
  5686. return false;
  5687. }
  5688. };
  5689. /**
  5690. * Hide the item from the DOM (when visible)
  5691. * @return {Boolean} changed
  5692. */
  5693. ItemRange.prototype.hide = function hide() {
  5694. var changed = false,
  5695. dom = this.dom;
  5696. if (dom) {
  5697. if (dom.box.parentNode) {
  5698. dom.box.parentNode.removeChild(dom.box);
  5699. changed = true;
  5700. }
  5701. }
  5702. return changed;
  5703. };
  5704. /**
  5705. * Reflow the item: calculate its actual size from the DOM
  5706. * @return {boolean} resized returns true if the axis is resized
  5707. * @override
  5708. */
  5709. ItemRange.prototype.reflow = function reflow() {
  5710. var changed = 0,
  5711. dom,
  5712. props,
  5713. options,
  5714. margin,
  5715. padding,
  5716. parent,
  5717. start,
  5718. end,
  5719. data,
  5720. range,
  5721. update,
  5722. box,
  5723. parentWidth,
  5724. contentLeft,
  5725. orientation,
  5726. top;
  5727. if (this.data.start == undefined) {
  5728. throw new Error('Property "start" missing in item ' + this.data.id);
  5729. }
  5730. if (this.data.end == undefined) {
  5731. throw new Error('Property "end" missing in item ' + this.data.id);
  5732. }
  5733. data = this.data;
  5734. range = this.parent && this.parent.range;
  5735. if (data && range) {
  5736. // TODO: account for the width of the item. Take some margin
  5737. this.visible = (data.start < range.end) && (data.end > range.start);
  5738. }
  5739. else {
  5740. this.visible = false;
  5741. }
  5742. if (this.visible) {
  5743. dom = this.dom;
  5744. if (dom) {
  5745. props = this.props;
  5746. options = this.options;
  5747. parent = this.parent;
  5748. start = parent.toScreen(this.data.start);
  5749. end = parent.toScreen(this.data.end);
  5750. update = util.updateProperty;
  5751. box = dom.box;
  5752. parentWidth = parent.width;
  5753. orientation = options.orientation || this.defaultOptions.orientation;
  5754. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5755. padding = options.padding || this.defaultOptions.padding;
  5756. changed += update(props.content, 'width', dom.content.offsetWidth);
  5757. changed += update(this, 'height', box.offsetHeight);
  5758. // limit the width of the this, as browsers cannot draw very wide divs
  5759. if (start < -parentWidth) {
  5760. start = -parentWidth;
  5761. }
  5762. if (end > 2 * parentWidth) {
  5763. end = 2 * parentWidth;
  5764. }
  5765. // when range exceeds left of the window, position the contents at the left of the visible area
  5766. if (start < 0) {
  5767. contentLeft = Math.min(-start,
  5768. (end - start - props.content.width - 2 * padding));
  5769. // TODO: remove the need for options.padding. it's terrible.
  5770. }
  5771. else {
  5772. contentLeft = 0;
  5773. }
  5774. changed += update(props.content, 'left', contentLeft);
  5775. if (orientation == 'top') {
  5776. top = margin;
  5777. changed += update(this, 'top', top);
  5778. }
  5779. else {
  5780. // default or 'bottom'
  5781. top = parent.height - this.height - margin;
  5782. changed += update(this, 'top', top);
  5783. }
  5784. changed += update(this, 'left', start);
  5785. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  5786. }
  5787. else {
  5788. changed += 1;
  5789. }
  5790. }
  5791. return (changed > 0);
  5792. };
  5793. /**
  5794. * Create an items DOM
  5795. * @private
  5796. */
  5797. ItemRange.prototype._create = function _create() {
  5798. var dom = this.dom;
  5799. if (!dom) {
  5800. this.dom = dom = {};
  5801. // background box
  5802. dom.box = document.createElement('div');
  5803. // className is updated in repaint()
  5804. // contents box
  5805. dom.content = document.createElement('div');
  5806. dom.content.className = 'content';
  5807. dom.box.appendChild(dom.content);
  5808. }
  5809. };
  5810. /**
  5811. * Reposition the item, recalculate its left, top, and width, using the current
  5812. * range and size of the items itemset
  5813. * @override
  5814. */
  5815. ItemRange.prototype.reposition = function reposition() {
  5816. var dom = this.dom,
  5817. props = this.props;
  5818. if (dom) {
  5819. dom.box.style.top = this.top + 'px';
  5820. dom.box.style.left = this.left + 'px';
  5821. dom.box.style.width = this.width + 'px';
  5822. dom.content.style.left = props.content.left + 'px';
  5823. }
  5824. };
  5825. /**
  5826. * @constructor ItemRangeOverflow
  5827. * @extends ItemRange
  5828. * @param {ItemSet} parent
  5829. * @param {Object} data Object containing parameters start, end
  5830. * content, className.
  5831. * @param {Object} [options] Options to set initial property values
  5832. * @param {Object} [defaultOptions] default options
  5833. * // TODO: describe available options
  5834. */
  5835. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  5836. this.props = {
  5837. content: {
  5838. left: 0,
  5839. width: 0
  5840. }
  5841. };
  5842. ItemRange.call(this, parent, data, options, defaultOptions);
  5843. }
  5844. ItemRangeOverflow.prototype = new ItemRange (null, null);
  5845. /**
  5846. * Repaint the item
  5847. * @return {Boolean} changed
  5848. */
  5849. ItemRangeOverflow.prototype.repaint = function repaint() {
  5850. // TODO: make an efficient repaint
  5851. var changed = false;
  5852. var dom = this.dom;
  5853. if (!dom) {
  5854. this._create();
  5855. dom = this.dom;
  5856. changed = true;
  5857. }
  5858. if (dom) {
  5859. if (!this.parent) {
  5860. throw new Error('Cannot repaint item: no parent attached');
  5861. }
  5862. var foreground = this.parent.getForeground();
  5863. if (!foreground) {
  5864. throw new Error('Cannot repaint time axis: ' +
  5865. 'parent has no foreground container element');
  5866. }
  5867. if (!dom.box.parentNode) {
  5868. foreground.appendChild(dom.box);
  5869. changed = true;
  5870. }
  5871. // update content
  5872. if (this.data.content != this.content) {
  5873. this.content = this.data.content;
  5874. if (this.content instanceof Element) {
  5875. dom.content.innerHTML = '';
  5876. dom.content.appendChild(this.content);
  5877. }
  5878. else if (this.data.content != undefined) {
  5879. dom.content.innerHTML = this.content;
  5880. }
  5881. else {
  5882. throw new Error('Property "content" missing in item ' + this.data.id);
  5883. }
  5884. changed = true;
  5885. }
  5886. // update class
  5887. var className = this.data.className ? (' ' + this.data.className) : '';
  5888. if (this.className != className) {
  5889. this.className = className;
  5890. dom.box.className = 'item rangeoverflow' + className;
  5891. changed = true;
  5892. }
  5893. }
  5894. return changed;
  5895. };
  5896. /**
  5897. * Return the items width
  5898. * @return {Number} width
  5899. */
  5900. ItemRangeOverflow.prototype.getWidth = function getWidth() {
  5901. if (this.props.content !== undefined && this.width < this.props.content.width)
  5902. return this.props.content.width;
  5903. else
  5904. return this.width;
  5905. };
  5906. /**
  5907. * @constructor Group
  5908. * @param {GroupSet} parent
  5909. * @param {Number | String} groupId
  5910. * @param {Object} [options] Options to set initial property values
  5911. * // TODO: describe available options
  5912. * @extends Component
  5913. */
  5914. function Group (parent, groupId, options) {
  5915. this.id = util.randomUUID();
  5916. this.parent = parent;
  5917. this.groupId = groupId;
  5918. this.itemset = null; // ItemSet
  5919. this.options = options || {};
  5920. this.options.top = 0;
  5921. this.props = {
  5922. label: {
  5923. width: 0,
  5924. height: 0
  5925. }
  5926. };
  5927. this.top = 0;
  5928. this.left = 0;
  5929. this.width = 0;
  5930. this.height = 0;
  5931. }
  5932. Group.prototype = new Component();
  5933. // TODO: comment
  5934. Group.prototype.setOptions = Component.prototype.setOptions;
  5935. /**
  5936. * Get the container element of the panel, which can be used by a child to
  5937. * add its own widgets.
  5938. * @returns {HTMLElement} container
  5939. */
  5940. Group.prototype.getContainer = function () {
  5941. return this.parent.getContainer();
  5942. };
  5943. /**
  5944. * Set item set for the group. The group will create a view on the itemset,
  5945. * filtered by the groups id.
  5946. * @param {DataSet | DataView} items
  5947. */
  5948. Group.prototype.setItems = function setItems(items) {
  5949. if (this.itemset) {
  5950. // remove current item set
  5951. this.itemset.hide();
  5952. this.itemset.setItems();
  5953. this.parent.controller.remove(this.itemset);
  5954. this.itemset = null;
  5955. }
  5956. if (items) {
  5957. var groupId = this.groupId;
  5958. var itemsetOptions = Object.create(this.options);
  5959. this.itemset = new ItemSet(this, null, itemsetOptions);
  5960. this.itemset.setRange(this.parent.range);
  5961. this.view = new DataView(items, {
  5962. filter: function (item) {
  5963. return item.group == groupId;
  5964. }
  5965. });
  5966. this.itemset.setItems(this.view);
  5967. this.parent.controller.add(this.itemset);
  5968. }
  5969. };
  5970. /**
  5971. * Change the item selection, and/or get currently selected items
  5972. * @param {Array} [ids] An array with zero or more ids of the items to be selected.
  5973. * @return {Array} ids The ids of the selected items
  5974. */
  5975. Group.prototype.select = function select(ids) {
  5976. return this.itemset ? this.itemset.select(ids) : [];
  5977. };
  5978. /**
  5979. * Repaint the item
  5980. * @return {Boolean} changed
  5981. */
  5982. Group.prototype.repaint = function repaint() {
  5983. return false;
  5984. };
  5985. /**
  5986. * Reflow the item
  5987. * @return {Boolean} resized
  5988. */
  5989. Group.prototype.reflow = function reflow() {
  5990. var changed = 0,
  5991. update = util.updateProperty;
  5992. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  5993. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  5994. // TODO: reckon with the height of the group label
  5995. if (this.label) {
  5996. var inner = this.label.firstChild;
  5997. changed += update(this.props.label, 'width', inner.clientWidth);
  5998. changed += update(this.props.label, 'height', inner.clientHeight);
  5999. }
  6000. else {
  6001. changed += update(this.props.label, 'width', 0);
  6002. changed += update(this.props.label, 'height', 0);
  6003. }
  6004. return (changed > 0);
  6005. };
  6006. /**
  6007. * An GroupSet holds a set of groups
  6008. * @param {Component} parent
  6009. * @param {Component[]} [depends] Components on which this components depends
  6010. * (except for the parent)
  6011. * @param {Object} [options] See GroupSet.setOptions for the available
  6012. * options.
  6013. * @constructor GroupSet
  6014. * @extends Panel
  6015. */
  6016. function GroupSet(parent, depends, options) {
  6017. this.id = util.randomUUID();
  6018. this.parent = parent;
  6019. this.depends = depends;
  6020. this.options = options || {};
  6021. this.range = null; // Range or Object {start: number, end: number}
  6022. this.itemsData = null; // DataSet with items
  6023. this.groupsData = null; // DataSet with groups
  6024. this.groups = {}; // map with groups
  6025. this.dom = {};
  6026. this.props = {
  6027. labels: {
  6028. width: 0
  6029. }
  6030. };
  6031. // TODO: implement right orientation of the labels
  6032. // changes in groups are queued key/value map containing id/action
  6033. this.queue = {};
  6034. var me = this;
  6035. this.listeners = {
  6036. 'add': function (event, params) {
  6037. me._onAdd(params.items);
  6038. },
  6039. 'update': function (event, params) {
  6040. me._onUpdate(params.items);
  6041. },
  6042. 'remove': function (event, params) {
  6043. me._onRemove(params.items);
  6044. }
  6045. };
  6046. }
  6047. GroupSet.prototype = new Panel();
  6048. /**
  6049. * Set options for the GroupSet. Existing options will be extended/overwritten.
  6050. * @param {Object} [options] The following options are available:
  6051. * {String | function} groupsOrder
  6052. * TODO: describe options
  6053. */
  6054. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  6055. GroupSet.prototype.setRange = function (range) {
  6056. // TODO: implement setRange
  6057. };
  6058. /**
  6059. * Set items
  6060. * @param {vis.DataSet | null} items
  6061. */
  6062. GroupSet.prototype.setItems = function setItems(items) {
  6063. this.itemsData = items;
  6064. for (var id in this.groups) {
  6065. if (this.groups.hasOwnProperty(id)) {
  6066. var group = this.groups[id];
  6067. group.setItems(items);
  6068. }
  6069. }
  6070. };
  6071. /**
  6072. * Get items
  6073. * @return {vis.DataSet | null} items
  6074. */
  6075. GroupSet.prototype.getItems = function getItems() {
  6076. return this.itemsData;
  6077. };
  6078. /**
  6079. * Set range (start and end).
  6080. * @param {Range | Object} range A Range or an object containing start and end.
  6081. */
  6082. GroupSet.prototype.setRange = function setRange(range) {
  6083. this.range = range;
  6084. };
  6085. /**
  6086. * Set groups
  6087. * @param {vis.DataSet} groups
  6088. */
  6089. GroupSet.prototype.setGroups = function setGroups(groups) {
  6090. var me = this,
  6091. ids;
  6092. // unsubscribe from current dataset
  6093. if (this.groupsData) {
  6094. util.forEach(this.listeners, function (callback, event) {
  6095. me.groupsData.unsubscribe(event, callback);
  6096. });
  6097. // remove all drawn groups
  6098. ids = this.groupsData.getIds();
  6099. this._onRemove(ids);
  6100. }
  6101. // replace the dataset
  6102. if (!groups) {
  6103. this.groupsData = null;
  6104. }
  6105. else if (groups instanceof DataSet) {
  6106. this.groupsData = groups;
  6107. }
  6108. else {
  6109. this.groupsData = new DataSet({
  6110. convert: {
  6111. start: 'Date',
  6112. end: 'Date'
  6113. }
  6114. });
  6115. this.groupsData.add(groups);
  6116. }
  6117. if (this.groupsData) {
  6118. // subscribe to new dataset
  6119. var id = this.id;
  6120. util.forEach(this.listeners, function (callback, event) {
  6121. me.groupsData.subscribe(event, callback, id);
  6122. });
  6123. // draw all new groups
  6124. ids = this.groupsData.getIds();
  6125. this._onAdd(ids);
  6126. }
  6127. };
  6128. /**
  6129. * Get groups
  6130. * @return {vis.DataSet | null} groups
  6131. */
  6132. GroupSet.prototype.getGroups = function getGroups() {
  6133. return this.groupsData;
  6134. };
  6135. /**
  6136. * Change the item selection, and/or get currently selected items
  6137. * @param {Array} [ids] An array with zero or more ids of the items to be selected.
  6138. * @return {Array} ids The ids of the selected items
  6139. */
  6140. GroupSet.prototype.select = function select(ids) {
  6141. var selection = [],
  6142. groups = this.groups;
  6143. // iterate over each of the groups
  6144. for (var id in groups) {
  6145. if (groups.hasOwnProperty(id)) {
  6146. var group = groups[id];
  6147. selection = selection.concat(group.select(ids));
  6148. }
  6149. }
  6150. return selection;
  6151. };
  6152. /**
  6153. * Repaint the component
  6154. * @return {Boolean} changed
  6155. */
  6156. GroupSet.prototype.repaint = function repaint() {
  6157. var changed = 0,
  6158. i, id, group, label,
  6159. update = util.updateProperty,
  6160. asSize = util.option.asSize,
  6161. asElement = util.option.asElement,
  6162. options = this.options,
  6163. frame = this.dom.frame,
  6164. labels = this.dom.labels,
  6165. labelSet = this.dom.labelSet;
  6166. // create frame
  6167. if (!this.parent) {
  6168. throw new Error('Cannot repaint groupset: no parent attached');
  6169. }
  6170. var parentContainer = this.parent.getContainer();
  6171. if (!parentContainer) {
  6172. throw new Error('Cannot repaint groupset: parent has no container element');
  6173. }
  6174. if (!frame) {
  6175. frame = document.createElement('div');
  6176. frame.className = 'groupset';
  6177. this.dom.frame = frame;
  6178. var className = options.className;
  6179. if (className) {
  6180. util.addClassName(frame, util.option.asString(className));
  6181. }
  6182. changed += 1;
  6183. }
  6184. if (!frame.parentNode) {
  6185. parentContainer.appendChild(frame);
  6186. changed += 1;
  6187. }
  6188. // create labels
  6189. var labelContainer = asElement(options.labelContainer);
  6190. if (!labelContainer) {
  6191. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  6192. }
  6193. if (!labels) {
  6194. labels = document.createElement('div');
  6195. labels.className = 'labels';
  6196. this.dom.labels = labels;
  6197. }
  6198. if (!labelSet) {
  6199. labelSet = document.createElement('div');
  6200. labelSet.className = 'label-set';
  6201. labels.appendChild(labelSet);
  6202. this.dom.labelSet = labelSet;
  6203. }
  6204. if (!labels.parentNode || labels.parentNode != labelContainer) {
  6205. if (labels.parentNode) {
  6206. labels.parentNode.removeChild(labels.parentNode);
  6207. }
  6208. labelContainer.appendChild(labels);
  6209. }
  6210. // reposition frame
  6211. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  6212. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6213. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6214. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6215. // reposition labels
  6216. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  6217. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  6218. var me = this,
  6219. queue = this.queue,
  6220. groups = this.groups,
  6221. groupsData = this.groupsData;
  6222. // show/hide added/changed/removed groups
  6223. var ids = Object.keys(queue);
  6224. if (ids.length) {
  6225. ids.forEach(function (id) {
  6226. var action = queue[id];
  6227. var group = groups[id];
  6228. //noinspection FallthroughInSwitchStatementJS
  6229. switch (action) {
  6230. case 'add':
  6231. case 'update':
  6232. if (!group) {
  6233. var groupOptions = Object.create(me.options);
  6234. util.extend(groupOptions, {
  6235. height: null,
  6236. maxHeight: null
  6237. });
  6238. group = new Group(me, id, groupOptions);
  6239. group.setItems(me.itemsData); // attach items data
  6240. groups[id] = group;
  6241. me.controller.add(group);
  6242. }
  6243. // TODO: update group data
  6244. group.data = groupsData.get(id);
  6245. delete queue[id];
  6246. break;
  6247. case 'remove':
  6248. if (group) {
  6249. group.setItems(); // detach items data
  6250. delete groups[id];
  6251. me.controller.remove(group);
  6252. }
  6253. // update lists
  6254. delete queue[id];
  6255. break;
  6256. default:
  6257. console.log('Error: unknown action "' + action + '"');
  6258. }
  6259. });
  6260. // the groupset depends on each of the groups
  6261. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  6262. // TODO: apply dependencies of the groupset
  6263. // update the top positions of the groups in the correct order
  6264. var orderedGroups = this.groupsData.getIds({
  6265. order: this.options.groupOrder
  6266. });
  6267. for (i = 0; i < orderedGroups.length; i++) {
  6268. (function (group, prevGroup) {
  6269. var top = 0;
  6270. if (prevGroup) {
  6271. top = function () {
  6272. // TODO: top must reckon with options.maxHeight
  6273. return prevGroup.top + prevGroup.height;
  6274. }
  6275. }
  6276. group.setOptions({
  6277. top: top
  6278. });
  6279. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  6280. }
  6281. // (re)create the labels
  6282. while (labelSet.firstChild) {
  6283. labelSet.removeChild(labelSet.firstChild);
  6284. }
  6285. for (i = 0; i < orderedGroups.length; i++) {
  6286. id = orderedGroups[i];
  6287. label = this._createLabel(id);
  6288. labelSet.appendChild(label);
  6289. }
  6290. changed++;
  6291. }
  6292. // reposition the labels
  6293. // TODO: labels are not displayed correctly when orientation=='top'
  6294. // TODO: width of labelPanel is not immediately updated on a change in groups
  6295. for (id in groups) {
  6296. if (groups.hasOwnProperty(id)) {
  6297. group = groups[id];
  6298. label = group.label;
  6299. if (label) {
  6300. label.style.top = group.top + 'px';
  6301. label.style.height = group.height + 'px';
  6302. }
  6303. }
  6304. }
  6305. return (changed > 0);
  6306. };
  6307. /**
  6308. * Create a label for group with given id
  6309. * @param {Number} id
  6310. * @return {Element} label
  6311. * @private
  6312. */
  6313. GroupSet.prototype._createLabel = function(id) {
  6314. var group = this.groups[id];
  6315. var label = document.createElement('div');
  6316. label.className = 'label';
  6317. var inner = document.createElement('div');
  6318. inner.className = 'inner';
  6319. label.appendChild(inner);
  6320. var content = group.data && group.data.content;
  6321. if (content instanceof Element) {
  6322. inner.appendChild(content);
  6323. }
  6324. else if (content != undefined) {
  6325. inner.innerHTML = content;
  6326. }
  6327. var className = group.data && group.data.className;
  6328. if (className) {
  6329. util.addClassName(label, className);
  6330. }
  6331. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  6332. return label;
  6333. };
  6334. /**
  6335. * Get container element
  6336. * @return {HTMLElement} container
  6337. */
  6338. GroupSet.prototype.getContainer = function getContainer() {
  6339. return this.dom.frame;
  6340. };
  6341. /**
  6342. * Get the width of the group labels
  6343. * @return {Number} width
  6344. */
  6345. GroupSet.prototype.getLabelsWidth = function getContainer() {
  6346. return this.props.labels.width;
  6347. };
  6348. /**
  6349. * Reflow the component
  6350. * @return {Boolean} resized
  6351. */
  6352. GroupSet.prototype.reflow = function reflow() {
  6353. var changed = 0,
  6354. id, group,
  6355. options = this.options,
  6356. update = util.updateProperty,
  6357. asNumber = util.option.asNumber,
  6358. asSize = util.option.asSize,
  6359. frame = this.dom.frame;
  6360. if (frame) {
  6361. var maxHeight = asNumber(options.maxHeight);
  6362. var fixedHeight = (asSize(options.height) != null);
  6363. var height;
  6364. if (fixedHeight) {
  6365. height = frame.offsetHeight;
  6366. }
  6367. else {
  6368. // height is not specified, calculate the sum of the height of all groups
  6369. height = 0;
  6370. for (id in this.groups) {
  6371. if (this.groups.hasOwnProperty(id)) {
  6372. group = this.groups[id];
  6373. height += group.height;
  6374. }
  6375. }
  6376. }
  6377. if (maxHeight != null) {
  6378. height = Math.min(height, maxHeight);
  6379. }
  6380. changed += update(this, 'height', height);
  6381. changed += update(this, 'top', frame.offsetTop);
  6382. changed += update(this, 'left', frame.offsetLeft);
  6383. changed += update(this, 'width', frame.offsetWidth);
  6384. }
  6385. // calculate the maximum width of the labels
  6386. var width = 0;
  6387. for (id in this.groups) {
  6388. if (this.groups.hasOwnProperty(id)) {
  6389. group = this.groups[id];
  6390. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  6391. width = Math.max(width, labelWidth);
  6392. }
  6393. }
  6394. changed += update(this.props.labels, 'width', width);
  6395. return (changed > 0);
  6396. };
  6397. /**
  6398. * Hide the component from the DOM
  6399. * @return {Boolean} changed
  6400. */
  6401. GroupSet.prototype.hide = function hide() {
  6402. if (this.dom.frame && this.dom.frame.parentNode) {
  6403. this.dom.frame.parentNode.removeChild(this.dom.frame);
  6404. return true;
  6405. }
  6406. else {
  6407. return false;
  6408. }
  6409. };
  6410. /**
  6411. * Show the component in the DOM (when not already visible).
  6412. * A repaint will be executed when the component is not visible
  6413. * @return {Boolean} changed
  6414. */
  6415. GroupSet.prototype.show = function show() {
  6416. if (!this.dom.frame || !this.dom.frame.parentNode) {
  6417. return this.repaint();
  6418. }
  6419. else {
  6420. return false;
  6421. }
  6422. };
  6423. /**
  6424. * Handle updated groups
  6425. * @param {Number[]} ids
  6426. * @private
  6427. */
  6428. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  6429. this._toQueue(ids, 'update');
  6430. };
  6431. /**
  6432. * Handle changed groups
  6433. * @param {Number[]} ids
  6434. * @private
  6435. */
  6436. GroupSet.prototype._onAdd = function _onAdd(ids) {
  6437. this._toQueue(ids, 'add');
  6438. };
  6439. /**
  6440. * Handle removed groups
  6441. * @param {Number[]} ids
  6442. * @private
  6443. */
  6444. GroupSet.prototype._onRemove = function _onRemove(ids) {
  6445. this._toQueue(ids, 'remove');
  6446. };
  6447. /**
  6448. * Put groups in the queue to be added/updated/remove
  6449. * @param {Number[]} ids
  6450. * @param {String} action can be 'add', 'update', 'remove'
  6451. */
  6452. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  6453. var queue = this.queue;
  6454. ids.forEach(function (id) {
  6455. queue[id] = action;
  6456. });
  6457. if (this.controller) {
  6458. //this.requestReflow();
  6459. this.requestRepaint();
  6460. }
  6461. };
  6462. /**
  6463. * Create a timeline visualization
  6464. * @param {HTMLElement} container
  6465. * @param {vis.DataSet | Array | DataTable} [items]
  6466. * @param {Object} [options] See Timeline.setOptions for the available options.
  6467. * @constructor
  6468. */
  6469. function Timeline (container, items, options) {
  6470. var me = this;
  6471. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6472. this.options = {
  6473. orientation: 'bottom',
  6474. min: null,
  6475. max: null,
  6476. zoomMin: 10, // milliseconds
  6477. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6478. // moveable: true, // TODO: option moveable
  6479. // zoomable: true, // TODO: option zoomable
  6480. showMinorLabels: true,
  6481. showMajorLabels: true,
  6482. showCurrentTime: false,
  6483. showCustomTime: false,
  6484. autoResize: false
  6485. };
  6486. // controller
  6487. this.controller = new Controller();
  6488. // root panel
  6489. if (!container) {
  6490. throw new Error('No container element provided');
  6491. }
  6492. var rootOptions = Object.create(this.options);
  6493. rootOptions.height = function () {
  6494. // TODO: change to height
  6495. if (me.options.height) {
  6496. // fixed height
  6497. return me.options.height;
  6498. }
  6499. else {
  6500. // auto height
  6501. return (me.timeaxis.height + me.content.height) + 'px';
  6502. }
  6503. };
  6504. this.rootPanel = new RootPanel(container, rootOptions);
  6505. this.controller.add(this.rootPanel);
  6506. // item panel
  6507. var itemOptions = Object.create(this.options);
  6508. itemOptions.left = function () {
  6509. return me.labelPanel.width;
  6510. };
  6511. itemOptions.width = function () {
  6512. return me.rootPanel.width - me.labelPanel.width;
  6513. };
  6514. itemOptions.top = null;
  6515. itemOptions.height = null;
  6516. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  6517. this.controller.add(this.itemPanel);
  6518. // label panel
  6519. var labelOptions = Object.create(this.options);
  6520. labelOptions.top = null;
  6521. labelOptions.left = null;
  6522. labelOptions.height = null;
  6523. labelOptions.width = function () {
  6524. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  6525. return me.content.getLabelsWidth();
  6526. }
  6527. else {
  6528. return 0;
  6529. }
  6530. };
  6531. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  6532. this.controller.add(this.labelPanel);
  6533. // range
  6534. var rangeOptions = Object.create(this.options);
  6535. this.range = new Range(rangeOptions);
  6536. this.range.setRange(
  6537. now.clone().add('days', -3).valueOf(),
  6538. now.clone().add('days', 4).valueOf()
  6539. );
  6540. // TODO: reckon with options moveable and zoomable
  6541. this.range.subscribe(this.rootPanel, 'move', 'horizontal');
  6542. this.range.subscribe(this.rootPanel, 'zoom', 'horizontal');
  6543. this.range.on('rangechange', function () {
  6544. var force = true;
  6545. me.controller.requestReflow(force);
  6546. });
  6547. this.range.on('rangechanged', function () {
  6548. var force = true;
  6549. me.controller.requestReflow(force);
  6550. });
  6551. // TODO: put the listeners in setOptions, be able to dynamically change with options moveable and zoomable
  6552. // time axis
  6553. var timeaxisOptions = Object.create(rootOptions);
  6554. timeaxisOptions.range = this.range;
  6555. timeaxisOptions.left = null;
  6556. timeaxisOptions.top = null;
  6557. timeaxisOptions.width = '100%';
  6558. timeaxisOptions.height = null;
  6559. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6560. this.timeaxis.setRange(this.range);
  6561. this.controller.add(this.timeaxis);
  6562. // current time bar
  6563. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  6564. this.controller.add(this.currenttime);
  6565. // custom time bar
  6566. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  6567. this.controller.add(this.customtime);
  6568. // create groupset
  6569. this.setGroups(null);
  6570. this.itemsData = null; // DataSet
  6571. this.groupsData = null; // DataSet
  6572. // apply options
  6573. if (options) {
  6574. this.setOptions(options);
  6575. }
  6576. // create itemset and groupset
  6577. if (items) {
  6578. this.setItems(items);
  6579. }
  6580. }
  6581. /**
  6582. * Set options
  6583. * @param {Object} options TODO: describe the available options
  6584. */
  6585. Timeline.prototype.setOptions = function (options) {
  6586. util.extend(this.options, options);
  6587. // force update of range
  6588. // options.start and options.end can be undefined
  6589. //this.range.setRange(options.start, options.end);
  6590. this.range.setRange();
  6591. this.controller.reflow();
  6592. this.controller.repaint();
  6593. };
  6594. /**
  6595. * Set a custom time bar
  6596. * @param {Date} time
  6597. */
  6598. Timeline.prototype.setCustomTime = function (time) {
  6599. this.customtime._setCustomTime(time);
  6600. };
  6601. /**
  6602. * Retrieve the current custom time.
  6603. * @return {Date} customTime
  6604. */
  6605. Timeline.prototype.getCustomTime = function() {
  6606. return new Date(this.customtime.customTime.valueOf());
  6607. };
  6608. /**
  6609. * Set items
  6610. * @param {vis.DataSet | Array | DataTable | null} items
  6611. */
  6612. Timeline.prototype.setItems = function(items) {
  6613. var initialLoad = (this.itemsData == null);
  6614. // convert to type DataSet when needed
  6615. var newItemSet;
  6616. if (!items) {
  6617. newItemSet = null;
  6618. }
  6619. else if (items instanceof DataSet) {
  6620. newItemSet = items;
  6621. }
  6622. if (!(items instanceof DataSet)) {
  6623. newItemSet = new DataSet({
  6624. convert: {
  6625. start: 'Date',
  6626. end: 'Date'
  6627. }
  6628. });
  6629. newItemSet.add(items);
  6630. }
  6631. // set items
  6632. this.itemsData = newItemSet;
  6633. this.content.setItems(newItemSet);
  6634. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6635. // apply the data range as range
  6636. var dataRange = this.getItemRange();
  6637. // add 5% space on both sides
  6638. var min = dataRange.min;
  6639. var max = dataRange.max;
  6640. if (min != null && max != null) {
  6641. var interval = (max.valueOf() - min.valueOf());
  6642. if (interval <= 0) {
  6643. // prevent an empty interval
  6644. interval = 24 * 60 * 60 * 1000; // 1 day
  6645. }
  6646. min = new Date(min.valueOf() - interval * 0.05);
  6647. max = new Date(max.valueOf() + interval * 0.05);
  6648. }
  6649. // override specified start and/or end date
  6650. if (this.options.start != undefined) {
  6651. min = util.convert(this.options.start, 'Date');
  6652. }
  6653. if (this.options.end != undefined) {
  6654. max = util.convert(this.options.end, 'Date');
  6655. }
  6656. // apply range if there is a min or max available
  6657. if (min != null || max != null) {
  6658. this.range.setRange(min, max);
  6659. }
  6660. }
  6661. };
  6662. /**
  6663. * Set groups
  6664. * @param {vis.DataSet | Array | DataTable} groups
  6665. */
  6666. Timeline.prototype.setGroups = function(groups) {
  6667. var me = this;
  6668. this.groupsData = groups;
  6669. // switch content type between ItemSet or GroupSet when needed
  6670. var Type = this.groupsData ? GroupSet : ItemSet;
  6671. if (!(this.content instanceof Type)) {
  6672. // remove old content set
  6673. if (this.content) {
  6674. this.content.hide();
  6675. if (this.content.setItems) {
  6676. this.content.setItems(); // disconnect from items
  6677. }
  6678. if (this.content.setGroups) {
  6679. this.content.setGroups(); // disconnect from groups
  6680. }
  6681. this.controller.remove(this.content);
  6682. }
  6683. // create new content set
  6684. var options = Object.create(this.options);
  6685. util.extend(options, {
  6686. top: function () {
  6687. if (me.options.orientation == 'top') {
  6688. return me.timeaxis.height;
  6689. }
  6690. else {
  6691. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  6692. }
  6693. },
  6694. left: null,
  6695. width: '100%',
  6696. height: function () {
  6697. if (me.options.height) {
  6698. // fixed height
  6699. return me.itemPanel.height - me.timeaxis.height;
  6700. }
  6701. else {
  6702. // auto height
  6703. return null;
  6704. }
  6705. },
  6706. maxHeight: function () {
  6707. // TODO: change maxHeight to be a css string like '100%' or '300px'
  6708. if (me.options.maxHeight) {
  6709. if (!util.isNumber(me.options.maxHeight)) {
  6710. throw new TypeError('Number expected for property maxHeight');
  6711. }
  6712. return me.options.maxHeight - me.timeaxis.height;
  6713. }
  6714. else {
  6715. return null;
  6716. }
  6717. },
  6718. labelContainer: function () {
  6719. return me.labelPanel.getContainer();
  6720. }
  6721. });
  6722. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  6723. if (this.content.setRange) {
  6724. this.content.setRange(this.range);
  6725. }
  6726. if (this.content.setItems) {
  6727. this.content.setItems(this.itemsData);
  6728. }
  6729. if (this.content.setGroups) {
  6730. this.content.setGroups(this.groupsData);
  6731. }
  6732. this.controller.add(this.content);
  6733. }
  6734. };
  6735. /**
  6736. * Get the data range of the item set.
  6737. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6738. * When no minimum is found, min==null
  6739. * When no maximum is found, max==null
  6740. */
  6741. Timeline.prototype.getItemRange = function getItemRange() {
  6742. // calculate min from start filed
  6743. var itemsData = this.itemsData,
  6744. min = null,
  6745. max = null;
  6746. if (itemsData) {
  6747. // calculate the minimum value of the field 'start'
  6748. var minItem = itemsData.min('start');
  6749. min = minItem ? minItem.start.valueOf() : null;
  6750. // calculate maximum value of fields 'start' and 'end'
  6751. var maxStartItem = itemsData.max('start');
  6752. if (maxStartItem) {
  6753. max = maxStartItem.start.valueOf();
  6754. }
  6755. var maxEndItem = itemsData.max('end');
  6756. if (maxEndItem) {
  6757. if (max == null) {
  6758. max = maxEndItem.end.valueOf();
  6759. }
  6760. else {
  6761. max = Math.max(max, maxEndItem.end.valueOf());
  6762. }
  6763. }
  6764. }
  6765. return {
  6766. min: (min != null) ? new Date(min) : null,
  6767. max: (max != null) ? new Date(max) : null
  6768. };
  6769. };
  6770. /**
  6771. * Change the item selection, and/or get currently selected items
  6772. * @param {Array} [ids] An array with zero or more ids of the items to be selected.
  6773. * @return {Array} ids The ids of the selected items
  6774. */
  6775. Timeline.prototype.select = function select(ids) {
  6776. return this.content ? this.content.select(ids) : [];
  6777. };
  6778. (function(exports) {
  6779. /**
  6780. * Parse a text source containing data in DOT language into a JSON object.
  6781. * The object contains two lists: one with nodes and one with edges.
  6782. *
  6783. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6784. *
  6785. * @param {String} data Text containing a graph in DOT-notation
  6786. * @return {Object} graph An object containing two parameters:
  6787. * {Object[]} nodes
  6788. * {Object[]} edges
  6789. */
  6790. function parseDOT (data) {
  6791. dot = data;
  6792. return parseGraph();
  6793. }
  6794. // token types enumeration
  6795. var TOKENTYPE = {
  6796. NULL : 0,
  6797. DELIMITER : 1,
  6798. IDENTIFIER: 2,
  6799. UNKNOWN : 3
  6800. };
  6801. // map with all delimiters
  6802. var DELIMITERS = {
  6803. '{': true,
  6804. '}': true,
  6805. '[': true,
  6806. ']': true,
  6807. ';': true,
  6808. '=': true,
  6809. ',': true,
  6810. '->': true,
  6811. '--': true
  6812. };
  6813. var dot = ''; // current dot file
  6814. var index = 0; // current index in dot file
  6815. var c = ''; // current token character in expr
  6816. var token = ''; // current token
  6817. var tokenType = TOKENTYPE.NULL; // type of the token
  6818. /**
  6819. * Get the first character from the dot file.
  6820. * The character is stored into the char c. If the end of the dot file is
  6821. * reached, the function puts an empty string in c.
  6822. */
  6823. function first() {
  6824. index = 0;
  6825. c = dot.charAt(0);
  6826. }
  6827. /**
  6828. * Get the next character from the dot file.
  6829. * The character is stored into the char c. If the end of the dot file is
  6830. * reached, the function puts an empty string in c.
  6831. */
  6832. function next() {
  6833. index++;
  6834. c = dot.charAt(index);
  6835. }
  6836. /**
  6837. * Preview the next character from the dot file.
  6838. * @return {String} cNext
  6839. */
  6840. function nextPreview() {
  6841. return dot.charAt(index + 1);
  6842. }
  6843. /**
  6844. * Test whether given character is alphabetic or numeric
  6845. * @param {String} c
  6846. * @return {Boolean} isAlphaNumeric
  6847. */
  6848. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  6849. function isAlphaNumeric(c) {
  6850. return regexAlphaNumeric.test(c);
  6851. }
  6852. /**
  6853. * Merge all properties of object b into object b
  6854. * @param {Object} a
  6855. * @param {Object} b
  6856. * @return {Object} a
  6857. */
  6858. function merge (a, b) {
  6859. if (!a) {
  6860. a = {};
  6861. }
  6862. if (b) {
  6863. for (var name in b) {
  6864. if (b.hasOwnProperty(name)) {
  6865. a[name] = b[name];
  6866. }
  6867. }
  6868. }
  6869. return a;
  6870. }
  6871. /**
  6872. * Set a value in an object, where the provided parameter name can be a
  6873. * path with nested parameters. For example:
  6874. *
  6875. * var obj = {a: 2};
  6876. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  6877. *
  6878. * @param {Object} obj
  6879. * @param {String} path A parameter name or dot-separated parameter path,
  6880. * like "color.highlight.border".
  6881. * @param {*} value
  6882. */
  6883. function setValue(obj, path, value) {
  6884. var keys = path.split('.');
  6885. var o = obj;
  6886. while (keys.length) {
  6887. var key = keys.shift();
  6888. if (keys.length) {
  6889. // this isn't the end point
  6890. if (!o[key]) {
  6891. o[key] = {};
  6892. }
  6893. o = o[key];
  6894. }
  6895. else {
  6896. // this is the end point
  6897. o[key] = value;
  6898. }
  6899. }
  6900. }
  6901. /**
  6902. * Add a node to a graph object. If there is already a node with
  6903. * the same id, their attributes will be merged.
  6904. * @param {Object} graph
  6905. * @param {Object} node
  6906. */
  6907. function addNode(graph, node) {
  6908. var i, len;
  6909. var current = null;
  6910. // find root graph (in case of subgraph)
  6911. var graphs = [graph]; // list with all graphs from current graph to root graph
  6912. var root = graph;
  6913. while (root.parent) {
  6914. graphs.push(root.parent);
  6915. root = root.parent;
  6916. }
  6917. // find existing node (at root level) by its id
  6918. if (root.nodes) {
  6919. for (i = 0, len = root.nodes.length; i < len; i++) {
  6920. if (node.id === root.nodes[i].id) {
  6921. current = root.nodes[i];
  6922. break;
  6923. }
  6924. }
  6925. }
  6926. if (!current) {
  6927. // this is a new node
  6928. current = {
  6929. id: node.id
  6930. };
  6931. if (graph.node) {
  6932. // clone default attributes
  6933. current.attr = merge(current.attr, graph.node);
  6934. }
  6935. }
  6936. // add node to this (sub)graph and all its parent graphs
  6937. for (i = graphs.length - 1; i >= 0; i--) {
  6938. var g = graphs[i];
  6939. if (!g.nodes) {
  6940. g.nodes = [];
  6941. }
  6942. if (g.nodes.indexOf(current) == -1) {
  6943. g.nodes.push(current);
  6944. }
  6945. }
  6946. // merge attributes
  6947. if (node.attr) {
  6948. current.attr = merge(current.attr, node.attr);
  6949. }
  6950. }
  6951. /**
  6952. * Add an edge to a graph object
  6953. * @param {Object} graph
  6954. * @param {Object} edge
  6955. */
  6956. function addEdge(graph, edge) {
  6957. if (!graph.edges) {
  6958. graph.edges = [];
  6959. }
  6960. graph.edges.push(edge);
  6961. if (graph.edge) {
  6962. var attr = merge({}, graph.edge); // clone default attributes
  6963. edge.attr = merge(attr, edge.attr); // merge attributes
  6964. }
  6965. }
  6966. /**
  6967. * Create an edge to a graph object
  6968. * @param {Object} graph
  6969. * @param {String | Number | Object} from
  6970. * @param {String | Number | Object} to
  6971. * @param {String} type
  6972. * @param {Object | null} attr
  6973. * @return {Object} edge
  6974. */
  6975. function createEdge(graph, from, to, type, attr) {
  6976. var edge = {
  6977. from: from,
  6978. to: to,
  6979. type: type
  6980. };
  6981. if (graph.edge) {
  6982. edge.attr = merge({}, graph.edge); // clone default attributes
  6983. }
  6984. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  6985. return edge;
  6986. }
  6987. /**
  6988. * Get next token in the current dot file.
  6989. * The token and token type are available as token and tokenType
  6990. */
  6991. function getToken() {
  6992. tokenType = TOKENTYPE.NULL;
  6993. token = '';
  6994. // skip over whitespaces
  6995. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  6996. next();
  6997. }
  6998. do {
  6999. var isComment = false;
  7000. // skip comment
  7001. if (c == '#') {
  7002. // find the previous non-space character
  7003. var i = index - 1;
  7004. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7005. i--;
  7006. }
  7007. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7008. // the # is at the start of a line, this is indeed a line comment
  7009. while (c != '' && c != '\n') {
  7010. next();
  7011. }
  7012. isComment = true;
  7013. }
  7014. }
  7015. if (c == '/' && nextPreview() == '/') {
  7016. // skip line comment
  7017. while (c != '' && c != '\n') {
  7018. next();
  7019. }
  7020. isComment = true;
  7021. }
  7022. if (c == '/' && nextPreview() == '*') {
  7023. // skip block comment
  7024. while (c != '') {
  7025. if (c == '*' && nextPreview() == '/') {
  7026. // end of block comment found. skip these last two characters
  7027. next();
  7028. next();
  7029. break;
  7030. }
  7031. else {
  7032. next();
  7033. }
  7034. }
  7035. isComment = true;
  7036. }
  7037. // skip over whitespaces
  7038. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7039. next();
  7040. }
  7041. }
  7042. while (isComment);
  7043. // check for end of dot file
  7044. if (c == '') {
  7045. // token is still empty
  7046. tokenType = TOKENTYPE.DELIMITER;
  7047. return;
  7048. }
  7049. // check for delimiters consisting of 2 characters
  7050. var c2 = c + nextPreview();
  7051. if (DELIMITERS[c2]) {
  7052. tokenType = TOKENTYPE.DELIMITER;
  7053. token = c2;
  7054. next();
  7055. next();
  7056. return;
  7057. }
  7058. // check for delimiters consisting of 1 character
  7059. if (DELIMITERS[c]) {
  7060. tokenType = TOKENTYPE.DELIMITER;
  7061. token = c;
  7062. next();
  7063. return;
  7064. }
  7065. // check for an identifier (number or string)
  7066. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7067. if (isAlphaNumeric(c) || c == '-') {
  7068. token += c;
  7069. next();
  7070. while (isAlphaNumeric(c)) {
  7071. token += c;
  7072. next();
  7073. }
  7074. if (token == 'false') {
  7075. token = false; // convert to boolean
  7076. }
  7077. else if (token == 'true') {
  7078. token = true; // convert to boolean
  7079. }
  7080. else if (!isNaN(Number(token))) {
  7081. token = Number(token); // convert to number
  7082. }
  7083. tokenType = TOKENTYPE.IDENTIFIER;
  7084. return;
  7085. }
  7086. // check for a string enclosed by double quotes
  7087. if (c == '"') {
  7088. next();
  7089. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7090. token += c;
  7091. if (c == '"') { // skip the escape character
  7092. next();
  7093. }
  7094. next();
  7095. }
  7096. if (c != '"') {
  7097. throw newSyntaxError('End of string " expected');
  7098. }
  7099. next();
  7100. tokenType = TOKENTYPE.IDENTIFIER;
  7101. return;
  7102. }
  7103. // something unknown is found, wrong characters, a syntax error
  7104. tokenType = TOKENTYPE.UNKNOWN;
  7105. while (c != '') {
  7106. token += c;
  7107. next();
  7108. }
  7109. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7110. }
  7111. /**
  7112. * Parse a graph.
  7113. * @returns {Object} graph
  7114. */
  7115. function parseGraph() {
  7116. var graph = {};
  7117. first();
  7118. getToken();
  7119. // optional strict keyword
  7120. if (token == 'strict') {
  7121. graph.strict = true;
  7122. getToken();
  7123. }
  7124. // graph or digraph keyword
  7125. if (token == 'graph' || token == 'digraph') {
  7126. graph.type = token;
  7127. getToken();
  7128. }
  7129. // optional graph id
  7130. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7131. graph.id = token;
  7132. getToken();
  7133. }
  7134. // open angle bracket
  7135. if (token != '{') {
  7136. throw newSyntaxError('Angle bracket { expected');
  7137. }
  7138. getToken();
  7139. // statements
  7140. parseStatements(graph);
  7141. // close angle bracket
  7142. if (token != '}') {
  7143. throw newSyntaxError('Angle bracket } expected');
  7144. }
  7145. getToken();
  7146. // end of file
  7147. if (token !== '') {
  7148. throw newSyntaxError('End of file expected');
  7149. }
  7150. getToken();
  7151. // remove temporary default properties
  7152. delete graph.node;
  7153. delete graph.edge;
  7154. delete graph.graph;
  7155. return graph;
  7156. }
  7157. /**
  7158. * Parse a list with statements.
  7159. * @param {Object} graph
  7160. */
  7161. function parseStatements (graph) {
  7162. while (token !== '' && token != '}') {
  7163. parseStatement(graph);
  7164. if (token == ';') {
  7165. getToken();
  7166. }
  7167. }
  7168. }
  7169. /**
  7170. * Parse a single statement. Can be a an attribute statement, node
  7171. * statement, a series of node statements and edge statements, or a
  7172. * parameter.
  7173. * @param {Object} graph
  7174. */
  7175. function parseStatement(graph) {
  7176. // parse subgraph
  7177. var subgraph = parseSubgraph(graph);
  7178. if (subgraph) {
  7179. // edge statements
  7180. parseEdge(graph, subgraph);
  7181. return;
  7182. }
  7183. // parse an attribute statement
  7184. var attr = parseAttributeStatement(graph);
  7185. if (attr) {
  7186. return;
  7187. }
  7188. // parse node
  7189. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7190. throw newSyntaxError('Identifier expected');
  7191. }
  7192. var id = token; // id can be a string or a number
  7193. getToken();
  7194. if (token == '=') {
  7195. // id statement
  7196. getToken();
  7197. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7198. throw newSyntaxError('Identifier expected');
  7199. }
  7200. graph[id] = token;
  7201. getToken();
  7202. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7203. }
  7204. else {
  7205. parseNodeStatement(graph, id);
  7206. }
  7207. }
  7208. /**
  7209. * Parse a subgraph
  7210. * @param {Object} graph parent graph object
  7211. * @return {Object | null} subgraph
  7212. */
  7213. function parseSubgraph (graph) {
  7214. var subgraph = null;
  7215. // optional subgraph keyword
  7216. if (token == 'subgraph') {
  7217. subgraph = {};
  7218. subgraph.type = 'subgraph';
  7219. getToken();
  7220. // optional graph id
  7221. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7222. subgraph.id = token;
  7223. getToken();
  7224. }
  7225. }
  7226. // open angle bracket
  7227. if (token == '{') {
  7228. getToken();
  7229. if (!subgraph) {
  7230. subgraph = {};
  7231. }
  7232. subgraph.parent = graph;
  7233. subgraph.node = graph.node;
  7234. subgraph.edge = graph.edge;
  7235. subgraph.graph = graph.graph;
  7236. // statements
  7237. parseStatements(subgraph);
  7238. // close angle bracket
  7239. if (token != '}') {
  7240. throw newSyntaxError('Angle bracket } expected');
  7241. }
  7242. getToken();
  7243. // remove temporary default properties
  7244. delete subgraph.node;
  7245. delete subgraph.edge;
  7246. delete subgraph.graph;
  7247. delete subgraph.parent;
  7248. // register at the parent graph
  7249. if (!graph.subgraphs) {
  7250. graph.subgraphs = [];
  7251. }
  7252. graph.subgraphs.push(subgraph);
  7253. }
  7254. return subgraph;
  7255. }
  7256. /**
  7257. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7258. * Available keywords are 'node', 'edge', 'graph'.
  7259. * The previous list with default attributes will be replaced
  7260. * @param {Object} graph
  7261. * @returns {String | null} keyword Returns the name of the parsed attribute
  7262. * (node, edge, graph), or null if nothing
  7263. * is parsed.
  7264. */
  7265. function parseAttributeStatement (graph) {
  7266. // attribute statements
  7267. if (token == 'node') {
  7268. getToken();
  7269. // node attributes
  7270. graph.node = parseAttributeList();
  7271. return 'node';
  7272. }
  7273. else if (token == 'edge') {
  7274. getToken();
  7275. // edge attributes
  7276. graph.edge = parseAttributeList();
  7277. return 'edge';
  7278. }
  7279. else if (token == 'graph') {
  7280. getToken();
  7281. // graph attributes
  7282. graph.graph = parseAttributeList();
  7283. return 'graph';
  7284. }
  7285. return null;
  7286. }
  7287. /**
  7288. * parse a node statement
  7289. * @param {Object} graph
  7290. * @param {String | Number} id
  7291. */
  7292. function parseNodeStatement(graph, id) {
  7293. // node statement
  7294. var node = {
  7295. id: id
  7296. };
  7297. var attr = parseAttributeList();
  7298. if (attr) {
  7299. node.attr = attr;
  7300. }
  7301. addNode(graph, node);
  7302. // edge statements
  7303. parseEdge(graph, id);
  7304. }
  7305. /**
  7306. * Parse an edge or a series of edges
  7307. * @param {Object} graph
  7308. * @param {String | Number} from Id of the from node
  7309. */
  7310. function parseEdge(graph, from) {
  7311. while (token == '->' || token == '--') {
  7312. var to;
  7313. var type = token;
  7314. getToken();
  7315. var subgraph = parseSubgraph(graph);
  7316. if (subgraph) {
  7317. to = subgraph;
  7318. }
  7319. else {
  7320. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7321. throw newSyntaxError('Identifier or subgraph expected');
  7322. }
  7323. to = token;
  7324. addNode(graph, {
  7325. id: to
  7326. });
  7327. getToken();
  7328. }
  7329. // parse edge attributes
  7330. var attr = parseAttributeList();
  7331. // create edge
  7332. var edge = createEdge(graph, from, to, type, attr);
  7333. addEdge(graph, edge);
  7334. from = to;
  7335. }
  7336. }
  7337. /**
  7338. * Parse a set with attributes,
  7339. * for example [label="1.000", shape=solid]
  7340. * @return {Object | null} attr
  7341. */
  7342. function parseAttributeList() {
  7343. var attr = null;
  7344. while (token == '[') {
  7345. getToken();
  7346. attr = {};
  7347. while (token !== '' && token != ']') {
  7348. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7349. throw newSyntaxError('Attribute name expected');
  7350. }
  7351. var name = token;
  7352. getToken();
  7353. if (token != '=') {
  7354. throw newSyntaxError('Equal sign = expected');
  7355. }
  7356. getToken();
  7357. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7358. throw newSyntaxError('Attribute value expected');
  7359. }
  7360. var value = token;
  7361. setValue(attr, name, value); // name can be a path
  7362. getToken();
  7363. if (token ==',') {
  7364. getToken();
  7365. }
  7366. }
  7367. if (token != ']') {
  7368. throw newSyntaxError('Bracket ] expected');
  7369. }
  7370. getToken();
  7371. }
  7372. return attr;
  7373. }
  7374. /**
  7375. * Create a syntax error with extra information on current token and index.
  7376. * @param {String} message
  7377. * @returns {SyntaxError} err
  7378. */
  7379. function newSyntaxError(message) {
  7380. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7381. }
  7382. /**
  7383. * Chop off text after a maximum length
  7384. * @param {String} text
  7385. * @param {Number} maxLength
  7386. * @returns {String}
  7387. */
  7388. function chop (text, maxLength) {
  7389. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7390. }
  7391. /**
  7392. * Execute a function fn for each pair of elements in two arrays
  7393. * @param {Array | *} array1
  7394. * @param {Array | *} array2
  7395. * @param {function} fn
  7396. */
  7397. function forEach2(array1, array2, fn) {
  7398. if (array1 instanceof Array) {
  7399. array1.forEach(function (elem1) {
  7400. if (array2 instanceof Array) {
  7401. array2.forEach(function (elem2) {
  7402. fn(elem1, elem2);
  7403. });
  7404. }
  7405. else {
  7406. fn(elem1, array2);
  7407. }
  7408. });
  7409. }
  7410. else {
  7411. if (array2 instanceof Array) {
  7412. array2.forEach(function (elem2) {
  7413. fn(array1, elem2);
  7414. });
  7415. }
  7416. else {
  7417. fn(array1, array2);
  7418. }
  7419. }
  7420. }
  7421. /**
  7422. * Convert a string containing a graph in DOT language into a map containing
  7423. * with nodes and edges in the format of graph.
  7424. * @param {String} data Text containing a graph in DOT-notation
  7425. * @return {Object} graphData
  7426. */
  7427. function DOTToGraph (data) {
  7428. // parse the DOT file
  7429. var dotData = parseDOT(data);
  7430. var graphData = {
  7431. nodes: [],
  7432. edges: [],
  7433. options: {}
  7434. };
  7435. // copy the nodes
  7436. if (dotData.nodes) {
  7437. dotData.nodes.forEach(function (dotNode) {
  7438. var graphNode = {
  7439. id: dotNode.id,
  7440. label: String(dotNode.label || dotNode.id)
  7441. };
  7442. merge(graphNode, dotNode.attr);
  7443. if (graphNode.image) {
  7444. graphNode.shape = 'image';
  7445. }
  7446. graphData.nodes.push(graphNode);
  7447. });
  7448. }
  7449. // copy the edges
  7450. if (dotData.edges) {
  7451. /**
  7452. * Convert an edge in DOT format to an edge with VisGraph format
  7453. * @param {Object} dotEdge
  7454. * @returns {Object} graphEdge
  7455. */
  7456. function convertEdge(dotEdge) {
  7457. var graphEdge = {
  7458. from: dotEdge.from,
  7459. to: dotEdge.to
  7460. };
  7461. merge(graphEdge, dotEdge.attr);
  7462. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  7463. return graphEdge;
  7464. }
  7465. dotData.edges.forEach(function (dotEdge) {
  7466. var from, to;
  7467. if (dotEdge.from instanceof Object) {
  7468. from = dotEdge.from.nodes;
  7469. }
  7470. else {
  7471. from = {
  7472. id: dotEdge.from
  7473. }
  7474. }
  7475. if (dotEdge.to instanceof Object) {
  7476. to = dotEdge.to.nodes;
  7477. }
  7478. else {
  7479. to = {
  7480. id: dotEdge.to
  7481. }
  7482. }
  7483. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  7484. dotEdge.from.edges.forEach(function (subEdge) {
  7485. var graphEdge = convertEdge(subEdge);
  7486. graphData.edges.push(graphEdge);
  7487. });
  7488. }
  7489. forEach2(from, to, function (from, to) {
  7490. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  7491. var graphEdge = convertEdge(subEdge);
  7492. graphData.edges.push(graphEdge);
  7493. });
  7494. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  7495. dotEdge.to.edges.forEach(function (subEdge) {
  7496. var graphEdge = convertEdge(subEdge);
  7497. graphData.edges.push(graphEdge);
  7498. });
  7499. }
  7500. });
  7501. }
  7502. // copy the options
  7503. if (dotData.attr) {
  7504. graphData.options = dotData.attr;
  7505. }
  7506. return graphData;
  7507. }
  7508. // exports
  7509. exports.parseDOT = parseDOT;
  7510. exports.DOTToGraph = DOTToGraph;
  7511. })(typeof util !== 'undefined' ? util : exports);
  7512. /**
  7513. * Canvas shapes used by the Graph
  7514. */
  7515. if (typeof CanvasRenderingContext2D !== 'undefined') {
  7516. /**
  7517. * Draw a circle shape
  7518. */
  7519. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  7520. this.beginPath();
  7521. this.arc(x, y, r, 0, 2*Math.PI, false);
  7522. };
  7523. /**
  7524. * Draw a square shape
  7525. * @param {Number} x horizontal center
  7526. * @param {Number} y vertical center
  7527. * @param {Number} r size, width and height of the square
  7528. */
  7529. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  7530. this.beginPath();
  7531. this.rect(x - r, y - r, r * 2, r * 2);
  7532. };
  7533. /**
  7534. * Draw a triangle shape
  7535. * @param {Number} x horizontal center
  7536. * @param {Number} y vertical center
  7537. * @param {Number} r radius, half the length of the sides of the triangle
  7538. */
  7539. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  7540. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7541. this.beginPath();
  7542. var s = r * 2;
  7543. var s2 = s / 2;
  7544. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7545. var h = Math.sqrt(s * s - s2 * s2); // height
  7546. this.moveTo(x, y - (h - ir));
  7547. this.lineTo(x + s2, y + ir);
  7548. this.lineTo(x - s2, y + ir);
  7549. this.lineTo(x, y - (h - ir));
  7550. this.closePath();
  7551. };
  7552. /**
  7553. * Draw a triangle shape in downward orientation
  7554. * @param {Number} x horizontal center
  7555. * @param {Number} y vertical center
  7556. * @param {Number} r radius
  7557. */
  7558. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  7559. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7560. this.beginPath();
  7561. var s = r * 2;
  7562. var s2 = s / 2;
  7563. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7564. var h = Math.sqrt(s * s - s2 * s2); // height
  7565. this.moveTo(x, y + (h - ir));
  7566. this.lineTo(x + s2, y - ir);
  7567. this.lineTo(x - s2, y - ir);
  7568. this.lineTo(x, y + (h - ir));
  7569. this.closePath();
  7570. };
  7571. /**
  7572. * Draw a star shape, a star with 5 points
  7573. * @param {Number} x horizontal center
  7574. * @param {Number} y vertical center
  7575. * @param {Number} r radius, half the length of the sides of the triangle
  7576. */
  7577. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  7578. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  7579. this.beginPath();
  7580. for (var n = 0; n < 10; n++) {
  7581. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  7582. this.lineTo(
  7583. x + radius * Math.sin(n * 2 * Math.PI / 10),
  7584. y - radius * Math.cos(n * 2 * Math.PI / 10)
  7585. );
  7586. }
  7587. this.closePath();
  7588. };
  7589. /**
  7590. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7591. */
  7592. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7593. var r2d = Math.PI/180;
  7594. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7595. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7596. this.beginPath();
  7597. this.moveTo(x+r,y);
  7598. this.lineTo(x+w-r,y);
  7599. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7600. this.lineTo(x+w,y+h-r);
  7601. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7602. this.lineTo(x+r,y+h);
  7603. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7604. this.lineTo(x,y+r);
  7605. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7606. };
  7607. /**
  7608. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7609. */
  7610. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7611. var kappa = .5522848,
  7612. ox = (w / 2) * kappa, // control point offset horizontal
  7613. oy = (h / 2) * kappa, // control point offset vertical
  7614. xe = x + w, // x-end
  7615. ye = y + h, // y-end
  7616. xm = x + w / 2, // x-middle
  7617. ym = y + h / 2; // y-middle
  7618. this.beginPath();
  7619. this.moveTo(x, ym);
  7620. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7621. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7622. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7623. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7624. };
  7625. /**
  7626. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7627. */
  7628. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7629. var f = 1/3;
  7630. var wEllipse = w;
  7631. var hEllipse = h * f;
  7632. var kappa = .5522848,
  7633. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7634. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7635. xe = x + wEllipse, // x-end
  7636. ye = y + hEllipse, // y-end
  7637. xm = x + wEllipse / 2, // x-middle
  7638. ym = y + hEllipse / 2, // y-middle
  7639. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7640. yeb = y + h; // y-end, bottom ellipse
  7641. this.beginPath();
  7642. this.moveTo(xe, ym);
  7643. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7644. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7645. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7646. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7647. this.lineTo(xe, ymb);
  7648. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7649. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7650. this.lineTo(x, ym);
  7651. };
  7652. /**
  7653. * Draw an arrow point (no line)
  7654. */
  7655. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  7656. // tail
  7657. var xt = x - length * Math.cos(angle);
  7658. var yt = y - length * Math.sin(angle);
  7659. // inner tail
  7660. // TODO: allow to customize different shapes
  7661. var xi = x - length * 0.9 * Math.cos(angle);
  7662. var yi = y - length * 0.9 * Math.sin(angle);
  7663. // left
  7664. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  7665. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  7666. // right
  7667. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  7668. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  7669. this.beginPath();
  7670. this.moveTo(x, y);
  7671. this.lineTo(xl, yl);
  7672. this.lineTo(xi, yi);
  7673. this.lineTo(xr, yr);
  7674. this.closePath();
  7675. };
  7676. /**
  7677. * Sets up the dashedLine functionality for drawing
  7678. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  7679. * @author David Jordan
  7680. * @date 2012-08-08
  7681. */
  7682. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  7683. if (!dashArray) dashArray=[10,5];
  7684. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  7685. var dashCount = dashArray.length;
  7686. this.moveTo(x, y);
  7687. var dx = (x2-x), dy = (y2-y);
  7688. var slope = dy/dx;
  7689. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  7690. var dashIndex=0, draw=true;
  7691. while (distRemaining>=0.1){
  7692. var dashLength = dashArray[dashIndex++%dashCount];
  7693. if (dashLength > distRemaining) dashLength = distRemaining;
  7694. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  7695. if (dx<0) xStep = -xStep;
  7696. x += xStep;
  7697. y += slope*xStep;
  7698. this[draw ? 'lineTo' : 'moveTo'](x,y);
  7699. distRemaining -= dashLength;
  7700. draw = !draw;
  7701. }
  7702. };
  7703. // TODO: add diamond shape
  7704. }
  7705. /**
  7706. * @class Node
  7707. * A node. A node can be connected to other nodes via one or multiple edges.
  7708. * @param {object} properties An object containing properties for the node. All
  7709. * properties are optional, except for the id.
  7710. * {number} id Id of the node. Required
  7711. * {string} label Text label for the node
  7712. * {number} x Horizontal position of the node
  7713. * {number} y Vertical position of the node
  7714. * {string} shape Node shape, available:
  7715. * "database", "circle", "ellipse",
  7716. * "box", "image", "text", "dot",
  7717. * "star", "triangle", "triangleDown",
  7718. * "square"
  7719. * {string} image An image url
  7720. * {string} title An title text, can be HTML
  7721. * {anytype} group A group name or number
  7722. * @param {Graph.Images} imagelist A list with images. Only needed
  7723. * when the node has an image
  7724. * @param {Graph.Groups} grouplist A list with groups. Needed for
  7725. * retrieving group properties
  7726. * @param {Object} constants An object with default values for
  7727. * example for the color
  7728. */
  7729. function Node(properties, imagelist, grouplist, constants) {
  7730. this.selected = false;
  7731. this.edges = []; // all edges connected to this node
  7732. this.dynamicEdges = [];
  7733. this.reroutedEdges = {};
  7734. this.group = constants.nodes.group;
  7735. this.fontSize = constants.nodes.fontSize;
  7736. this.fontFace = constants.nodes.fontFace;
  7737. this.fontColor = constants.nodes.fontColor;
  7738. this.color = constants.nodes.color;
  7739. // set defaults for the properties
  7740. this.id = undefined;
  7741. this.shape = constants.nodes.shape;
  7742. this.image = constants.nodes.image;
  7743. this.x = 0;
  7744. this.y = 0;
  7745. this.xFixed = false;
  7746. this.yFixed = false;
  7747. this.radius = constants.nodes.radius;
  7748. this.baseRadiusValue = constants.nodes.radius;
  7749. this.radiusFixed = false;
  7750. this.radiusMin = constants.nodes.radiusMin;
  7751. this.radiusMax = constants.nodes.radiusMax;
  7752. this.imagelist = imagelist;
  7753. this.grouplist = grouplist;
  7754. this.nodeProperties = properties;
  7755. this.setProperties(properties, constants);
  7756. // creating the variables for clustering
  7757. this.resetCluster();
  7758. this.dynamicEdgesLength = 0;
  7759. this.clusterSession = 0;
  7760. this.clusterSizeWidthFactor = constants.clustering.clusterSizeWidthFactor;
  7761. this.clusterSizeHeightFactor = constants.clustering.clusterSizeHeightFactor;
  7762. this.clusterSizeRadiusFactor = constants.clustering.clusterSizeRadiusFactor;
  7763. // mass, force, velocity
  7764. this.mass = 50; // kg (mass is adjusted for the number of connected edges)
  7765. this.fx = 0.0; // external force x
  7766. this.fy = 0.0; // external force y
  7767. this.vx = 0.0; // velocity x
  7768. this.vy = 0.0; // velocity y
  7769. this.minForce = constants.minForce;
  7770. this.damping = 0.9; // damping factor
  7771. this.graphScaleInv = 1;
  7772. this.canvasTopLeft = {"x": -300, "y": -300};
  7773. this.canvasBottomRight = {"x": 300, "y": 300};
  7774. }
  7775. /**
  7776. * (re)setting the clustering variables and objects
  7777. */
  7778. Node.prototype.resetCluster = function() {
  7779. // clustering variables
  7780. this.formationScale = undefined; // this is used to determine when to open the cluster
  7781. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  7782. this.containedNodes = {};
  7783. this.containedEdges = {};
  7784. this.clusterSessions = [];
  7785. };
  7786. /**
  7787. * Attach a edge to the node
  7788. * @param {Edge} edge
  7789. */
  7790. Node.prototype.attachEdge = function(edge) {
  7791. if (this.edges.indexOf(edge) == -1) {
  7792. this.edges.push(edge);
  7793. }
  7794. if (this.dynamicEdges.indexOf(edge) == -1) {
  7795. this.dynamicEdges.push(edge);
  7796. }
  7797. this.dynamicEdgesLength = this.dynamicEdges.length;
  7798. this._updateMass();
  7799. };
  7800. /**
  7801. * Detach a edge from the node
  7802. * @param {Edge} edge
  7803. */
  7804. Node.prototype.detachEdge = function(edge) {
  7805. var index = this.edges.indexOf(edge);
  7806. if (index != -1) {
  7807. this.edges.splice(index, 1);
  7808. this.dynamicEdges.splice(index, 1);
  7809. }
  7810. this.dynamicEdgesLength = this.dynamicEdges.length;
  7811. this._updateMass();
  7812. };
  7813. /**
  7814. * Update the nodes mass, which is determined by the number of edges connecting
  7815. * to it (more edges -> heavier node).
  7816. * @private
  7817. */
  7818. Node.prototype._updateMass = function() {
  7819. this.mass = 50 + 20 * this.edges.length; // kg
  7820. };
  7821. /**
  7822. * Set or overwrite properties for the node
  7823. * @param {Object} properties an object with properties
  7824. * @param {Object} constants and object with default, global properties
  7825. */
  7826. Node.prototype.setProperties = function(properties, constants) {
  7827. if (!properties) {
  7828. return;
  7829. }
  7830. // basic properties
  7831. if (properties.id !== undefined) {this.id = properties.id;}
  7832. if (properties.label !== undefined) {this.label = properties.label;}
  7833. if (properties.title !== undefined) {this.title = properties.title;}
  7834. if (properties.group !== undefined) {this.group = properties.group;}
  7835. if (properties.x !== undefined) {this.x = properties.x;}
  7836. if (properties.y !== undefined) {this.y = properties.y;}
  7837. if (properties.value !== undefined) {this.value = properties.value;}
  7838. if (this.id === undefined) {
  7839. throw "Node must have an id";
  7840. }
  7841. // copy group properties
  7842. if (this.group) {
  7843. var groupObj = this.grouplist.get(this.group);
  7844. for (var prop in groupObj) {
  7845. if (groupObj.hasOwnProperty(prop)) {
  7846. this[prop] = groupObj[prop];
  7847. }
  7848. }
  7849. }
  7850. // individual shape properties
  7851. if (properties.shape !== undefined) {this.shape = properties.shape;}
  7852. if (properties.image !== undefined) {this.image = properties.image;}
  7853. if (properties.radius !== undefined) {this.radius = properties.radius;}
  7854. if (properties.color !== undefined) {this.color = Node.parseColor(properties.color);}
  7855. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  7856. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  7857. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  7858. if (this.image !== undefined) {
  7859. if (this.imagelist) {
  7860. this.imageObj = this.imagelist.load(this.image);
  7861. }
  7862. else {
  7863. throw "No imagelist provided";
  7864. }
  7865. }
  7866. this.xFixed = this.xFixed || (properties.x !== undefined);
  7867. this.yFixed = this.yFixed || (properties.y !== undefined);
  7868. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  7869. if (this.shape == 'image') {
  7870. this.radiusMin = constants.nodes.widthMin;
  7871. this.radiusMax = constants.nodes.widthMax;
  7872. }
  7873. // choose draw method depending on the shape
  7874. switch (this.shape) {
  7875. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  7876. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  7877. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  7878. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7879. // TODO: add diamond shape
  7880. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  7881. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  7882. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  7883. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  7884. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  7885. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  7886. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  7887. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7888. }
  7889. // reset the size of the node, this can be changed
  7890. this._reset();
  7891. };
  7892. /**
  7893. * Parse a color property into an object with border, background, and
  7894. * hightlight colors
  7895. * @param {Object | String} color
  7896. * @return {Object} colorObject
  7897. */
  7898. Node.parseColor = function(color) {
  7899. var c;
  7900. if (util.isString(color)) {
  7901. c = {
  7902. border: color,
  7903. background: color,
  7904. highlight: {
  7905. border: color,
  7906. background: color
  7907. }
  7908. };
  7909. // TODO: automatically generate a nice highlight color
  7910. }
  7911. else {
  7912. c = {};
  7913. c.background = color.background || 'white';
  7914. c.border = color.border || c.background;
  7915. if (util.isString(color.highlight)) {
  7916. c.highlight = {
  7917. border: color.highlight,
  7918. background: color.highlight
  7919. }
  7920. }
  7921. else {
  7922. c.highlight = {};
  7923. c.highlight.background = color.highlight && color.highlight.background || c.background;
  7924. c.highlight.border = color.highlight && color.highlight.border || c.border;
  7925. }
  7926. }
  7927. return c;
  7928. };
  7929. /**
  7930. * select this node
  7931. */
  7932. Node.prototype.select = function() {
  7933. this.selected = true;
  7934. this._reset();
  7935. };
  7936. /**
  7937. * unselect this node
  7938. */
  7939. Node.prototype.unselect = function() {
  7940. this.selected = false;
  7941. this._reset();
  7942. };
  7943. /**
  7944. * Reset the calculated size of the node, forces it to recalculate its size
  7945. */
  7946. Node.prototype.clearSizeCache = function() {
  7947. this._reset();
  7948. };
  7949. /**
  7950. * Reset the calculated size of the node, forces it to recalculate its size
  7951. * @private
  7952. */
  7953. Node.prototype._reset = function() {
  7954. this.width = undefined;
  7955. this.height = undefined;
  7956. };
  7957. /**
  7958. * get the title of this node.
  7959. * @return {string} title The title of the node, or undefined when no title
  7960. * has been set.
  7961. */
  7962. Node.prototype.getTitle = function() {
  7963. return this.title;
  7964. };
  7965. /**
  7966. * Calculate the distance to the border of the Node
  7967. * @param {CanvasRenderingContext2D} ctx
  7968. * @param {Number} angle Angle in radians
  7969. * @returns {number} distance Distance to the border in pixels
  7970. */
  7971. Node.prototype.distanceToBorder = function (ctx, angle) {
  7972. var borderWidth = 1;
  7973. if (!this.width) {
  7974. this.resize(ctx);
  7975. }
  7976. //noinspection FallthroughInSwitchStatementJS
  7977. switch (this.shape) {
  7978. case 'circle':
  7979. case 'dot':
  7980. return this.radius + borderWidth;
  7981. case 'ellipse':
  7982. var a = this.width / 2;
  7983. var b = this.height / 2;
  7984. var w = (Math.sin(angle) * a);
  7985. var h = (Math.cos(angle) * b);
  7986. return a * b / Math.sqrt(w * w + h * h);
  7987. // TODO: implement distanceToBorder for database
  7988. // TODO: implement distanceToBorder for triangle
  7989. // TODO: implement distanceToBorder for triangleDown
  7990. case 'box':
  7991. case 'image':
  7992. case 'text':
  7993. default:
  7994. if (this.width) {
  7995. return Math.min(
  7996. Math.abs(this.width / 2 / Math.cos(angle)),
  7997. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  7998. // TODO: reckon with border radius too in case of box
  7999. }
  8000. else {
  8001. return 0;
  8002. }
  8003. }
  8004. // TODO: implement calculation of distance to border for all shapes
  8005. };
  8006. /**
  8007. * Set forces acting on the node
  8008. * @param {number} fx Force in horizontal direction
  8009. * @param {number} fy Force in vertical direction
  8010. */
  8011. Node.prototype._setForce = function(fx, fy) {
  8012. this.fx = fx;
  8013. this.fy = fy;
  8014. };
  8015. /**
  8016. * Add forces acting on the node
  8017. * @param {number} fx Force in horizontal direction
  8018. * @param {number} fy Force in vertical direction
  8019. * @private
  8020. */
  8021. Node.prototype._addForce = function(fx, fy) {
  8022. this.fx += fx;
  8023. this.fy += fy;
  8024. };
  8025. /**
  8026. * Perform one discrete step for the node
  8027. * @param {number} interval Time interval in seconds
  8028. */
  8029. Node.prototype.discreteStep = function(interval) {
  8030. if (!this.xFixed) {
  8031. var dx = -this.damping * this.vx; // damping force
  8032. var ax = (this.fx + dx) / this.mass; // acceleration
  8033. this.vx += ax / interval; // velocity
  8034. this.x += this.vx / interval; // position
  8035. }
  8036. if (!this.yFixed) {
  8037. var dy = -this.damping * this.vy; // damping force
  8038. var ay = (this.fy + dy) / this.mass; // acceleration
  8039. this.vy += ay / interval; // velocity
  8040. this.y += this.vy / interval; // position
  8041. }
  8042. };
  8043. /**
  8044. * Check if this node has a fixed x and y position
  8045. * @return {boolean} true if fixed, false if not
  8046. */
  8047. Node.prototype.isFixed = function() {
  8048. return (this.xFixed && this.yFixed);
  8049. };
  8050. /**
  8051. * Check if this node is moving
  8052. * @param {number} vmin the minimum velocity considered as "moving"
  8053. * @return {boolean} true if moving, false if it has no velocity
  8054. */
  8055. // TODO: replace this method with calculating the kinetic energy
  8056. Node.prototype.isMoving = function(vmin) {
  8057. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin ||
  8058. (!this.xFixed && Math.abs(this.fx) > this.minForce) ||
  8059. (!this.yFixed && Math.abs(this.fy) > this.minForce));
  8060. };
  8061. /**
  8062. * check if this node is selecte
  8063. * @return {boolean} selected True if node is selected, else false
  8064. */
  8065. Node.prototype.isSelected = function() {
  8066. return this.selected;
  8067. };
  8068. /**
  8069. * Retrieve the value of the node. Can be undefined
  8070. * @return {Number} value
  8071. */
  8072. Node.prototype.getValue = function() {
  8073. return this.value;
  8074. };
  8075. /**
  8076. * Calculate the distance from the nodes location to the given location (x,y)
  8077. * @param {Number} x
  8078. * @param {Number} y
  8079. * @return {Number} value
  8080. */
  8081. Node.prototype.getDistance = function(x, y) {
  8082. var dx = this.x - x,
  8083. dy = this.y - y;
  8084. return Math.sqrt(dx * dx + dy * dy);
  8085. };
  8086. /**
  8087. * Adjust the value range of the node. The node will adjust it's radius
  8088. * based on its value.
  8089. * @param {Number} min
  8090. * @param {Number} max
  8091. */
  8092. Node.prototype.setValueRange = function(min, max) {
  8093. if (!this.radiusFixed && this.value !== undefined) {
  8094. if (max == min) {
  8095. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8096. }
  8097. else {
  8098. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8099. this.radius = (this.value - min) * scale + this.radiusMin;
  8100. }
  8101. }
  8102. };
  8103. /**
  8104. * Draw this node in the given canvas
  8105. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8106. * @param {CanvasRenderingContext2D} ctx
  8107. */
  8108. Node.prototype.draw = function(ctx) {
  8109. throw "Draw method not initialized for node";
  8110. };
  8111. /**
  8112. * Recalculate the size of this node in the given canvas
  8113. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8114. * @param {CanvasRenderingContext2D} ctx
  8115. */
  8116. Node.prototype.resize = function(ctx) {
  8117. throw "Resize method not initialized for node";
  8118. };
  8119. /**
  8120. * Check if this object is overlapping with the provided object
  8121. * @param {Object} obj an object with parameters left, top, right, bottom
  8122. * @return {boolean} True if location is located on node
  8123. */
  8124. Node.prototype.isOverlappingWith = function(obj) {
  8125. return (this.left < obj.right &&
  8126. this.left + this.width > obj.left &&
  8127. this.top < obj.bottom &&
  8128. this.top + this.height > obj.top);
  8129. };
  8130. Node.prototype._resizeImage = function (ctx) {
  8131. // TODO: pre calculate the image size
  8132. if (!this.width) { // undefined or 0
  8133. var width, height;
  8134. if (this.value) {
  8135. var scale = this.imageObj.height / this.imageObj.width;
  8136. width = this.radius || this.imageObj.width;
  8137. height = this.radius * scale || this.imageObj.height;
  8138. }
  8139. else {
  8140. width = this.imageObj.width;
  8141. height = this.imageObj.height;
  8142. }
  8143. this.width = width;
  8144. this.height = height;
  8145. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  8146. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  8147. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  8148. }
  8149. };
  8150. Node.prototype._drawImage = function (ctx) {
  8151. this._resizeImage(ctx);
  8152. this.left = this.x - this.width / 2;
  8153. this.top = this.y - this.height / 2;
  8154. var yLabel;
  8155. if (this.imageObj) {
  8156. // draw the shade
  8157. if (this.clusterSize > 1) {
  8158. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8159. lineWidth *= this.graphScaleInv;
  8160. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8161. ctx.globalAlpha = 0.5;
  8162. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8163. }
  8164. ctx.globalAlpha = 1.0;
  8165. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8166. yLabel = this.y + this.height / 2;
  8167. }
  8168. else {
  8169. // image still loading... just draw the label for now
  8170. yLabel = this.y;
  8171. }
  8172. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8173. };
  8174. Node.prototype._resizeBox = function (ctx) {
  8175. if (!this.width) {
  8176. var margin = 5;
  8177. var textSize = this.getTextSize(ctx);
  8178. this.width = textSize.width + 2 * margin;
  8179. this.height = textSize.height + 2 * margin;
  8180. this.width += this.clusterSize * 0.5 * this.clusterSizeWidthFactor;
  8181. this.height += this.clusterSize * 0.5 * this.clusterSizeHeightFactor;
  8182. //this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  8183. }
  8184. };
  8185. Node.prototype._drawBox = function (ctx) {
  8186. this._resizeBox(ctx);
  8187. this.left = this.x - this.width / 2;
  8188. this.top = this.y - this.height / 2;
  8189. var clusterLineWidth = 2.5;
  8190. var selectionLineWidth = 2;
  8191. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8192. // draw the outer border
  8193. if (this.clusterSize > 1) {
  8194. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8195. ctx.lineWidth *= this.graphScaleInv;
  8196. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8197. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8198. ctx.stroke();
  8199. }
  8200. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8201. ctx.lineWidth *= this.graphScaleInv;
  8202. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8203. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8204. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8205. ctx.fill();
  8206. ctx.stroke();
  8207. this._label(ctx, this.label, this.x, this.y);
  8208. };
  8209. Node.prototype._resizeDatabase = function (ctx) {
  8210. if (!this.width) {
  8211. var margin = 5;
  8212. var textSize = this.getTextSize(ctx);
  8213. var size = textSize.width + 2 * margin;
  8214. this.width = size;
  8215. this.height = size;
  8216. // scaling used for clustering
  8217. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  8218. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  8219. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  8220. }
  8221. };
  8222. Node.prototype._drawDatabase = function (ctx) {
  8223. this._resizeDatabase(ctx);
  8224. this.left = this.x - this.width / 2;
  8225. this.top = this.y - this.height / 2;
  8226. var clusterLineWidth = 2.5;
  8227. var selectionLineWidth = 2;
  8228. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8229. // draw the outer border
  8230. if (this.clusterSize > 1) {
  8231. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8232. ctx.lineWidth *= this.graphScaleInv;
  8233. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8234. 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);
  8235. ctx.stroke();
  8236. }
  8237. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8238. ctx.lineWidth *= this.graphScaleInv;
  8239. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8240. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8241. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8242. ctx.fill();
  8243. ctx.stroke();
  8244. this._label(ctx, this.label, this.x, this.y);
  8245. };
  8246. Node.prototype._resizeCircle = function (ctx) {
  8247. if (!this.width) {
  8248. var margin = 5;
  8249. var textSize = this.getTextSize(ctx);
  8250. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8251. this.radius = diameter / 2;
  8252. this.width = diameter;
  8253. this.height = diameter;
  8254. // scaling used for clustering
  8255. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  8256. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  8257. this.radius += this.clusterSize * 0.5*this.clusterSizeRadiusFactor;
  8258. }
  8259. };
  8260. Node.prototype._drawCircle = function (ctx) {
  8261. this._resizeCircle(ctx);
  8262. this.left = this.x - this.width / 2;
  8263. this.top = this.y - this.height / 2;
  8264. var clusterLineWidth = 2.5;
  8265. var selectionLineWidth = 2;
  8266. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8267. // draw the outer border
  8268. if (this.clusterSize > 1) {
  8269. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8270. ctx.lineWidth *= this.graphScaleInv;
  8271. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8272. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8273. ctx.stroke();
  8274. }
  8275. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8276. ctx.lineWidth *= this.graphScaleInv;
  8277. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8278. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8279. ctx.circle(this.x, this.y, this.radius);
  8280. ctx.fill();
  8281. ctx.stroke();
  8282. this._label(ctx, this.label, this.x, this.y);
  8283. };
  8284. Node.prototype._resizeEllipse = function (ctx) {
  8285. if (!this.width) {
  8286. var textSize = this.getTextSize(ctx);
  8287. this.width = textSize.width * 1.5;
  8288. this.height = textSize.height * 2;
  8289. if (this.width < this.height) {
  8290. this.width = this.height;
  8291. }
  8292. // scaling used for clustering
  8293. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  8294. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  8295. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  8296. }
  8297. };
  8298. Node.prototype._drawEllipse = function (ctx) {
  8299. this._resizeEllipse(ctx);
  8300. this.left = this.x - this.width / 2;
  8301. this.top = this.y - this.height / 2;
  8302. var clusterLineWidth = 2.5;
  8303. var selectionLineWidth = 2;
  8304. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8305. // draw the outer border
  8306. if (this.clusterSize > 1) {
  8307. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8308. ctx.lineWidth *= this.graphScaleInv;
  8309. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8310. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8311. ctx.stroke();
  8312. }
  8313. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8314. ctx.lineWidth *= this.graphScaleInv;
  8315. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8316. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8317. ctx.ellipse(this.left, this.top, this.width, this.height);
  8318. ctx.fill();
  8319. ctx.stroke();
  8320. this._label(ctx, this.label, this.x, this.y);
  8321. };
  8322. Node.prototype._drawDot = function (ctx) {
  8323. this._drawShape(ctx, 'circle');
  8324. };
  8325. Node.prototype._drawTriangle = function (ctx) {
  8326. this._drawShape(ctx, 'triangle');
  8327. };
  8328. Node.prototype._drawTriangleDown = function (ctx) {
  8329. this._drawShape(ctx, 'triangleDown');
  8330. };
  8331. Node.prototype._drawSquare = function (ctx) {
  8332. this._drawShape(ctx, 'square');
  8333. };
  8334. Node.prototype._drawStar = function (ctx) {
  8335. this._drawShape(ctx, 'star');
  8336. };
  8337. Node.prototype._resizeShape = function (ctx) {
  8338. if (!this.width) {
  8339. this.radius = this.baseRadiusValue;
  8340. var size = 2 * this.radius;
  8341. this.width = size;
  8342. this.height = size;
  8343. // scaling used for clustering
  8344. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  8345. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  8346. this.radius += this.clusterSize * 0.5 * this.clusterSizeRadiusFactor;
  8347. }
  8348. };
  8349. Node.prototype._drawShape = function (ctx, shape) {
  8350. this._resizeShape(ctx);
  8351. this.left = this.x - this.width / 2;
  8352. this.top = this.y - this.height / 2;
  8353. var clusterLineWidth = 2.5;
  8354. var selectionLineWidth = 2;
  8355. var radiusMultiplier = 2;
  8356. // choose draw method depending on the shape
  8357. switch (shape) {
  8358. case 'dot': radiusMultiplier = 2; break;
  8359. case 'square': radiusMultiplier = 2; break;
  8360. case 'triangle': radiusMultiplier = 3; break;
  8361. case 'triangleDown': radiusMultiplier = 3; break;
  8362. case 'star': radiusMultiplier = 4; break;
  8363. }
  8364. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8365. // draw the outer border
  8366. if (this.clusterSize > 1) {
  8367. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8368. ctx.lineWidth *= this.graphScaleInv;
  8369. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8370. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8371. ctx.stroke();
  8372. }
  8373. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8374. ctx.lineWidth *= this.graphScaleInv;
  8375. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8376. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8377. ctx[shape](this.x, this.y, this.radius);
  8378. ctx.fill();
  8379. ctx.stroke();
  8380. if (this.label) {
  8381. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8382. }
  8383. };
  8384. Node.prototype._resizeText = function (ctx) {
  8385. if (!this.width) {
  8386. var margin = 5;
  8387. var textSize = this.getTextSize(ctx);
  8388. this.width = textSize.width + 2 * margin;
  8389. this.height = textSize.height + 2 * margin;
  8390. // scaling used for clustering
  8391. this.width += this.clusterSize * this.clusterSizeWidthFactor;
  8392. this.height += this.clusterSize * this.clusterSizeHeightFactor;
  8393. this.radius += this.clusterSize * this.clusterSizeRadiusFactor;
  8394. }
  8395. };
  8396. Node.prototype._drawText = function (ctx) {
  8397. this._resizeText(ctx);
  8398. this.left = this.x - this.width / 2;
  8399. this.top = this.y - this.height / 2;
  8400. this._label(ctx, this.label, this.x, this.y);
  8401. };
  8402. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  8403. if (text) {
  8404. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8405. ctx.fillStyle = this.fontColor || "black";
  8406. ctx.textAlign = align || "center";
  8407. ctx.textBaseline = baseline || "middle";
  8408. var lines = text.split('\n'),
  8409. lineCount = lines.length,
  8410. fontSize = (this.fontSize + 4),
  8411. yLine = y + (1 - lineCount) / 2 * fontSize;
  8412. for (var i = 0; i < lineCount; i++) {
  8413. ctx.fillText(lines[i], x, yLine);
  8414. yLine += fontSize;
  8415. }
  8416. }
  8417. };
  8418. Node.prototype.getTextSize = function(ctx) {
  8419. if (this.label !== undefined) {
  8420. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8421. var lines = this.label.split('\n'),
  8422. height = (this.fontSize + 4) * lines.length,
  8423. width = 0;
  8424. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  8425. width = Math.max(width, ctx.measureText(lines[i]).width);
  8426. }
  8427. return {"width": width, "height": height};
  8428. }
  8429. else {
  8430. return {"width": 0, "height": 0};
  8431. }
  8432. };
  8433. /**
  8434. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  8435. * there is a safety margin of 0.3 * width;
  8436. *
  8437. * @returns {boolean}
  8438. */
  8439. Node.prototype.inArea = function() {
  8440. if (this.width !== undefined) {
  8441. return (this.x + this.width*0.8 >= this.canvasTopLeft.x &&
  8442. this.x - this.width*0.8 < this.canvasBottomRight.x &&
  8443. this.y + this.height*0.8 >= this.canvasTopLeft.y &&
  8444. this.y - this.height*0.8 < this.canvasBottomRight.y);
  8445. }
  8446. else {
  8447. return true;
  8448. }
  8449. }
  8450. /**
  8451. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  8452. * @returns {boolean}
  8453. */
  8454. Node.prototype.inView = function() {
  8455. return (this.x >= this.canvasTopLeft.x &&
  8456. this.x < this.canvasBottomRight.x &&
  8457. this.y >= this.canvasTopLeft.y &&
  8458. this.y < this.canvasBottomRight.y);
  8459. }
  8460. /**
  8461. * This allows the zoom level of the graph to influence the rendering
  8462. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  8463. *
  8464. * @param scale
  8465. */
  8466. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  8467. this.graphScaleInv = 1.0/scale;
  8468. this.canvasTopLeft = canvasTopLeft;
  8469. this.canvasBottomRight = canvasBottomRight;
  8470. };
  8471. /**
  8472. * This function updates the damping parameter for clusters, based ont he
  8473. *
  8474. * @param {Integer} numberOfNodes
  8475. */
  8476. Node.prototype.updateDamping = function(numberOfNodes) {
  8477. this.damping = 0.8 + 0.1*this.clusterSize * (1 + 2/Math.pow(numberOfNodes,2));
  8478. };
  8479. /**
  8480. * set the velocity at 0. Is called when this node is contained in another during clustering
  8481. */
  8482. Node.prototype.clearVelocity = function() {
  8483. this.vx = 0;
  8484. this.vy = 0;
  8485. };
  8486. /**
  8487. * Basic preservation of (kinectic) energy
  8488. *
  8489. * @param massBeforeClustering
  8490. */
  8491. Node.prototype.updateVelocity = function(massBeforeClustering) {
  8492. var energyBefore = this.vx * this.vx * massBeforeClustering;
  8493. this.vx = Math.sqrt(energyBefore/this.mass);
  8494. energyBefore = this.vy * this.vy * massBeforeClustering;
  8495. this.vy = Math.sqrt(energyBefore/this.mass);
  8496. };
  8497. /**
  8498. * @class Edge
  8499. *
  8500. * A edge connects two nodes
  8501. * @param {Object} properties Object with properties. Must contain
  8502. * At least properties from and to.
  8503. * Available properties: from (number),
  8504. * to (number), label (string, color (string),
  8505. * width (number), style (string),
  8506. * length (number), title (string)
  8507. * @param {Graph} graph A graph object, used to find and edge to
  8508. * nodes.
  8509. * @param {Object} constants An object with default values for
  8510. * example for the color
  8511. */
  8512. function Edge (properties, graph, constants) {
  8513. if (!graph) {
  8514. throw "No graph provided";
  8515. }
  8516. this.graph = graph;
  8517. // initialize constants
  8518. this.widthMin = constants.edges.widthMin;
  8519. this.widthMax = constants.edges.widthMax;
  8520. // initialize variables
  8521. this.id = undefined;
  8522. this.fromId = undefined;
  8523. this.toId = undefined;
  8524. this.style = constants.edges.style;
  8525. this.title = undefined;
  8526. this.width = constants.edges.width;
  8527. this.value = undefined;
  8528. this.length = constants.edges.length;
  8529. this.from = null; // a node
  8530. this.to = null; // a node
  8531. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  8532. // by storing the original information we can revert to the original connection when the cluser is opened.
  8533. this.originalFromID = [];
  8534. this.originalToID = [];
  8535. this.connected = false;
  8536. // Added to support dashed lines
  8537. // David Jordan
  8538. // 2012-08-08
  8539. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  8540. this.stiffness = undefined; // depends on the length of the edge
  8541. this.color = constants.edges.color;
  8542. this.widthFixed = false;
  8543. this.lengthFixed = false;
  8544. this.setProperties(properties, constants);
  8545. };
  8546. /**
  8547. * Set or overwrite properties for the edge
  8548. * @param {Object} properties an object with properties
  8549. * @param {Object} constants and object with default, global properties
  8550. */
  8551. Edge.prototype.setProperties = function(properties, constants) {
  8552. if (!properties) {
  8553. return;
  8554. }
  8555. if (properties.from != undefined) {this.fromId = properties.from;}
  8556. if (properties.to != undefined) {this.toId = properties.to;}
  8557. if (properties.id != undefined) {this.id = properties.id;}
  8558. if (properties.style != undefined) {this.style = properties.style;}
  8559. if (properties.label != undefined) {this.label = properties.label;}
  8560. if (this.label) {
  8561. this.fontSize = constants.edges.fontSize;
  8562. this.fontFace = constants.edges.fontFace;
  8563. this.fontColor = constants.edges.fontColor;
  8564. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  8565. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  8566. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  8567. }
  8568. if (properties.title != undefined) {this.title = properties.title;}
  8569. if (properties.width != undefined) {this.width = properties.width;}
  8570. if (properties.value != undefined) {this.value = properties.value;}
  8571. if (properties.length != undefined) {this.length = properties.length;}
  8572. // Added to support dashed lines
  8573. // David Jordan
  8574. // 2012-08-08
  8575. if (properties.dash) {
  8576. if (properties.dash.length != undefined) {this.dash.length = properties.dash.length;}
  8577. if (properties.dash.gap != undefined) {this.dash.gap = properties.dash.gap;}
  8578. if (properties.dash.altLength != undefined) {this.dash.altLength = properties.dash.altLength;}
  8579. }
  8580. if (properties.color != undefined) {this.color = properties.color;}
  8581. // A node is connected when it has a from and to node.
  8582. this.connect();
  8583. this.widthFixed = this.widthFixed || (properties.width != undefined);
  8584. this.lengthFixed = this.lengthFixed || (properties.length != undefined);
  8585. this.stiffness = 1 / this.length;
  8586. // set draw method based on style
  8587. switch (this.style) {
  8588. case 'line': this.draw = this._drawLine; break;
  8589. case 'arrow': this.draw = this._drawArrow; break;
  8590. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  8591. case 'dash-line': this.draw = this._drawDashLine; break;
  8592. default: this.draw = this._drawLine; break;
  8593. }
  8594. };
  8595. /**
  8596. * Connect an edge to its nodes
  8597. */
  8598. Edge.prototype.connect = function () {
  8599. this.disconnect();
  8600. this.from = this.graph.nodes[this.fromId] || null;
  8601. this.to = this.graph.nodes[this.toId] || null;
  8602. this.connected = (this.from && this.to);
  8603. if (this.connected) {
  8604. this.from.attachEdge(this);
  8605. this.to.attachEdge(this);
  8606. }
  8607. else {
  8608. if (this.from) {
  8609. this.from.detachEdge(this);
  8610. }
  8611. if (this.to) {
  8612. this.to.detachEdge(this);
  8613. }
  8614. }
  8615. };
  8616. /**
  8617. * Disconnect an edge from its nodes
  8618. */
  8619. Edge.prototype.disconnect = function () {
  8620. if (this.from) {
  8621. this.from.detachEdge(this);
  8622. this.from = null;
  8623. }
  8624. if (this.to) {
  8625. this.to.detachEdge(this);
  8626. this.to = null;
  8627. }
  8628. this.connected = false;
  8629. };
  8630. /**
  8631. * get the title of this edge.
  8632. * @return {string} title The title of the edge, or undefined when no title
  8633. * has been set.
  8634. */
  8635. Edge.prototype.getTitle = function() {
  8636. return this.title;
  8637. };
  8638. /**
  8639. * Retrieve the value of the edge. Can be undefined
  8640. * @return {Number} value
  8641. */
  8642. Edge.prototype.getValue = function() {
  8643. return this.value;
  8644. };
  8645. /**
  8646. * Adjust the value range of the edge. The edge will adjust it's width
  8647. * based on its value.
  8648. * @param {Number} min
  8649. * @param {Number} max
  8650. */
  8651. Edge.prototype.setValueRange = function(min, max) {
  8652. if (!this.widthFixed && this.value !== undefined) {
  8653. var scale = (this.widthMax - this.widthMin) / (max - min);
  8654. this.width = (this.value - min) * scale + this.widthMin;
  8655. }
  8656. };
  8657. /**
  8658. * Redraw a edge
  8659. * Draw this edge in the given canvas
  8660. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8661. * @param {CanvasRenderingContext2D} ctx
  8662. */
  8663. Edge.prototype.draw = function(ctx) {
  8664. throw "Method draw not initialized in edge";
  8665. };
  8666. /**
  8667. * Check if this object is overlapping with the provided object
  8668. * @param {Object} obj an object with parameters left, top
  8669. * @return {boolean} True if location is located on the edge
  8670. */
  8671. Edge.prototype.isOverlappingWith = function(obj) {
  8672. var distMax = 10;
  8673. var xFrom = this.from.x;
  8674. var yFrom = this.from.y;
  8675. var xTo = this.to.x;
  8676. var yTo = this.to.y;
  8677. var xObj = obj.left;
  8678. var yObj = obj.top;
  8679. var dist = Edge._dist(xFrom, yFrom, xTo, yTo, xObj, yObj);
  8680. return (dist < distMax);
  8681. };
  8682. /**
  8683. * Redraw a edge as a line
  8684. * Draw this edge in the given canvas
  8685. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8686. * @param {CanvasRenderingContext2D} ctx
  8687. * @private
  8688. */
  8689. Edge.prototype._drawLine = function(ctx) {
  8690. // set style
  8691. ctx.strokeStyle = this.color;
  8692. ctx.lineWidth = this._getLineWidth();
  8693. var point;
  8694. if (this.from != this.to) {
  8695. // draw line
  8696. this._line(ctx);
  8697. // draw label
  8698. if (this.label) {
  8699. point = this._pointOnLine(0.5);
  8700. this._label(ctx, this.label, point.x, point.y);
  8701. }
  8702. }
  8703. else {
  8704. var x, y;
  8705. var radius = this.length / 4;
  8706. var node = this.from;
  8707. if (!node.width) {
  8708. node.resize(ctx);
  8709. }
  8710. if (node.width > node.height) {
  8711. x = node.x + node.width / 2;
  8712. y = node.y - radius;
  8713. }
  8714. else {
  8715. x = node.x + radius;
  8716. y = node.y - node.height / 2;
  8717. }
  8718. this._circle(ctx, x, y, radius);
  8719. point = this._pointOnCircle(x, y, radius, 0.5);
  8720. this._label(ctx, this.label, point.x, point.y);
  8721. }
  8722. };
  8723. /**
  8724. * Get the line width of the edge. Depends on width and whether one of the
  8725. * connected nodes is selected.
  8726. * @return {Number} width
  8727. * @private
  8728. */
  8729. Edge.prototype._getLineWidth = function() {
  8730. if (this.from.selected || this.to.selected) {
  8731. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  8732. }
  8733. else {
  8734. return this.width*this.graphScaleInv;
  8735. }
  8736. };
  8737. /**
  8738. * Draw a line between two nodes
  8739. * @param {CanvasRenderingContext2D} ctx
  8740. * @private
  8741. */
  8742. Edge.prototype._line = function (ctx) {
  8743. // draw a straight line
  8744. ctx.beginPath();
  8745. ctx.moveTo(this.from.x, this.from.y);
  8746. ctx.lineTo(this.to.x, this.to.y);
  8747. ctx.stroke();
  8748. };
  8749. /**
  8750. * Draw a line from a node to itself, a circle
  8751. * @param {CanvasRenderingContext2D} ctx
  8752. * @param {Number} x
  8753. * @param {Number} y
  8754. * @param {Number} radius
  8755. * @private
  8756. */
  8757. Edge.prototype._circle = function (ctx, x, y, radius) {
  8758. // draw a circle
  8759. ctx.beginPath();
  8760. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  8761. ctx.stroke();
  8762. };
  8763. /**
  8764. * Draw label with white background and with the middle at (x, y)
  8765. * @param {CanvasRenderingContext2D} ctx
  8766. * @param {String} text
  8767. * @param {Number} x
  8768. * @param {Number} y
  8769. * @private
  8770. */
  8771. Edge.prototype._label = function (ctx, text, x, y) {
  8772. if (text) {
  8773. // TODO: cache the calculated size
  8774. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  8775. this.fontSize + "px " + this.fontFace;
  8776. ctx.fillStyle = 'white';
  8777. var width = ctx.measureText(text).width;
  8778. var height = this.fontSize;
  8779. var left = x - width / 2;
  8780. var top = y - height / 2;
  8781. ctx.fillRect(left, top, width, height);
  8782. // draw text
  8783. ctx.fillStyle = this.fontColor || "black";
  8784. ctx.textAlign = "left";
  8785. ctx.textBaseline = "top";
  8786. ctx.fillText(text, left, top);
  8787. }
  8788. };
  8789. /**
  8790. * Redraw a edge as a dashed line
  8791. * Draw this edge in the given canvas
  8792. * @author David Jordan
  8793. * @date 2012-08-08
  8794. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8795. * @param {CanvasRenderingContext2D} ctx
  8796. * @private
  8797. */
  8798. Edge.prototype._drawDashLine = function(ctx) {
  8799. // set style
  8800. ctx.strokeStyle = this.color;
  8801. ctx.lineWidth = this._getLineWidth();
  8802. // draw dashed line
  8803. ctx.beginPath();
  8804. ctx.lineCap = 'round';
  8805. if (this.dash.altLength != undefined) //If an alt dash value has been set add to the array this value
  8806. {
  8807. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8808. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  8809. }
  8810. 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
  8811. {
  8812. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8813. [this.dash.length,this.dash.gap]);
  8814. }
  8815. else //If all else fails draw a line
  8816. {
  8817. ctx.moveTo(this.from.x, this.from.y);
  8818. ctx.lineTo(this.to.x, this.to.y);
  8819. }
  8820. ctx.stroke();
  8821. // draw label
  8822. if (this.label) {
  8823. var point = this._pointOnLine(0.5);
  8824. this._label(ctx, this.label, point.x, point.y);
  8825. }
  8826. };
  8827. /**
  8828. * Get a point on a line
  8829. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8830. * @return {Object} point
  8831. * @private
  8832. */
  8833. Edge.prototype._pointOnLine = function (percentage) {
  8834. return {
  8835. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  8836. y: (1 - percentage) * this.from.y + percentage * this.to.y
  8837. }
  8838. };
  8839. /**
  8840. * Get a point on a circle
  8841. * @param {Number} x
  8842. * @param {Number} y
  8843. * @param {Number} radius
  8844. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8845. * @return {Object} point
  8846. * @private
  8847. */
  8848. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  8849. var angle = (percentage - 3/8) * 2 * Math.PI;
  8850. return {
  8851. x: x + radius * Math.cos(angle),
  8852. y: y - radius * Math.sin(angle)
  8853. }
  8854. };
  8855. /**
  8856. * Redraw a edge as a line with an arrow halfway the line
  8857. * Draw this edge in the given canvas
  8858. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8859. * @param {CanvasRenderingContext2D} ctx
  8860. * @private
  8861. */
  8862. Edge.prototype._drawArrowCenter = function(ctx) {
  8863. var point;
  8864. // set style
  8865. ctx.strokeStyle = this.color;
  8866. ctx.fillStyle = this.color;
  8867. ctx.lineWidth = this._getLineWidth();
  8868. if (this.from != this.to) {
  8869. // draw line
  8870. this._line(ctx);
  8871. // draw an arrow halfway the line
  8872. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8873. var length = 10 + 5 * this.width; // TODO: make customizable?
  8874. point = this._pointOnLine(0.5);
  8875. ctx.arrow(point.x, point.y, angle, length);
  8876. ctx.fill();
  8877. ctx.stroke();
  8878. // draw label
  8879. if (this.label) {
  8880. point = this._pointOnLine(0.5);
  8881. this._label(ctx, this.label, point.x, point.y);
  8882. }
  8883. }
  8884. else {
  8885. // draw circle
  8886. var x, y;
  8887. var radius = this.length / 4;
  8888. var node = this.from;
  8889. if (!node.width) {
  8890. node.resize(ctx);
  8891. }
  8892. if (node.width > node.height) {
  8893. x = node.x + node.width / 2;
  8894. y = node.y - radius;
  8895. }
  8896. else {
  8897. x = node.x + radius;
  8898. y = node.y - node.height / 2;
  8899. }
  8900. this._circle(ctx, x, y, radius);
  8901. // draw all arrows
  8902. var angle = 0.2 * Math.PI;
  8903. var length = 10 + 5 * this.width; // TODO: make customizable?
  8904. point = this._pointOnCircle(x, y, radius, 0.5);
  8905. ctx.arrow(point.x, point.y, angle, length);
  8906. ctx.fill();
  8907. ctx.stroke();
  8908. // draw label
  8909. if (this.label) {
  8910. point = this._pointOnCircle(x, y, radius, 0.5);
  8911. this._label(ctx, this.label, point.x, point.y);
  8912. }
  8913. }
  8914. };
  8915. /**
  8916. * Redraw a edge as a line with an arrow
  8917. * Draw this edge in the given canvas
  8918. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8919. * @param {CanvasRenderingContext2D} ctx
  8920. * @private
  8921. */
  8922. Edge.prototype._drawArrow = function(ctx) {
  8923. // set style
  8924. ctx.strokeStyle = this.color;
  8925. ctx.fillStyle = this.color;
  8926. ctx.lineWidth = this._getLineWidth();
  8927. // draw line
  8928. var angle, length;
  8929. if (this.from != this.to) {
  8930. // calculate length and angle of the line
  8931. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8932. var dx = (this.to.x - this.from.x);
  8933. var dy = (this.to.y - this.from.y);
  8934. var lEdge = Math.sqrt(dx * dx + dy * dy);
  8935. var lFrom = this.from.distanceToBorder(ctx, angle + Math.PI);
  8936. var pFrom = (lEdge - lFrom) / lEdge;
  8937. var xFrom = (pFrom) * this.from.x + (1 - pFrom) * this.to.x;
  8938. var yFrom = (pFrom) * this.from.y + (1 - pFrom) * this.to.y;
  8939. var lTo = this.to.distanceToBorder(ctx, angle);
  8940. var pTo = (lEdge - lTo) / lEdge;
  8941. var xTo = (1 - pTo) * this.from.x + pTo * this.to.x;
  8942. var yTo = (1 - pTo) * this.from.y + pTo * this.to.y;
  8943. ctx.beginPath();
  8944. ctx.moveTo(xFrom, yFrom);
  8945. ctx.lineTo(xTo, yTo);
  8946. ctx.stroke();
  8947. // draw arrow at the end of the line
  8948. length = 10 + 5 * this.width; // TODO: make customizable?
  8949. ctx.arrow(xTo, yTo, angle, length);
  8950. ctx.fill();
  8951. ctx.stroke();
  8952. // draw label
  8953. if (this.label) {
  8954. var point = this._pointOnLine(0.5);
  8955. this._label(ctx, this.label, point.x, point.y);
  8956. }
  8957. }
  8958. else {
  8959. // draw circle
  8960. var node = this.from;
  8961. var x, y, arrow;
  8962. var radius = this.length / 4;
  8963. if (!node.width) {
  8964. node.resize(ctx);
  8965. }
  8966. if (node.width > node.height) {
  8967. x = node.x + node.width / 2;
  8968. y = node.y - radius;
  8969. arrow = {
  8970. x: x,
  8971. y: node.y,
  8972. angle: 0.9 * Math.PI
  8973. };
  8974. }
  8975. else {
  8976. x = node.x + radius;
  8977. y = node.y - node.height / 2;
  8978. arrow = {
  8979. x: node.x,
  8980. y: y,
  8981. angle: 0.6 * Math.PI
  8982. };
  8983. }
  8984. ctx.beginPath();
  8985. // TODO: do not draw a circle, but an arc
  8986. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  8987. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  8988. ctx.stroke();
  8989. // draw all arrows
  8990. length = 10 + 5 * this.width; // TODO: make customizable?
  8991. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  8992. ctx.fill();
  8993. ctx.stroke();
  8994. // draw label
  8995. if (this.label) {
  8996. point = this._pointOnCircle(x, y, radius, 0.5);
  8997. this._label(ctx, this.label, point.x, point.y);
  8998. }
  8999. }
  9000. };
  9001. /**
  9002. * Calculate the distance between a point (x3,y3) and a line segment from
  9003. * (x1,y1) to (x2,y2).
  9004. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9005. * @param {number} x1
  9006. * @param {number} y1
  9007. * @param {number} x2
  9008. * @param {number} y2
  9009. * @param {number} x3
  9010. * @param {number} y3
  9011. * @private
  9012. */
  9013. Edge._dist = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9014. var px = x2-x1,
  9015. py = y2-y1,
  9016. something = px*px + py*py,
  9017. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9018. if (u > 1) {
  9019. u = 1;
  9020. }
  9021. else if (u < 0) {
  9022. u = 0;
  9023. }
  9024. var x = x1 + u * px,
  9025. y = y1 + u * py,
  9026. dx = x - x3,
  9027. dy = y - y3;
  9028. //# Note: If the actual distance does not matter,
  9029. //# if you only want to compare what this function
  9030. //# returns to other results of this function, you
  9031. //# can just return the squared distance instead
  9032. //# (i.e. remove the sqrt) to gain a little performance
  9033. return Math.sqrt(dx*dx + dy*dy);
  9034. };
  9035. /**
  9036. * This allows the zoom level of the graph to influence the rendering
  9037. *
  9038. * @param scale
  9039. */
  9040. Edge.prototype.setScale = function(scale) {
  9041. this.graphScaleInv = 1.0/scale;
  9042. };
  9043. /**
  9044. * Popup is a class to create a popup window with some text
  9045. * @param {Element} container The container object.
  9046. * @param {Number} [x]
  9047. * @param {Number} [y]
  9048. * @param {String} [text]
  9049. */
  9050. function Popup(container, x, y, text) {
  9051. if (container) {
  9052. this.container = container;
  9053. }
  9054. else {
  9055. this.container = document.body;
  9056. }
  9057. this.x = 0;
  9058. this.y = 0;
  9059. this.padding = 5;
  9060. if (x !== undefined && y !== undefined ) {
  9061. this.setPosition(x, y);
  9062. }
  9063. if (text !== undefined) {
  9064. this.setText(text);
  9065. }
  9066. // create the frame
  9067. this.frame = document.createElement("div");
  9068. var style = this.frame.style;
  9069. style.position = "absolute";
  9070. style.visibility = "hidden";
  9071. style.border = "1px solid #666";
  9072. style.color = "black";
  9073. style.padding = this.padding + "px";
  9074. style.backgroundColor = "#FFFFC6";
  9075. style.borderRadius = "3px";
  9076. style.MozBorderRadius = "3px";
  9077. style.WebkitBorderRadius = "3px";
  9078. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9079. style.whiteSpace = "nowrap";
  9080. this.container.appendChild(this.frame);
  9081. };
  9082. /**
  9083. * @param {number} x Horizontal position of the popup window
  9084. * @param {number} y Vertical position of the popup window
  9085. */
  9086. Popup.prototype.setPosition = function(x, y) {
  9087. this.x = parseInt(x);
  9088. this.y = parseInt(y);
  9089. };
  9090. /**
  9091. * Set the text for the popup window. This can be HTML code
  9092. * @param {string} text
  9093. */
  9094. Popup.prototype.setText = function(text) {
  9095. this.frame.innerHTML = text;
  9096. };
  9097. /**
  9098. * Show the popup window
  9099. * @param {boolean} show Optional. Show or hide the window
  9100. */
  9101. Popup.prototype.show = function (show) {
  9102. if (show === undefined) {
  9103. show = true;
  9104. }
  9105. if (show) {
  9106. var height = this.frame.clientHeight;
  9107. var width = this.frame.clientWidth;
  9108. var maxHeight = this.frame.parentNode.clientHeight;
  9109. var maxWidth = this.frame.parentNode.clientWidth;
  9110. var top = (this.y - height);
  9111. if (top + height + this.padding > maxHeight) {
  9112. top = maxHeight - height - this.padding;
  9113. }
  9114. if (top < this.padding) {
  9115. top = this.padding;
  9116. }
  9117. var left = this.x;
  9118. if (left + width + this.padding > maxWidth) {
  9119. left = maxWidth - width - this.padding;
  9120. }
  9121. if (left < this.padding) {
  9122. left = this.padding;
  9123. }
  9124. this.frame.style.left = left + "px";
  9125. this.frame.style.top = top + "px";
  9126. this.frame.style.visibility = "visible";
  9127. }
  9128. else {
  9129. this.hide();
  9130. }
  9131. };
  9132. /**
  9133. * Hide the popup window
  9134. */
  9135. Popup.prototype.hide = function () {
  9136. this.frame.style.visibility = "hidden";
  9137. };
  9138. /**
  9139. * @class Groups
  9140. * This class can store groups and properties specific for groups.
  9141. */
  9142. Groups = function () {
  9143. this.clear();
  9144. this.defaultIndex = 0;
  9145. };
  9146. /**
  9147. * default constants for group colors
  9148. */
  9149. Groups.DEFAULT = [
  9150. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9151. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9152. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9153. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9154. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9155. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9156. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9157. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9158. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9159. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9160. ];
  9161. /**
  9162. * Clear all groups
  9163. */
  9164. Groups.prototype.clear = function () {
  9165. this.groups = {};
  9166. this.groups.length = function()
  9167. {
  9168. var i = 0;
  9169. for ( var p in this ) {
  9170. if (this.hasOwnProperty(p)) {
  9171. i++;
  9172. }
  9173. }
  9174. return i;
  9175. }
  9176. };
  9177. /**
  9178. * get group properties of a groupname. If groupname is not found, a new group
  9179. * is added.
  9180. * @param {*} groupname Can be a number, string, Date, etc.
  9181. * @return {Object} group The created group, containing all group properties
  9182. */
  9183. Groups.prototype.get = function (groupname) {
  9184. var group = this.groups[groupname];
  9185. if (group == undefined) {
  9186. // create new group
  9187. var index = this.defaultIndex % Groups.DEFAULT.length;
  9188. this.defaultIndex++;
  9189. group = {};
  9190. group.color = Groups.DEFAULT[index];
  9191. this.groups[groupname] = group;
  9192. }
  9193. return group;
  9194. };
  9195. /**
  9196. * Add a custom group style
  9197. * @param {String} groupname
  9198. * @param {Object} style An object containing borderColor,
  9199. * backgroundColor, etc.
  9200. * @return {Object} group The created group object
  9201. */
  9202. Groups.prototype.add = function (groupname, style) {
  9203. this.groups[groupname] = style;
  9204. if (style.color) {
  9205. style.color = Node.parseColor(style.color);
  9206. }
  9207. return style;
  9208. };
  9209. /**
  9210. * @class Images
  9211. * This class loads images and keeps them stored.
  9212. */
  9213. Images = function () {
  9214. this.images = {};
  9215. this.callback = undefined;
  9216. };
  9217. /**
  9218. * Set an onload callback function. This will be called each time an image
  9219. * is loaded
  9220. * @param {function} callback
  9221. */
  9222. Images.prototype.setOnloadCallback = function(callback) {
  9223. this.callback = callback;
  9224. };
  9225. /**
  9226. *
  9227. * @param {string} url Url of the image
  9228. * @return {Image} img The image object
  9229. */
  9230. Images.prototype.load = function(url) {
  9231. var img = this.images[url];
  9232. if (img == undefined) {
  9233. // create the image
  9234. var images = this;
  9235. img = new Image();
  9236. this.images[url] = img;
  9237. img.onload = function() {
  9238. if (images.callback) {
  9239. images.callback(this);
  9240. }
  9241. };
  9242. img.src = url;
  9243. }
  9244. return img;
  9245. };
  9246. function Universe() {
  9247. this.universe = {};
  9248. this.activeUniverse = ["default"];
  9249. this.universe["activePockets"] = {};
  9250. this.universe["activePockets"][this.activeUniverse[this.activeUniverse.length-1]] = {"nodes":{},"edges":{},"nodeIndices":[]};
  9251. this.universe["frozenPockets"] = {};
  9252. this.universe["draw"] = {};
  9253. this.nodeIndices = this.universe["activePockets"][this.activeUniverse[this.activeUniverse.length-1]]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  9254. }
  9255. Universe.prototype._putDataInUniverse = function() {
  9256. this.universe["activePockets"][this._universe()].nodes = this.nodes;
  9257. this.universe["activePockets"][this._universe()].edges = this.edges;
  9258. this.universe["activePockets"][this._universe()].nodeIndices = this.nodeIndices;
  9259. };
  9260. Universe.prototype._switchToUniverse = function(universeID) {
  9261. this.nodeIndices = this.universe["activePockets"][universeID]["nodeIndices"];
  9262. this.nodes = this.universe["activePockets"][universeID]["nodes"];
  9263. this.edges = this.universe["activePockets"][universeID]["edges"];
  9264. };
  9265. Universe.prototype._loadActiveUniverse = function() {
  9266. this._switchToUniverse(this._universe());
  9267. };
  9268. Universe.prototype._universe = function() {
  9269. return this.activeUniverse[this.activeUniverse.length-1];
  9270. };
  9271. Universe.prototype._previousUniverse = function() {
  9272. if (this.activeUniverse.length > 1) {
  9273. return this.activeUniverse[this.activeUniverse.length-2];
  9274. }
  9275. else {
  9276. throw new TypeError('there are not enough universes in the this.activeUniverse array.');
  9277. return "";
  9278. }
  9279. };
  9280. Universe.prototype._setActiveUniverse = function(newID) {
  9281. this.activeUniverse.push(newID);
  9282. };
  9283. Universe.prototype._forgetLastUniverse = function() {
  9284. this.activeUniverse.pop();
  9285. };
  9286. Universe.prototype._createNewUniverse = function(newID) {
  9287. this.universe["activePockets"][newID] = {"nodes":{},"edges":{},"nodeIndices":[]}
  9288. };
  9289. Universe.prototype._deleteActiveUniverse = function(universeID) {
  9290. delete this.universe["activePockets"][universeID];
  9291. };
  9292. Universe.prototype._deleteFrozenUniverse = function(universeID) {
  9293. delete this.universe["frozenPockets"][universeID];
  9294. };
  9295. Universe.prototype._freezeUniverse = function(universeID) {
  9296. this.universe["frozenPockets"][universeID] = this.universe["activePockets"][universeID];
  9297. this._deleteActiveUniverse(universeID);
  9298. };
  9299. Universe.prototype._activateUniverse = function(universeID) {
  9300. this.universe["activePockets"][universeID] = this.universe["frozenPockets"][universeID];
  9301. this._deleteFrozenUniverse(universeID);
  9302. };
  9303. Universe.prototype._mergeThisWithFrozen = function(universeID) {
  9304. for (var nodeID in this.nodes) {
  9305. if (this.nodes.hasOwnProperty(nodeID)) {
  9306. this.universe["frozenPockets"][universeID]["nodes"][nodeID] = this.nodes[nodeID];
  9307. }
  9308. }
  9309. for (var edgeID in this.edges) {
  9310. if (this.edges.hasOwnProperty(edgeID)) {
  9311. this.universe["frozenPockets"][universeID]["edges"][edgeID] = this.edges[edgeID];
  9312. }
  9313. }
  9314. for (var i = 0; i < this.nodeIndices.length; i++) {
  9315. this.universe["frozenPockets"][universeID]["edges"][nodeIndices].push(this.nodeIndices[i]);
  9316. }
  9317. };
  9318. Universe.prototype._collapseThisToSingleCluster = function() {
  9319. this.clusterToFit(1,false);
  9320. };
  9321. Universe.prototype._addUniverse = function(node) {
  9322. var universe = this._universe();
  9323. if (this.universe['activePockets'][universe]["nodes"].hasOwnProperty(node.id)) {
  9324. console.log("the node is part of the active universe");
  9325. }
  9326. else {
  9327. console.log("I dont konw what the fuck happened!!");
  9328. }
  9329. delete this.nodes[node.id];
  9330. this._freezeUniverse(universe);
  9331. this._createNewUniverse(node.id);
  9332. this._setActiveUniverse(node.id);
  9333. this._switchToUniverse(this._universe());
  9334. this.nodes[node.id] = node;
  9335. //this.universe["draw"][node.id] = new Node(node.nodeProperties,node.imagelist,node.grouplist,this.constants);
  9336. };
  9337. Universe.prototype._collapseUniverse = function() {
  9338. var universe = this._universe();
  9339. if (universe != "default") {
  9340. var isMovingBeforeClustering = this.moving;
  9341. var previousUniverse = this._previousUniverse();
  9342. this._collapseThisToSingleCluster();
  9343. this._mergeThisWithFrozen(previousUniverse);
  9344. this._deleteActiveUniverse(universe);
  9345. this._activateUniverse(previousUniverse);
  9346. this._switchToUniverse(previousUniverse);
  9347. this._forgetLastUniverse();
  9348. this._updateNodeIndexList();
  9349. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  9350. if (this.moving != isMovingBeforeClustering) {
  9351. this.start();
  9352. }
  9353. }
  9354. };
  9355. Universe.prototype._doInAllActiveUniverses = function(runFunction,arguments) {
  9356. }
  9357. /**
  9358. * @constructor Cluster
  9359. * Contains the cluster properties for the graph object
  9360. */
  9361. function Cluster() {
  9362. this.clusterSession = 0;
  9363. this.hubThreshold = 5;
  9364. }
  9365. /**
  9366. * This function can be called to open up a specific cluster.
  9367. * It will unpack the cluster back one level.
  9368. *
  9369. * @param node | Node object: cluster to open.
  9370. */
  9371. Cluster.prototype.openCluster = function(node) {
  9372. if (node.clusterSize > 15) {
  9373. this._addUniverse(node);
  9374. }
  9375. var isMovingBeforeClustering = this.moving;
  9376. this._expandClusterNode(node,false,true);
  9377. // housekeeping
  9378. this._updateNodeIndexList();
  9379. this._updateDynamicEdges();
  9380. this.updateLabels();
  9381. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  9382. if (this.moving != isMovingBeforeClustering) {
  9383. this.start();
  9384. }
  9385. };
  9386. /**
  9387. * This calls the updateClustes with default arguments
  9388. */
  9389. Cluster.prototype.updateClustersDefault = function() {
  9390. if (this.constants.clustering.enableClustering) {
  9391. this.updateClusters(0,false,false);
  9392. }
  9393. }
  9394. /**
  9395. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  9396. * be clustered with their connected node. This can be repeated as many times as needed.
  9397. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  9398. */
  9399. Cluster.prototype.increaseClusterLevel = function() {
  9400. this.updateClusters(-1,false,true);
  9401. };
  9402. /**
  9403. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  9404. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  9405. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  9406. */
  9407. Cluster.prototype.decreaseClusterLevel = function() {
  9408. this.updateClusters(1,false,true);
  9409. };
  9410. /**
  9411. * This function clusters on zoom, it can be called with a predefined zoom direction
  9412. * If out, check if we can form clusters, if in, check if we can open clusters.
  9413. * This function is only called from _zoom()
  9414. *
  9415. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  9416. * @param {Boolean} recursive | enable or disable recursive calling of the opening of clusters
  9417. * @param {Boolean} force | enable or disable forcing
  9418. *
  9419. */
  9420. Cluster.prototype.updateClusters = function(zoomDirection,recursive,force) {
  9421. var isMovingBeforeClustering = this.moving;
  9422. var amountOfNodes = this.nodeIndices.length;
  9423. // on zoom out collapse the universe back to default
  9424. // if (this.previousScale > this.scale && zoomDirection == 0) {
  9425. // this._collapseUniverse();
  9426. // }
  9427. // check if we zoom in or out
  9428. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  9429. this._formClusters(force);
  9430. }
  9431. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom out
  9432. this._openClusters(recursive,force);
  9433. this._openClustersBySize();
  9434. }
  9435. this._updateNodeIndexList();
  9436. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  9437. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  9438. this._aggregateHubs(force);
  9439. }
  9440. // we now reduce snakes.
  9441. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  9442. this.handleSnakes();
  9443. this._updateNodeIndexList();
  9444. }
  9445. this.previousScale = this.scale;
  9446. // rest of the housekeeping
  9447. this._updateDynamicEdges();
  9448. this.updateLabels();
  9449. // if a cluster was formed, we increase the clusterSession
  9450. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  9451. this.clusterSession += 1;
  9452. }
  9453. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  9454. if (this.moving != isMovingBeforeClustering) {
  9455. this.start();
  9456. }
  9457. };
  9458. /**
  9459. * This function handles the snakes. It is called on every updateClusters().
  9460. */
  9461. Cluster.prototype.handleSnakes = function() {
  9462. // after clustering we check how many snakes there are
  9463. var snakePercentage = this._getSnakeFraction();
  9464. if (snakePercentage > this.constants.clustering.snakeThreshold) {
  9465. this._reduceAmountOfSnakes(1 - this.constants.clustering.snakeThreshold / snakePercentage)
  9466. }
  9467. };
  9468. /**
  9469. * this functions starts clustering by hubs
  9470. * The minimum hub threshold is set globally
  9471. *
  9472. * @private
  9473. */
  9474. Cluster.prototype._aggregateHubs = function(force) {
  9475. this._getHubSize();
  9476. this._formClustersByHub(force);
  9477. };
  9478. /**
  9479. * This function is fired by keypress. It forces hubs to form.
  9480. *
  9481. */
  9482. Cluster.prototype.forceAggregateHubs = function() {
  9483. var isMovingBeforeClustering = this.moving;
  9484. var amountOfNodes = this.nodeIndices.length;
  9485. this._aggregateHubs(true);
  9486. // housekeeping
  9487. this._updateNodeIndexList();
  9488. this._updateDynamicEdges();
  9489. this.updateLabels();
  9490. // if a cluster was formed, we increase the clusterSession
  9491. if (this.nodeIndices.length != amountOfNodes) {
  9492. this.clusterSession += 1;
  9493. }
  9494. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  9495. if (this.moving != isMovingBeforeClustering) {
  9496. this.start();
  9497. }
  9498. };
  9499. /**
  9500. * If a cluster takes up more than a set percentage of the screen, open the cluster
  9501. *
  9502. * @private
  9503. */
  9504. Cluster.prototype._openClustersBySize = function() {
  9505. for (nodeID in this.nodes) {
  9506. if (this.nodes.hasOwnProperty(nodeID)) {
  9507. node = this.nodes[nodeID];
  9508. if (node.inView() == true) {
  9509. if ((node.width*this.scale > this.constants.clustering.relativeOpenFactor * this.frame.canvas.clientWidth) ||
  9510. (node.height*this.scale > this.constants.clustering.relativeOpenFactor * this.frame.canvas.clientHeight)) {
  9511. this.openCluster(node);
  9512. this.openCluster(node);
  9513. }
  9514. }
  9515. }
  9516. }
  9517. };
  9518. /**
  9519. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  9520. * has to be opened based on the current zoom level.
  9521. *
  9522. * @private
  9523. */
  9524. Cluster.prototype._openClusters = function(recursive,force) {
  9525. for (var i = 0; i < this.nodeIndices.length; i++) {
  9526. var node = this.nodes[this.nodeIndices[i]];
  9527. this._expandClusterNode(node,recursive,force);
  9528. }
  9529. };
  9530. /**
  9531. * This function checks if a node has to be opened. This is done by checking the zoom level.
  9532. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  9533. * This recursive behaviour is optional and can be set by the recursive argument.
  9534. *
  9535. * @param {Node} parentNode | to check for cluster and expand
  9536. * @param {Boolean} recursive | enable or disable recursive calling
  9537. * @param {Boolean} force | enable or disable forcing
  9538. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  9539. * @private
  9540. */
  9541. Cluster.prototype._expandClusterNode = function(parentNode, recursive, force, openAll) {
  9542. // first check if node is a cluster
  9543. if (parentNode.clusterSize > 1) {
  9544. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  9545. if (parentNode.clusterSize < 20) {
  9546. openAll = true;
  9547. }
  9548. recursive = openAll ? true : recursive;
  9549. // if the last child has been added on a smaller scale than current scale (@optimization)
  9550. if (parentNode.formationScale < this.scale || force == true) {
  9551. // we will check if any of the contained child nodes should be removed from the cluster
  9552. for (var containedNodeID in parentNode.containedNodes) {
  9553. if (parentNode.containedNodes.hasOwnProperty(containedNodeID)) {
  9554. var childNode = parentNode.containedNodes[containedNodeID];
  9555. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  9556. // the largest cluster is the one that comes from outside
  9557. if (force == true) {
  9558. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  9559. || openAll) {
  9560. this._expelChildFromParent(parentNode,containedNodeID,recursive,force,openAll);
  9561. }
  9562. }
  9563. else {
  9564. if (this._parentNodeInActiveArea(parentNode)) {
  9565. this._expelChildFromParent(parentNode,containedNodeID,recursive,force,openAll);
  9566. }
  9567. }
  9568. }
  9569. }
  9570. }
  9571. }
  9572. };
  9573. /**
  9574. * ONLY CALLED FROM _expandClusterNode
  9575. *
  9576. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  9577. * the child node from the parent contained_node object and put it back into the global nodes object.
  9578. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  9579. *
  9580. * @param {Node} parentNode | the parent node
  9581. * @param {String} containedNodeID | child_node id as it is contained in the containedNodes object of the parent node
  9582. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  9583. * With force and recursive both true, the entire cluster is unpacked
  9584. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  9585. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  9586. * @private
  9587. */
  9588. Cluster.prototype._expelChildFromParent = function(parentNode, containedNodeID, recursive, force, openAll) {
  9589. var childNode = parentNode.containedNodes[containedNodeID];
  9590. // if child node has been added on smaller scale than current, kick out
  9591. if (childNode.formationScale < this.scale || force == true) {
  9592. // put the child node back in the global nodes object
  9593. this.nodes[containedNodeID] = childNode;
  9594. // release the contained edges from this childNode back into the global edges
  9595. this._releaseContainedEdges(parentNode,childNode);
  9596. // reconnect rerouted edges to the childNode
  9597. this._connectEdgeBackToChild(parentNode,childNode);
  9598. // validate all edges in dynamicEdges
  9599. this._validateEdges(parentNode);
  9600. // undo the changes from the clustering operation on the parent node
  9601. parentNode.mass -= this.constants.clustering.massTransferCoefficient * childNode.mass;
  9602. parentNode.fontSize -= this.constants.clustering.fontSizeMultiplier * childNode.clusterSize;
  9603. parentNode.clusterSize -= childNode.clusterSize;
  9604. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  9605. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  9606. childNode.x = parentNode.x + this.constants.edges.length * 0.3 * (0.5 - Math.random()) * parentNode.clusterSize;
  9607. childNode.y = parentNode.y + this.constants.edges.length * 0.3 * (0.5 - Math.random()) * parentNode.clusterSize;
  9608. // remove node from the list
  9609. delete parentNode.containedNodes[containedNodeID];
  9610. // check if there are other childs with this clusterSession in the parent.
  9611. var othersPresent = false;
  9612. for (var childNodeID in parentNode.containedNodes) {
  9613. if (parentNode.containedNodes.hasOwnProperty(childNodeID)) {
  9614. if (parentNode.containedNodes[childNodeID].clusterSession == childNode.clusterSession) {
  9615. othersPresent = true;
  9616. break;
  9617. }
  9618. }
  9619. }
  9620. // if there are no others, remove the cluster session from the list
  9621. if (othersPresent == false) {
  9622. parentNode.clusterSessions.pop();
  9623. }
  9624. // remove the clusterSession from the child node
  9625. childNode.clusterSession = 0;
  9626. // restart the simulation to reorganise all nodes
  9627. this.moving = true;
  9628. // recalculate the size of the node on the next time the node is rendered
  9629. parentNode.clearSizeCache();
  9630. }
  9631. // check if a further expansion step is possible if recursivity is enabled
  9632. if (recursive == true) {
  9633. this._expandClusterNode(childNode,recursive,force,openAll);
  9634. }
  9635. };
  9636. /**
  9637. * This function checks if any nodes at the end of their trees have edges below a threshold length
  9638. * This function is called only from updateClusters()
  9639. * forceLevelCollapse ignores the length of the edge and collapses one level
  9640. * This means that a node with only one edge will be clustered with its connected node
  9641. *
  9642. * @private
  9643. * @param {Boolean} force
  9644. */
  9645. Cluster.prototype._formClusters = function(force) {
  9646. if (force == false) {
  9647. this._formClustersByZoom();
  9648. }
  9649. else {
  9650. this._forceClustersByZoom();
  9651. }
  9652. };
  9653. /**
  9654. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  9655. *
  9656. * @private
  9657. */
  9658. Cluster.prototype._formClustersByZoom = function() {
  9659. var dx,dy,length,
  9660. minLength = this.constants.clustering.clusterLength/this.scale;
  9661. // check if any edges are shorter than minLength and start the clustering
  9662. // the clustering favours the node with the larger mass
  9663. for (var edgeID in this.edges) {
  9664. if (this.edges.hasOwnProperty(edgeID)) {
  9665. var edge = this.edges[edgeID];
  9666. if (edge.connected) {
  9667. dx = (edge.to.x - edge.from.x);
  9668. dy = (edge.to.y - edge.from.y);
  9669. length = Math.sqrt(dx * dx + dy * dy);
  9670. if (length < minLength) {
  9671. // first check which node is larger
  9672. var parentNode = edge.from;
  9673. var childNode = edge.to;
  9674. if (edge.to.mass > edge.from.mass) {
  9675. parentNode = edge.to;
  9676. childNode = edge.from;
  9677. }
  9678. if (childNode.dynamicEdgesLength == 1) {
  9679. this._addToCluster(parentNode,childNode,false);
  9680. }
  9681. else if (parentNode.dynamicEdgesLength == 1) {
  9682. this._addToCluster(childNode,parentNode,false);
  9683. }
  9684. }
  9685. }
  9686. }
  9687. }
  9688. };
  9689. /**
  9690. * This function forces the graph to cluster all nodes with only one connecting edge to their
  9691. * connected node.
  9692. *
  9693. * @private
  9694. */
  9695. Cluster.prototype._forceClustersByZoom = function() {
  9696. for (var nodeID in this.nodes) {
  9697. // another node could have absorbed this child.
  9698. if (this.nodes.hasOwnProperty(nodeID)) {
  9699. var childNode = this.nodes[nodeID];
  9700. // the edges can be swallowed by another decrease
  9701. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  9702. var edge = childNode.dynamicEdges[0];
  9703. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  9704. // group to the largest node
  9705. if (parentNode.mass > childNode.mass) {
  9706. this._addToCluster(parentNode,childNode,true);
  9707. }
  9708. else {
  9709. this._addToCluster(childNode,parentNode,true);
  9710. }
  9711. }
  9712. }
  9713. }
  9714. };
  9715. /**
  9716. * This function forms clusters from hubs, it loops over all nodes
  9717. *
  9718. * @param {Boolean} force | Disregard zoom level
  9719. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  9720. * @private
  9721. */
  9722. Cluster.prototype._formClustersByHub = function(force, onlyEqual) {
  9723. // we loop over all nodes in the list
  9724. for (var nodeID in this.nodes) {
  9725. // we check if it is still available since it can be used by the clustering in this loop
  9726. if (this.nodes.hasOwnProperty(nodeID)) {
  9727. this._formClusterFromHub(this.nodes[nodeID],force,onlyEqual);
  9728. }
  9729. }
  9730. };
  9731. /**
  9732. * This function forms a cluster from a specific preselected hub node
  9733. *
  9734. * @param {Node} hubNode | the node we will cluster as a hub
  9735. * @param {Boolean} force | Disregard zoom level
  9736. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  9737. * @param [Number] absorptionSizeOffset |
  9738. * @private
  9739. */
  9740. Cluster.prototype._formClusterFromHub = function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  9741. if (absorptionSizeOffset === undefined) {
  9742. absorptionSizeOffset = 0;
  9743. }
  9744. // we decide if the node is a hub
  9745. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  9746. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  9747. // initialize variables
  9748. var dx,dy,length;
  9749. var minLength = this.constants.clustering.clusterLength/this.scale;
  9750. var allowCluster = false;
  9751. // we create a list of edges because the dynamicEdges change over the course of this loop
  9752. var edgesIDarray = [];
  9753. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  9754. for (var j = 0; j < amountOfInitialEdges; j++) {
  9755. edgesIDarray.push(hubNode.dynamicEdges[j].id);
  9756. }
  9757. // if the hub clustering is not forces, we check if one of the edges connected
  9758. // to a cluster is small enough based on the constants.clustering.clusterLength
  9759. if (force == false) {
  9760. allowCluster = false;
  9761. for (j = 0; j < amountOfInitialEdges; j++) {
  9762. var edge = this.edges[edgesIDarray[j]];
  9763. if (edge !== undefined) {
  9764. if (edge.connected) {
  9765. dx = (edge.to.x - edge.from.x);
  9766. dy = (edge.to.y - edge.from.y);
  9767. length = Math.sqrt(dx * dx + dy * dy);
  9768. if (length < minLength) {
  9769. allowCluster = true;
  9770. break;
  9771. }
  9772. }
  9773. }
  9774. }
  9775. }
  9776. // start the clustering if allowed
  9777. if ((!force && allowCluster) || force) {
  9778. // we loop over all edges INITIALLY connected to this hub
  9779. for (j = 0; j < amountOfInitialEdges; j++) {
  9780. edge = this.edges[edgesIDarray[j]];
  9781. // the edge can be clustered by this function in a previous loop
  9782. if (edge !== undefined) {
  9783. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  9784. // we do not want hubs to merge with other hubs.
  9785. if (childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) {
  9786. this._addToCluster(hubNode,childNode,force);
  9787. }
  9788. }
  9789. }
  9790. }
  9791. }
  9792. };
  9793. /**
  9794. * This function adds the child node to the parent node, creating a cluster if it is not already.
  9795. * This function is called only from updateClusters()
  9796. *
  9797. * @param {Node} parentNode | this is the node that will house the child node
  9798. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  9799. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  9800. * @private
  9801. */
  9802. Cluster.prototype._addToCluster = function(parentNode, childNode, force) {
  9803. // join child node in the parent node
  9804. parentNode.containedNodes[childNode.id] = childNode;
  9805. // manage all the edges connected to the child and parent nodes
  9806. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  9807. var edge = childNode.dynamicEdges[i];
  9808. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  9809. this._addToContainedEdges(parentNode,childNode,edge);
  9810. }
  9811. else {
  9812. this._connectEdgeToCluster(parentNode,childNode,edge);
  9813. }
  9814. }
  9815. childNode.dynamicEdges = [];
  9816. // remove the childNode from the global nodes object
  9817. delete this.nodes[childNode.id];
  9818. var massBefore = parentNode.mass;
  9819. childNode.clusterSession = this.clusterSession;
  9820. parentNode.mass += this.constants.clustering.massTransferCoefficient * childNode.mass;
  9821. parentNode.clusterSize += childNode.clusterSize;
  9822. parentNode.fontSize += this.constants.clustering.fontSizeMultiplier * childNode.clusterSize;
  9823. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  9824. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  9825. parentNode.clusterSessions.push(this.clusterSession);
  9826. }
  9827. // giving the clusters a dynamic formationScale to ensure not all clusters open up when zoomed
  9828. if (force == true) {
  9829. parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  9830. }
  9831. else {
  9832. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  9833. }
  9834. // recalculate the size of the node on the next time the node is rendered
  9835. parentNode.clearSizeCache();
  9836. // set the pop-out scale for the childnode
  9837. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  9838. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  9839. childNode.clearVelocity();
  9840. // the mass has altered, preservation of energy dictates the velocity to be updated
  9841. parentNode.updateVelocity(massBefore);
  9842. // restart the simulation to reorganise all nodes
  9843. this.moving = true;
  9844. };
  9845. /**
  9846. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  9847. * This is a seperate function to allow for level-wise collapsing of the node tree.
  9848. * It has to be called if a level is collapsed. It is called by _formClusters().
  9849. * @private
  9850. */
  9851. Cluster.prototype._updateDynamicEdges = function() {
  9852. for (var i = 0; i < this.nodeIndices.length; i++) {
  9853. var node = this.nodes[this.nodeIndices[i]];
  9854. node.dynamicEdgesLength = node.dynamicEdges.length;
  9855. // this corrects for multiple edges pointing at the same other node
  9856. var correction = 0;
  9857. if (node.dynamicEdgesLength > 1) {
  9858. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  9859. var edgeToId = node.dynamicEdges[j].toId;
  9860. var edgeFromId = node.dynamicEdges[j].fromId;
  9861. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  9862. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  9863. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  9864. correction += 1;
  9865. }
  9866. }
  9867. }
  9868. }
  9869. node.dynamicEdgesLength -= correction;
  9870. }
  9871. };
  9872. /**
  9873. * This adds an edge from the childNode to the contained edges of the parent node
  9874. *
  9875. * @param parentNode | Node object
  9876. * @param childNode | Node object
  9877. * @param edge | Edge object
  9878. * @private
  9879. */
  9880. Cluster.prototype._addToContainedEdges = function(parentNode, childNode, edge) {
  9881. // create an array object if it does not yet exist for this childNode
  9882. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  9883. parentNode.containedEdges[childNode.id] = []
  9884. }
  9885. // add this edge to the list
  9886. parentNode.containedEdges[childNode.id].push(edge);
  9887. // remove the edge from the global edges object
  9888. delete this.edges[edge.id];
  9889. // remove the edge from the parent object
  9890. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  9891. if (parentNode.dynamicEdges[i].id == edge.id) {
  9892. parentNode.dynamicEdges.splice(i,1);
  9893. break;
  9894. }
  9895. }
  9896. };
  9897. /**
  9898. * This function connects an edge that was connected to a child node to the parent node.
  9899. * It keeps track of which nodes it has been connected to with the originalID array.
  9900. *
  9901. * @param parentNode | Node object
  9902. * @param childNode | Node object
  9903. * @param edge | Edge object
  9904. * @private
  9905. */
  9906. Cluster.prototype._connectEdgeToCluster = function(parentNode, childNode, edge) {
  9907. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  9908. edge.originalToID.push(childNode.id);
  9909. edge.to = parentNode;
  9910. edge.toId = parentNode.id;
  9911. }
  9912. else { // edge connected to other node with the "from" side
  9913. edge.originalFromID.push(childNode.id);
  9914. edge.from = parentNode;
  9915. edge.fromId = parentNode.id;
  9916. }
  9917. this._addToReroutedEdges(parentNode,childNode,edge);
  9918. };
  9919. /**
  9920. * This adds an edge from the childNode to the rerouted edges of the parent node
  9921. *
  9922. * @param parentNode | Node object
  9923. * @param childNode | Node object
  9924. * @param edge | Edge object
  9925. * @private
  9926. */
  9927. Cluster.prototype._addToReroutedEdges = function(parentNode, childNode, edge) {
  9928. // create an array object if it does not yet exist for this childNode
  9929. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  9930. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  9931. parentNode.reroutedEdges[childNode.id] = [];
  9932. }
  9933. parentNode.reroutedEdges[childNode.id].push(edge);
  9934. // this edge becomes part of the dynamicEdges of the cluster node
  9935. parentNode.dynamicEdges.push(edge);
  9936. };
  9937. /**
  9938. * This function connects an edge that was connected to a cluster node back to the child node.
  9939. *
  9940. * @param parentNode | Node object
  9941. * @param childNode | Node object
  9942. * @private
  9943. */
  9944. Cluster.prototype._connectEdgeBackToChild = function(parentNode, childNode) {
  9945. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  9946. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  9947. var edge = parentNode.reroutedEdges[childNode.id][i];
  9948. if (edge.originalFromID[edge.originalFromID.length-1] == childNode.id) {
  9949. edge.originalFromID.pop();
  9950. edge.fromId = childNode.id;
  9951. edge.from = childNode;
  9952. }
  9953. else {
  9954. edge.originalToID.pop();
  9955. edge.toId = childNode.id;
  9956. edge.to = childNode;
  9957. }
  9958. // append this edge to the list of edges connecting to the childnode
  9959. childNode.dynamicEdges.push(edge);
  9960. // remove the edge from the parent object
  9961. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  9962. if (parentNode.dynamicEdges[j].id == edge.id) {
  9963. parentNode.dynamicEdges.splice(j,1);
  9964. break;
  9965. }
  9966. }
  9967. }
  9968. // remove the entry from the rerouted edges
  9969. delete parentNode.reroutedEdges[childNode.id];
  9970. }
  9971. };
  9972. /**
  9973. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  9974. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  9975. * parentNode
  9976. *
  9977. * @param parentNode | Node object
  9978. * @private
  9979. */
  9980. Cluster.prototype._validateEdges = function(parentNode) {
  9981. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  9982. var edge = parentNode.dynamicEdges[i];
  9983. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  9984. parentNode.dynamicEdges.splice(i,1);
  9985. }
  9986. }
  9987. };
  9988. /**
  9989. * This function released the contained edges back into the global domain and puts them back into the
  9990. * dynamic edges of both parent and child.
  9991. *
  9992. * @param {Node} parentNode |
  9993. * @param {Node} childNode |
  9994. * @private
  9995. */
  9996. Cluster.prototype._releaseContainedEdges = function(parentNode, childNode) {
  9997. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  9998. var edge = parentNode.containedEdges[childNode.id][i];
  9999. // put the edge back in the global edges object
  10000. this.edges[edge.id] = edge;
  10001. // put the edge back in the dynamic edges of the child and parent
  10002. childNode.dynamicEdges.push(edge);
  10003. parentNode.dynamicEdges.push(edge);
  10004. }
  10005. // remove the entry from the contained edges
  10006. delete parentNode.containedEdges[childNode.id];
  10007. };
  10008. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  10009. /**
  10010. * This updates the node labels for all nodes (for debugging purposes)
  10011. */
  10012. Cluster.prototype.updateLabels = function() {
  10013. var nodeID;
  10014. // update node labels
  10015. for (nodeID in this.nodes) {
  10016. if (this.nodes.hasOwnProperty(nodeID)) {
  10017. var node = this.nodes[nodeID];
  10018. if (node.clusterSize > 1) {
  10019. node.label = "[".concat(String(node.clusterSize),"]");
  10020. }
  10021. }
  10022. }
  10023. // update node labels
  10024. for (nodeID in this.nodes) {
  10025. if (this.nodes.hasOwnProperty(nodeID)) {
  10026. node = this.nodes[nodeID];
  10027. if (node.clusterSize == 1) {
  10028. node.label = String(node.id);
  10029. }
  10030. }
  10031. }
  10032. /* Debug Override */
  10033. // for (nodeID in this.nodes) {
  10034. // if (this.nodes.hasOwnProperty(nodeID)) {
  10035. // node = this.nodes[nodeID];
  10036. // node.label = String(Math.round(node.width)).concat(":",Math.round(node.width*this.scale));
  10037. // }
  10038. // }
  10039. };
  10040. /**
  10041. * This function determines if the cluster we want to decluster is in the active area
  10042. * this means around the zoom center
  10043. *
  10044. * @param {Node} node
  10045. * @returns {boolean}
  10046. * @private
  10047. */
  10048. Cluster.prototype._parentNodeInActiveArea = function(node) {
  10049. return (
  10050. Math.abs(node.x - this.zoomCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  10051. &&
  10052. Math.abs(node.y - this.zoomCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  10053. )
  10054. };
  10055. /**
  10056. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  10057. * It puts large clusters away from the center and randomizes the order.
  10058. *
  10059. */
  10060. Cluster.prototype.repositionNodes = function() {
  10061. for (var i = 0; i < this.nodeIndices.length; i++) {
  10062. var node = this.nodes[this.nodeIndices[i]];
  10063. if (!node.isFixed()) {
  10064. var radius = this.constants.edges.length * (1 + 0.6*node.clusterSize);
  10065. var angle = 2 * Math.PI * Math.random();
  10066. node.x = radius * Math.cos(angle);
  10067. node.y = radius * Math.sin(angle);
  10068. }
  10069. }
  10070. };
  10071. /**
  10072. * We determine how many connections denote an important hub.
  10073. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  10074. *
  10075. * @private
  10076. */
  10077. Cluster.prototype._getHubSize = function() {
  10078. var average = 0;
  10079. var averageSquared = 0;
  10080. var hubCounter = 0;
  10081. var largestHub = 0;
  10082. for (var i = 0; i < this.nodeIndices.length; i++) {
  10083. var node = this.nodes[this.nodeIndices[i]];
  10084. if (node.dynamicEdgesLength > largestHub) {
  10085. largestHub = node.dynamicEdgesLength;
  10086. }
  10087. average += node.dynamicEdgesLength;
  10088. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  10089. hubCounter += 1;
  10090. }
  10091. average = average / hubCounter;
  10092. averageSquared = averageSquared / hubCounter;
  10093. var variance = averageSquared - Math.pow(average,2);
  10094. var standardDeviation = Math.sqrt(variance);
  10095. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  10096. // always have at least one to cluster
  10097. if (this.hubThreshold > largestHub) {
  10098. this.hubThreshold = largestHub;
  10099. }
  10100. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  10101. // console.log("hubThreshold:",this.hubThreshold);
  10102. };
  10103. /**
  10104. * We reduce the amount of "extension nodes" or snakes. These are not quickly clustered with the outliers and hubs methods
  10105. * with this amount we can cluster specifically on these snakes.
  10106. *
  10107. * @param {double} fraction | between 0 and 1, the percentage of snakes to reduce
  10108. * @private
  10109. */
  10110. Cluster.prototype._reduceAmountOfSnakes = function(fraction) {
  10111. this.hubThreshold = 2;
  10112. for (nodeID in this.nodes) {
  10113. if (this.nodes.hasOwnProperty(nodeID)) {
  10114. if (this.nodes[nodeID].dynamicEdgesLength == 2 && this.nodes[nodeID].dynamicEdges.length >= 2) {
  10115. if (Math.random() <= fraction) {
  10116. this._formClusterFromHub(this.nodes[nodeID],true,true,1)
  10117. }
  10118. }
  10119. }
  10120. }
  10121. };
  10122. /**
  10123. * We get the amount of "extension nodes" or snakes. These are not quickly clustered with the outliers and hubs methods
  10124. * with this amount we can cluster specifically on these snakes.
  10125. *
  10126. * @private
  10127. */
  10128. Cluster.prototype._getSnakeFraction = function() {
  10129. var snakes = 0;
  10130. var total = 0;
  10131. for (nodeID in this.nodes) {
  10132. if (this.nodes.hasOwnProperty(nodeID)) {
  10133. if (this.nodes[nodeID].dynamicEdgesLength == 2 && this.nodes[nodeID].dynamicEdges.length >= 2) {
  10134. snakes += 1;
  10135. }
  10136. total += 1;
  10137. }
  10138. }
  10139. return snakes/total;
  10140. };
  10141. /**
  10142. * @constructor Graph
  10143. * Create a graph visualization, displaying nodes and edges.
  10144. *
  10145. * @param {Element} container The DOM element in which the Graph will
  10146. * be created. Normally a div element.
  10147. * @param {Object} data An object containing parameters
  10148. * {Array} nodes
  10149. * {Array} edges
  10150. * @param {Object} options Options
  10151. */
  10152. function Graph (container, data, options) {
  10153. // create variables and set default values
  10154. this.containerElement = container;
  10155. this.width = '100%';
  10156. this.height = '100%';
  10157. this.refreshRate = 50; // milliseconds
  10158. this.stabilize = true; // stabilize before displaying the graph
  10159. this.selectable = true;
  10160. // set constant values
  10161. this.constants = {
  10162. nodes: {
  10163. radiusMin: 5,
  10164. radiusMax: 20,
  10165. radius: 5,
  10166. distance: 100, // px
  10167. shape: 'ellipse',
  10168. image: undefined,
  10169. widthMin: 16, // px
  10170. widthMax: 64, // px
  10171. fontColor: 'black',
  10172. fontSize: 14, // px
  10173. //fontFace: verdana,
  10174. fontFace: 'arial',
  10175. color: {
  10176. border: '#2B7CE9',
  10177. background: '#97C2FC',
  10178. highlight: {
  10179. border: '#2B7CE9',
  10180. background: '#D2E5FF'
  10181. }
  10182. },
  10183. borderColor: '#2B7CE9',
  10184. backgroundColor: '#97C2FC',
  10185. highlightColor: '#D2E5FF',
  10186. group: undefined
  10187. },
  10188. edges: {
  10189. widthMin: 1,
  10190. widthMax: 15,
  10191. width: 1,
  10192. style: 'line',
  10193. color: '#343434',
  10194. fontColor: '#343434',
  10195. fontSize: 14, // px
  10196. fontFace: 'arial',
  10197. //distance: 100, //px
  10198. length: 100, // px
  10199. dash: {
  10200. length: 10,
  10201. gap: 5,
  10202. altLength: undefined
  10203. }
  10204. },
  10205. clustering: { // TODO: naming of variables
  10206. enableClustering: true,
  10207. maxNumberOfNodes: 100, // for automatic (initial) clustering
  10208. snakeThreshold: 0.5, // maximum percentage of allowed snakes (long strings of connected nodes)
  10209. clusterLength: 25, // threshold edge length for clusteringl
  10210. relativeOpenFactor: 0.2, // if the width or height of a cluster takes up this much of the screen, open the cluster
  10211. fontSizeMultiplier: 4, // how much the cluster font size grows per node (in px)
  10212. forceAmplification: 0.7, // amount of clusterSize between two nodes multiply this value (+1) with the repulsion force
  10213. distanceAmplification: 0.3, // amount of clusterSize between two nodes multiply this value (+1) with the repulsion force
  10214. edgeGrowth: 11, // amount of clusterSize connected to the edge is multiplied with this and added to edgeLength
  10215. clusterSizeWidthFactor: 10,
  10216. clusterSizeHeightFactor: 10,
  10217. clusterSizeRadiusFactor: 10,
  10218. activeAreaBoxSize: 100, // box area around the curser where clusters are popped open
  10219. massTransferCoefficient: 1 // parent.mass += massTransferCoefficient * child.mass
  10220. },
  10221. minForce: 0.05,
  10222. minVelocity: 0.02, // px/s
  10223. maxIterations: 1000 // maximum number of iteration to stabilize
  10224. };
  10225. // call the constructor of the cluster object
  10226. Cluster.call(this);
  10227. // call the universe constructor
  10228. Universe.call(this);
  10229. var graph = this;
  10230. this.freezeSimulation = false;// freeze the simulation
  10231. this.tapTimer = 0; // timer to detect doubleclick or double tap
  10232. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  10233. this.nodes = {}; // object with Node objects
  10234. this.edges = {}; // object with Edge objects
  10235. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during calcForces.
  10236. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during calcForces
  10237. this.zoomCenter = {}; // object with x and y elements used for determining the center of the zoom action
  10238. this.scale = 1; // defining the global scale variable in the constructor
  10239. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  10240. // TODO: create a counter to keep track on the number of nodes having values
  10241. // TODO: create a counter to keep track on the number of nodes currently moving
  10242. // TODO: create a counter to keep track on the number of edges having values
  10243. this.nodesData = null; // A DataSet or DataView
  10244. this.edgesData = null; // A DataSet or DataView
  10245. // create event listeners used to subscribe on the DataSets of the nodes and edges
  10246. var me = this;
  10247. this.nodesListeners = {
  10248. 'add': function (event, params) {
  10249. me._addNodes(params.items);
  10250. me.start();
  10251. },
  10252. 'update': function (event, params) {
  10253. me._updateNodes(params.items);
  10254. me.start();
  10255. },
  10256. 'remove': function (event, params) {
  10257. me._removeNodes(params.items);
  10258. me.start();
  10259. }
  10260. };
  10261. this.edgesListeners = {
  10262. 'add': function (event, params) {
  10263. me._addEdges(params.items);
  10264. me.start();
  10265. },
  10266. 'update': function (event, params) {
  10267. me._updateEdges(params.items);
  10268. me.start();
  10269. },
  10270. 'remove': function (event, params) {
  10271. me._removeEdges(params.items);
  10272. me.start();
  10273. }
  10274. };
  10275. this.groups = new Groups(); // object with groups
  10276. this.images = new Images(); // object with images
  10277. this.images.setOnloadCallback(function () {
  10278. graph._redraw();
  10279. });
  10280. // properties of the data
  10281. this.moving = false; // True if any of the nodes have an undefined position
  10282. this.selection = [];
  10283. this.timer = undefined;
  10284. // create a frame and canvas
  10285. this._create();
  10286. // apply options
  10287. this.setOptions(options);
  10288. // load data (the disable start variable will be the same as the enable clustering)
  10289. this.setData(data,this.constants.clustering.enableClustering); //
  10290. // zoom so all data will fit on the screen
  10291. this.zoomToFit();
  10292. if (this.constants.clustering.enableClustering) {
  10293. // cluster if the data set is big
  10294. this.clusterToFit(this.constants.clustering.maxNumberOfNodes, true);
  10295. // updates the lables after clustering
  10296. this.updateLabels();
  10297. // this is called here because if clusterin is disabled, the start and stabilize are called in
  10298. // the setData function.
  10299. if (this.stabilize) {
  10300. this._doStabilize();
  10301. }
  10302. this.start();
  10303. }
  10304. }
  10305. // add the universe functionality to this
  10306. Graph.prototype = Object.create(Universe.prototype);
  10307. /**
  10308. * We add the functionality of the cluster object to the graph object
  10309. * @type {Cluster.prototype}
  10310. */
  10311. Graph.prototype = Object.create(Cluster.prototype);
  10312. /**
  10313. * This function clusters until the maxNumberOfNodes has been reached
  10314. *
  10315. * @param {Number} maxNumberOfNodes
  10316. * @param {Boolean} reposition
  10317. */
  10318. Graph.prototype.clusterToFit = function(maxNumberOfNodes, reposition) {
  10319. var numberOfNodes = this.nodeIndices.length;
  10320. var maxLevels = 15;
  10321. var level = 0;
  10322. // we first cluster the hubs, then we pull in the outliers, repeat
  10323. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  10324. if (level % 5 == 0) {
  10325. console.log("Aggregating Hubs @ level: ",level,". Threshold:", this.hubThreshold,"clusterSession",this.clusterSession);
  10326. this.forceAggregateHubs();
  10327. }
  10328. else {
  10329. console.log("Pulling in Outliers @ level: ",level,"clusterSession",this.clusterSession);
  10330. this.increaseClusterLevel();
  10331. }
  10332. numberOfNodes = this.nodeIndices.length;
  10333. level += 1;
  10334. }
  10335. // after the clustering we reposition the nodes to reduce the initial chaos
  10336. if (level > 1 && reposition == true) {
  10337. this.repositionNodes();
  10338. }
  10339. };
  10340. /**
  10341. * This function zooms out to fit all data on screen based on amount of nodes
  10342. */
  10343. Graph.prototype.zoomToFit = function() {
  10344. var numberOfNodes = this.nodeIndices.length;
  10345. var zoomLevel = 105 / (numberOfNodes + 80); // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  10346. if (zoomLevel > 1.0) {
  10347. zoomLevel = 1.0;
  10348. }
  10349. if (!('mousewheelScale' in this.pinch)) {
  10350. this.pinch.mousewheelScale = zoomLevel;
  10351. }
  10352. this._setScale(zoomLevel);
  10353. };
  10354. /**
  10355. * Update the this.nodeIndices with the most recent node index list
  10356. * @private
  10357. */
  10358. Graph.prototype._updateNodeIndexList = function() {
  10359. var universe = this.activeUniverse[this.activeUniverse.length-1];
  10360. this.universe["activePockets"][universe]["nodeIndices"] = [];
  10361. this.nodeIndices = this.universe["activePockets"][universe]["nodeIndices"];
  10362. for (var idx in this.nodes) {
  10363. if (this.nodes.hasOwnProperty(idx)) {
  10364. this.nodeIndices.push(idx);
  10365. }
  10366. }
  10367. };
  10368. /**
  10369. * Set nodes and edges, and optionally options as well.
  10370. *
  10371. * @param {Object} data Object containing parameters:
  10372. * {Array | DataSet | DataView} [nodes] Array with nodes
  10373. * {Array | DataSet | DataView} [edges] Array with edges
  10374. * {String} [dot] String containing data in DOT format
  10375. * {Options} [options] Object with options
  10376. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  10377. */
  10378. Graph.prototype.setData = function(data, disableStart) {
  10379. if (disableStart === undefined) {
  10380. disableStart = false;
  10381. }
  10382. if (data && data.dot && (data.nodes || data.edges)) {
  10383. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  10384. ' parameter pair "nodes" and "edges", but not both.');
  10385. }
  10386. // set options
  10387. this.setOptions(data && data.options);
  10388. // set all data
  10389. if (data && data.dot) {
  10390. // parse DOT file
  10391. if(data && data.dot) {
  10392. var dotData = vis.util.DOTToGraph(data.dot);
  10393. this.setData(dotData);
  10394. return;
  10395. }
  10396. }
  10397. else {
  10398. this._setNodes(data && data.nodes);
  10399. this._setEdges(data && data.edges);
  10400. }
  10401. this._putDataInUniverse();
  10402. if (!disableStart) {
  10403. // find a stable position or start animating to a stable position
  10404. if (this.stabilize) {
  10405. this._doStabilize();
  10406. }
  10407. this.start();
  10408. }
  10409. };
  10410. /**
  10411. * Set options
  10412. * @param {Object} options
  10413. */
  10414. Graph.prototype.setOptions = function (options) {
  10415. if (options) {
  10416. // retrieve parameter values
  10417. if (options.width !== undefined) {this.width = options.width;}
  10418. if (options.height !== undefined) {this.height = options.height;}
  10419. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  10420. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  10421. // TODO: work out these options and document them
  10422. if (options.edges) {
  10423. for (var prop in options.edges) {
  10424. if (options.edges.hasOwnProperty(prop)) {
  10425. this.constants.edges[prop] = options.edges[prop];
  10426. }
  10427. }
  10428. if (options.edges.length !== undefined &&
  10429. options.nodes && options.nodes.distance === undefined) {
  10430. this.constants.edges.length = options.edges.length;
  10431. this.constants.nodes.distance = options.edges.length * 1.25;
  10432. }
  10433. if (!options.edges.fontColor) {
  10434. this.constants.edges.fontColor = options.edges.color;
  10435. }
  10436. // Added to support dashed lines
  10437. // David Jordan
  10438. // 2012-08-08
  10439. if (options.edges.dash) {
  10440. if (options.edges.dash.length !== undefined) {
  10441. this.constants.edges.dash.length = options.edges.dash.length;
  10442. }
  10443. if (options.edges.dash.gap !== undefined) {
  10444. this.constants.edges.dash.gap = options.edges.dash.gap;
  10445. }
  10446. if (options.edges.dash.altLength !== undefined) {
  10447. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  10448. }
  10449. }
  10450. }
  10451. if (options.nodes) {
  10452. for (prop in options.nodes) {
  10453. if (options.nodes.hasOwnProperty(prop)) {
  10454. this.constants.nodes[prop] = options.nodes[prop];
  10455. }
  10456. }
  10457. if (options.nodes.color) {
  10458. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  10459. }
  10460. /*
  10461. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  10462. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  10463. */
  10464. }
  10465. if (options.groups) {
  10466. for (var groupname in options.groups) {
  10467. if (options.groups.hasOwnProperty(groupname)) {
  10468. var group = options.groups[groupname];
  10469. this.groups.add(groupname, group);
  10470. }
  10471. }
  10472. }
  10473. }
  10474. this.setSize(this.width, this.height);
  10475. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  10476. this._setScale(1);
  10477. };
  10478. /**
  10479. * fire an event
  10480. * @param {String} event The name of an event, for example 'select'
  10481. * @param {Object} params Optional object with event parameters
  10482. * @private
  10483. */
  10484. Graph.prototype._trigger = function (event, params) {
  10485. events.trigger(this, event, params);
  10486. };
  10487. /**
  10488. * Create the main frame for the Graph.
  10489. * This function is executed once when a Graph object is created. The frame
  10490. * contains a canvas, and this canvas contains all objects like the axis and
  10491. * nodes.
  10492. * @private
  10493. */
  10494. Graph.prototype._create = function () {
  10495. // remove all elements from the container element.
  10496. while (this.containerElement.hasChildNodes()) {
  10497. this.containerElement.removeChild(this.containerElement.firstChild);
  10498. }
  10499. this.frame = document.createElement('div');
  10500. this.frame.className = 'graph-frame';
  10501. this.frame.style.position = 'relative';
  10502. this.frame.style.overflow = 'hidden';
  10503. // create the graph canvas (HTML canvas element)
  10504. this.frame.canvas = document.createElement( 'canvas' );
  10505. this.frame.canvas.style.position = 'relative';
  10506. this.frame.appendChild(this.frame.canvas);
  10507. if (!this.frame.canvas.getContext) {
  10508. var noCanvas = document.createElement( 'DIV' );
  10509. noCanvas.style.color = 'red';
  10510. noCanvas.style.fontWeight = 'bold' ;
  10511. noCanvas.style.padding = '10px';
  10512. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  10513. this.frame.canvas.appendChild(noCanvas);
  10514. }
  10515. var me = this;
  10516. this.drag = {};
  10517. this.pinch = {};
  10518. this.hammer = Hammer(this.frame.canvas, {
  10519. prevent_default: true
  10520. });
  10521. this.hammer.on('tap', me._onTap.bind(me) );
  10522. this.hammer.on('hold', me._onHold.bind(me) );
  10523. this.hammer.on('pinch', me._onPinch.bind(me) );
  10524. this.hammer.on('touch', me._onTouch.bind(me) );
  10525. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  10526. this.hammer.on('drag', me._onDrag.bind(me) );
  10527. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  10528. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  10529. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  10530. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  10531. /*
  10532. this.mouseTrap = mouseTrap;
  10533. this.mouseTrap.bind("=",this.decreaseClusterLevel.bind(me));
  10534. this.mouseTrap.bind("-",this.increaseClusterLevel.bind(me));
  10535. this.mouseTrap.bind("s",this.singleStep.bind(me));
  10536. this.mouseTrap.bind("h",this.updateClustersDefault.bind(me));
  10537. this.mouseTrap.bind("c",this._collapseUniverse.bind(me));
  10538. this.mouseTrap.bind("f",this.toggleFreeze.bind(me));
  10539. */
  10540. // add the frame to the container element
  10541. this.containerElement.appendChild(this.frame);
  10542. };
  10543. /**
  10544. *
  10545. * @param {{x: Number, y: Number}} pointer
  10546. * @return {Number | null} node
  10547. * @private
  10548. */
  10549. Graph.prototype._getNodeAt = function (pointer) {
  10550. var x = this._canvasToX(pointer.x);
  10551. var y = this._canvasToY(pointer.y);
  10552. var obj = {
  10553. left: x,
  10554. top: y,
  10555. right: x,
  10556. bottom: y
  10557. };
  10558. // if there are overlapping nodes, select the last one, this is the
  10559. // one which is drawn on top of the others
  10560. var overlappingNodes = this._getNodesOverlappingWith(obj);
  10561. return (overlappingNodes.length > 0) ?
  10562. overlappingNodes[overlappingNodes.length - 1] : null;
  10563. };
  10564. /**
  10565. * Get the pointer location from a touch location
  10566. * @param {{pageX: Number, pageY: Number}} touch
  10567. * @return {{x: Number, y: Number}} pointer
  10568. * @private
  10569. */
  10570. Graph.prototype._getPointer = function (touch) {
  10571. return {
  10572. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  10573. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  10574. };
  10575. };
  10576. /**
  10577. * On start of a touch gesture, store the pointer
  10578. * @param event
  10579. * @private
  10580. */
  10581. Graph.prototype._onTouch = function (event) {
  10582. this.drag.pointer = this._getPointer(event.gesture.touches[0]);
  10583. this.drag.pinched = false;
  10584. this.pinch.scale = this._getScale();
  10585. };
  10586. /**
  10587. * handle drag start event
  10588. * @private
  10589. */
  10590. Graph.prototype._onDragStart = function () {
  10591. var drag = this.drag;
  10592. drag.selection = [];
  10593. drag.translation = this._getTranslation();
  10594. drag.nodeId = this._getNodeAt(drag.pointer);
  10595. // note: drag.pointer is set in _onTouch to get the initial touch location
  10596. var node = this.nodes[drag.nodeId];
  10597. if (node) {
  10598. // select the clicked node if not yet selected
  10599. if (!node.isSelected()) {
  10600. this._selectNodes([drag.nodeId]);
  10601. }
  10602. // create an array with the selected nodes and their original location and status
  10603. var me = this;
  10604. this.selection.forEach(function (id) {
  10605. var node = me.nodes[id];
  10606. if (node) {
  10607. var s = {
  10608. id: id,
  10609. node: node,
  10610. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  10611. x: node.x,
  10612. y: node.y,
  10613. xFixed: node.xFixed,
  10614. yFixed: node.yFixed
  10615. };
  10616. node.xFixed = true;
  10617. node.yFixed = true;
  10618. drag.selection.push(s);
  10619. }
  10620. });
  10621. }
  10622. };
  10623. /**
  10624. * handle drag event
  10625. * @private
  10626. */
  10627. Graph.prototype._onDrag = function (event) {
  10628. if (this.drag.pinched) {
  10629. return;
  10630. }
  10631. var pointer = this._getPointer(event.gesture.touches[0]);
  10632. var me = this,
  10633. drag = this.drag,
  10634. selection = drag.selection;
  10635. if (selection && selection.length) {
  10636. // calculate delta's and new location
  10637. var deltaX = pointer.x - drag.pointer.x,
  10638. deltaY = pointer.y - drag.pointer.y;
  10639. // update position of all selected nodes
  10640. selection.forEach(function (s) {
  10641. var node = s.node;
  10642. if (!s.xFixed) {
  10643. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  10644. }
  10645. if (!s.yFixed) {
  10646. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  10647. }
  10648. });
  10649. // start animation if not yet running
  10650. if (!this.moving) {
  10651. this.moving = true;
  10652. this.start();
  10653. }
  10654. }
  10655. else {
  10656. // move the graph
  10657. var diffX = pointer.x - this.drag.pointer.x;
  10658. var diffY = pointer.y - this.drag.pointer.y;
  10659. this._setTranslation(
  10660. this.drag.translation.x + diffX,
  10661. this.drag.translation.y + diffY);
  10662. this._redraw();
  10663. this.moved = true;
  10664. }
  10665. };
  10666. /**
  10667. * handle drag start event
  10668. * @private
  10669. */
  10670. Graph.prototype._onDragEnd = function () {
  10671. var selection = this.drag.selection;
  10672. if (selection) {
  10673. selection.forEach(function (s) {
  10674. // restore original xFixed and yFixed
  10675. s.node.xFixed = s.xFixed;
  10676. s.node.yFixed = s.yFixed;
  10677. });
  10678. }
  10679. };
  10680. /**
  10681. * handle tap/click event: select/unselect a node
  10682. * @private
  10683. */
  10684. Graph.prototype._onTap = function (event) {
  10685. var pointer = this._getPointer(event.gesture.touches[0]);
  10686. var nodeId = this._getNodeAt(pointer);
  10687. var node = this.nodes[nodeId];
  10688. var elapsedTime = new Date().getTime() - this.tapTimer;
  10689. this.tapTimer = new Date().getTime();
  10690. if (node) {
  10691. if (node.isSelected() && elapsedTime < 300) {
  10692. this.openCluster(node);
  10693. this.openCluster(node);
  10694. }
  10695. // select this node
  10696. this._selectNodes([nodeId]);
  10697. if (!this.moving) {
  10698. this._redraw();
  10699. }
  10700. }
  10701. else {
  10702. // remove selection
  10703. this._unselectNodes();
  10704. this._redraw();
  10705. }
  10706. };
  10707. /**
  10708. * handle long tap event: multi select nodes
  10709. * @private
  10710. */
  10711. Graph.prototype._onHold = function (event) {
  10712. var pointer = this._getPointer(event.gesture.touches[0]);
  10713. var nodeId = this._getNodeAt(pointer);
  10714. var node = this.nodes[nodeId];
  10715. if (node) {
  10716. if (!node.isSelected()) {
  10717. // select this node, keep previous selection
  10718. var append = true;
  10719. this._selectNodes([nodeId], append);
  10720. }
  10721. else {
  10722. this._unselectNodes([nodeId]);
  10723. }
  10724. if (!this.moving) {
  10725. this._redraw();
  10726. }
  10727. }
  10728. else {
  10729. // Do nothing
  10730. }
  10731. };
  10732. /**
  10733. * Handle pinch event
  10734. * @param event
  10735. * @private
  10736. */
  10737. Graph.prototype._onPinch = function (event) {
  10738. var pointer = this._getPointer(event.gesture.center);
  10739. this.drag.pinched = true;
  10740. if (!('scale' in this.pinch)) {
  10741. this.pinch.scale = 1;
  10742. }
  10743. // TODO: enable moving while pinching?
  10744. var scale = this.pinch.scale * event.gesture.scale;
  10745. this._zoom(scale, pointer)
  10746. };
  10747. /**
  10748. * Zoom the graph in or out
  10749. * @param {Number} scale a number around 1, and between 0.01 and 10
  10750. * @param {{x: Number, y: Number}} pointer
  10751. * @return {Number} appliedScale scale is limited within the boundaries
  10752. * @private
  10753. */
  10754. Graph.prototype._zoom = function(scale, pointer) {
  10755. var scaleOld = this._getScale();
  10756. if (scale < 0.001) {
  10757. scale = 0.001;
  10758. }
  10759. if (scale > 10) {
  10760. scale = 10;
  10761. }
  10762. // + this.frame.canvas.clientHeight / 2
  10763. var translation = this._getTranslation();
  10764. var scaleFrac = scale / scaleOld;
  10765. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  10766. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  10767. this.zoomCenter = {"x" : this._canvasToX(pointer.x),
  10768. "y" : this._canvasToY(pointer.y)};
  10769. // this.zoomCenter = {"x" : pointer.x,"y" : pointer.y };
  10770. this._setScale(scale);
  10771. this._setTranslation(tx, ty);
  10772. this.updateClustersDefault();
  10773. this._redraw();
  10774. // console.log("current zoomscale:",this.scale);
  10775. return scale;
  10776. };
  10777. /**
  10778. * Event handler for mouse wheel event, used to zoom the timeline
  10779. * See http://adomas.org/javascript-mouse-wheel/
  10780. * https://github.com/EightMedia/hammer.js/issues/256
  10781. * @param {MouseEvent} event
  10782. * @private
  10783. */
  10784. Graph.prototype._onMouseWheel = function(event) {
  10785. // retrieve delta
  10786. var delta = 0;
  10787. if (event.wheelDelta) { /* IE/Opera. */
  10788. delta = event.wheelDelta/120;
  10789. } else if (event.detail) { /* Mozilla case. */
  10790. // In Mozilla, sign of delta is different than in IE.
  10791. // Also, delta is multiple of 3.
  10792. delta = -event.detail/3;
  10793. }
  10794. // If delta is nonzero, handle it.
  10795. // Basically, delta is now positive if wheel was scrolled up,
  10796. // and negative, if wheel was scrolled down.
  10797. if (delta) {
  10798. if (!('mousewheelScale' in this.pinch)) {
  10799. this.pinch.mousewheelScale = 1;
  10800. }
  10801. // calculate the new scale
  10802. var scale = this.pinch.mousewheelScale;
  10803. var zoom = delta / 10;
  10804. if (delta < 0) {
  10805. zoom = zoom / (1 - zoom);
  10806. }
  10807. scale *= (1 + zoom);
  10808. // calculate the pointer location
  10809. var gesture = util.fakeGesture(this, event);
  10810. var pointer = this._getPointer(gesture.center);
  10811. // apply the new scale
  10812. scale = this._zoom(scale, pointer);
  10813. // store the new, applied scale
  10814. this.pinch.mousewheelScale = scale;
  10815. }
  10816. // Prevent default actions caused by mouse wheel.
  10817. event.preventDefault();
  10818. };
  10819. /**
  10820. * Mouse move handler for checking whether the title moves over a node with a title.
  10821. * @param {Event} event
  10822. * @private
  10823. */
  10824. Graph.prototype._onMouseMoveTitle = function (event) {
  10825. var gesture = util.fakeGesture(this, event);
  10826. var pointer = this._getPointer(gesture.center);
  10827. // check if the previously selected node is still selected
  10828. if (this.popupNode) {
  10829. this._checkHidePopup(pointer);
  10830. }
  10831. // start a timeout that will check if the mouse is positioned above
  10832. // an element
  10833. var me = this;
  10834. var checkShow = function() {
  10835. me._checkShowPopup(pointer);
  10836. };
  10837. if (this.popupTimer) {
  10838. clearInterval(this.popupTimer); // stop any running timer
  10839. }
  10840. if (!this.leftButtonDown) {
  10841. this.popupTimer = setTimeout(checkShow, 300);
  10842. }
  10843. };
  10844. /**
  10845. * Check if there is an element on the given position in the graph
  10846. * (a node or edge). If so, and if this element has a title,
  10847. * show a popup window with its title.
  10848. *
  10849. * @param {{x:Number, y:Number}} pointer
  10850. * @private
  10851. */
  10852. Graph.prototype._checkShowPopup = function (pointer) {
  10853. var obj = {
  10854. left: this._canvasToX(pointer.x),
  10855. top: this._canvasToY(pointer.y),
  10856. right: this._canvasToX(pointer.x),
  10857. bottom: this._canvasToY(pointer.y)
  10858. };
  10859. var id;
  10860. var lastPopupNode = this.popupNode;
  10861. if (this.popupNode == undefined) {
  10862. // search the nodes for overlap, select the top one in case of multiple nodes
  10863. var nodes = this.nodes;
  10864. for (id in nodes) {
  10865. if (nodes.hasOwnProperty(id)) {
  10866. var node = nodes[id];
  10867. if (node.getTitle() != undefined && node.isOverlappingWith(obj)) {
  10868. this.popupNode = node;
  10869. break;
  10870. }
  10871. }
  10872. }
  10873. }
  10874. if (this.popupNode == undefined) {
  10875. // search the edges for overlap
  10876. var edges = this.edges;
  10877. for (id in edges) {
  10878. if (edges.hasOwnProperty(id)) {
  10879. var edge = edges[id];
  10880. if (edge.connected && (edge.getTitle() != undefined) &&
  10881. edge.isOverlappingWith(obj)) {
  10882. this.popupNode = edge;
  10883. break;
  10884. }
  10885. }
  10886. }
  10887. }
  10888. if (this.popupNode) {
  10889. // show popup message window
  10890. if (this.popupNode != lastPopupNode) {
  10891. var me = this;
  10892. if (!me.popup) {
  10893. me.popup = new Popup(me.frame);
  10894. }
  10895. // adjust a small offset such that the mouse cursor is located in the
  10896. // bottom left location of the popup, and you can easily move over the
  10897. // popup area
  10898. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  10899. me.popup.setText(me.popupNode.getTitle());
  10900. me.popup.show();
  10901. }
  10902. }
  10903. else {
  10904. if (this.popup) {
  10905. this.popup.hide();
  10906. }
  10907. }
  10908. };
  10909. /**
  10910. * Check if the popup must be hided, which is the case when the mouse is no
  10911. * longer hovering on the object
  10912. * @param {{x:Number, y:Number}} pointer
  10913. * @private
  10914. */
  10915. Graph.prototype._checkHidePopup = function (pointer) {
  10916. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  10917. this.popupNode = undefined;
  10918. if (this.popup) {
  10919. this.popup.hide();
  10920. }
  10921. }
  10922. };
  10923. /**
  10924. * Unselect selected nodes. If no selection array is provided, all nodes
  10925. * are unselected
  10926. * @param {Object[]} selection Array with selection objects, each selection
  10927. * object has a parameter row. Optional
  10928. * @param {Boolean} triggerSelect If true (default), the select event
  10929. * is triggered when nodes are unselected
  10930. * @return {Boolean} changed True if the selection is changed
  10931. * @private
  10932. */
  10933. Graph.prototype._unselectNodes = function(selection, triggerSelect) {
  10934. var changed = false;
  10935. var i, iMax, id;
  10936. if (selection) {
  10937. // remove provided selections
  10938. for (i = 0, iMax = selection.length; i < iMax; i++) {
  10939. id = selection[i];
  10940. if (this.nodes.hasOwnProperty(id)) {
  10941. this.nodes[id].unselect();
  10942. }
  10943. var j = 0;
  10944. while (j < this.selection.length) {
  10945. if (this.selection[j] == id) {
  10946. this.selection.splice(j, 1);
  10947. changed = true;
  10948. }
  10949. else {
  10950. j++;
  10951. }
  10952. }
  10953. }
  10954. }
  10955. else if (this.selection && this.selection.length) {
  10956. // remove all selections
  10957. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  10958. id = this.selection[i];
  10959. if (this.nodes.hasOwnProperty(id)) {
  10960. this.nodes[id].unselect();
  10961. }
  10962. changed = true;
  10963. }
  10964. this.selection = [];
  10965. }
  10966. if (changed && (triggerSelect == true || triggerSelect == undefined)) {
  10967. // fire the select event
  10968. this._trigger('select');
  10969. }
  10970. return changed;
  10971. };
  10972. /**
  10973. * select all nodes on given location x, y
  10974. * @param {Array} selection an array with node ids
  10975. * @param {boolean} append If true, the new selection will be appended to the
  10976. * current selection (except for duplicate entries)
  10977. * @return {Boolean} changed True if the selection is changed
  10978. * @private
  10979. */
  10980. Graph.prototype._selectNodes = function(selection, append) {
  10981. var changed = false;
  10982. var i, iMax;
  10983. // TODO: the selectNodes method is a little messy, rework this
  10984. // check if the current selection equals the desired selection
  10985. var selectionAlreadyThere = true;
  10986. if (selection.length != this.selection.length) {
  10987. selectionAlreadyThere = false;
  10988. }
  10989. else {
  10990. for (i = 0, iMax = Math.min(selection.length, this.selection.length); i < iMax; i++) {
  10991. if (selection[i] != this.selection[i]) {
  10992. selectionAlreadyThere = false;
  10993. break;
  10994. }
  10995. }
  10996. }
  10997. if (selectionAlreadyThere) {
  10998. return changed;
  10999. }
  11000. if (append == undefined || append == false) {
  11001. // first deselect any selected node
  11002. var triggerSelect = false;
  11003. changed = this._unselectNodes(undefined, triggerSelect);
  11004. }
  11005. for (i = 0, iMax = selection.length; i < iMax; i++) {
  11006. // add each of the new selections, but only when they are not duplicate
  11007. var id = selection[i];
  11008. var isDuplicate = (this.selection.indexOf(id) != -1);
  11009. if (!isDuplicate) {
  11010. this.nodes[id].select();
  11011. this.selection.push(id);
  11012. changed = true;
  11013. }
  11014. }
  11015. if (changed) {
  11016. // fire the select event
  11017. this._trigger('select');
  11018. }
  11019. return changed;
  11020. };
  11021. /**
  11022. * retrieve all nodes overlapping with given object
  11023. * @param {Object} obj An object with parameters left, top, right, bottom
  11024. * @return {Number[]} An array with id's of the overlapping nodes
  11025. * @private
  11026. */
  11027. Graph.prototype._getNodesOverlappingWith = function (obj) {
  11028. var overlappingNodes = [];
  11029. var nodes;
  11030. // search in all universes for nodes
  11031. for (var universe in this.universe["activePockets"]) {
  11032. if (this.universe["activePockets"].hasOwnProperty(universe)) {
  11033. nodes = this.universe["activePockets"][universe]["nodes"];
  11034. for (var id in nodes) {
  11035. if (nodes.hasOwnProperty(id)) {
  11036. if (nodes[id].isOverlappingWith(obj)) {
  11037. overlappingNodes.push(id);
  11038. }
  11039. }
  11040. }
  11041. }
  11042. }
  11043. for (var universe in this.universe["frozenPockets"]) {
  11044. if (this.universe["frozenPockets"].hasOwnProperty(universe)) {
  11045. nodes = this.universe["frozenPockets"][universe]["nodes"];
  11046. for (var id in nodes) {
  11047. if (nodes.hasOwnProperty(id)) {
  11048. if (nodes[id].isOverlappingWith(obj)) {
  11049. overlappingNodes.push(id);
  11050. }
  11051. }
  11052. }
  11053. }
  11054. }
  11055. this.nodes = this.universe["activePockets"][this.activeUniverse[this.activeUniverse.length-1]]["nodes"];
  11056. return overlappingNodes;
  11057. };
  11058. /**
  11059. * retrieve the currently selected nodes
  11060. * @return {Number[] | String[]} selection An array with the ids of the
  11061. * selected nodes.
  11062. */
  11063. Graph.prototype.getSelection = function() {
  11064. return this.selection.concat([]);
  11065. };
  11066. /**
  11067. * select zero or more nodes
  11068. * @param {Number[] | String[]} selection An array with the ids of the
  11069. * selected nodes.
  11070. */
  11071. Graph.prototype.setSelection = function(selection) {
  11072. var i, iMax, id;
  11073. if (!selection || (selection.length == undefined))
  11074. throw 'Selection must be an array with ids';
  11075. // first unselect any selected node
  11076. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  11077. id = this.selection[i];
  11078. this.nodes[id].unselect();
  11079. }
  11080. this.selection = [];
  11081. for (i = 0, iMax = selection.length; i < iMax; i++) {
  11082. id = selection[i];
  11083. var node = this.nodes[id];
  11084. if (!node) {
  11085. throw new RangeError('Node with id "' + id + '" not found');
  11086. }
  11087. node.select();
  11088. this.selection.push(id);
  11089. }
  11090. this.redraw();
  11091. };
  11092. /**
  11093. * Validate the selection: remove ids of nodes which no longer exist
  11094. * @private
  11095. */
  11096. Graph.prototype._updateSelection = function () {
  11097. var i = 0;
  11098. while (i < this.selection.length) {
  11099. var id = this.selection[i];
  11100. if (!this.nodes[id]) {
  11101. this.selection.splice(i, 1);
  11102. }
  11103. else {
  11104. i++;
  11105. }
  11106. }
  11107. };
  11108. /**
  11109. * Temporary method to test calculating a hub value for the nodes
  11110. * @param {number} level Maximum number edges between two nodes in order
  11111. * to call them connected. Optional, 1 by default
  11112. * @return {Number[]} connectioncount array with the connection count
  11113. * for each node
  11114. * @private
  11115. */
  11116. Graph.prototype._getConnectionCount = function(level) {
  11117. if (level == undefined) {
  11118. level = 1;
  11119. }
  11120. // get the nodes connected to given nodes
  11121. function getConnectedNodes(nodes) {
  11122. var connectedNodes = [];
  11123. for (var j = 0, jMax = nodes.length; j < jMax; j++) {
  11124. var node = nodes[j];
  11125. // find all nodes connected to this node
  11126. var edges = node.edges;
  11127. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  11128. var edge = edges[i];
  11129. var other = null;
  11130. // check if connected
  11131. if (edge.from == node)
  11132. other = edge.to;
  11133. else if (edge.to == node)
  11134. other = edge.from;
  11135. // check if the other node is not already in the list with nodes
  11136. var k, kMax;
  11137. if (other) {
  11138. for (k = 0, kMax = nodes.length; k < kMax; k++) {
  11139. if (nodes[k] == other) {
  11140. other = null;
  11141. break;
  11142. }
  11143. }
  11144. }
  11145. if (other) {
  11146. for (k = 0, kMax = connectedNodes.length; k < kMax; k++) {
  11147. if (connectedNodes[k] == other) {
  11148. other = null;
  11149. break;
  11150. }
  11151. }
  11152. }
  11153. if (other)
  11154. connectedNodes.push(other);
  11155. }
  11156. }
  11157. return connectedNodes;
  11158. }
  11159. var connections = [];
  11160. var nodes = this.nodes;
  11161. for (var id in nodes) {
  11162. if (nodes.hasOwnProperty(id)) {
  11163. var c = [nodes[id]];
  11164. for (var l = 0; l < level; l++) {
  11165. c = c.concat(getConnectedNodes(c));
  11166. }
  11167. connections.push(c);
  11168. }
  11169. }
  11170. var hubs = [];
  11171. for (var i = 0, len = connections.length; i < len; i++) {
  11172. hubs.push(connections[i].length);
  11173. }
  11174. return hubs;
  11175. };
  11176. /**
  11177. * Set a new size for the graph
  11178. * @param {string} width Width in pixels or percentage (for example '800px'
  11179. * or '50%')
  11180. * @param {string} height Height in pixels or percentage (for example '400px'
  11181. * or '30%')
  11182. */
  11183. Graph.prototype.setSize = function(width, height) {
  11184. this.frame.style.width = width;
  11185. this.frame.style.height = height;
  11186. this.frame.canvas.style.width = '100%';
  11187. this.frame.canvas.style.height = '100%';
  11188. this.frame.canvas.width = this.frame.canvas.clientWidth;
  11189. this.frame.canvas.height = this.frame.canvas.clientHeight;
  11190. };
  11191. /**
  11192. * Set a data set with nodes for the graph
  11193. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  11194. * @private
  11195. */
  11196. Graph.prototype._setNodes = function(nodes) {
  11197. var oldNodesData = this.nodesData;
  11198. if (nodes instanceof DataSet || nodes instanceof DataView) {
  11199. this.nodesData = nodes;
  11200. }
  11201. else if (nodes instanceof Array) {
  11202. this.nodesData = new DataSet();
  11203. this.nodesData.add(nodes);
  11204. }
  11205. else if (!nodes) {
  11206. this.nodesData = new DataSet();
  11207. }
  11208. else {
  11209. throw new TypeError('Array or DataSet expected');
  11210. }
  11211. if (oldNodesData) {
  11212. // unsubscribe from old dataset
  11213. util.forEach(this.nodesListeners, function (callback, event) {
  11214. oldNodesData.unsubscribe(event, callback);
  11215. });
  11216. }
  11217. // remove drawn nodes
  11218. this.nodes = {};
  11219. if (this.nodesData) {
  11220. // subscribe to new dataset
  11221. var me = this;
  11222. util.forEach(this.nodesListeners, function (callback, event) {
  11223. me.nodesData.subscribe(event, callback);
  11224. });
  11225. // draw all new nodes
  11226. var ids = this.nodesData.getIds();
  11227. this._addNodes(ids);
  11228. }
  11229. this._updateSelection();
  11230. };
  11231. /**
  11232. * Add nodes
  11233. * @param {Number[] | String[]} ids
  11234. * @private
  11235. */
  11236. Graph.prototype._addNodes = function(ids) {
  11237. var id;
  11238. for (var i = 0, len = ids.length; i < len; i++) {
  11239. id = ids[i];
  11240. var data = this.nodesData.get(id);
  11241. var node = new Node(data, this.images, this.groups, this.constants);
  11242. this.nodes[id] = node; // note: this may replace an existing node
  11243. if (!node.isFixed()) {
  11244. // TODO: position new nodes in a smarter way!
  11245. var radius = this.constants.edges.length * 2;
  11246. var count = ids.length;
  11247. var angle = 2 * Math.PI * (i / count);
  11248. node.x = radius * Math.cos(angle);
  11249. node.y = radius * Math.sin(angle);
  11250. // note: no not use node.isMoving() here, as that gives the current
  11251. // velocity of the node, which is zero after creation of the node.
  11252. this.moving = true;
  11253. }
  11254. }
  11255. this._updateNodeIndexList();
  11256. this._reconnectEdges();
  11257. this._updateValueRange(this.nodes);
  11258. };
  11259. /**
  11260. * Update existing nodes, or create them when not yet existing
  11261. * @param {Number[] | String[]} ids
  11262. * @private
  11263. */
  11264. Graph.prototype._updateNodes = function(ids) {
  11265. var nodes = this.nodes,
  11266. nodesData = this.nodesData;
  11267. for (var i = 0, len = ids.length; i < len; i++) {
  11268. var id = ids[i];
  11269. var node = nodes[id];
  11270. var data = nodesData.get(id);
  11271. if (node) {
  11272. // update node
  11273. node.setProperties(data, this.constants);
  11274. }
  11275. else {
  11276. // create node
  11277. node = new Node(properties, this.images, this.groups, this.constants);
  11278. nodes[id] = node;
  11279. if (!node.isFixed()) {
  11280. this.moving = true;
  11281. }
  11282. }
  11283. }
  11284. this._updateNodeIndexList();
  11285. this._reconnectEdges();
  11286. this._updateValueRange(nodes);
  11287. };
  11288. /**
  11289. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  11290. * @param {Number[] | String[]} ids
  11291. * @private
  11292. */
  11293. Graph.prototype._removeNodes = function(ids) {
  11294. var nodes = this.nodes;
  11295. for (var i = 0, len = ids.length; i < len; i++) {
  11296. var id = ids[i];
  11297. delete nodes[id];
  11298. }
  11299. this._updateNodeIndexList();
  11300. this._reconnectEdges();
  11301. this._updateSelection();
  11302. this._updateValueRange(nodes);
  11303. };
  11304. /**
  11305. * Load edges by reading the data table
  11306. * @param {Array | DataSet | DataView} edges The data containing the edges.
  11307. * @private
  11308. * @private
  11309. */
  11310. Graph.prototype._setEdges = function(edges) {
  11311. var oldEdgesData = this.edgesData;
  11312. if (edges instanceof DataSet || edges instanceof DataView) {
  11313. this.edgesData = edges;
  11314. }
  11315. else if (edges instanceof Array) {
  11316. this.edgesData = new DataSet();
  11317. this.edgesData.add(edges);
  11318. }
  11319. else if (!edges) {
  11320. this.edgesData = new DataSet();
  11321. }
  11322. else {
  11323. throw new TypeError('Array or DataSet expected');
  11324. }
  11325. if (oldEdgesData) {
  11326. // unsubscribe from old dataset
  11327. util.forEach(this.edgesListeners, function (callback, event) {
  11328. oldEdgesData.unsubscribe(event, callback);
  11329. });
  11330. }
  11331. // remove drawn edges
  11332. this.edges = {};
  11333. if (this.edgesData) {
  11334. // subscribe to new dataset
  11335. var me = this;
  11336. util.forEach(this.edgesListeners, function (callback, event) {
  11337. me.edgesData.subscribe(event, callback);
  11338. });
  11339. // draw all new nodes
  11340. var ids = this.edgesData.getIds();
  11341. this._addEdges(ids);
  11342. }
  11343. this._reconnectEdges();
  11344. };
  11345. /**
  11346. * Add edges
  11347. * @param {Number[] | String[]} ids
  11348. * @private
  11349. */
  11350. Graph.prototype._addEdges = function (ids) {
  11351. var edges = this.edges,
  11352. edgesData = this.edgesData;
  11353. for (var i = 0, len = ids.length; i < len; i++) {
  11354. var id = ids[i];
  11355. var oldEdge = edges[id];
  11356. if (oldEdge) {
  11357. oldEdge.disconnect();
  11358. }
  11359. var data = edgesData.get(id, {"showInternalIds" : true});
  11360. edges[id] = new Edge(data, this, this.constants);
  11361. }
  11362. this.moving = true;
  11363. this._updateValueRange(edges);
  11364. };
  11365. /**
  11366. * Update existing edges, or create them when not yet existing
  11367. * @param {Number[] | String[]} ids
  11368. * @private
  11369. */
  11370. Graph.prototype._updateEdges = function (ids) {
  11371. var edges = this.edges,
  11372. edgesData = this.edgesData;
  11373. for (var i = 0, len = ids.length; i < len; i++) {
  11374. var id = ids[i];
  11375. var data = edgesData.get(id);
  11376. var edge = edges[id];
  11377. if (edge) {
  11378. // update edge
  11379. edge.disconnect();
  11380. edge.setProperties(data, this.constants);
  11381. edge.connect();
  11382. }
  11383. else {
  11384. // create edge
  11385. edge = new Edge(data, this, this.constants);
  11386. this.edges[id] = edge;
  11387. }
  11388. }
  11389. this.moving = true;
  11390. this._updateValueRange(edges);
  11391. };
  11392. /**
  11393. * Remove existing edges. Non existing ids will be ignored
  11394. * @param {Number[] | String[]} ids
  11395. * @private
  11396. */
  11397. Graph.prototype._removeEdges = function (ids) {
  11398. var edges = this.edges;
  11399. for (var i = 0, len = ids.length; i < len; i++) {
  11400. var id = ids[i];
  11401. var edge = edges[id];
  11402. if (edge) {
  11403. edge.disconnect();
  11404. delete edges[id];
  11405. }
  11406. }
  11407. this.moving = true;
  11408. this._updateValueRange(edges);
  11409. };
  11410. /**
  11411. * Reconnect all edges
  11412. * @private
  11413. */
  11414. Graph.prototype._reconnectEdges = function() {
  11415. var id,
  11416. nodes = this.nodes,
  11417. edges = this.edges;
  11418. for (id in nodes) {
  11419. if (nodes.hasOwnProperty(id)) {
  11420. nodes[id].edges = [];
  11421. }
  11422. }
  11423. for (id in edges) {
  11424. if (edges.hasOwnProperty(id)) {
  11425. var edge = edges[id];
  11426. edge.from = null;
  11427. edge.to = null;
  11428. edge.connect();
  11429. }
  11430. }
  11431. };
  11432. /**
  11433. * Update the values of all object in the given array according to the current
  11434. * value range of the objects in the array.
  11435. * @param {Object} obj An object containing a set of Edges or Nodes
  11436. * The objects must have a method getValue() and
  11437. * setValueRange(min, max).
  11438. * @private
  11439. */
  11440. Graph.prototype._updateValueRange = function(obj) {
  11441. var id;
  11442. // determine the range of the objects
  11443. var valueMin = undefined;
  11444. var valueMax = undefined;
  11445. for (id in obj) {
  11446. if (obj.hasOwnProperty(id)) {
  11447. var value = obj[id].getValue();
  11448. if (value !== undefined) {
  11449. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  11450. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  11451. }
  11452. }
  11453. }
  11454. // adjust the range of all objects
  11455. if (valueMin !== undefined && valueMax !== undefined) {
  11456. for (id in obj) {
  11457. if (obj.hasOwnProperty(id)) {
  11458. obj[id].setValueRange(valueMin, valueMax);
  11459. }
  11460. }
  11461. }
  11462. };
  11463. /**
  11464. * Redraw the graph with the current data
  11465. * chart will be resized too.
  11466. */
  11467. Graph.prototype.redraw = function() {
  11468. this.setSize(this.width, this.height);
  11469. this._redraw();
  11470. };
  11471. /**
  11472. * Redraw the graph with the current data
  11473. * @private
  11474. */
  11475. Graph.prototype._redraw = function() {
  11476. var ctx = this.frame.canvas.getContext('2d');
  11477. // clear the canvas
  11478. var w = this.frame.canvas.width;
  11479. var h = this.frame.canvas.height;
  11480. ctx.clearRect(0, 0, w, h);
  11481. // set scaling and translation
  11482. ctx.save();
  11483. ctx.translate(this.translation.x, this.translation.y);
  11484. ctx.scale(this.scale, this.scale);
  11485. // this._drawEdges(ctx);
  11486. // this._drawNodes(ctx);
  11487. for (var universe in this.universe["activePockets"]) {
  11488. if (this.universe["activePockets"].hasOwnProperty(universe)) {
  11489. this.edges = this.universe["activePockets"][universe]["edges"];
  11490. this._drawEdges(ctx);
  11491. }
  11492. }
  11493. for (var universe in this.universe["frozenPockets"]) {
  11494. if (this.universe["frozenPockets"].hasOwnProperty(universe)) {
  11495. this.edges = this.universe["frozenPockets"][universe]["edges"];
  11496. this._drawEdges(ctx);
  11497. }
  11498. }
  11499. for (var universe in this.universe["activePockets"]) {
  11500. if (this.universe["activePockets"].hasOwnProperty(universe)) {
  11501. this.nodes = this.universe["activePockets"][universe]["nodes"];
  11502. this._drawNodes(ctx);
  11503. }
  11504. }
  11505. for (var universe in this.universe["frozenPockets"]) {
  11506. if (this.universe["frozenPockets"].hasOwnProperty(universe)) {
  11507. this.nodes = this.universe["frozenPockets"][universe]["nodes"];
  11508. this._drawNodes(ctx);
  11509. }
  11510. }
  11511. this.nodeIndices = this.universe["activePockets"][this.activeUniverse[this.activeUniverse.length-1]]["nodeIndices"];
  11512. this.nodes = this.universe["activePockets"][this.activeUniverse[this.activeUniverse.length-1]]["nodes"];
  11513. this.edges = this.universe["activePockets"][this.activeUniverse[this.activeUniverse.length-1]]["edges"];
  11514. // restore original scaling and translation
  11515. ctx.restore();
  11516. };
  11517. /**
  11518. * Set the translation of the graph
  11519. * @param {Number} offsetX Horizontal offset
  11520. * @param {Number} offsetY Vertical offset
  11521. * @private
  11522. */
  11523. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  11524. if (this.translation === undefined) {
  11525. this.translation = {
  11526. x: 0,
  11527. y: 0
  11528. };
  11529. }
  11530. if (offsetX !== undefined) {
  11531. this.translation.x = offsetX;
  11532. }
  11533. if (offsetY !== undefined) {
  11534. this.translation.y = offsetY;
  11535. }
  11536. };
  11537. /**
  11538. * Get the translation of the graph
  11539. * @return {Object} translation An object with parameters x and y, both a number
  11540. * @private
  11541. */
  11542. Graph.prototype._getTranslation = function() {
  11543. return {
  11544. x: this.translation.x,
  11545. y: this.translation.y
  11546. };
  11547. };
  11548. /**
  11549. * Scale the graph
  11550. * @param {Number} scale Scaling factor 1.0 is unscaled
  11551. * @private
  11552. */
  11553. Graph.prototype._setScale = function(scale) {
  11554. this.scale = scale;
  11555. };
  11556. /**
  11557. * Get the current scale of the graph
  11558. * @return {Number} scale Scaling factor 1.0 is unscaled
  11559. * @private
  11560. */
  11561. Graph.prototype._getScale = function() {
  11562. return this.scale;
  11563. };
  11564. /**
  11565. * Convert a horizontal point on the HTML canvas to the x-value of the model
  11566. * @param {number} x
  11567. * @returns {number}
  11568. * @private
  11569. */
  11570. Graph.prototype._canvasToX = function(x) {
  11571. return (x - this.translation.x) / this.scale;
  11572. };
  11573. /**
  11574. * Convert an x-value in the model to a horizontal point on the HTML canvas
  11575. * @param {number} x
  11576. * @returns {number}
  11577. * @private
  11578. */
  11579. Graph.prototype._xToCanvas = function(x) {
  11580. return x * this.scale + this.translation.x;
  11581. };
  11582. /**
  11583. * Convert a vertical point on the HTML canvas to the y-value of the model
  11584. * @param {number} y
  11585. * @returns {number}
  11586. * @private
  11587. */
  11588. Graph.prototype._canvasToY = function(y) {
  11589. return (y - this.translation.y) / this.scale;
  11590. };
  11591. /**
  11592. * Convert an y-value in the model to a vertical point on the HTML canvas
  11593. * @param {number} y
  11594. * @returns {number}
  11595. * @private
  11596. */
  11597. Graph.prototype._yToCanvas = function(y) {
  11598. return y * this.scale + this.translation.y ;
  11599. };
  11600. /**
  11601. * Redraw all nodes
  11602. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  11603. * @param {CanvasRenderingContext2D} ctx
  11604. * @private
  11605. */
  11606. Graph.prototype._drawNodes = function(ctx) {
  11607. // first draw the unselected nodes
  11608. var nodes = this.nodes;
  11609. var selected = [];
  11610. for (var id in nodes) {
  11611. if (nodes.hasOwnProperty(id)) {
  11612. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  11613. if (nodes[id].isSelected()) {
  11614. selected.push(id);
  11615. }
  11616. else {
  11617. if (nodes[id].inArea()) {
  11618. nodes[id].draw(ctx);
  11619. }
  11620. }
  11621. }
  11622. }
  11623. // draw the selected nodes on top
  11624. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  11625. if (nodes[selected[s]].inArea()) {
  11626. nodes[selected[s]].draw(ctx);
  11627. }
  11628. }
  11629. };
  11630. /**
  11631. * Redraw all edges
  11632. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  11633. * @param {CanvasRenderingContext2D} ctx
  11634. * @private
  11635. */
  11636. Graph.prototype._drawEdges = function(ctx) {
  11637. var edges = this.edges;
  11638. for (var id in edges) {
  11639. if (edges.hasOwnProperty(id)) {
  11640. var edge = edges[id];
  11641. edge.setScale(this.scale);
  11642. if (edge.connected) {
  11643. edges[id].draw(ctx);
  11644. }
  11645. }
  11646. }
  11647. };
  11648. /**
  11649. * Find a stable position for all nodes
  11650. * @private
  11651. */
  11652. Graph.prototype._doStabilize = function() {
  11653. //var start = new Date();
  11654. // find stable position
  11655. var count = 0;
  11656. var vmin = this.constants.minVelocity;
  11657. var stable = false;
  11658. while (!stable && count < this.constants.maxIterations) {
  11659. this._calculateForces();
  11660. this._discreteStepNodes();
  11661. stable = !this._isMoving(vmin);
  11662. count++;
  11663. }
  11664. // var end = new Date();
  11665. // console.log('Stabilized in ' + (end-start) + ' ms, ' + count + ' iterations' ); // TODO: cleanup
  11666. };
  11667. /**
  11668. * Calculate the external forces acting on the nodes
  11669. * Forces are caused by: edges, repulsing forces between nodes, gravity
  11670. * @private
  11671. */
  11672. Graph.prototype._calculateForces = function(nodes,edges) {
  11673. // stop calculation if there is only one node
  11674. if (this.nodeIndices.length == 1) {
  11675. this.nodes[this.nodeIndices[0]]._setForce(0,0);
  11676. }
  11677. // if there are too many nodes on screen, we cluster without repositioning
  11678. else if (this.nodeIndices.length > this.constants.clustering.maxNumberOfNodes * 4 && this.constants.clustering.enableClustering == true) {
  11679. this.clusterToFit(this.constants.clustering.maxNumberOfNodes * 2, false);
  11680. this._calculateForces();
  11681. }
  11682. else {
  11683. this.canvasTopLeft = {"x": (0-this.translation.x)/this.scale,
  11684. "y": (0-this.translation.y)/this.scale};
  11685. this.canvasBottomRight = {"x": (this.frame.canvas.clientWidth -this.translation.x)/this.scale,
  11686. "y": (this.frame.canvas.clientHeight-this.translation.y)/this.scale};
  11687. var centerPos = {"x":0.5*(this.canvasTopLeft.x + this.canvasBottomRight.x),
  11688. "y":0.5*(this.canvasTopLeft.y + this.canvasBottomRight.y)}
  11689. // create a local edge to the nodes and edges, that is faster
  11690. var dx, dy, angle, distance, fx, fy,
  11691. repulsingForce, springForce, length, edgeLength,
  11692. node, node1, node2, edge, edgeID, i, j, nodeID, xCenter, yCenter;
  11693. var clusterSize;
  11694. var nodes = this.nodes;
  11695. var edges = this.edges;
  11696. // Gravity is required to keep separated groups from floating off
  11697. // the forces are reset to zero in this loop by using _setForce instead
  11698. // of _addForce
  11699. var gravity = 0.08;
  11700. for (i = 0; i < this.nodeIndices.length; i++) {
  11701. node = nodes[this.nodeIndices[i]];
  11702. if (this.activeUniverse[this.activeUniverse.length-1] == "default") {
  11703. dx = -node.x + centerPos.x;
  11704. dy = -node.y + centerPos.y;
  11705. angle = Math.atan2(dy, dx);
  11706. fx = Math.cos(angle) * gravity;
  11707. fy = Math.sin(angle) * gravity;
  11708. }
  11709. else {
  11710. fx = 0;
  11711. fy = 0;
  11712. }
  11713. node._setForce(fx, fy);
  11714. node.updateDamping(this.nodeIndices.length);
  11715. }
  11716. this.updateLabels();
  11717. // repulsing forces between nodes
  11718. var minimumDistance = this.constants.nodes.distance,
  11719. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  11720. // we loop from i over all but the last entree in the array
  11721. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  11722. for (i = 0; i < this.nodeIndices.length-1; i++) {
  11723. node1 = nodes[this.nodeIndices[i]];
  11724. for (j = i+1; j < this.nodeIndices.length; j++) {
  11725. node2 = nodes[this.nodeIndices[j]];
  11726. clusterSize = (node1.clusterSize + node2.clusterSize - 2);
  11727. dx = node2.x - node1.x;
  11728. dy = node2.y - node1.y;
  11729. distance = Math.sqrt(dx * dx + dy * dy);
  11730. // clusters have a larger region of influence
  11731. minimumDistance = (clusterSize == 0) ? this.constants.nodes.distance : (this.constants.nodes.distance * (1 + clusterSize * this.constants.clustering.distanceAmplification));
  11732. if (distance < 2*minimumDistance) { // at 2.0 * the minimum distance, the force is 0.000045
  11733. angle = Math.atan2(dy, dx);
  11734. if (distance < 0.5*minimumDistance) { // at 0.5 * the minimum distance, the force is 0.993307
  11735. repulsingForce = 1.0;
  11736. }
  11737. else {
  11738. // TODO: correct factor for repulsing force
  11739. //repulsingForce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  11740. //repulsingForce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  11741. repulsingForce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)); // TODO: customize the repulsing force
  11742. }
  11743. // amplify the repulsion for clusters.
  11744. repulsingForce *= (clusterSize == 0) ? 1 : 1 + clusterSize * this.constants.clustering.forceAmplification;
  11745. fx = Math.cos(angle) * repulsingForce;
  11746. fy = Math.sin(angle) * repulsingForce;
  11747. node1._addForce(-fx, -fy);
  11748. node2._addForce(fx, fy);
  11749. }
  11750. }
  11751. }
  11752. /*
  11753. // repulsion of the edges on the nodes and
  11754. for (var nodeID in nodes) {
  11755. if (nodes.hasOwnProperty(nodeID)) {
  11756. node = nodes[nodeID];
  11757. for(var edgeID in edges) {
  11758. if (edges.hasOwnProperty(edgeID)) {
  11759. edge = edges[edgeID];
  11760. // get the center of the edge
  11761. xCenter = edge.from.x+(edge.to.x - edge.from.x)/2;
  11762. yCenter = edge.from.y+(edge.to.y - edge.from.y)/2;
  11763. // calculate normally distributed force
  11764. dx = node.x - xCenter;
  11765. dy = node.y - yCenter;
  11766. distance = Math.sqrt(dx * dx + dy * dy);
  11767. if (distance < 2*minimumDistance) { // at 2.0 * the minimum distance, the force is 0.000045
  11768. angle = Math.atan2(dy, dx);
  11769. if (distance < 0.5*minimumDistance) { // at 0.5 * the minimum distance, the force is 0.993307
  11770. repulsingForce = 1.0;
  11771. }
  11772. else {
  11773. // TODO: correct factor for repulsing force
  11774. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  11775. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  11776. repulsingForce = 1 / (1 + Math.exp((distance / (minimumDistance / 2) - 1) * steepness)); // TODO: customize the repulsing force
  11777. }
  11778. fx = Math.cos(angle) * repulsingForce;
  11779. fy = Math.sin(angle) * repulsingForce;
  11780. node._addForce(fx, fy);
  11781. edge.from._addForce(-fx/2,-fy/2);
  11782. edge.to._addForce(-fx/2,-fy/2);
  11783. }
  11784. }
  11785. }
  11786. }
  11787. }
  11788. */
  11789. // forces caused by the edges, modelled as springs
  11790. for (edgeID in edges) {
  11791. if (edges.hasOwnProperty(edgeID)) {
  11792. edge = edges[edgeID];
  11793. if (edge.connected) {
  11794. // only calculate forces if nodes are in the same universe
  11795. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  11796. clusterSize = (edge.to.clusterSize + edge.from.clusterSize - 2);
  11797. dx = (edge.to.x - edge.from.x);
  11798. dy = (edge.to.y - edge.from.y);
  11799. //edgeLength = (edge.from.width + edge.from.height + edge.to.width + edge.to.height)/2 || edge.length; // TODO: dmin
  11800. //edgeLength = (edge.from.width + edge.to.width)/2 || edge.length; // TODO: dmin
  11801. //edgeLength = 20 + ((edge.from.width + edge.to.width) || 0) / 2;
  11802. edgeLength = edge.length;
  11803. // this implies that the edges between big clusters are longer
  11804. edgeLength += clusterSize * this.constants.clustering.edgeGrowth;
  11805. length = Math.sqrt(dx * dx + dy * dy);
  11806. angle = Math.atan2(dy, dx);
  11807. springForce = edge.stiffness * (edgeLength - length);
  11808. fx = Math.cos(angle) * springForce;
  11809. fy = Math.sin(angle) * springForce;
  11810. edge.from._addForce(-fx, -fy);
  11811. edge.to._addForce(fx, fy);
  11812. }
  11813. }
  11814. }
  11815. }
  11816. /*
  11817. // TODO: re-implement repulsion of edges
  11818. // repulsing forces between edges
  11819. var minimumDistance = this.constants.edges.distance,
  11820. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  11821. for (var l = 0; l < edges.length; l++) {
  11822. //Keep distance from other edge centers
  11823. for (var l2 = l + 1; l2 < this.edges.length; l2++) {
  11824. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  11825. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  11826. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  11827. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  11828. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  11829. l2x = edges[l2].from.x+(edges[l2].to.x - edges[l2].from.x)/2,
  11830. l2y = edges[l2].from.y+(edges[l2].to.y - edges[l2].from.y)/2,
  11831. // calculate normally distributed force
  11832. dx = l2x - lx,
  11833. dy = l2y - ly,
  11834. distance = Math.sqrt(dx * dx + dy * dy),
  11835. angle = Math.atan2(dy, dx),
  11836. // TODO: correct factor for repulsing force
  11837. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  11838. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  11839. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  11840. fx = Math.cos(angle) * repulsingforce,
  11841. fy = Math.sin(angle) * repulsingforce;
  11842. edges[l].from._addForce(-fx, -fy);
  11843. edges[l].to._addForce(-fx, -fy);
  11844. edges[l2].from._addForce(fx, fy);
  11845. edges[l2].to._addForce(fx, fy);
  11846. }
  11847. }
  11848. */
  11849. }
  11850. };
  11851. /**
  11852. * Check if any of the nodes is still moving
  11853. * @param {number} vmin the minimum velocity considered as 'moving'
  11854. * @return {boolean} true if moving, false if non of the nodes is moving
  11855. * @private
  11856. */
  11857. Graph.prototype._isMoving = function(vmin) {
  11858. // TODO: ismoving does not work well: should check the kinetic energy, not its velocity
  11859. var nodes = this.nodes;
  11860. for (var id in nodes) {
  11861. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  11862. return true;
  11863. }
  11864. }
  11865. return false;
  11866. };
  11867. /**
  11868. * Perform one discrete step for all nodes
  11869. * @private
  11870. */
  11871. Graph.prototype._discreteStepNodes = function() {
  11872. var interval = this.refreshRate / 1000.0; // in seconds
  11873. var nodes = this.nodes;
  11874. for (var id in nodes) {
  11875. if (nodes.hasOwnProperty(id)) {
  11876. nodes[id].discreteStep(interval);
  11877. }
  11878. }
  11879. };
  11880. /**
  11881. * Start animating nodes and edges
  11882. */
  11883. Graph.prototype.start = function() {
  11884. if (!this.freezeSimulation) {
  11885. if (this.moving) {
  11886. var vmin = this.constants.minVelocity;
  11887. /*
  11888. this._calculateForces();
  11889. this._discreteStepNodes();
  11890. this.moving = this._isMoving(vmin);
  11891. */
  11892. //console.log("no",this.nodes)
  11893. for (var universe in this.universe["activePockets"]) {
  11894. if (this.universe["activePockets"].hasOwnProperty(universe)) {
  11895. this._switchToUniverse(universe);
  11896. this._calculateForces();
  11897. this._discreteStepNodes();
  11898. this.moving = this._isMoving(vmin);
  11899. }
  11900. }
  11901. this._loadActiveUniverse();
  11902. }
  11903. if (this.moving) {
  11904. // start animation. only start timer if it is not already running
  11905. if (!this.timer) {
  11906. var graph = this;
  11907. this.timer = window.setTimeout(function () {
  11908. graph.timer = undefined;
  11909. graph.start();
  11910. graph.start();
  11911. graph._redraw();
  11912. // var start = window.performance.now();
  11913. // graph._redraw();
  11914. // var end = window.performance.now();
  11915. // var time = end - start;
  11916. // console.log('Drawing time: ' + time);
  11917. }, this.refreshRate);
  11918. }
  11919. }
  11920. else {
  11921. this._redraw();
  11922. }
  11923. }
  11924. };
  11925. Graph.prototype.singleStep = function() {
  11926. if (this.moving) {
  11927. this._calculateForces();
  11928. this._discreteStepNodes();
  11929. var vmin = this.constants.minVelocity;
  11930. this.moving = this._isMoving(vmin);
  11931. this._redraw();
  11932. }
  11933. };
  11934. /**
  11935. * Freeze the animation
  11936. */
  11937. Graph.prototype.toggleFreeze = function() {
  11938. if (this.freezeSimulation == false) {
  11939. this.freezeSimulation = true;
  11940. }
  11941. else {
  11942. this.freezeSimulation = false;
  11943. this.start();
  11944. }
  11945. };
  11946. /**
  11947. * vis.js module exports
  11948. */
  11949. var vis = {
  11950. util: util,
  11951. events: events,
  11952. Controller: Controller,
  11953. DataSet: DataSet,
  11954. DataView: DataView,
  11955. Range: Range,
  11956. Stack: Stack,
  11957. TimeStep: TimeStep,
  11958. EventBus: EventBus,
  11959. components: {
  11960. items: {
  11961. Item: Item,
  11962. ItemBox: ItemBox,
  11963. ItemPoint: ItemPoint,
  11964. ItemRange: ItemRange
  11965. },
  11966. Component: Component,
  11967. Panel: Panel,
  11968. RootPanel: RootPanel,
  11969. ItemSet: ItemSet,
  11970. TimeAxis: TimeAxis
  11971. },
  11972. graph: {
  11973. Node: Node,
  11974. Edge: Edge,
  11975. Popup: Popup,
  11976. Groups: Groups,
  11977. Images: Images
  11978. },
  11979. Timeline: Timeline,
  11980. Graph: Graph
  11981. };
  11982. /**
  11983. * CommonJS module exports
  11984. */
  11985. if (typeof exports !== 'undefined') {
  11986. exports = vis;
  11987. }
  11988. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  11989. module.exports = vis;
  11990. }
  11991. /**
  11992. * AMD module exports
  11993. */
  11994. if (typeof(define) === 'function') {
  11995. define(function () {
  11996. return vis;
  11997. });
  11998. }
  11999. /**
  12000. * Window exports
  12001. */
  12002. if (typeof window !== 'undefined') {
  12003. // attach the module to the window, load as a regular javascript file
  12004. window['vis'] = vis;
  12005. }
  12006. },{"hammerjs":2,"moment":3,"mouseTrap":4}],2:[function(require,module,exports){
  12007. /*! Hammer.JS - v1.0.5 - 2013-04-07
  12008. * http://eightmedia.github.com/hammer.js
  12009. *
  12010. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  12011. * Licensed under the MIT license */
  12012. (function(window, undefined) {
  12013. 'use strict';
  12014. /**
  12015. * Hammer
  12016. * use this to create instances
  12017. * @param {HTMLElement} element
  12018. * @param {Object} options
  12019. * @returns {Hammer.Instance}
  12020. * @constructor
  12021. */
  12022. var Hammer = function(element, options) {
  12023. return new Hammer.Instance(element, options || {});
  12024. };
  12025. // default settings
  12026. Hammer.defaults = {
  12027. // add styles and attributes to the element to prevent the browser from doing
  12028. // its native behavior. this doesnt prevent the scrolling, but cancels
  12029. // the contextmenu, tap highlighting etc
  12030. // set to false to disable this
  12031. stop_browser_behavior: {
  12032. // this also triggers onselectstart=false for IE
  12033. userSelect: 'none',
  12034. // this makes the element blocking in IE10 >, you could experiment with the value
  12035. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  12036. touchAction: 'none',
  12037. touchCallout: 'none',
  12038. contentZooming: 'none',
  12039. userDrag: 'none',
  12040. tapHighlightColor: 'rgba(0,0,0,0)'
  12041. }
  12042. // more settings are defined per gesture at gestures.js
  12043. };
  12044. // detect touchevents
  12045. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  12046. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  12047. // dont use mouseevents on mobile devices
  12048. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  12049. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  12050. // eventtypes per touchevent (start, move, end)
  12051. // are filled by Hammer.event.determineEventTypes on setup
  12052. Hammer.EVENT_TYPES = {};
  12053. // direction defines
  12054. Hammer.DIRECTION_DOWN = 'down';
  12055. Hammer.DIRECTION_LEFT = 'left';
  12056. Hammer.DIRECTION_UP = 'up';
  12057. Hammer.DIRECTION_RIGHT = 'right';
  12058. // pointer type
  12059. Hammer.POINTER_MOUSE = 'mouse';
  12060. Hammer.POINTER_TOUCH = 'touch';
  12061. Hammer.POINTER_PEN = 'pen';
  12062. // touch event defines
  12063. Hammer.EVENT_START = 'start';
  12064. Hammer.EVENT_MOVE = 'move';
  12065. Hammer.EVENT_END = 'end';
  12066. // hammer document where the base events are added at
  12067. Hammer.DOCUMENT = document;
  12068. // plugins namespace
  12069. Hammer.plugins = {};
  12070. // if the window events are set...
  12071. Hammer.READY = false;
  12072. /**
  12073. * setup events to detect gestures on the document
  12074. */
  12075. function setup() {
  12076. if(Hammer.READY) {
  12077. return;
  12078. }
  12079. // find what eventtypes we add listeners to
  12080. Hammer.event.determineEventTypes();
  12081. // Register all gestures inside Hammer.gestures
  12082. for(var name in Hammer.gestures) {
  12083. if(Hammer.gestures.hasOwnProperty(name)) {
  12084. Hammer.detection.register(Hammer.gestures[name]);
  12085. }
  12086. }
  12087. // Add touch events on the document
  12088. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  12089. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  12090. // Hammer is ready...!
  12091. Hammer.READY = true;
  12092. }
  12093. /**
  12094. * create new hammer instance
  12095. * all methods should return the instance itself, so it is chainable.
  12096. * @param {HTMLElement} element
  12097. * @param {Object} [options={}]
  12098. * @returns {Hammer.Instance}
  12099. * @constructor
  12100. */
  12101. Hammer.Instance = function(element, options) {
  12102. var self = this;
  12103. // setup HammerJS window events and register all gestures
  12104. // this also sets up the default options
  12105. setup();
  12106. this.element = element;
  12107. // start/stop detection option
  12108. this.enabled = true;
  12109. // merge options
  12110. this.options = Hammer.utils.extend(
  12111. Hammer.utils.extend({}, Hammer.defaults),
  12112. options || {});
  12113. // add some css to the element to prevent the browser from doing its native behavoir
  12114. if(this.options.stop_browser_behavior) {
  12115. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  12116. }
  12117. // start detection on touchstart
  12118. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  12119. if(self.enabled) {
  12120. Hammer.detection.startDetect(self, ev);
  12121. }
  12122. });
  12123. // return instance
  12124. return this;
  12125. };
  12126. Hammer.Instance.prototype = {
  12127. /**
  12128. * bind events to the instance
  12129. * @param {String} gesture
  12130. * @param {Function} handler
  12131. * @returns {Hammer.Instance}
  12132. */
  12133. on: function onEvent(gesture, handler){
  12134. var gestures = gesture.split(' ');
  12135. for(var t=0; t<gestures.length; t++) {
  12136. this.element.addEventListener(gestures[t], handler, false);
  12137. }
  12138. return this;
  12139. },
  12140. /**
  12141. * unbind events to the instance
  12142. * @param {String} gesture
  12143. * @param {Function} handler
  12144. * @returns {Hammer.Instance}
  12145. */
  12146. off: function offEvent(gesture, handler){
  12147. var gestures = gesture.split(' ');
  12148. for(var t=0; t<gestures.length; t++) {
  12149. this.element.removeEventListener(gestures[t], handler, false);
  12150. }
  12151. return this;
  12152. },
  12153. /**
  12154. * trigger gesture event
  12155. * @param {String} gesture
  12156. * @param {Object} eventData
  12157. * @returns {Hammer.Instance}
  12158. */
  12159. trigger: function triggerEvent(gesture, eventData){
  12160. // create DOM event
  12161. var event = Hammer.DOCUMENT.createEvent('Event');
  12162. event.initEvent(gesture, true, true);
  12163. event.gesture = eventData;
  12164. // trigger on the target if it is in the instance element,
  12165. // this is for event delegation tricks
  12166. var element = this.element;
  12167. if(Hammer.utils.hasParent(eventData.target, element)) {
  12168. element = eventData.target;
  12169. }
  12170. element.dispatchEvent(event);
  12171. return this;
  12172. },
  12173. /**
  12174. * enable of disable hammer.js detection
  12175. * @param {Boolean} state
  12176. * @returns {Hammer.Instance}
  12177. */
  12178. enable: function enable(state) {
  12179. this.enabled = state;
  12180. return this;
  12181. }
  12182. };
  12183. /**
  12184. * this holds the last move event,
  12185. * used to fix empty touchend issue
  12186. * see the onTouch event for an explanation
  12187. * @type {Object}
  12188. */
  12189. var last_move_event = null;
  12190. /**
  12191. * when the mouse is hold down, this is true
  12192. * @type {Boolean}
  12193. */
  12194. var enable_detect = false;
  12195. /**
  12196. * when touch events have been fired, this is true
  12197. * @type {Boolean}
  12198. */
  12199. var touch_triggered = false;
  12200. Hammer.event = {
  12201. /**
  12202. * simple addEventListener
  12203. * @param {HTMLElement} element
  12204. * @param {String} type
  12205. * @param {Function} handler
  12206. */
  12207. bindDom: function(element, type, handler) {
  12208. var types = type.split(' ');
  12209. for(var t=0; t<types.length; t++) {
  12210. element.addEventListener(types[t], handler, false);
  12211. }
  12212. },
  12213. /**
  12214. * touch events with mouse fallback
  12215. * @param {HTMLElement} element
  12216. * @param {String} eventType like Hammer.EVENT_MOVE
  12217. * @param {Function} handler
  12218. */
  12219. onTouch: function onTouch(element, eventType, handler) {
  12220. var self = this;
  12221. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  12222. var sourceEventType = ev.type.toLowerCase();
  12223. // onmouseup, but when touchend has been fired we do nothing.
  12224. // this is for touchdevices which also fire a mouseup on touchend
  12225. if(sourceEventType.match(/mouse/) && touch_triggered) {
  12226. return;
  12227. }
  12228. // mousebutton must be down or a touch event
  12229. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  12230. sourceEventType.match(/pointerdown/) || // pointerevents touch
  12231. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  12232. ){
  12233. enable_detect = true;
  12234. }
  12235. // we are in a touch event, set the touch triggered bool to true,
  12236. // this for the conflicts that may occur on ios and android
  12237. if(sourceEventType.match(/touch|pointer/)) {
  12238. touch_triggered = true;
  12239. }
  12240. // count the total touches on the screen
  12241. var count_touches = 0;
  12242. // when touch has been triggered in this detection session
  12243. // and we are now handling a mouse event, we stop that to prevent conflicts
  12244. if(enable_detect) {
  12245. // update pointerevent
  12246. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  12247. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  12248. }
  12249. // touch
  12250. else if(sourceEventType.match(/touch/)) {
  12251. count_touches = ev.touches.length;
  12252. }
  12253. // mouse
  12254. else if(!touch_triggered) {
  12255. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  12256. }
  12257. // if we are in a end event, but when we remove one touch and
  12258. // we still have enough, set eventType to move
  12259. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  12260. eventType = Hammer.EVENT_MOVE;
  12261. }
  12262. // no touches, force the end event
  12263. else if(!count_touches) {
  12264. eventType = Hammer.EVENT_END;
  12265. }
  12266. // because touchend has no touches, and we often want to use these in our gestures,
  12267. // we send the last move event as our eventData in touchend
  12268. if(!count_touches && last_move_event !== null) {
  12269. ev = last_move_event;
  12270. }
  12271. // store the last move event
  12272. else {
  12273. last_move_event = ev;
  12274. }
  12275. // trigger the handler
  12276. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  12277. // remove pointerevent from list
  12278. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  12279. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  12280. }
  12281. }
  12282. //debug(sourceEventType +" "+ eventType);
  12283. // on the end we reset everything
  12284. if(!count_touches) {
  12285. last_move_event = null;
  12286. enable_detect = false;
  12287. touch_triggered = false;
  12288. Hammer.PointerEvent.reset();
  12289. }
  12290. });
  12291. },
  12292. /**
  12293. * we have different events for each device/browser
  12294. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  12295. */
  12296. determineEventTypes: function determineEventTypes() {
  12297. // determine the eventtype we want to set
  12298. var types;
  12299. // pointerEvents magic
  12300. if(Hammer.HAS_POINTEREVENTS) {
  12301. types = Hammer.PointerEvent.getEvents();
  12302. }
  12303. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  12304. else if(Hammer.NO_MOUSEEVENTS) {
  12305. types = [
  12306. 'touchstart',
  12307. 'touchmove',
  12308. 'touchend touchcancel'];
  12309. }
  12310. // for non pointer events browsers and mixed browsers,
  12311. // like chrome on windows8 touch laptop
  12312. else {
  12313. types = [
  12314. 'touchstart mousedown',
  12315. 'touchmove mousemove',
  12316. 'touchend touchcancel mouseup'];
  12317. }
  12318. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  12319. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  12320. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  12321. },
  12322. /**
  12323. * create touchlist depending on the event
  12324. * @param {Object} ev
  12325. * @param {String} eventType used by the fakemultitouch plugin
  12326. */
  12327. getTouchList: function getTouchList(ev/*, eventType*/) {
  12328. // get the fake pointerEvent touchlist
  12329. if(Hammer.HAS_POINTEREVENTS) {
  12330. return Hammer.PointerEvent.getTouchList();
  12331. }
  12332. // get the touchlist
  12333. else if(ev.touches) {
  12334. return ev.touches;
  12335. }
  12336. // make fake touchlist from mouse position
  12337. else {
  12338. return [{
  12339. identifier: 1,
  12340. pageX: ev.pageX,
  12341. pageY: ev.pageY,
  12342. target: ev.target
  12343. }];
  12344. }
  12345. },
  12346. /**
  12347. * collect event data for Hammer js
  12348. * @param {HTMLElement} element
  12349. * @param {String} eventType like Hammer.EVENT_MOVE
  12350. * @param {Object} eventData
  12351. */
  12352. collectEventData: function collectEventData(element, eventType, ev) {
  12353. var touches = this.getTouchList(ev, eventType);
  12354. // find out pointerType
  12355. var pointerType = Hammer.POINTER_TOUCH;
  12356. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  12357. pointerType = Hammer.POINTER_MOUSE;
  12358. }
  12359. return {
  12360. center : Hammer.utils.getCenter(touches),
  12361. timeStamp : new Date().getTime(),
  12362. target : ev.target,
  12363. touches : touches,
  12364. eventType : eventType,
  12365. pointerType : pointerType,
  12366. srcEvent : ev,
  12367. /**
  12368. * prevent the browser default actions
  12369. * mostly used to disable scrolling of the browser
  12370. */
  12371. preventDefault: function() {
  12372. if(this.srcEvent.preventManipulation) {
  12373. this.srcEvent.preventManipulation();
  12374. }
  12375. if(this.srcEvent.preventDefault) {
  12376. this.srcEvent.preventDefault();
  12377. }
  12378. },
  12379. /**
  12380. * stop bubbling the event up to its parents
  12381. */
  12382. stopPropagation: function() {
  12383. this.srcEvent.stopPropagation();
  12384. },
  12385. /**
  12386. * immediately stop gesture detection
  12387. * might be useful after a swipe was detected
  12388. * @return {*}
  12389. */
  12390. stopDetect: function() {
  12391. return Hammer.detection.stopDetect();
  12392. }
  12393. };
  12394. }
  12395. };
  12396. Hammer.PointerEvent = {
  12397. /**
  12398. * holds all pointers
  12399. * @type {Object}
  12400. */
  12401. pointers: {},
  12402. /**
  12403. * get a list of pointers
  12404. * @returns {Array} touchlist
  12405. */
  12406. getTouchList: function() {
  12407. var self = this;
  12408. var touchlist = [];
  12409. // we can use forEach since pointerEvents only is in IE10
  12410. Object.keys(self.pointers).sort().forEach(function(id) {
  12411. touchlist.push(self.pointers[id]);
  12412. });
  12413. return touchlist;
  12414. },
  12415. /**
  12416. * update the position of a pointer
  12417. * @param {String} type Hammer.EVENT_END
  12418. * @param {Object} pointerEvent
  12419. */
  12420. updatePointer: function(type, pointerEvent) {
  12421. if(type == Hammer.EVENT_END) {
  12422. this.pointers = {};
  12423. }
  12424. else {
  12425. pointerEvent.identifier = pointerEvent.pointerId;
  12426. this.pointers[pointerEvent.pointerId] = pointerEvent;
  12427. }
  12428. return Object.keys(this.pointers).length;
  12429. },
  12430. /**
  12431. * check if ev matches pointertype
  12432. * @param {String} pointerType Hammer.POINTER_MOUSE
  12433. * @param {PointerEvent} ev
  12434. */
  12435. matchType: function(pointerType, ev) {
  12436. if(!ev.pointerType) {
  12437. return false;
  12438. }
  12439. var types = {};
  12440. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  12441. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  12442. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  12443. return types[pointerType];
  12444. },
  12445. /**
  12446. * get events
  12447. */
  12448. getEvents: function() {
  12449. return [
  12450. 'pointerdown MSPointerDown',
  12451. 'pointermove MSPointerMove',
  12452. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  12453. ];
  12454. },
  12455. /**
  12456. * reset the list
  12457. */
  12458. reset: function() {
  12459. this.pointers = {};
  12460. }
  12461. };
  12462. Hammer.utils = {
  12463. /**
  12464. * extend method,
  12465. * also used for cloning when dest is an empty object
  12466. * @param {Object} dest
  12467. * @param {Object} src
  12468. * @parm {Boolean} merge do a merge
  12469. * @returns {Object} dest
  12470. */
  12471. extend: function extend(dest, src, merge) {
  12472. for (var key in src) {
  12473. if(dest[key] !== undefined && merge) {
  12474. continue;
  12475. }
  12476. dest[key] = src[key];
  12477. }
  12478. return dest;
  12479. },
  12480. /**
  12481. * find if a node is in the given parent
  12482. * used for event delegation tricks
  12483. * @param {HTMLElement} node
  12484. * @param {HTMLElement} parent
  12485. * @returns {boolean} has_parent
  12486. */
  12487. hasParent: function(node, parent) {
  12488. while(node){
  12489. if(node == parent) {
  12490. return true;
  12491. }
  12492. node = node.parentNode;
  12493. }
  12494. return false;
  12495. },
  12496. /**
  12497. * get the center of all the touches
  12498. * @param {Array} touches
  12499. * @returns {Object} center
  12500. */
  12501. getCenter: function getCenter(touches) {
  12502. var valuesX = [], valuesY = [];
  12503. for(var t= 0,len=touches.length; t<len; t++) {
  12504. valuesX.push(touches[t].pageX);
  12505. valuesY.push(touches[t].pageY);
  12506. }
  12507. return {
  12508. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  12509. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  12510. };
  12511. },
  12512. /**
  12513. * calculate the velocity between two points
  12514. * @param {Number} delta_time
  12515. * @param {Number} delta_x
  12516. * @param {Number} delta_y
  12517. * @returns {Object} velocity
  12518. */
  12519. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  12520. return {
  12521. x: Math.abs(delta_x / delta_time) || 0,
  12522. y: Math.abs(delta_y / delta_time) || 0
  12523. };
  12524. },
  12525. /**
  12526. * calculate the angle between two coordinates
  12527. * @param {Touch} touch1
  12528. * @param {Touch} touch2
  12529. * @returns {Number} angle
  12530. */
  12531. getAngle: function getAngle(touch1, touch2) {
  12532. var y = touch2.pageY - touch1.pageY,
  12533. x = touch2.pageX - touch1.pageX;
  12534. return Math.atan2(y, x) * 180 / Math.PI;
  12535. },
  12536. /**
  12537. * angle to direction define
  12538. * @param {Touch} touch1
  12539. * @param {Touch} touch2
  12540. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  12541. */
  12542. getDirection: function getDirection(touch1, touch2) {
  12543. var x = Math.abs(touch1.pageX - touch2.pageX),
  12544. y = Math.abs(touch1.pageY - touch2.pageY);
  12545. if(x >= y) {
  12546. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  12547. }
  12548. else {
  12549. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  12550. }
  12551. },
  12552. /**
  12553. * calculate the distance between two touches
  12554. * @param {Touch} touch1
  12555. * @param {Touch} touch2
  12556. * @returns {Number} distance
  12557. */
  12558. getDistance: function getDistance(touch1, touch2) {
  12559. var x = touch2.pageX - touch1.pageX,
  12560. y = touch2.pageY - touch1.pageY;
  12561. return Math.sqrt((x*x) + (y*y));
  12562. },
  12563. /**
  12564. * calculate the scale factor between two touchLists (fingers)
  12565. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  12566. * @param {Array} start
  12567. * @param {Array} end
  12568. * @returns {Number} scale
  12569. */
  12570. getScale: function getScale(start, end) {
  12571. // need two fingers...
  12572. if(start.length >= 2 && end.length >= 2) {
  12573. return this.getDistance(end[0], end[1]) /
  12574. this.getDistance(start[0], start[1]);
  12575. }
  12576. return 1;
  12577. },
  12578. /**
  12579. * calculate the rotation degrees between two touchLists (fingers)
  12580. * @param {Array} start
  12581. * @param {Array} end
  12582. * @returns {Number} rotation
  12583. */
  12584. getRotation: function getRotation(start, end) {
  12585. // need two fingers
  12586. if(start.length >= 2 && end.length >= 2) {
  12587. return this.getAngle(end[1], end[0]) -
  12588. this.getAngle(start[1], start[0]);
  12589. }
  12590. return 0;
  12591. },
  12592. /**
  12593. * boolean if the direction is vertical
  12594. * @param {String} direction
  12595. * @returns {Boolean} is_vertical
  12596. */
  12597. isVertical: function isVertical(direction) {
  12598. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  12599. },
  12600. /**
  12601. * stop browser default behavior with css props
  12602. * @param {HtmlElement} element
  12603. * @param {Object} css_props
  12604. */
  12605. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  12606. var prop,
  12607. vendors = ['webkit','khtml','moz','ms','o',''];
  12608. if(!css_props || !element.style) {
  12609. return;
  12610. }
  12611. // with css properties for modern browsers
  12612. for(var i = 0; i < vendors.length; i++) {
  12613. for(var p in css_props) {
  12614. if(css_props.hasOwnProperty(p)) {
  12615. prop = p;
  12616. // vender prefix at the property
  12617. if(vendors[i]) {
  12618. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  12619. }
  12620. // set the style
  12621. element.style[prop] = css_props[p];
  12622. }
  12623. }
  12624. }
  12625. // also the disable onselectstart
  12626. if(css_props.userSelect == 'none') {
  12627. element.onselectstart = function() {
  12628. return false;
  12629. };
  12630. }
  12631. }
  12632. };
  12633. Hammer.detection = {
  12634. // contains all registred Hammer.gestures in the correct order
  12635. gestures: [],
  12636. // data of the current Hammer.gesture detection session
  12637. current: null,
  12638. // the previous Hammer.gesture session data
  12639. // is a full clone of the previous gesture.current object
  12640. previous: null,
  12641. // when this becomes true, no gestures are fired
  12642. stopped: false,
  12643. /**
  12644. * start Hammer.gesture detection
  12645. * @param {Hammer.Instance} inst
  12646. * @param {Object} eventData
  12647. */
  12648. startDetect: function startDetect(inst, eventData) {
  12649. // already busy with a Hammer.gesture detection on an element
  12650. if(this.current) {
  12651. return;
  12652. }
  12653. this.stopped = false;
  12654. this.current = {
  12655. inst : inst, // reference to HammerInstance we're working for
  12656. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  12657. lastEvent : false, // last eventData
  12658. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  12659. };
  12660. this.detect(eventData);
  12661. },
  12662. /**
  12663. * Hammer.gesture detection
  12664. * @param {Object} eventData
  12665. * @param {Object} eventData
  12666. */
  12667. detect: function detect(eventData) {
  12668. if(!this.current || this.stopped) {
  12669. return;
  12670. }
  12671. // extend event data with calculations about scale, distance etc
  12672. eventData = this.extendEventData(eventData);
  12673. // instance options
  12674. var inst_options = this.current.inst.options;
  12675. // call Hammer.gesture handlers
  12676. for(var g=0,len=this.gestures.length; g<len; g++) {
  12677. var gesture = this.gestures[g];
  12678. // only when the instance options have enabled this gesture
  12679. if(!this.stopped && inst_options[gesture.name] !== false) {
  12680. // if a handler returns false, we stop with the detection
  12681. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  12682. this.stopDetect();
  12683. break;
  12684. }
  12685. }
  12686. }
  12687. // store as previous event event
  12688. if(this.current) {
  12689. this.current.lastEvent = eventData;
  12690. }
  12691. // endevent, but not the last touch, so dont stop
  12692. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  12693. this.stopDetect();
  12694. }
  12695. return eventData;
  12696. },
  12697. /**
  12698. * clear the Hammer.gesture vars
  12699. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  12700. * to stop other Hammer.gestures from being fired
  12701. */
  12702. stopDetect: function stopDetect() {
  12703. // clone current data to the store as the previous gesture
  12704. // used for the double tap gesture, since this is an other gesture detect session
  12705. this.previous = Hammer.utils.extend({}, this.current);
  12706. // reset the current
  12707. this.current = null;
  12708. // stopped!
  12709. this.stopped = true;
  12710. },
  12711. /**
  12712. * extend eventData for Hammer.gestures
  12713. * @param {Object} ev
  12714. * @returns {Object} ev
  12715. */
  12716. extendEventData: function extendEventData(ev) {
  12717. var startEv = this.current.startEvent;
  12718. // if the touches change, set the new touches over the startEvent touches
  12719. // this because touchevents don't have all the touches on touchstart, or the
  12720. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  12721. // but, sometimes it happens that both fingers are touching at the EXACT same time
  12722. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  12723. // extend 1 level deep to get the touchlist with the touch objects
  12724. startEv.touches = [];
  12725. for(var i=0,len=ev.touches.length; i<len; i++) {
  12726. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  12727. }
  12728. }
  12729. var delta_time = ev.timeStamp - startEv.timeStamp,
  12730. delta_x = ev.center.pageX - startEv.center.pageX,
  12731. delta_y = ev.center.pageY - startEv.center.pageY,
  12732. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  12733. Hammer.utils.extend(ev, {
  12734. deltaTime : delta_time,
  12735. deltaX : delta_x,
  12736. deltaY : delta_y,
  12737. velocityX : velocity.x,
  12738. velocityY : velocity.y,
  12739. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  12740. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  12741. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  12742. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  12743. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  12744. startEvent : startEv
  12745. });
  12746. return ev;
  12747. },
  12748. /**
  12749. * register new gesture
  12750. * @param {Object} gesture object, see gestures.js for documentation
  12751. * @returns {Array} gestures
  12752. */
  12753. register: function register(gesture) {
  12754. // add an enable gesture options if there is no given
  12755. var options = gesture.defaults || {};
  12756. if(options[gesture.name] === undefined) {
  12757. options[gesture.name] = true;
  12758. }
  12759. // extend Hammer default options with the Hammer.gesture options
  12760. Hammer.utils.extend(Hammer.defaults, options, true);
  12761. // set its index
  12762. gesture.index = gesture.index || 1000;
  12763. // add Hammer.gesture to the list
  12764. this.gestures.push(gesture);
  12765. // sort the list by index
  12766. this.gestures.sort(function(a, b) {
  12767. if (a.index < b.index) {
  12768. return -1;
  12769. }
  12770. if (a.index > b.index) {
  12771. return 1;
  12772. }
  12773. return 0;
  12774. });
  12775. return this.gestures;
  12776. }
  12777. };
  12778. Hammer.gestures = Hammer.gestures || {};
  12779. /**
  12780. * Custom gestures
  12781. * ==============================
  12782. *
  12783. * Gesture object
  12784. * --------------------
  12785. * The object structure of a gesture:
  12786. *
  12787. * { name: 'mygesture',
  12788. * index: 1337,
  12789. * defaults: {
  12790. * mygesture_option: true
  12791. * }
  12792. * handler: function(type, ev, inst) {
  12793. * // trigger gesture event
  12794. * inst.trigger(this.name, ev);
  12795. * }
  12796. * }
  12797. * @param {String} name
  12798. * this should be the name of the gesture, lowercase
  12799. * it is also being used to disable/enable the gesture per instance config.
  12800. *
  12801. * @param {Number} [index=1000]
  12802. * the index of the gesture, where it is going to be in the stack of gestures detection
  12803. * like when you build an gesture that depends on the drag gesture, it is a good
  12804. * idea to place it after the index of the drag gesture.
  12805. *
  12806. * @param {Object} [defaults={}]
  12807. * the default settings of the gesture. these are added to the instance settings,
  12808. * and can be overruled per instance. you can also add the name of the gesture,
  12809. * but this is also added by default (and set to true).
  12810. *
  12811. * @param {Function} handler
  12812. * this handles the gesture detection of your custom gesture and receives the
  12813. * following arguments:
  12814. *
  12815. * @param {Object} eventData
  12816. * event data containing the following properties:
  12817. * timeStamp {Number} time the event occurred
  12818. * target {HTMLElement} target element
  12819. * touches {Array} touches (fingers, pointers, mouse) on the screen
  12820. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  12821. * center {Object} center position of the touches. contains pageX and pageY
  12822. * deltaTime {Number} the total time of the touches in the screen
  12823. * deltaX {Number} the delta on x axis we haved moved
  12824. * deltaY {Number} the delta on y axis we haved moved
  12825. * velocityX {Number} the velocity on the x
  12826. * velocityY {Number} the velocity on y
  12827. * angle {Number} the angle we are moving
  12828. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  12829. * distance {Number} the distance we haved moved
  12830. * scale {Number} scaling of the touches, needs 2 touches
  12831. * rotation {Number} rotation of the touches, needs 2 touches *
  12832. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  12833. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  12834. * startEvent {Object} contains the same properties as above,
  12835. * but from the first touch. this is used to calculate
  12836. * distances, deltaTime, scaling etc
  12837. *
  12838. * @param {Hammer.Instance} inst
  12839. * the instance we are doing the detection for. you can get the options from
  12840. * the inst.options object and trigger the gesture event by calling inst.trigger
  12841. *
  12842. *
  12843. * Handle gestures
  12844. * --------------------
  12845. * inside the handler you can get/set Hammer.detection.current. This is the current
  12846. * detection session. It has the following properties
  12847. * @param {String} name
  12848. * contains the name of the gesture we have detected. it has not a real function,
  12849. * only to check in other gestures if something is detected.
  12850. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  12851. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  12852. *
  12853. * @readonly
  12854. * @param {Hammer.Instance} inst
  12855. * the instance we do the detection for
  12856. *
  12857. * @readonly
  12858. * @param {Object} startEvent
  12859. * contains the properties of the first gesture detection in this session.
  12860. * Used for calculations about timing, distance, etc.
  12861. *
  12862. * @readonly
  12863. * @param {Object} lastEvent
  12864. * contains all the properties of the last gesture detect in this session.
  12865. *
  12866. * after the gesture detection session has been completed (user has released the screen)
  12867. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  12868. * this is usefull for gestures like doubletap, where you need to know if the
  12869. * previous gesture was a tap
  12870. *
  12871. * options that have been set by the instance can be received by calling inst.options
  12872. *
  12873. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  12874. * The first param is the name of your gesture, the second the event argument
  12875. *
  12876. *
  12877. * Register gestures
  12878. * --------------------
  12879. * When an gesture is added to the Hammer.gestures object, it is auto registered
  12880. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  12881. * manually and pass your gesture object as a param
  12882. *
  12883. */
  12884. /**
  12885. * Hold
  12886. * Touch stays at the same place for x time
  12887. * @events hold
  12888. */
  12889. Hammer.gestures.Hold = {
  12890. name: 'hold',
  12891. index: 10,
  12892. defaults: {
  12893. hold_timeout : 500,
  12894. hold_threshold : 1
  12895. },
  12896. timer: null,
  12897. handler: function holdGesture(ev, inst) {
  12898. switch(ev.eventType) {
  12899. case Hammer.EVENT_START:
  12900. // clear any running timers
  12901. clearTimeout(this.timer);
  12902. // set the gesture so we can check in the timeout if it still is
  12903. Hammer.detection.current.name = this.name;
  12904. // set timer and if after the timeout it still is hold,
  12905. // we trigger the hold event
  12906. this.timer = setTimeout(function() {
  12907. if(Hammer.detection.current.name == 'hold') {
  12908. inst.trigger('hold', ev);
  12909. }
  12910. }, inst.options.hold_timeout);
  12911. break;
  12912. // when you move or end we clear the timer
  12913. case Hammer.EVENT_MOVE:
  12914. if(ev.distance > inst.options.hold_threshold) {
  12915. clearTimeout(this.timer);
  12916. }
  12917. break;
  12918. case Hammer.EVENT_END:
  12919. clearTimeout(this.timer);
  12920. break;
  12921. }
  12922. }
  12923. };
  12924. /**
  12925. * Tap/DoubleTap
  12926. * Quick touch at a place or double at the same place
  12927. * @events tap, doubletap
  12928. */
  12929. Hammer.gestures.Tap = {
  12930. name: 'tap',
  12931. index: 100,
  12932. defaults: {
  12933. tap_max_touchtime : 250,
  12934. tap_max_distance : 10,
  12935. tap_always : true,
  12936. doubletap_distance : 20,
  12937. doubletap_interval : 300
  12938. },
  12939. handler: function tapGesture(ev, inst) {
  12940. if(ev.eventType == Hammer.EVENT_END) {
  12941. // previous gesture, for the double tap since these are two different gesture detections
  12942. var prev = Hammer.detection.previous,
  12943. did_doubletap = false;
  12944. // when the touchtime is higher then the max touch time
  12945. // or when the moving distance is too much
  12946. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  12947. ev.distance > inst.options.tap_max_distance) {
  12948. return;
  12949. }
  12950. // check if double tap
  12951. if(prev && prev.name == 'tap' &&
  12952. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  12953. ev.distance < inst.options.doubletap_distance) {
  12954. inst.trigger('doubletap', ev);
  12955. did_doubletap = true;
  12956. }
  12957. // do a single tap
  12958. if(!did_doubletap || inst.options.tap_always) {
  12959. Hammer.detection.current.name = 'tap';
  12960. inst.trigger(Hammer.detection.current.name, ev);
  12961. }
  12962. }
  12963. }
  12964. };
  12965. /**
  12966. * Swipe
  12967. * triggers swipe events when the end velocity is above the threshold
  12968. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  12969. */
  12970. Hammer.gestures.Swipe = {
  12971. name: 'swipe',
  12972. index: 40,
  12973. defaults: {
  12974. // set 0 for unlimited, but this can conflict with transform
  12975. swipe_max_touches : 1,
  12976. swipe_velocity : 0.7
  12977. },
  12978. handler: function swipeGesture(ev, inst) {
  12979. if(ev.eventType == Hammer.EVENT_END) {
  12980. // max touches
  12981. if(inst.options.swipe_max_touches > 0 &&
  12982. ev.touches.length > inst.options.swipe_max_touches) {
  12983. return;
  12984. }
  12985. // when the distance we moved is too small we skip this gesture
  12986. // or we can be already in dragging
  12987. if(ev.velocityX > inst.options.swipe_velocity ||
  12988. ev.velocityY > inst.options.swipe_velocity) {
  12989. // trigger swipe events
  12990. inst.trigger(this.name, ev);
  12991. inst.trigger(this.name + ev.direction, ev);
  12992. }
  12993. }
  12994. }
  12995. };
  12996. /**
  12997. * Drag
  12998. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  12999. * moving left and right is a good practice. When all the drag events are blocking
  13000. * you disable scrolling on that area.
  13001. * @events drag, drapleft, dragright, dragup, dragdown
  13002. */
  13003. Hammer.gestures.Drag = {
  13004. name: 'drag',
  13005. index: 50,
  13006. defaults: {
  13007. drag_min_distance : 10,
  13008. // set 0 for unlimited, but this can conflict with transform
  13009. drag_max_touches : 1,
  13010. // prevent default browser behavior when dragging occurs
  13011. // be careful with it, it makes the element a blocking element
  13012. // when you are using the drag gesture, it is a good practice to set this true
  13013. drag_block_horizontal : false,
  13014. drag_block_vertical : false,
  13015. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  13016. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  13017. drag_lock_to_axis : false,
  13018. // drag lock only kicks in when distance > drag_lock_min_distance
  13019. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  13020. drag_lock_min_distance : 25
  13021. },
  13022. triggered: false,
  13023. handler: function dragGesture(ev, inst) {
  13024. // current gesture isnt drag, but dragged is true
  13025. // this means an other gesture is busy. now call dragend
  13026. if(Hammer.detection.current.name != this.name && this.triggered) {
  13027. inst.trigger(this.name +'end', ev);
  13028. this.triggered = false;
  13029. return;
  13030. }
  13031. // max touches
  13032. if(inst.options.drag_max_touches > 0 &&
  13033. ev.touches.length > inst.options.drag_max_touches) {
  13034. return;
  13035. }
  13036. switch(ev.eventType) {
  13037. case Hammer.EVENT_START:
  13038. this.triggered = false;
  13039. break;
  13040. case Hammer.EVENT_MOVE:
  13041. // when the distance we moved is too small we skip this gesture
  13042. // or we can be already in dragging
  13043. if(ev.distance < inst.options.drag_min_distance &&
  13044. Hammer.detection.current.name != this.name) {
  13045. return;
  13046. }
  13047. // we are dragging!
  13048. Hammer.detection.current.name = this.name;
  13049. // lock drag to axis?
  13050. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  13051. ev.drag_locked_to_axis = true;
  13052. }
  13053. var last_direction = Hammer.detection.current.lastEvent.direction;
  13054. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  13055. // keep direction on the axis that the drag gesture started on
  13056. if(Hammer.utils.isVertical(last_direction)) {
  13057. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  13058. }
  13059. else {
  13060. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  13061. }
  13062. }
  13063. // first time, trigger dragstart event
  13064. if(!this.triggered) {
  13065. inst.trigger(this.name +'start', ev);
  13066. this.triggered = true;
  13067. }
  13068. // trigger normal event
  13069. inst.trigger(this.name, ev);
  13070. // direction event, like dragdown
  13071. inst.trigger(this.name + ev.direction, ev);
  13072. // block the browser events
  13073. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  13074. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  13075. ev.preventDefault();
  13076. }
  13077. break;
  13078. case Hammer.EVENT_END:
  13079. // trigger dragend
  13080. if(this.triggered) {
  13081. inst.trigger(this.name +'end', ev);
  13082. }
  13083. this.triggered = false;
  13084. break;
  13085. }
  13086. }
  13087. };
  13088. /**
  13089. * Transform
  13090. * User want to scale or rotate with 2 fingers
  13091. * @events transform, pinch, pinchin, pinchout, rotate
  13092. */
  13093. Hammer.gestures.Transform = {
  13094. name: 'transform',
  13095. index: 45,
  13096. defaults: {
  13097. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  13098. transform_min_scale : 0.01,
  13099. // rotation in degrees
  13100. transform_min_rotation : 1,
  13101. // prevent default browser behavior when two touches are on the screen
  13102. // but it makes the element a blocking element
  13103. // when you are using the transform gesture, it is a good practice to set this true
  13104. transform_always_block : false
  13105. },
  13106. triggered: false,
  13107. handler: function transformGesture(ev, inst) {
  13108. // current gesture isnt drag, but dragged is true
  13109. // this means an other gesture is busy. now call dragend
  13110. if(Hammer.detection.current.name != this.name && this.triggered) {
  13111. inst.trigger(this.name +'end', ev);
  13112. this.triggered = false;
  13113. return;
  13114. }
  13115. // atleast multitouch
  13116. if(ev.touches.length < 2) {
  13117. return;
  13118. }
  13119. // prevent default when two fingers are on the screen
  13120. if(inst.options.transform_always_block) {
  13121. ev.preventDefault();
  13122. }
  13123. switch(ev.eventType) {
  13124. case Hammer.EVENT_START:
  13125. this.triggered = false;
  13126. break;
  13127. case Hammer.EVENT_MOVE:
  13128. var scale_threshold = Math.abs(1-ev.scale);
  13129. var rotation_threshold = Math.abs(ev.rotation);
  13130. // when the distance we moved is too small we skip this gesture
  13131. // or we can be already in dragging
  13132. if(scale_threshold < inst.options.transform_min_scale &&
  13133. rotation_threshold < inst.options.transform_min_rotation) {
  13134. return;
  13135. }
  13136. // we are transforming!
  13137. Hammer.detection.current.name = this.name;
  13138. // first time, trigger dragstart event
  13139. if(!this.triggered) {
  13140. inst.trigger(this.name +'start', ev);
  13141. this.triggered = true;
  13142. }
  13143. inst.trigger(this.name, ev); // basic transform event
  13144. // trigger rotate event
  13145. if(rotation_threshold > inst.options.transform_min_rotation) {
  13146. inst.trigger('rotate', ev);
  13147. }
  13148. // trigger pinch event
  13149. if(scale_threshold > inst.options.transform_min_scale) {
  13150. inst.trigger('pinch', ev);
  13151. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  13152. }
  13153. break;
  13154. case Hammer.EVENT_END:
  13155. // trigger dragend
  13156. if(this.triggered) {
  13157. inst.trigger(this.name +'end', ev);
  13158. }
  13159. this.triggered = false;
  13160. break;
  13161. }
  13162. }
  13163. };
  13164. /**
  13165. * Touch
  13166. * Called as first, tells the user has touched the screen
  13167. * @events touch
  13168. */
  13169. Hammer.gestures.Touch = {
  13170. name: 'touch',
  13171. index: -Infinity,
  13172. defaults: {
  13173. // call preventDefault at touchstart, and makes the element blocking by
  13174. // disabling the scrolling of the page, but it improves gestures like
  13175. // transforming and dragging.
  13176. // be careful with using this, it can be very annoying for users to be stuck
  13177. // on the page
  13178. prevent_default: false,
  13179. // disable mouse events, so only touch (or pen!) input triggers events
  13180. prevent_mouseevents: false
  13181. },
  13182. handler: function touchGesture(ev, inst) {
  13183. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  13184. ev.stopDetect();
  13185. return;
  13186. }
  13187. if(inst.options.prevent_default) {
  13188. ev.preventDefault();
  13189. }
  13190. if(ev.eventType == Hammer.EVENT_START) {
  13191. inst.trigger(this.name, ev);
  13192. }
  13193. }
  13194. };
  13195. /**
  13196. * Release
  13197. * Called as last, tells the user has released the screen
  13198. * @events release
  13199. */
  13200. Hammer.gestures.Release = {
  13201. name: 'release',
  13202. index: Infinity,
  13203. handler: function releaseGesture(ev, inst) {
  13204. if(ev.eventType == Hammer.EVENT_END) {
  13205. inst.trigger(this.name, ev);
  13206. }
  13207. }
  13208. };
  13209. // node export
  13210. if(typeof module === 'object' && typeof module.exports === 'object'){
  13211. module.exports = Hammer;
  13212. }
  13213. // just window export
  13214. else {
  13215. window.Hammer = Hammer;
  13216. // requireJS module definition
  13217. if(typeof window.define === 'function' && window.define.amd) {
  13218. window.define('hammer', [], function() {
  13219. return Hammer;
  13220. });
  13221. }
  13222. }
  13223. })(this);
  13224. },{}],3:[function(require,module,exports){
  13225. //! moment.js
  13226. //! version : 2.5.0
  13227. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  13228. //! license : MIT
  13229. //! momentjs.com
  13230. (function (undefined) {
  13231. /************************************
  13232. Constants
  13233. ************************************/
  13234. var moment,
  13235. VERSION = "2.5.0",
  13236. global = this,
  13237. round = Math.round,
  13238. i,
  13239. YEAR = 0,
  13240. MONTH = 1,
  13241. DATE = 2,
  13242. HOUR = 3,
  13243. MINUTE = 4,
  13244. SECOND = 5,
  13245. MILLISECOND = 6,
  13246. // internal storage for language config files
  13247. languages = {},
  13248. // check for nodeJS
  13249. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  13250. // ASP.NET json date format regex
  13251. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  13252. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  13253. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  13254. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  13255. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  13256. // format tokens
  13257. 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,
  13258. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  13259. // parsing token regexes
  13260. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  13261. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  13262. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  13263. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  13264. parseTokenDigits = /\d+/, // nonzero number of digits
  13265. 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.
  13266. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  13267. parseTokenT = /T/i, // T (ISO separator)
  13268. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  13269. //strict parsing regexes
  13270. parseTokenOneDigit = /\d/, // 0 - 9
  13271. parseTokenTwoDigits = /\d\d/, // 00 - 99
  13272. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  13273. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  13274. parseTokenSixDigits = /[+\-]?\d{6}/, // -999,999 - 999,999
  13275. // iso 8601 regex
  13276. // 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)
  13277. isoRegex = /^\s*\d{4}-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
  13278. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  13279. isoDates = [
  13280. 'YYYY-MM-DD',
  13281. 'GGGG-[W]WW',
  13282. 'GGGG-[W]WW-E',
  13283. 'YYYY-DDD'
  13284. ],
  13285. // iso time formats and regexes
  13286. isoTimes = [
  13287. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  13288. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  13289. ['HH:mm', /(T| )\d\d:\d\d/],
  13290. ['HH', /(T| )\d\d/]
  13291. ],
  13292. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  13293. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  13294. // getter and setter names
  13295. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  13296. unitMillisecondFactors = {
  13297. 'Milliseconds' : 1,
  13298. 'Seconds' : 1e3,
  13299. 'Minutes' : 6e4,
  13300. 'Hours' : 36e5,
  13301. 'Days' : 864e5,
  13302. 'Months' : 2592e6,
  13303. 'Years' : 31536e6
  13304. },
  13305. unitAliases = {
  13306. ms : 'millisecond',
  13307. s : 'second',
  13308. m : 'minute',
  13309. h : 'hour',
  13310. d : 'day',
  13311. D : 'date',
  13312. w : 'week',
  13313. W : 'isoWeek',
  13314. M : 'month',
  13315. y : 'year',
  13316. DDD : 'dayOfYear',
  13317. e : 'weekday',
  13318. E : 'isoWeekday',
  13319. gg: 'weekYear',
  13320. GG: 'isoWeekYear'
  13321. },
  13322. camelFunctions = {
  13323. dayofyear : 'dayOfYear',
  13324. isoweekday : 'isoWeekday',
  13325. isoweek : 'isoWeek',
  13326. weekyear : 'weekYear',
  13327. isoweekyear : 'isoWeekYear'
  13328. },
  13329. // format function strings
  13330. formatFunctions = {},
  13331. // tokens to ordinalize and pad
  13332. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  13333. paddedTokens = 'M D H h m s w W'.split(' '),
  13334. formatTokenFunctions = {
  13335. M : function () {
  13336. return this.month() + 1;
  13337. },
  13338. MMM : function (format) {
  13339. return this.lang().monthsShort(this, format);
  13340. },
  13341. MMMM : function (format) {
  13342. return this.lang().months(this, format);
  13343. },
  13344. D : function () {
  13345. return this.date();
  13346. },
  13347. DDD : function () {
  13348. return this.dayOfYear();
  13349. },
  13350. d : function () {
  13351. return this.day();
  13352. },
  13353. dd : function (format) {
  13354. return this.lang().weekdaysMin(this, format);
  13355. },
  13356. ddd : function (format) {
  13357. return this.lang().weekdaysShort(this, format);
  13358. },
  13359. dddd : function (format) {
  13360. return this.lang().weekdays(this, format);
  13361. },
  13362. w : function () {
  13363. return this.week();
  13364. },
  13365. W : function () {
  13366. return this.isoWeek();
  13367. },
  13368. YY : function () {
  13369. return leftZeroFill(this.year() % 100, 2);
  13370. },
  13371. YYYY : function () {
  13372. return leftZeroFill(this.year(), 4);
  13373. },
  13374. YYYYY : function () {
  13375. return leftZeroFill(this.year(), 5);
  13376. },
  13377. YYYYYY : function () {
  13378. var y = this.year(), sign = y >= 0 ? '+' : '-';
  13379. return sign + leftZeroFill(Math.abs(y), 6);
  13380. },
  13381. gg : function () {
  13382. return leftZeroFill(this.weekYear() % 100, 2);
  13383. },
  13384. gggg : function () {
  13385. return this.weekYear();
  13386. },
  13387. ggggg : function () {
  13388. return leftZeroFill(this.weekYear(), 5);
  13389. },
  13390. GG : function () {
  13391. return leftZeroFill(this.isoWeekYear() % 100, 2);
  13392. },
  13393. GGGG : function () {
  13394. return this.isoWeekYear();
  13395. },
  13396. GGGGG : function () {
  13397. return leftZeroFill(this.isoWeekYear(), 5);
  13398. },
  13399. e : function () {
  13400. return this.weekday();
  13401. },
  13402. E : function () {
  13403. return this.isoWeekday();
  13404. },
  13405. a : function () {
  13406. return this.lang().meridiem(this.hours(), this.minutes(), true);
  13407. },
  13408. A : function () {
  13409. return this.lang().meridiem(this.hours(), this.minutes(), false);
  13410. },
  13411. H : function () {
  13412. return this.hours();
  13413. },
  13414. h : function () {
  13415. return this.hours() % 12 || 12;
  13416. },
  13417. m : function () {
  13418. return this.minutes();
  13419. },
  13420. s : function () {
  13421. return this.seconds();
  13422. },
  13423. S : function () {
  13424. return toInt(this.milliseconds() / 100);
  13425. },
  13426. SS : function () {
  13427. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  13428. },
  13429. SSS : function () {
  13430. return leftZeroFill(this.milliseconds(), 3);
  13431. },
  13432. SSSS : function () {
  13433. return leftZeroFill(this.milliseconds(), 3);
  13434. },
  13435. Z : function () {
  13436. var a = -this.zone(),
  13437. b = "+";
  13438. if (a < 0) {
  13439. a = -a;
  13440. b = "-";
  13441. }
  13442. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  13443. },
  13444. ZZ : function () {
  13445. var a = -this.zone(),
  13446. b = "+";
  13447. if (a < 0) {
  13448. a = -a;
  13449. b = "-";
  13450. }
  13451. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  13452. },
  13453. z : function () {
  13454. return this.zoneAbbr();
  13455. },
  13456. zz : function () {
  13457. return this.zoneName();
  13458. },
  13459. X : function () {
  13460. return this.unix();
  13461. },
  13462. Q : function () {
  13463. return this.quarter();
  13464. }
  13465. },
  13466. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  13467. function padToken(func, count) {
  13468. return function (a) {
  13469. return leftZeroFill(func.call(this, a), count);
  13470. };
  13471. }
  13472. function ordinalizeToken(func, period) {
  13473. return function (a) {
  13474. return this.lang().ordinal(func.call(this, a), period);
  13475. };
  13476. }
  13477. while (ordinalizeTokens.length) {
  13478. i = ordinalizeTokens.pop();
  13479. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  13480. }
  13481. while (paddedTokens.length) {
  13482. i = paddedTokens.pop();
  13483. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  13484. }
  13485. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  13486. /************************************
  13487. Constructors
  13488. ************************************/
  13489. function Language() {
  13490. }
  13491. // Moment prototype object
  13492. function Moment(config) {
  13493. checkOverflow(config);
  13494. extend(this, config);
  13495. }
  13496. // Duration Constructor
  13497. function Duration(duration) {
  13498. var normalizedInput = normalizeObjectUnits(duration),
  13499. years = normalizedInput.year || 0,
  13500. months = normalizedInput.month || 0,
  13501. weeks = normalizedInput.week || 0,
  13502. days = normalizedInput.day || 0,
  13503. hours = normalizedInput.hour || 0,
  13504. minutes = normalizedInput.minute || 0,
  13505. seconds = normalizedInput.second || 0,
  13506. milliseconds = normalizedInput.millisecond || 0;
  13507. // representation for dateAddRemove
  13508. this._milliseconds = +milliseconds +
  13509. seconds * 1e3 + // 1000
  13510. minutes * 6e4 + // 1000 * 60
  13511. hours * 36e5; // 1000 * 60 * 60
  13512. // Because of dateAddRemove treats 24 hours as different from a
  13513. // day when working around DST, we need to store them separately
  13514. this._days = +days +
  13515. weeks * 7;
  13516. // It is impossible translate months into days without knowing
  13517. // which months you are are talking about, so we have to store
  13518. // it separately.
  13519. this._months = +months +
  13520. years * 12;
  13521. this._data = {};
  13522. this._bubble();
  13523. }
  13524. /************************************
  13525. Helpers
  13526. ************************************/
  13527. function extend(a, b) {
  13528. for (var i in b) {
  13529. if (b.hasOwnProperty(i)) {
  13530. a[i] = b[i];
  13531. }
  13532. }
  13533. if (b.hasOwnProperty("toString")) {
  13534. a.toString = b.toString;
  13535. }
  13536. if (b.hasOwnProperty("valueOf")) {
  13537. a.valueOf = b.valueOf;
  13538. }
  13539. return a;
  13540. }
  13541. function absRound(number) {
  13542. if (number < 0) {
  13543. return Math.ceil(number);
  13544. } else {
  13545. return Math.floor(number);
  13546. }
  13547. }
  13548. // left zero fill a number
  13549. // see http://jsperf.com/left-zero-filling for performance comparison
  13550. function leftZeroFill(number, targetLength, forceSign) {
  13551. var output = Math.abs(number) + '',
  13552. sign = number >= 0;
  13553. while (output.length < targetLength) {
  13554. output = '0' + output;
  13555. }
  13556. return (sign ? (forceSign ? '+' : '') : '-') + output;
  13557. }
  13558. // helper function for _.addTime and _.subtractTime
  13559. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  13560. var milliseconds = duration._milliseconds,
  13561. days = duration._days,
  13562. months = duration._months,
  13563. minutes,
  13564. hours;
  13565. if (milliseconds) {
  13566. mom._d.setTime(+mom._d + milliseconds * isAdding);
  13567. }
  13568. // store the minutes and hours so we can restore them
  13569. if (days || months) {
  13570. minutes = mom.minute();
  13571. hours = mom.hour();
  13572. }
  13573. if (days) {
  13574. mom.date(mom.date() + days * isAdding);
  13575. }
  13576. if (months) {
  13577. mom.month(mom.month() + months * isAdding);
  13578. }
  13579. if (milliseconds && !ignoreUpdateOffset) {
  13580. moment.updateOffset(mom);
  13581. }
  13582. // restore the minutes and hours after possibly changing dst
  13583. if (days || months) {
  13584. mom.minute(minutes);
  13585. mom.hour(hours);
  13586. }
  13587. }
  13588. // check if is an array
  13589. function isArray(input) {
  13590. return Object.prototype.toString.call(input) === '[object Array]';
  13591. }
  13592. function isDate(input) {
  13593. return Object.prototype.toString.call(input) === '[object Date]' ||
  13594. input instanceof Date;
  13595. }
  13596. // compare two arrays, return the number of differences
  13597. function compareArrays(array1, array2, dontConvert) {
  13598. var len = Math.min(array1.length, array2.length),
  13599. lengthDiff = Math.abs(array1.length - array2.length),
  13600. diffs = 0,
  13601. i;
  13602. for (i = 0; i < len; i++) {
  13603. if ((dontConvert && array1[i] !== array2[i]) ||
  13604. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  13605. diffs++;
  13606. }
  13607. }
  13608. return diffs + lengthDiff;
  13609. }
  13610. function normalizeUnits(units) {
  13611. if (units) {
  13612. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  13613. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  13614. }
  13615. return units;
  13616. }
  13617. function normalizeObjectUnits(inputObject) {
  13618. var normalizedInput = {},
  13619. normalizedProp,
  13620. prop;
  13621. for (prop in inputObject) {
  13622. if (inputObject.hasOwnProperty(prop)) {
  13623. normalizedProp = normalizeUnits(prop);
  13624. if (normalizedProp) {
  13625. normalizedInput[normalizedProp] = inputObject[prop];
  13626. }
  13627. }
  13628. }
  13629. return normalizedInput;
  13630. }
  13631. function makeList(field) {
  13632. var count, setter;
  13633. if (field.indexOf('week') === 0) {
  13634. count = 7;
  13635. setter = 'day';
  13636. }
  13637. else if (field.indexOf('month') === 0) {
  13638. count = 12;
  13639. setter = 'month';
  13640. }
  13641. else {
  13642. return;
  13643. }
  13644. moment[field] = function (format, index) {
  13645. var i, getter,
  13646. method = moment.fn._lang[field],
  13647. results = [];
  13648. if (typeof format === 'number') {
  13649. index = format;
  13650. format = undefined;
  13651. }
  13652. getter = function (i) {
  13653. var m = moment().utc().set(setter, i);
  13654. return method.call(moment.fn._lang, m, format || '');
  13655. };
  13656. if (index != null) {
  13657. return getter(index);
  13658. }
  13659. else {
  13660. for (i = 0; i < count; i++) {
  13661. results.push(getter(i));
  13662. }
  13663. return results;
  13664. }
  13665. };
  13666. }
  13667. function toInt(argumentForCoercion) {
  13668. var coercedNumber = +argumentForCoercion,
  13669. value = 0;
  13670. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  13671. if (coercedNumber >= 0) {
  13672. value = Math.floor(coercedNumber);
  13673. } else {
  13674. value = Math.ceil(coercedNumber);
  13675. }
  13676. }
  13677. return value;
  13678. }
  13679. function daysInMonth(year, month) {
  13680. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  13681. }
  13682. function daysInYear(year) {
  13683. return isLeapYear(year) ? 366 : 365;
  13684. }
  13685. function isLeapYear(year) {
  13686. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  13687. }
  13688. function checkOverflow(m) {
  13689. var overflow;
  13690. if (m._a && m._pf.overflow === -2) {
  13691. overflow =
  13692. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  13693. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  13694. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  13695. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  13696. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  13697. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  13698. -1;
  13699. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  13700. overflow = DATE;
  13701. }
  13702. m._pf.overflow = overflow;
  13703. }
  13704. }
  13705. function initializeParsingFlags(config) {
  13706. config._pf = {
  13707. empty : false,
  13708. unusedTokens : [],
  13709. unusedInput : [],
  13710. overflow : -2,
  13711. charsLeftOver : 0,
  13712. nullInput : false,
  13713. invalidMonth : null,
  13714. invalidFormat : false,
  13715. userInvalidated : false,
  13716. iso: false
  13717. };
  13718. }
  13719. function isValid(m) {
  13720. if (m._isValid == null) {
  13721. m._isValid = !isNaN(m._d.getTime()) &&
  13722. m._pf.overflow < 0 &&
  13723. !m._pf.empty &&
  13724. !m._pf.invalidMonth &&
  13725. !m._pf.nullInput &&
  13726. !m._pf.invalidFormat &&
  13727. !m._pf.userInvalidated;
  13728. if (m._strict) {
  13729. m._isValid = m._isValid &&
  13730. m._pf.charsLeftOver === 0 &&
  13731. m._pf.unusedTokens.length === 0;
  13732. }
  13733. }
  13734. return m._isValid;
  13735. }
  13736. function normalizeLanguage(key) {
  13737. return key ? key.toLowerCase().replace('_', '-') : key;
  13738. }
  13739. // Return a moment from input, that is local/utc/zone equivalent to model.
  13740. function makeAs(input, model) {
  13741. return model._isUTC ? moment(input).zone(model._offset || 0) :
  13742. moment(input).local();
  13743. }
  13744. /************************************
  13745. Languages
  13746. ************************************/
  13747. extend(Language.prototype, {
  13748. set : function (config) {
  13749. var prop, i;
  13750. for (i in config) {
  13751. prop = config[i];
  13752. if (typeof prop === 'function') {
  13753. this[i] = prop;
  13754. } else {
  13755. this['_' + i] = prop;
  13756. }
  13757. }
  13758. },
  13759. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  13760. months : function (m) {
  13761. return this._months[m.month()];
  13762. },
  13763. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  13764. monthsShort : function (m) {
  13765. return this._monthsShort[m.month()];
  13766. },
  13767. monthsParse : function (monthName) {
  13768. var i, mom, regex;
  13769. if (!this._monthsParse) {
  13770. this._monthsParse = [];
  13771. }
  13772. for (i = 0; i < 12; i++) {
  13773. // make the regex if we don't have it already
  13774. if (!this._monthsParse[i]) {
  13775. mom = moment.utc([2000, i]);
  13776. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  13777. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  13778. }
  13779. // test the regex
  13780. if (this._monthsParse[i].test(monthName)) {
  13781. return i;
  13782. }
  13783. }
  13784. },
  13785. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  13786. weekdays : function (m) {
  13787. return this._weekdays[m.day()];
  13788. },
  13789. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  13790. weekdaysShort : function (m) {
  13791. return this._weekdaysShort[m.day()];
  13792. },
  13793. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  13794. weekdaysMin : function (m) {
  13795. return this._weekdaysMin[m.day()];
  13796. },
  13797. weekdaysParse : function (weekdayName) {
  13798. var i, mom, regex;
  13799. if (!this._weekdaysParse) {
  13800. this._weekdaysParse = [];
  13801. }
  13802. for (i = 0; i < 7; i++) {
  13803. // make the regex if we don't have it already
  13804. if (!this._weekdaysParse[i]) {
  13805. mom = moment([2000, 1]).day(i);
  13806. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  13807. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  13808. }
  13809. // test the regex
  13810. if (this._weekdaysParse[i].test(weekdayName)) {
  13811. return i;
  13812. }
  13813. }
  13814. },
  13815. _longDateFormat : {
  13816. LT : "h:mm A",
  13817. L : "MM/DD/YYYY",
  13818. LL : "MMMM D YYYY",
  13819. LLL : "MMMM D YYYY LT",
  13820. LLLL : "dddd, MMMM D YYYY LT"
  13821. },
  13822. longDateFormat : function (key) {
  13823. var output = this._longDateFormat[key];
  13824. if (!output && this._longDateFormat[key.toUpperCase()]) {
  13825. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  13826. return val.slice(1);
  13827. });
  13828. this._longDateFormat[key] = output;
  13829. }
  13830. return output;
  13831. },
  13832. isPM : function (input) {
  13833. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  13834. // Using charAt should be more compatible.
  13835. return ((input + '').toLowerCase().charAt(0) === 'p');
  13836. },
  13837. _meridiemParse : /[ap]\.?m?\.?/i,
  13838. meridiem : function (hours, minutes, isLower) {
  13839. if (hours > 11) {
  13840. return isLower ? 'pm' : 'PM';
  13841. } else {
  13842. return isLower ? 'am' : 'AM';
  13843. }
  13844. },
  13845. _calendar : {
  13846. sameDay : '[Today at] LT',
  13847. nextDay : '[Tomorrow at] LT',
  13848. nextWeek : 'dddd [at] LT',
  13849. lastDay : '[Yesterday at] LT',
  13850. lastWeek : '[Last] dddd [at] LT',
  13851. sameElse : 'L'
  13852. },
  13853. calendar : function (key, mom) {
  13854. var output = this._calendar[key];
  13855. return typeof output === 'function' ? output.apply(mom) : output;
  13856. },
  13857. _relativeTime : {
  13858. future : "in %s",
  13859. past : "%s ago",
  13860. s : "a few seconds",
  13861. m : "a minute",
  13862. mm : "%d minutes",
  13863. h : "an hour",
  13864. hh : "%d hours",
  13865. d : "a day",
  13866. dd : "%d days",
  13867. M : "a month",
  13868. MM : "%d months",
  13869. y : "a year",
  13870. yy : "%d years"
  13871. },
  13872. relativeTime : function (number, withoutSuffix, string, isFuture) {
  13873. var output = this._relativeTime[string];
  13874. return (typeof output === 'function') ?
  13875. output(number, withoutSuffix, string, isFuture) :
  13876. output.replace(/%d/i, number);
  13877. },
  13878. pastFuture : function (diff, output) {
  13879. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  13880. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  13881. },
  13882. ordinal : function (number) {
  13883. return this._ordinal.replace("%d", number);
  13884. },
  13885. _ordinal : "%d",
  13886. preparse : function (string) {
  13887. return string;
  13888. },
  13889. postformat : function (string) {
  13890. return string;
  13891. },
  13892. week : function (mom) {
  13893. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  13894. },
  13895. _week : {
  13896. dow : 0, // Sunday is the first day of the week.
  13897. doy : 6 // The week that contains Jan 1st is the first week of the year.
  13898. },
  13899. _invalidDate: 'Invalid date',
  13900. invalidDate: function () {
  13901. return this._invalidDate;
  13902. }
  13903. });
  13904. // Loads a language definition into the `languages` cache. The function
  13905. // takes a key and optionally values. If not in the browser and no values
  13906. // are provided, it will load the language file module. As a convenience,
  13907. // this function also returns the language values.
  13908. function loadLang(key, values) {
  13909. values.abbr = key;
  13910. if (!languages[key]) {
  13911. languages[key] = new Language();
  13912. }
  13913. languages[key].set(values);
  13914. return languages[key];
  13915. }
  13916. // Remove a language from the `languages` cache. Mostly useful in tests.
  13917. function unloadLang(key) {
  13918. delete languages[key];
  13919. }
  13920. // Determines which language definition to use and returns it.
  13921. //
  13922. // With no parameters, it will return the global language. If you
  13923. // pass in a language key, such as 'en', it will return the
  13924. // definition for 'en', so long as 'en' has already been loaded using
  13925. // moment.lang.
  13926. function getLangDefinition(key) {
  13927. var i = 0, j, lang, next, split,
  13928. get = function (k) {
  13929. if (!languages[k] && hasModule) {
  13930. try {
  13931. require('./lang/' + k);
  13932. } catch (e) { }
  13933. }
  13934. return languages[k];
  13935. };
  13936. if (!key) {
  13937. return moment.fn._lang;
  13938. }
  13939. if (!isArray(key)) {
  13940. //short-circuit everything else
  13941. lang = get(key);
  13942. if (lang) {
  13943. return lang;
  13944. }
  13945. key = [key];
  13946. }
  13947. //pick the language from the array
  13948. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  13949. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  13950. while (i < key.length) {
  13951. split = normalizeLanguage(key[i]).split('-');
  13952. j = split.length;
  13953. next = normalizeLanguage(key[i + 1]);
  13954. next = next ? next.split('-') : null;
  13955. while (j > 0) {
  13956. lang = get(split.slice(0, j).join('-'));
  13957. if (lang) {
  13958. return lang;
  13959. }
  13960. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  13961. //the next array item is better than a shallower substring of this one
  13962. break;
  13963. }
  13964. j--;
  13965. }
  13966. i++;
  13967. }
  13968. return moment.fn._lang;
  13969. }
  13970. /************************************
  13971. Formatting
  13972. ************************************/
  13973. function removeFormattingTokens(input) {
  13974. if (input.match(/\[[\s\S]/)) {
  13975. return input.replace(/^\[|\]$/g, "");
  13976. }
  13977. return input.replace(/\\/g, "");
  13978. }
  13979. function makeFormatFunction(format) {
  13980. var array = format.match(formattingTokens), i, length;
  13981. for (i = 0, length = array.length; i < length; i++) {
  13982. if (formatTokenFunctions[array[i]]) {
  13983. array[i] = formatTokenFunctions[array[i]];
  13984. } else {
  13985. array[i] = removeFormattingTokens(array[i]);
  13986. }
  13987. }
  13988. return function (mom) {
  13989. var output = "";
  13990. for (i = 0; i < length; i++) {
  13991. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  13992. }
  13993. return output;
  13994. };
  13995. }
  13996. // format date using native date object
  13997. function formatMoment(m, format) {
  13998. if (!m.isValid()) {
  13999. return m.lang().invalidDate();
  14000. }
  14001. format = expandFormat(format, m.lang());
  14002. if (!formatFunctions[format]) {
  14003. formatFunctions[format] = makeFormatFunction(format);
  14004. }
  14005. return formatFunctions[format](m);
  14006. }
  14007. function expandFormat(format, lang) {
  14008. var i = 5;
  14009. function replaceLongDateFormatTokens(input) {
  14010. return lang.longDateFormat(input) || input;
  14011. }
  14012. localFormattingTokens.lastIndex = 0;
  14013. while (i >= 0 && localFormattingTokens.test(format)) {
  14014. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  14015. localFormattingTokens.lastIndex = 0;
  14016. i -= 1;
  14017. }
  14018. return format;
  14019. }
  14020. /************************************
  14021. Parsing
  14022. ************************************/
  14023. // get the regex to find the next token
  14024. function getParseRegexForToken(token, config) {
  14025. var a, strict = config._strict;
  14026. switch (token) {
  14027. case 'DDDD':
  14028. return parseTokenThreeDigits;
  14029. case 'YYYY':
  14030. case 'GGGG':
  14031. case 'gggg':
  14032. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  14033. case 'YYYYYY':
  14034. case 'YYYYY':
  14035. case 'GGGGG':
  14036. case 'ggggg':
  14037. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  14038. case 'S':
  14039. if (strict) { return parseTokenOneDigit; }
  14040. /* falls through */
  14041. case 'SS':
  14042. if (strict) { return parseTokenTwoDigits; }
  14043. /* falls through */
  14044. case 'SSS':
  14045. case 'DDD':
  14046. return strict ? parseTokenThreeDigits : parseTokenOneToThreeDigits;
  14047. case 'MMM':
  14048. case 'MMMM':
  14049. case 'dd':
  14050. case 'ddd':
  14051. case 'dddd':
  14052. return parseTokenWord;
  14053. case 'a':
  14054. case 'A':
  14055. return getLangDefinition(config._l)._meridiemParse;
  14056. case 'X':
  14057. return parseTokenTimestampMs;
  14058. case 'Z':
  14059. case 'ZZ':
  14060. return parseTokenTimezone;
  14061. case 'T':
  14062. return parseTokenT;
  14063. case 'SSSS':
  14064. return parseTokenDigits;
  14065. case 'MM':
  14066. case 'DD':
  14067. case 'YY':
  14068. case 'GG':
  14069. case 'gg':
  14070. case 'HH':
  14071. case 'hh':
  14072. case 'mm':
  14073. case 'ss':
  14074. case 'ww':
  14075. case 'WW':
  14076. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  14077. case 'M':
  14078. case 'D':
  14079. case 'd':
  14080. case 'H':
  14081. case 'h':
  14082. case 'm':
  14083. case 's':
  14084. case 'w':
  14085. case 'W':
  14086. case 'e':
  14087. case 'E':
  14088. return strict ? parseTokenOneDigit : parseTokenOneOrTwoDigits;
  14089. default :
  14090. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  14091. return a;
  14092. }
  14093. }
  14094. function timezoneMinutesFromString(string) {
  14095. string = string || "";
  14096. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  14097. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  14098. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  14099. minutes = +(parts[1] * 60) + toInt(parts[2]);
  14100. return parts[0] === '+' ? -minutes : minutes;
  14101. }
  14102. // function to convert string input to date
  14103. function addTimeToArrayFromToken(token, input, config) {
  14104. var a, datePartArray = config._a;
  14105. switch (token) {
  14106. // MONTH
  14107. case 'M' : // fall through to MM
  14108. case 'MM' :
  14109. if (input != null) {
  14110. datePartArray[MONTH] = toInt(input) - 1;
  14111. }
  14112. break;
  14113. case 'MMM' : // fall through to MMMM
  14114. case 'MMMM' :
  14115. a = getLangDefinition(config._l).monthsParse(input);
  14116. // if we didn't find a month name, mark the date as invalid.
  14117. if (a != null) {
  14118. datePartArray[MONTH] = a;
  14119. } else {
  14120. config._pf.invalidMonth = input;
  14121. }
  14122. break;
  14123. // DAY OF MONTH
  14124. case 'D' : // fall through to DD
  14125. case 'DD' :
  14126. if (input != null) {
  14127. datePartArray[DATE] = toInt(input);
  14128. }
  14129. break;
  14130. // DAY OF YEAR
  14131. case 'DDD' : // fall through to DDDD
  14132. case 'DDDD' :
  14133. if (input != null) {
  14134. config._dayOfYear = toInt(input);
  14135. }
  14136. break;
  14137. // YEAR
  14138. case 'YY' :
  14139. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  14140. break;
  14141. case 'YYYY' :
  14142. case 'YYYYY' :
  14143. case 'YYYYYY' :
  14144. datePartArray[YEAR] = toInt(input);
  14145. break;
  14146. // AM / PM
  14147. case 'a' : // fall through to A
  14148. case 'A' :
  14149. config._isPm = getLangDefinition(config._l).isPM(input);
  14150. break;
  14151. // 24 HOUR
  14152. case 'H' : // fall through to hh
  14153. case 'HH' : // fall through to hh
  14154. case 'h' : // fall through to hh
  14155. case 'hh' :
  14156. datePartArray[HOUR] = toInt(input);
  14157. break;
  14158. // MINUTE
  14159. case 'm' : // fall through to mm
  14160. case 'mm' :
  14161. datePartArray[MINUTE] = toInt(input);
  14162. break;
  14163. // SECOND
  14164. case 's' : // fall through to ss
  14165. case 'ss' :
  14166. datePartArray[SECOND] = toInt(input);
  14167. break;
  14168. // MILLISECOND
  14169. case 'S' :
  14170. case 'SS' :
  14171. case 'SSS' :
  14172. case 'SSSS' :
  14173. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  14174. break;
  14175. // UNIX TIMESTAMP WITH MS
  14176. case 'X':
  14177. config._d = new Date(parseFloat(input) * 1000);
  14178. break;
  14179. // TIMEZONE
  14180. case 'Z' : // fall through to ZZ
  14181. case 'ZZ' :
  14182. config._useUTC = true;
  14183. config._tzm = timezoneMinutesFromString(input);
  14184. break;
  14185. case 'w':
  14186. case 'ww':
  14187. case 'W':
  14188. case 'WW':
  14189. case 'd':
  14190. case 'dd':
  14191. case 'ddd':
  14192. case 'dddd':
  14193. case 'e':
  14194. case 'E':
  14195. token = token.substr(0, 1);
  14196. /* falls through */
  14197. case 'gg':
  14198. case 'gggg':
  14199. case 'GG':
  14200. case 'GGGG':
  14201. case 'GGGGG':
  14202. token = token.substr(0, 2);
  14203. if (input) {
  14204. config._w = config._w || {};
  14205. config._w[token] = input;
  14206. }
  14207. break;
  14208. }
  14209. }
  14210. // convert an array to a date.
  14211. // the array should mirror the parameters below
  14212. // note: all values past the year are optional and will default to the lowest possible value.
  14213. // [year, month, day , hour, minute, second, millisecond]
  14214. function dateFromConfig(config) {
  14215. var i, date, input = [], currentDate,
  14216. yearToUse, fixYear, w, temp, lang, weekday, week;
  14217. if (config._d) {
  14218. return;
  14219. }
  14220. currentDate = currentDateArray(config);
  14221. //compute day of the year from weeks and weekdays
  14222. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  14223. fixYear = function (val) {
  14224. var int_val = parseInt(val, 10);
  14225. return val ?
  14226. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  14227. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  14228. };
  14229. w = config._w;
  14230. if (w.GG != null || w.W != null || w.E != null) {
  14231. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  14232. }
  14233. else {
  14234. lang = getLangDefinition(config._l);
  14235. weekday = w.d != null ? parseWeekday(w.d, lang) :
  14236. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  14237. week = parseInt(w.w, 10) || 1;
  14238. //if we're parsing 'd', then the low day numbers may be next week
  14239. if (w.d != null && weekday < lang._week.dow) {
  14240. week++;
  14241. }
  14242. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  14243. }
  14244. config._a[YEAR] = temp.year;
  14245. config._dayOfYear = temp.dayOfYear;
  14246. }
  14247. //if the day of the year is set, figure out what it is
  14248. if (config._dayOfYear) {
  14249. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  14250. if (config._dayOfYear > daysInYear(yearToUse)) {
  14251. config._pf._overflowDayOfYear = true;
  14252. }
  14253. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  14254. config._a[MONTH] = date.getUTCMonth();
  14255. config._a[DATE] = date.getUTCDate();
  14256. }
  14257. // Default to current date.
  14258. // * if no year, month, day of month are given, default to today
  14259. // * if day of month is given, default month and year
  14260. // * if month is given, default only year
  14261. // * if year is given, don't default anything
  14262. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  14263. config._a[i] = input[i] = currentDate[i];
  14264. }
  14265. // Zero out whatever was not defaulted, including time
  14266. for (; i < 7; i++) {
  14267. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  14268. }
  14269. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  14270. input[HOUR] += toInt((config._tzm || 0) / 60);
  14271. input[MINUTE] += toInt((config._tzm || 0) % 60);
  14272. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  14273. }
  14274. function dateFromObject(config) {
  14275. var normalizedInput;
  14276. if (config._d) {
  14277. return;
  14278. }
  14279. normalizedInput = normalizeObjectUnits(config._i);
  14280. config._a = [
  14281. normalizedInput.year,
  14282. normalizedInput.month,
  14283. normalizedInput.day,
  14284. normalizedInput.hour,
  14285. normalizedInput.minute,
  14286. normalizedInput.second,
  14287. normalizedInput.millisecond
  14288. ];
  14289. dateFromConfig(config);
  14290. }
  14291. function currentDateArray(config) {
  14292. var now = new Date();
  14293. if (config._useUTC) {
  14294. return [
  14295. now.getUTCFullYear(),
  14296. now.getUTCMonth(),
  14297. now.getUTCDate()
  14298. ];
  14299. } else {
  14300. return [now.getFullYear(), now.getMonth(), now.getDate()];
  14301. }
  14302. }
  14303. // date from string and format string
  14304. function makeDateFromStringAndFormat(config) {
  14305. config._a = [];
  14306. config._pf.empty = true;
  14307. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  14308. var lang = getLangDefinition(config._l),
  14309. string = '' + config._i,
  14310. i, parsedInput, tokens, token, skipped,
  14311. stringLength = string.length,
  14312. totalParsedInputLength = 0;
  14313. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  14314. for (i = 0; i < tokens.length; i++) {
  14315. token = tokens[i];
  14316. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  14317. if (parsedInput) {
  14318. skipped = string.substr(0, string.indexOf(parsedInput));
  14319. if (skipped.length > 0) {
  14320. config._pf.unusedInput.push(skipped);
  14321. }
  14322. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  14323. totalParsedInputLength += parsedInput.length;
  14324. }
  14325. // don't parse if it's not a known token
  14326. if (formatTokenFunctions[token]) {
  14327. if (parsedInput) {
  14328. config._pf.empty = false;
  14329. }
  14330. else {
  14331. config._pf.unusedTokens.push(token);
  14332. }
  14333. addTimeToArrayFromToken(token, parsedInput, config);
  14334. }
  14335. else if (config._strict && !parsedInput) {
  14336. config._pf.unusedTokens.push(token);
  14337. }
  14338. }
  14339. // add remaining unparsed input length to the string
  14340. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  14341. if (string.length > 0) {
  14342. config._pf.unusedInput.push(string);
  14343. }
  14344. // handle am pm
  14345. if (config._isPm && config._a[HOUR] < 12) {
  14346. config._a[HOUR] += 12;
  14347. }
  14348. // if is 12 am, change hours to 0
  14349. if (config._isPm === false && config._a[HOUR] === 12) {
  14350. config._a[HOUR] = 0;
  14351. }
  14352. dateFromConfig(config);
  14353. checkOverflow(config);
  14354. }
  14355. function unescapeFormat(s) {
  14356. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  14357. return p1 || p2 || p3 || p4;
  14358. });
  14359. }
  14360. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  14361. function regexpEscape(s) {
  14362. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  14363. }
  14364. // date from string and array of format strings
  14365. function makeDateFromStringAndArray(config) {
  14366. var tempConfig,
  14367. bestMoment,
  14368. scoreToBeat,
  14369. i,
  14370. currentScore;
  14371. if (config._f.length === 0) {
  14372. config._pf.invalidFormat = true;
  14373. config._d = new Date(NaN);
  14374. return;
  14375. }
  14376. for (i = 0; i < config._f.length; i++) {
  14377. currentScore = 0;
  14378. tempConfig = extend({}, config);
  14379. initializeParsingFlags(tempConfig);
  14380. tempConfig._f = config._f[i];
  14381. makeDateFromStringAndFormat(tempConfig);
  14382. if (!isValid(tempConfig)) {
  14383. continue;
  14384. }
  14385. // if there is any input that was not parsed add a penalty for that format
  14386. currentScore += tempConfig._pf.charsLeftOver;
  14387. //or tokens
  14388. currentScore += tempConfig._pf.unusedTokens.length * 10;
  14389. tempConfig._pf.score = currentScore;
  14390. if (scoreToBeat == null || currentScore < scoreToBeat) {
  14391. scoreToBeat = currentScore;
  14392. bestMoment = tempConfig;
  14393. }
  14394. }
  14395. extend(config, bestMoment || tempConfig);
  14396. }
  14397. // date from iso format
  14398. function makeDateFromString(config) {
  14399. var i,
  14400. string = config._i,
  14401. match = isoRegex.exec(string);
  14402. if (match) {
  14403. config._pf.iso = true;
  14404. for (i = 4; i > 0; i--) {
  14405. if (match[i]) {
  14406. // match[5] should be "T" or undefined
  14407. config._f = isoDates[i - 1] + (match[6] || " ");
  14408. break;
  14409. }
  14410. }
  14411. for (i = 0; i < 4; i++) {
  14412. if (isoTimes[i][1].exec(string)) {
  14413. config._f += isoTimes[i][0];
  14414. break;
  14415. }
  14416. }
  14417. if (string.match(parseTokenTimezone)) {
  14418. config._f += "Z";
  14419. }
  14420. makeDateFromStringAndFormat(config);
  14421. }
  14422. else {
  14423. config._d = new Date(string);
  14424. }
  14425. }
  14426. function makeDateFromInput(config) {
  14427. var input = config._i,
  14428. matched = aspNetJsonRegex.exec(input);
  14429. if (input === undefined) {
  14430. config._d = new Date();
  14431. } else if (matched) {
  14432. config._d = new Date(+matched[1]);
  14433. } else if (typeof input === 'string') {
  14434. makeDateFromString(config);
  14435. } else if (isArray(input)) {
  14436. config._a = input.slice(0);
  14437. dateFromConfig(config);
  14438. } else if (isDate(input)) {
  14439. config._d = new Date(+input);
  14440. } else if (typeof(input) === 'object') {
  14441. dateFromObject(config);
  14442. } else {
  14443. config._d = new Date(input);
  14444. }
  14445. }
  14446. function makeDate(y, m, d, h, M, s, ms) {
  14447. //can't just apply() to create a date:
  14448. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  14449. var date = new Date(y, m, d, h, M, s, ms);
  14450. //the date constructor doesn't accept years < 1970
  14451. if (y < 1970) {
  14452. date.setFullYear(y);
  14453. }
  14454. return date;
  14455. }
  14456. function makeUTCDate(y) {
  14457. var date = new Date(Date.UTC.apply(null, arguments));
  14458. if (y < 1970) {
  14459. date.setUTCFullYear(y);
  14460. }
  14461. return date;
  14462. }
  14463. function parseWeekday(input, language) {
  14464. if (typeof input === 'string') {
  14465. if (!isNaN(input)) {
  14466. input = parseInt(input, 10);
  14467. }
  14468. else {
  14469. input = language.weekdaysParse(input);
  14470. if (typeof input !== 'number') {
  14471. return null;
  14472. }
  14473. }
  14474. }
  14475. return input;
  14476. }
  14477. /************************************
  14478. Relative Time
  14479. ************************************/
  14480. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  14481. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  14482. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  14483. }
  14484. function relativeTime(milliseconds, withoutSuffix, lang) {
  14485. var seconds = round(Math.abs(milliseconds) / 1000),
  14486. minutes = round(seconds / 60),
  14487. hours = round(minutes / 60),
  14488. days = round(hours / 24),
  14489. years = round(days / 365),
  14490. args = seconds < 45 && ['s', seconds] ||
  14491. minutes === 1 && ['m'] ||
  14492. minutes < 45 && ['mm', minutes] ||
  14493. hours === 1 && ['h'] ||
  14494. hours < 22 && ['hh', hours] ||
  14495. days === 1 && ['d'] ||
  14496. days <= 25 && ['dd', days] ||
  14497. days <= 45 && ['M'] ||
  14498. days < 345 && ['MM', round(days / 30)] ||
  14499. years === 1 && ['y'] || ['yy', years];
  14500. args[2] = withoutSuffix;
  14501. args[3] = milliseconds > 0;
  14502. args[4] = lang;
  14503. return substituteTimeAgo.apply({}, args);
  14504. }
  14505. /************************************
  14506. Week of Year
  14507. ************************************/
  14508. // firstDayOfWeek 0 = sun, 6 = sat
  14509. // the day of the week that starts the week
  14510. // (usually sunday or monday)
  14511. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  14512. // the first week is the week that contains the first
  14513. // of this day of the week
  14514. // (eg. ISO weeks use thursday (4))
  14515. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  14516. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  14517. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  14518. adjustedMoment;
  14519. if (daysToDayOfWeek > end) {
  14520. daysToDayOfWeek -= 7;
  14521. }
  14522. if (daysToDayOfWeek < end - 7) {
  14523. daysToDayOfWeek += 7;
  14524. }
  14525. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  14526. return {
  14527. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  14528. year: adjustedMoment.year()
  14529. };
  14530. }
  14531. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  14532. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  14533. // The only solid way to create an iso date from year is to use
  14534. // a string format (Date.UTC handles only years > 1900). Don't ask why
  14535. // it doesn't need Z at the end.
  14536. var d = new Date(leftZeroFill(year, 6, true) + '-01-01').getUTCDay(),
  14537. daysToAdd, dayOfYear;
  14538. weekday = weekday != null ? weekday : firstDayOfWeek;
  14539. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0);
  14540. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  14541. return {
  14542. year: dayOfYear > 0 ? year : year - 1,
  14543. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  14544. };
  14545. }
  14546. /************************************
  14547. Top Level Functions
  14548. ************************************/
  14549. function makeMoment(config) {
  14550. var input = config._i,
  14551. format = config._f;
  14552. if (typeof config._pf === 'undefined') {
  14553. initializeParsingFlags(config);
  14554. }
  14555. if (input === null) {
  14556. return moment.invalid({nullInput: true});
  14557. }
  14558. if (typeof input === 'string') {
  14559. config._i = input = getLangDefinition().preparse(input);
  14560. }
  14561. if (moment.isMoment(input)) {
  14562. config = extend({}, input);
  14563. config._d = new Date(+input._d);
  14564. } else if (format) {
  14565. if (isArray(format)) {
  14566. makeDateFromStringAndArray(config);
  14567. } else {
  14568. makeDateFromStringAndFormat(config);
  14569. }
  14570. } else {
  14571. makeDateFromInput(config);
  14572. }
  14573. return new Moment(config);
  14574. }
  14575. moment = function (input, format, lang, strict) {
  14576. if (typeof(lang) === "boolean") {
  14577. strict = lang;
  14578. lang = undefined;
  14579. }
  14580. return makeMoment({
  14581. _i : input,
  14582. _f : format,
  14583. _l : lang,
  14584. _strict : strict,
  14585. _isUTC : false
  14586. });
  14587. };
  14588. // creating with utc
  14589. moment.utc = function (input, format, lang, strict) {
  14590. var m;
  14591. if (typeof(lang) === "boolean") {
  14592. strict = lang;
  14593. lang = undefined;
  14594. }
  14595. m = makeMoment({
  14596. _useUTC : true,
  14597. _isUTC : true,
  14598. _l : lang,
  14599. _i : input,
  14600. _f : format,
  14601. _strict : strict
  14602. }).utc();
  14603. return m;
  14604. };
  14605. // creating with unix timestamp (in seconds)
  14606. moment.unix = function (input) {
  14607. return moment(input * 1000);
  14608. };
  14609. // duration
  14610. moment.duration = function (input, key) {
  14611. var duration = input,
  14612. // matching against regexp is expensive, do it on demand
  14613. match = null,
  14614. sign,
  14615. ret,
  14616. parseIso;
  14617. if (moment.isDuration(input)) {
  14618. duration = {
  14619. ms: input._milliseconds,
  14620. d: input._days,
  14621. M: input._months
  14622. };
  14623. } else if (typeof input === 'number') {
  14624. duration = {};
  14625. if (key) {
  14626. duration[key] = input;
  14627. } else {
  14628. duration.milliseconds = input;
  14629. }
  14630. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  14631. sign = (match[1] === "-") ? -1 : 1;
  14632. duration = {
  14633. y: 0,
  14634. d: toInt(match[DATE]) * sign,
  14635. h: toInt(match[HOUR]) * sign,
  14636. m: toInt(match[MINUTE]) * sign,
  14637. s: toInt(match[SECOND]) * sign,
  14638. ms: toInt(match[MILLISECOND]) * sign
  14639. };
  14640. } else if (!!(match = isoDurationRegex.exec(input))) {
  14641. sign = (match[1] === "-") ? -1 : 1;
  14642. parseIso = function (inp) {
  14643. // We'd normally use ~~inp for this, but unfortunately it also
  14644. // converts floats to ints.
  14645. // inp may be undefined, so careful calling replace on it.
  14646. var res = inp && parseFloat(inp.replace(',', '.'));
  14647. // apply sign while we're at it
  14648. return (isNaN(res) ? 0 : res) * sign;
  14649. };
  14650. duration = {
  14651. y: parseIso(match[2]),
  14652. M: parseIso(match[3]),
  14653. d: parseIso(match[4]),
  14654. h: parseIso(match[5]),
  14655. m: parseIso(match[6]),
  14656. s: parseIso(match[7]),
  14657. w: parseIso(match[8])
  14658. };
  14659. }
  14660. ret = new Duration(duration);
  14661. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  14662. ret._lang = input._lang;
  14663. }
  14664. return ret;
  14665. };
  14666. // version number
  14667. moment.version = VERSION;
  14668. // default format
  14669. moment.defaultFormat = isoFormat;
  14670. // This function will be called whenever a moment is mutated.
  14671. // It is intended to keep the offset in sync with the timezone.
  14672. moment.updateOffset = function () {};
  14673. // This function will load languages and then set the global language. If
  14674. // no arguments are passed in, it will simply return the current global
  14675. // language key.
  14676. moment.lang = function (key, values) {
  14677. var r;
  14678. if (!key) {
  14679. return moment.fn._lang._abbr;
  14680. }
  14681. if (values) {
  14682. loadLang(normalizeLanguage(key), values);
  14683. } else if (values === null) {
  14684. unloadLang(key);
  14685. key = 'en';
  14686. } else if (!languages[key]) {
  14687. getLangDefinition(key);
  14688. }
  14689. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  14690. return r._abbr;
  14691. };
  14692. // returns language data
  14693. moment.langData = function (key) {
  14694. if (key && key._lang && key._lang._abbr) {
  14695. key = key._lang._abbr;
  14696. }
  14697. return getLangDefinition(key);
  14698. };
  14699. // compare moment object
  14700. moment.isMoment = function (obj) {
  14701. return obj instanceof Moment;
  14702. };
  14703. // for typechecking Duration objects
  14704. moment.isDuration = function (obj) {
  14705. return obj instanceof Duration;
  14706. };
  14707. for (i = lists.length - 1; i >= 0; --i) {
  14708. makeList(lists[i]);
  14709. }
  14710. moment.normalizeUnits = function (units) {
  14711. return normalizeUnits(units);
  14712. };
  14713. moment.invalid = function (flags) {
  14714. var m = moment.utc(NaN);
  14715. if (flags != null) {
  14716. extend(m._pf, flags);
  14717. }
  14718. else {
  14719. m._pf.userInvalidated = true;
  14720. }
  14721. return m;
  14722. };
  14723. moment.parseZone = function (input) {
  14724. return moment(input).parseZone();
  14725. };
  14726. /************************************
  14727. Moment Prototype
  14728. ************************************/
  14729. extend(moment.fn = Moment.prototype, {
  14730. clone : function () {
  14731. return moment(this);
  14732. },
  14733. valueOf : function () {
  14734. return +this._d + ((this._offset || 0) * 60000);
  14735. },
  14736. unix : function () {
  14737. return Math.floor(+this / 1000);
  14738. },
  14739. toString : function () {
  14740. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  14741. },
  14742. toDate : function () {
  14743. return this._offset ? new Date(+this) : this._d;
  14744. },
  14745. toISOString : function () {
  14746. var m = moment(this).utc();
  14747. if (0 < m.year() && m.year() <= 9999) {
  14748. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  14749. } else {
  14750. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  14751. }
  14752. },
  14753. toArray : function () {
  14754. var m = this;
  14755. return [
  14756. m.year(),
  14757. m.month(),
  14758. m.date(),
  14759. m.hours(),
  14760. m.minutes(),
  14761. m.seconds(),
  14762. m.milliseconds()
  14763. ];
  14764. },
  14765. isValid : function () {
  14766. return isValid(this);
  14767. },
  14768. isDSTShifted : function () {
  14769. if (this._a) {
  14770. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  14771. }
  14772. return false;
  14773. },
  14774. parsingFlags : function () {
  14775. return extend({}, this._pf);
  14776. },
  14777. invalidAt: function () {
  14778. return this._pf.overflow;
  14779. },
  14780. utc : function () {
  14781. return this.zone(0);
  14782. },
  14783. local : function () {
  14784. this.zone(0);
  14785. this._isUTC = false;
  14786. return this;
  14787. },
  14788. format : function (inputString) {
  14789. var output = formatMoment(this, inputString || moment.defaultFormat);
  14790. return this.lang().postformat(output);
  14791. },
  14792. add : function (input, val) {
  14793. var dur;
  14794. // switch args to support add('s', 1) and add(1, 's')
  14795. if (typeof input === 'string') {
  14796. dur = moment.duration(+val, input);
  14797. } else {
  14798. dur = moment.duration(input, val);
  14799. }
  14800. addOrSubtractDurationFromMoment(this, dur, 1);
  14801. return this;
  14802. },
  14803. subtract : function (input, val) {
  14804. var dur;
  14805. // switch args to support subtract('s', 1) and subtract(1, 's')
  14806. if (typeof input === 'string') {
  14807. dur = moment.duration(+val, input);
  14808. } else {
  14809. dur = moment.duration(input, val);
  14810. }
  14811. addOrSubtractDurationFromMoment(this, dur, -1);
  14812. return this;
  14813. },
  14814. diff : function (input, units, asFloat) {
  14815. var that = makeAs(input, this),
  14816. zoneDiff = (this.zone() - that.zone()) * 6e4,
  14817. diff, output;
  14818. units = normalizeUnits(units);
  14819. if (units === 'year' || units === 'month') {
  14820. // average number of days in the months in the given dates
  14821. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  14822. // difference in months
  14823. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  14824. // adjust by taking difference in days, average number of days
  14825. // and dst in the given months.
  14826. output += ((this - moment(this).startOf('month')) -
  14827. (that - moment(that).startOf('month'))) / diff;
  14828. // same as above but with zones, to negate all dst
  14829. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  14830. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  14831. if (units === 'year') {
  14832. output = output / 12;
  14833. }
  14834. } else {
  14835. diff = (this - that);
  14836. output = units === 'second' ? diff / 1e3 : // 1000
  14837. units === 'minute' ? diff / 6e4 : // 1000 * 60
  14838. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  14839. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  14840. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  14841. diff;
  14842. }
  14843. return asFloat ? output : absRound(output);
  14844. },
  14845. from : function (time, withoutSuffix) {
  14846. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  14847. },
  14848. fromNow : function (withoutSuffix) {
  14849. return this.from(moment(), withoutSuffix);
  14850. },
  14851. calendar : function () {
  14852. // We want to compare the start of today, vs this.
  14853. // Getting start-of-today depends on whether we're zone'd or not.
  14854. var sod = makeAs(moment(), this).startOf('day'),
  14855. diff = this.diff(sod, 'days', true),
  14856. format = diff < -6 ? 'sameElse' :
  14857. diff < -1 ? 'lastWeek' :
  14858. diff < 0 ? 'lastDay' :
  14859. diff < 1 ? 'sameDay' :
  14860. diff < 2 ? 'nextDay' :
  14861. diff < 7 ? 'nextWeek' : 'sameElse';
  14862. return this.format(this.lang().calendar(format, this));
  14863. },
  14864. isLeapYear : function () {
  14865. return isLeapYear(this.year());
  14866. },
  14867. isDST : function () {
  14868. return (this.zone() < this.clone().month(0).zone() ||
  14869. this.zone() < this.clone().month(5).zone());
  14870. },
  14871. day : function (input) {
  14872. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  14873. if (input != null) {
  14874. input = parseWeekday(input, this.lang());
  14875. return this.add({ d : input - day });
  14876. } else {
  14877. return day;
  14878. }
  14879. },
  14880. month : function (input) {
  14881. var utc = this._isUTC ? 'UTC' : '',
  14882. dayOfMonth;
  14883. if (input != null) {
  14884. if (typeof input === 'string') {
  14885. input = this.lang().monthsParse(input);
  14886. if (typeof input !== 'number') {
  14887. return this;
  14888. }
  14889. }
  14890. dayOfMonth = this.date();
  14891. this.date(1);
  14892. this._d['set' + utc + 'Month'](input);
  14893. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  14894. moment.updateOffset(this);
  14895. return this;
  14896. } else {
  14897. return this._d['get' + utc + 'Month']();
  14898. }
  14899. },
  14900. startOf: function (units) {
  14901. units = normalizeUnits(units);
  14902. // the following switch intentionally omits break keywords
  14903. // to utilize falling through the cases.
  14904. switch (units) {
  14905. case 'year':
  14906. this.month(0);
  14907. /* falls through */
  14908. case 'month':
  14909. this.date(1);
  14910. /* falls through */
  14911. case 'week':
  14912. case 'isoWeek':
  14913. case 'day':
  14914. this.hours(0);
  14915. /* falls through */
  14916. case 'hour':
  14917. this.minutes(0);
  14918. /* falls through */
  14919. case 'minute':
  14920. this.seconds(0);
  14921. /* falls through */
  14922. case 'second':
  14923. this.milliseconds(0);
  14924. /* falls through */
  14925. }
  14926. // weeks are a special case
  14927. if (units === 'week') {
  14928. this.weekday(0);
  14929. } else if (units === 'isoWeek') {
  14930. this.isoWeekday(1);
  14931. }
  14932. return this;
  14933. },
  14934. endOf: function (units) {
  14935. units = normalizeUnits(units);
  14936. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  14937. },
  14938. isAfter: function (input, units) {
  14939. units = typeof units !== 'undefined' ? units : 'millisecond';
  14940. return +this.clone().startOf(units) > +moment(input).startOf(units);
  14941. },
  14942. isBefore: function (input, units) {
  14943. units = typeof units !== 'undefined' ? units : 'millisecond';
  14944. return +this.clone().startOf(units) < +moment(input).startOf(units);
  14945. },
  14946. isSame: function (input, units) {
  14947. units = units || 'ms';
  14948. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  14949. },
  14950. min: function (other) {
  14951. other = moment.apply(null, arguments);
  14952. return other < this ? this : other;
  14953. },
  14954. max: function (other) {
  14955. other = moment.apply(null, arguments);
  14956. return other > this ? this : other;
  14957. },
  14958. zone : function (input) {
  14959. var offset = this._offset || 0;
  14960. if (input != null) {
  14961. if (typeof input === "string") {
  14962. input = timezoneMinutesFromString(input);
  14963. }
  14964. if (Math.abs(input) < 16) {
  14965. input = input * 60;
  14966. }
  14967. this._offset = input;
  14968. this._isUTC = true;
  14969. if (offset !== input) {
  14970. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  14971. }
  14972. } else {
  14973. return this._isUTC ? offset : this._d.getTimezoneOffset();
  14974. }
  14975. return this;
  14976. },
  14977. zoneAbbr : function () {
  14978. return this._isUTC ? "UTC" : "";
  14979. },
  14980. zoneName : function () {
  14981. return this._isUTC ? "Coordinated Universal Time" : "";
  14982. },
  14983. parseZone : function () {
  14984. if (this._tzm) {
  14985. this.zone(this._tzm);
  14986. } else if (typeof this._i === 'string') {
  14987. this.zone(this._i);
  14988. }
  14989. return this;
  14990. },
  14991. hasAlignedHourOffset : function (input) {
  14992. if (!input) {
  14993. input = 0;
  14994. }
  14995. else {
  14996. input = moment(input).zone();
  14997. }
  14998. return (this.zone() - input) % 60 === 0;
  14999. },
  15000. daysInMonth : function () {
  15001. return daysInMonth(this.year(), this.month());
  15002. },
  15003. dayOfYear : function (input) {
  15004. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  15005. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  15006. },
  15007. quarter : function () {
  15008. return Math.ceil((this.month() + 1.0) / 3.0);
  15009. },
  15010. weekYear : function (input) {
  15011. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  15012. return input == null ? year : this.add("y", (input - year));
  15013. },
  15014. isoWeekYear : function (input) {
  15015. var year = weekOfYear(this, 1, 4).year;
  15016. return input == null ? year : this.add("y", (input - year));
  15017. },
  15018. week : function (input) {
  15019. var week = this.lang().week(this);
  15020. return input == null ? week : this.add("d", (input - week) * 7);
  15021. },
  15022. isoWeek : function (input) {
  15023. var week = weekOfYear(this, 1, 4).week;
  15024. return input == null ? week : this.add("d", (input - week) * 7);
  15025. },
  15026. weekday : function (input) {
  15027. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  15028. return input == null ? weekday : this.add("d", input - weekday);
  15029. },
  15030. isoWeekday : function (input) {
  15031. // behaves the same as moment#day except
  15032. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  15033. // as a setter, sunday should belong to the previous week.
  15034. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  15035. },
  15036. get : function (units) {
  15037. units = normalizeUnits(units);
  15038. return this[units]();
  15039. },
  15040. set : function (units, value) {
  15041. units = normalizeUnits(units);
  15042. if (typeof this[units] === 'function') {
  15043. this[units](value);
  15044. }
  15045. return this;
  15046. },
  15047. // If passed a language key, it will set the language for this
  15048. // instance. Otherwise, it will return the language configuration
  15049. // variables for this instance.
  15050. lang : function (key) {
  15051. if (key === undefined) {
  15052. return this._lang;
  15053. } else {
  15054. this._lang = getLangDefinition(key);
  15055. return this;
  15056. }
  15057. }
  15058. });
  15059. // helper for adding shortcuts
  15060. function makeGetterAndSetter(name, key) {
  15061. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  15062. var utc = this._isUTC ? 'UTC' : '';
  15063. if (input != null) {
  15064. this._d['set' + utc + key](input);
  15065. moment.updateOffset(this);
  15066. return this;
  15067. } else {
  15068. return this._d['get' + utc + key]();
  15069. }
  15070. };
  15071. }
  15072. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  15073. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  15074. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  15075. }
  15076. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  15077. makeGetterAndSetter('year', 'FullYear');
  15078. // add plural methods
  15079. moment.fn.days = moment.fn.day;
  15080. moment.fn.months = moment.fn.month;
  15081. moment.fn.weeks = moment.fn.week;
  15082. moment.fn.isoWeeks = moment.fn.isoWeek;
  15083. // add aliased format methods
  15084. moment.fn.toJSON = moment.fn.toISOString;
  15085. /************************************
  15086. Duration Prototype
  15087. ************************************/
  15088. extend(moment.duration.fn = Duration.prototype, {
  15089. _bubble : function () {
  15090. var milliseconds = this._milliseconds,
  15091. days = this._days,
  15092. months = this._months,
  15093. data = this._data,
  15094. seconds, minutes, hours, years;
  15095. // The following code bubbles up values, see the tests for
  15096. // examples of what that means.
  15097. data.milliseconds = milliseconds % 1000;
  15098. seconds = absRound(milliseconds / 1000);
  15099. data.seconds = seconds % 60;
  15100. minutes = absRound(seconds / 60);
  15101. data.minutes = minutes % 60;
  15102. hours = absRound(minutes / 60);
  15103. data.hours = hours % 24;
  15104. days += absRound(hours / 24);
  15105. data.days = days % 30;
  15106. months += absRound(days / 30);
  15107. data.months = months % 12;
  15108. years = absRound(months / 12);
  15109. data.years = years;
  15110. },
  15111. weeks : function () {
  15112. return absRound(this.days() / 7);
  15113. },
  15114. valueOf : function () {
  15115. return this._milliseconds +
  15116. this._days * 864e5 +
  15117. (this._months % 12) * 2592e6 +
  15118. toInt(this._months / 12) * 31536e6;
  15119. },
  15120. humanize : function (withSuffix) {
  15121. var difference = +this,
  15122. output = relativeTime(difference, !withSuffix, this.lang());
  15123. if (withSuffix) {
  15124. output = this.lang().pastFuture(difference, output);
  15125. }
  15126. return this.lang().postformat(output);
  15127. },
  15128. add : function (input, val) {
  15129. // supports only 2.0-style add(1, 's') or add(moment)
  15130. var dur = moment.duration(input, val);
  15131. this._milliseconds += dur._milliseconds;
  15132. this._days += dur._days;
  15133. this._months += dur._months;
  15134. this._bubble();
  15135. return this;
  15136. },
  15137. subtract : function (input, val) {
  15138. var dur = moment.duration(input, val);
  15139. this._milliseconds -= dur._milliseconds;
  15140. this._days -= dur._days;
  15141. this._months -= dur._months;
  15142. this._bubble();
  15143. return this;
  15144. },
  15145. get : function (units) {
  15146. units = normalizeUnits(units);
  15147. return this[units.toLowerCase() + 's']();
  15148. },
  15149. as : function (units) {
  15150. units = normalizeUnits(units);
  15151. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  15152. },
  15153. lang : moment.fn.lang,
  15154. toIsoString : function () {
  15155. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  15156. var years = Math.abs(this.years()),
  15157. months = Math.abs(this.months()),
  15158. days = Math.abs(this.days()),
  15159. hours = Math.abs(this.hours()),
  15160. minutes = Math.abs(this.minutes()),
  15161. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  15162. if (!this.asSeconds()) {
  15163. // this is the same as C#'s (Noda) and python (isodate)...
  15164. // but not other JS (goog.date)
  15165. return 'P0D';
  15166. }
  15167. return (this.asSeconds() < 0 ? '-' : '') +
  15168. 'P' +
  15169. (years ? years + 'Y' : '') +
  15170. (months ? months + 'M' : '') +
  15171. (days ? days + 'D' : '') +
  15172. ((hours || minutes || seconds) ? 'T' : '') +
  15173. (hours ? hours + 'H' : '') +
  15174. (minutes ? minutes + 'M' : '') +
  15175. (seconds ? seconds + 'S' : '');
  15176. }
  15177. });
  15178. function makeDurationGetter(name) {
  15179. moment.duration.fn[name] = function () {
  15180. return this._data[name];
  15181. };
  15182. }
  15183. function makeDurationAsGetter(name, factor) {
  15184. moment.duration.fn['as' + name] = function () {
  15185. return +this / factor;
  15186. };
  15187. }
  15188. for (i in unitMillisecondFactors) {
  15189. if (unitMillisecondFactors.hasOwnProperty(i)) {
  15190. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  15191. makeDurationGetter(i.toLowerCase());
  15192. }
  15193. }
  15194. makeDurationAsGetter('Weeks', 6048e5);
  15195. moment.duration.fn.asMonths = function () {
  15196. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  15197. };
  15198. /************************************
  15199. Default Lang
  15200. ************************************/
  15201. // Set default language, other languages will inherit from English.
  15202. moment.lang('en', {
  15203. ordinal : function (number) {
  15204. var b = number % 10,
  15205. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  15206. (b === 1) ? 'st' :
  15207. (b === 2) ? 'nd' :
  15208. (b === 3) ? 'rd' : 'th';
  15209. return number + output;
  15210. }
  15211. });
  15212. /* EMBED_LANGUAGES */
  15213. /************************************
  15214. Exposing Moment
  15215. ************************************/
  15216. function makeGlobal(deprecate) {
  15217. var warned = false, local_moment = moment;
  15218. /*global ender:false */
  15219. if (typeof ender !== 'undefined') {
  15220. return;
  15221. }
  15222. // here, `this` means `window` in the browser, or `global` on the server
  15223. // add `moment` as a global object via a string identifier,
  15224. // for Closure Compiler "advanced" mode
  15225. if (deprecate) {
  15226. global.moment = function () {
  15227. if (!warned && console && console.warn) {
  15228. warned = true;
  15229. console.warn(
  15230. "Accessing Moment through the global scope is " +
  15231. "deprecated, and will be removed in an upcoming " +
  15232. "release.");
  15233. }
  15234. return local_moment.apply(null, arguments);
  15235. };
  15236. extend(global.moment, local_moment);
  15237. } else {
  15238. global['moment'] = moment;
  15239. }
  15240. }
  15241. // CommonJS module is defined
  15242. if (hasModule) {
  15243. module.exports = moment;
  15244. makeGlobal(true);
  15245. } else if (typeof define === "function" && define.amd) {
  15246. define("moment", function (require, exports, module) {
  15247. if (module.config && module.config() && module.config().noGlobal !== true) {
  15248. // If user provided noGlobal, he is aware of global
  15249. makeGlobal(module.config().noGlobal === undefined);
  15250. }
  15251. return moment;
  15252. });
  15253. } else {
  15254. makeGlobal();
  15255. }
  15256. }).call(this);
  15257. },{}],4:[function(require,module,exports){
  15258. /**
  15259. * Copyright 2012 Craig Campbell
  15260. *
  15261. * Licensed under the Apache License, Version 2.0 (the "License");
  15262. * you may not use this file except in compliance with the License.
  15263. * You may obtain a copy of the License at
  15264. *
  15265. * http://www.apache.org/licenses/LICENSE-2.0
  15266. *
  15267. * Unless required by applicable law or agreed to in writing, software
  15268. * distributed under the License is distributed on an "AS IS" BASIS,
  15269. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15270. * See the License for the specific language governing permissions and
  15271. * limitations under the License.
  15272. *
  15273. * Mousetrap is a simple keyboard shortcut library for Javascript with
  15274. * no external dependencies
  15275. *
  15276. * @version 1.1.2
  15277. * @url craig.is/killing/mice
  15278. */
  15279. /**
  15280. * mapping of special keycodes to their corresponding keys
  15281. *
  15282. * everything in this dictionary cannot use keypress events
  15283. * so it has to be here to map to the correct keycodes for
  15284. * keyup/keydown events
  15285. *
  15286. * @type {Object}
  15287. */
  15288. var _MAP = {
  15289. 8: 'backspace',
  15290. 9: 'tab',
  15291. 13: 'enter',
  15292. 16: 'shift',
  15293. 17: 'ctrl',
  15294. 18: 'alt',
  15295. 20: 'capslock',
  15296. 27: 'esc',
  15297. 32: 'space',
  15298. 33: 'pageup',
  15299. 34: 'pagedown',
  15300. 35: 'end',
  15301. 36: 'home',
  15302. 37: 'left',
  15303. 38: 'up',
  15304. 39: 'right',
  15305. 40: 'down',
  15306. 45: 'ins',
  15307. 46: 'del',
  15308. 91: 'meta',
  15309. 93: 'meta',
  15310. 224: 'meta'
  15311. },
  15312. /**
  15313. * mapping for special characters so they can support
  15314. *
  15315. * this dictionary is only used incase you want to bind a
  15316. * keyup or keydown event to one of these keys
  15317. *
  15318. * @type {Object}
  15319. */
  15320. _KEYCODE_MAP = {
  15321. 106: '*',
  15322. 107: '+',
  15323. 109: '-',
  15324. 110: '.',
  15325. 111 : '/',
  15326. 186: ';',
  15327. 187: '=',
  15328. 188: ',',
  15329. 189: '-',
  15330. 190: '.',
  15331. 191: '/',
  15332. 192: '`',
  15333. 219: '[',
  15334. 220: '\\',
  15335. 221: ']',
  15336. 222: '\''
  15337. },
  15338. /**
  15339. * this is a mapping of keys that require shift on a US keypad
  15340. * back to the non shift equivelents
  15341. *
  15342. * this is so you can use keyup events with these keys
  15343. *
  15344. * note that this will only work reliably on US keyboards
  15345. *
  15346. * @type {Object}
  15347. */
  15348. _SHIFT_MAP = {
  15349. '~': '`',
  15350. '!': '1',
  15351. '@': '2',
  15352. '#': '3',
  15353. '$': '4',
  15354. '%': '5',
  15355. '^': '6',
  15356. '&': '7',
  15357. '*': '8',
  15358. '(': '9',
  15359. ')': '0',
  15360. '_': '-',
  15361. '+': '=',
  15362. ':': ';',
  15363. '\"': '\'',
  15364. '<': ',',
  15365. '>': '.',
  15366. '?': '/',
  15367. '|': '\\'
  15368. },
  15369. /**
  15370. * this is a list of special strings you can use to map
  15371. * to modifier keys when you specify your keyboard shortcuts
  15372. *
  15373. * @type {Object}
  15374. */
  15375. _SPECIAL_ALIASES = {
  15376. 'option': 'alt',
  15377. 'command': 'meta',
  15378. 'return': 'enter',
  15379. 'escape': 'esc'
  15380. },
  15381. /**
  15382. * variable to store the flipped version of _MAP from above
  15383. * needed to check if we should use keypress or not when no action
  15384. * is specified
  15385. *
  15386. * @type {Object|undefined}
  15387. */
  15388. _REVERSE_MAP,
  15389. /**
  15390. * a list of all the callbacks setup via Mousetrap.bind()
  15391. *
  15392. * @type {Object}
  15393. */
  15394. _callbacks = {},
  15395. /**
  15396. * direct map of string combinations to callbacks used for trigger()
  15397. *
  15398. * @type {Object}
  15399. */
  15400. _direct_map = {},
  15401. /**
  15402. * keeps track of what level each sequence is at since multiple
  15403. * sequences can start out with the same sequence
  15404. *
  15405. * @type {Object}
  15406. */
  15407. _sequence_levels = {},
  15408. /**
  15409. * variable to store the setTimeout call
  15410. *
  15411. * @type {null|number}
  15412. */
  15413. _reset_timer,
  15414. /**
  15415. * temporary state where we will ignore the next keyup
  15416. *
  15417. * @type {boolean|string}
  15418. */
  15419. _ignore_next_keyup = false,
  15420. /**
  15421. * are we currently inside of a sequence?
  15422. * type of action ("keyup" or "keydown" or "keypress") or false
  15423. *
  15424. * @type {boolean|string}
  15425. */
  15426. _inside_sequence = false;
  15427. /**
  15428. * loop through the f keys, f1 to f19 and add them to the map
  15429. * programatically
  15430. */
  15431. for (var i = 1; i < 20; ++i) {
  15432. _MAP[111 + i] = 'f' + i;
  15433. }
  15434. /**
  15435. * loop through to map numbers on the numeric keypad
  15436. */
  15437. for (i = 0; i <= 9; ++i) {
  15438. _MAP[i + 96] = i;
  15439. }
  15440. /**
  15441. * cross browser add event method
  15442. *
  15443. * @param {Element|HTMLDocument} object
  15444. * @param {string} type
  15445. * @param {Function} callback
  15446. * @returns void
  15447. */
  15448. function _addEvent(object, type, callback) {
  15449. if (object.addEventListener) {
  15450. return object.addEventListener(type, callback, false);
  15451. }
  15452. object.attachEvent('on' + type, callback);
  15453. }
  15454. /**
  15455. * takes the event and returns the key character
  15456. *
  15457. * @param {Event} e
  15458. * @return {string}
  15459. */
  15460. function _characterFromEvent(e) {
  15461. // for keypress events we should return the character as is
  15462. if (e.type == 'keypress') {
  15463. return String.fromCharCode(e.which);
  15464. }
  15465. // for non keypress events the special maps are needed
  15466. if (_MAP[e.which]) {
  15467. return _MAP[e.which];
  15468. }
  15469. if (_KEYCODE_MAP[e.which]) {
  15470. return _KEYCODE_MAP[e.which];
  15471. }
  15472. // if it is not in the special map
  15473. return String.fromCharCode(e.which).toLowerCase();
  15474. }
  15475. /**
  15476. * should we stop this event before firing off callbacks
  15477. *
  15478. * @param {Event} e
  15479. * @return {boolean}
  15480. */
  15481. function _stop(e) {
  15482. var element = e.target || e.srcElement,
  15483. tag_name = element.tagName;
  15484. // if the element has the class "mousetrap" then no need to stop
  15485. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  15486. return false;
  15487. }
  15488. // stop for input, select, and textarea
  15489. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  15490. }
  15491. /**
  15492. * checks if two arrays are equal
  15493. *
  15494. * @param {Array} modifiers1
  15495. * @param {Array} modifiers2
  15496. * @returns {boolean}
  15497. */
  15498. function _modifiersMatch(modifiers1, modifiers2) {
  15499. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  15500. }
  15501. /**
  15502. * resets all sequence counters except for the ones passed in
  15503. *
  15504. * @param {Object} do_not_reset
  15505. * @returns void
  15506. */
  15507. function _resetSequences(do_not_reset) {
  15508. do_not_reset = do_not_reset || {};
  15509. var active_sequences = false,
  15510. key;
  15511. for (key in _sequence_levels) {
  15512. if (do_not_reset[key]) {
  15513. active_sequences = true;
  15514. continue;
  15515. }
  15516. _sequence_levels[key] = 0;
  15517. }
  15518. if (!active_sequences) {
  15519. _inside_sequence = false;
  15520. }
  15521. }
  15522. /**
  15523. * finds all callbacks that match based on the keycode, modifiers,
  15524. * and action
  15525. *
  15526. * @param {string} character
  15527. * @param {Array} modifiers
  15528. * @param {string} action
  15529. * @param {boolean=} remove - should we remove any matches
  15530. * @param {string=} combination
  15531. * @returns {Array}
  15532. */
  15533. function _getMatches(character, modifiers, action, remove, combination) {
  15534. var i,
  15535. callback,
  15536. matches = [];
  15537. // if there are no events related to this keycode
  15538. if (!_callbacks[character]) {
  15539. return [];
  15540. }
  15541. // if a modifier key is coming up on its own we should allow it
  15542. if (action == 'keyup' && _isModifier(character)) {
  15543. modifiers = [character];
  15544. }
  15545. // loop through all callbacks for the key that was pressed
  15546. // and see if any of them match
  15547. for (i = 0; i < _callbacks[character].length; ++i) {
  15548. callback = _callbacks[character][i];
  15549. // if this is a sequence but it is not at the right level
  15550. // then move onto the next match
  15551. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  15552. continue;
  15553. }
  15554. // if the action we are looking for doesn't match the action we got
  15555. // then we should keep going
  15556. if (action != callback.action) {
  15557. continue;
  15558. }
  15559. // if this is a keypress event that means that we need to only
  15560. // look at the character, otherwise check the modifiers as
  15561. // well
  15562. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  15563. // remove is used so if you change your mind and call bind a
  15564. // second time with a new function the first one is overwritten
  15565. if (remove && callback.combo == combination) {
  15566. _callbacks[character].splice(i, 1);
  15567. }
  15568. matches.push(callback);
  15569. }
  15570. }
  15571. return matches;
  15572. }
  15573. /**
  15574. * takes a key event and figures out what the modifiers are
  15575. *
  15576. * @param {Event} e
  15577. * @returns {Array}
  15578. */
  15579. function _eventModifiers(e) {
  15580. var modifiers = [];
  15581. if (e.shiftKey) {
  15582. modifiers.push('shift');
  15583. }
  15584. if (e.altKey) {
  15585. modifiers.push('alt');
  15586. }
  15587. if (e.ctrlKey) {
  15588. modifiers.push('ctrl');
  15589. }
  15590. if (e.metaKey) {
  15591. modifiers.push('meta');
  15592. }
  15593. return modifiers;
  15594. }
  15595. /**
  15596. * actually calls the callback function
  15597. *
  15598. * if your callback function returns false this will use the jquery
  15599. * convention - prevent default and stop propogation on the event
  15600. *
  15601. * @param {Function} callback
  15602. * @param {Event} e
  15603. * @returns void
  15604. */
  15605. function _fireCallback(callback, e) {
  15606. if (callback(e) === false) {
  15607. if (e.preventDefault) {
  15608. e.preventDefault();
  15609. }
  15610. if (e.stopPropagation) {
  15611. e.stopPropagation();
  15612. }
  15613. e.returnValue = false;
  15614. e.cancelBubble = true;
  15615. }
  15616. }
  15617. /**
  15618. * handles a character key event
  15619. *
  15620. * @param {string} character
  15621. * @param {Event} e
  15622. * @returns void
  15623. */
  15624. function _handleCharacter(character, e) {
  15625. // if this event should not happen stop here
  15626. if (_stop(e)) {
  15627. return;
  15628. }
  15629. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  15630. i,
  15631. do_not_reset = {},
  15632. processed_sequence_callback = false;
  15633. // loop through matching callbacks for this key event
  15634. for (i = 0; i < callbacks.length; ++i) {
  15635. // fire for all sequence callbacks
  15636. // this is because if for example you have multiple sequences
  15637. // bound such as "g i" and "g t" they both need to fire the
  15638. // callback for matching g cause otherwise you can only ever
  15639. // match the first one
  15640. if (callbacks[i].seq) {
  15641. processed_sequence_callback = true;
  15642. // keep a list of which sequences were matches for later
  15643. do_not_reset[callbacks[i].seq] = 1;
  15644. _fireCallback(callbacks[i].callback, e);
  15645. continue;
  15646. }
  15647. // if there were no sequence matches but we are still here
  15648. // that means this is a regular match so we should fire that
  15649. if (!processed_sequence_callback && !_inside_sequence) {
  15650. _fireCallback(callbacks[i].callback, e);
  15651. }
  15652. }
  15653. // if you are inside of a sequence and the key you are pressing
  15654. // is not a modifier key then we should reset all sequences
  15655. // that were not matched by this key event
  15656. if (e.type == _inside_sequence && !_isModifier(character)) {
  15657. _resetSequences(do_not_reset);
  15658. }
  15659. }
  15660. /**
  15661. * handles a keydown event
  15662. *
  15663. * @param {Event} e
  15664. * @returns void
  15665. */
  15666. function _handleKey(e) {
  15667. // normalize e.which for key events
  15668. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  15669. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  15670. var character = _characterFromEvent(e);
  15671. // no character found then stop
  15672. if (!character) {
  15673. return;
  15674. }
  15675. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  15676. _ignore_next_keyup = false;
  15677. return;
  15678. }
  15679. _handleCharacter(character, e);
  15680. }
  15681. /**
  15682. * determines if the keycode specified is a modifier key or not
  15683. *
  15684. * @param {string} key
  15685. * @returns {boolean}
  15686. */
  15687. function _isModifier(key) {
  15688. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  15689. }
  15690. /**
  15691. * called to set a 1 second timeout on the specified sequence
  15692. *
  15693. * this is so after each key press in the sequence you have 1 second
  15694. * to press the next key before you have to start over
  15695. *
  15696. * @returns void
  15697. */
  15698. function _resetSequenceTimer() {
  15699. clearTimeout(_reset_timer);
  15700. _reset_timer = setTimeout(_resetSequences, 1000);
  15701. }
  15702. /**
  15703. * reverses the map lookup so that we can look for specific keys
  15704. * to see what can and can't use keypress
  15705. *
  15706. * @return {Object}
  15707. */
  15708. function _getReverseMap() {
  15709. if (!_REVERSE_MAP) {
  15710. _REVERSE_MAP = {};
  15711. for (var key in _MAP) {
  15712. // pull out the numeric keypad from here cause keypress should
  15713. // be able to detect the keys from the character
  15714. if (key > 95 && key < 112) {
  15715. continue;
  15716. }
  15717. if (_MAP.hasOwnProperty(key)) {
  15718. _REVERSE_MAP[_MAP[key]] = key;
  15719. }
  15720. }
  15721. }
  15722. return _REVERSE_MAP;
  15723. }
  15724. /**
  15725. * picks the best action based on the key combination
  15726. *
  15727. * @param {string} key - character for key
  15728. * @param {Array} modifiers
  15729. * @param {string=} action passed in
  15730. */
  15731. function _pickBestAction(key, modifiers, action) {
  15732. // if no action was picked in we should try to pick the one
  15733. // that we think would work best for this key
  15734. if (!action) {
  15735. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  15736. }
  15737. // modifier keys don't work as expected with keypress,
  15738. // switch to keydown
  15739. if (action == 'keypress' && modifiers.length) {
  15740. action = 'keydown';
  15741. }
  15742. return action;
  15743. }
  15744. /**
  15745. * binds a key sequence to an event
  15746. *
  15747. * @param {string} combo - combo specified in bind call
  15748. * @param {Array} keys
  15749. * @param {Function} callback
  15750. * @param {string=} action
  15751. * @returns void
  15752. */
  15753. function _bindSequence(combo, keys, callback, action) {
  15754. // start off by adding a sequence level record for this combination
  15755. // and setting the level to 0
  15756. _sequence_levels[combo] = 0;
  15757. // if there is no action pick the best one for the first key
  15758. // in the sequence
  15759. if (!action) {
  15760. action = _pickBestAction(keys[0], []);
  15761. }
  15762. /**
  15763. * callback to increase the sequence level for this sequence and reset
  15764. * all other sequences that were active
  15765. *
  15766. * @param {Event} e
  15767. * @returns void
  15768. */
  15769. var _increaseSequence = function(e) {
  15770. _inside_sequence = action;
  15771. ++_sequence_levels[combo];
  15772. _resetSequenceTimer();
  15773. },
  15774. /**
  15775. * wraps the specified callback inside of another function in order
  15776. * to reset all sequence counters as soon as this sequence is done
  15777. *
  15778. * @param {Event} e
  15779. * @returns void
  15780. */
  15781. _callbackAndReset = function(e) {
  15782. _fireCallback(callback, e);
  15783. // we should ignore the next key up if the action is key down
  15784. // or keypress. this is so if you finish a sequence and
  15785. // release the key the final key will not trigger a keyup
  15786. if (action !== 'keyup') {
  15787. _ignore_next_keyup = _characterFromEvent(e);
  15788. }
  15789. // weird race condition if a sequence ends with the key
  15790. // another sequence begins with
  15791. setTimeout(_resetSequences, 10);
  15792. },
  15793. i;
  15794. // loop through keys one at a time and bind the appropriate callback
  15795. // function. for any key leading up to the final one it should
  15796. // increase the sequence. after the final, it should reset all sequences
  15797. for (i = 0; i < keys.length; ++i) {
  15798. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  15799. }
  15800. }
  15801. /**
  15802. * binds a single keyboard combination
  15803. *
  15804. * @param {string} combination
  15805. * @param {Function} callback
  15806. * @param {string=} action
  15807. * @param {string=} sequence_name - name of sequence if part of sequence
  15808. * @param {number=} level - what part of the sequence the command is
  15809. * @returns void
  15810. */
  15811. function _bindSingle(combination, callback, action, sequence_name, level) {
  15812. // make sure multiple spaces in a row become a single space
  15813. combination = combination.replace(/\s+/g, ' ');
  15814. var sequence = combination.split(' '),
  15815. i,
  15816. key,
  15817. keys,
  15818. modifiers = [];
  15819. // if this pattern is a sequence of keys then run through this method
  15820. // to reprocess each pattern one key at a time
  15821. if (sequence.length > 1) {
  15822. return _bindSequence(combination, sequence, callback, action);
  15823. }
  15824. // take the keys from this pattern and figure out what the actual
  15825. // pattern is all about
  15826. keys = combination === '+' ? ['+'] : combination.split('+');
  15827. for (i = 0; i < keys.length; ++i) {
  15828. key = keys[i];
  15829. // normalize key names
  15830. if (_SPECIAL_ALIASES[key]) {
  15831. key = _SPECIAL_ALIASES[key];
  15832. }
  15833. // if this is not a keypress event then we should
  15834. // be smart about using shift keys
  15835. // this will only work for US keyboards however
  15836. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  15837. key = _SHIFT_MAP[key];
  15838. modifiers.push('shift');
  15839. }
  15840. // if this key is a modifier then add it to the list of modifiers
  15841. if (_isModifier(key)) {
  15842. modifiers.push(key);
  15843. }
  15844. }
  15845. // depending on what the key combination is
  15846. // we will try to pick the best event for it
  15847. action = _pickBestAction(key, modifiers, action);
  15848. // make sure to initialize array if this is the first time
  15849. // a callback is added for this key
  15850. if (!_callbacks[key]) {
  15851. _callbacks[key] = [];
  15852. }
  15853. // remove an existing match if there is one
  15854. _getMatches(key, modifiers, action, !sequence_name, combination);
  15855. // add this call back to the array
  15856. // if it is a sequence put it at the beginning
  15857. // if not put it at the end
  15858. //
  15859. // this is important because the way these are processed expects
  15860. // the sequence ones to come first
  15861. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  15862. callback: callback,
  15863. modifiers: modifiers,
  15864. action: action,
  15865. seq: sequence_name,
  15866. level: level,
  15867. combo: combination
  15868. });
  15869. }
  15870. /**
  15871. * binds multiple combinations to the same callback
  15872. *
  15873. * @param {Array} combinations
  15874. * @param {Function} callback
  15875. * @param {string|undefined} action
  15876. * @returns void
  15877. */
  15878. function _bindMultiple(combinations, callback, action) {
  15879. for (var i = 0; i < combinations.length; ++i) {
  15880. _bindSingle(combinations[i], callback, action);
  15881. }
  15882. }
  15883. // start!
  15884. _addEvent(document, 'keypress', _handleKey);
  15885. _addEvent(document, 'keydown', _handleKey);
  15886. _addEvent(document, 'keyup', _handleKey);
  15887. var mousetrap = {
  15888. /**
  15889. * binds an event to mousetrap
  15890. *
  15891. * can be a single key, a combination of keys separated with +,
  15892. * a comma separated list of keys, an array of keys, or
  15893. * a sequence of keys separated by spaces
  15894. *
  15895. * be sure to list the modifier keys first to make sure that the
  15896. * correct key ends up getting bound (the last key in the pattern)
  15897. *
  15898. * @param {string|Array} keys
  15899. * @param {Function} callback
  15900. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  15901. * @returns void
  15902. */
  15903. bind: function(keys, callback, action) {
  15904. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  15905. _direct_map[keys + ':' + action] = callback;
  15906. return this;
  15907. },
  15908. /**
  15909. * unbinds an event to mousetrap
  15910. *
  15911. * the unbinding sets the callback function of the specified key combo
  15912. * to an empty function and deletes the corresponding key in the
  15913. * _direct_map dict.
  15914. *
  15915. * the keycombo+action has to be exactly the same as
  15916. * it was defined in the bind method
  15917. *
  15918. * TODO: actually remove this from the _callbacks dictionary instead
  15919. * of binding an empty function
  15920. *
  15921. * @param {string|Array} keys
  15922. * @param {string} action
  15923. * @returns void
  15924. */
  15925. unbind: function(keys, action) {
  15926. if (_direct_map[keys + ':' + action]) {
  15927. delete _direct_map[keys + ':' + action];
  15928. this.bind(keys, function() {}, action);
  15929. }
  15930. return this;
  15931. },
  15932. /**
  15933. * triggers an event that has already been bound
  15934. *
  15935. * @param {string} keys
  15936. * @param {string=} action
  15937. * @returns void
  15938. */
  15939. trigger: function(keys, action) {
  15940. _direct_map[keys + ':' + action]();
  15941. return this;
  15942. },
  15943. /**
  15944. * resets the library back to its initial state. this is useful
  15945. * if you want to clear out the current keyboard shortcuts and bind
  15946. * new ones - for example if you switch to another page
  15947. *
  15948. * @returns void
  15949. */
  15950. reset: function() {
  15951. _callbacks = {};
  15952. _direct_map = {};
  15953. return this;
  15954. }
  15955. };
  15956. module.exports = mousetrap;
  15957. },{}]},{},[1])
  15958. (1)
  15959. });