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.

23699 lines
700 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 1.0.2-SNAPSHOT
  8. * @date 2014-05-28
  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 Emitter = require('emitter-component');
  33. var Hammer;
  34. if (typeof window !== 'undefined') {
  35. // load hammer.js only when running in a browser (where window is available)
  36. Hammer = window['Hammer'] || require('hammerjs');
  37. }
  38. else {
  39. Hammer = function () {
  40. throw Error('hammer.js is only available in a browser, not in node.js.');
  41. }
  42. }
  43. var mousetrap;
  44. if (typeof window !== 'undefined') {
  45. // load mousetrap.js only when running in a browser (where window is available)
  46. mousetrap = window['mousetrap'] || require('mousetrap');
  47. }
  48. else {
  49. mousetrap = function () {
  50. throw Error('mouseTrap is only available in a browser, not in node.js.');
  51. }
  52. }
  53. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  54. // it here in that case.
  55. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  56. if(!Array.prototype.indexOf) {
  57. Array.prototype.indexOf = function(obj){
  58. for(var i = 0; i < this.length; i++){
  59. if(this[i] == obj){
  60. return i;
  61. }
  62. }
  63. return -1;
  64. };
  65. try {
  66. console.log("Warning: Ancient browser detected. Please update your browser");
  67. }
  68. catch (err) {
  69. }
  70. }
  71. // Internet Explorer 8 and older does not support Array.forEach, so we define
  72. // it here in that case.
  73. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  74. if (!Array.prototype.forEach) {
  75. Array.prototype.forEach = function(fn, scope) {
  76. for(var i = 0, len = this.length; i < len; ++i) {
  77. fn.call(scope || this, this[i], i, this);
  78. }
  79. }
  80. }
  81. // Internet Explorer 8 and older does not support Array.map, so we define it
  82. // here in that case.
  83. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  84. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  85. // Reference: http://es5.github.com/#x15.4.4.19
  86. if (!Array.prototype.map) {
  87. Array.prototype.map = function(callback, thisArg) {
  88. var T, A, k;
  89. if (this == null) {
  90. throw new TypeError(" this is null or not defined");
  91. }
  92. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  93. var O = Object(this);
  94. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  95. // 3. Let len be ToUint32(lenValue).
  96. var len = O.length >>> 0;
  97. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  98. // See: http://es5.github.com/#x9.11
  99. if (typeof callback !== "function") {
  100. throw new TypeError(callback + " is not a function");
  101. }
  102. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  103. if (thisArg) {
  104. T = thisArg;
  105. }
  106. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  107. // the standard built-in constructor with that name and len is the value of len.
  108. A = new Array(len);
  109. // 7. Let k be 0
  110. k = 0;
  111. // 8. Repeat, while k < len
  112. while(k < len) {
  113. var kValue, mappedValue;
  114. // a. Let Pk be ToString(k).
  115. // This is implicit for LHS operands of the in operator
  116. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  117. // This step can be combined with c
  118. // c. If kPresent is true, then
  119. if (k in O) {
  120. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  121. kValue = O[ k ];
  122. // ii. Let mappedValue be the result of calling the Call internal method of callback
  123. // with T as the this value and argument list containing kValue, k, and O.
  124. mappedValue = callback.call(T, kValue, k, O);
  125. // iii. Call the DefineOwnProperty internal method of A with arguments
  126. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  127. // and false.
  128. // In browsers that support Object.defineProperty, use the following:
  129. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  130. // For best browser support, use the following:
  131. A[ k ] = mappedValue;
  132. }
  133. // d. Increase k by 1.
  134. k++;
  135. }
  136. // 9. return A
  137. return A;
  138. };
  139. }
  140. // Internet Explorer 8 and older does not support Array.filter, so we define it
  141. // here in that case.
  142. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  143. if (!Array.prototype.filter) {
  144. Array.prototype.filter = function(fun /*, thisp */) {
  145. "use strict";
  146. if (this == null) {
  147. throw new TypeError();
  148. }
  149. var t = Object(this);
  150. var len = t.length >>> 0;
  151. if (typeof fun != "function") {
  152. throw new TypeError();
  153. }
  154. var res = [];
  155. var thisp = arguments[1];
  156. for (var i = 0; i < len; i++) {
  157. if (i in t) {
  158. var val = t[i]; // in case fun mutates this
  159. if (fun.call(thisp, val, i, t))
  160. res.push(val);
  161. }
  162. }
  163. return res;
  164. };
  165. }
  166. // Internet Explorer 8 and older does not support Object.keys, so we define it
  167. // here in that case.
  168. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  169. if (!Object.keys) {
  170. Object.keys = (function () {
  171. var hasOwnProperty = Object.prototype.hasOwnProperty,
  172. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  173. dontEnums = [
  174. 'toString',
  175. 'toLocaleString',
  176. 'valueOf',
  177. 'hasOwnProperty',
  178. 'isPrototypeOf',
  179. 'propertyIsEnumerable',
  180. 'constructor'
  181. ],
  182. dontEnumsLength = dontEnums.length;
  183. return function (obj) {
  184. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  185. throw new TypeError('Object.keys called on non-object');
  186. }
  187. var result = [];
  188. for (var prop in obj) {
  189. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  190. }
  191. if (hasDontEnumBug) {
  192. for (var i=0; i < dontEnumsLength; i++) {
  193. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  194. }
  195. }
  196. return result;
  197. }
  198. })()
  199. }
  200. // Internet Explorer 8 and older does not support Array.isArray,
  201. // so we define it here in that case.
  202. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  203. if(!Array.isArray) {
  204. Array.isArray = function (vArg) {
  205. return Object.prototype.toString.call(vArg) === "[object Array]";
  206. };
  207. }
  208. // Internet Explorer 8 and older does not support Function.bind,
  209. // so we define it here in that case.
  210. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  211. if (!Function.prototype.bind) {
  212. Function.prototype.bind = function (oThis) {
  213. if (typeof this !== "function") {
  214. // closest thing possible to the ECMAScript 5 internal IsCallable function
  215. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  216. }
  217. var aArgs = Array.prototype.slice.call(arguments, 1),
  218. fToBind = this,
  219. fNOP = function () {},
  220. fBound = function () {
  221. return fToBind.apply(this instanceof fNOP && oThis
  222. ? this
  223. : oThis,
  224. aArgs.concat(Array.prototype.slice.call(arguments)));
  225. };
  226. fNOP.prototype = this.prototype;
  227. fBound.prototype = new fNOP();
  228. return fBound;
  229. };
  230. }
  231. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  232. if (!Object.create) {
  233. Object.create = function (o) {
  234. if (arguments.length > 1) {
  235. throw new Error('Object.create implementation only accepts the first parameter.');
  236. }
  237. function F() {}
  238. F.prototype = o;
  239. return new F();
  240. };
  241. }
  242. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  243. if (!Function.prototype.bind) {
  244. Function.prototype.bind = function (oThis) {
  245. if (typeof this !== "function") {
  246. // closest thing possible to the ECMAScript 5 internal IsCallable function
  247. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  248. }
  249. var aArgs = Array.prototype.slice.call(arguments, 1),
  250. fToBind = this,
  251. fNOP = function () {},
  252. fBound = function () {
  253. return fToBind.apply(this instanceof fNOP && oThis
  254. ? this
  255. : oThis,
  256. aArgs.concat(Array.prototype.slice.call(arguments)));
  257. };
  258. fNOP.prototype = this.prototype;
  259. fBound.prototype = new fNOP();
  260. return fBound;
  261. };
  262. }
  263. /**
  264. * utility functions
  265. */
  266. var util = {};
  267. /**
  268. * Test whether given object is a number
  269. * @param {*} object
  270. * @return {Boolean} isNumber
  271. */
  272. util.isNumber = function isNumber(object) {
  273. return (object instanceof Number || typeof object == 'number');
  274. };
  275. /**
  276. * Test whether given object is a string
  277. * @param {*} object
  278. * @return {Boolean} isString
  279. */
  280. util.isString = function isString(object) {
  281. return (object instanceof String || typeof object == 'string');
  282. };
  283. /**
  284. * Test whether given object is a Date, or a String containing a Date
  285. * @param {Date | String} object
  286. * @return {Boolean} isDate
  287. */
  288. util.isDate = function isDate(object) {
  289. if (object instanceof Date) {
  290. return true;
  291. }
  292. else if (util.isString(object)) {
  293. // test whether this string contains a date
  294. var match = ASPDateRegex.exec(object);
  295. if (match) {
  296. return true;
  297. }
  298. else if (!isNaN(Date.parse(object))) {
  299. return true;
  300. }
  301. }
  302. return false;
  303. };
  304. /**
  305. * Test whether given object is an instance of google.visualization.DataTable
  306. * @param {*} object
  307. * @return {Boolean} isDataTable
  308. */
  309. util.isDataTable = function isDataTable(object) {
  310. return (typeof (google) !== 'undefined') &&
  311. (google.visualization) &&
  312. (google.visualization.DataTable) &&
  313. (object instanceof google.visualization.DataTable);
  314. };
  315. /**
  316. * Create a semi UUID
  317. * source: http://stackoverflow.com/a/105074/1262753
  318. * @return {String} uuid
  319. */
  320. util.randomUUID = function randomUUID () {
  321. var S4 = function () {
  322. return Math.floor(
  323. Math.random() * 0x10000 /* 65536 */
  324. ).toString(16);
  325. };
  326. return (
  327. S4() + S4() + '-' +
  328. S4() + '-' +
  329. S4() + '-' +
  330. S4() + '-' +
  331. S4() + S4() + S4()
  332. );
  333. };
  334. /**
  335. * Extend object a with the properties of object b or a series of objects
  336. * Only properties with defined values are copied
  337. * @param {Object} a
  338. * @param {... Object} b
  339. * @return {Object} a
  340. */
  341. util.extend = function (a, b) {
  342. for (var i = 1, len = arguments.length; i < len; i++) {
  343. var other = arguments[i];
  344. for (var prop in other) {
  345. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  346. a[prop] = other[prop];
  347. }
  348. }
  349. }
  350. return a;
  351. };
  352. /**
  353. * Test whether all elements in two arrays are equal.
  354. * @param {Array} a
  355. * @param {Array} b
  356. * @return {boolean} Returns true if both arrays have the same length and same
  357. * elements.
  358. */
  359. util.equalArray = function (a, b) {
  360. if (a.length != b.length) return false;
  361. for (var i = 0, len = a.length; i < len; i++) {
  362. if (a[i] != b[i]) return false;
  363. }
  364. return true;
  365. };
  366. /**
  367. * Convert an object to another type
  368. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  369. * @param {String | undefined} type Name of the type. Available types:
  370. * 'Boolean', 'Number', 'String',
  371. * 'Date', 'Moment', ISODate', 'ASPDate'.
  372. * @return {*} object
  373. * @throws Error
  374. */
  375. util.convert = function convert(object, type) {
  376. var match;
  377. if (object === undefined) {
  378. return undefined;
  379. }
  380. if (object === null) {
  381. return null;
  382. }
  383. if (!type) {
  384. return object;
  385. }
  386. if (!(typeof type === 'string') && !(type instanceof String)) {
  387. throw new Error('Type must be a string');
  388. }
  389. //noinspection FallthroughInSwitchStatementJS
  390. switch (type) {
  391. case 'boolean':
  392. case 'Boolean':
  393. return Boolean(object);
  394. case 'number':
  395. case 'Number':
  396. return Number(object.valueOf());
  397. case 'string':
  398. case 'String':
  399. return String(object);
  400. case 'Date':
  401. if (util.isNumber(object)) {
  402. return new Date(object);
  403. }
  404. if (object instanceof Date) {
  405. return new Date(object.valueOf());
  406. }
  407. else if (moment.isMoment(object)) {
  408. return new Date(object.valueOf());
  409. }
  410. if (util.isString(object)) {
  411. match = ASPDateRegex.exec(object);
  412. if (match) {
  413. // object is an ASP date
  414. return new Date(Number(match[1])); // parse number
  415. }
  416. else {
  417. return moment(object).toDate(); // parse string
  418. }
  419. }
  420. else {
  421. throw new Error(
  422. 'Cannot convert object of type ' + util.getType(object) +
  423. ' to type Date');
  424. }
  425. case 'Moment':
  426. if (util.isNumber(object)) {
  427. return moment(object);
  428. }
  429. if (object instanceof Date) {
  430. return moment(object.valueOf());
  431. }
  432. else if (moment.isMoment(object)) {
  433. return moment(object);
  434. }
  435. if (util.isString(object)) {
  436. match = ASPDateRegex.exec(object);
  437. if (match) {
  438. // object is an ASP date
  439. return moment(Number(match[1])); // parse number
  440. }
  441. else {
  442. return moment(object); // parse string
  443. }
  444. }
  445. else {
  446. throw new Error(
  447. 'Cannot convert object of type ' + util.getType(object) +
  448. ' to type Date');
  449. }
  450. case 'ISODate':
  451. if (util.isNumber(object)) {
  452. return new Date(object);
  453. }
  454. else if (object instanceof Date) {
  455. return object.toISOString();
  456. }
  457. else if (moment.isMoment(object)) {
  458. return object.toDate().toISOString();
  459. }
  460. else if (util.isString(object)) {
  461. match = ASPDateRegex.exec(object);
  462. if (match) {
  463. // object is an ASP date
  464. return new Date(Number(match[1])).toISOString(); // parse number
  465. }
  466. else {
  467. return new Date(object).toISOString(); // parse string
  468. }
  469. }
  470. else {
  471. throw new Error(
  472. 'Cannot convert object of type ' + util.getType(object) +
  473. ' to type ISODate');
  474. }
  475. case 'ASPDate':
  476. if (util.isNumber(object)) {
  477. return '/Date(' + object + ')/';
  478. }
  479. else if (object instanceof Date) {
  480. return '/Date(' + object.valueOf() + ')/';
  481. }
  482. else if (util.isString(object)) {
  483. match = ASPDateRegex.exec(object);
  484. var value;
  485. if (match) {
  486. // object is an ASP date
  487. value = new Date(Number(match[1])).valueOf(); // parse number
  488. }
  489. else {
  490. value = new Date(object).valueOf(); // parse string
  491. }
  492. return '/Date(' + value + ')/';
  493. }
  494. else {
  495. throw new Error(
  496. 'Cannot convert object of type ' + util.getType(object) +
  497. ' to type ASPDate');
  498. }
  499. default:
  500. throw new Error('Cannot convert object of type ' + util.getType(object) +
  501. ' to type "' + type + '"');
  502. }
  503. };
  504. // parse ASP.Net Date pattern,
  505. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  506. // code from http://momentjs.com/
  507. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  508. /**
  509. * Get the type of an object, for example util.getType([]) returns 'Array'
  510. * @param {*} object
  511. * @return {String} type
  512. */
  513. util.getType = function getType(object) {
  514. var type = typeof object;
  515. if (type == 'object') {
  516. if (object == null) {
  517. return 'null';
  518. }
  519. if (object instanceof Boolean) {
  520. return 'Boolean';
  521. }
  522. if (object instanceof Number) {
  523. return 'Number';
  524. }
  525. if (object instanceof String) {
  526. return 'String';
  527. }
  528. if (object instanceof Array) {
  529. return 'Array';
  530. }
  531. if (object instanceof Date) {
  532. return 'Date';
  533. }
  534. return 'Object';
  535. }
  536. else if (type == 'number') {
  537. return 'Number';
  538. }
  539. else if (type == 'boolean') {
  540. return 'Boolean';
  541. }
  542. else if (type == 'string') {
  543. return 'String';
  544. }
  545. return type;
  546. };
  547. /**
  548. * Retrieve the absolute left value of a DOM element
  549. * @param {Element} elem A dom element, for example a div
  550. * @return {number} left The absolute left position of this element
  551. * in the browser page.
  552. */
  553. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  554. var doc = document.documentElement;
  555. var body = document.body;
  556. var left = elem.offsetLeft;
  557. var e = elem.offsetParent;
  558. while (e != null && e != body && e != doc) {
  559. left += e.offsetLeft;
  560. left -= e.scrollLeft;
  561. e = e.offsetParent;
  562. }
  563. return left;
  564. };
  565. /**
  566. * Retrieve the absolute top value of a DOM element
  567. * @param {Element} elem A dom element, for example a div
  568. * @return {number} top The absolute top position of this element
  569. * in the browser page.
  570. */
  571. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  572. var doc = document.documentElement;
  573. var body = document.body;
  574. var top = elem.offsetTop;
  575. var e = elem.offsetParent;
  576. while (e != null && e != body && e != doc) {
  577. top += e.offsetTop;
  578. top -= e.scrollTop;
  579. e = e.offsetParent;
  580. }
  581. return top;
  582. };
  583. /**
  584. * Get the absolute, vertical mouse position from an event.
  585. * @param {Event} event
  586. * @return {Number} pageY
  587. */
  588. util.getPageY = function getPageY (event) {
  589. if ('pageY' in event) {
  590. return event.pageY;
  591. }
  592. else {
  593. var clientY;
  594. if (('targetTouches' in event) && event.targetTouches.length) {
  595. clientY = event.targetTouches[0].clientY;
  596. }
  597. else {
  598. clientY = event.clientY;
  599. }
  600. var doc = document.documentElement;
  601. var body = document.body;
  602. return clientY +
  603. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  604. ( doc && doc.clientTop || body && body.clientTop || 0 );
  605. }
  606. };
  607. /**
  608. * Get the absolute, horizontal mouse position from an event.
  609. * @param {Event} event
  610. * @return {Number} pageX
  611. */
  612. util.getPageX = function getPageX (event) {
  613. if ('pageY' in event) {
  614. return event.pageX;
  615. }
  616. else {
  617. var clientX;
  618. if (('targetTouches' in event) && event.targetTouches.length) {
  619. clientX = event.targetTouches[0].clientX;
  620. }
  621. else {
  622. clientX = event.clientX;
  623. }
  624. var doc = document.documentElement;
  625. var body = document.body;
  626. return clientX +
  627. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  628. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  629. }
  630. };
  631. /**
  632. * add a className to the given elements style
  633. * @param {Element} elem
  634. * @param {String} className
  635. */
  636. util.addClassName = function addClassName(elem, className) {
  637. var classes = elem.className.split(' ');
  638. if (classes.indexOf(className) == -1) {
  639. classes.push(className); // add the class to the array
  640. elem.className = classes.join(' ');
  641. }
  642. };
  643. /**
  644. * add a className to the given elements style
  645. * @param {Element} elem
  646. * @param {String} className
  647. */
  648. util.removeClassName = function removeClassname(elem, className) {
  649. var classes = elem.className.split(' ');
  650. var index = classes.indexOf(className);
  651. if (index != -1) {
  652. classes.splice(index, 1); // remove the class from the array
  653. elem.className = classes.join(' ');
  654. }
  655. };
  656. /**
  657. * For each method for both arrays and objects.
  658. * In case of an array, the built-in Array.forEach() is applied.
  659. * In case of an Object, the method loops over all properties of the object.
  660. * @param {Object | Array} object An Object or Array
  661. * @param {function} callback Callback method, called for each item in
  662. * the object or array with three parameters:
  663. * callback(value, index, object)
  664. */
  665. util.forEach = function forEach (object, callback) {
  666. var i,
  667. len;
  668. if (object instanceof Array) {
  669. // array
  670. for (i = 0, len = object.length; i < len; i++) {
  671. callback(object[i], i, object);
  672. }
  673. }
  674. else {
  675. // object
  676. for (i in object) {
  677. if (object.hasOwnProperty(i)) {
  678. callback(object[i], i, object);
  679. }
  680. }
  681. }
  682. };
  683. /**
  684. * Convert an object into an array: all objects properties are put into the
  685. * array. The resulting array is unordered.
  686. * @param {Object} object
  687. * @param {Array} array
  688. */
  689. util.toArray = function toArray(object) {
  690. var array = [];
  691. for (var prop in object) {
  692. if (object.hasOwnProperty(prop)) array.push(object[prop]);
  693. }
  694. return array;
  695. }
  696. /**
  697. * Update a property in an object
  698. * @param {Object} object
  699. * @param {String} key
  700. * @param {*} value
  701. * @return {Boolean} changed
  702. */
  703. util.updateProperty = function updateProperty (object, key, value) {
  704. if (object[key] !== value) {
  705. object[key] = value;
  706. return true;
  707. }
  708. else {
  709. return false;
  710. }
  711. };
  712. /**
  713. * Add and event listener. Works for all browsers
  714. * @param {Element} element An html element
  715. * @param {string} action The action, for example "click",
  716. * without the prefix "on"
  717. * @param {function} listener The callback function to be executed
  718. * @param {boolean} [useCapture]
  719. */
  720. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  721. if (element.addEventListener) {
  722. if (useCapture === undefined)
  723. useCapture = false;
  724. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  725. action = "DOMMouseScroll"; // For Firefox
  726. }
  727. element.addEventListener(action, listener, useCapture);
  728. } else {
  729. element.attachEvent("on" + action, listener); // IE browsers
  730. }
  731. };
  732. /**
  733. * Remove an event listener from an element
  734. * @param {Element} element An html dom element
  735. * @param {string} action The name of the event, for example "mousedown"
  736. * @param {function} listener The listener function
  737. * @param {boolean} [useCapture]
  738. */
  739. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  740. if (element.removeEventListener) {
  741. // non-IE browsers
  742. if (useCapture === undefined)
  743. useCapture = false;
  744. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  745. action = "DOMMouseScroll"; // For Firefox
  746. }
  747. element.removeEventListener(action, listener, useCapture);
  748. } else {
  749. // IE browsers
  750. element.detachEvent("on" + action, listener);
  751. }
  752. };
  753. /**
  754. * Get HTML element which is the target of the event
  755. * @param {Event} event
  756. * @return {Element} target element
  757. */
  758. util.getTarget = function getTarget(event) {
  759. // code from http://www.quirksmode.org/js/events_properties.html
  760. if (!event) {
  761. event = window.event;
  762. }
  763. var target;
  764. if (event.target) {
  765. target = event.target;
  766. }
  767. else if (event.srcElement) {
  768. target = event.srcElement;
  769. }
  770. if (target.nodeType != undefined && target.nodeType == 3) {
  771. // defeat Safari bug
  772. target = target.parentNode;
  773. }
  774. return target;
  775. };
  776. /**
  777. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  778. * @param {Element} element
  779. * @param {Event} event
  780. */
  781. util.fakeGesture = function fakeGesture (element, event) {
  782. var eventType = null;
  783. // for hammer.js 1.0.5
  784. var gesture = Hammer.event.collectEventData(this, eventType, event);
  785. // for hammer.js 1.0.6
  786. //var touches = Hammer.event.getTouchList(event, eventType);
  787. // var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  788. // on IE in standards mode, no touches are recognized by hammer.js,
  789. // resulting in NaN values for center.pageX and center.pageY
  790. if (isNaN(gesture.center.pageX)) {
  791. gesture.center.pageX = event.pageX;
  792. }
  793. if (isNaN(gesture.center.pageY)) {
  794. gesture.center.pageY = event.pageY;
  795. }
  796. return gesture;
  797. };
  798. util.option = {};
  799. /**
  800. * Convert a value into a boolean
  801. * @param {Boolean | function | undefined} value
  802. * @param {Boolean} [defaultValue]
  803. * @returns {Boolean} bool
  804. */
  805. util.option.asBoolean = function (value, defaultValue) {
  806. if (typeof value == 'function') {
  807. value = value();
  808. }
  809. if (value != null) {
  810. return (value != false);
  811. }
  812. return defaultValue || null;
  813. };
  814. /**
  815. * Convert a value into a number
  816. * @param {Boolean | function | undefined} value
  817. * @param {Number} [defaultValue]
  818. * @returns {Number} number
  819. */
  820. util.option.asNumber = function (value, defaultValue) {
  821. if (typeof value == 'function') {
  822. value = value();
  823. }
  824. if (value != null) {
  825. return Number(value) || defaultValue || null;
  826. }
  827. return defaultValue || null;
  828. };
  829. /**
  830. * Convert a value into a string
  831. * @param {String | function | undefined} value
  832. * @param {String} [defaultValue]
  833. * @returns {String} str
  834. */
  835. util.option.asString = function (value, defaultValue) {
  836. if (typeof value == 'function') {
  837. value = value();
  838. }
  839. if (value != null) {
  840. return String(value);
  841. }
  842. return defaultValue || null;
  843. };
  844. /**
  845. * Convert a size or location into a string with pixels or a percentage
  846. * @param {String | Number | function | undefined} value
  847. * @param {String} [defaultValue]
  848. * @returns {String} size
  849. */
  850. util.option.asSize = function (value, defaultValue) {
  851. if (typeof value == 'function') {
  852. value = value();
  853. }
  854. if (util.isString(value)) {
  855. return value;
  856. }
  857. else if (util.isNumber(value)) {
  858. return value + 'px';
  859. }
  860. else {
  861. return defaultValue || null;
  862. }
  863. };
  864. /**
  865. * Convert a value into a DOM element
  866. * @param {HTMLElement | function | undefined} value
  867. * @param {HTMLElement} [defaultValue]
  868. * @returns {HTMLElement | null} dom
  869. */
  870. util.option.asElement = function (value, defaultValue) {
  871. if (typeof value == 'function') {
  872. value = value();
  873. }
  874. return value || defaultValue || null;
  875. };
  876. util.GiveDec = function GiveDec(Hex) {
  877. var Value;
  878. if (Hex == "A")
  879. Value = 10;
  880. else if (Hex == "B")
  881. Value = 11;
  882. else if (Hex == "C")
  883. Value = 12;
  884. else if (Hex == "D")
  885. Value = 13;
  886. else if (Hex == "E")
  887. Value = 14;
  888. else if (Hex == "F")
  889. Value = 15;
  890. else
  891. Value = eval(Hex);
  892. return Value;
  893. };
  894. util.GiveHex = function GiveHex(Dec) {
  895. var Value;
  896. if(Dec == 10)
  897. Value = "A";
  898. else if (Dec == 11)
  899. Value = "B";
  900. else if (Dec == 12)
  901. Value = "C";
  902. else if (Dec == 13)
  903. Value = "D";
  904. else if (Dec == 14)
  905. Value = "E";
  906. else if (Dec == 15)
  907. Value = "F";
  908. else
  909. Value = "" + Dec;
  910. return Value;
  911. };
  912. /**
  913. * Parse a color property into an object with border, background, and
  914. * highlight colors
  915. * @param {Object | String} color
  916. * @return {Object} colorObject
  917. */
  918. util.parseColor = function(color) {
  919. var c;
  920. if (util.isString(color)) {
  921. if (util.isValidHex(color)) {
  922. var hsv = util.hexToHSV(color);
  923. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  924. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  925. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  926. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  927. c = {
  928. background: color,
  929. border:darkerColorHex,
  930. highlight: {
  931. background:lighterColorHex,
  932. border:darkerColorHex
  933. }
  934. };
  935. }
  936. else {
  937. c = {
  938. background:color,
  939. border:color,
  940. highlight: {
  941. background:color,
  942. border:color
  943. }
  944. };
  945. }
  946. }
  947. else {
  948. c = {};
  949. c.background = color.background || 'white';
  950. c.border = color.border || c.background;
  951. if (util.isString(color.highlight)) {
  952. c.highlight = {
  953. border: color.highlight,
  954. background: color.highlight
  955. }
  956. }
  957. else {
  958. c.highlight = {};
  959. c.highlight.background = color.highlight && color.highlight.background || c.background;
  960. c.highlight.border = color.highlight && color.highlight.border || c.border;
  961. }
  962. }
  963. return c;
  964. };
  965. /**
  966. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  967. *
  968. * @param {String} hex
  969. * @returns {{r: *, g: *, b: *}}
  970. */
  971. util.hexToRGB = function hexToRGB(hex) {
  972. hex = hex.replace("#","").toUpperCase();
  973. var a = util.GiveDec(hex.substring(0, 1));
  974. var b = util.GiveDec(hex.substring(1, 2));
  975. var c = util.GiveDec(hex.substring(2, 3));
  976. var d = util.GiveDec(hex.substring(3, 4));
  977. var e = util.GiveDec(hex.substring(4, 5));
  978. var f = util.GiveDec(hex.substring(5, 6));
  979. var r = (a * 16) + b;
  980. var g = (c * 16) + d;
  981. var b = (e * 16) + f;
  982. return {r:r,g:g,b:b};
  983. };
  984. util.RGBToHex = function RGBToHex(red,green,blue) {
  985. var a = util.GiveHex(Math.floor(red / 16));
  986. var b = util.GiveHex(red % 16);
  987. var c = util.GiveHex(Math.floor(green / 16));
  988. var d = util.GiveHex(green % 16);
  989. var e = util.GiveHex(Math.floor(blue / 16));
  990. var f = util.GiveHex(blue % 16);
  991. var hex = a + b + c + d + e + f;
  992. return "#" + hex;
  993. };
  994. /**
  995. * http://www.javascripter.net/faq/rgb2hsv.htm
  996. *
  997. * @param red
  998. * @param green
  999. * @param blue
  1000. * @returns {*}
  1001. * @constructor
  1002. */
  1003. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  1004. red=red/255; green=green/255; blue=blue/255;
  1005. var minRGB = Math.min(red,Math.min(green,blue));
  1006. var maxRGB = Math.max(red,Math.max(green,blue));
  1007. // Black-gray-white
  1008. if (minRGB == maxRGB) {
  1009. return {h:0,s:0,v:minRGB};
  1010. }
  1011. // Colors other than black-gray-white:
  1012. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  1013. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  1014. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  1015. var saturation = (maxRGB - minRGB)/maxRGB;
  1016. var value = maxRGB;
  1017. return {h:hue,s:saturation,v:value};
  1018. };
  1019. /**
  1020. * https://gist.github.com/mjijackson/5311256
  1021. * @param hue
  1022. * @param saturation
  1023. * @param value
  1024. * @returns {{r: number, g: number, b: number}}
  1025. * @constructor
  1026. */
  1027. util.HSVToRGB = function HSVToRGB(h, s, v) {
  1028. var r, g, b;
  1029. var i = Math.floor(h * 6);
  1030. var f = h * 6 - i;
  1031. var p = v * (1 - s);
  1032. var q = v * (1 - f * s);
  1033. var t = v * (1 - (1 - f) * s);
  1034. switch (i % 6) {
  1035. case 0: r = v, g = t, b = p; break;
  1036. case 1: r = q, g = v, b = p; break;
  1037. case 2: r = p, g = v, b = t; break;
  1038. case 3: r = p, g = q, b = v; break;
  1039. case 4: r = t, g = p, b = v; break;
  1040. case 5: r = v, g = p, b = q; break;
  1041. }
  1042. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  1043. };
  1044. util.HSVToHex = function HSVToHex(h, s, v) {
  1045. var rgb = util.HSVToRGB(h, s, v);
  1046. return util.RGBToHex(rgb.r, rgb.g, rgb.b);
  1047. };
  1048. util.hexToHSV = function hexToHSV(hex) {
  1049. var rgb = util.hexToRGB(hex);
  1050. return util.RGBToHSV(rgb.r, rgb.g, rgb.b);
  1051. };
  1052. util.isValidHex = function isValidHex(hex) {
  1053. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1054. return isOk;
  1055. };
  1056. util.copyObject = function copyObject(objectFrom, objectTo) {
  1057. for (var i in objectFrom) {
  1058. if (objectFrom.hasOwnProperty(i)) {
  1059. if (typeof objectFrom[i] == "object") {
  1060. objectTo[i] = {};
  1061. util.copyObject(objectFrom[i], objectTo[i]);
  1062. }
  1063. else {
  1064. objectTo[i] = objectFrom[i];
  1065. }
  1066. }
  1067. }
  1068. };
  1069. /**
  1070. * DataSet
  1071. *
  1072. * Usage:
  1073. * var dataSet = new DataSet({
  1074. * fieldId: '_id',
  1075. * convert: {
  1076. * // ...
  1077. * }
  1078. * });
  1079. *
  1080. * dataSet.add(item);
  1081. * dataSet.add(data);
  1082. * dataSet.update(item);
  1083. * dataSet.update(data);
  1084. * dataSet.remove(id);
  1085. * dataSet.remove(ids);
  1086. * var data = dataSet.get();
  1087. * var data = dataSet.get(id);
  1088. * var data = dataSet.get(ids);
  1089. * var data = dataSet.get(ids, options, data);
  1090. * dataSet.clear();
  1091. *
  1092. * A data set can:
  1093. * - add/remove/update data
  1094. * - gives triggers upon changes in the data
  1095. * - can import/export data in various data formats
  1096. *
  1097. * @param {Array | DataTable} [data] Optional array with initial data
  1098. * @param {Object} [options] Available options:
  1099. * {String} fieldId Field name of the id in the
  1100. * items, 'id' by default.
  1101. * {Object.<String, String} convert
  1102. * A map with field names as key,
  1103. * and the field type as value.
  1104. * @constructor DataSet
  1105. */
  1106. // TODO: add a DataSet constructor DataSet(data, options)
  1107. function DataSet (data, options) {
  1108. this.id = util.randomUUID();
  1109. // correctly read optional arguments
  1110. if (data && !Array.isArray(data) && !util.isDataTable(data)) {
  1111. options = data;
  1112. data = null;
  1113. }
  1114. this.options = options || {};
  1115. this.data = {}; // map with data indexed by id
  1116. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1117. this.convert = {}; // field types by field name
  1118. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1119. if (this.options.convert) {
  1120. for (var field in this.options.convert) {
  1121. if (this.options.convert.hasOwnProperty(field)) {
  1122. var value = this.options.convert[field];
  1123. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1124. this.convert[field] = 'Date';
  1125. }
  1126. else {
  1127. this.convert[field] = value;
  1128. }
  1129. }
  1130. }
  1131. }
  1132. this.subscribers = {}; // event subscribers
  1133. this.internalIds = {}; // internally generated id's
  1134. // add initial data when provided
  1135. if (data) {
  1136. this.add(data);
  1137. }
  1138. }
  1139. /**
  1140. * Subscribe to an event, add an event listener
  1141. * @param {String} event Event name. Available events: 'put', 'update',
  1142. * 'remove'
  1143. * @param {function} callback Callback method. Called with three parameters:
  1144. * {String} event
  1145. * {Object | null} params
  1146. * {String | Number} senderId
  1147. */
  1148. DataSet.prototype.on = function on (event, callback) {
  1149. var subscribers = this.subscribers[event];
  1150. if (!subscribers) {
  1151. subscribers = [];
  1152. this.subscribers[event] = subscribers;
  1153. }
  1154. subscribers.push({
  1155. callback: callback
  1156. });
  1157. };
  1158. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1159. DataSet.prototype.subscribe = DataSet.prototype.on;
  1160. /**
  1161. * Unsubscribe from an event, remove an event listener
  1162. * @param {String} event
  1163. * @param {function} callback
  1164. */
  1165. DataSet.prototype.off = function off(event, callback) {
  1166. var subscribers = this.subscribers[event];
  1167. if (subscribers) {
  1168. this.subscribers[event] = subscribers.filter(function (listener) {
  1169. return (listener.callback != callback);
  1170. });
  1171. }
  1172. };
  1173. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1174. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1175. /**
  1176. * Trigger an event
  1177. * @param {String} event
  1178. * @param {Object | null} params
  1179. * @param {String} [senderId] Optional id of the sender.
  1180. * @private
  1181. */
  1182. DataSet.prototype._trigger = function (event, params, senderId) {
  1183. if (event == '*') {
  1184. throw new Error('Cannot trigger event *');
  1185. }
  1186. var subscribers = [];
  1187. if (event in this.subscribers) {
  1188. subscribers = subscribers.concat(this.subscribers[event]);
  1189. }
  1190. if ('*' in this.subscribers) {
  1191. subscribers = subscribers.concat(this.subscribers['*']);
  1192. }
  1193. for (var i = 0; i < subscribers.length; i++) {
  1194. var subscriber = subscribers[i];
  1195. if (subscriber.callback) {
  1196. subscriber.callback(event, params, senderId || null);
  1197. }
  1198. }
  1199. };
  1200. /**
  1201. * Add data.
  1202. * Adding an item will fail when there already is an item with the same id.
  1203. * @param {Object | Array | DataTable} data
  1204. * @param {String} [senderId] Optional sender id
  1205. * @return {Array} addedIds Array with the ids of the added items
  1206. */
  1207. DataSet.prototype.add = function (data, senderId) {
  1208. var addedIds = [],
  1209. id,
  1210. me = this;
  1211. if (data instanceof Array) {
  1212. // Array
  1213. for (var i = 0, len = data.length; i < len; i++) {
  1214. id = me._addItem(data[i]);
  1215. addedIds.push(id);
  1216. }
  1217. }
  1218. else if (util.isDataTable(data)) {
  1219. // Google DataTable
  1220. var columns = this._getColumnNames(data);
  1221. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1222. var item = {};
  1223. for (var col = 0, cols = columns.length; col < cols; col++) {
  1224. var field = columns[col];
  1225. item[field] = data.getValue(row, col);
  1226. }
  1227. id = me._addItem(item);
  1228. addedIds.push(id);
  1229. }
  1230. }
  1231. else if (data instanceof Object) {
  1232. // Single item
  1233. id = me._addItem(data);
  1234. addedIds.push(id);
  1235. }
  1236. else {
  1237. throw new Error('Unknown dataType');
  1238. }
  1239. if (addedIds.length) {
  1240. this._trigger('add', {items: addedIds}, senderId);
  1241. }
  1242. return addedIds;
  1243. };
  1244. /**
  1245. * Update existing items. When an item does not exist, it will be created
  1246. * @param {Object | Array | DataTable} data
  1247. * @param {String} [senderId] Optional sender id
  1248. * @return {Array} updatedIds The ids of the added or updated items
  1249. */
  1250. DataSet.prototype.update = function (data, senderId) {
  1251. var addedIds = [],
  1252. updatedIds = [],
  1253. me = this,
  1254. fieldId = me.fieldId;
  1255. var addOrUpdate = function (item) {
  1256. var id = item[fieldId];
  1257. if (me.data[id]) {
  1258. // update item
  1259. id = me._updateItem(item);
  1260. updatedIds.push(id);
  1261. }
  1262. else {
  1263. // add new item
  1264. id = me._addItem(item);
  1265. addedIds.push(id);
  1266. }
  1267. };
  1268. if (data instanceof Array) {
  1269. // Array
  1270. for (var i = 0, len = data.length; i < len; i++) {
  1271. addOrUpdate(data[i]);
  1272. }
  1273. }
  1274. else if (util.isDataTable(data)) {
  1275. // Google DataTable
  1276. var columns = this._getColumnNames(data);
  1277. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1278. var item = {};
  1279. for (var col = 0, cols = columns.length; col < cols; col++) {
  1280. var field = columns[col];
  1281. item[field] = data.getValue(row, col);
  1282. }
  1283. addOrUpdate(item);
  1284. }
  1285. }
  1286. else if (data instanceof Object) {
  1287. // Single item
  1288. addOrUpdate(data);
  1289. }
  1290. else {
  1291. throw new Error('Unknown dataType');
  1292. }
  1293. if (addedIds.length) {
  1294. this._trigger('add', {items: addedIds}, senderId);
  1295. }
  1296. if (updatedIds.length) {
  1297. this._trigger('update', {items: updatedIds}, senderId);
  1298. }
  1299. return addedIds.concat(updatedIds);
  1300. };
  1301. /**
  1302. * Get a data item or multiple items.
  1303. *
  1304. * Usage:
  1305. *
  1306. * get()
  1307. * get(options: Object)
  1308. * get(options: Object, data: Array | DataTable)
  1309. *
  1310. * get(id: Number | String)
  1311. * get(id: Number | String, options: Object)
  1312. * get(id: Number | String, options: Object, data: Array | DataTable)
  1313. *
  1314. * get(ids: Number[] | String[])
  1315. * get(ids: Number[] | String[], options: Object)
  1316. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1317. *
  1318. * Where:
  1319. *
  1320. * {Number | String} id The id of an item
  1321. * {Number[] | String{}} ids An array with ids of items
  1322. * {Object} options An Object with options. Available options:
  1323. * {String} [type] Type of data to be returned. Can
  1324. * be 'DataTable' or 'Array' (default)
  1325. * {Object.<String, String>} [convert]
  1326. * {String[]} [fields] field names to be returned
  1327. * {function} [filter] filter items
  1328. * {String | function} [order] Order the items by
  1329. * a field name or custom sort function.
  1330. * {Array | DataTable} [data] If provided, items will be appended to this
  1331. * array or table. Required in case of Google
  1332. * DataTable.
  1333. *
  1334. * @throws Error
  1335. */
  1336. DataSet.prototype.get = function (args) {
  1337. var me = this;
  1338. var globalShowInternalIds = this.showInternalIds;
  1339. // parse the arguments
  1340. var id, ids, options, data;
  1341. var firstType = util.getType(arguments[0]);
  1342. if (firstType == 'String' || firstType == 'Number') {
  1343. // get(id [, options] [, data])
  1344. id = arguments[0];
  1345. options = arguments[1];
  1346. data = arguments[2];
  1347. }
  1348. else if (firstType == 'Array') {
  1349. // get(ids [, options] [, data])
  1350. ids = arguments[0];
  1351. options = arguments[1];
  1352. data = arguments[2];
  1353. }
  1354. else {
  1355. // get([, options] [, data])
  1356. options = arguments[0];
  1357. data = arguments[1];
  1358. }
  1359. // determine the return type
  1360. var type;
  1361. if (options && options.type) {
  1362. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1363. if (data && (type != util.getType(data))) {
  1364. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1365. 'does not correspond with specified options.type (' + options.type + ')');
  1366. }
  1367. if (type == 'DataTable' && !util.isDataTable(data)) {
  1368. throw new Error('Parameter "data" must be a DataTable ' +
  1369. 'when options.type is "DataTable"');
  1370. }
  1371. }
  1372. else if (data) {
  1373. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1374. }
  1375. else {
  1376. type = 'Array';
  1377. }
  1378. // we allow the setting of this value for a single get request.
  1379. if (options != undefined) {
  1380. if (options.showInternalIds != undefined) {
  1381. this.showInternalIds = options.showInternalIds;
  1382. }
  1383. }
  1384. // build options
  1385. var convert = options && options.convert || this.options.convert;
  1386. var filter = options && options.filter;
  1387. var items = [], item, itemId, i, len;
  1388. // convert items
  1389. if (id != undefined) {
  1390. // return a single item
  1391. item = me._getItem(id, convert);
  1392. if (filter && !filter(item)) {
  1393. item = null;
  1394. }
  1395. }
  1396. else if (ids != undefined) {
  1397. // return a subset of items
  1398. for (i = 0, len = ids.length; i < len; i++) {
  1399. item = me._getItem(ids[i], convert);
  1400. if (!filter || filter(item)) {
  1401. items.push(item);
  1402. }
  1403. }
  1404. }
  1405. else {
  1406. // return all items
  1407. for (itemId in this.data) {
  1408. if (this.data.hasOwnProperty(itemId)) {
  1409. item = me._getItem(itemId, convert);
  1410. if (!filter || filter(item)) {
  1411. items.push(item);
  1412. }
  1413. }
  1414. }
  1415. }
  1416. // restore the global value of showInternalIds
  1417. this.showInternalIds = globalShowInternalIds;
  1418. // order the results
  1419. if (options && options.order && id == undefined) {
  1420. this._sort(items, options.order);
  1421. }
  1422. // filter fields of the items
  1423. if (options && options.fields) {
  1424. var fields = options.fields;
  1425. if (id != undefined) {
  1426. item = this._filterFields(item, fields);
  1427. }
  1428. else {
  1429. for (i = 0, len = items.length; i < len; i++) {
  1430. items[i] = this._filterFields(items[i], fields);
  1431. }
  1432. }
  1433. }
  1434. // return the results
  1435. if (type == 'DataTable') {
  1436. var columns = this._getColumnNames(data);
  1437. if (id != undefined) {
  1438. // append a single item to the data table
  1439. me._appendRow(data, columns, item);
  1440. }
  1441. else {
  1442. // copy the items to the provided data table
  1443. for (i = 0, len = items.length; i < len; i++) {
  1444. me._appendRow(data, columns, items[i]);
  1445. }
  1446. }
  1447. return data;
  1448. }
  1449. else {
  1450. // return an array
  1451. if (id != undefined) {
  1452. // a single item
  1453. return item;
  1454. }
  1455. else {
  1456. // multiple items
  1457. if (data) {
  1458. // copy the items to the provided array
  1459. for (i = 0, len = items.length; i < len; i++) {
  1460. data.push(items[i]);
  1461. }
  1462. return data;
  1463. }
  1464. else {
  1465. // just return our array
  1466. return items;
  1467. }
  1468. }
  1469. }
  1470. };
  1471. /**
  1472. * Get ids of all items or from a filtered set of items.
  1473. * @param {Object} [options] An Object with options. Available options:
  1474. * {function} [filter] filter items
  1475. * {String | function} [order] Order the items by
  1476. * a field name or custom sort function.
  1477. * @return {Array} ids
  1478. */
  1479. DataSet.prototype.getIds = function (options) {
  1480. var data = this.data,
  1481. filter = options && options.filter,
  1482. order = options && options.order,
  1483. convert = options && options.convert || this.options.convert,
  1484. i,
  1485. len,
  1486. id,
  1487. item,
  1488. items,
  1489. ids = [];
  1490. if (filter) {
  1491. // get filtered items
  1492. if (order) {
  1493. // create ordered list
  1494. items = [];
  1495. for (id in data) {
  1496. if (data.hasOwnProperty(id)) {
  1497. item = this._getItem(id, convert);
  1498. if (filter(item)) {
  1499. items.push(item);
  1500. }
  1501. }
  1502. }
  1503. this._sort(items, order);
  1504. for (i = 0, len = items.length; i < len; i++) {
  1505. ids[i] = items[i][this.fieldId];
  1506. }
  1507. }
  1508. else {
  1509. // create unordered list
  1510. for (id in data) {
  1511. if (data.hasOwnProperty(id)) {
  1512. item = this._getItem(id, convert);
  1513. if (filter(item)) {
  1514. ids.push(item[this.fieldId]);
  1515. }
  1516. }
  1517. }
  1518. }
  1519. }
  1520. else {
  1521. // get all items
  1522. if (order) {
  1523. // create an ordered list
  1524. items = [];
  1525. for (id in data) {
  1526. if (data.hasOwnProperty(id)) {
  1527. items.push(data[id]);
  1528. }
  1529. }
  1530. this._sort(items, order);
  1531. for (i = 0, len = items.length; i < len; i++) {
  1532. ids[i] = items[i][this.fieldId];
  1533. }
  1534. }
  1535. else {
  1536. // create unordered list
  1537. for (id in data) {
  1538. if (data.hasOwnProperty(id)) {
  1539. item = data[id];
  1540. ids.push(item[this.fieldId]);
  1541. }
  1542. }
  1543. }
  1544. }
  1545. return ids;
  1546. };
  1547. /**
  1548. * Execute a callback function for every item in the dataset.
  1549. * @param {function} callback
  1550. * @param {Object} [options] Available options:
  1551. * {Object.<String, String>} [convert]
  1552. * {String[]} [fields] filter fields
  1553. * {function} [filter] filter items
  1554. * {String | function} [order] Order the items by
  1555. * a field name or custom sort function.
  1556. */
  1557. DataSet.prototype.forEach = function (callback, options) {
  1558. var filter = options && options.filter,
  1559. convert = options && options.convert || this.options.convert,
  1560. data = this.data,
  1561. item,
  1562. id;
  1563. if (options && options.order) {
  1564. // execute forEach on ordered list
  1565. var items = this.get(options);
  1566. for (var i = 0, len = items.length; i < len; i++) {
  1567. item = items[i];
  1568. id = item[this.fieldId];
  1569. callback(item, id);
  1570. }
  1571. }
  1572. else {
  1573. // unordered
  1574. for (id in data) {
  1575. if (data.hasOwnProperty(id)) {
  1576. item = this._getItem(id, convert);
  1577. if (!filter || filter(item)) {
  1578. callback(item, id);
  1579. }
  1580. }
  1581. }
  1582. }
  1583. };
  1584. /**
  1585. * Map every item in the dataset.
  1586. * @param {function} callback
  1587. * @param {Object} [options] Available options:
  1588. * {Object.<String, String>} [convert]
  1589. * {String[]} [fields] filter fields
  1590. * {function} [filter] filter items
  1591. * {String | function} [order] Order the items by
  1592. * a field name or custom sort function.
  1593. * @return {Object[]} mappedItems
  1594. */
  1595. DataSet.prototype.map = function (callback, options) {
  1596. var filter = options && options.filter,
  1597. convert = options && options.convert || this.options.convert,
  1598. mappedItems = [],
  1599. data = this.data,
  1600. item;
  1601. // convert and filter items
  1602. for (var id in data) {
  1603. if (data.hasOwnProperty(id)) {
  1604. item = this._getItem(id, convert);
  1605. if (!filter || filter(item)) {
  1606. mappedItems.push(callback(item, id));
  1607. }
  1608. }
  1609. }
  1610. // order items
  1611. if (options && options.order) {
  1612. this._sort(mappedItems, options.order);
  1613. }
  1614. return mappedItems;
  1615. };
  1616. /**
  1617. * Filter the fields of an item
  1618. * @param {Object} item
  1619. * @param {String[]} fields Field names
  1620. * @return {Object} filteredItem
  1621. * @private
  1622. */
  1623. DataSet.prototype._filterFields = function (item, fields) {
  1624. var filteredItem = {};
  1625. for (var field in item) {
  1626. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1627. filteredItem[field] = item[field];
  1628. }
  1629. }
  1630. return filteredItem;
  1631. };
  1632. /**
  1633. * Sort the provided array with items
  1634. * @param {Object[]} items
  1635. * @param {String | function} order A field name or custom sort function.
  1636. * @private
  1637. */
  1638. DataSet.prototype._sort = function (items, order) {
  1639. if (util.isString(order)) {
  1640. // order by provided field name
  1641. var name = order; // field name
  1642. items.sort(function (a, b) {
  1643. var av = a[name];
  1644. var bv = b[name];
  1645. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1646. });
  1647. }
  1648. else if (typeof order === 'function') {
  1649. // order by sort function
  1650. items.sort(order);
  1651. }
  1652. // TODO: extend order by an Object {field:String, direction:String}
  1653. // where direction can be 'asc' or 'desc'
  1654. else {
  1655. throw new TypeError('Order must be a function or a string');
  1656. }
  1657. };
  1658. /**
  1659. * Remove an object by pointer or by id
  1660. * @param {String | Number | Object | Array} id Object or id, or an array with
  1661. * objects or ids to be removed
  1662. * @param {String} [senderId] Optional sender id
  1663. * @return {Array} removedIds
  1664. */
  1665. DataSet.prototype.remove = function (id, senderId) {
  1666. var removedIds = [],
  1667. i, len, removedId;
  1668. if (id instanceof Array) {
  1669. for (i = 0, len = id.length; i < len; i++) {
  1670. removedId = this._remove(id[i]);
  1671. if (removedId != null) {
  1672. removedIds.push(removedId);
  1673. }
  1674. }
  1675. }
  1676. else {
  1677. removedId = this._remove(id);
  1678. if (removedId != null) {
  1679. removedIds.push(removedId);
  1680. }
  1681. }
  1682. if (removedIds.length) {
  1683. this._trigger('remove', {items: removedIds}, senderId);
  1684. }
  1685. return removedIds;
  1686. };
  1687. /**
  1688. * Remove an item by its id
  1689. * @param {Number | String | Object} id id or item
  1690. * @returns {Number | String | null} id
  1691. * @private
  1692. */
  1693. DataSet.prototype._remove = function (id) {
  1694. if (util.isNumber(id) || util.isString(id)) {
  1695. if (this.data[id]) {
  1696. delete this.data[id];
  1697. delete this.internalIds[id];
  1698. return id;
  1699. }
  1700. }
  1701. else if (id instanceof Object) {
  1702. var itemId = id[this.fieldId];
  1703. if (itemId && this.data[itemId]) {
  1704. delete this.data[itemId];
  1705. delete this.internalIds[itemId];
  1706. return itemId;
  1707. }
  1708. }
  1709. return null;
  1710. };
  1711. /**
  1712. * Clear the data
  1713. * @param {String} [senderId] Optional sender id
  1714. * @return {Array} removedIds The ids of all removed items
  1715. */
  1716. DataSet.prototype.clear = function (senderId) {
  1717. var ids = Object.keys(this.data);
  1718. this.data = {};
  1719. this.internalIds = {};
  1720. this._trigger('remove', {items: ids}, senderId);
  1721. return ids;
  1722. };
  1723. /**
  1724. * Find the item with maximum value of a specified field
  1725. * @param {String} field
  1726. * @return {Object | null} item Item containing max value, or null if no items
  1727. */
  1728. DataSet.prototype.max = function (field) {
  1729. var data = this.data,
  1730. max = null,
  1731. maxField = null;
  1732. for (var id in data) {
  1733. if (data.hasOwnProperty(id)) {
  1734. var item = data[id];
  1735. var itemField = item[field];
  1736. if (itemField != null && (!max || itemField > maxField)) {
  1737. max = item;
  1738. maxField = itemField;
  1739. }
  1740. }
  1741. }
  1742. return max;
  1743. };
  1744. /**
  1745. * Find the item with minimum value of a specified field
  1746. * @param {String} field
  1747. * @return {Object | null} item Item containing max value, or null if no items
  1748. */
  1749. DataSet.prototype.min = function (field) {
  1750. var data = this.data,
  1751. min = null,
  1752. minField = null;
  1753. for (var id in data) {
  1754. if (data.hasOwnProperty(id)) {
  1755. var item = data[id];
  1756. var itemField = item[field];
  1757. if (itemField != null && (!min || itemField < minField)) {
  1758. min = item;
  1759. minField = itemField;
  1760. }
  1761. }
  1762. }
  1763. return min;
  1764. };
  1765. /**
  1766. * Find all distinct values of a specified field
  1767. * @param {String} field
  1768. * @return {Array} values Array containing all distinct values. If data items
  1769. * do not contain the specified field are ignored.
  1770. * The returned array is unordered.
  1771. */
  1772. DataSet.prototype.distinct = function (field) {
  1773. var data = this.data,
  1774. values = [],
  1775. fieldType = this.options.convert[field],
  1776. count = 0;
  1777. for (var prop in data) {
  1778. if (data.hasOwnProperty(prop)) {
  1779. var item = data[prop];
  1780. var value = util.convert(item[field], fieldType);
  1781. var exists = false;
  1782. for (var i = 0; i < count; i++) {
  1783. if (values[i] == value) {
  1784. exists = true;
  1785. break;
  1786. }
  1787. }
  1788. if (!exists && (value !== undefined)) {
  1789. values[count] = value;
  1790. count++;
  1791. }
  1792. }
  1793. }
  1794. return values;
  1795. };
  1796. /**
  1797. * Add a single item. Will fail when an item with the same id already exists.
  1798. * @param {Object} item
  1799. * @return {String} id
  1800. * @private
  1801. */
  1802. DataSet.prototype._addItem = function (item) {
  1803. var id = item[this.fieldId];
  1804. if (id != undefined) {
  1805. // check whether this id is already taken
  1806. if (this.data[id]) {
  1807. // item already exists
  1808. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1809. }
  1810. }
  1811. else {
  1812. // generate an id
  1813. id = util.randomUUID();
  1814. item[this.fieldId] = id;
  1815. this.internalIds[id] = item;
  1816. }
  1817. var d = {};
  1818. for (var field in item) {
  1819. if (item.hasOwnProperty(field)) {
  1820. var fieldType = this.convert[field]; // type may be undefined
  1821. d[field] = util.convert(item[field], fieldType);
  1822. }
  1823. }
  1824. this.data[id] = d;
  1825. return id;
  1826. };
  1827. /**
  1828. * Get an item. Fields can be converted to a specific type
  1829. * @param {String} id
  1830. * @param {Object.<String, String>} [convert] field types to convert
  1831. * @return {Object | null} item
  1832. * @private
  1833. */
  1834. DataSet.prototype._getItem = function (id, convert) {
  1835. var field, value;
  1836. // get the item from the dataset
  1837. var raw = this.data[id];
  1838. if (!raw) {
  1839. return null;
  1840. }
  1841. // convert the items field types
  1842. var converted = {},
  1843. fieldId = this.fieldId,
  1844. internalIds = this.internalIds;
  1845. if (convert) {
  1846. for (field in raw) {
  1847. if (raw.hasOwnProperty(field)) {
  1848. value = raw[field];
  1849. // output all fields, except internal ids
  1850. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1851. converted[field] = util.convert(value, convert[field]);
  1852. }
  1853. }
  1854. }
  1855. }
  1856. else {
  1857. // no field types specified, no converting needed
  1858. for (field in raw) {
  1859. if (raw.hasOwnProperty(field)) {
  1860. value = raw[field];
  1861. // output all fields, except internal ids
  1862. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1863. converted[field] = value;
  1864. }
  1865. }
  1866. }
  1867. }
  1868. return converted;
  1869. };
  1870. /**
  1871. * Update a single item: merge with existing item.
  1872. * Will fail when the item has no id, or when there does not exist an item
  1873. * with the same id.
  1874. * @param {Object} item
  1875. * @return {String} id
  1876. * @private
  1877. */
  1878. DataSet.prototype._updateItem = function (item) {
  1879. var id = item[this.fieldId];
  1880. if (id == undefined) {
  1881. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1882. }
  1883. var d = this.data[id];
  1884. if (!d) {
  1885. // item doesn't exist
  1886. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1887. }
  1888. // merge with current item
  1889. for (var field in item) {
  1890. if (item.hasOwnProperty(field)) {
  1891. var fieldType = this.convert[field]; // type may be undefined
  1892. d[field] = util.convert(item[field], fieldType);
  1893. }
  1894. }
  1895. return id;
  1896. };
  1897. /**
  1898. * check if an id is an internal or external id
  1899. * @param id
  1900. * @returns {boolean}
  1901. * @private
  1902. */
  1903. DataSet.prototype.isInternalId = function(id) {
  1904. return (id in this.internalIds);
  1905. };
  1906. /**
  1907. * Get an array with the column names of a Google DataTable
  1908. * @param {DataTable} dataTable
  1909. * @return {String[]} columnNames
  1910. * @private
  1911. */
  1912. DataSet.prototype._getColumnNames = function (dataTable) {
  1913. var columns = [];
  1914. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1915. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1916. }
  1917. return columns;
  1918. };
  1919. /**
  1920. * Append an item as a row to the dataTable
  1921. * @param dataTable
  1922. * @param columns
  1923. * @param item
  1924. * @private
  1925. */
  1926. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1927. var row = dataTable.addRow();
  1928. for (var col = 0, cols = columns.length; col < cols; col++) {
  1929. var field = columns[col];
  1930. dataTable.setValue(row, col, item[field]);
  1931. }
  1932. };
  1933. /**
  1934. * DataView
  1935. *
  1936. * a dataview offers a filtered view on a dataset or an other dataview.
  1937. *
  1938. * @param {DataSet | DataView} data
  1939. * @param {Object} [options] Available options: see method get
  1940. *
  1941. * @constructor DataView
  1942. */
  1943. function DataView (data, options) {
  1944. this.id = util.randomUUID();
  1945. this.data = null;
  1946. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1947. this.options = options || {};
  1948. this.fieldId = 'id'; // name of the field containing id
  1949. this.subscribers = {}; // event subscribers
  1950. var me = this;
  1951. this.listener = function () {
  1952. me._onEvent.apply(me, arguments);
  1953. };
  1954. this.setData(data);
  1955. }
  1956. // TODO: implement a function .config() to dynamically update things like configured filter
  1957. // and trigger changes accordingly
  1958. /**
  1959. * Set a data source for the view
  1960. * @param {DataSet | DataView} data
  1961. */
  1962. DataView.prototype.setData = function (data) {
  1963. var ids, dataItems, i, len;
  1964. if (this.data) {
  1965. // unsubscribe from current dataset
  1966. if (this.data.unsubscribe) {
  1967. this.data.unsubscribe('*', this.listener);
  1968. }
  1969. // trigger a remove of all items in memory
  1970. ids = [];
  1971. for (var id in this.ids) {
  1972. if (this.ids.hasOwnProperty(id)) {
  1973. ids.push(id);
  1974. }
  1975. }
  1976. this.ids = {};
  1977. this._trigger('remove', {items: ids});
  1978. }
  1979. this.data = data;
  1980. if (this.data) {
  1981. // update fieldId
  1982. this.fieldId = this.options.fieldId ||
  1983. (this.data && this.data.options && this.data.options.fieldId) ||
  1984. 'id';
  1985. // trigger an add of all added items
  1986. ids = this.data.getIds({filter: this.options && this.options.filter});
  1987. for (i = 0, len = ids.length; i < len; i++) {
  1988. id = ids[i];
  1989. this.ids[id] = true;
  1990. }
  1991. this._trigger('add', {items: ids});
  1992. // subscribe to new dataset
  1993. if (this.data.on) {
  1994. this.data.on('*', this.listener);
  1995. }
  1996. }
  1997. };
  1998. /**
  1999. * Get data from the data view
  2000. *
  2001. * Usage:
  2002. *
  2003. * get()
  2004. * get(options: Object)
  2005. * get(options: Object, data: Array | DataTable)
  2006. *
  2007. * get(id: Number)
  2008. * get(id: Number, options: Object)
  2009. * get(id: Number, options: Object, data: Array | DataTable)
  2010. *
  2011. * get(ids: Number[])
  2012. * get(ids: Number[], options: Object)
  2013. * get(ids: Number[], options: Object, data: Array | DataTable)
  2014. *
  2015. * Where:
  2016. *
  2017. * {Number | String} id The id of an item
  2018. * {Number[] | String{}} ids An array with ids of items
  2019. * {Object} options An Object with options. Available options:
  2020. * {String} [type] Type of data to be returned. Can
  2021. * be 'DataTable' or 'Array' (default)
  2022. * {Object.<String, String>} [convert]
  2023. * {String[]} [fields] field names to be returned
  2024. * {function} [filter] filter items
  2025. * {String | function} [order] Order the items by
  2026. * a field name or custom sort function.
  2027. * {Array | DataTable} [data] If provided, items will be appended to this
  2028. * array or table. Required in case of Google
  2029. * DataTable.
  2030. * @param args
  2031. */
  2032. DataView.prototype.get = function (args) {
  2033. var me = this;
  2034. // parse the arguments
  2035. var ids, options, data;
  2036. var firstType = util.getType(arguments[0]);
  2037. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2038. // get(id(s) [, options] [, data])
  2039. ids = arguments[0]; // can be a single id or an array with ids
  2040. options = arguments[1];
  2041. data = arguments[2];
  2042. }
  2043. else {
  2044. // get([, options] [, data])
  2045. options = arguments[0];
  2046. data = arguments[1];
  2047. }
  2048. // extend the options with the default options and provided options
  2049. var viewOptions = util.extend({}, this.options, options);
  2050. // create a combined filter method when needed
  2051. if (this.options.filter && options && options.filter) {
  2052. viewOptions.filter = function (item) {
  2053. return me.options.filter(item) && options.filter(item);
  2054. }
  2055. }
  2056. // build up the call to the linked data set
  2057. var getArguments = [];
  2058. if (ids != undefined) {
  2059. getArguments.push(ids);
  2060. }
  2061. getArguments.push(viewOptions);
  2062. getArguments.push(data);
  2063. return this.data && this.data.get.apply(this.data, getArguments);
  2064. };
  2065. /**
  2066. * Get ids of all items or from a filtered set of items.
  2067. * @param {Object} [options] An Object with options. Available options:
  2068. * {function} [filter] filter items
  2069. * {String | function} [order] Order the items by
  2070. * a field name or custom sort function.
  2071. * @return {Array} ids
  2072. */
  2073. DataView.prototype.getIds = function (options) {
  2074. var ids;
  2075. if (this.data) {
  2076. var defaultFilter = this.options.filter;
  2077. var filter;
  2078. if (options && options.filter) {
  2079. if (defaultFilter) {
  2080. filter = function (item) {
  2081. return defaultFilter(item) && options.filter(item);
  2082. }
  2083. }
  2084. else {
  2085. filter = options.filter;
  2086. }
  2087. }
  2088. else {
  2089. filter = defaultFilter;
  2090. }
  2091. ids = this.data.getIds({
  2092. filter: filter,
  2093. order: options && options.order
  2094. });
  2095. }
  2096. else {
  2097. ids = [];
  2098. }
  2099. return ids;
  2100. };
  2101. /**
  2102. * Event listener. Will propagate all events from the connected data set to
  2103. * the subscribers of the DataView, but will filter the items and only trigger
  2104. * when there are changes in the filtered data set.
  2105. * @param {String} event
  2106. * @param {Object | null} params
  2107. * @param {String} senderId
  2108. * @private
  2109. */
  2110. DataView.prototype._onEvent = function (event, params, senderId) {
  2111. var i, len, id, item,
  2112. ids = params && params.items,
  2113. data = this.data,
  2114. added = [],
  2115. updated = [],
  2116. removed = [];
  2117. if (ids && data) {
  2118. switch (event) {
  2119. case 'add':
  2120. // filter the ids of the added items
  2121. for (i = 0, len = ids.length; i < len; i++) {
  2122. id = ids[i];
  2123. item = this.get(id);
  2124. if (item) {
  2125. this.ids[id] = true;
  2126. added.push(id);
  2127. }
  2128. }
  2129. break;
  2130. case 'update':
  2131. // determine the event from the views viewpoint: an updated
  2132. // item can be added, updated, or removed from this view.
  2133. for (i = 0, len = ids.length; i < len; i++) {
  2134. id = ids[i];
  2135. item = this.get(id);
  2136. if (item) {
  2137. if (this.ids[id]) {
  2138. updated.push(id);
  2139. }
  2140. else {
  2141. this.ids[id] = true;
  2142. added.push(id);
  2143. }
  2144. }
  2145. else {
  2146. if (this.ids[id]) {
  2147. delete this.ids[id];
  2148. removed.push(id);
  2149. }
  2150. else {
  2151. // nothing interesting for me :-(
  2152. }
  2153. }
  2154. }
  2155. break;
  2156. case 'remove':
  2157. // filter the ids of the removed items
  2158. for (i = 0, len = ids.length; i < len; i++) {
  2159. id = ids[i];
  2160. if (this.ids[id]) {
  2161. delete this.ids[id];
  2162. removed.push(id);
  2163. }
  2164. }
  2165. break;
  2166. }
  2167. if (added.length) {
  2168. this._trigger('add', {items: added}, senderId);
  2169. }
  2170. if (updated.length) {
  2171. this._trigger('update', {items: updated}, senderId);
  2172. }
  2173. if (removed.length) {
  2174. this._trigger('remove', {items: removed}, senderId);
  2175. }
  2176. }
  2177. };
  2178. // copy subscription functionality from DataSet
  2179. DataView.prototype.on = DataSet.prototype.on;
  2180. DataView.prototype.off = DataSet.prototype.off;
  2181. DataView.prototype._trigger = DataSet.prototype._trigger;
  2182. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2183. DataView.prototype.subscribe = DataView.prototype.on;
  2184. DataView.prototype.unsubscribe = DataView.prototype.off;
  2185. /**
  2186. * Utility functions for ordering and stacking of items
  2187. */
  2188. var stack = {};
  2189. /**
  2190. * Order items by their start data
  2191. * @param {Item[]} items
  2192. */
  2193. stack.orderByStart = function orderByStart(items) {
  2194. items.sort(function (a, b) {
  2195. return a.data.start - b.data.start;
  2196. });
  2197. };
  2198. /**
  2199. * Order items by their end date. If they have no end date, their start date
  2200. * is used.
  2201. * @param {Item[]} items
  2202. */
  2203. stack.orderByEnd = function orderByEnd(items) {
  2204. items.sort(function (a, b) {
  2205. var aTime = ('end' in a.data) ? a.data.end : a.data.start,
  2206. bTime = ('end' in b.data) ? b.data.end : b.data.start;
  2207. return aTime - bTime;
  2208. });
  2209. };
  2210. /**
  2211. * Adjust vertical positions of the items such that they don't overlap each
  2212. * other.
  2213. * @param {Item[]} items
  2214. * All visible items
  2215. * @param {{item: number, axis: number}} margin
  2216. * Margins between items and between items and the axis.
  2217. * @param {boolean} [force=false]
  2218. * If true, all items will be repositioned. If false (default), only
  2219. * items having a top===null will be re-stacked
  2220. */
  2221. stack.stack = function _stack (items, margin, force) {
  2222. var i, iMax;
  2223. if (force) {
  2224. // reset top position of all items
  2225. for (i = 0, iMax = items.length; i < iMax; i++) {
  2226. items[i].top = null;
  2227. }
  2228. }
  2229. // calculate new, non-overlapping positions
  2230. for (i = 0, iMax = items.length; i < iMax; i++) {
  2231. var item = items[i];
  2232. if (item.top === null) {
  2233. // initialize top position
  2234. item.top = margin.axis;
  2235. do {
  2236. // TODO: optimize checking for overlap. when there is a gap without items,
  2237. // you only need to check for items from the next item on, not from zero
  2238. var collidingItem = null;
  2239. for (var j = 0, jj = items.length; j < jj; j++) {
  2240. var other = items[j];
  2241. if (other.top !== null && other !== item && stack.collision(item, other, margin.item)) {
  2242. collidingItem = other;
  2243. break;
  2244. }
  2245. }
  2246. if (collidingItem != null) {
  2247. // There is a collision. Reposition the items above the colliding element
  2248. item.top = collidingItem.top + collidingItem.height + margin.item;
  2249. }
  2250. } while (collidingItem);
  2251. }
  2252. }
  2253. };
  2254. /**
  2255. * Adjust vertical positions of the items without stacking them
  2256. * @param {Item[]} items
  2257. * All visible items
  2258. * @param {{item: number, axis: number}} margin
  2259. * Margins between items and between items and the axis.
  2260. */
  2261. stack.nostack = function nostack (items, margin) {
  2262. var i, iMax;
  2263. // reset top position of all items
  2264. for (i = 0, iMax = items.length; i < iMax; i++) {
  2265. items[i].top = margin.axis;
  2266. }
  2267. };
  2268. /**
  2269. * Test if the two provided items collide
  2270. * The items must have parameters left, width, top, and height.
  2271. * @param {Item} a The first item
  2272. * @param {Item} b The second item
  2273. * @param {Number} margin A minimum required margin.
  2274. * If margin is provided, the two items will be
  2275. * marked colliding when they overlap or
  2276. * when the margin between the two is smaller than
  2277. * the requested margin.
  2278. * @return {boolean} true if a and b collide, else false
  2279. */
  2280. stack.collision = function collision (a, b, margin) {
  2281. return ((a.left - margin) < (b.left + b.width) &&
  2282. (a.left + a.width + margin) > b.left &&
  2283. (a.top - margin) < (b.top + b.height) &&
  2284. (a.top + a.height + margin) > b.top);
  2285. };
  2286. /**
  2287. * @constructor TimeStep
  2288. * The class TimeStep is an iterator for dates. You provide a start date and an
  2289. * end date. The class itself determines the best scale (step size) based on the
  2290. * provided start Date, end Date, and minimumStep.
  2291. *
  2292. * If minimumStep is provided, the step size is chosen as close as possible
  2293. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2294. * provided, the scale is set to 1 DAY.
  2295. * The minimumStep should correspond with the onscreen size of about 6 characters
  2296. *
  2297. * Alternatively, you can set a scale by hand.
  2298. * After creation, you can initialize the class by executing first(). Then you
  2299. * can iterate from the start date to the end date via next(). You can check if
  2300. * the end date is reached with the function hasNext(). After each step, you can
  2301. * retrieve the current date via getCurrent().
  2302. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2303. * days, to years.
  2304. *
  2305. * Version: 1.2
  2306. *
  2307. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2308. * or new Date(2010, 9, 21, 23, 45, 00)
  2309. * @param {Date} [end] The end date
  2310. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2311. */
  2312. function TimeStep(start, end, minimumStep) {
  2313. // variables
  2314. this.current = new Date();
  2315. this._start = new Date();
  2316. this._end = new Date();
  2317. this.autoScale = true;
  2318. this.scale = TimeStep.SCALE.DAY;
  2319. this.step = 1;
  2320. // initialize the range
  2321. this.setRange(start, end, minimumStep);
  2322. }
  2323. /// enum scale
  2324. TimeStep.SCALE = {
  2325. MILLISECOND: 1,
  2326. SECOND: 2,
  2327. MINUTE: 3,
  2328. HOUR: 4,
  2329. DAY: 5,
  2330. WEEKDAY: 6,
  2331. MONTH: 7,
  2332. YEAR: 8
  2333. };
  2334. /**
  2335. * Set a new range
  2336. * If minimumStep is provided, the step size is chosen as close as possible
  2337. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2338. * provided, the scale is set to 1 DAY.
  2339. * The minimumStep should correspond with the onscreen size of about 6 characters
  2340. * @param {Date} [start] The start date and time.
  2341. * @param {Date} [end] The end date and time.
  2342. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2343. */
  2344. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2345. if (!(start instanceof Date) || !(end instanceof Date)) {
  2346. throw "No legal start or end date in method setRange";
  2347. }
  2348. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2349. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2350. if (this.autoScale) {
  2351. this.setMinimumStep(minimumStep);
  2352. }
  2353. };
  2354. /**
  2355. * Set the range iterator to the start date.
  2356. */
  2357. TimeStep.prototype.first = function() {
  2358. this.current = new Date(this._start.valueOf());
  2359. this.roundToMinor();
  2360. };
  2361. /**
  2362. * Round the current date to the first minor date value
  2363. * This must be executed once when the current date is set to start Date
  2364. */
  2365. TimeStep.prototype.roundToMinor = function() {
  2366. // round to floor
  2367. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2368. //noinspection FallthroughInSwitchStatementJS
  2369. switch (this.scale) {
  2370. case TimeStep.SCALE.YEAR:
  2371. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2372. this.current.setMonth(0);
  2373. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2374. case TimeStep.SCALE.DAY: // intentional fall through
  2375. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2376. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2377. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2378. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2379. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2380. }
  2381. if (this.step != 1) {
  2382. // round down to the first minor value that is a multiple of the current step size
  2383. switch (this.scale) {
  2384. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2385. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2386. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2387. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2388. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2389. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2390. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2391. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2392. default: break;
  2393. }
  2394. }
  2395. };
  2396. /**
  2397. * Check if the there is a next step
  2398. * @return {boolean} true if the current date has not passed the end date
  2399. */
  2400. TimeStep.prototype.hasNext = function () {
  2401. return (this.current.valueOf() <= this._end.valueOf());
  2402. };
  2403. /**
  2404. * Do the next step
  2405. */
  2406. TimeStep.prototype.next = function() {
  2407. var prev = this.current.valueOf();
  2408. // Two cases, needed to prevent issues with switching daylight savings
  2409. // (end of March and end of October)
  2410. if (this.current.getMonth() < 6) {
  2411. switch (this.scale) {
  2412. case TimeStep.SCALE.MILLISECOND:
  2413. this.current = new Date(this.current.valueOf() + this.step); break;
  2414. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2415. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2416. case TimeStep.SCALE.HOUR:
  2417. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2418. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2419. var h = this.current.getHours();
  2420. this.current.setHours(h - (h % this.step));
  2421. break;
  2422. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2423. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2424. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2425. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2426. default: break;
  2427. }
  2428. }
  2429. else {
  2430. switch (this.scale) {
  2431. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2432. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2433. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2434. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2435. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2436. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2437. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2438. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2439. default: break;
  2440. }
  2441. }
  2442. if (this.step != 1) {
  2443. // round down to the correct major value
  2444. switch (this.scale) {
  2445. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2446. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2447. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2448. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2449. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2450. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2451. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2452. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2453. default: break;
  2454. }
  2455. }
  2456. // safety mechanism: if current time is still unchanged, move to the end
  2457. if (this.current.valueOf() == prev) {
  2458. this.current = new Date(this._end.valueOf());
  2459. }
  2460. };
  2461. /**
  2462. * Get the current datetime
  2463. * @return {Date} current The current date
  2464. */
  2465. TimeStep.prototype.getCurrent = function() {
  2466. return this.current;
  2467. };
  2468. /**
  2469. * Set a custom scale. Autoscaling will be disabled.
  2470. * For example setScale(SCALE.MINUTES, 5) will result
  2471. * in minor steps of 5 minutes, and major steps of an hour.
  2472. *
  2473. * @param {TimeStep.SCALE} newScale
  2474. * A scale. Choose from SCALE.MILLISECOND,
  2475. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2476. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2477. * SCALE.YEAR.
  2478. * @param {Number} newStep A step size, by default 1. Choose for
  2479. * example 1, 2, 5, or 10.
  2480. */
  2481. TimeStep.prototype.setScale = function(newScale, newStep) {
  2482. this.scale = newScale;
  2483. if (newStep > 0) {
  2484. this.step = newStep;
  2485. }
  2486. this.autoScale = false;
  2487. };
  2488. /**
  2489. * Enable or disable autoscaling
  2490. * @param {boolean} enable If true, autoascaling is set true
  2491. */
  2492. TimeStep.prototype.setAutoScale = function (enable) {
  2493. this.autoScale = enable;
  2494. };
  2495. /**
  2496. * Automatically determine the scale that bests fits the provided minimum step
  2497. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2498. */
  2499. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2500. if (minimumStep == undefined) {
  2501. return;
  2502. }
  2503. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2504. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2505. var stepDay = (1000 * 60 * 60 * 24);
  2506. var stepHour = (1000 * 60 * 60);
  2507. var stepMinute = (1000 * 60);
  2508. var stepSecond = (1000);
  2509. var stepMillisecond= (1);
  2510. // find the smallest step that is larger than the provided minimumStep
  2511. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2512. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2513. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2514. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2515. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2516. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2517. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2518. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2519. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2520. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2521. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2522. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2523. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2524. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2525. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2526. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2527. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2528. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2529. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2530. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2531. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2532. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2533. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2534. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2535. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2536. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2537. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2538. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2539. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2540. };
  2541. /**
  2542. * Snap a date to a rounded value.
  2543. * The snap intervals are dependent on the current scale and step.
  2544. * @param {Date} date the date to be snapped.
  2545. * @return {Date} snappedDate
  2546. */
  2547. TimeStep.prototype.snap = function(date) {
  2548. var clone = new Date(date.valueOf());
  2549. if (this.scale == TimeStep.SCALE.YEAR) {
  2550. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2551. clone.setFullYear(Math.round(year / this.step) * this.step);
  2552. clone.setMonth(0);
  2553. clone.setDate(0);
  2554. clone.setHours(0);
  2555. clone.setMinutes(0);
  2556. clone.setSeconds(0);
  2557. clone.setMilliseconds(0);
  2558. }
  2559. else if (this.scale == TimeStep.SCALE.MONTH) {
  2560. if (clone.getDate() > 15) {
  2561. clone.setDate(1);
  2562. clone.setMonth(clone.getMonth() + 1);
  2563. // important: first set Date to 1, after that change the month.
  2564. }
  2565. else {
  2566. clone.setDate(1);
  2567. }
  2568. clone.setHours(0);
  2569. clone.setMinutes(0);
  2570. clone.setSeconds(0);
  2571. clone.setMilliseconds(0);
  2572. }
  2573. else if (this.scale == TimeStep.SCALE.DAY) {
  2574. //noinspection FallthroughInSwitchStatementJS
  2575. switch (this.step) {
  2576. case 5:
  2577. case 2:
  2578. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2579. default:
  2580. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2581. }
  2582. clone.setMinutes(0);
  2583. clone.setSeconds(0);
  2584. clone.setMilliseconds(0);
  2585. }
  2586. else if (this.scale == TimeStep.SCALE.WEEKDAY) {
  2587. //noinspection FallthroughInSwitchStatementJS
  2588. switch (this.step) {
  2589. case 5:
  2590. case 2:
  2591. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2592. default:
  2593. clone.setHours(Math.round(clone.getHours() / 6) * 6); break;
  2594. }
  2595. clone.setMinutes(0);
  2596. clone.setSeconds(0);
  2597. clone.setMilliseconds(0);
  2598. }
  2599. else if (this.scale == TimeStep.SCALE.HOUR) {
  2600. switch (this.step) {
  2601. case 4:
  2602. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2603. default:
  2604. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2605. }
  2606. clone.setSeconds(0);
  2607. clone.setMilliseconds(0);
  2608. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2609. //noinspection FallthroughInSwitchStatementJS
  2610. switch (this.step) {
  2611. case 15:
  2612. case 10:
  2613. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2614. clone.setSeconds(0);
  2615. break;
  2616. case 5:
  2617. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2618. default:
  2619. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2620. }
  2621. clone.setMilliseconds(0);
  2622. }
  2623. else if (this.scale == TimeStep.SCALE.SECOND) {
  2624. //noinspection FallthroughInSwitchStatementJS
  2625. switch (this.step) {
  2626. case 15:
  2627. case 10:
  2628. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2629. clone.setMilliseconds(0);
  2630. break;
  2631. case 5:
  2632. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2633. default:
  2634. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2635. }
  2636. }
  2637. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2638. var step = this.step > 5 ? this.step / 2 : 1;
  2639. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2640. }
  2641. return clone;
  2642. };
  2643. /**
  2644. * Check if the current value is a major value (for example when the step
  2645. * is DAY, a major value is each first day of the MONTH)
  2646. * @return {boolean} true if current date is major, else false.
  2647. */
  2648. TimeStep.prototype.isMajor = function() {
  2649. switch (this.scale) {
  2650. case TimeStep.SCALE.MILLISECOND:
  2651. return (this.current.getMilliseconds() == 0);
  2652. case TimeStep.SCALE.SECOND:
  2653. return (this.current.getSeconds() == 0);
  2654. case TimeStep.SCALE.MINUTE:
  2655. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2656. // Note: this is no bug. Major label is equal for both minute and hour scale
  2657. case TimeStep.SCALE.HOUR:
  2658. return (this.current.getHours() == 0);
  2659. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2660. case TimeStep.SCALE.DAY:
  2661. return (this.current.getDate() == 1);
  2662. case TimeStep.SCALE.MONTH:
  2663. return (this.current.getMonth() == 0);
  2664. case TimeStep.SCALE.YEAR:
  2665. return false;
  2666. default:
  2667. return false;
  2668. }
  2669. };
  2670. /**
  2671. * Returns formatted text for the minor axislabel, depending on the current
  2672. * date and the scale. For example when scale is MINUTE, the current time is
  2673. * formatted as "hh:mm".
  2674. * @param {Date} [date] custom date. if not provided, current date is taken
  2675. */
  2676. TimeStep.prototype.getLabelMinor = function(date) {
  2677. if (date == undefined) {
  2678. date = this.current;
  2679. }
  2680. switch (this.scale) {
  2681. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2682. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2683. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2684. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2685. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2686. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2687. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2688. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2689. default: return '';
  2690. }
  2691. };
  2692. /**
  2693. * Returns formatted text for the major axis label, depending on the current
  2694. * date and the scale. For example when scale is MINUTE, the major scale is
  2695. * hours, and the hour will be formatted as "hh".
  2696. * @param {Date} [date] custom date. if not provided, current date is taken
  2697. */
  2698. TimeStep.prototype.getLabelMajor = function(date) {
  2699. if (date == undefined) {
  2700. date = this.current;
  2701. }
  2702. return "";
  2703. };
  2704. /**
  2705. * @constructor DataStep
  2706. * The class DataStep is an iterator for data for the lineGraph. You provide a start data point and an
  2707. * end data point. The class itself determines the best scale (step size) based on the
  2708. * provided start Date, end Date, and minimumStep.
  2709. *
  2710. * If minimumStep is provided, the step size is chosen as close as possible
  2711. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2712. * provided, the scale is set to 1 DAY.
  2713. * The minimumStep should correspond with the onscreen size of about 6 characters
  2714. *
  2715. * Alternatively, you can set a scale by hand.
  2716. * After creation, you can initialize the class by executing first(). Then you
  2717. * can iterate from the start date to the end date via next(). You can check if
  2718. * the end date is reached with the function hasNext(). After each step, you can
  2719. * retrieve the current date via getCurrent().
  2720. * The DataStep has scales ranging from milliseconds, seconds, minutes, hours,
  2721. * days, to years.
  2722. *
  2723. * Version: 1.2
  2724. *
  2725. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2726. * or new Date(2010, 9, 21, 23, 45, 00)
  2727. * @param {Date} [end] The end date
  2728. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2729. */
  2730. function DataStep(start, end, minimumStep, containerHeight) {
  2731. // variables
  2732. this.current = 0;
  2733. this.containerHeight = containerHeight;
  2734. this.autoScale = true;
  2735. this.stepIndex = 0;
  2736. this.step = 1;
  2737. this.scale = 1;
  2738. this.marginStart;
  2739. this.marginEnd;
  2740. this.majorSteps = [1, 2, 5, 10];
  2741. this.minorSteps = [0.25, 0.5, 1, 2];
  2742. this.setRange(start,end,minimumStep, containerHeight);
  2743. }
  2744. /**
  2745. * Set a new range
  2746. * If minimumStep is provided, the step size is chosen as close as possible
  2747. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2748. * provided, the scale is set to 1 DAY.
  2749. * The minimumStep should correspond with the onscreen size of about 6 characters
  2750. * @param {Number} [start] The start date and time.
  2751. * @param {Number} [end] The end date and time.
  2752. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2753. */
  2754. DataStep.prototype.setRange = function(start, end, minimumStep, containerHeight) {
  2755. this._start = start;
  2756. this._end = end;
  2757. this.setFirst();
  2758. if (this.autoScale) {
  2759. this.setMinimumStep(minimumStep, containerHeight);
  2760. }
  2761. };
  2762. /**
  2763. * Set the range iterator to the start date.
  2764. */
  2765. DataStep.prototype.first = function() {
  2766. this.setFirst();
  2767. };
  2768. /**
  2769. * Round the current date to the first minor date value
  2770. * This must be executed once when the current date is set to start Date
  2771. */
  2772. DataStep.prototype.setFirst = function() {
  2773. var niceStart = this._start - (this.scale * this.minorSteps[this.stepIndex]);
  2774. var niceEnd = this._end + (this.scale * this.minorSteps[this.stepIndex]);
  2775. this.marginEnd = this.roundToMinor(niceEnd);
  2776. this.marginStart = this.roundToMinor(niceStart);
  2777. this.marginRange = this.current - this.marginStart;
  2778. this.current = this.marginEnd;
  2779. };
  2780. DataStep.prototype.roundToMinor = function(value) {
  2781. var rounded = value - (value % (this.scale * this.minorSteps[this.stepIndex]));
  2782. if (value % (this.scale * this.minorSteps[this.stepIndex]) > 0.5 * (this.scale * this.minorSteps[this.stepIndex])) {
  2783. return rounded + (this.scale * this.minorSteps[this.stepIndex]);
  2784. }
  2785. else {
  2786. return rounded;
  2787. }
  2788. }
  2789. /**
  2790. * Check if the there is a next step
  2791. * @return {boolean} true if the current date has not passed the end date
  2792. */
  2793. DataStep.prototype.hasNext = function () {
  2794. return (this.current >= this.marginStart);
  2795. };
  2796. /**
  2797. * Do the next step
  2798. */
  2799. DataStep.prototype.next = function() {
  2800. var prev = this.current;
  2801. this.current -= this.step;
  2802. // safety mechanism: if current time is still unchanged, move to the end
  2803. if (this.current == prev) {
  2804. this.current = this._end;
  2805. }
  2806. };
  2807. /**
  2808. * Get the current datetime
  2809. * @return {Date} current The current date
  2810. */
  2811. DataStep.prototype.getCurrent = function() {
  2812. return this.current;
  2813. };
  2814. /**
  2815. * Automatically determine the scale that bests fits the provided minimum step
  2816. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2817. */
  2818. DataStep.prototype.setMinimumStep = function(minimumStep, containerHeight) {
  2819. // round to floor
  2820. var size = this._end - this._start;
  2821. var safeSize = size * 1.1;
  2822. var minimumStepValue = minimumStep * (safeSize / containerHeight);
  2823. var orderOfMagnitude = Math.round(Math.log(safeSize)/Math.LN10);
  2824. var minorStepIdx = -1;
  2825. var magnitudefactor = Math.pow(10,orderOfMagnitude);
  2826. var solutionFound = false;
  2827. for (var i = 0; i <= orderOfMagnitude; i++) {
  2828. magnitudefactor = Math.pow(10,i);
  2829. for (var j = 0; j < this.minorSteps.length; j++) {
  2830. var stepSize = magnitudefactor * this.minorSteps[j];
  2831. if (stepSize >= minimumStepValue) {
  2832. solutionFound = true;
  2833. minorStepIdx = j;
  2834. break;
  2835. }
  2836. }
  2837. if (solutionFound == true) {
  2838. break;
  2839. }
  2840. }
  2841. this.stepIndex = minorStepIdx;
  2842. this.scale = magnitudefactor;
  2843. this.step = magnitudefactor * this.minorSteps[minorStepIdx];
  2844. };
  2845. /**
  2846. * Snap a date to a rounded value.
  2847. * The snap intervals are dependent on the current scale and step.
  2848. * @param {Date} date the date to be snapped.
  2849. * @return {Date} snappedDate
  2850. */
  2851. DataStep.prototype.snap = function(date) {
  2852. };
  2853. /**
  2854. * Check if the current value is a major value (for example when the step
  2855. * is DAY, a major value is each first day of the MONTH)
  2856. * @return {boolean} true if current date is major, else false.
  2857. */
  2858. DataStep.prototype.isMajor = function() {
  2859. return (this.current % (this.scale * this.majorSteps[this.stepIndex]) == 0);
  2860. };
  2861. /**
  2862. * Returns formatted text for the minor axislabel, depending on the current
  2863. * date and the scale. For example when scale is MINUTE, the current time is
  2864. * formatted as "hh:mm".
  2865. * @param {Date} [date] custom date. if not provided, current date is taken
  2866. */
  2867. DataStep.prototype.getLabelMinor = function() {
  2868. return this.current;
  2869. };
  2870. /**
  2871. * Returns formatted text for the major axis label, depending on the current
  2872. * date and the scale. For example when scale is MINUTE, the major scale is
  2873. * hours, and the hour will be formatted as "hh".
  2874. * @param {Date} [date] custom date. if not provided, current date is taken
  2875. */
  2876. DataStep.prototype.getLabelMajor = function() {
  2877. return this.current;
  2878. };
  2879. /**
  2880. * @constructor Range
  2881. * A Range controls a numeric range with a start and end value.
  2882. * The Range adjusts the range based on mouse events or programmatic changes,
  2883. * and triggers events when the range is changing or has been changed.
  2884. * @param {RootPanel} root Root panel, used to subscribe to events
  2885. * @param {Panel} parent Parent panel, used to attach to the DOM
  2886. * @param {Object} [options] See description at Range.setOptions
  2887. */
  2888. function Range(root, parent, options) {
  2889. this.id = util.randomUUID();
  2890. this.start = null; // Number
  2891. this.end = null; // Number
  2892. this.root = root;
  2893. this.parent = parent;
  2894. this.options = options || {};
  2895. // drag listeners for dragging
  2896. this.root.on('dragstart', this._onDragStart.bind(this));
  2897. this.root.on('drag', this._onDrag.bind(this));
  2898. this.root.on('dragend', this._onDragEnd.bind(this));
  2899. // ignore dragging when holding
  2900. this.root.on('hold', this._onHold.bind(this));
  2901. // mouse wheel for zooming
  2902. this.root.on('mousewheel', this._onMouseWheel.bind(this));
  2903. this.root.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF
  2904. // pinch to zoom
  2905. this.root.on('touch', this._onTouch.bind(this));
  2906. this.root.on('pinch', this._onPinch.bind(this));
  2907. this.setOptions(options);
  2908. }
  2909. // turn Range into an event emitter
  2910. Emitter(Range.prototype);
  2911. /**
  2912. * Set options for the range controller
  2913. * @param {Object} options Available options:
  2914. * {Number} min Minimum value for start
  2915. * {Number} max Maximum value for end
  2916. * {Number} zoomMin Set a minimum value for
  2917. * (end - start).
  2918. * {Number} zoomMax Set a maximum value for
  2919. * (end - start).
  2920. */
  2921. Range.prototype.setOptions = function (options) {
  2922. util.extend(this.options, options);
  2923. // re-apply range with new limitations
  2924. if (this.start !== null && this.end !== null) {
  2925. this.setRange(this.start, this.end);
  2926. }
  2927. };
  2928. /**
  2929. * Test whether direction has a valid value
  2930. * @param {String} direction 'horizontal' or 'vertical'
  2931. */
  2932. function validateDirection (direction) {
  2933. if (direction != 'horizontal' && direction != 'vertical') {
  2934. throw new TypeError('Unknown direction "' + direction + '". ' +
  2935. 'Choose "horizontal" or "vertical".');
  2936. }
  2937. }
  2938. /**
  2939. * Set a new start and end range
  2940. * @param {Number} [start]
  2941. * @param {Number} [end]
  2942. */
  2943. Range.prototype.setRange = function(start, end) {
  2944. var changed = this._applyRange(start, end);
  2945. if (changed) {
  2946. var params = {
  2947. start: new Date(this.start),
  2948. end: new Date(this.end)
  2949. };
  2950. this.emit('rangechange', params);
  2951. this.emit('rangechanged', params);
  2952. }
  2953. };
  2954. /**
  2955. * Set a new start and end range. This method is the same as setRange, but
  2956. * does not trigger a range change and range changed event, and it returns
  2957. * true when the range is changed
  2958. * @param {Number} [start]
  2959. * @param {Number} [end]
  2960. * @return {Boolean} changed
  2961. * @private
  2962. */
  2963. Range.prototype._applyRange = function(start, end) {
  2964. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2965. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2966. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2967. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2968. diff;
  2969. // check for valid number
  2970. if (isNaN(newStart) || newStart === null) {
  2971. throw new Error('Invalid start "' + start + '"');
  2972. }
  2973. if (isNaN(newEnd) || newEnd === null) {
  2974. throw new Error('Invalid end "' + end + '"');
  2975. }
  2976. // prevent start < end
  2977. if (newEnd < newStart) {
  2978. newEnd = newStart;
  2979. }
  2980. // prevent start < min
  2981. if (min !== null) {
  2982. if (newStart < min) {
  2983. diff = (min - newStart);
  2984. newStart += diff;
  2985. newEnd += diff;
  2986. // prevent end > max
  2987. if (max != null) {
  2988. if (newEnd > max) {
  2989. newEnd = max;
  2990. }
  2991. }
  2992. }
  2993. }
  2994. // prevent end > max
  2995. if (max !== null) {
  2996. if (newEnd > max) {
  2997. diff = (newEnd - max);
  2998. newStart -= diff;
  2999. newEnd -= diff;
  3000. // prevent start < min
  3001. if (min != null) {
  3002. if (newStart < min) {
  3003. newStart = min;
  3004. }
  3005. }
  3006. }
  3007. }
  3008. // prevent (end-start) < zoomMin
  3009. if (this.options.zoomMin !== null) {
  3010. var zoomMin = parseFloat(this.options.zoomMin);
  3011. if (zoomMin < 0) {
  3012. zoomMin = 0;
  3013. }
  3014. if ((newEnd - newStart) < zoomMin) {
  3015. if ((this.end - this.start) === zoomMin) {
  3016. // ignore this action, we are already zoomed to the minimum
  3017. newStart = this.start;
  3018. newEnd = this.end;
  3019. }
  3020. else {
  3021. // zoom to the minimum
  3022. diff = (zoomMin - (newEnd - newStart));
  3023. newStart -= diff / 2;
  3024. newEnd += diff / 2;
  3025. }
  3026. }
  3027. }
  3028. // prevent (end-start) > zoomMax
  3029. if (this.options.zoomMax !== null) {
  3030. var zoomMax = parseFloat(this.options.zoomMax);
  3031. if (zoomMax < 0) {
  3032. zoomMax = 0;
  3033. }
  3034. if ((newEnd - newStart) > zoomMax) {
  3035. if ((this.end - this.start) === zoomMax) {
  3036. // ignore this action, we are already zoomed to the maximum
  3037. newStart = this.start;
  3038. newEnd = this.end;
  3039. }
  3040. else {
  3041. // zoom to the maximum
  3042. diff = ((newEnd - newStart) - zoomMax);
  3043. newStart += diff / 2;
  3044. newEnd -= diff / 2;
  3045. }
  3046. }
  3047. }
  3048. var changed = (this.start != newStart || this.end != newEnd);
  3049. this.start = newStart;
  3050. this.end = newEnd;
  3051. return changed;
  3052. };
  3053. /**
  3054. * Retrieve the current range.
  3055. * @return {Object} An object with start and end properties
  3056. */
  3057. Range.prototype.getRange = function() {
  3058. return {
  3059. start: this.start,
  3060. end: this.end
  3061. };
  3062. };
  3063. /**
  3064. * Calculate the conversion offset and scale for current range, based on
  3065. * the provided width
  3066. * @param {Number} width
  3067. * @returns {{offset: number, scale: number}} conversion
  3068. */
  3069. Range.prototype.conversion = function (width) {
  3070. return Range.conversion(this.start, this.end, width);
  3071. };
  3072. /**
  3073. * Static method to calculate the conversion offset and scale for a range,
  3074. * based on the provided start, end, and width
  3075. * @param {Number} start
  3076. * @param {Number} end
  3077. * @param {Number} width
  3078. * @returns {{offset: number, scale: number}} conversion
  3079. */
  3080. Range.conversion = function (start, end, width) {
  3081. if (width != 0 && (end - start != 0)) {
  3082. return {
  3083. offset: start,
  3084. scale: width / (end - start)
  3085. }
  3086. }
  3087. else {
  3088. return {
  3089. offset: 0,
  3090. scale: 1
  3091. };
  3092. }
  3093. };
  3094. // global (private) object to store drag params
  3095. var touchParams = {};
  3096. /**
  3097. * Start dragging horizontally or vertically
  3098. * @param {Event} event
  3099. * @private
  3100. */
  3101. Range.prototype._onDragStart = function(event) {
  3102. // refuse to drag when we where pinching to prevent the timeline make a jump
  3103. // when releasing the fingers in opposite order from the touch screen
  3104. if (touchParams.ignore) return;
  3105. // TODO: reckon with option movable
  3106. touchParams.start = this.start;
  3107. touchParams.end = this.end;
  3108. var frame = this.parent.frame;
  3109. if (frame) {
  3110. frame.style.cursor = 'move';
  3111. }
  3112. };
  3113. /**
  3114. * Perform dragging operating.
  3115. * @param {Event} event
  3116. * @private
  3117. */
  3118. Range.prototype._onDrag = function (event) {
  3119. var direction = this.options.direction;
  3120. validateDirection(direction);
  3121. // TODO: reckon with option movable
  3122. // refuse to drag when we where pinching to prevent the timeline make a jump
  3123. // when releasing the fingers in opposite order from the touch screen
  3124. if (touchParams.ignore) return;
  3125. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  3126. interval = (touchParams.end - touchParams.start),
  3127. width = (direction == 'horizontal') ? this.parent.width : this.parent.height,
  3128. diffRange = -delta / width * interval;
  3129. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  3130. this.emit('rangechange', {
  3131. start: new Date(this.start),
  3132. end: new Date(this.end)
  3133. });
  3134. };
  3135. /**
  3136. * Stop dragging operating.
  3137. * @param {event} event
  3138. * @private
  3139. */
  3140. Range.prototype._onDragEnd = function (event) {
  3141. // refuse to drag when we where pinching to prevent the timeline make a jump
  3142. // when releasing the fingers in opposite order from the touch screen
  3143. if (touchParams.ignore) return;
  3144. // TODO: reckon with option movable
  3145. if (this.parent.frame) {
  3146. this.parent.frame.style.cursor = 'auto';
  3147. }
  3148. // fire a rangechanged event
  3149. this.emit('rangechanged', {
  3150. start: new Date(this.start),
  3151. end: new Date(this.end)
  3152. });
  3153. };
  3154. /**
  3155. * Event handler for mouse wheel event, used to zoom
  3156. * Code from http://adomas.org/javascript-mouse-wheel/
  3157. * @param {Event} event
  3158. * @private
  3159. */
  3160. Range.prototype._onMouseWheel = function(event) {
  3161. // TODO: reckon with option zoomable
  3162. // retrieve delta
  3163. var delta = 0;
  3164. if (event.wheelDelta) { /* IE/Opera. */
  3165. delta = event.wheelDelta / 120;
  3166. } else if (event.detail) { /* Mozilla case. */
  3167. // In Mozilla, sign of delta is different than in IE.
  3168. // Also, delta is multiple of 3.
  3169. delta = -event.detail / 3;
  3170. }
  3171. // If delta is nonzero, handle it.
  3172. // Basically, delta is now positive if wheel was scrolled up,
  3173. // and negative, if wheel was scrolled down.
  3174. if (delta) {
  3175. // perform the zoom action. Delta is normally 1 or -1
  3176. // adjust a negative delta such that zooming in with delta 0.1
  3177. // equals zooming out with a delta -0.1
  3178. var scale;
  3179. if (delta < 0) {
  3180. scale = 1 - (delta / 5);
  3181. }
  3182. else {
  3183. scale = 1 / (1 + (delta / 5)) ;
  3184. }
  3185. // calculate center, the date to zoom around
  3186. var gesture = util.fakeGesture(this, event),
  3187. pointer = getPointer(gesture.center, this.parent.frame),
  3188. pointerDate = this._pointerToDate(pointer);
  3189. this.zoom(scale, pointerDate);
  3190. }
  3191. // Prevent default actions caused by mouse wheel
  3192. // (else the page and timeline both zoom and scroll)
  3193. event.preventDefault();
  3194. };
  3195. /**
  3196. * Start of a touch gesture
  3197. * @private
  3198. */
  3199. Range.prototype._onTouch = function (event) {
  3200. touchParams.start = this.start;
  3201. touchParams.end = this.end;
  3202. touchParams.ignore = false;
  3203. touchParams.center = null;
  3204. // don't move the range when dragging a selected event
  3205. // TODO: it's not so neat to have to know about the state of the ItemSet
  3206. var item = ItemSet.itemFromTarget(event);
  3207. if (item && item.selected && this.options.editable) {
  3208. touchParams.ignore = true;
  3209. }
  3210. };
  3211. /**
  3212. * On start of a hold gesture
  3213. * @private
  3214. */
  3215. Range.prototype._onHold = function () {
  3216. touchParams.ignore = true;
  3217. };
  3218. /**
  3219. * Handle pinch event
  3220. * @param {Event} event
  3221. * @private
  3222. */
  3223. Range.prototype._onPinch = function (event) {
  3224. var direction = this.options.direction;
  3225. touchParams.ignore = true;
  3226. // TODO: reckon with option zoomable
  3227. if (event.gesture.touches.length > 1) {
  3228. if (!touchParams.center) {
  3229. touchParams.center = getPointer(event.gesture.center, this.parent.frame);
  3230. }
  3231. var scale = 1 / event.gesture.scale,
  3232. initDate = this._pointerToDate(touchParams.center),
  3233. center = getPointer(event.gesture.center, this.parent.frame),
  3234. date = this._pointerToDate(this.parent, center),
  3235. delta = date - initDate; // TODO: utilize delta
  3236. // calculate new start and end
  3237. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3238. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3239. // apply new range
  3240. this.setRange(newStart, newEnd);
  3241. }
  3242. };
  3243. /**
  3244. * Helper function to calculate the center date for zooming
  3245. * @param {{x: Number, y: Number}} pointer
  3246. * @return {number} date
  3247. * @private
  3248. */
  3249. Range.prototype._pointerToDate = function (pointer) {
  3250. var conversion;
  3251. var direction = this.options.direction;
  3252. validateDirection(direction);
  3253. if (direction == 'horizontal') {
  3254. var width = this.parent.width;
  3255. conversion = this.conversion(width);
  3256. return pointer.x / conversion.scale + conversion.offset;
  3257. }
  3258. else {
  3259. var height = this.parent.height;
  3260. conversion = this.conversion(height);
  3261. return pointer.y / conversion.scale + conversion.offset;
  3262. }
  3263. };
  3264. /**
  3265. * Get the pointer location relative to the location of the dom element
  3266. * @param {{pageX: Number, pageY: Number}} touch
  3267. * @param {Element} element HTML DOM element
  3268. * @return {{x: Number, y: Number}} pointer
  3269. * @private
  3270. */
  3271. function getPointer (touch, element) {
  3272. return {
  3273. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3274. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3275. };
  3276. }
  3277. /**
  3278. * Zoom the range the given scale in or out. Start and end date will
  3279. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3280. * date around which to zoom.
  3281. * For example, try scale = 0.9 or 1.1
  3282. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3283. * values below 1 will zoom in.
  3284. * @param {Number} [center] Value representing a date around which will
  3285. * be zoomed.
  3286. */
  3287. Range.prototype.zoom = function(scale, center) {
  3288. // if centerDate is not provided, take it half between start Date and end Date
  3289. if (center == null) {
  3290. center = (this.start + this.end) / 2;
  3291. }
  3292. // calculate new start and end
  3293. var newStart = center + (this.start - center) * scale;
  3294. var newEnd = center + (this.end - center) * scale;
  3295. this.setRange(newStart, newEnd);
  3296. };
  3297. /**
  3298. * Move the range with a given delta to the left or right. Start and end
  3299. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3300. * @param {Number} delta Moving amount. Positive value will move right,
  3301. * negative value will move left
  3302. */
  3303. Range.prototype.move = function(delta) {
  3304. // zoom start Date and end Date relative to the centerDate
  3305. var diff = (this.end - this.start);
  3306. // apply new values
  3307. var newStart = this.start + diff * delta;
  3308. var newEnd = this.end + diff * delta;
  3309. // TODO: reckon with min and max range
  3310. this.start = newStart;
  3311. this.end = newEnd;
  3312. };
  3313. /**
  3314. * Move the range to a new center point
  3315. * @param {Number} moveTo New center point of the range
  3316. */
  3317. Range.prototype.moveTo = function(moveTo) {
  3318. var center = (this.start + this.end) / 2;
  3319. var diff = center - moveTo;
  3320. // calculate new start and end
  3321. var newStart = this.start - diff;
  3322. var newEnd = this.end - diff;
  3323. this.setRange(newStart, newEnd);
  3324. };
  3325. /**
  3326. * Prototype for visual components
  3327. */
  3328. function Component () {
  3329. this.id = null;
  3330. this.parent = null;
  3331. this.childs = null;
  3332. this.options = null;
  3333. this.top = 0;
  3334. this.left = 0;
  3335. this.width = 0;
  3336. this.height = 0;
  3337. }
  3338. // Turn the Component into an event emitter
  3339. Emitter(Component.prototype);
  3340. /**
  3341. * Set parameters for the frame. Parameters will be merged in current parameter
  3342. * set.
  3343. * @param {Object} options Available parameters:
  3344. * {String | function} [className]
  3345. * {String | Number | function} [left]
  3346. * {String | Number | function} [top]
  3347. * {String | Number | function} [width]
  3348. * {String | Number | function} [height]
  3349. */
  3350. Component.prototype.setOptions = function setOptions(options) {
  3351. if (options) {
  3352. util.extend(this.options, options);
  3353. this.repaint();
  3354. }
  3355. };
  3356. /**
  3357. * Get an option value by name
  3358. * The function will first check this.options object, and else will check
  3359. * this.defaultOptions.
  3360. * @param {String} name
  3361. * @return {*} value
  3362. */
  3363. Component.prototype.getOption = function getOption(name) {
  3364. var value;
  3365. if (this.options) {
  3366. value = this.options[name];
  3367. }
  3368. if (value === undefined && this.defaultOptions) {
  3369. value = this.defaultOptions[name];
  3370. }
  3371. return value;
  3372. };
  3373. /**
  3374. * Get the frame element of the component, the outer HTML DOM element.
  3375. * @returns {HTMLElement | null} frame
  3376. */
  3377. Component.prototype.getFrame = function getFrame() {
  3378. // should be implemented by the component
  3379. return null;
  3380. };
  3381. /**
  3382. * Repaint the component
  3383. * @return {boolean} Returns true if the component is resized
  3384. */
  3385. Component.prototype.repaint = function repaint() {
  3386. // should be implemented by the component
  3387. return false;
  3388. };
  3389. /**
  3390. * Test whether the component is resized since the last time _isResized() was
  3391. * called.
  3392. * @return {Boolean} Returns true if the component is resized
  3393. * @protected
  3394. */
  3395. Component.prototype._isResized = function _isResized() {
  3396. var resized = (this._previousWidth !== this.width || this._previousHeight !== this.height);
  3397. this._previousWidth = this.width;
  3398. this._previousHeight = this.height;
  3399. return resized;
  3400. };
  3401. /**
  3402. * A panel can contain components
  3403. * @param {Object} [options] Available parameters:
  3404. * {String | Number | function} [left]
  3405. * {String | Number | function} [top]
  3406. * {String | Number | function} [width]
  3407. * {String | Number | function} [height]
  3408. * {String | function} [className]
  3409. * @constructor Panel
  3410. * @extends Component
  3411. */
  3412. function Panel(options) {
  3413. this.id = util.randomUUID();
  3414. this.parent = null;
  3415. this.childs = [];
  3416. this.visibilityForced = false;
  3417. this.visibility = false;
  3418. this.options = options || {};
  3419. // create frame
  3420. this.frame = (typeof document !== 'undefined') ? document.createElement('div') : null;
  3421. }
  3422. Panel.prototype = new Component();
  3423. /**
  3424. * Set options. Will extend the current options.
  3425. * @param {Object} [options] Available parameters:
  3426. * {String | function} [className]
  3427. * {String | Number | function} [left]
  3428. * {String | Number | function} [top]
  3429. * {String | Number | function} [width]
  3430. * {String | Number | function} [height]
  3431. */
  3432. Panel.prototype.setOptions = Component.prototype.setOptions;
  3433. /**
  3434. * Get the outer frame of the panel
  3435. * @returns {HTMLElement} frame
  3436. */
  3437. Panel.prototype.getFrame = function () {
  3438. return this.frame;
  3439. };
  3440. /**
  3441. * Append a child to the panel
  3442. * @param {Component} child
  3443. */
  3444. Panel.prototype.appendChild = function (child) {
  3445. this.childs.push(child);
  3446. child.parent = this;
  3447. // attach to the DOM
  3448. var frame = child.getFrame();
  3449. if (frame) {
  3450. if (frame.parentNode) {
  3451. frame.parentNode.removeChild(frame);
  3452. }
  3453. this.frame.appendChild(frame);
  3454. }
  3455. };
  3456. /**
  3457. * Insert a child to the panel
  3458. * @param {Component} child
  3459. * @param {Component} beforeChild
  3460. */
  3461. Panel.prototype.insertBefore = function (child, beforeChild) {
  3462. var index = this.childs.indexOf(beforeChild);
  3463. if (index != -1) {
  3464. this.childs.splice(index, 0, child);
  3465. child.parent = this;
  3466. // attach to the DOM
  3467. var frame = child.getFrame();
  3468. if (frame) {
  3469. if (frame.parentNode) {
  3470. frame.parentNode.removeChild(frame);
  3471. }
  3472. var beforeFrame = beforeChild.getFrame();
  3473. if (beforeFrame) {
  3474. this.frame.insertBefore(frame, beforeFrame);
  3475. }
  3476. else {
  3477. this.frame.appendChild(frame);
  3478. }
  3479. }
  3480. }
  3481. };
  3482. /**
  3483. * Remove a child from the panel
  3484. * @param {Component} child
  3485. */
  3486. Panel.prototype.removeChild = function (child) {
  3487. var index = this.childs.indexOf(child);
  3488. if (index != -1) {
  3489. this.childs.splice(index, 1);
  3490. child.parent = null;
  3491. // remove from the DOM
  3492. var frame = child.getFrame();
  3493. if (frame && frame.parentNode) {
  3494. this.frame.removeChild(frame);
  3495. }
  3496. }
  3497. };
  3498. /**
  3499. * Test whether the panel contains given child
  3500. * @param {Component} child
  3501. */
  3502. Panel.prototype.hasChild = function (child) {
  3503. var index = this.childs.indexOf(child);
  3504. return (index != -1);
  3505. };
  3506. /**
  3507. * Test whether the panel contains given child
  3508. * @param {Component} child
  3509. */
  3510. Panel.prototype.hidePanel = function () {
  3511. this.visibilityForced = true;
  3512. this.visibility = false;
  3513. var frame = this.getFrame();
  3514. if (frame.className.search(" hidden") == -1) {
  3515. frame.className += " hidden";
  3516. }
  3517. };
  3518. /**
  3519. * Test whether the panel contains given child
  3520. * @param {Component} child
  3521. */
  3522. Panel.prototype.showPanel = function () {
  3523. this.visibilityForced = true;
  3524. this.visibility = true;
  3525. var frame = this.getFrame();
  3526. frame.className = frame.className.replace(" hidden","");
  3527. };
  3528. /**
  3529. * Repaint the component
  3530. * @return {boolean} Returns true if the component was resized since previous repaint
  3531. */
  3532. Panel.prototype.repaint = function () {
  3533. var asString = util.option.asString,
  3534. options = this.options,
  3535. frame = this.getFrame();
  3536. // update className
  3537. frame.className = 'vpanel' + (options.className ? (' ' + asString(options.className)) : '');
  3538. if (this.visibilityForced == true && this.visibility == true) {
  3539. this.showPanel();
  3540. }
  3541. else if (this.visibilityForced == true) {
  3542. this.hidePanel();
  3543. }
  3544. // repaint the child components
  3545. var childsResized = this._repaintChilds();
  3546. // update frame size
  3547. this._updateSize();
  3548. return this._isResized() || childsResized;
  3549. };
  3550. /**
  3551. * Repaint all childs of the panel
  3552. * @return {boolean} Returns true if the component is resized
  3553. * @private
  3554. */
  3555. Panel.prototype._repaintChilds = function () {
  3556. var resized = false;
  3557. for (var i = 0, ii = this.childs.length; i < ii; i++) {
  3558. resized = this.childs[i].repaint() || resized;
  3559. }
  3560. return resized;
  3561. };
  3562. /**
  3563. * Apply the size from options to the panel, and recalculate it's actual size.
  3564. * @private
  3565. */
  3566. Panel.prototype._updateSize = function () {
  3567. // apply size
  3568. this.frame.style.top = util.option.asSize(this.options.top);
  3569. this.frame.style.bottom = util.option.asSize(this.options.bottom);
  3570. this.frame.style.left = util.option.asSize(this.options.left);
  3571. this.frame.style.right = util.option.asSize(this.options.right);
  3572. this.frame.style.width = util.option.asSize(this.options.width, '100%');
  3573. this.frame.style.height = util.option.asSize(this.options.height, '');
  3574. // get actual size
  3575. this.top = this.frame.offsetTop;
  3576. this.left = this.frame.offsetLeft;
  3577. this.width = this.frame.offsetWidth;
  3578. this.height = this.frame.offsetHeight;
  3579. };
  3580. /**
  3581. * A root panel can hold components. The root panel must be initialized with
  3582. * a DOM element as container.
  3583. * @param {HTMLElement} container
  3584. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3585. * @constructor RootPanel
  3586. * @extends Panel
  3587. */
  3588. function RootPanel(container, options) {
  3589. this.id = util.randomUUID();
  3590. this.container = container;
  3591. this.options = options || {};
  3592. this.defaultOptions = {
  3593. autoResize: true
  3594. };
  3595. // create the HTML DOM
  3596. this._create();
  3597. // attach the root panel to the provided container
  3598. if (!this.container) throw new Error('Cannot repaint root panel: no container attached');
  3599. this.container.appendChild(this.getFrame());
  3600. this._initWatch();
  3601. }
  3602. RootPanel.prototype = new Panel();
  3603. /**
  3604. * Create the HTML DOM for the root panel
  3605. */
  3606. RootPanel.prototype._create = function _create() {
  3607. // create frame
  3608. this.frame = document.createElement('div');
  3609. // create event listeners for all interesting events, these events will be
  3610. // emitted via emitter
  3611. this.hammer = Hammer(this.frame, {
  3612. prevent_default: true
  3613. });
  3614. this.listeners = {};
  3615. var me = this;
  3616. var events = [
  3617. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3618. 'dragstart', 'drag', 'dragend',
  3619. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3620. ];
  3621. events.forEach(function (event) {
  3622. var listener = function () {
  3623. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3624. me.emit.apply(me, args);
  3625. };
  3626. me.hammer.on(event, listener);
  3627. me.listeners[event] = listener;
  3628. });
  3629. };
  3630. /**
  3631. * Set options. Will extend the current options.
  3632. * @param {Object} [options] Available parameters:
  3633. * {String | function} [className]
  3634. * {String | Number | function} [left]
  3635. * {String | Number | function} [top]
  3636. * {String | Number | function} [width]
  3637. * {String | Number | function} [height]
  3638. * {Boolean | function} [autoResize]
  3639. */
  3640. RootPanel.prototype.setOptions = function setOptions(options) {
  3641. if (options) {
  3642. util.extend(this.options, options);
  3643. this.repaint();
  3644. this._initWatch();
  3645. }
  3646. };
  3647. /**
  3648. * Get the frame of the root panel
  3649. */
  3650. RootPanel.prototype.getFrame = function getFrame() {
  3651. return this.frame;
  3652. };
  3653. /**
  3654. * Repaint the root panel
  3655. */
  3656. RootPanel.prototype.repaint = function repaint() {
  3657. // update class name
  3658. var options = this.options;
  3659. var editable = options.editable.updateTime || options.editable.updateGroup;
  3660. var className = 'vis timeline rootpanel ' + options.orientation + (editable ? ' editable' : '');
  3661. if (options.className) className += ' ' + util.option.asString(className);
  3662. this.frame.className = className;
  3663. // repaint the child components
  3664. var childsResized = this._repaintChilds();
  3665. // update frame size
  3666. this.frame.style.maxHeight = util.option.asSize(this.options.maxHeight, '');
  3667. this._updateSize();
  3668. // if the root panel or any of its childs is resized, repaint again,
  3669. // as other components may need to be resized accordingly
  3670. var resized = this._isResized() || childsResized;
  3671. if (resized) {
  3672. setTimeout(this.repaint.bind(this), 0);
  3673. }
  3674. };
  3675. /**
  3676. * Initialize watching when option autoResize is true
  3677. * @private
  3678. */
  3679. RootPanel.prototype._initWatch = function _initWatch() {
  3680. var autoResize = this.getOption('autoResize');
  3681. if (autoResize) {
  3682. this._watch();
  3683. }
  3684. else {
  3685. this._unwatch();
  3686. }
  3687. };
  3688. /**
  3689. * Watch for changes in the size of the frame. On resize, the Panel will
  3690. * automatically redraw itself.
  3691. * @private
  3692. */
  3693. RootPanel.prototype._watch = function _watch() {
  3694. var me = this;
  3695. this._unwatch();
  3696. var checkSize = function checkSize() {
  3697. var autoResize = me.getOption('autoResize');
  3698. if (!autoResize) {
  3699. // stop watching when the option autoResize is changed to false
  3700. me._unwatch();
  3701. return;
  3702. }
  3703. if (me.frame) {
  3704. // check whether the frame is resized
  3705. if ((me.frame.clientWidth != me.lastWidth) ||
  3706. (me.frame.clientHeight != me.lastHeight)) {
  3707. me.lastWidth = me.frame.clientWidth;
  3708. me.lastHeight = me.frame.clientHeight;
  3709. me.repaint();
  3710. // TODO: emit a resize event instead?
  3711. }
  3712. }
  3713. };
  3714. // TODO: automatically cleanup the event listener when the frame is deleted
  3715. util.addEventListener(window, 'resize', checkSize);
  3716. this.watchTimer = setInterval(checkSize, 1000);
  3717. };
  3718. /**
  3719. * Stop watching for a resize of the frame.
  3720. * @private
  3721. */
  3722. RootPanel.prototype._unwatch = function _unwatch() {
  3723. if (this.watchTimer) {
  3724. clearInterval(this.watchTimer);
  3725. this.watchTimer = undefined;
  3726. }
  3727. // TODO: remove event listener on window.resize
  3728. };
  3729. /**
  3730. * A horizontal time axis
  3731. * @param {Object} [options] See DataAxis.setOptions for the available
  3732. * options.
  3733. * @constructor DataAxis
  3734. * @extends Component
  3735. */
  3736. function DataAxis (options) {
  3737. this.id = util.randomUUID();
  3738. this.dom = {
  3739. majorLines: [],
  3740. majorTexts: [],
  3741. minorLines: [],
  3742. minorTexts: [],
  3743. redundant: {
  3744. majorLines: [],
  3745. majorTexts: [],
  3746. minorLines: [],
  3747. minorTexts: []
  3748. }
  3749. };
  3750. this.props = {
  3751. range: {
  3752. start: 0,
  3753. end: 0,
  3754. minimumStep: 0
  3755. },
  3756. lineTop: 0
  3757. };
  3758. this.options = options || {};
  3759. this.defaultOptions = {
  3760. orientation: 'left', // supported: 'left'
  3761. showMinorLabels: true,
  3762. showMajorLabels: true
  3763. };
  3764. this.range = null;
  3765. this.conversionFactor = 1;
  3766. // create the HTML DOM
  3767. this._create();
  3768. }
  3769. DataAxis.prototype = new Component();
  3770. // TODO: comment options
  3771. DataAxis.prototype.setOptions = Component.prototype.setOptions;
  3772. /**
  3773. * Create the HTML DOM for the DataAxis
  3774. */
  3775. DataAxis.prototype._create = function _create() {
  3776. this.frame = document.createElement('div');
  3777. };
  3778. /**
  3779. * Set a range (start and end)
  3780. * @param {Range | Object} range A Range or an object containing start and end.
  3781. */
  3782. DataAxis.prototype.setRange = function (range) {
  3783. console.log(range, range.start, range.end, !range, !range.start, !range.end);
  3784. if (!(range instanceof Range) && (!range || range.start === undefined || range.end === undefined)) {
  3785. throw new TypeError('Range must be an instance of Range, ' +
  3786. 'or an object containing start and end.');
  3787. }
  3788. this.range = range;
  3789. };
  3790. /**
  3791. * Get the outer frame of the time axis
  3792. * @return {HTMLElement} frame
  3793. */
  3794. DataAxis.prototype.getFrame = function getFrame() {
  3795. return this.frame;
  3796. };
  3797. /**
  3798. * Repaint the component
  3799. * @return {boolean} Returns true if the component is resized
  3800. */
  3801. DataAxis.prototype.repaint = function () {
  3802. var asSize = util.option.asSize;
  3803. var options = this.options;
  3804. var props = this.props;
  3805. var frame = this.frame;
  3806. // update classname
  3807. frame.className = 'dataaxis'; // TODO: add className from options if defined
  3808. // calculate character width and height
  3809. this._calculateCharSize();
  3810. // TODO: recalculate sizes only needed when parent is resized or options is changed
  3811. var orientation = this.getOption('orientation');
  3812. var showMinorLabels = this.getOption('showMinorLabels');
  3813. var showMajorLabels = this.getOption('showMajorLabels');
  3814. // determine the width and height of the elemens for the axis
  3815. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  3816. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  3817. this.height = this.options.height;
  3818. this.width = frame.offsetWidth; // TODO: only update the width when the frame is resized?
  3819. props.minorLineWidth = this.options.svg.offsetWidth;
  3820. props.minorLineHeight = 1; // TODO: really calculate width
  3821. props.majorLineWidth = this.options.svg.offsetWidth;
  3822. props.majorLineHeight = 1; // TODO: really calculate width
  3823. // take frame offline while updating (is almost twice as fast)
  3824. // TODO: top/bottom positioning should be determined by options set in the Timeline, not here
  3825. if (orientation == 'left') {
  3826. frame.style.top = '0';
  3827. frame.style.left = '0';
  3828. frame.style.bottom = '';
  3829. frame.style.width = this.width + 'px';
  3830. frame.style.height = this.height + "px";
  3831. }
  3832. else { // right
  3833. frame.style.top = '';
  3834. frame.style.bottom = '0';
  3835. frame.style.left = '0';
  3836. frame.style.width = this.width + 'px';
  3837. frame.style.height = this.height + "px";
  3838. }
  3839. this._repaintLabels();
  3840. };
  3841. /**
  3842. * Repaint major and minor text labels and vertical grid lines
  3843. * @private
  3844. */
  3845. DataAxis.prototype._repaintLabels = function () {
  3846. var orientation = this.getOption('orientation');
  3847. // calculate range and step (step such that we have space for 7 characters per label)
  3848. var start = this.range.start;
  3849. var end = this.range.end;
  3850. var minimumStep = (this.props.minorCharHeight || 10); //in pixels
  3851. var step = new DataStep(start, end, minimumStep, this.options.svg.offsetHeight);
  3852. this.step = step;
  3853. // Move all DOM elements to a "redundant" list, where they
  3854. // can be picked for re-use, and clear the lists with lines and texts.
  3855. // At the end of the function _repaintLabels, left over elements will be cleaned up
  3856. var dom = this.dom;
  3857. dom.redundant.majorLines = dom.majorLines;
  3858. dom.redundant.majorTexts = dom.majorTexts;
  3859. dom.redundant.minorLines = dom.minorLines;
  3860. dom.redundant.minorTexts = dom.minorTexts;
  3861. dom.majorLines = [];
  3862. dom.majorTexts = [];
  3863. dom.minorLines = [];
  3864. dom.minorTexts = [];
  3865. step.first();
  3866. var stepPixels = this.options.svg.offsetHeight / ((step.marginRange / step.step) + 1);
  3867. var xFirstMajorLabel = undefined;
  3868. this.valueAtZero = step.marginEnd;
  3869. var marginStartPos = 0;
  3870. var max = 0;
  3871. while (step.hasNext() && max < 1000) {
  3872. var y = Math.round(max * stepPixels);
  3873. var isMajor = step.isMajor();
  3874. if (this.getOption('showMinorLabels') && isMajor == false) {
  3875. this._repaintMinorText(y, step.getLabelMinor(), orientation);
  3876. }
  3877. if (isMajor && this.getOption('showMajorLabels')) {
  3878. if (y > 0) {
  3879. if (xFirstMajorLabel == undefined) {
  3880. xFirstMajorLabel = y;
  3881. }
  3882. this._repaintMajorText(y, step.getLabelMajor(), orientation);
  3883. }
  3884. this._repaintMajorLine(y, orientation);
  3885. }
  3886. else {
  3887. this._repaintMinorLine(y, orientation);
  3888. }
  3889. step.next();
  3890. marginStartPos = y;
  3891. max++;
  3892. }
  3893. this.conversionFactor = marginStartPos/step.marginRange;
  3894. // create a major label on the left when needed
  3895. if (this.getOption('showMajorLabels')) {
  3896. var leftPoint = this._start;
  3897. var leftText = step.getLabelMajor(leftPoint);
  3898. var widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  3899. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3900. this._repaintMajorText(0, leftText, orientation);
  3901. }
  3902. }
  3903. // Cleanup leftover DOM elements from the redundant list
  3904. util.forEach(this.dom.redundant, function (arr) {
  3905. while (arr.length) {
  3906. var elem = arr.pop();
  3907. if (elem && elem.parentNode) {
  3908. elem.parentNode.removeChild(elem);
  3909. }
  3910. }
  3911. });
  3912. };
  3913. DataAxis.prototype._getPos = function(value) {
  3914. var invertedValue = this.valueAtZero - value;
  3915. return invertedValue * this.conversionFactor;
  3916. }
  3917. /**
  3918. * Create a minor label for the axis at position x
  3919. * @param {Number} x
  3920. * @param {String} text
  3921. * @param {String} orientation "top" or "bottom" (default)
  3922. * @private
  3923. */
  3924. DataAxis.prototype._repaintMinorText = function (x, text, orientation) {
  3925. // reuse redundant label
  3926. var label = this.dom.redundant.minorTexts.shift();
  3927. if (!label) {
  3928. // create new label
  3929. var content = document.createTextNode('');
  3930. label = document.createElement('div');
  3931. label.appendChild(content);
  3932. label.className = 'yAxis minor';
  3933. this.frame.appendChild(label);
  3934. }
  3935. this.dom.minorTexts.push(label);
  3936. label.childNodes[0].nodeValue = text;
  3937. if (orientation == 'left') {
  3938. label.style.left = '-2px';
  3939. label.style.textAlign = "right";
  3940. }
  3941. else {
  3942. label.style.left = '2px';
  3943. label.style.textAlign = "left";
  3944. }
  3945. label.style.top = x + 'px';
  3946. //label.title = title; // TODO: this is a heavy operation
  3947. };
  3948. /**
  3949. * Create a Major label for the axis at position x
  3950. * @param {Number} x
  3951. * @param {String} text
  3952. * @param {String} orientation "top" or "bottom" (default)
  3953. * @private
  3954. */
  3955. DataAxis.prototype._repaintMajorText = function (x, text, orientation) {
  3956. // reuse redundant label
  3957. var label = this.dom.redundant.majorTexts.shift();
  3958. if (!label) {
  3959. // create label
  3960. var content = document.createTextNode(text);
  3961. label = document.createElement('div');
  3962. label.className = 'yAxis major';
  3963. label.appendChild(content);
  3964. this.frame.appendChild(label);
  3965. }
  3966. this.dom.majorTexts.push(label);
  3967. label.childNodes[0].nodeValue = text;
  3968. //label.title = title; // TODO: this is a heavy operation
  3969. if (orientation == 'left') {
  3970. label.style.left = '-2px';
  3971. label.style.textAlign = "right";
  3972. }
  3973. else {
  3974. label.style.left = '2';
  3975. label.style.textAlign = "left";
  3976. }
  3977. label.style.top = x + 'px';
  3978. };
  3979. /**
  3980. * Create a minor line for the axis at position x
  3981. * @param {Number} x
  3982. * @param {String} orientation "top" or "bottom" (default)
  3983. * @private
  3984. */
  3985. DataAxis.prototype._repaintMinorLine = function (x, orientation) {
  3986. // reuse redundant line
  3987. var line = this.dom.redundant.minorLines.shift();
  3988. if (!line) {
  3989. // create vertical line
  3990. line = document.createElement('div');
  3991. line.className = 'grid horizontal minor';
  3992. this.frame.appendChild(line);
  3993. }
  3994. this.dom.minorLines.push(line);
  3995. var props = this.props;
  3996. if (orientation == 'left') {
  3997. line.style.left = (this.width - 15) + 'px';
  3998. }
  3999. else {
  4000. line.style.left = -1*(this.width - 15) + 'px';
  4001. }
  4002. line.style.width = props.minorLineWidth + 'px';
  4003. line.style.top = (x - props.minorLineHeight / 2) + 'px';
  4004. };
  4005. /**
  4006. * Create a Major line for the axis at position x
  4007. * @param {Number} x
  4008. * @param {String} orientation "top" or "bottom" (default)
  4009. * @private
  4010. */
  4011. DataAxis.prototype._repaintMajorLine = function (x, orientation) {
  4012. // reuse redundant line
  4013. var line = this.dom.redundant.majorLines.shift();
  4014. if (!line) {
  4015. // create vertical line
  4016. line = document.createElement('div');
  4017. line.className = 'grid horizontal major';
  4018. this.frame.appendChild(line);
  4019. }
  4020. this.dom.majorLines.push(line);
  4021. var props = this.props;
  4022. if (orientation == 'left') {
  4023. line.style.left = (this.width - 25) + 'px';
  4024. }
  4025. else {
  4026. line.style.left = -1*(this.width - 25) + 'px';
  4027. }
  4028. line.style.top = (x - props.majorLineHeight / 2) + 'px';
  4029. line.style.width = props.majorLineWidth + 'px';
  4030. };
  4031. /**
  4032. * Determine the size of text on the axis (both major and minor axis).
  4033. * The size is calculated only once and then cached in this.props.
  4034. * @private
  4035. */
  4036. DataAxis.prototype._calculateCharSize = function () {
  4037. // determine the char width and height on the minor axis
  4038. if (!('minorCharHeight' in this.props)) {
  4039. var textMinor = document.createTextNode('0');
  4040. var measureCharMinor = document.createElement('DIV');
  4041. measureCharMinor.className = 'text minor measure';
  4042. measureCharMinor.appendChild(textMinor);
  4043. this.frame.appendChild(measureCharMinor);
  4044. this.props.minorCharHeight = measureCharMinor.clientHeight;
  4045. this.props.minorCharWidth = measureCharMinor.clientWidth;
  4046. this.frame.removeChild(measureCharMinor);
  4047. }
  4048. if (!('majorCharHeight' in this.props)) {
  4049. var textMajor = document.createTextNode('0');
  4050. var measureCharMajor = document.createElement('DIV');
  4051. measureCharMajor.className = 'text major measure';
  4052. measureCharMajor.appendChild(textMajor);
  4053. this.frame.appendChild(measureCharMajor);
  4054. this.props.majorCharHeight = measureCharMajor.clientHeight;
  4055. this.props.majorCharWidth = measureCharMajor.clientWidth;
  4056. this.frame.removeChild(measureCharMajor);
  4057. }
  4058. };
  4059. /**
  4060. * Snap a date to a rounded value.
  4061. * The snap intervals are dependent on the current scale and step.
  4062. * @param {Date} date the date to be snapped.
  4063. * @return {Date} snappedDate
  4064. */
  4065. DataAxis.prototype.snap = function snap (date) {
  4066. return this.step.snap(date);
  4067. };
  4068. /**
  4069. * A horizontal time axis
  4070. * @param {Object} [options] See TimeAxis.setOptions for the available
  4071. * options.
  4072. * @constructor TimeAxis
  4073. * @extends Component
  4074. */
  4075. function TimeAxis (options) {
  4076. this.id = util.randomUUID();
  4077. this.dom = {
  4078. majorLines: [],
  4079. majorTexts: [],
  4080. minorLines: [],
  4081. minorTexts: [],
  4082. redundant: {
  4083. majorLines: [],
  4084. majorTexts: [],
  4085. minorLines: [],
  4086. minorTexts: []
  4087. }
  4088. };
  4089. this.props = {
  4090. range: {
  4091. start: 0,
  4092. end: 0,
  4093. minimumStep: 0
  4094. },
  4095. lineTop: 0
  4096. };
  4097. this.options = options || {};
  4098. this.defaultOptions = {
  4099. orientation: 'bottom', // supported: 'top', 'bottom'
  4100. // TODO: implement timeaxis orientations 'left' and 'right'
  4101. showMinorLabels: true,
  4102. showMajorLabels: true
  4103. };
  4104. this.range = null;
  4105. // create the HTML DOM
  4106. this._create();
  4107. }
  4108. TimeAxis.prototype = new Component();
  4109. // TODO: comment options
  4110. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  4111. /**
  4112. * Create the HTML DOM for the TimeAxis
  4113. */
  4114. TimeAxis.prototype._create = function _create() {
  4115. this.frame = document.createElement('div');
  4116. };
  4117. /**
  4118. * Set a range (start and end)
  4119. * @param {Range | Object} range A Range or an object containing start and end.
  4120. */
  4121. TimeAxis.prototype.setRange = function (range) {
  4122. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4123. throw new TypeError('Range must be an instance of Range, ' +
  4124. 'or an object containing start and end.');
  4125. }
  4126. this.range = range;
  4127. };
  4128. /**
  4129. * Get the outer frame of the time axis
  4130. * @return {HTMLElement} frame
  4131. */
  4132. TimeAxis.prototype.getFrame = function getFrame() {
  4133. return this.frame;
  4134. };
  4135. /**
  4136. * Repaint the component
  4137. * @return {boolean} Returns true if the component is resized
  4138. */
  4139. TimeAxis.prototype.repaint = function () {
  4140. var asSize = util.option.asSize,
  4141. options = this.options,
  4142. props = this.props,
  4143. frame = this.frame;
  4144. // update classname
  4145. frame.className = 'timeaxis'; // TODO: add className from options if defined
  4146. var parent = frame.parentNode;
  4147. if (parent) {
  4148. // calculate character width and height
  4149. this._calculateCharSize();
  4150. // TODO: recalculate sizes only needed when parent is resized or options is changed
  4151. var orientation = this.getOption('orientation'),
  4152. showMinorLabels = this.getOption('showMinorLabels'),
  4153. showMajorLabels = this.getOption('showMajorLabels');
  4154. // determine the width and height of the elemens for the axis
  4155. var parentHeight = this.parent.height;
  4156. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4157. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4158. this.height = props.minorLabelHeight + props.majorLabelHeight;
  4159. this.width = frame.offsetWidth; // TODO: only update the width when the frame is resized?
  4160. props.minorLineHeight = parentHeight + props.minorLabelHeight;
  4161. props.minorLineWidth = 1; // TODO: really calculate width
  4162. props.majorLineHeight = parentHeight + this.height;
  4163. props.majorLineWidth = 1; // TODO: really calculate width
  4164. // take frame offline while updating (is almost twice as fast)
  4165. var beforeChild = frame.nextSibling;
  4166. parent.removeChild(frame);
  4167. // TODO: top/bottom positioning should be determined by options set in the Timeline, not here
  4168. if (orientation == 'top') {
  4169. frame.style.top = '0';
  4170. frame.style.left = '0';
  4171. frame.style.bottom = '';
  4172. frame.style.width = asSize(options.width, '100%');
  4173. frame.style.height = this.height + 'px';
  4174. }
  4175. else { // bottom
  4176. frame.style.top = '';
  4177. frame.style.bottom = '0';
  4178. frame.style.left = '0';
  4179. frame.style.width = asSize(options.width, '100%');
  4180. frame.style.height = this.height + 'px';
  4181. }
  4182. this._repaintLabels();
  4183. this._repaintLine();
  4184. // put frame online again
  4185. if (beforeChild) {
  4186. parent.insertBefore(frame, beforeChild);
  4187. }
  4188. else {
  4189. parent.appendChild(frame)
  4190. }
  4191. }
  4192. return this._isResized();
  4193. };
  4194. /**
  4195. * Repaint major and minor text labels and vertical grid lines
  4196. * @private
  4197. */
  4198. TimeAxis.prototype._repaintLabels = function () {
  4199. var orientation = this.getOption('orientation');
  4200. // calculate range and step (step such that we have space for 7 characters per label)
  4201. var start = util.convert(this.range.start, 'Number'),
  4202. end = util.convert(this.range.end, 'Number'),
  4203. minimumStep = this.options.toTime((this.props.minorCharWidth || 10) * 7).valueOf()
  4204. -this.options.toTime(0).valueOf();
  4205. var step = new TimeStep(new Date(start), new Date(end), minimumStep);
  4206. this.step = step;
  4207. // Move all DOM elements to a "redundant" list, where they
  4208. // can be picked for re-use, and clear the lists with lines and texts.
  4209. // At the end of the function _repaintLabels, left over elements will be cleaned up
  4210. var dom = this.dom;
  4211. dom.redundant.majorLines = dom.majorLines;
  4212. dom.redundant.majorTexts = dom.majorTexts;
  4213. dom.redundant.minorLines = dom.minorLines;
  4214. dom.redundant.minorTexts = dom.minorTexts;
  4215. dom.majorLines = [];
  4216. dom.majorTexts = [];
  4217. dom.minorLines = [];
  4218. dom.minorTexts = [];
  4219. step.first();
  4220. var xFirstMajorLabel = undefined;
  4221. var max = 0;
  4222. while (step.hasNext() && max < 1000) {
  4223. max++;
  4224. var cur = step.getCurrent(),
  4225. x = this.options.toScreen(cur),
  4226. isMajor = step.isMajor();
  4227. // TODO: lines must have a width, such that we can create css backgrounds
  4228. if (this.getOption('showMinorLabels')) {
  4229. this._repaintMinorText(x, step.getLabelMinor(), orientation);
  4230. }
  4231. if (isMajor && this.getOption('showMajorLabels')) {
  4232. if (x > 0) {
  4233. if (xFirstMajorLabel == undefined) {
  4234. xFirstMajorLabel = x;
  4235. }
  4236. this._repaintMajorText(x, step.getLabelMajor(), orientation);
  4237. }
  4238. this._repaintMajorLine(x, orientation);
  4239. }
  4240. else {
  4241. this._repaintMinorLine(x, orientation);
  4242. }
  4243. step.next();
  4244. }
  4245. // create a major label on the left when needed
  4246. if (this.getOption('showMajorLabels')) {
  4247. var leftTime = this.options.toTime(0),
  4248. leftText = step.getLabelMajor(leftTime),
  4249. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  4250. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  4251. this._repaintMajorText(0, leftText, orientation);
  4252. }
  4253. }
  4254. // Cleanup leftover DOM elements from the redundant list
  4255. util.forEach(this.dom.redundant, function (arr) {
  4256. while (arr.length) {
  4257. var elem = arr.pop();
  4258. if (elem && elem.parentNode) {
  4259. elem.parentNode.removeChild(elem);
  4260. }
  4261. }
  4262. });
  4263. };
  4264. /**
  4265. * Create a minor label for the axis at position x
  4266. * @param {Number} x
  4267. * @param {String} text
  4268. * @param {String} orientation "top" or "bottom" (default)
  4269. * @private
  4270. */
  4271. TimeAxis.prototype._repaintMinorText = function (x, text, orientation) {
  4272. // reuse redundant label
  4273. var label = this.dom.redundant.minorTexts.shift();
  4274. if (!label) {
  4275. // create new label
  4276. var content = document.createTextNode('');
  4277. label = document.createElement('div');
  4278. label.appendChild(content);
  4279. label.className = 'text minor';
  4280. this.frame.appendChild(label);
  4281. }
  4282. this.dom.minorTexts.push(label);
  4283. label.childNodes[0].nodeValue = text;
  4284. if (orientation == 'top') {
  4285. label.style.top = this.props.majorLabelHeight + 'px';
  4286. label.style.bottom = '';
  4287. }
  4288. else {
  4289. label.style.top = '';
  4290. label.style.bottom = this.props.majorLabelHeight + 'px';
  4291. }
  4292. label.style.left = x + 'px';
  4293. //label.title = title; // TODO: this is a heavy operation
  4294. };
  4295. /**
  4296. * Create a Major label for the axis at position x
  4297. * @param {Number} x
  4298. * @param {String} text
  4299. * @param {String} orientation "top" or "bottom" (default)
  4300. * @private
  4301. */
  4302. TimeAxis.prototype._repaintMajorText = function (x, text, orientation) {
  4303. // reuse redundant label
  4304. var label = this.dom.redundant.majorTexts.shift();
  4305. if (!label) {
  4306. // create label
  4307. var content = document.createTextNode(text);
  4308. label = document.createElement('div');
  4309. label.className = 'text major';
  4310. label.appendChild(content);
  4311. this.frame.appendChild(label);
  4312. }
  4313. this.dom.majorTexts.push(label);
  4314. label.childNodes[0].nodeValue = text;
  4315. //label.title = title; // TODO: this is a heavy operation
  4316. if (orientation == 'top') {
  4317. label.style.top = '0px';
  4318. label.style.bottom = '';
  4319. }
  4320. else {
  4321. label.style.top = '';
  4322. label.style.bottom = '0px';
  4323. }
  4324. label.style.left = x + 'px';
  4325. };
  4326. /**
  4327. * Create a minor line for the axis at position x
  4328. * @param {Number} x
  4329. * @param {String} orientation "top" or "bottom" (default)
  4330. * @private
  4331. */
  4332. TimeAxis.prototype._repaintMinorLine = function (x, orientation) {
  4333. // reuse redundant line
  4334. var line = this.dom.redundant.minorLines.shift();
  4335. if (!line) {
  4336. // create vertical line
  4337. line = document.createElement('div');
  4338. line.className = 'grid vertical minor';
  4339. this.frame.appendChild(line);
  4340. }
  4341. this.dom.minorLines.push(line);
  4342. var props = this.props;
  4343. if (orientation == 'top') {
  4344. line.style.top = this.props.majorLabelHeight + 'px';
  4345. line.style.bottom = '';
  4346. }
  4347. else {
  4348. line.style.top = '';
  4349. line.style.bottom = this.props.majorLabelHeight + 'px';
  4350. }
  4351. line.style.height = props.minorLineHeight + 'px';
  4352. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  4353. };
  4354. /**
  4355. * Create a Major line for the axis at position x
  4356. * @param {Number} x
  4357. * @param {String} orientation "top" or "bottom" (default)
  4358. * @private
  4359. */
  4360. TimeAxis.prototype._repaintMajorLine = function (x, orientation) {
  4361. // reuse redundant line
  4362. var line = this.dom.redundant.majorLines.shift();
  4363. if (!line) {
  4364. // create vertical line
  4365. line = document.createElement('DIV');
  4366. line.className = 'grid vertical major';
  4367. this.frame.appendChild(line);
  4368. }
  4369. this.dom.majorLines.push(line);
  4370. var props = this.props;
  4371. if (orientation == 'top') {
  4372. line.style.top = '0px';
  4373. line.style.bottom = '';
  4374. }
  4375. else {
  4376. line.style.top = '';
  4377. line.style.bottom = '0px';
  4378. }
  4379. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4380. line.style.height = props.majorLineHeight + 'px';
  4381. };
  4382. /**
  4383. * Repaint the horizontal line for the axis
  4384. * @private
  4385. */
  4386. TimeAxis.prototype._repaintLine = function() {
  4387. var line = this.dom.line,
  4388. frame = this.frame,
  4389. orientation = this.getOption('orientation');
  4390. // line before all axis elements
  4391. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4392. if (line) {
  4393. // put this line at the end of all childs
  4394. frame.removeChild(line);
  4395. frame.appendChild(line);
  4396. }
  4397. else {
  4398. // create the axis line
  4399. line = document.createElement('div');
  4400. line.className = 'grid horizontal major';
  4401. frame.appendChild(line);
  4402. this.dom.line = line;
  4403. }
  4404. if (orientation == 'top') {
  4405. line.style.top = this.height + 'px';
  4406. line.style.bottom = '';
  4407. }
  4408. else {
  4409. line.style.top = '';
  4410. line.style.bottom = this.height + 'px';
  4411. }
  4412. }
  4413. else {
  4414. if (line && line.parentNode) {
  4415. line.parentNode.removeChild(line);
  4416. delete this.dom.line;
  4417. }
  4418. }
  4419. };
  4420. /**
  4421. * Determine the size of text on the axis (both major and minor axis).
  4422. * The size is calculated only once and then cached in this.props.
  4423. * @private
  4424. */
  4425. TimeAxis.prototype._calculateCharSize = function () {
  4426. // determine the char width and height on the minor axis
  4427. if (!('minorCharHeight' in this.props)) {
  4428. var textMinor = document.createTextNode('0');
  4429. var measureCharMinor = document.createElement('DIV');
  4430. measureCharMinor.className = 'text minor measure';
  4431. measureCharMinor.appendChild(textMinor);
  4432. this.frame.appendChild(measureCharMinor);
  4433. this.props.minorCharHeight = measureCharMinor.clientHeight;
  4434. this.props.minorCharWidth = measureCharMinor.clientWidth;
  4435. this.frame.removeChild(measureCharMinor);
  4436. }
  4437. if (!('majorCharHeight' in this.props)) {
  4438. var textMajor = document.createTextNode('0');
  4439. var measureCharMajor = document.createElement('DIV');
  4440. measureCharMajor.className = 'text major measure';
  4441. measureCharMajor.appendChild(textMajor);
  4442. this.frame.appendChild(measureCharMajor);
  4443. this.props.majorCharHeight = measureCharMajor.clientHeight;
  4444. this.props.majorCharWidth = measureCharMajor.clientWidth;
  4445. this.frame.removeChild(measureCharMajor);
  4446. }
  4447. };
  4448. /**
  4449. * Snap a date to a rounded value.
  4450. * The snap intervals are dependent on the current scale and step.
  4451. * @param {Date} date the date to be snapped.
  4452. * @return {Date} snappedDate
  4453. */
  4454. TimeAxis.prototype.snap = function snap (date) {
  4455. return this.step.snap(date);
  4456. };
  4457. /**
  4458. * A current time bar
  4459. * @param {Range} range
  4460. * @param {Object} [options] Available parameters:
  4461. * {Boolean} [showCurrentTime]
  4462. * @constructor CurrentTime
  4463. * @extends Component
  4464. */
  4465. function CurrentTime (range, options) {
  4466. this.id = util.randomUUID();
  4467. this.range = range;
  4468. this.options = options || {};
  4469. this.defaultOptions = {
  4470. showCurrentTime: false
  4471. };
  4472. this._create();
  4473. }
  4474. CurrentTime.prototype = new Component();
  4475. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  4476. /**
  4477. * Create the HTML DOM for the current time bar
  4478. * @private
  4479. */
  4480. CurrentTime.prototype._create = function _create () {
  4481. var bar = document.createElement('div');
  4482. bar.className = 'currenttime';
  4483. bar.style.position = 'absolute';
  4484. bar.style.top = '0px';
  4485. bar.style.height = '100%';
  4486. this.bar = bar;
  4487. };
  4488. /**
  4489. * Get the frame element of the current time bar
  4490. * @returns {HTMLElement} frame
  4491. */
  4492. CurrentTime.prototype.getFrame = function getFrame() {
  4493. return this.bar;
  4494. };
  4495. /**
  4496. * Repaint the component
  4497. * @return {boolean} Returns true if the component is resized
  4498. */
  4499. CurrentTime.prototype.repaint = function repaint() {
  4500. var parent = this.parent;
  4501. var now = new Date();
  4502. var x = this.options.toScreen(now);
  4503. this.bar.style.left = x + 'px';
  4504. this.bar.title = 'Current time: ' + now;
  4505. return false;
  4506. };
  4507. /**
  4508. * Start auto refreshing the current time bar
  4509. */
  4510. CurrentTime.prototype.start = function start() {
  4511. var me = this;
  4512. function update () {
  4513. me.stop();
  4514. // determine interval to refresh
  4515. var scale = me.range.conversion(me.parent.width).scale;
  4516. var interval = 1 / scale / 10;
  4517. if (interval < 30) interval = 30;
  4518. if (interval > 1000) interval = 1000;
  4519. me.repaint();
  4520. // start a timer to adjust for the new time
  4521. me.currentTimeTimer = setTimeout(update, interval);
  4522. }
  4523. update();
  4524. };
  4525. /**
  4526. * Stop auto refreshing the current time bar
  4527. */
  4528. CurrentTime.prototype.stop = function stop() {
  4529. if (this.currentTimeTimer !== undefined) {
  4530. clearTimeout(this.currentTimeTimer);
  4531. delete this.currentTimeTimer;
  4532. }
  4533. };
  4534. /**
  4535. * A custom time bar
  4536. * @param {Object} [options] Available parameters:
  4537. * {Boolean} [showCustomTime]
  4538. * @constructor CustomTime
  4539. * @extends Component
  4540. */
  4541. function CustomTime (options) {
  4542. this.id = util.randomUUID();
  4543. this.options = options || {};
  4544. this.defaultOptions = {
  4545. showCustomTime: false
  4546. };
  4547. this.customTime = new Date();
  4548. this.eventParams = {}; // stores state parameters while dragging the bar
  4549. // create the DOM
  4550. this._create();
  4551. }
  4552. CustomTime.prototype = new Component();
  4553. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4554. /**
  4555. * Create the DOM for the custom time
  4556. * @private
  4557. */
  4558. CustomTime.prototype._create = function _create () {
  4559. var bar = document.createElement('div');
  4560. bar.className = 'customtime';
  4561. bar.style.position = 'absolute';
  4562. bar.style.top = '0px';
  4563. bar.style.height = '100%';
  4564. this.bar = bar;
  4565. var drag = document.createElement('div');
  4566. drag.style.position = 'relative';
  4567. drag.style.top = '0px';
  4568. drag.style.left = '-10px';
  4569. drag.style.height = '100%';
  4570. drag.style.width = '20px';
  4571. bar.appendChild(drag);
  4572. // attach event listeners
  4573. this.hammer = Hammer(bar, {
  4574. prevent_default: true
  4575. });
  4576. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4577. this.hammer.on('drag', this._onDrag.bind(this));
  4578. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4579. };
  4580. /**
  4581. * Get the frame element of the custom time bar
  4582. * @returns {HTMLElement} frame
  4583. */
  4584. CustomTime.prototype.getFrame = function getFrame() {
  4585. return this.bar;
  4586. };
  4587. /**
  4588. * Repaint the component
  4589. * @return {boolean} Returns true if the component is resized
  4590. */
  4591. CustomTime.prototype.repaint = function () {
  4592. var x = this.options.toScreen(this.customTime);
  4593. this.bar.style.left = x + 'px';
  4594. this.bar.title = 'Time: ' + this.customTime;
  4595. return false;
  4596. };
  4597. /**
  4598. * Set custom time.
  4599. * @param {Date} time
  4600. */
  4601. CustomTime.prototype.setCustomTime = function(time) {
  4602. this.customTime = new Date(time.valueOf());
  4603. this.repaint();
  4604. };
  4605. /**
  4606. * Retrieve the current custom time.
  4607. * @return {Date} customTime
  4608. */
  4609. CustomTime.prototype.getCustomTime = function() {
  4610. return new Date(this.customTime.valueOf());
  4611. };
  4612. /**
  4613. * Start moving horizontally
  4614. * @param {Event} event
  4615. * @private
  4616. */
  4617. CustomTime.prototype._onDragStart = function(event) {
  4618. this.eventParams.dragging = true;
  4619. this.eventParams.customTime = this.customTime;
  4620. event.stopPropagation();
  4621. event.preventDefault();
  4622. };
  4623. /**
  4624. * Perform moving operating.
  4625. * @param {Event} event
  4626. * @private
  4627. */
  4628. CustomTime.prototype._onDrag = function (event) {
  4629. if (!this.eventParams.dragging) return;
  4630. var deltaX = event.gesture.deltaX,
  4631. x = this.options.toScreen(this.eventParams.customTime) + deltaX,
  4632. time = this.options.toTime(x);
  4633. this.setCustomTime(time);
  4634. // fire a timechange event
  4635. this.emit('timechange', {
  4636. time: new Date(this.customTime.valueOf())
  4637. });
  4638. event.stopPropagation();
  4639. event.preventDefault();
  4640. };
  4641. /**
  4642. * Stop moving operating.
  4643. * @param {event} event
  4644. * @private
  4645. */
  4646. CustomTime.prototype._onDragEnd = function (event) {
  4647. if (!this.eventParams.dragging) return;
  4648. // fire a timechanged event
  4649. this.emit('timechanged', {
  4650. time: new Date(this.customTime.valueOf())
  4651. });
  4652. event.stopPropagation();
  4653. event.preventDefault();
  4654. };
  4655. /**
  4656. * Created by Alex on 5/6/14.
  4657. */
  4658. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  4659. /**
  4660. * An ItemSet holds a set of items and ranges which can be displayed in a
  4661. * range. The width is determined by the parent of the ItemSet, and the height
  4662. * is determined by the size of the items.
  4663. * @param {Panel} backgroundPanel Panel which can be used to display the
  4664. * vertical lines of box items.
  4665. * @param {Panel} axisPanel Panel on the axis where the dots of box-items
  4666. * can be displayed.
  4667. * @param {Panel} sidePanel Left side panel holding labels
  4668. * @param {Object} [options] See ItemSet.setOptions for the available options.
  4669. * @constructor ItemSet
  4670. * @extends Panel
  4671. */
  4672. function Linegraph(backgroundPanel, axisPanel, sidePanel, options, timeline, sidePanelParent) {
  4673. this.id = util.randomUUID();
  4674. this.timeline = timeline;
  4675. // one options object is shared by this itemset and all its items
  4676. this.options = options || {};
  4677. this.backgroundPanel = backgroundPanel;
  4678. this.axisPanel = axisPanel;
  4679. this.sidePanel = sidePanel;
  4680. this.sidePanelParent = sidePanelParent;
  4681. this.itemOptions = Object.create(this.options);
  4682. this.dom = {};
  4683. this.hammer = null;
  4684. this.itemsData = null; // DataSet
  4685. this.groupsData = null; // DataSet
  4686. this.range = null; // Range or Object {start: number, end: number}
  4687. // listeners for the DataSet of the items
  4688. // this.itemListeners = {
  4689. // 'add': function(event, params, senderId) {
  4690. // if (senderId != me.id) me._onAdd(params.items);
  4691. // },
  4692. // 'update': function(event, params, senderId) {
  4693. // if (senderId != me.id) me._onUpdate(params.items);
  4694. // },
  4695. // 'remove': function(event, params, senderId) {
  4696. // if (senderId != me.id) me._onRemove(params.items);
  4697. // }
  4698. // };
  4699. //
  4700. // // listeners for the DataSet of the groups
  4701. // this.groupListeners = {
  4702. // 'add': function(event, params, senderId) {
  4703. // if (senderId != me.id) me._onAddGroups(params.items);
  4704. // },
  4705. // 'update': function(event, params, senderId) {
  4706. // if (senderId != me.id) me._onUpdateGroups(params.items);
  4707. // },
  4708. // 'remove': function(event, params, senderId) {
  4709. // if (senderId != me.id) me._onRemoveGroups(params.items);
  4710. // }
  4711. // };
  4712. this.items = {}; // object with an Item for every data item
  4713. this.groups = {}; // Group object for every group
  4714. this.groupIds = [];
  4715. this.selection = []; // list with the ids of all selected nodes
  4716. this.stackDirty = true; // if true, all items will be restacked on next repaint
  4717. this.touchParams = {}; // stores properties while dragging
  4718. // create the HTML DOM
  4719. this.lastStart = 0;
  4720. this._create();
  4721. var me = this;
  4722. this.timeline.on("rangechange", function() {
  4723. if (me.lastStart != 0) {
  4724. var offset = me.range.start - me.lastStart;
  4725. var range = me.range.end - me.range.start;
  4726. if (me.width != 0) {
  4727. var rangePerPixelInv = me.width/range;
  4728. var xOffset = offset * rangePerPixelInv;
  4729. me.svg.style.left = util.option.asSize(-me.width - xOffset);
  4730. }
  4731. }
  4732. })
  4733. this.timeline.on("rangechanged", function() {
  4734. me.lastStart = me.range.start;
  4735. me.svg.style.left = util.option.asSize(-me.width);
  4736. me.setData.apply(me);
  4737. });
  4738. }
  4739. Linegraph.prototype = new Panel();
  4740. /**
  4741. * Create the HTML DOM for the ItemSet
  4742. */
  4743. Linegraph.prototype._create = function(){
  4744. var frame = document.createElement('div');
  4745. frame['timeline-linegraph'] = this;
  4746. this.frame = frame;
  4747. this.frame.className = 'itemset';
  4748. // create background panel
  4749. var background = document.createElement('div');
  4750. background.className = 'background';
  4751. this.backgroundPanel.frame.appendChild(background);
  4752. this.dom.background = background;
  4753. // create foreground panel
  4754. var foreground = document.createElement('div');
  4755. foreground.className = 'foreground';
  4756. frame.appendChild(foreground);
  4757. this.dom.foreground = foreground;
  4758. // // create axis panel
  4759. // var axis = document.createElement('div');
  4760. // axis.className = 'axis';
  4761. // this.dom.axis = axis;
  4762. // this.axisPanel.frame.appendChild(axis);
  4763. //
  4764. // // create labelset
  4765. // var labelSet = document.createElement('div');
  4766. // labelSet.className = 'labelset';
  4767. // this.dom.labelSet = labelSet;
  4768. // this.sidePanel.frame.appendChild(labelSet);
  4769. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
  4770. this.svg.style.position = "relative"
  4771. this.svg.style.height = "300px";
  4772. this.path = document.createElementNS('http://www.w3.org/2000/svg',"path");
  4773. this.path.setAttributeNS(null, "fill","none");
  4774. this.path.setAttributeNS(null, "stroke","blue");
  4775. this.path.setAttributeNS(null, "stroke-width","1");
  4776. this.path2 = document.createElementNS('http://www.w3.org/2000/svg',"path");
  4777. this.path2.setAttributeNS(null, "fill","none");
  4778. this.path2.setAttributeNS(null, "stroke","red");
  4779. this.path2.setAttributeNS(null, "stroke-width","2");
  4780. this.dom.foreground.appendChild(this.svg);
  4781. this.svg.appendChild(this.path2);
  4782. this.svg.appendChild(this.path);
  4783. // this.yAxisDiv = document.createElement('div');
  4784. // this.yAxisDiv.style.backgroundColor = 'rgb(220,220,220)';
  4785. // this.yAxisDiv.style.width = '100px';
  4786. // this.yAxisDiv.style.height = this.svg.style.height;
  4787. this._createAxis();
  4788. // this.dom.yAxisDiv = this.yAxisDiv;
  4789. // this.sidePanel.frame.appendChild(this.yAxisDiv);
  4790. this.sidePanel.showPanel.apply(this.sidePanel);
  4791. this.sidePanelParent.showPanel();
  4792. };
  4793. Linegraph.prototype._createAxis = function() {
  4794. // panel with time axis
  4795. var dataAxisOptions = {
  4796. range: this.range,
  4797. left: null,
  4798. top: null,
  4799. width: null,
  4800. height: 300,
  4801. svg: this.svg
  4802. };
  4803. this.yAxis = new DataAxis(dataAxisOptions);
  4804. this.yAxis.setRange({start:-60,end:260});
  4805. this.sidePanel.frame.appendChild(this.yAxis.getFrame());
  4806. }
  4807. Linegraph.prototype.setData = function() {
  4808. var data = [];
  4809. this.yAxis.repaint();
  4810. this.startTime = this.range.start;
  4811. var min = Date.now() - 3600000 * 24 * 30;
  4812. var max = Date.now() + 3600000 * 24 * 10;
  4813. var count = 60;
  4814. var step = (max-min) / count;
  4815. var range = this.range.end - this.range.start;
  4816. if (this.width != 0) {
  4817. var rangePerPixel = range/this.width;
  4818. var rangePerPixelInv = this.width/range;
  4819. var xOffset = -this.range.start + this.width*rangePerPixel;
  4820. for (var i = 0; i < count; i++) {
  4821. data.push({x:(min + i*step + xOffset) * rangePerPixelInv, y: 250*(i%2) + 25})
  4822. }
  4823. // catmull rom
  4824. var p0, p1, p2, p3, bp1, bp2, bp3;
  4825. var d2 = "M" + data[0].x + "," + data[0].y + " ";
  4826. for (var i = 0; i < data.length - 2; i++) {
  4827. if (i == 0) {
  4828. p0 = data[0]
  4829. }
  4830. else {
  4831. p0 = data[i-1];
  4832. }
  4833. p1 = data[i];
  4834. p2 = data[i+1];
  4835. p3 = data[i+2];
  4836. // Catmull-Rom to Cubic Bezier conversion matrix
  4837. // 0 1 0 0
  4838. // -1/6 1 1/6 0
  4839. // 0 1/6 1 -1/6
  4840. // 0 0 1 0
  4841. // bp0 = { x: p1.x, y: p1.y };
  4842. bp1 = { x: ((-p0.x + 6*p1.x + p2.x) / 6), y: ((-p0.y + 6*p1.y + p2.y) / 6)};
  4843. bp2 = { x: ((p1.x + 6*p2.x - p3.x) / 6), y: ((p1.y + 6*p2.y - p3.y) / 6)};
  4844. bp3 = { x: p2.x, y: p2.y };
  4845. d2 += "C" + bp1.x + "," + bp1.y + " " + bp2.x + "," + bp2.y + " " + bp3.x + "," + bp3.y + " ";
  4846. }
  4847. // linear
  4848. var d = "";
  4849. for (var i = 0; i < data.length - 1; i++) {
  4850. if (i == 0) {
  4851. d += "M" + data[i].x + "," + data[i].y;
  4852. }
  4853. else {
  4854. d += " " + data[i].x + "," + data[i].y;
  4855. }
  4856. }
  4857. this.path.setAttributeNS(null, "d",d);
  4858. this.path2.setAttributeNS(null, "d",d2);
  4859. }
  4860. }
  4861. /**
  4862. * Set options for the Linegraph. Existing options will be extended/overwritten.
  4863. * @param {Object} [options] The following options are available:
  4864. * {String | function} [className]
  4865. * class name for the itemset
  4866. * {String} [type]
  4867. * Default type for the items. Choose from 'box'
  4868. * (default), 'point', or 'range'. The default
  4869. * Style can be overwritten by individual items.
  4870. * {String} align
  4871. * Alignment for the items, only applicable for
  4872. * ItemBox. Choose 'center' (default), 'left', or
  4873. * 'right'.
  4874. * {String} orientation
  4875. * Orientation of the item set. Choose 'top' or
  4876. * 'bottom' (default).
  4877. * {Number} margin.axis
  4878. * Margin between the axis and the items in pixels.
  4879. * Default is 20.
  4880. * {Number} margin.item
  4881. * Margin between items in pixels. Default is 10.
  4882. * {Number} padding
  4883. * Padding of the contents of an item in pixels.
  4884. * Must correspond with the items css. Default is 5.
  4885. * {Function} snap
  4886. * Function to let items snap to nice dates when
  4887. * dragging items.
  4888. */
  4889. Linegraph.prototype.setOptions = function(options) {
  4890. Component.prototype.setOptions.call(this, options);
  4891. };
  4892. /**
  4893. * Set range (start and end).
  4894. * @param {Range | Object} range A Range or an object containing start and end.
  4895. */
  4896. Linegraph.prototype.setRange = function(range) {
  4897. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4898. throw new TypeError('Range must be an instance of Range, ' +
  4899. 'or an object containing start and end.');
  4900. }
  4901. this.range = range;
  4902. };
  4903. Linegraph.prototype.repaint = function() {
  4904. var margin = this.options.margin,
  4905. range = this.range,
  4906. asSize = util.option.asSize,
  4907. asString = util.option.asString,
  4908. options = this.options,
  4909. orientation = this.getOption('orientation'),
  4910. resized = false,
  4911. frame = this.frame;
  4912. // TODO: document this feature to specify one margin for both item and axis distance
  4913. if (typeof margin === 'number') {
  4914. margin = {
  4915. item: margin,
  4916. axis: margin
  4917. };
  4918. }
  4919. // update className
  4920. this.frame.className = 'itemset' + (options.className ? (' ' + asString(options.className)) : '');
  4921. // check whether zoomed (in that case we need to re-stack everything)
  4922. // TODO: would be nicer to get this as a trigger from Range
  4923. var visibleInterval = this.range.end - this.range.start;
  4924. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth);
  4925. if (zoomed) this.stackDirty = true;
  4926. this.lastVisibleInterval = visibleInterval;
  4927. this.lastWidth = this.width;
  4928. // reposition frame
  4929. this.frame.style.left = asSize(options.left, '');
  4930. this.frame.style.right = asSize(options.right, '');
  4931. this.frame.style.top = asSize((orientation == 'top') ? '0' : '');
  4932. this.frame.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4933. this.frame.style.width = asSize(options.width, '100%');
  4934. // frame.style.height = asSize(height);
  4935. //frame.style.height = asSize('height' in options ? options.height : height); // TODO: reckon with height
  4936. // calculate actual size and position
  4937. this.top = this.frame.offsetTop;
  4938. this.left = this.frame.offsetLeft;
  4939. this.width = this.frame.offsetWidth;
  4940. // this.height = height;
  4941. // check if this component is resized
  4942. resized = this._isResized() || resized;
  4943. if (resized) {
  4944. this.svg.style.width = asSize(3*this.width);
  4945. this.svg.style.left = asSize(-this.width);
  4946. }
  4947. if (zoomed) {
  4948. this.setData();
  4949. }
  4950. }
  4951. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  4952. /**
  4953. * An ItemSet holds a set of items and ranges which can be displayed in a
  4954. * range. The width is determined by the parent of the ItemSet, and the height
  4955. * is determined by the size of the items.
  4956. * @param {Panel} backgroundPanel Panel which can be used to display the
  4957. * vertical lines of box items.
  4958. * @param {Panel} axisPanel Panel on the axis where the dots of box-items
  4959. * can be displayed.
  4960. * @param {Panel} sidePanel Left side panel holding labels
  4961. * @param {Object} [options] See ItemSet.setOptions for the available options.
  4962. * @constructor ItemSet
  4963. * @extends Panel
  4964. */
  4965. function ItemSet(backgroundPanel, axisPanel, sidePanel, options) {
  4966. this.id = util.randomUUID();
  4967. // one options object is shared by this itemset and all its items
  4968. this.options = options || {};
  4969. this.backgroundPanel = backgroundPanel;
  4970. this.axisPanel = axisPanel;
  4971. this.sidePanel = sidePanel;
  4972. this.itemOptions = Object.create(this.options);
  4973. this.dom = {};
  4974. this.hammer = null;
  4975. var me = this;
  4976. this.itemsData = null; // DataSet
  4977. this.groupsData = null; // DataSet
  4978. this.range = null; // Range or Object {start: number, end: number}
  4979. // listeners for the DataSet of the items
  4980. this.itemListeners = {
  4981. 'add': function (event, params, senderId) {
  4982. if (senderId != me.id) me._onAdd(params.items);
  4983. },
  4984. 'update': function (event, params, senderId) {
  4985. if (senderId != me.id) me._onUpdate(params.items);
  4986. },
  4987. 'remove': function (event, params, senderId) {
  4988. if (senderId != me.id) me._onRemove(params.items);
  4989. }
  4990. };
  4991. // listeners for the DataSet of the groups
  4992. this.groupListeners = {
  4993. 'add': function (event, params, senderId) {
  4994. if (senderId != me.id) me._onAddGroups(params.items);
  4995. },
  4996. 'update': function (event, params, senderId) {
  4997. if (senderId != me.id) me._onUpdateGroups(params.items);
  4998. },
  4999. 'remove': function (event, params, senderId) {
  5000. if (senderId != me.id) me._onRemoveGroups(params.items);
  5001. }
  5002. };
  5003. this.items = {}; // object with an Item for every data item
  5004. this.groups = {}; // Group object for every group
  5005. this.groupIds = [];
  5006. this.selection = []; // list with the ids of all selected nodes
  5007. this.stackDirty = true; // if true, all items will be restacked on next repaint
  5008. this.touchParams = {}; // stores properties while dragging
  5009. // create the HTML DOM
  5010. this._create();
  5011. }
  5012. ItemSet.prototype = new Panel();
  5013. // available item types will be registered here
  5014. ItemSet.types = {
  5015. box: ItemBox,
  5016. range: ItemRange,
  5017. rangeoverflow: ItemRangeOverflow,
  5018. point: ItemPoint
  5019. };
  5020. /**
  5021. * Create the HTML DOM for the ItemSet
  5022. */
  5023. ItemSet.prototype._create = function _create(){
  5024. var frame = document.createElement('div');
  5025. frame['timeline-itemset'] = this;
  5026. this.frame = frame;
  5027. // create background panel
  5028. var background = document.createElement('div');
  5029. background.className = 'background';
  5030. this.backgroundPanel.frame.appendChild(background);
  5031. this.dom.background = background;
  5032. // create foreground panel
  5033. var foreground = document.createElement('div');
  5034. foreground.className = 'foreground';
  5035. frame.appendChild(foreground);
  5036. this.dom.foreground = foreground;
  5037. // create axis panel
  5038. var axis = document.createElement('div');
  5039. axis.className = 'axis';
  5040. this.dom.axis = axis;
  5041. this.axisPanel.frame.appendChild(axis);
  5042. // create labelset
  5043. var labelSet = document.createElement('div');
  5044. labelSet.className = 'labelset';
  5045. this.dom.labelSet = labelSet;
  5046. this.sidePanel.frame.appendChild(labelSet);
  5047. // create ungrouped Group
  5048. this._updateUngrouped();
  5049. // attach event listeners
  5050. // TODO: use event listeners from the rootpanel to improve performance?
  5051. this.hammer = Hammer(frame, {
  5052. prevent_default: true
  5053. });
  5054. this.hammer.on('dragstart', this._onDragStart.bind(this));
  5055. this.hammer.on('drag', this._onDrag.bind(this));
  5056. this.hammer.on('dragend', this._onDragEnd.bind(this));
  5057. };
  5058. /**
  5059. * Set options for the ItemSet. Existing options will be extended/overwritten.
  5060. * @param {Object} [options] The following options are available:
  5061. * {String | function} [className]
  5062. * class name for the itemset
  5063. * {String} [type]
  5064. * Default type for the items. Choose from 'box'
  5065. * (default), 'point', or 'range'. The default
  5066. * Style can be overwritten by individual items.
  5067. * {String} align
  5068. * Alignment for the items, only applicable for
  5069. * ItemBox. Choose 'center' (default), 'left', or
  5070. * 'right'.
  5071. * {String} orientation
  5072. * Orientation of the item set. Choose 'top' or
  5073. * 'bottom' (default).
  5074. * {Number} margin.axis
  5075. * Margin between the axis and the items in pixels.
  5076. * Default is 20.
  5077. * {Number} margin.item
  5078. * Margin between items in pixels. Default is 10.
  5079. * {Number} padding
  5080. * Padding of the contents of an item in pixels.
  5081. * Must correspond with the items css. Default is 5.
  5082. * {Function} snap
  5083. * Function to let items snap to nice dates when
  5084. * dragging items.
  5085. */
  5086. ItemSet.prototype.setOptions = function setOptions(options) {
  5087. Component.prototype.setOptions.call(this, options);
  5088. };
  5089. /**
  5090. * Mark the ItemSet dirty so it will refresh everything with next repaint
  5091. */
  5092. ItemSet.prototype.markDirty = function markDirty() {
  5093. this.groupIds = [];
  5094. this.stackDirty = true;
  5095. };
  5096. /**
  5097. * Hide the component from the DOM
  5098. */
  5099. ItemSet.prototype.hide = function hide() {
  5100. // remove the axis with dots
  5101. if (this.dom.axis.parentNode) {
  5102. this.dom.axis.parentNode.removeChild(this.dom.axis);
  5103. }
  5104. // remove the background with vertical lines
  5105. if (this.dom.background.parentNode) {
  5106. this.dom.background.parentNode.removeChild(this.dom.background);
  5107. }
  5108. // remove the labelset containing all group labels
  5109. if (this.dom.labelSet.parentNode) {
  5110. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  5111. }
  5112. };
  5113. /**
  5114. * Show the component in the DOM (when not already visible).
  5115. * @return {Boolean} changed
  5116. */
  5117. ItemSet.prototype.show = function show() {
  5118. // show axis with dots
  5119. if (!this.dom.axis.parentNode) {
  5120. this.axisPanel.frame.appendChild(this.dom.axis);
  5121. }
  5122. // show background with vertical lines
  5123. if (!this.dom.background.parentNode) {
  5124. this.backgroundPanel.frame.appendChild(this.dom.background);
  5125. }
  5126. // show labelset containing labels
  5127. if (!this.dom.labelSet.parentNode) {
  5128. this.sidePanel.frame.appendChild(this.dom.labelSet);
  5129. }
  5130. };
  5131. /**
  5132. * Set range (start and end).
  5133. * @param {Range | Object} range A Range or an object containing start and end.
  5134. */
  5135. ItemSet.prototype.setRange = function setRange(range) {
  5136. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  5137. throw new TypeError('Range must be an instance of Range, ' +
  5138. 'or an object containing start and end.');
  5139. }
  5140. this.range = range;
  5141. };
  5142. /**
  5143. * Set selected items by their id. Replaces the current selection
  5144. * Unknown id's are silently ignored.
  5145. * @param {Array} [ids] An array with zero or more id's of the items to be
  5146. * selected. If ids is an empty array, all items will be
  5147. * unselected.
  5148. */
  5149. ItemSet.prototype.setSelection = function setSelection(ids) {
  5150. var i, ii, id, item;
  5151. if (ids) {
  5152. if (!Array.isArray(ids)) {
  5153. throw new TypeError('Array expected');
  5154. }
  5155. // unselect currently selected items
  5156. for (i = 0, ii = this.selection.length; i < ii; i++) {
  5157. id = this.selection[i];
  5158. item = this.items[id];
  5159. if (item) item.unselect();
  5160. }
  5161. // select items
  5162. this.selection = [];
  5163. for (i = 0, ii = ids.length; i < ii; i++) {
  5164. id = ids[i];
  5165. item = this.items[id];
  5166. if (item) {
  5167. this.selection.push(id);
  5168. item.select();
  5169. }
  5170. }
  5171. }
  5172. };
  5173. /**
  5174. * Get the selected items by their id
  5175. * @return {Array} ids The ids of the selected items
  5176. */
  5177. ItemSet.prototype.getSelection = function getSelection() {
  5178. return this.selection.concat([]);
  5179. };
  5180. /**
  5181. * Deselect a selected item
  5182. * @param {String | Number} id
  5183. * @private
  5184. */
  5185. ItemSet.prototype._deselect = function _deselect(id) {
  5186. var selection = this.selection;
  5187. for (var i = 0, ii = selection.length; i < ii; i++) {
  5188. if (selection[i] == id) { // non-strict comparison!
  5189. selection.splice(i, 1);
  5190. break;
  5191. }
  5192. }
  5193. };
  5194. /**
  5195. * Return the item sets frame
  5196. * @returns {HTMLElement} frame
  5197. */
  5198. ItemSet.prototype.getFrame = function getFrame() {
  5199. return this.frame;
  5200. };
  5201. /**
  5202. * Repaint the component
  5203. * @return {boolean} Returns true if the component is resized
  5204. */
  5205. ItemSet.prototype.repaint = function repaint() {
  5206. var margin = this.options.margin,
  5207. range = this.range,
  5208. asSize = util.option.asSize,
  5209. asString = util.option.asString,
  5210. options = this.options,
  5211. orientation = this.getOption('orientation'),
  5212. resized = false,
  5213. frame = this.frame;
  5214. // TODO: document this feature to specify one margin for both item and axis distance
  5215. if (typeof margin === 'number') {
  5216. margin = {
  5217. item: margin,
  5218. axis: margin
  5219. };
  5220. }
  5221. // update className
  5222. frame.className = 'itemset' + (options.className ? (' ' + asString(options.className)) : '');
  5223. // reorder the groups (if needed)
  5224. resized = this._orderGroups() || resized;
  5225. // check whether zoomed (in that case we need to re-stack everything)
  5226. // TODO: would be nicer to get this as a trigger from Range
  5227. var visibleInterval = this.range.end - this.range.start;
  5228. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth);
  5229. if (zoomed) this.stackDirty = true;
  5230. this.lastVisibleInterval = visibleInterval;
  5231. this.lastWidth = this.width;
  5232. // repaint all groups
  5233. var restack = this.stackDirty,
  5234. firstGroup = this._firstGroup(),
  5235. firstMargin = {
  5236. item: margin.item,
  5237. axis: margin.axis
  5238. },
  5239. nonFirstMargin = {
  5240. item: margin.item,
  5241. axis: margin.item / 2
  5242. },
  5243. height = 0,
  5244. minHeight = margin.axis + margin.item;
  5245. util.forEach(this.groups, function (group) {
  5246. var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
  5247. resized = group.repaint(range, groupMargin, restack) || resized;
  5248. height += group.height;
  5249. });
  5250. height = Math.max(height, minHeight);
  5251. this.stackDirty = false;
  5252. // reposition frame
  5253. frame.style.left = asSize(options.left, '');
  5254. frame.style.right = asSize(options.right, '');
  5255. frame.style.top = asSize((orientation == 'top') ? '0' : '');
  5256. frame.style.bottom = asSize((orientation == 'top') ? '' : '0');
  5257. frame.style.width = asSize(options.width, '100%');
  5258. frame.style.height = asSize(height);
  5259. //frame.style.height = asSize('height' in options ? options.height : height); // TODO: reckon with height
  5260. // calculate actual size and position
  5261. this.top = frame.offsetTop;
  5262. this.left = frame.offsetLeft;
  5263. this.width = frame.offsetWidth;
  5264. this.height = height;
  5265. // reposition axis
  5266. this.dom.axis.style.left = asSize(options.left, '0');
  5267. this.dom.axis.style.right = asSize(options.right, '');
  5268. this.dom.axis.style.width = asSize(options.width, '100%');
  5269. this.dom.axis.style.height = asSize(0);
  5270. this.dom.axis.style.top = asSize((orientation == 'top') ? '0' : '');
  5271. this.dom.axis.style.bottom = asSize((orientation == 'top') ? '' : '0');
  5272. // check if this component is resized
  5273. resized = this._isResized() || resized;
  5274. return resized;
  5275. };
  5276. /**
  5277. * Get the first group, aligned with the axis
  5278. * @return {Group | null} firstGroup
  5279. * @private
  5280. */
  5281. ItemSet.prototype._firstGroup = function _firstGroup() {
  5282. var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1);
  5283. var firstGroupId = this.groupIds[firstGroupIndex];
  5284. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  5285. return firstGroup || null;
  5286. };
  5287. /**
  5288. * Create or delete the group holding all ungrouped items. This group is used when
  5289. * there are no groups specified.
  5290. * @protected
  5291. */
  5292. ItemSet.prototype._updateUngrouped = function _updateUngrouped() {
  5293. var ungrouped = this.groups[UNGROUPED];
  5294. if (this.groupsData) {
  5295. // remove the group holding all ungrouped items
  5296. if (ungrouped) {
  5297. ungrouped.hide();
  5298. delete this.groups[UNGROUPED];
  5299. }
  5300. }
  5301. else {
  5302. // create a group holding all (unfiltered) items
  5303. if (!ungrouped) {
  5304. var id = null;
  5305. var data = null;
  5306. ungrouped = new Group(id, data, this);
  5307. this.groups[UNGROUPED] = ungrouped;
  5308. for (var itemId in this.items) {
  5309. if (this.items.hasOwnProperty(itemId)) {
  5310. ungrouped.add(this.items[itemId]);
  5311. }
  5312. }
  5313. ungrouped.show();
  5314. }
  5315. }
  5316. };
  5317. /**
  5318. * Get the foreground container element
  5319. * @return {HTMLElement} foreground
  5320. */
  5321. ItemSet.prototype.getForeground = function getForeground() {
  5322. return this.dom.foreground;
  5323. };
  5324. /**
  5325. * Get the background container element
  5326. * @return {HTMLElement} background
  5327. */
  5328. ItemSet.prototype.getBackground = function getBackground() {
  5329. return this.dom.background;
  5330. };
  5331. /**
  5332. * Get the axis container element
  5333. * @return {HTMLElement} axis
  5334. */
  5335. ItemSet.prototype.getAxis = function getAxis() {
  5336. return this.dom.axis;
  5337. };
  5338. /**
  5339. * Get the element for the labelset
  5340. * @return {HTMLElement} labelSet
  5341. */
  5342. ItemSet.prototype.getLabelSet = function getLabelSet() {
  5343. return this.dom.labelSet;
  5344. };
  5345. /**
  5346. * Set items
  5347. * @param {vis.DataSet | null} items
  5348. */
  5349. ItemSet.prototype.setItems = function setItems(items) {
  5350. var me = this,
  5351. ids,
  5352. oldItemsData = this.itemsData;
  5353. // replace the dataset
  5354. if (!items) {
  5355. this.itemsData = null;
  5356. }
  5357. else if (items instanceof DataSet || items instanceof DataView) {
  5358. this.itemsData = items;
  5359. }
  5360. else {
  5361. throw new TypeError('Data must be an instance of DataSet or DataView');
  5362. }
  5363. if (oldItemsData) {
  5364. // unsubscribe from old dataset
  5365. util.forEach(this.itemListeners, function (callback, event) {
  5366. oldItemsData.unsubscribe(event, callback);
  5367. });
  5368. // remove all drawn items
  5369. ids = oldItemsData.getIds();
  5370. this._onRemove(ids);
  5371. }
  5372. if (this.itemsData) {
  5373. // subscribe to new dataset
  5374. var id = this.id;
  5375. util.forEach(this.itemListeners, function (callback, event) {
  5376. me.itemsData.on(event, callback, id);
  5377. });
  5378. // add all new items
  5379. ids = this.itemsData.getIds();
  5380. this._onAdd(ids);
  5381. // update the group holding all ungrouped items
  5382. this._updateUngrouped();
  5383. }
  5384. };
  5385. /**
  5386. * Get the current items
  5387. * @returns {vis.DataSet | null}
  5388. */
  5389. ItemSet.prototype.getItems = function getItems() {
  5390. return this.itemsData;
  5391. };
  5392. /**
  5393. * Set groups
  5394. * @param {vis.DataSet} groups
  5395. */
  5396. ItemSet.prototype.setGroups = function setGroups(groups) {
  5397. var me = this,
  5398. ids;
  5399. // unsubscribe from current dataset
  5400. if (this.groupsData) {
  5401. util.forEach(this.groupListeners, function (callback, event) {
  5402. me.groupsData.unsubscribe(event, callback);
  5403. });
  5404. // remove all drawn groups
  5405. ids = this.groupsData.getIds();
  5406. this.groupsData = null;
  5407. this._onRemoveGroups(ids); // note: this will cause a repaint
  5408. }
  5409. // replace the dataset
  5410. if (!groups) {
  5411. this.groupsData = null;
  5412. }
  5413. else if (groups instanceof DataSet || groups instanceof DataView) {
  5414. this.groupsData = groups;
  5415. }
  5416. else {
  5417. throw new TypeError('Data must be an instance of DataSet or DataView');
  5418. }
  5419. if (this.groupsData) {
  5420. // subscribe to new dataset
  5421. var id = this.id;
  5422. util.forEach(this.groupListeners, function (callback, event) {
  5423. me.groupsData.on(event, callback, id);
  5424. });
  5425. // draw all ms
  5426. ids = this.groupsData.getIds();
  5427. this._onAddGroups(ids);
  5428. }
  5429. // update the group holding all ungrouped items
  5430. this._updateUngrouped();
  5431. // update the order of all items in each group
  5432. this._order();
  5433. this.emit('change');
  5434. };
  5435. /**
  5436. * Get the current groups
  5437. * @returns {vis.DataSet | null} groups
  5438. */
  5439. ItemSet.prototype.getGroups = function getGroups() {
  5440. return this.groupsData;
  5441. };
  5442. /**
  5443. * Remove an item by its id
  5444. * @param {String | Number} id
  5445. */
  5446. ItemSet.prototype.removeItem = function removeItem (id) {
  5447. var item = this.itemsData.get(id),
  5448. dataset = this._myDataSet();
  5449. if (item) {
  5450. // confirm deletion
  5451. this.options.onRemove(item, function (item) {
  5452. if (item) {
  5453. // remove by id here, it is possible that an item has no id defined
  5454. // itself, so better not delete by the item itself
  5455. dataset.remove(id);
  5456. }
  5457. });
  5458. }
  5459. };
  5460. /**
  5461. * Handle updated items
  5462. * @param {Number[]} ids
  5463. * @protected
  5464. */
  5465. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  5466. var me = this,
  5467. items = this.items,
  5468. itemOptions = this.itemOptions;
  5469. ids.forEach(function (id) {
  5470. var itemData = me.itemsData.get(id),
  5471. item = items[id],
  5472. type = itemData.type ||
  5473. (itemData.start && itemData.end && 'range') ||
  5474. me.options.type ||
  5475. 'box';
  5476. var constructor = ItemSet.types[type];
  5477. if (item) {
  5478. // update item
  5479. if (!constructor || !(item instanceof constructor)) {
  5480. // item type has changed, delete the item and recreate it
  5481. me._removeItem(item);
  5482. item = null;
  5483. }
  5484. else {
  5485. me._updateItem(item, itemData);
  5486. }
  5487. }
  5488. if (!item) {
  5489. // create item
  5490. if (constructor) {
  5491. item = new constructor(itemData, me.options, itemOptions);
  5492. item.id = id; // TODO: not so nice setting id afterwards
  5493. me._addItem(item);
  5494. }
  5495. else {
  5496. throw new TypeError('Unknown item type "' + type + '"');
  5497. }
  5498. }
  5499. });
  5500. this._order();
  5501. this.stackDirty = true; // force re-stacking of all items next repaint
  5502. this.emit('change');
  5503. };
  5504. /**
  5505. * Handle added items
  5506. * @param {Number[]} ids
  5507. * @protected
  5508. */
  5509. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  5510. /**
  5511. * Handle removed items
  5512. * @param {Number[]} ids
  5513. * @protected
  5514. */
  5515. ItemSet.prototype._onRemove = function _onRemove(ids) {
  5516. var count = 0;
  5517. var me = this;
  5518. ids.forEach(function (id) {
  5519. var item = me.items[id];
  5520. if (item) {
  5521. count++;
  5522. me._removeItem(item);
  5523. }
  5524. });
  5525. if (count) {
  5526. // update order
  5527. this._order();
  5528. this.stackDirty = true; // force re-stacking of all items next repaint
  5529. this.emit('change');
  5530. }
  5531. };
  5532. /**
  5533. * Update the order of item in all groups
  5534. * @private
  5535. */
  5536. ItemSet.prototype._order = function _order() {
  5537. // reorder the items in all groups
  5538. // TODO: optimization: only reorder groups affected by the changed items
  5539. util.forEach(this.groups, function (group) {
  5540. group.order();
  5541. });
  5542. };
  5543. /**
  5544. * Handle updated groups
  5545. * @param {Number[]} ids
  5546. * @private
  5547. */
  5548. ItemSet.prototype._onUpdateGroups = function _onUpdateGroups(ids) {
  5549. this._onAddGroups(ids);
  5550. };
  5551. /**
  5552. * Handle changed groups
  5553. * @param {Number[]} ids
  5554. * @private
  5555. */
  5556. ItemSet.prototype._onAddGroups = function _onAddGroups(ids) {
  5557. var me = this;
  5558. ids.forEach(function (id) {
  5559. var groupData = me.groupsData.get(id);
  5560. var group = me.groups[id];
  5561. if (!group) {
  5562. // check for reserved ids
  5563. if (id == UNGROUPED) {
  5564. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  5565. }
  5566. var groupOptions = Object.create(me.options);
  5567. util.extend(groupOptions, {
  5568. height: null
  5569. });
  5570. group = new Group(id, groupData, me);
  5571. me.groups[id] = group;
  5572. // add items with this groupId to the new group
  5573. for (var itemId in me.items) {
  5574. if (me.items.hasOwnProperty(itemId)) {
  5575. var item = me.items[itemId];
  5576. if (item.data.group == id) {
  5577. group.add(item);
  5578. }
  5579. }
  5580. }
  5581. group.order();
  5582. group.show();
  5583. }
  5584. else {
  5585. // update group
  5586. group.setData(groupData);
  5587. }
  5588. });
  5589. this.emit('change');
  5590. };
  5591. /**
  5592. * Handle removed groups
  5593. * @param {Number[]} ids
  5594. * @private
  5595. */
  5596. ItemSet.prototype._onRemoveGroups = function _onRemoveGroups(ids) {
  5597. var groups = this.groups;
  5598. ids.forEach(function (id) {
  5599. var group = groups[id];
  5600. if (group) {
  5601. group.hide();
  5602. delete groups[id];
  5603. }
  5604. });
  5605. this.markDirty();
  5606. this.emit('change');
  5607. };
  5608. /**
  5609. * Reorder the groups if needed
  5610. * @return {boolean} changed
  5611. * @private
  5612. */
  5613. ItemSet.prototype._orderGroups = function () {
  5614. if (this.groupsData) {
  5615. // reorder the groups
  5616. var groupIds = this.groupsData.getIds({
  5617. order: this.options.groupOrder
  5618. });
  5619. var changed = !util.equalArray(groupIds, this.groupIds);
  5620. if (changed) {
  5621. // hide all groups, removes them from the DOM
  5622. var groups = this.groups;
  5623. groupIds.forEach(function (groupId) {
  5624. groups[groupId].hide();
  5625. });
  5626. // show the groups again, attach them to the DOM in correct order
  5627. groupIds.forEach(function (groupId) {
  5628. groups[groupId].show();
  5629. });
  5630. this.groupIds = groupIds;
  5631. }
  5632. return changed;
  5633. }
  5634. else {
  5635. return false;
  5636. }
  5637. };
  5638. /**
  5639. * Add a new item
  5640. * @param {Item} item
  5641. * @private
  5642. */
  5643. ItemSet.prototype._addItem = function _addItem(item) {
  5644. this.items[item.id] = item;
  5645. // add to group
  5646. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  5647. var group = this.groups[groupId];
  5648. if (group) group.add(item);
  5649. };
  5650. /**
  5651. * Update an existing item
  5652. * @param {Item} item
  5653. * @param {Object} itemData
  5654. * @private
  5655. */
  5656. ItemSet.prototype._updateItem = function _updateItem(item, itemData) {
  5657. var oldGroupId = item.data.group;
  5658. item.data = itemData;
  5659. if (item.displayed) {
  5660. item.repaint();
  5661. }
  5662. // update group
  5663. if (oldGroupId != item.data.group) {
  5664. var oldGroup = this.groups[oldGroupId];
  5665. if (oldGroup) oldGroup.remove(item);
  5666. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  5667. var group = this.groups[groupId];
  5668. if (group) group.add(item);
  5669. }
  5670. };
  5671. /**
  5672. * Delete an item from the ItemSet: remove it from the DOM, from the map
  5673. * with items, and from the map with visible items, and from the selection
  5674. * @param {Item} item
  5675. * @private
  5676. */
  5677. ItemSet.prototype._removeItem = function _removeItem(item) {
  5678. // remove from DOM
  5679. item.hide();
  5680. // remove from items
  5681. delete this.items[item.id];
  5682. // remove from selection
  5683. var index = this.selection.indexOf(item.id);
  5684. if (index != -1) this.selection.splice(index, 1);
  5685. // remove from group
  5686. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  5687. var group = this.groups[groupId];
  5688. if (group) group.remove(item);
  5689. };
  5690. /**
  5691. * Create an array containing all items being a range (having an end date)
  5692. * @param array
  5693. * @returns {Array}
  5694. * @private
  5695. */
  5696. ItemSet.prototype._constructByEndArray = function _constructByEndArray(array) {
  5697. var endArray = [];
  5698. for (var i = 0; i < array.length; i++) {
  5699. if (array[i] instanceof ItemRange) {
  5700. endArray.push(array[i]);
  5701. }
  5702. }
  5703. return endArray;
  5704. };
  5705. /**
  5706. * Get the width of the group labels
  5707. * @return {Number} width
  5708. */
  5709. ItemSet.prototype.getLabelsWidth = function getLabelsWidth() {
  5710. var width = 0;
  5711. util.forEach(this.groups, function (group) {
  5712. width = Math.max(width, group.getLabelWidth());
  5713. });
  5714. return width;
  5715. };
  5716. /**
  5717. * Get the height of the itemsets background
  5718. * @return {Number} height
  5719. */
  5720. ItemSet.prototype.getBackgroundHeight = function getBackgroundHeight() {
  5721. return this.height;
  5722. };
  5723. /**
  5724. * Start dragging the selected events
  5725. * @param {Event} event
  5726. * @private
  5727. */
  5728. ItemSet.prototype._onDragStart = function (event) {
  5729. if (!this.options.editable.updateTime && !this.options.editable.updateGroup) {
  5730. return;
  5731. }
  5732. var item = ItemSet.itemFromTarget(event),
  5733. me = this,
  5734. props;
  5735. if (item && item.selected) {
  5736. var dragLeftItem = event.target.dragLeftItem;
  5737. var dragRightItem = event.target.dragRightItem;
  5738. if (dragLeftItem) {
  5739. props = {
  5740. item: dragLeftItem
  5741. };
  5742. if (me.options.editable.updateTime) {
  5743. props.start = item.data.start.valueOf();
  5744. }
  5745. if (me.options.editable.updateGroup) {
  5746. if ('group' in item.data) props.group = item.data.group;
  5747. }
  5748. this.touchParams.itemProps = [props];
  5749. }
  5750. else if (dragRightItem) {
  5751. props = {
  5752. item: dragRightItem
  5753. };
  5754. if (me.options.editable.updateTime) {
  5755. props.end = item.data.end.valueOf();
  5756. }
  5757. if (me.options.editable.updateGroup) {
  5758. if ('group' in item.data) props.group = item.data.group;
  5759. }
  5760. this.touchParams.itemProps = [props];
  5761. }
  5762. else {
  5763. this.touchParams.itemProps = this.getSelection().map(function (id) {
  5764. var item = me.items[id];
  5765. var props = {
  5766. item: item
  5767. };
  5768. if (me.options.editable.updateTime) {
  5769. if ('start' in item.data) props.start = item.data.start.valueOf();
  5770. if ('end' in item.data) props.end = item.data.end.valueOf();
  5771. }
  5772. if (me.options.editable.updateGroup) {
  5773. if ('group' in item.data) props.group = item.data.group;
  5774. }
  5775. return props;
  5776. });
  5777. }
  5778. event.stopPropagation();
  5779. }
  5780. };
  5781. /**
  5782. * Drag selected items
  5783. * @param {Event} event
  5784. * @private
  5785. */
  5786. ItemSet.prototype._onDrag = function (event) {
  5787. if (this.touchParams.itemProps) {
  5788. var snap = this.options.snap || null,
  5789. deltaX = event.gesture.deltaX,
  5790. scale = (this.width / (this.range.end - this.range.start)),
  5791. offset = deltaX / scale;
  5792. // move
  5793. this.touchParams.itemProps.forEach(function (props) {
  5794. if ('start' in props) {
  5795. var start = new Date(props.start + offset);
  5796. props.item.data.start = snap ? snap(start) : start;
  5797. }
  5798. if ('end' in props) {
  5799. var end = new Date(props.end + offset);
  5800. props.item.data.end = snap ? snap(end) : end;
  5801. }
  5802. if ('group' in props) {
  5803. // drag from one group to another
  5804. var group = ItemSet.groupFromTarget(event);
  5805. if (group && group.groupId != props.item.data.group) {
  5806. var oldGroup = props.item.parent;
  5807. oldGroup.remove(props.item);
  5808. oldGroup.order();
  5809. group.add(props.item);
  5810. group.order();
  5811. props.item.data.group = group.groupId;
  5812. }
  5813. }
  5814. });
  5815. // TODO: implement onMoving handler
  5816. this.stackDirty = true; // force re-stacking of all items next repaint
  5817. this.emit('change');
  5818. event.stopPropagation();
  5819. }
  5820. };
  5821. /**
  5822. * End of dragging selected items
  5823. * @param {Event} event
  5824. * @private
  5825. */
  5826. ItemSet.prototype._onDragEnd = function (event) {
  5827. if (this.touchParams.itemProps) {
  5828. // prepare a change set for the changed items
  5829. var changes = [],
  5830. me = this,
  5831. dataset = this._myDataSet();
  5832. this.touchParams.itemProps.forEach(function (props) {
  5833. var id = props.item.id,
  5834. itemData = me.itemsData.get(id);
  5835. var changed = false;
  5836. if ('start' in props.item.data) {
  5837. changed = (props.start != props.item.data.start.valueOf());
  5838. itemData.start = util.convert(props.item.data.start, dataset.convert['start']);
  5839. }
  5840. if ('end' in props.item.data) {
  5841. changed = changed || (props.end != props.item.data.end.valueOf());
  5842. itemData.end = util.convert(props.item.data.end, dataset.convert['end']);
  5843. }
  5844. if ('group' in props.item.data) {
  5845. changed = changed || (props.group != props.item.data.group);
  5846. itemData.group = props.item.data.group;
  5847. }
  5848. // only apply changes when start or end is actually changed
  5849. if (changed) {
  5850. me.options.onMove(itemData, function (itemData) {
  5851. if (itemData) {
  5852. // apply changes
  5853. itemData[dataset.fieldId] = id; // ensure the item contains its id (can be undefined)
  5854. changes.push(itemData);
  5855. }
  5856. else {
  5857. // restore original values
  5858. if ('start' in props) props.item.data.start = props.start;
  5859. if ('end' in props) props.item.data.end = props.end;
  5860. me.stackDirty = true; // force re-stacking of all items next repaint
  5861. me.emit('change');
  5862. }
  5863. });
  5864. }
  5865. });
  5866. this.touchParams.itemProps = null;
  5867. // apply the changes to the data (if there are changes)
  5868. if (changes.length) {
  5869. dataset.update(changes);
  5870. }
  5871. event.stopPropagation();
  5872. }
  5873. };
  5874. /**
  5875. * Find an item from an event target:
  5876. * searches for the attribute 'timeline-item' in the event target's element tree
  5877. * @param {Event} event
  5878. * @return {Item | null} item
  5879. */
  5880. ItemSet.itemFromTarget = function itemFromTarget (event) {
  5881. var target = event.target;
  5882. while (target) {
  5883. if (target.hasOwnProperty('timeline-item')) {
  5884. return target['timeline-item'];
  5885. }
  5886. target = target.parentNode;
  5887. }
  5888. return null;
  5889. };
  5890. /**
  5891. * Find the Group from an event target:
  5892. * searches for the attribute 'timeline-group' in the event target's element tree
  5893. * @param {Event} event
  5894. * @return {Group | null} group
  5895. */
  5896. ItemSet.groupFromTarget = function groupFromTarget (event) {
  5897. var target = event.target;
  5898. while (target) {
  5899. if (target.hasOwnProperty('timeline-group')) {
  5900. return target['timeline-group'];
  5901. }
  5902. target = target.parentNode;
  5903. }
  5904. return null;
  5905. };
  5906. /**
  5907. * Find the ItemSet from an event target:
  5908. * searches for the attribute 'timeline-itemset' in the event target's element tree
  5909. * @param {Event} event
  5910. * @return {ItemSet | null} item
  5911. */
  5912. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  5913. var target = event.target;
  5914. while (target) {
  5915. if (target.hasOwnProperty('timeline-itemset')) {
  5916. return target['timeline-itemset'];
  5917. }
  5918. target = target.parentNode;
  5919. }
  5920. return null;
  5921. };
  5922. /**
  5923. * Find the DataSet to which this ItemSet is connected
  5924. * @returns {null | DataSet} dataset
  5925. * @private
  5926. */
  5927. ItemSet.prototype._myDataSet = function _myDataSet() {
  5928. // find the root DataSet
  5929. var dataset = this.itemsData;
  5930. while (dataset instanceof DataView) {
  5931. dataset = dataset.data;
  5932. }
  5933. return dataset;
  5934. };
  5935. /**
  5936. * @constructor Item
  5937. * @param {Object} data Object containing (optional) parameters type,
  5938. * start, end, content, group, className.
  5939. * @param {Object} [options] Options to set initial property values
  5940. * @param {Object} [defaultOptions] default options
  5941. * // TODO: describe available options
  5942. */
  5943. function Item (data, options, defaultOptions) {
  5944. this.id = null;
  5945. this.parent = null;
  5946. this.data = data;
  5947. this.dom = null;
  5948. this.options = options || {};
  5949. this.defaultOptions = defaultOptions || {};
  5950. this.selected = false;
  5951. this.displayed = false;
  5952. this.dirty = true;
  5953. this.top = null;
  5954. this.left = null;
  5955. this.width = null;
  5956. this.height = null;
  5957. }
  5958. /**
  5959. * Select current item
  5960. */
  5961. Item.prototype.select = function select() {
  5962. this.selected = true;
  5963. if (this.displayed) this.repaint();
  5964. };
  5965. /**
  5966. * Unselect current item
  5967. */
  5968. Item.prototype.unselect = function unselect() {
  5969. this.selected = false;
  5970. if (this.displayed) this.repaint();
  5971. };
  5972. /**
  5973. * Set a parent for the item
  5974. * @param {ItemSet | Group} parent
  5975. */
  5976. Item.prototype.setParent = function setParent(parent) {
  5977. if (this.displayed) {
  5978. this.hide();
  5979. this.parent = parent;
  5980. if (this.parent) {
  5981. this.show();
  5982. }
  5983. }
  5984. else {
  5985. this.parent = parent;
  5986. }
  5987. };
  5988. /**
  5989. * Check whether this item is visible inside given range
  5990. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5991. * @returns {boolean} True if visible
  5992. */
  5993. Item.prototype.isVisible = function isVisible (range) {
  5994. // Should be implemented by Item implementations
  5995. return false;
  5996. };
  5997. /**
  5998. * Show the Item in the DOM (when not already visible)
  5999. * @return {Boolean} changed
  6000. */
  6001. Item.prototype.show = function show() {
  6002. return false;
  6003. };
  6004. /**
  6005. * Hide the Item from the DOM (when visible)
  6006. * @return {Boolean} changed
  6007. */
  6008. Item.prototype.hide = function hide() {
  6009. return false;
  6010. };
  6011. /**
  6012. * Repaint the item
  6013. */
  6014. Item.prototype.repaint = function repaint() {
  6015. // should be implemented by the item
  6016. };
  6017. /**
  6018. * Reposition the Item horizontally
  6019. */
  6020. Item.prototype.repositionX = function repositionX() {
  6021. // should be implemented by the item
  6022. };
  6023. /**
  6024. * Reposition the Item vertically
  6025. */
  6026. Item.prototype.repositionY = function repositionY() {
  6027. // should be implemented by the item
  6028. };
  6029. /**
  6030. * Repaint a delete button on the top right of the item when the item is selected
  6031. * @param {HTMLElement} anchor
  6032. * @protected
  6033. */
  6034. Item.prototype._repaintDeleteButton = function (anchor) {
  6035. if (this.selected && this.options.editable.remove && !this.dom.deleteButton) {
  6036. // create and show button
  6037. var me = this;
  6038. var deleteButton = document.createElement('div');
  6039. deleteButton.className = 'delete';
  6040. deleteButton.title = 'Delete this item';
  6041. Hammer(deleteButton, {
  6042. preventDefault: true
  6043. }).on('tap', function (event) {
  6044. me.parent.removeFromDataSet(me);
  6045. event.stopPropagation();
  6046. });
  6047. anchor.appendChild(deleteButton);
  6048. this.dom.deleteButton = deleteButton;
  6049. }
  6050. else if (!this.selected && this.dom.deleteButton) {
  6051. // remove button
  6052. if (this.dom.deleteButton.parentNode) {
  6053. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  6054. }
  6055. this.dom.deleteButton = null;
  6056. }
  6057. };
  6058. /**
  6059. * @constructor ItemBox
  6060. * @extends Item
  6061. * @param {Object} data Object containing parameters start
  6062. * content, className.
  6063. * @param {Object} [options] Options to set initial property values
  6064. * @param {Object} [defaultOptions] default options
  6065. * // TODO: describe available options
  6066. */
  6067. function ItemBox (data, options, defaultOptions) {
  6068. this.props = {
  6069. dot: {
  6070. width: 0,
  6071. height: 0
  6072. },
  6073. line: {
  6074. width: 0,
  6075. height: 0
  6076. }
  6077. };
  6078. // validate data
  6079. if (data) {
  6080. if (data.start == undefined) {
  6081. throw new Error('Property "start" missing in item ' + data);
  6082. }
  6083. }
  6084. Item.call(this, data, options, defaultOptions);
  6085. }
  6086. ItemBox.prototype = new Item (null);
  6087. /**
  6088. * Check whether this item is visible inside given range
  6089. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  6090. * @returns {boolean} True if visible
  6091. */
  6092. ItemBox.prototype.isVisible = function isVisible (range) {
  6093. // determine visibility
  6094. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  6095. var interval = (range.end - range.start) / 4;
  6096. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  6097. };
  6098. /**
  6099. * Repaint the item
  6100. */
  6101. ItemBox.prototype.repaint = function repaint() {
  6102. var dom = this.dom;
  6103. if (!dom) {
  6104. // create DOM
  6105. this.dom = {};
  6106. dom = this.dom;
  6107. // create main box
  6108. dom.box = document.createElement('DIV');
  6109. // contents box (inside the background box). used for making margins
  6110. dom.content = document.createElement('DIV');
  6111. dom.content.className = 'content';
  6112. dom.box.appendChild(dom.content);
  6113. // line to axis
  6114. dom.line = document.createElement('DIV');
  6115. dom.line.className = 'line';
  6116. // dot on axis
  6117. dom.dot = document.createElement('DIV');
  6118. dom.dot.className = 'dot';
  6119. // attach this item as attribute
  6120. dom.box['timeline-item'] = this;
  6121. }
  6122. // append DOM to parent DOM
  6123. if (!this.parent) {
  6124. throw new Error('Cannot repaint item: no parent attached');
  6125. }
  6126. if (!dom.box.parentNode) {
  6127. var foreground = this.parent.getForeground();
  6128. if (!foreground) throw new Error('Cannot repaint time axis: parent has no foreground container element');
  6129. foreground.appendChild(dom.box);
  6130. }
  6131. if (!dom.line.parentNode) {
  6132. var background = this.parent.getBackground();
  6133. if (!background) throw new Error('Cannot repaint time axis: parent has no background container element');
  6134. background.appendChild(dom.line);
  6135. }
  6136. if (!dom.dot.parentNode) {
  6137. var axis = this.parent.getAxis();
  6138. if (!background) throw new Error('Cannot repaint time axis: parent has no axis container element');
  6139. axis.appendChild(dom.dot);
  6140. }
  6141. this.displayed = true;
  6142. // update contents
  6143. if (this.data.content != this.content) {
  6144. this.content = this.data.content;
  6145. if (this.content instanceof Element) {
  6146. dom.content.innerHTML = '';
  6147. dom.content.appendChild(this.content);
  6148. }
  6149. else if (this.data.content != undefined) {
  6150. dom.content.innerHTML = this.content;
  6151. }
  6152. else {
  6153. throw new Error('Property "content" missing in item ' + this.data.id);
  6154. }
  6155. this.dirty = true;
  6156. }
  6157. // update class
  6158. var className = (this.data.className? ' ' + this.data.className : '') +
  6159. (this.selected ? ' selected' : '');
  6160. if (this.className != className) {
  6161. this.className = className;
  6162. dom.box.className = 'item box' + className;
  6163. dom.line.className = 'item line' + className;
  6164. dom.dot.className = 'item dot' + className;
  6165. this.dirty = true;
  6166. }
  6167. // recalculate size
  6168. if (this.dirty) {
  6169. this.props.dot.height = dom.dot.offsetHeight;
  6170. this.props.dot.width = dom.dot.offsetWidth;
  6171. this.props.line.width = dom.line.offsetWidth;
  6172. this.width = dom.box.offsetWidth;
  6173. this.height = dom.box.offsetHeight;
  6174. this.dirty = false;
  6175. }
  6176. this._repaintDeleteButton(dom.box);
  6177. };
  6178. /**
  6179. * Show the item in the DOM (when not already displayed). The items DOM will
  6180. * be created when needed.
  6181. */
  6182. ItemBox.prototype.show = function show() {
  6183. if (!this.displayed) {
  6184. this.repaint();
  6185. }
  6186. };
  6187. /**
  6188. * Hide the item from the DOM (when visible)
  6189. */
  6190. ItemBox.prototype.hide = function hide() {
  6191. if (this.displayed) {
  6192. var dom = this.dom;
  6193. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  6194. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  6195. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  6196. this.top = null;
  6197. this.left = null;
  6198. this.displayed = false;
  6199. }
  6200. };
  6201. /**
  6202. * Reposition the item horizontally
  6203. * @Override
  6204. */
  6205. ItemBox.prototype.repositionX = function repositionX() {
  6206. var start = this.defaultOptions.toScreen(this.data.start),
  6207. align = this.options.align || this.defaultOptions.align,
  6208. left,
  6209. box = this.dom.box,
  6210. line = this.dom.line,
  6211. dot = this.dom.dot;
  6212. // calculate left position of the box
  6213. if (align == 'right') {
  6214. this.left = start - this.width;
  6215. }
  6216. else if (align == 'left') {
  6217. this.left = start;
  6218. }
  6219. else {
  6220. // default or 'center'
  6221. this.left = start - this.width / 2;
  6222. }
  6223. // reposition box
  6224. box.style.left = this.left + 'px';
  6225. // reposition line
  6226. line.style.left = (start - this.props.line.width / 2) + 'px';
  6227. // reposition dot
  6228. dot.style.left = (start - this.props.dot.width / 2) + 'px';
  6229. };
  6230. /**
  6231. * Reposition the item vertically
  6232. * @Override
  6233. */
  6234. ItemBox.prototype.repositionY = function repositionY () {
  6235. var orientation = this.options.orientation || this.defaultOptions.orientation,
  6236. box = this.dom.box,
  6237. line = this.dom.line,
  6238. dot = this.dom.dot;
  6239. if (orientation == 'top') {
  6240. box.style.top = (this.top || 0) + 'px';
  6241. box.style.bottom = '';
  6242. line.style.top = '0';
  6243. line.style.bottom = '';
  6244. line.style.height = (this.parent.top + this.top + 1) + 'px';
  6245. }
  6246. else { // orientation 'bottom'
  6247. box.style.top = '';
  6248. box.style.bottom = (this.top || 0) + 'px';
  6249. line.style.top = (this.parent.top + this.parent.height - this.top - 1) + 'px';
  6250. line.style.bottom = '0';
  6251. line.style.height = '';
  6252. }
  6253. dot.style.top = (-this.props.dot.height / 2) + 'px';
  6254. };
  6255. /**
  6256. * @constructor ItemPoint
  6257. * @extends Item
  6258. * @param {Object} data Object containing parameters start
  6259. * content, className.
  6260. * @param {Object} [options] Options to set initial property values
  6261. * @param {Object} [defaultOptions] default options
  6262. * // TODO: describe available options
  6263. */
  6264. function ItemPoint (data, options, defaultOptions) {
  6265. this.props = {
  6266. dot: {
  6267. top: 0,
  6268. width: 0,
  6269. height: 0
  6270. },
  6271. content: {
  6272. height: 0,
  6273. marginLeft: 0
  6274. }
  6275. };
  6276. // validate data
  6277. if (data) {
  6278. if (data.start == undefined) {
  6279. throw new Error('Property "start" missing in item ' + data);
  6280. }
  6281. }
  6282. Item.call(this, data, options, defaultOptions);
  6283. }
  6284. ItemPoint.prototype = new Item (null);
  6285. /**
  6286. * Check whether this item is visible inside given range
  6287. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  6288. * @returns {boolean} True if visible
  6289. */
  6290. ItemPoint.prototype.isVisible = function isVisible (range) {
  6291. // determine visibility
  6292. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  6293. var interval = (range.end - range.start) / 4;
  6294. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  6295. };
  6296. /**
  6297. * Repaint the item
  6298. */
  6299. ItemPoint.prototype.repaint = function repaint() {
  6300. var dom = this.dom;
  6301. if (!dom) {
  6302. // create DOM
  6303. this.dom = {};
  6304. dom = this.dom;
  6305. // background box
  6306. dom.point = document.createElement('div');
  6307. // className is updated in repaint()
  6308. // contents box, right from the dot
  6309. dom.content = document.createElement('div');
  6310. dom.content.className = 'content';
  6311. dom.point.appendChild(dom.content);
  6312. // dot at start
  6313. dom.dot = document.createElement('div');
  6314. dom.point.appendChild(dom.dot);
  6315. // attach this item as attribute
  6316. dom.point['timeline-item'] = this;
  6317. }
  6318. // append DOM to parent DOM
  6319. if (!this.parent) {
  6320. throw new Error('Cannot repaint item: no parent attached');
  6321. }
  6322. if (!dom.point.parentNode) {
  6323. var foreground = this.parent.getForeground();
  6324. if (!foreground) {
  6325. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  6326. }
  6327. foreground.appendChild(dom.point);
  6328. }
  6329. this.displayed = true;
  6330. // update contents
  6331. if (this.data.content != this.content) {
  6332. this.content = this.data.content;
  6333. if (this.content instanceof Element) {
  6334. dom.content.innerHTML = '';
  6335. dom.content.appendChild(this.content);
  6336. }
  6337. else if (this.data.content != undefined) {
  6338. dom.content.innerHTML = this.content;
  6339. }
  6340. else {
  6341. throw new Error('Property "content" missing in item ' + this.data.id);
  6342. }
  6343. this.dirty = true;
  6344. }
  6345. // update class
  6346. var className = (this.data.className? ' ' + this.data.className : '') +
  6347. (this.selected ? ' selected' : '');
  6348. if (this.className != className) {
  6349. this.className = className;
  6350. dom.point.className = 'item point' + className;
  6351. dom.dot.className = 'item dot' + className;
  6352. this.dirty = true;
  6353. }
  6354. // recalculate size
  6355. if (this.dirty) {
  6356. this.width = dom.point.offsetWidth;
  6357. this.height = dom.point.offsetHeight;
  6358. this.props.dot.width = dom.dot.offsetWidth;
  6359. this.props.dot.height = dom.dot.offsetHeight;
  6360. this.props.content.height = dom.content.offsetHeight;
  6361. // resize contents
  6362. dom.content.style.marginLeft = 2 * this.props.dot.width + 'px';
  6363. //dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  6364. dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px';
  6365. dom.dot.style.left = (this.props.dot.width / 2) + 'px';
  6366. this.dirty = false;
  6367. }
  6368. this._repaintDeleteButton(dom.point);
  6369. };
  6370. /**
  6371. * Show the item in the DOM (when not already visible). The items DOM will
  6372. * be created when needed.
  6373. */
  6374. ItemPoint.prototype.show = function show() {
  6375. if (!this.displayed) {
  6376. this.repaint();
  6377. }
  6378. };
  6379. /**
  6380. * Hide the item from the DOM (when visible)
  6381. */
  6382. ItemPoint.prototype.hide = function hide() {
  6383. if (this.displayed) {
  6384. if (this.dom.point.parentNode) {
  6385. this.dom.point.parentNode.removeChild(this.dom.point);
  6386. }
  6387. this.top = null;
  6388. this.left = null;
  6389. this.displayed = false;
  6390. }
  6391. };
  6392. /**
  6393. * Reposition the item horizontally
  6394. * @Override
  6395. */
  6396. ItemPoint.prototype.repositionX = function repositionX() {
  6397. var start = this.defaultOptions.toScreen(this.data.start);
  6398. this.left = start - this.props.dot.width;
  6399. // reposition point
  6400. this.dom.point.style.left = this.left + 'px';
  6401. };
  6402. /**
  6403. * Reposition the item vertically
  6404. * @Override
  6405. */
  6406. ItemPoint.prototype.repositionY = function repositionY () {
  6407. var orientation = this.options.orientation || this.defaultOptions.orientation,
  6408. point = this.dom.point;
  6409. if (orientation == 'top') {
  6410. point.style.top = this.top + 'px';
  6411. point.style.bottom = '';
  6412. }
  6413. else {
  6414. point.style.top = '';
  6415. point.style.bottom = this.top + 'px';
  6416. }
  6417. };
  6418. /**
  6419. * @constructor ItemRange
  6420. * @extends Item
  6421. * @param {Object} data Object containing parameters start, end
  6422. * content, className.
  6423. * @param {Object} [options] Options to set initial property values
  6424. * @param {Object} [defaultOptions] default options
  6425. * // TODO: describe available options
  6426. */
  6427. function ItemRange (data, options, defaultOptions) {
  6428. this.props = {
  6429. content: {
  6430. width: 0
  6431. }
  6432. };
  6433. // validate data
  6434. if (data) {
  6435. if (data.start == undefined) {
  6436. throw new Error('Property "start" missing in item ' + data.id);
  6437. }
  6438. if (data.end == undefined) {
  6439. throw new Error('Property "end" missing in item ' + data.id);
  6440. }
  6441. }
  6442. Item.call(this, data, options, defaultOptions);
  6443. }
  6444. ItemRange.prototype = new Item (null);
  6445. ItemRange.prototype.baseClassName = 'item range';
  6446. /**
  6447. * Check whether this item is visible inside given range
  6448. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  6449. * @returns {boolean} True if visible
  6450. */
  6451. ItemRange.prototype.isVisible = function isVisible (range) {
  6452. // determine visibility
  6453. return (this.data.start < range.end) && (this.data.end > range.start);
  6454. };
  6455. /**
  6456. * Repaint the item
  6457. */
  6458. ItemRange.prototype.repaint = function repaint() {
  6459. var dom = this.dom;
  6460. if (!dom) {
  6461. // create DOM
  6462. this.dom = {};
  6463. dom = this.dom;
  6464. // background box
  6465. dom.box = document.createElement('div');
  6466. // className is updated in repaint()
  6467. // contents box
  6468. dom.content = document.createElement('div');
  6469. dom.content.className = 'content';
  6470. dom.box.appendChild(dom.content);
  6471. // attach this item as attribute
  6472. dom.box['timeline-item'] = this;
  6473. }
  6474. // append DOM to parent DOM
  6475. if (!this.parent) {
  6476. throw new Error('Cannot repaint item: no parent attached');
  6477. }
  6478. if (!dom.box.parentNode) {
  6479. var foreground = this.parent.getForeground();
  6480. if (!foreground) {
  6481. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  6482. }
  6483. foreground.appendChild(dom.box);
  6484. }
  6485. this.displayed = true;
  6486. // update contents
  6487. if (this.data.content != this.content) {
  6488. this.content = this.data.content;
  6489. if (this.content instanceof Element) {
  6490. dom.content.innerHTML = '';
  6491. dom.content.appendChild(this.content);
  6492. }
  6493. else if (this.data.content != undefined) {
  6494. dom.content.innerHTML = this.content;
  6495. }
  6496. else {
  6497. throw new Error('Property "content" missing in item ' + this.data.id);
  6498. }
  6499. this.dirty = true;
  6500. }
  6501. // update class
  6502. var className = (this.data.className ? (' ' + this.data.className) : '') +
  6503. (this.selected ? ' selected' : '');
  6504. if (this.className != className) {
  6505. this.className = className;
  6506. dom.box.className = this.baseClassName + className;
  6507. this.dirty = true;
  6508. }
  6509. // recalculate size
  6510. if (this.dirty) {
  6511. this.props.content.width = this.dom.content.offsetWidth;
  6512. this.height = this.dom.box.offsetHeight;
  6513. this.dirty = false;
  6514. }
  6515. this._repaintDeleteButton(dom.box);
  6516. this._repaintDragLeft();
  6517. this._repaintDragRight();
  6518. };
  6519. /**
  6520. * Show the item in the DOM (when not already visible). The items DOM will
  6521. * be created when needed.
  6522. */
  6523. ItemRange.prototype.show = function show() {
  6524. if (!this.displayed) {
  6525. this.repaint();
  6526. }
  6527. };
  6528. /**
  6529. * Hide the item from the DOM (when visible)
  6530. * @return {Boolean} changed
  6531. */
  6532. ItemRange.prototype.hide = function hide() {
  6533. if (this.displayed) {
  6534. var box = this.dom.box;
  6535. if (box.parentNode) {
  6536. box.parentNode.removeChild(box);
  6537. }
  6538. this.top = null;
  6539. this.left = null;
  6540. this.displayed = false;
  6541. }
  6542. };
  6543. /**
  6544. * Reposition the item horizontally
  6545. * @Override
  6546. */
  6547. ItemRange.prototype.repositionX = function repositionX() {
  6548. var props = this.props,
  6549. parentWidth = this.parent.width,
  6550. start = this.defaultOptions.toScreen(this.data.start),
  6551. end = this.defaultOptions.toScreen(this.data.end),
  6552. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  6553. contentLeft;
  6554. // limit the width of the this, as browsers cannot draw very wide divs
  6555. if (start < -parentWidth) {
  6556. start = -parentWidth;
  6557. }
  6558. if (end > 2 * parentWidth) {
  6559. end = 2 * parentWidth;
  6560. }
  6561. // when range exceeds left of the window, position the contents at the left of the visible area
  6562. if (start < 0) {
  6563. contentLeft = Math.min(-start,
  6564. (end - start - props.content.width - 2 * padding));
  6565. // TODO: remove the need for options.padding. it's terrible.
  6566. }
  6567. else {
  6568. contentLeft = 0;
  6569. }
  6570. this.left = start;
  6571. this.width = Math.max(end - start, 1);
  6572. this.dom.box.style.left = this.left + 'px';
  6573. this.dom.box.style.width = this.width + 'px';
  6574. this.dom.content.style.left = contentLeft + 'px';
  6575. };
  6576. /**
  6577. * Reposition the item vertically
  6578. * @Override
  6579. */
  6580. ItemRange.prototype.repositionY = function repositionY() {
  6581. var orientation = this.options.orientation || this.defaultOptions.orientation,
  6582. box = this.dom.box;
  6583. if (orientation == 'top') {
  6584. box.style.top = this.top + 'px';
  6585. box.style.bottom = '';
  6586. }
  6587. else {
  6588. box.style.top = '';
  6589. box.style.bottom = this.top + 'px';
  6590. }
  6591. };
  6592. /**
  6593. * Repaint a drag area on the left side of the range when the range is selected
  6594. * @protected
  6595. */
  6596. ItemRange.prototype._repaintDragLeft = function () {
  6597. if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) {
  6598. // create and show drag area
  6599. var dragLeft = document.createElement('div');
  6600. dragLeft.className = 'drag-left';
  6601. dragLeft.dragLeftItem = this;
  6602. // TODO: this should be redundant?
  6603. Hammer(dragLeft, {
  6604. preventDefault: true
  6605. }).on('drag', function () {
  6606. //console.log('drag left')
  6607. });
  6608. this.dom.box.appendChild(dragLeft);
  6609. this.dom.dragLeft = dragLeft;
  6610. }
  6611. else if (!this.selected && this.dom.dragLeft) {
  6612. // delete drag area
  6613. if (this.dom.dragLeft.parentNode) {
  6614. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  6615. }
  6616. this.dom.dragLeft = null;
  6617. }
  6618. };
  6619. /**
  6620. * Repaint a drag area on the right side of the range when the range is selected
  6621. * @protected
  6622. */
  6623. ItemRange.prototype._repaintDragRight = function () {
  6624. if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) {
  6625. // create and show drag area
  6626. var dragRight = document.createElement('div');
  6627. dragRight.className = 'drag-right';
  6628. dragRight.dragRightItem = this;
  6629. // TODO: this should be redundant?
  6630. Hammer(dragRight, {
  6631. preventDefault: true
  6632. }).on('drag', function () {
  6633. //console.log('drag right')
  6634. });
  6635. this.dom.box.appendChild(dragRight);
  6636. this.dom.dragRight = dragRight;
  6637. }
  6638. else if (!this.selected && this.dom.dragRight) {
  6639. // delete drag area
  6640. if (this.dom.dragRight.parentNode) {
  6641. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  6642. }
  6643. this.dom.dragRight = null;
  6644. }
  6645. };
  6646. /**
  6647. * @constructor ItemRangeOverflow
  6648. * @extends ItemRange
  6649. * @param {Object} data Object containing parameters start, end
  6650. * content, className.
  6651. * @param {Object} [options] Options to set initial property values
  6652. * @param {Object} [defaultOptions] default options
  6653. * // TODO: describe available options
  6654. */
  6655. function ItemRangeOverflow (data, options, defaultOptions) {
  6656. this.props = {
  6657. content: {
  6658. left: 0,
  6659. width: 0
  6660. }
  6661. };
  6662. ItemRange.call(this, data, options, defaultOptions);
  6663. }
  6664. ItemRangeOverflow.prototype = new ItemRange (null);
  6665. ItemRangeOverflow.prototype.baseClassName = 'item rangeoverflow';
  6666. /**
  6667. * Reposition the item horizontally
  6668. * @Override
  6669. */
  6670. ItemRangeOverflow.prototype.repositionX = function repositionX() {
  6671. var parentWidth = this.parent.width,
  6672. start = this.defaultOptions.toScreen(this.data.start),
  6673. end = this.defaultOptions.toScreen(this.data.end),
  6674. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  6675. contentLeft;
  6676. // limit the width of the this, as browsers cannot draw very wide divs
  6677. if (start < -parentWidth) {
  6678. start = -parentWidth;
  6679. }
  6680. if (end > 2 * parentWidth) {
  6681. end = 2 * parentWidth;
  6682. }
  6683. // when range exceeds left of the window, position the contents at the left of the visible area
  6684. contentLeft = Math.max(-start, 0);
  6685. this.left = start;
  6686. var boxWidth = Math.max(end - start, 1);
  6687. this.width = boxWidth + this.props.content.width;
  6688. // Note: The calculation of width is an optimistic calculation, giving
  6689. // a width which will not change when moving the Timeline
  6690. // So no restacking needed, which is nicer for the eye
  6691. this.dom.box.style.left = this.left + 'px';
  6692. this.dom.box.style.width = boxWidth + 'px';
  6693. this.dom.content.style.left = contentLeft + 'px';
  6694. };
  6695. /**
  6696. * @constructor Group
  6697. * @param {Number | String} groupId
  6698. * @param {Object} data
  6699. * @param {ItemSet} itemSet
  6700. */
  6701. function Group (groupId, data, itemSet) {
  6702. this.groupId = groupId;
  6703. this.itemSet = itemSet;
  6704. this.dom = {};
  6705. this.props = {
  6706. label: {
  6707. width: 0,
  6708. height: 0
  6709. }
  6710. };
  6711. this.items = {}; // items filtered by groupId of this group
  6712. this.visibleItems = []; // items currently visible in window
  6713. this.orderedItems = { // items sorted by start and by end
  6714. byStart: [],
  6715. byEnd: []
  6716. };
  6717. this._create();
  6718. this.setData(data);
  6719. }
  6720. /**
  6721. * Create DOM elements for the group
  6722. * @private
  6723. */
  6724. Group.prototype._create = function() {
  6725. var label = document.createElement('div');
  6726. label.className = 'vlabel';
  6727. this.dom.label = label;
  6728. var inner = document.createElement('div');
  6729. inner.className = 'inner';
  6730. label.appendChild(inner);
  6731. this.dom.inner = inner;
  6732. var foreground = document.createElement('div');
  6733. foreground.className = 'group';
  6734. foreground['timeline-group'] = this;
  6735. this.dom.foreground = foreground;
  6736. this.dom.background = document.createElement('div');
  6737. this.dom.axis = document.createElement('div');
  6738. };
  6739. /**
  6740. * Set the group data for this group
  6741. * @param {Object} data Group data, can contain properties content and className
  6742. */
  6743. Group.prototype.setData = function setData(data) {
  6744. // update contents
  6745. var content = data && data.content;
  6746. if (content instanceof Element) {
  6747. this.dom.inner.appendChild(content);
  6748. }
  6749. else if (content != undefined) {
  6750. this.dom.inner.innerHTML = content;
  6751. }
  6752. else {
  6753. this.dom.inner.innerHTML = this.groupId;
  6754. }
  6755. // update className
  6756. var className = data && data.className;
  6757. if (className) {
  6758. util.addClassName(this.dom.label, className);
  6759. }
  6760. };
  6761. /**
  6762. * Get the foreground container element
  6763. * @return {HTMLElement} foreground
  6764. */
  6765. Group.prototype.getForeground = function getForeground() {
  6766. return this.dom.foreground;
  6767. };
  6768. /**
  6769. * Get the background container element
  6770. * @return {HTMLElement} background
  6771. */
  6772. Group.prototype.getBackground = function getBackground() {
  6773. return this.dom.background;
  6774. };
  6775. /**
  6776. * Get the axis container element
  6777. * @return {HTMLElement} axis
  6778. */
  6779. Group.prototype.getAxis = function getAxis() {
  6780. return this.dom.axis;
  6781. };
  6782. /**
  6783. * Get the width of the group label
  6784. * @return {number} width
  6785. */
  6786. Group.prototype.getLabelWidth = function getLabelWidth() {
  6787. return this.props.label.width;
  6788. };
  6789. /**
  6790. * Repaint this group
  6791. * @param {{start: number, end: number}} range
  6792. * @param {{item: number, axis: number}} margin
  6793. * @param {boolean} [restack=false] Force restacking of all items
  6794. * @return {boolean} Returns true if the group is resized
  6795. */
  6796. Group.prototype.repaint = function repaint(range, margin, restack) {
  6797. var resized = false;
  6798. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  6799. // reposition visible items vertically
  6800. if (this.itemSet.options.stack) { // TODO: ugly way to access options...
  6801. stack.stack(this.visibleItems, margin, restack);
  6802. }
  6803. else { // no stacking
  6804. stack.nostack(this.visibleItems, margin);
  6805. }
  6806. this.stackDirty = false;
  6807. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  6808. var item = this.visibleItems[i];
  6809. item.repositionY();
  6810. }
  6811. // recalculate the height of the group
  6812. var height;
  6813. var visibleItems = this.visibleItems;
  6814. if (visibleItems.length) {
  6815. var min = visibleItems[0].top;
  6816. var max = visibleItems[0].top + visibleItems[0].height;
  6817. util.forEach(visibleItems, function (item) {
  6818. min = Math.min(min, item.top);
  6819. max = Math.max(max, (item.top + item.height));
  6820. });
  6821. height = (max - min) + margin.axis + margin.item;
  6822. }
  6823. else {
  6824. height = margin.axis + margin.item;
  6825. }
  6826. height = Math.max(height, this.props.label.height);
  6827. // calculate actual size and position
  6828. var foreground = this.dom.foreground;
  6829. this.top = foreground.offsetTop;
  6830. this.left = foreground.offsetLeft;
  6831. this.width = foreground.offsetWidth;
  6832. resized = util.updateProperty(this, 'height', height) || resized;
  6833. // recalculate size of label
  6834. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  6835. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  6836. // apply new height
  6837. foreground.style.height = height + 'px';
  6838. this.dom.label.style.height = height + 'px';
  6839. return resized;
  6840. };
  6841. /**
  6842. * Show this group: attach to the DOM
  6843. */
  6844. Group.prototype.show = function show() {
  6845. if (!this.dom.label.parentNode) {
  6846. this.itemSet.getLabelSet().appendChild(this.dom.label);
  6847. }
  6848. if (!this.dom.foreground.parentNode) {
  6849. this.itemSet.getForeground().appendChild(this.dom.foreground);
  6850. }
  6851. if (!this.dom.background.parentNode) {
  6852. this.itemSet.getBackground().appendChild(this.dom.background);
  6853. }
  6854. if (!this.dom.axis.parentNode) {
  6855. this.itemSet.getAxis().appendChild(this.dom.axis);
  6856. }
  6857. };
  6858. /**
  6859. * Hide this group: remove from the DOM
  6860. */
  6861. Group.prototype.hide = function hide() {
  6862. var label = this.dom.label;
  6863. if (label.parentNode) {
  6864. label.parentNode.removeChild(label);
  6865. }
  6866. var foreground = this.dom.foreground;
  6867. if (foreground.parentNode) {
  6868. foreground.parentNode.removeChild(foreground);
  6869. }
  6870. var background = this.dom.background;
  6871. if (background.parentNode) {
  6872. background.parentNode.removeChild(background);
  6873. }
  6874. var axis = this.dom.axis;
  6875. if (axis.parentNode) {
  6876. axis.parentNode.removeChild(axis);
  6877. }
  6878. };
  6879. /**
  6880. * Add an item to the group
  6881. * @param {Item} item
  6882. */
  6883. Group.prototype.add = function add(item) {
  6884. this.items[item.id] = item;
  6885. item.setParent(this);
  6886. if (item instanceof ItemRange && this.visibleItems.indexOf(item) == -1) {
  6887. var range = this.itemSet.range; // TODO: not nice accessing the range like this
  6888. this._checkIfVisible(item, this.visibleItems, range);
  6889. }
  6890. };
  6891. /**
  6892. * Remove an item from the group
  6893. * @param {Item} item
  6894. */
  6895. Group.prototype.remove = function remove(item) {
  6896. delete this.items[item.id];
  6897. item.setParent(this.itemSet);
  6898. // remove from visible items
  6899. var index = this.visibleItems.indexOf(item);
  6900. if (index != -1) this.visibleItems.splice(index, 1);
  6901. // TODO: also remove from ordered items?
  6902. };
  6903. /**
  6904. * Remove an item from the corresponding DataSet
  6905. * @param {Item} item
  6906. */
  6907. Group.prototype.removeFromDataSet = function removeFromDataSet(item) {
  6908. this.itemSet.removeItem(item.id);
  6909. };
  6910. /**
  6911. * Reorder the items
  6912. */
  6913. Group.prototype.order = function order() {
  6914. var array = util.toArray(this.items);
  6915. this.orderedItems.byStart = array;
  6916. this.orderedItems.byEnd = this._constructByEndArray(array);
  6917. stack.orderByStart(this.orderedItems.byStart);
  6918. stack.orderByEnd(this.orderedItems.byEnd);
  6919. };
  6920. /**
  6921. * Create an array containing all items being a range (having an end date)
  6922. * @param {Item[]} array
  6923. * @returns {ItemRange[]}
  6924. * @private
  6925. */
  6926. Group.prototype._constructByEndArray = function _constructByEndArray(array) {
  6927. var endArray = [];
  6928. for (var i = 0; i < array.length; i++) {
  6929. if (array[i] instanceof ItemRange) {
  6930. endArray.push(array[i]);
  6931. }
  6932. }
  6933. return endArray;
  6934. };
  6935. /**
  6936. * Update the visible items
  6937. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  6938. * @param {Item[]} visibleItems The previously visible items.
  6939. * @param {{start: number, end: number}} range Visible range
  6940. * @return {Item[]} visibleItems The new visible items.
  6941. * @private
  6942. */
  6943. Group.prototype._updateVisibleItems = function _updateVisibleItems(orderedItems, visibleItems, range) {
  6944. var initialPosByStart,
  6945. newVisibleItems = [],
  6946. i;
  6947. // first check if the items that were in view previously are still in view.
  6948. // this handles the case for the ItemRange that is both before and after the current one.
  6949. if (visibleItems.length > 0) {
  6950. for (i = 0; i < visibleItems.length; i++) {
  6951. this._checkIfVisible(visibleItems[i], newVisibleItems, range);
  6952. }
  6953. }
  6954. // If there were no visible items previously, use binarySearch to find a visible ItemPoint or ItemRange (based on startTime)
  6955. if (newVisibleItems.length == 0) {
  6956. initialPosByStart = this._binarySearch(orderedItems, range, false);
  6957. }
  6958. else {
  6959. initialPosByStart = orderedItems.byStart.indexOf(newVisibleItems[0]);
  6960. }
  6961. // use visible search to find a visible ItemRange (only based on endTime)
  6962. var initialPosByEnd = this._binarySearch(orderedItems, range, true);
  6963. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  6964. if (initialPosByStart != -1) {
  6965. for (i = initialPosByStart; i >= 0; i--) {
  6966. if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;}
  6967. }
  6968. for (i = initialPosByStart + 1; i < orderedItems.byStart.length; i++) {
  6969. if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;}
  6970. }
  6971. }
  6972. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  6973. if (initialPosByEnd != -1) {
  6974. for (i = initialPosByEnd; i >= 0; i--) {
  6975. if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;}
  6976. }
  6977. for (i = initialPosByEnd + 1; i < orderedItems.byEnd.length; i++) {
  6978. if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;}
  6979. }
  6980. }
  6981. return newVisibleItems;
  6982. };
  6983. /**
  6984. * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd
  6985. * arrays. This is done by giving a boolean value true if you want to use the byEnd.
  6986. * This is done to be able to select the correct if statement (we do not want to check if an item is visible, we want to check
  6987. * if the time we selected (start or end) is within the current range).
  6988. *
  6989. * The trick is that every interval has to either enter the screen at the initial load or by dragging. The case of the ItemRange that is
  6990. * before and after the current range is handled by simply checking if it was in view before and if it is again. For all the rest,
  6991. * either the start OR end time has to be in the range.
  6992. *
  6993. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems
  6994. * @param {{start: number, end: number}} range
  6995. * @param {Boolean} byEnd
  6996. * @returns {number}
  6997. * @private
  6998. */
  6999. Group.prototype._binarySearch = function _binarySearch(orderedItems, range, byEnd) {
  7000. var array = [];
  7001. var byTime = byEnd ? 'end' : 'start';
  7002. if (byEnd == true) {array = orderedItems.byEnd; }
  7003. else {array = orderedItems.byStart;}
  7004. var interval = range.end - range.start;
  7005. var found = false;
  7006. var low = 0;
  7007. var high = array.length;
  7008. var guess = Math.floor(0.5*(high+low));
  7009. var newGuess;
  7010. if (high == 0) {guess = -1;}
  7011. else if (high == 1) {
  7012. if ((array[guess].data[byTime] > range.start - interval) && (array[guess].data[byTime] < range.end)) {
  7013. guess = 0;
  7014. }
  7015. else {
  7016. guess = -1;
  7017. }
  7018. }
  7019. else {
  7020. high -= 1;
  7021. while (found == false) {
  7022. if ((array[guess].data[byTime] > range.start - interval) && (array[guess].data[byTime] < range.end)) {
  7023. found = true;
  7024. }
  7025. else {
  7026. if (array[guess].data[byTime] < range.start - interval) { // it is too small --> increase low
  7027. low = Math.floor(0.5*(high+low));
  7028. }
  7029. else { // it is too big --> decrease high
  7030. high = Math.floor(0.5*(high+low));
  7031. }
  7032. newGuess = Math.floor(0.5*(high+low));
  7033. // not in list;
  7034. if (guess == newGuess) {
  7035. guess = -1;
  7036. found = true;
  7037. }
  7038. else {
  7039. guess = newGuess;
  7040. }
  7041. }
  7042. }
  7043. }
  7044. return guess;
  7045. };
  7046. /**
  7047. * this function checks if an item is invisible. If it is NOT we make it visible
  7048. * and add it to the global visible items. If it is, return true.
  7049. *
  7050. * @param {Item} item
  7051. * @param {Item[]} visibleItems
  7052. * @param {{start:number, end:number}} range
  7053. * @returns {boolean}
  7054. * @private
  7055. */
  7056. Group.prototype._checkIfInvisible = function _checkIfInvisible(item, visibleItems, range) {
  7057. if (item.isVisible(range)) {
  7058. if (!item.displayed) item.show();
  7059. item.repositionX();
  7060. if (visibleItems.indexOf(item) == -1) {
  7061. visibleItems.push(item);
  7062. }
  7063. return false;
  7064. }
  7065. else {
  7066. return true;
  7067. }
  7068. };
  7069. /**
  7070. * this function is very similar to the _checkIfInvisible() but it does not
  7071. * return booleans, hides the item if it should not be seen and always adds to
  7072. * the visibleItems.
  7073. * this one is for brute forcing and hiding.
  7074. *
  7075. * @param {Item} item
  7076. * @param {Array} visibleItems
  7077. * @param {{start:number, end:number}} range
  7078. * @private
  7079. */
  7080. Group.prototype._checkIfVisible = function _checkIfVisible(item, visibleItems, range) {
  7081. if (item.isVisible(range)) {
  7082. if (!item.displayed) item.show();
  7083. // reposition item horizontally
  7084. item.repositionX();
  7085. visibleItems.push(item);
  7086. }
  7087. else {
  7088. if (item.displayed) item.hide();
  7089. }
  7090. };
  7091. /**
  7092. * Create a timeline visualization
  7093. * @param {HTMLElement} container
  7094. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  7095. * @param {Object} [options] See Timeline.setOptions for the available options.
  7096. * @constructor
  7097. */
  7098. function Timeline (container, items, options) {
  7099. // validate arguments
  7100. if (!container) throw new Error('No container element provided');
  7101. var me = this;
  7102. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  7103. this.options = {
  7104. orientation: 'bottom',
  7105. direction: 'horizontal', // 'horizontal' or 'vertical'
  7106. autoResize: true,
  7107. stack: true,
  7108. editable: {
  7109. updateTime: false,
  7110. updateGroup: false,
  7111. add: false,
  7112. remove: false
  7113. },
  7114. selectable: true,
  7115. snap: null, // will be specified after timeaxis is created
  7116. min: null,
  7117. max: null,
  7118. zoomMin: 10, // milliseconds
  7119. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  7120. // moveable: true, // TODO: option moveable
  7121. // zoomable: true, // TODO: option zoomable
  7122. showMinorLabels: true,
  7123. showMajorLabels: true,
  7124. showCurrentTime: false,
  7125. showCustomTime: false,
  7126. type: 'box',
  7127. align: 'center',
  7128. margin: {
  7129. axis: 20,
  7130. item: 10
  7131. },
  7132. padding: 5,
  7133. onAdd: function (item, callback) {
  7134. callback(item);
  7135. },
  7136. onUpdate: function (item, callback) {
  7137. callback(item);
  7138. },
  7139. onMove: function (item, callback) {
  7140. callback(item);
  7141. },
  7142. onRemove: function (item, callback) {
  7143. callback(item);
  7144. },
  7145. toScreen: me._toScreen.bind(me),
  7146. toTime: me._toTime.bind(me)
  7147. };
  7148. // root panel
  7149. var rootOptions = util.extend(Object.create(this.options), {
  7150. height: function () {
  7151. if (me.options.height) {
  7152. // fixed height
  7153. return me.options.height;
  7154. }
  7155. else {
  7156. // auto height
  7157. // TODO: implement a css based solution to automatically have the right hight
  7158. return (me.timeAxis.height + me.contentPanel.height) + 'px';
  7159. }
  7160. }
  7161. });
  7162. this.rootPanel = new RootPanel(container, rootOptions);
  7163. // single select (or unselect) when tapping an item
  7164. this.rootPanel.on('tap', this._onSelectItem.bind(this));
  7165. // multi select when holding mouse/touch, or on ctrl+click
  7166. this.rootPanel.on('hold', this._onMultiSelectItem.bind(this));
  7167. // add item on doubletap
  7168. this.rootPanel.on('doubletap', this._onAddItem.bind(this));
  7169. // side panel
  7170. var sideOptions = util.extend(Object.create(this.options), {
  7171. top: function () {
  7172. return (sideOptions.orientation == 'top') ? '0' : '';
  7173. },
  7174. bottom: function () {
  7175. return (sideOptions.orientation == 'top') ? '' : '0';
  7176. },
  7177. left: '0',
  7178. right: null,
  7179. height: '100%',
  7180. width: function () {
  7181. if (me.itemSet) {
  7182. // return me.itemSet.getLabelsWidth();
  7183. return "100px";
  7184. }
  7185. else {
  7186. return 0;
  7187. }
  7188. },
  7189. className: function () {
  7190. return 'side' + (me.groupsData ? '' : ' hidden');
  7191. }
  7192. });
  7193. this.sidePanel = new Panel(sideOptions);
  7194. this.rootPanel.appendChild(this.sidePanel);
  7195. // main panel (contains time axis and itemsets)
  7196. var mainOptions = util.extend(Object.create(this.options), {
  7197. left: function () {
  7198. // we align left to enable a smooth resizing of the window
  7199. return me.sidePanel.width;
  7200. },
  7201. right: null,
  7202. height: '100%',
  7203. width: function () {
  7204. return me.rootPanel.width - me.sidePanel.width;
  7205. },
  7206. className: 'main'
  7207. });
  7208. this.mainPanel = new Panel(mainOptions);
  7209. this.rootPanel.appendChild(this.mainPanel);
  7210. // range
  7211. // TODO: move range inside rootPanel?
  7212. var rangeOptions = Object.create(this.options);
  7213. this.range = new Range(this.rootPanel, this.mainPanel, rangeOptions);
  7214. this.range.setRange(
  7215. now.clone().add('days', -3).valueOf(),
  7216. now.clone().add('days', 4).valueOf()
  7217. );
  7218. this.range.on('rangechange', function (properties) {
  7219. me.rootPanel.repaint();
  7220. me.emit('rangechange', properties);
  7221. });
  7222. this.range.on('rangechanged', function (properties) {
  7223. me.rootPanel.repaint();
  7224. me.emit('rangechanged', properties);
  7225. });
  7226. // panel with time axis
  7227. var timeAxisOptions = util.extend(Object.create(rootOptions), {
  7228. range: this.range,
  7229. left: null,
  7230. top: null,
  7231. width: null,
  7232. height: null
  7233. });
  7234. this.timeAxis = new TimeAxis(timeAxisOptions);
  7235. this.timeAxis.setRange(this.range);
  7236. this.options.snap = this.timeAxis.snap.bind(this.timeAxis);
  7237. this.mainPanel.appendChild(this.timeAxis);
  7238. // content panel (contains itemset(s))
  7239. var contentOptions = util.extend(Object.create(this.options), {
  7240. top: function () {
  7241. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  7242. },
  7243. bottom: function () {
  7244. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  7245. },
  7246. left: null,
  7247. right: null,
  7248. height: null,
  7249. width: null,
  7250. className: 'content'
  7251. });
  7252. this.contentPanel = new Panel(contentOptions);
  7253. this.mainPanel.appendChild(this.contentPanel);
  7254. // content panel (contains the vertical lines of box items)
  7255. var backgroundOptions = util.extend(Object.create(this.options), {
  7256. top: function () {
  7257. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  7258. },
  7259. bottom: function () {
  7260. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  7261. },
  7262. left: null,
  7263. right: null,
  7264. height: function () {
  7265. return me.contentPanel.height;
  7266. },
  7267. width: null,
  7268. className: 'background'
  7269. });
  7270. this.backgroundPanel = new Panel(backgroundOptions);
  7271. this.mainPanel.insertBefore(this.backgroundPanel, this.contentPanel);
  7272. // panel with axis holding the dots of item boxes
  7273. var axisPanelOptions = util.extend(Object.create(rootOptions), {
  7274. left: 0,
  7275. top: function () {
  7276. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  7277. },
  7278. bottom: function () {
  7279. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  7280. },
  7281. width: '100%',
  7282. height: 0,
  7283. className: 'axis'
  7284. });
  7285. this.axisPanel = new Panel(axisPanelOptions);
  7286. this.mainPanel.appendChild(this.axisPanel);
  7287. // content panel (contains itemset(s))
  7288. var sideContentOptions = util.extend(Object.create(this.options), {
  7289. top: function () {
  7290. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  7291. },
  7292. bottom: function () {
  7293. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  7294. },
  7295. left: null,
  7296. right: null,
  7297. height: null,
  7298. width: null,
  7299. className: 'side-content'
  7300. });
  7301. this.sideContentPanel = new Panel(sideContentOptions);
  7302. this.sidePanel.appendChild(this.sideContentPanel);
  7303. // current time bar
  7304. // Note: time bar will be attached in this.setOptions when selected
  7305. this.currentTime = new CurrentTime(this.range, rootOptions);
  7306. // custom time bar
  7307. // Note: time bar will be attached in this.setOptions when selected
  7308. this.customTime = new CustomTime(rootOptions);
  7309. this.customTime.on('timechange', function (time) {
  7310. me.emit('timechange', time);
  7311. });
  7312. this.customTime.on('timechanged', function (time) {
  7313. me.emit('timechanged', time);
  7314. });
  7315. // itemset containing items and groups
  7316. var itemOptions = util.extend(Object.create(this.options), {
  7317. left: null,
  7318. right: null,
  7319. top: null,
  7320. bottom: null,
  7321. width: null,
  7322. height: null
  7323. });
  7324. this.linegraph = new Linegraph(this.backgroundPanel, this.axisPanel, this.sideContentPanel, itemOptions, this, this.sidePanel);
  7325. this.linegraph.setRange(this.range);
  7326. this.linegraph.on('change', me.rootPanel.repaint.bind(me.rootPanel));
  7327. this.contentPanel.appendChild(this.linegraph);
  7328. this.itemSet = new ItemSet(this.backgroundPanel, this.axisPanel, this.sideContentPanel, itemOptions);
  7329. this.itemSet.setRange(this.range);
  7330. this.itemSet.on('change', me.rootPanel.repaint.bind(me.rootPanel));
  7331. this.contentPanel.appendChild(this.itemSet);
  7332. this.itemsData = null; // DataSet
  7333. this.groupsData = null; // DataSet
  7334. // apply options
  7335. if (options) {
  7336. this.setOptions(options);
  7337. }
  7338. // create itemset
  7339. if (items) {
  7340. this.setItems(items);
  7341. }
  7342. }
  7343. // turn Timeline into an event emitter
  7344. Emitter(Timeline.prototype);
  7345. /**
  7346. * Set options
  7347. * @param {Object} options TODO: describe the available options
  7348. */
  7349. Timeline.prototype.setOptions = function (options) {
  7350. util.extend(this.options, options);
  7351. if ('editable' in options) {
  7352. var isBoolean = typeof options.editable === 'boolean';
  7353. this.options.editable = {
  7354. updateTime: isBoolean ? options.editable : (options.editable.updateTime || false),
  7355. updateGroup: isBoolean ? options.editable : (options.editable.updateGroup || false),
  7356. add: isBoolean ? options.editable : (options.editable.add || false),
  7357. remove: isBoolean ? options.editable : (options.editable.remove || false)
  7358. };
  7359. }
  7360. // force update of range (apply new min/max etc.)
  7361. // both start and end are optional
  7362. this.range.setRange(options.start, options.end);
  7363. if ('editable' in options || 'selectable' in options) {
  7364. if (this.options.selectable) {
  7365. // force update of selection
  7366. this.setSelection(this.getSelection());
  7367. }
  7368. else {
  7369. // remove selection
  7370. this.setSelection([]);
  7371. }
  7372. }
  7373. // force the itemSet to refresh: options like orientation and margins may be changed
  7374. this.itemSet.markDirty();
  7375. // validate the callback functions
  7376. var validateCallback = (function (fn) {
  7377. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  7378. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  7379. }
  7380. }).bind(this);
  7381. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  7382. // add/remove the current time bar
  7383. if (this.options.showCurrentTime) {
  7384. if (!this.mainPanel.hasChild(this.currentTime)) {
  7385. this.mainPanel.appendChild(this.currentTime);
  7386. this.currentTime.start();
  7387. }
  7388. }
  7389. else {
  7390. if (this.mainPanel.hasChild(this.currentTime)) {
  7391. this.currentTime.stop();
  7392. this.mainPanel.removeChild(this.currentTime);
  7393. }
  7394. }
  7395. // add/remove the custom time bar
  7396. if (this.options.showCustomTime) {
  7397. if (!this.mainPanel.hasChild(this.customTime)) {
  7398. this.mainPanel.appendChild(this.customTime);
  7399. }
  7400. }
  7401. else {
  7402. if (this.mainPanel.hasChild(this.customTime)) {
  7403. this.mainPanel.removeChild(this.customTime);
  7404. }
  7405. }
  7406. // TODO: remove deprecation error one day (deprecated since version 0.8.0)
  7407. if (options && options.order) {
  7408. throw new Error('Option order is deprecated. There is no replacement for this feature.');
  7409. }
  7410. // repaint everything
  7411. this.rootPanel.repaint();
  7412. };
  7413. /**
  7414. * Set a custom time bar
  7415. * @param {Date} time
  7416. */
  7417. Timeline.prototype.setCustomTime = function (time) {
  7418. if (!this.customTime) {
  7419. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  7420. }
  7421. this.customTime.setCustomTime(time);
  7422. };
  7423. /**
  7424. * Retrieve the current custom time.
  7425. * @return {Date} customTime
  7426. */
  7427. Timeline.prototype.getCustomTime = function() {
  7428. if (!this.customTime) {
  7429. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  7430. }
  7431. return this.customTime.getCustomTime();
  7432. };
  7433. /**
  7434. * Set items
  7435. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  7436. */
  7437. Timeline.prototype.setItems = function(items) {
  7438. var initialLoad = (this.itemsData == null);
  7439. // convert to type DataSet when needed
  7440. var newDataSet;
  7441. if (!items) {
  7442. newDataSet = null;
  7443. }
  7444. else if (items instanceof DataSet || items instanceof DataView) {
  7445. newDataSet = items;
  7446. }
  7447. else {
  7448. // turn an array into a dataset
  7449. newDataSet = new DataSet(items, {
  7450. convert: {
  7451. start: 'Date',
  7452. end: 'Date'
  7453. }
  7454. });
  7455. }
  7456. // set items
  7457. this.itemsData = newDataSet;
  7458. this.itemSet.setItems(newDataSet);
  7459. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  7460. this.fit();
  7461. var start = (this.options.start != undefined) ? util.convert(this.options.start, 'Date') : null;
  7462. var end = (this.options.end != undefined) ? util.convert(this.options.end, 'Date') : null;
  7463. this.setWindow(start, end);
  7464. }
  7465. };
  7466. /**
  7467. * Set groups
  7468. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  7469. */
  7470. Timeline.prototype.setGroups = function setGroups(groups) {
  7471. // convert to type DataSet when needed
  7472. var newDataSet;
  7473. if (!groups) {
  7474. newDataSet = null;
  7475. }
  7476. else if (groups instanceof DataSet || groups instanceof DataView) {
  7477. newDataSet = groups;
  7478. }
  7479. else {
  7480. // turn an array into a dataset
  7481. newDataSet = new DataSet(groups);
  7482. }
  7483. this.groupsData = newDataSet;
  7484. this.itemSet.setGroups(newDataSet);
  7485. };
  7486. /**
  7487. * Set Timeline window such that it fits all items
  7488. */
  7489. Timeline.prototype.fit = function fit() {
  7490. // apply the data range as range
  7491. var dataRange = this.getItemRange();
  7492. // add 5% space on both sides
  7493. var start = dataRange.min;
  7494. var end = dataRange.max;
  7495. if (start != null && end != null) {
  7496. var interval = (end.valueOf() - start.valueOf());
  7497. if (interval <= 0) {
  7498. // prevent an empty interval
  7499. interval = 24 * 60 * 60 * 1000; // 1 day
  7500. }
  7501. start = new Date(start.valueOf() - interval * 0.05);
  7502. end = new Date(end.valueOf() + interval * 0.05);
  7503. }
  7504. // skip range set if there is no start and end date
  7505. if (start === null && end === null) {
  7506. return;
  7507. }
  7508. this.range.setRange(start, end);
  7509. };
  7510. /**
  7511. * Get the data range of the item set.
  7512. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  7513. * When no minimum is found, min==null
  7514. * When no maximum is found, max==null
  7515. */
  7516. Timeline.prototype.getItemRange = function getItemRange() {
  7517. // calculate min from start filed
  7518. var itemsData = this.itemsData,
  7519. min = null,
  7520. max = null;
  7521. if (itemsData) {
  7522. // calculate the minimum value of the field 'start'
  7523. var minItem = itemsData.min('start');
  7524. min = minItem ? minItem.start.valueOf() : null;
  7525. // calculate maximum value of fields 'start' and 'end'
  7526. var maxStartItem = itemsData.max('start');
  7527. if (maxStartItem) {
  7528. max = maxStartItem.start.valueOf();
  7529. }
  7530. var maxEndItem = itemsData.max('end');
  7531. if (maxEndItem) {
  7532. if (max == null) {
  7533. max = maxEndItem.end.valueOf();
  7534. }
  7535. else {
  7536. max = Math.max(max, maxEndItem.end.valueOf());
  7537. }
  7538. }
  7539. }
  7540. return {
  7541. min: (min != null) ? new Date(min) : null,
  7542. max: (max != null) ? new Date(max) : null
  7543. };
  7544. };
  7545. /**
  7546. * Set selected items by their id. Replaces the current selection
  7547. * Unknown id's are silently ignored.
  7548. * @param {Array} [ids] An array with zero or more id's of the items to be
  7549. * selected. If ids is an empty array, all items will be
  7550. * unselected.
  7551. */
  7552. Timeline.prototype.setSelection = function setSelection (ids) {
  7553. this.itemSet.setSelection(ids);
  7554. };
  7555. /**
  7556. * Get the selected items by their id
  7557. * @return {Array} ids The ids of the selected items
  7558. */
  7559. Timeline.prototype.getSelection = function getSelection() {
  7560. return this.itemSet.getSelection();
  7561. };
  7562. /**
  7563. * Set the visible window. Both parameters are optional, you can change only
  7564. * start or only end. Syntax:
  7565. *
  7566. * TimeLine.setWindow(start, end)
  7567. * TimeLine.setWindow(range)
  7568. *
  7569. * Where start and end can be a Date, number, or string, and range is an
  7570. * object with properties start and end.
  7571. *
  7572. * @param {Date | Number | String} [start] Start date of visible window
  7573. * @param {Date | Number | String} [end] End date of visible window
  7574. */
  7575. Timeline.prototype.setWindow = function setWindow(start, end) {
  7576. if (arguments.length == 1) {
  7577. var range = arguments[0];
  7578. this.range.setRange(range.start, range.end);
  7579. }
  7580. else {
  7581. this.range.setRange(start, end);
  7582. }
  7583. };
  7584. /**
  7585. * Get the visible window
  7586. * @return {{start: Date, end: Date}} Visible range
  7587. */
  7588. Timeline.prototype.getWindow = function setWindow() {
  7589. var range = this.range.getRange();
  7590. return {
  7591. start: new Date(range.start),
  7592. end: new Date(range.end)
  7593. };
  7594. };
  7595. /**
  7596. * Handle selecting/deselecting an item when tapping it
  7597. * @param {Event} event
  7598. * @private
  7599. */
  7600. // TODO: move this function to ItemSet
  7601. Timeline.prototype._onSelectItem = function (event) {
  7602. if (!this.options.selectable) return;
  7603. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  7604. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  7605. if (ctrlKey || shiftKey) {
  7606. this._onMultiSelectItem(event);
  7607. return;
  7608. }
  7609. var oldSelection = this.getSelection();
  7610. var item = ItemSet.itemFromTarget(event);
  7611. var selection = item ? [item.id] : [];
  7612. this.setSelection(selection);
  7613. var newSelection = this.getSelection();
  7614. // if selection is changed, emit a select event
  7615. if (!util.equalArray(oldSelection, newSelection)) {
  7616. this.emit('select', {
  7617. items: this.getSelection()
  7618. });
  7619. }
  7620. event.stopPropagation();
  7621. };
  7622. /**
  7623. * Handle creation and updates of an item on double tap
  7624. * @param event
  7625. * @private
  7626. */
  7627. Timeline.prototype._onAddItem = function (event) {
  7628. if (!this.options.selectable) return;
  7629. if (!this.options.editable.add) return;
  7630. var me = this,
  7631. item = ItemSet.itemFromTarget(event);
  7632. if (item) {
  7633. // update item
  7634. // execute async handler to update the item (or cancel it)
  7635. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  7636. this.options.onUpdate(itemData, function (itemData) {
  7637. if (itemData) {
  7638. me.itemsData.update(itemData);
  7639. }
  7640. });
  7641. }
  7642. else {
  7643. // add item
  7644. var xAbs = vis.util.getAbsoluteLeft(this.contentPanel.frame);
  7645. var x = event.gesture.center.pageX - xAbs;
  7646. var newItem = {
  7647. start: this.timeAxis.snap(this._toTime(x)),
  7648. content: 'new item'
  7649. };
  7650. var id = util.randomUUID();
  7651. newItem[this.itemsData.fieldId] = id;
  7652. var group = ItemSet.groupFromTarget(event);
  7653. if (group) {
  7654. newItem.group = group.groupId;
  7655. }
  7656. // execute async handler to customize (or cancel) adding an item
  7657. this.options.onAdd(newItem, function (item) {
  7658. if (item) {
  7659. me.itemsData.add(newItem);
  7660. // TODO: need to trigger a repaint?
  7661. }
  7662. });
  7663. }
  7664. };
  7665. /**
  7666. * Handle selecting/deselecting multiple items when holding an item
  7667. * @param {Event} event
  7668. * @private
  7669. */
  7670. // TODO: move this function to ItemSet
  7671. Timeline.prototype._onMultiSelectItem = function (event) {
  7672. if (!this.options.selectable) return;
  7673. var selection,
  7674. item = ItemSet.itemFromTarget(event);
  7675. if (item) {
  7676. // multi select items
  7677. selection = this.getSelection(); // current selection
  7678. var index = selection.indexOf(item.id);
  7679. if (index == -1) {
  7680. // item is not yet selected -> select it
  7681. selection.push(item.id);
  7682. }
  7683. else {
  7684. // item is already selected -> deselect it
  7685. selection.splice(index, 1);
  7686. }
  7687. this.setSelection(selection);
  7688. this.emit('select', {
  7689. items: this.getSelection()
  7690. });
  7691. event.stopPropagation();
  7692. }
  7693. };
  7694. /**
  7695. * Convert a position on screen (pixels) to a datetime
  7696. * @param {int} x Position on the screen in pixels
  7697. * @return {Date} time The datetime the corresponds with given position x
  7698. * @private
  7699. */
  7700. Timeline.prototype._toTime = function _toTime(x) {
  7701. var conversion = this.range.conversion(this.mainPanel.width);
  7702. return new Date(x / conversion.scale + conversion.offset);
  7703. };
  7704. /**
  7705. * Convert a datetime (Date object) into a position on the screen
  7706. * @param {Date} time A date
  7707. * @return {int} x The position on the screen in pixels which corresponds
  7708. * with the given date.
  7709. * @private
  7710. */
  7711. Timeline.prototype._toScreen = function _toScreen(time) {
  7712. var conversion = this.range.conversion(this.mainPanel.width);
  7713. return (time.valueOf() - conversion.offset) * conversion.scale;
  7714. };
  7715. (function(exports) {
  7716. /**
  7717. * Parse a text source containing data in DOT language into a JSON object.
  7718. * The object contains two lists: one with nodes and one with edges.
  7719. *
  7720. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  7721. *
  7722. * @param {String} data Text containing a graph in DOT-notation
  7723. * @return {Object} graph An object containing two parameters:
  7724. * {Object[]} nodes
  7725. * {Object[]} edges
  7726. */
  7727. function parseDOT (data) {
  7728. dot = data;
  7729. return parseGraph();
  7730. }
  7731. // token types enumeration
  7732. var TOKENTYPE = {
  7733. NULL : 0,
  7734. DELIMITER : 1,
  7735. IDENTIFIER: 2,
  7736. UNKNOWN : 3
  7737. };
  7738. // map with all delimiters
  7739. var DELIMITERS = {
  7740. '{': true,
  7741. '}': true,
  7742. '[': true,
  7743. ']': true,
  7744. ';': true,
  7745. '=': true,
  7746. ',': true,
  7747. '->': true,
  7748. '--': true
  7749. };
  7750. var dot = ''; // current dot file
  7751. var index = 0; // current index in dot file
  7752. var c = ''; // current token character in expr
  7753. var token = ''; // current token
  7754. var tokenType = TOKENTYPE.NULL; // type of the token
  7755. /**
  7756. * Get the first character from the dot file.
  7757. * The character is stored into the char c. If the end of the dot file is
  7758. * reached, the function puts an empty string in c.
  7759. */
  7760. function first() {
  7761. index = 0;
  7762. c = dot.charAt(0);
  7763. }
  7764. /**
  7765. * Get the next character from the dot file.
  7766. * The character is stored into the char c. If the end of the dot file is
  7767. * reached, the function puts an empty string in c.
  7768. */
  7769. function next() {
  7770. index++;
  7771. c = dot.charAt(index);
  7772. }
  7773. /**
  7774. * Preview the next character from the dot file.
  7775. * @return {String} cNext
  7776. */
  7777. function nextPreview() {
  7778. return dot.charAt(index + 1);
  7779. }
  7780. /**
  7781. * Test whether given character is alphabetic or numeric
  7782. * @param {String} c
  7783. * @return {Boolean} isAlphaNumeric
  7784. */
  7785. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  7786. function isAlphaNumeric(c) {
  7787. return regexAlphaNumeric.test(c);
  7788. }
  7789. /**
  7790. * Merge all properties of object b into object b
  7791. * @param {Object} a
  7792. * @param {Object} b
  7793. * @return {Object} a
  7794. */
  7795. function merge (a, b) {
  7796. if (!a) {
  7797. a = {};
  7798. }
  7799. if (b) {
  7800. for (var name in b) {
  7801. if (b.hasOwnProperty(name)) {
  7802. a[name] = b[name];
  7803. }
  7804. }
  7805. }
  7806. return a;
  7807. }
  7808. /**
  7809. * Set a value in an object, where the provided parameter name can be a
  7810. * path with nested parameters. For example:
  7811. *
  7812. * var obj = {a: 2};
  7813. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  7814. *
  7815. * @param {Object} obj
  7816. * @param {String} path A parameter name or dot-separated parameter path,
  7817. * like "color.highlight.border".
  7818. * @param {*} value
  7819. */
  7820. function setValue(obj, path, value) {
  7821. var keys = path.split('.');
  7822. var o = obj;
  7823. while (keys.length) {
  7824. var key = keys.shift();
  7825. if (keys.length) {
  7826. // this isn't the end point
  7827. if (!o[key]) {
  7828. o[key] = {};
  7829. }
  7830. o = o[key];
  7831. }
  7832. else {
  7833. // this is the end point
  7834. o[key] = value;
  7835. }
  7836. }
  7837. }
  7838. /**
  7839. * Add a node to a graph object. If there is already a node with
  7840. * the same id, their attributes will be merged.
  7841. * @param {Object} graph
  7842. * @param {Object} node
  7843. */
  7844. function addNode(graph, node) {
  7845. var i, len;
  7846. var current = null;
  7847. // find root graph (in case of subgraph)
  7848. var graphs = [graph]; // list with all graphs from current graph to root graph
  7849. var root = graph;
  7850. while (root.parent) {
  7851. graphs.push(root.parent);
  7852. root = root.parent;
  7853. }
  7854. // find existing node (at root level) by its id
  7855. if (root.nodes) {
  7856. for (i = 0, len = root.nodes.length; i < len; i++) {
  7857. if (node.id === root.nodes[i].id) {
  7858. current = root.nodes[i];
  7859. break;
  7860. }
  7861. }
  7862. }
  7863. if (!current) {
  7864. // this is a new node
  7865. current = {
  7866. id: node.id
  7867. };
  7868. if (graph.node) {
  7869. // clone default attributes
  7870. current.attr = merge(current.attr, graph.node);
  7871. }
  7872. }
  7873. // add node to this (sub)graph and all its parent graphs
  7874. for (i = graphs.length - 1; i >= 0; i--) {
  7875. var g = graphs[i];
  7876. if (!g.nodes) {
  7877. g.nodes = [];
  7878. }
  7879. if (g.nodes.indexOf(current) == -1) {
  7880. g.nodes.push(current);
  7881. }
  7882. }
  7883. // merge attributes
  7884. if (node.attr) {
  7885. current.attr = merge(current.attr, node.attr);
  7886. }
  7887. }
  7888. /**
  7889. * Add an edge to a graph object
  7890. * @param {Object} graph
  7891. * @param {Object} edge
  7892. */
  7893. function addEdge(graph, edge) {
  7894. if (!graph.edges) {
  7895. graph.edges = [];
  7896. }
  7897. graph.edges.push(edge);
  7898. if (graph.edge) {
  7899. var attr = merge({}, graph.edge); // clone default attributes
  7900. edge.attr = merge(attr, edge.attr); // merge attributes
  7901. }
  7902. }
  7903. /**
  7904. * Create an edge to a graph object
  7905. * @param {Object} graph
  7906. * @param {String | Number | Object} from
  7907. * @param {String | Number | Object} to
  7908. * @param {String} type
  7909. * @param {Object | null} attr
  7910. * @return {Object} edge
  7911. */
  7912. function createEdge(graph, from, to, type, attr) {
  7913. var edge = {
  7914. from: from,
  7915. to: to,
  7916. type: type
  7917. };
  7918. if (graph.edge) {
  7919. edge.attr = merge({}, graph.edge); // clone default attributes
  7920. }
  7921. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7922. return edge;
  7923. }
  7924. /**
  7925. * Get next token in the current dot file.
  7926. * The token and token type are available as token and tokenType
  7927. */
  7928. function getToken() {
  7929. tokenType = TOKENTYPE.NULL;
  7930. token = '';
  7931. // skip over whitespaces
  7932. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7933. next();
  7934. }
  7935. do {
  7936. var isComment = false;
  7937. // skip comment
  7938. if (c == '#') {
  7939. // find the previous non-space character
  7940. var i = index - 1;
  7941. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7942. i--;
  7943. }
  7944. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7945. // the # is at the start of a line, this is indeed a line comment
  7946. while (c != '' && c != '\n') {
  7947. next();
  7948. }
  7949. isComment = true;
  7950. }
  7951. }
  7952. if (c == '/' && nextPreview() == '/') {
  7953. // skip line comment
  7954. while (c != '' && c != '\n') {
  7955. next();
  7956. }
  7957. isComment = true;
  7958. }
  7959. if (c == '/' && nextPreview() == '*') {
  7960. // skip block comment
  7961. while (c != '') {
  7962. if (c == '*' && nextPreview() == '/') {
  7963. // end of block comment found. skip these last two characters
  7964. next();
  7965. next();
  7966. break;
  7967. }
  7968. else {
  7969. next();
  7970. }
  7971. }
  7972. isComment = true;
  7973. }
  7974. // skip over whitespaces
  7975. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7976. next();
  7977. }
  7978. }
  7979. while (isComment);
  7980. // check for end of dot file
  7981. if (c == '') {
  7982. // token is still empty
  7983. tokenType = TOKENTYPE.DELIMITER;
  7984. return;
  7985. }
  7986. // check for delimiters consisting of 2 characters
  7987. var c2 = c + nextPreview();
  7988. if (DELIMITERS[c2]) {
  7989. tokenType = TOKENTYPE.DELIMITER;
  7990. token = c2;
  7991. next();
  7992. next();
  7993. return;
  7994. }
  7995. // check for delimiters consisting of 1 character
  7996. if (DELIMITERS[c]) {
  7997. tokenType = TOKENTYPE.DELIMITER;
  7998. token = c;
  7999. next();
  8000. return;
  8001. }
  8002. // check for an identifier (number or string)
  8003. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  8004. if (isAlphaNumeric(c) || c == '-') {
  8005. token += c;
  8006. next();
  8007. while (isAlphaNumeric(c)) {
  8008. token += c;
  8009. next();
  8010. }
  8011. if (token == 'false') {
  8012. token = false; // convert to boolean
  8013. }
  8014. else if (token == 'true') {
  8015. token = true; // convert to boolean
  8016. }
  8017. else if (!isNaN(Number(token))) {
  8018. token = Number(token); // convert to number
  8019. }
  8020. tokenType = TOKENTYPE.IDENTIFIER;
  8021. return;
  8022. }
  8023. // check for a string enclosed by double quotes
  8024. if (c == '"') {
  8025. next();
  8026. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  8027. token += c;
  8028. if (c == '"') { // skip the escape character
  8029. next();
  8030. }
  8031. next();
  8032. }
  8033. if (c != '"') {
  8034. throw newSyntaxError('End of string " expected');
  8035. }
  8036. next();
  8037. tokenType = TOKENTYPE.IDENTIFIER;
  8038. return;
  8039. }
  8040. // something unknown is found, wrong characters, a syntax error
  8041. tokenType = TOKENTYPE.UNKNOWN;
  8042. while (c != '') {
  8043. token += c;
  8044. next();
  8045. }
  8046. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  8047. }
  8048. /**
  8049. * Parse a graph.
  8050. * @returns {Object} graph
  8051. */
  8052. function parseGraph() {
  8053. var graph = {};
  8054. first();
  8055. getToken();
  8056. // optional strict keyword
  8057. if (token == 'strict') {
  8058. graph.strict = true;
  8059. getToken();
  8060. }
  8061. // graph or digraph keyword
  8062. if (token == 'graph' || token == 'digraph') {
  8063. graph.type = token;
  8064. getToken();
  8065. }
  8066. // optional graph id
  8067. if (tokenType == TOKENTYPE.IDENTIFIER) {
  8068. graph.id = token;
  8069. getToken();
  8070. }
  8071. // open angle bracket
  8072. if (token != '{') {
  8073. throw newSyntaxError('Angle bracket { expected');
  8074. }
  8075. getToken();
  8076. // statements
  8077. parseStatements(graph);
  8078. // close angle bracket
  8079. if (token != '}') {
  8080. throw newSyntaxError('Angle bracket } expected');
  8081. }
  8082. getToken();
  8083. // end of file
  8084. if (token !== '') {
  8085. throw newSyntaxError('End of file expected');
  8086. }
  8087. getToken();
  8088. // remove temporary default properties
  8089. delete graph.node;
  8090. delete graph.edge;
  8091. delete graph.graph;
  8092. return graph;
  8093. }
  8094. /**
  8095. * Parse a list with statements.
  8096. * @param {Object} graph
  8097. */
  8098. function parseStatements (graph) {
  8099. while (token !== '' && token != '}') {
  8100. parseStatement(graph);
  8101. if (token == ';') {
  8102. getToken();
  8103. }
  8104. }
  8105. }
  8106. /**
  8107. * Parse a single statement. Can be a an attribute statement, node
  8108. * statement, a series of node statements and edge statements, or a
  8109. * parameter.
  8110. * @param {Object} graph
  8111. */
  8112. function parseStatement(graph) {
  8113. // parse subgraph
  8114. var subgraph = parseSubgraph(graph);
  8115. if (subgraph) {
  8116. // edge statements
  8117. parseEdge(graph, subgraph);
  8118. return;
  8119. }
  8120. // parse an attribute statement
  8121. var attr = parseAttributeStatement(graph);
  8122. if (attr) {
  8123. return;
  8124. }
  8125. // parse node
  8126. if (tokenType != TOKENTYPE.IDENTIFIER) {
  8127. throw newSyntaxError('Identifier expected');
  8128. }
  8129. var id = token; // id can be a string or a number
  8130. getToken();
  8131. if (token == '=') {
  8132. // id statement
  8133. getToken();
  8134. if (tokenType != TOKENTYPE.IDENTIFIER) {
  8135. throw newSyntaxError('Identifier expected');
  8136. }
  8137. graph[id] = token;
  8138. getToken();
  8139. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  8140. }
  8141. else {
  8142. parseNodeStatement(graph, id);
  8143. }
  8144. }
  8145. /**
  8146. * Parse a subgraph
  8147. * @param {Object} graph parent graph object
  8148. * @return {Object | null} subgraph
  8149. */
  8150. function parseSubgraph (graph) {
  8151. var subgraph = null;
  8152. // optional subgraph keyword
  8153. if (token == 'subgraph') {
  8154. subgraph = {};
  8155. subgraph.type = 'subgraph';
  8156. getToken();
  8157. // optional graph id
  8158. if (tokenType == TOKENTYPE.IDENTIFIER) {
  8159. subgraph.id = token;
  8160. getToken();
  8161. }
  8162. }
  8163. // open angle bracket
  8164. if (token == '{') {
  8165. getToken();
  8166. if (!subgraph) {
  8167. subgraph = {};
  8168. }
  8169. subgraph.parent = graph;
  8170. subgraph.node = graph.node;
  8171. subgraph.edge = graph.edge;
  8172. subgraph.graph = graph.graph;
  8173. // statements
  8174. parseStatements(subgraph);
  8175. // close angle bracket
  8176. if (token != '}') {
  8177. throw newSyntaxError('Angle bracket } expected');
  8178. }
  8179. getToken();
  8180. // remove temporary default properties
  8181. delete subgraph.node;
  8182. delete subgraph.edge;
  8183. delete subgraph.graph;
  8184. delete subgraph.parent;
  8185. // register at the parent graph
  8186. if (!graph.subgraphs) {
  8187. graph.subgraphs = [];
  8188. }
  8189. graph.subgraphs.push(subgraph);
  8190. }
  8191. return subgraph;
  8192. }
  8193. /**
  8194. * parse an attribute statement like "node [shape=circle fontSize=16]".
  8195. * Available keywords are 'node', 'edge', 'graph'.
  8196. * The previous list with default attributes will be replaced
  8197. * @param {Object} graph
  8198. * @returns {String | null} keyword Returns the name of the parsed attribute
  8199. * (node, edge, graph), or null if nothing
  8200. * is parsed.
  8201. */
  8202. function parseAttributeStatement (graph) {
  8203. // attribute statements
  8204. if (token == 'node') {
  8205. getToken();
  8206. // node attributes
  8207. graph.node = parseAttributeList();
  8208. return 'node';
  8209. }
  8210. else if (token == 'edge') {
  8211. getToken();
  8212. // edge attributes
  8213. graph.edge = parseAttributeList();
  8214. return 'edge';
  8215. }
  8216. else if (token == 'graph') {
  8217. getToken();
  8218. // graph attributes
  8219. graph.graph = parseAttributeList();
  8220. return 'graph';
  8221. }
  8222. return null;
  8223. }
  8224. /**
  8225. * parse a node statement
  8226. * @param {Object} graph
  8227. * @param {String | Number} id
  8228. */
  8229. function parseNodeStatement(graph, id) {
  8230. // node statement
  8231. var node = {
  8232. id: id
  8233. };
  8234. var attr = parseAttributeList();
  8235. if (attr) {
  8236. node.attr = attr;
  8237. }
  8238. addNode(graph, node);
  8239. // edge statements
  8240. parseEdge(graph, id);
  8241. }
  8242. /**
  8243. * Parse an edge or a series of edges
  8244. * @param {Object} graph
  8245. * @param {String | Number} from Id of the from node
  8246. */
  8247. function parseEdge(graph, from) {
  8248. while (token == '->' || token == '--') {
  8249. var to;
  8250. var type = token;
  8251. getToken();
  8252. var subgraph = parseSubgraph(graph);
  8253. if (subgraph) {
  8254. to = subgraph;
  8255. }
  8256. else {
  8257. if (tokenType != TOKENTYPE.IDENTIFIER) {
  8258. throw newSyntaxError('Identifier or subgraph expected');
  8259. }
  8260. to = token;
  8261. addNode(graph, {
  8262. id: to
  8263. });
  8264. getToken();
  8265. }
  8266. // parse edge attributes
  8267. var attr = parseAttributeList();
  8268. // create edge
  8269. var edge = createEdge(graph, from, to, type, attr);
  8270. addEdge(graph, edge);
  8271. from = to;
  8272. }
  8273. }
  8274. /**
  8275. * Parse a set with attributes,
  8276. * for example [label="1.000", shape=solid]
  8277. * @return {Object | null} attr
  8278. */
  8279. function parseAttributeList() {
  8280. var attr = null;
  8281. while (token == '[') {
  8282. getToken();
  8283. attr = {};
  8284. while (token !== '' && token != ']') {
  8285. if (tokenType != TOKENTYPE.IDENTIFIER) {
  8286. throw newSyntaxError('Attribute name expected');
  8287. }
  8288. var name = token;
  8289. getToken();
  8290. if (token != '=') {
  8291. throw newSyntaxError('Equal sign = expected');
  8292. }
  8293. getToken();
  8294. if (tokenType != TOKENTYPE.IDENTIFIER) {
  8295. throw newSyntaxError('Attribute value expected');
  8296. }
  8297. var value = token;
  8298. setValue(attr, name, value); // name can be a path
  8299. getToken();
  8300. if (token ==',') {
  8301. getToken();
  8302. }
  8303. }
  8304. if (token != ']') {
  8305. throw newSyntaxError('Bracket ] expected');
  8306. }
  8307. getToken();
  8308. }
  8309. return attr;
  8310. }
  8311. /**
  8312. * Create a syntax error with extra information on current token and index.
  8313. * @param {String} message
  8314. * @returns {SyntaxError} err
  8315. */
  8316. function newSyntaxError(message) {
  8317. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  8318. }
  8319. /**
  8320. * Chop off text after a maximum length
  8321. * @param {String} text
  8322. * @param {Number} maxLength
  8323. * @returns {String}
  8324. */
  8325. function chop (text, maxLength) {
  8326. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  8327. }
  8328. /**
  8329. * Execute a function fn for each pair of elements in two arrays
  8330. * @param {Array | *} array1
  8331. * @param {Array | *} array2
  8332. * @param {function} fn
  8333. */
  8334. function forEach2(array1, array2, fn) {
  8335. if (array1 instanceof Array) {
  8336. array1.forEach(function (elem1) {
  8337. if (array2 instanceof Array) {
  8338. array2.forEach(function (elem2) {
  8339. fn(elem1, elem2);
  8340. });
  8341. }
  8342. else {
  8343. fn(elem1, array2);
  8344. }
  8345. });
  8346. }
  8347. else {
  8348. if (array2 instanceof Array) {
  8349. array2.forEach(function (elem2) {
  8350. fn(array1, elem2);
  8351. });
  8352. }
  8353. else {
  8354. fn(array1, array2);
  8355. }
  8356. }
  8357. }
  8358. /**
  8359. * Convert a string containing a graph in DOT language into a map containing
  8360. * with nodes and edges in the format of graph.
  8361. * @param {String} data Text containing a graph in DOT-notation
  8362. * @return {Object} graphData
  8363. */
  8364. function DOTToGraph (data) {
  8365. // parse the DOT file
  8366. var dotData = parseDOT(data);
  8367. var graphData = {
  8368. nodes: [],
  8369. edges: [],
  8370. options: {}
  8371. };
  8372. // copy the nodes
  8373. if (dotData.nodes) {
  8374. dotData.nodes.forEach(function (dotNode) {
  8375. var graphNode = {
  8376. id: dotNode.id,
  8377. label: String(dotNode.label || dotNode.id)
  8378. };
  8379. merge(graphNode, dotNode.attr);
  8380. if (graphNode.image) {
  8381. graphNode.shape = 'image';
  8382. }
  8383. graphData.nodes.push(graphNode);
  8384. });
  8385. }
  8386. // copy the edges
  8387. if (dotData.edges) {
  8388. /**
  8389. * Convert an edge in DOT format to an edge with VisGraph format
  8390. * @param {Object} dotEdge
  8391. * @returns {Object} graphEdge
  8392. */
  8393. function convertEdge(dotEdge) {
  8394. var graphEdge = {
  8395. from: dotEdge.from,
  8396. to: dotEdge.to
  8397. };
  8398. merge(graphEdge, dotEdge.attr);
  8399. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  8400. return graphEdge;
  8401. }
  8402. dotData.edges.forEach(function (dotEdge) {
  8403. var from, to;
  8404. if (dotEdge.from instanceof Object) {
  8405. from = dotEdge.from.nodes;
  8406. }
  8407. else {
  8408. from = {
  8409. id: dotEdge.from
  8410. }
  8411. }
  8412. if (dotEdge.to instanceof Object) {
  8413. to = dotEdge.to.nodes;
  8414. }
  8415. else {
  8416. to = {
  8417. id: dotEdge.to
  8418. }
  8419. }
  8420. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  8421. dotEdge.from.edges.forEach(function (subEdge) {
  8422. var graphEdge = convertEdge(subEdge);
  8423. graphData.edges.push(graphEdge);
  8424. });
  8425. }
  8426. forEach2(from, to, function (from, to) {
  8427. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  8428. var graphEdge = convertEdge(subEdge);
  8429. graphData.edges.push(graphEdge);
  8430. });
  8431. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  8432. dotEdge.to.edges.forEach(function (subEdge) {
  8433. var graphEdge = convertEdge(subEdge);
  8434. graphData.edges.push(graphEdge);
  8435. });
  8436. }
  8437. });
  8438. }
  8439. // copy the options
  8440. if (dotData.attr) {
  8441. graphData.options = dotData.attr;
  8442. }
  8443. return graphData;
  8444. }
  8445. // exports
  8446. exports.parseDOT = parseDOT;
  8447. exports.DOTToGraph = DOTToGraph;
  8448. })(typeof util !== 'undefined' ? util : exports);
  8449. /**
  8450. * Canvas shapes used by the Graph
  8451. */
  8452. if (typeof CanvasRenderingContext2D !== 'undefined') {
  8453. /**
  8454. * Draw a circle shape
  8455. */
  8456. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  8457. this.beginPath();
  8458. this.arc(x, y, r, 0, 2*Math.PI, false);
  8459. };
  8460. /**
  8461. * Draw a square shape
  8462. * @param {Number} x horizontal center
  8463. * @param {Number} y vertical center
  8464. * @param {Number} r size, width and height of the square
  8465. */
  8466. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  8467. this.beginPath();
  8468. this.rect(x - r, y - r, r * 2, r * 2);
  8469. };
  8470. /**
  8471. * Draw a triangle shape
  8472. * @param {Number} x horizontal center
  8473. * @param {Number} y vertical center
  8474. * @param {Number} r radius, half the length of the sides of the triangle
  8475. */
  8476. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  8477. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8478. this.beginPath();
  8479. var s = r * 2;
  8480. var s2 = s / 2;
  8481. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8482. var h = Math.sqrt(s * s - s2 * s2); // height
  8483. this.moveTo(x, y - (h - ir));
  8484. this.lineTo(x + s2, y + ir);
  8485. this.lineTo(x - s2, y + ir);
  8486. this.lineTo(x, y - (h - ir));
  8487. this.closePath();
  8488. };
  8489. /**
  8490. * Draw a triangle shape in downward orientation
  8491. * @param {Number} x horizontal center
  8492. * @param {Number} y vertical center
  8493. * @param {Number} r radius
  8494. */
  8495. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  8496. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8497. this.beginPath();
  8498. var s = r * 2;
  8499. var s2 = s / 2;
  8500. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8501. var h = Math.sqrt(s * s - s2 * s2); // height
  8502. this.moveTo(x, y + (h - ir));
  8503. this.lineTo(x + s2, y - ir);
  8504. this.lineTo(x - s2, y - ir);
  8505. this.lineTo(x, y + (h - ir));
  8506. this.closePath();
  8507. };
  8508. /**
  8509. * Draw a star shape, a star with 5 points
  8510. * @param {Number} x horizontal center
  8511. * @param {Number} y vertical center
  8512. * @param {Number} r radius, half the length of the sides of the triangle
  8513. */
  8514. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  8515. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  8516. this.beginPath();
  8517. for (var n = 0; n < 10; n++) {
  8518. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  8519. this.lineTo(
  8520. x + radius * Math.sin(n * 2 * Math.PI / 10),
  8521. y - radius * Math.cos(n * 2 * Math.PI / 10)
  8522. );
  8523. }
  8524. this.closePath();
  8525. };
  8526. /**
  8527. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  8528. */
  8529. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  8530. var r2d = Math.PI/180;
  8531. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  8532. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  8533. this.beginPath();
  8534. this.moveTo(x+r,y);
  8535. this.lineTo(x+w-r,y);
  8536. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  8537. this.lineTo(x+w,y+h-r);
  8538. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  8539. this.lineTo(x+r,y+h);
  8540. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  8541. this.lineTo(x,y+r);
  8542. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  8543. };
  8544. /**
  8545. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8546. */
  8547. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  8548. var kappa = .5522848,
  8549. ox = (w / 2) * kappa, // control point offset horizontal
  8550. oy = (h / 2) * kappa, // control point offset vertical
  8551. xe = x + w, // x-end
  8552. ye = y + h, // y-end
  8553. xm = x + w / 2, // x-middle
  8554. ym = y + h / 2; // y-middle
  8555. this.beginPath();
  8556. this.moveTo(x, ym);
  8557. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8558. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8559. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8560. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8561. };
  8562. /**
  8563. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8564. */
  8565. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  8566. var f = 1/3;
  8567. var wEllipse = w;
  8568. var hEllipse = h * f;
  8569. var kappa = .5522848,
  8570. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  8571. oy = (hEllipse / 2) * kappa, // control point offset vertical
  8572. xe = x + wEllipse, // x-end
  8573. ye = y + hEllipse, // y-end
  8574. xm = x + wEllipse / 2, // x-middle
  8575. ym = y + hEllipse / 2, // y-middle
  8576. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  8577. yeb = y + h; // y-end, bottom ellipse
  8578. this.beginPath();
  8579. this.moveTo(xe, ym);
  8580. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8581. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8582. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8583. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8584. this.lineTo(xe, ymb);
  8585. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  8586. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  8587. this.lineTo(x, ym);
  8588. };
  8589. /**
  8590. * Draw an arrow point (no line)
  8591. */
  8592. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  8593. // tail
  8594. var xt = x - length * Math.cos(angle);
  8595. var yt = y - length * Math.sin(angle);
  8596. // inner tail
  8597. // TODO: allow to customize different shapes
  8598. var xi = x - length * 0.9 * Math.cos(angle);
  8599. var yi = y - length * 0.9 * Math.sin(angle);
  8600. // left
  8601. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  8602. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  8603. // right
  8604. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  8605. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  8606. this.beginPath();
  8607. this.moveTo(x, y);
  8608. this.lineTo(xl, yl);
  8609. this.lineTo(xi, yi);
  8610. this.lineTo(xr, yr);
  8611. this.closePath();
  8612. };
  8613. /**
  8614. * Sets up the dashedLine functionality for drawing
  8615. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  8616. * @author David Jordan
  8617. * @date 2012-08-08
  8618. */
  8619. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  8620. if (!dashArray) dashArray=[10,5];
  8621. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  8622. var dashCount = dashArray.length;
  8623. this.moveTo(x, y);
  8624. var dx = (x2-x), dy = (y2-y);
  8625. var slope = dy/dx;
  8626. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  8627. var dashIndex=0, draw=true;
  8628. while (distRemaining>=0.1){
  8629. var dashLength = dashArray[dashIndex++%dashCount];
  8630. if (dashLength > distRemaining) dashLength = distRemaining;
  8631. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  8632. if (dx<0) xStep = -xStep;
  8633. x += xStep;
  8634. y += slope*xStep;
  8635. this[draw ? 'lineTo' : 'moveTo'](x,y);
  8636. distRemaining -= dashLength;
  8637. draw = !draw;
  8638. }
  8639. };
  8640. // TODO: add diamond shape
  8641. }
  8642. /**
  8643. * @class Node
  8644. * A node. A node can be connected to other nodes via one or multiple edges.
  8645. * @param {object} properties An object containing properties for the node. All
  8646. * properties are optional, except for the id.
  8647. * {number} id Id of the node. Required
  8648. * {string} label Text label for the node
  8649. * {number} x Horizontal position of the node
  8650. * {number} y Vertical position of the node
  8651. * {string} shape Node shape, available:
  8652. * "database", "circle", "ellipse",
  8653. * "box", "image", "text", "dot",
  8654. * "star", "triangle", "triangleDown",
  8655. * "square"
  8656. * {string} image An image url
  8657. * {string} title An title text, can be HTML
  8658. * {anytype} group A group name or number
  8659. * @param {Graph.Images} imagelist A list with images. Only needed
  8660. * when the node has an image
  8661. * @param {Graph.Groups} grouplist A list with groups. Needed for
  8662. * retrieving group properties
  8663. * @param {Object} constants An object with default values for
  8664. * example for the color
  8665. *
  8666. */
  8667. function Node(properties, imagelist, grouplist, constants) {
  8668. this.selected = false;
  8669. this.edges = []; // all edges connected to this node
  8670. this.dynamicEdges = [];
  8671. this.reroutedEdges = {};
  8672. this.group = constants.nodes.group;
  8673. this.fontSize = constants.nodes.fontSize;
  8674. this.fontFace = constants.nodes.fontFace;
  8675. this.fontColor = constants.nodes.fontColor;
  8676. this.fontDrawThreshold = 3;
  8677. this.color = constants.nodes.color;
  8678. // set defaults for the properties
  8679. this.id = undefined;
  8680. this.shape = constants.nodes.shape;
  8681. this.image = constants.nodes.image;
  8682. this.x = null;
  8683. this.y = null;
  8684. this.xFixed = false;
  8685. this.yFixed = false;
  8686. this.horizontalAlignLeft = true; // these are for the navigation controls
  8687. this.verticalAlignTop = true; // these are for the navigation controls
  8688. this.radius = constants.nodes.radius;
  8689. this.baseRadiusValue = constants.nodes.radius;
  8690. this.radiusFixed = false;
  8691. this.radiusMin = constants.nodes.radiusMin;
  8692. this.radiusMax = constants.nodes.radiusMax;
  8693. this.level = -1;
  8694. this.preassignedLevel = false;
  8695. this.imagelist = imagelist;
  8696. this.grouplist = grouplist;
  8697. // physics properties
  8698. this.fx = 0.0; // external force x
  8699. this.fy = 0.0; // external force y
  8700. this.vx = 0.0; // velocity x
  8701. this.vy = 0.0; // velocity y
  8702. this.minForce = constants.minForce;
  8703. this.damping = constants.physics.damping;
  8704. this.mass = 1; // kg
  8705. this.fixedData = {x:null,y:null};
  8706. this.setProperties(properties, constants);
  8707. // creating the variables for clustering
  8708. this.resetCluster();
  8709. this.dynamicEdgesLength = 0;
  8710. this.clusterSession = 0;
  8711. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  8712. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  8713. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  8714. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  8715. this.growthIndicator = 0;
  8716. // variables to tell the node about the graph.
  8717. this.graphScaleInv = 1;
  8718. this.graphScale = 1;
  8719. this.canvasTopLeft = {"x": -300, "y": -300};
  8720. this.canvasBottomRight = {"x": 300, "y": 300};
  8721. this.parentEdgeId = null;
  8722. }
  8723. /**
  8724. * (re)setting the clustering variables and objects
  8725. */
  8726. Node.prototype.resetCluster = function() {
  8727. // clustering variables
  8728. this.formationScale = undefined; // this is used to determine when to open the cluster
  8729. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  8730. this.containedNodes = {};
  8731. this.containedEdges = {};
  8732. this.clusterSessions = [];
  8733. };
  8734. /**
  8735. * Attach a edge to the node
  8736. * @param {Edge} edge
  8737. */
  8738. Node.prototype.attachEdge = function(edge) {
  8739. if (this.edges.indexOf(edge) == -1) {
  8740. this.edges.push(edge);
  8741. }
  8742. if (this.dynamicEdges.indexOf(edge) == -1) {
  8743. this.dynamicEdges.push(edge);
  8744. }
  8745. this.dynamicEdgesLength = this.dynamicEdges.length;
  8746. };
  8747. /**
  8748. * Detach a edge from the node
  8749. * @param {Edge} edge
  8750. */
  8751. Node.prototype.detachEdge = function(edge) {
  8752. var index = this.edges.indexOf(edge);
  8753. if (index != -1) {
  8754. this.edges.splice(index, 1);
  8755. this.dynamicEdges.splice(index, 1);
  8756. }
  8757. this.dynamicEdgesLength = this.dynamicEdges.length;
  8758. };
  8759. /**
  8760. * Set or overwrite properties for the node
  8761. * @param {Object} properties an object with properties
  8762. * @param {Object} constants and object with default, global properties
  8763. */
  8764. Node.prototype.setProperties = function(properties, constants) {
  8765. if (!properties) {
  8766. return;
  8767. }
  8768. this.originalLabel = undefined;
  8769. // basic properties
  8770. if (properties.id !== undefined) {this.id = properties.id;}
  8771. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  8772. if (properties.title !== undefined) {this.title = properties.title;}
  8773. if (properties.group !== undefined) {this.group = properties.group;}
  8774. if (properties.x !== undefined) {this.x = properties.x;}
  8775. if (properties.y !== undefined) {this.y = properties.y;}
  8776. if (properties.value !== undefined) {this.value = properties.value;}
  8777. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  8778. // physics
  8779. if (properties.mass !== undefined) {this.mass = properties.mass;}
  8780. // navigation controls properties
  8781. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  8782. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  8783. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  8784. if (this.id === undefined) {
  8785. throw "Node must have an id";
  8786. }
  8787. // copy group properties
  8788. if (this.group) {
  8789. var groupObj = this.grouplist.get(this.group);
  8790. for (var prop in groupObj) {
  8791. if (groupObj.hasOwnProperty(prop)) {
  8792. this[prop] = groupObj[prop];
  8793. }
  8794. }
  8795. }
  8796. // individual shape properties
  8797. if (properties.shape !== undefined) {this.shape = properties.shape;}
  8798. if (properties.image !== undefined) {this.image = properties.image;}
  8799. if (properties.radius !== undefined) {this.radius = properties.radius;}
  8800. if (properties.color !== undefined) {this.color = util.parseColor(properties.color);}
  8801. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8802. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8803. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8804. if (this.image !== undefined && this.image != "") {
  8805. if (this.imagelist) {
  8806. this.imageObj = this.imagelist.load(this.image);
  8807. }
  8808. else {
  8809. throw "No imagelist provided";
  8810. }
  8811. }
  8812. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX);
  8813. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  8814. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  8815. if (this.shape == 'image') {
  8816. this.radiusMin = constants.nodes.widthMin;
  8817. this.radiusMax = constants.nodes.widthMax;
  8818. }
  8819. // choose draw method depending on the shape
  8820. switch (this.shape) {
  8821. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  8822. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  8823. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  8824. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8825. // TODO: add diamond shape
  8826. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  8827. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  8828. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  8829. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  8830. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  8831. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  8832. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  8833. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8834. }
  8835. // reset the size of the node, this can be changed
  8836. this._reset();
  8837. };
  8838. /**
  8839. * select this node
  8840. */
  8841. Node.prototype.select = function() {
  8842. this.selected = true;
  8843. this._reset();
  8844. };
  8845. /**
  8846. * unselect this node
  8847. */
  8848. Node.prototype.unselect = function() {
  8849. this.selected = false;
  8850. this._reset();
  8851. };
  8852. /**
  8853. * Reset the calculated size of the node, forces it to recalculate its size
  8854. */
  8855. Node.prototype.clearSizeCache = function() {
  8856. this._reset();
  8857. };
  8858. /**
  8859. * Reset the calculated size of the node, forces it to recalculate its size
  8860. * @private
  8861. */
  8862. Node.prototype._reset = function() {
  8863. this.width = undefined;
  8864. this.height = undefined;
  8865. };
  8866. /**
  8867. * get the title of this node.
  8868. * @return {string} title The title of the node, or undefined when no title
  8869. * has been set.
  8870. */
  8871. Node.prototype.getTitle = function() {
  8872. return typeof this.title === "function" ? this.title() : this.title;
  8873. };
  8874. /**
  8875. * Calculate the distance to the border of the Node
  8876. * @param {CanvasRenderingContext2D} ctx
  8877. * @param {Number} angle Angle in radians
  8878. * @returns {number} distance Distance to the border in pixels
  8879. */
  8880. Node.prototype.distanceToBorder = function (ctx, angle) {
  8881. var borderWidth = 1;
  8882. if (!this.width) {
  8883. this.resize(ctx);
  8884. }
  8885. switch (this.shape) {
  8886. case 'circle':
  8887. case 'dot':
  8888. return this.radius + borderWidth;
  8889. case 'ellipse':
  8890. var a = this.width / 2;
  8891. var b = this.height / 2;
  8892. var w = (Math.sin(angle) * a);
  8893. var h = (Math.cos(angle) * b);
  8894. return a * b / Math.sqrt(w * w + h * h);
  8895. // TODO: implement distanceToBorder for database
  8896. // TODO: implement distanceToBorder for triangle
  8897. // TODO: implement distanceToBorder for triangleDown
  8898. case 'box':
  8899. case 'image':
  8900. case 'text':
  8901. default:
  8902. if (this.width) {
  8903. return Math.min(
  8904. Math.abs(this.width / 2 / Math.cos(angle)),
  8905. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8906. // TODO: reckon with border radius too in case of box
  8907. }
  8908. else {
  8909. return 0;
  8910. }
  8911. }
  8912. // TODO: implement calculation of distance to border for all shapes
  8913. };
  8914. /**
  8915. * Set forces acting on the node
  8916. * @param {number} fx Force in horizontal direction
  8917. * @param {number} fy Force in vertical direction
  8918. */
  8919. Node.prototype._setForce = function(fx, fy) {
  8920. this.fx = fx;
  8921. this.fy = fy;
  8922. };
  8923. /**
  8924. * Add forces acting on the node
  8925. * @param {number} fx Force in horizontal direction
  8926. * @param {number} fy Force in vertical direction
  8927. * @private
  8928. */
  8929. Node.prototype._addForce = function(fx, fy) {
  8930. this.fx += fx;
  8931. this.fy += fy;
  8932. };
  8933. /**
  8934. * Perform one discrete step for the node
  8935. * @param {number} interval Time interval in seconds
  8936. */
  8937. Node.prototype.discreteStep = function(interval) {
  8938. if (!this.xFixed) {
  8939. var dx = this.damping * this.vx; // damping force
  8940. var ax = (this.fx - dx) / this.mass; // acceleration
  8941. this.vx += ax * interval; // velocity
  8942. this.x += this.vx * interval; // position
  8943. }
  8944. if (!this.yFixed) {
  8945. var dy = this.damping * this.vy; // damping force
  8946. var ay = (this.fy - dy) / this.mass; // acceleration
  8947. this.vy += ay * interval; // velocity
  8948. this.y += this.vy * interval; // position
  8949. }
  8950. };
  8951. /**
  8952. * Perform one discrete step for the node
  8953. * @param {number} interval Time interval in seconds
  8954. * @param {number} maxVelocity The speed limit imposed on the velocity
  8955. */
  8956. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8957. if (!this.xFixed) {
  8958. var dx = this.damping * this.vx; // damping force
  8959. var ax = (this.fx - dx) / this.mass; // acceleration
  8960. this.vx += ax * interval; // velocity
  8961. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8962. this.x += this.vx * interval; // position
  8963. }
  8964. else {
  8965. this.fx = 0;
  8966. }
  8967. if (!this.yFixed) {
  8968. var dy = this.damping * this.vy; // damping force
  8969. var ay = (this.fy - dy) / this.mass; // acceleration
  8970. this.vy += ay * interval; // velocity
  8971. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8972. this.y += this.vy * interval; // position
  8973. }
  8974. else {
  8975. this.fy = 0;
  8976. }
  8977. };
  8978. /**
  8979. * Check if this node has a fixed x and y position
  8980. * @return {boolean} true if fixed, false if not
  8981. */
  8982. Node.prototype.isFixed = function() {
  8983. return (this.xFixed && this.yFixed);
  8984. };
  8985. /**
  8986. * Check if this node is moving
  8987. * @param {number} vmin the minimum velocity considered as "moving"
  8988. * @return {boolean} true if moving, false if it has no velocity
  8989. */
  8990. // TODO: replace this method with calculating the kinetic energy
  8991. Node.prototype.isMoving = function(vmin) {
  8992. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8993. };
  8994. /**
  8995. * check if this node is selecte
  8996. * @return {boolean} selected True if node is selected, else false
  8997. */
  8998. Node.prototype.isSelected = function() {
  8999. return this.selected;
  9000. };
  9001. /**
  9002. * Retrieve the value of the node. Can be undefined
  9003. * @return {Number} value
  9004. */
  9005. Node.prototype.getValue = function() {
  9006. return this.value;
  9007. };
  9008. /**
  9009. * Calculate the distance from the nodes location to the given location (x,y)
  9010. * @param {Number} x
  9011. * @param {Number} y
  9012. * @return {Number} value
  9013. */
  9014. Node.prototype.getDistance = function(x, y) {
  9015. var dx = this.x - x,
  9016. dy = this.y - y;
  9017. return Math.sqrt(dx * dx + dy * dy);
  9018. };
  9019. /**
  9020. * Adjust the value range of the node. The node will adjust it's radius
  9021. * based on its value.
  9022. * @param {Number} min
  9023. * @param {Number} max
  9024. */
  9025. Node.prototype.setValueRange = function(min, max) {
  9026. if (!this.radiusFixed && this.value !== undefined) {
  9027. if (max == min) {
  9028. this.radius = (this.radiusMin + this.radiusMax) / 2;
  9029. }
  9030. else {
  9031. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  9032. this.radius = (this.value - min) * scale + this.radiusMin;
  9033. }
  9034. }
  9035. this.baseRadiusValue = this.radius;
  9036. };
  9037. /**
  9038. * Draw this node in the given canvas
  9039. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9040. * @param {CanvasRenderingContext2D} ctx
  9041. */
  9042. Node.prototype.draw = function(ctx) {
  9043. throw "Draw method not initialized for node";
  9044. };
  9045. /**
  9046. * Recalculate the size of this node in the given canvas
  9047. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9048. * @param {CanvasRenderingContext2D} ctx
  9049. */
  9050. Node.prototype.resize = function(ctx) {
  9051. throw "Resize method not initialized for node";
  9052. };
  9053. /**
  9054. * Check if this object is overlapping with the provided object
  9055. * @param {Object} obj an object with parameters left, top, right, bottom
  9056. * @return {boolean} True if location is located on node
  9057. */
  9058. Node.prototype.isOverlappingWith = function(obj) {
  9059. return (this.left < obj.right &&
  9060. this.left + this.width > obj.left &&
  9061. this.top < obj.bottom &&
  9062. this.top + this.height > obj.top);
  9063. };
  9064. Node.prototype._resizeImage = function (ctx) {
  9065. // TODO: pre calculate the image size
  9066. if (!this.width || !this.height) { // undefined or 0
  9067. var width, height;
  9068. if (this.value) {
  9069. this.radius = this.baseRadiusValue;
  9070. var scale = this.imageObj.height / this.imageObj.width;
  9071. if (scale !== undefined) {
  9072. width = this.radius || this.imageObj.width;
  9073. height = this.radius * scale || this.imageObj.height;
  9074. }
  9075. else {
  9076. width = 0;
  9077. height = 0;
  9078. }
  9079. }
  9080. else {
  9081. width = this.imageObj.width;
  9082. height = this.imageObj.height;
  9083. }
  9084. this.width = width;
  9085. this.height = height;
  9086. this.growthIndicator = 0;
  9087. if (this.width > 0 && this.height > 0) {
  9088. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  9089. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  9090. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  9091. this.growthIndicator = this.width - width;
  9092. }
  9093. }
  9094. };
  9095. Node.prototype._drawImage = function (ctx) {
  9096. this._resizeImage(ctx);
  9097. this.left = this.x - this.width / 2;
  9098. this.top = this.y - this.height / 2;
  9099. var yLabel;
  9100. if (this.imageObj.width != 0 ) {
  9101. // draw the shade
  9102. if (this.clusterSize > 1) {
  9103. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  9104. lineWidth *= this.graphScaleInv;
  9105. lineWidth = Math.min(0.2 * this.width,lineWidth);
  9106. ctx.globalAlpha = 0.5;
  9107. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  9108. }
  9109. // draw the image
  9110. ctx.globalAlpha = 1.0;
  9111. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  9112. yLabel = this.y + this.height / 2;
  9113. }
  9114. else {
  9115. // image still loading... just draw the label for now
  9116. yLabel = this.y;
  9117. }
  9118. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  9119. };
  9120. Node.prototype._resizeBox = function (ctx) {
  9121. if (!this.width) {
  9122. var margin = 5;
  9123. var textSize = this.getTextSize(ctx);
  9124. this.width = textSize.width + 2 * margin;
  9125. this.height = textSize.height + 2 * margin;
  9126. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  9127. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  9128. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  9129. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  9130. }
  9131. };
  9132. Node.prototype._drawBox = function (ctx) {
  9133. this._resizeBox(ctx);
  9134. this.left = this.x - this.width / 2;
  9135. this.top = this.y - this.height / 2;
  9136. var clusterLineWidth = 2.5;
  9137. var selectionLineWidth = 2;
  9138. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  9139. // draw the outer border
  9140. if (this.clusterSize > 1) {
  9141. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  9142. ctx.lineWidth *= this.graphScaleInv;
  9143. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  9144. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  9145. ctx.stroke();
  9146. }
  9147. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  9148. ctx.lineWidth *= this.graphScaleInv;
  9149. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  9150. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  9151. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  9152. ctx.fill();
  9153. ctx.stroke();
  9154. this._label(ctx, this.label, this.x, this.y);
  9155. };
  9156. Node.prototype._resizeDatabase = function (ctx) {
  9157. if (!this.width) {
  9158. var margin = 5;
  9159. var textSize = this.getTextSize(ctx);
  9160. var size = textSize.width + 2 * margin;
  9161. this.width = size;
  9162. this.height = size;
  9163. // scaling used for clustering
  9164. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  9165. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  9166. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  9167. this.growthIndicator = this.width - size;
  9168. }
  9169. };
  9170. Node.prototype._drawDatabase = function (ctx) {
  9171. this._resizeDatabase(ctx);
  9172. this.left = this.x - this.width / 2;
  9173. this.top = this.y - this.height / 2;
  9174. var clusterLineWidth = 2.5;
  9175. var selectionLineWidth = 2;
  9176. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  9177. // draw the outer border
  9178. if (this.clusterSize > 1) {
  9179. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  9180. ctx.lineWidth *= this.graphScaleInv;
  9181. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  9182. 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);
  9183. ctx.stroke();
  9184. }
  9185. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  9186. ctx.lineWidth *= this.graphScaleInv;
  9187. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  9188. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  9189. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  9190. ctx.fill();
  9191. ctx.stroke();
  9192. this._label(ctx, this.label, this.x, this.y);
  9193. };
  9194. Node.prototype._resizeCircle = function (ctx) {
  9195. if (!this.width) {
  9196. var margin = 5;
  9197. var textSize = this.getTextSize(ctx);
  9198. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  9199. this.radius = diameter / 2;
  9200. this.width = diameter;
  9201. this.height = diameter;
  9202. // scaling used for clustering
  9203. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  9204. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  9205. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  9206. this.growthIndicator = this.radius - 0.5*diameter;
  9207. }
  9208. };
  9209. Node.prototype._drawCircle = function (ctx) {
  9210. this._resizeCircle(ctx);
  9211. this.left = this.x - this.width / 2;
  9212. this.top = this.y - this.height / 2;
  9213. var clusterLineWidth = 2.5;
  9214. var selectionLineWidth = 2;
  9215. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  9216. // draw the outer border
  9217. if (this.clusterSize > 1) {
  9218. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  9219. ctx.lineWidth *= this.graphScaleInv;
  9220. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  9221. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  9222. ctx.stroke();
  9223. }
  9224. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  9225. ctx.lineWidth *= this.graphScaleInv;
  9226. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  9227. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  9228. ctx.circle(this.x, this.y, this.radius);
  9229. ctx.fill();
  9230. ctx.stroke();
  9231. this._label(ctx, this.label, this.x, this.y);
  9232. };
  9233. Node.prototype._resizeEllipse = function (ctx) {
  9234. if (!this.width) {
  9235. var textSize = this.getTextSize(ctx);
  9236. this.width = textSize.width * 1.5;
  9237. this.height = textSize.height * 2;
  9238. if (this.width < this.height) {
  9239. this.width = this.height;
  9240. }
  9241. var defaultSize = this.width;
  9242. // scaling used for clustering
  9243. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  9244. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  9245. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  9246. this.growthIndicator = this.width - defaultSize;
  9247. }
  9248. };
  9249. Node.prototype._drawEllipse = function (ctx) {
  9250. this._resizeEllipse(ctx);
  9251. this.left = this.x - this.width / 2;
  9252. this.top = this.y - this.height / 2;
  9253. var clusterLineWidth = 2.5;
  9254. var selectionLineWidth = 2;
  9255. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  9256. // draw the outer border
  9257. if (this.clusterSize > 1) {
  9258. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  9259. ctx.lineWidth *= this.graphScaleInv;
  9260. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  9261. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  9262. ctx.stroke();
  9263. }
  9264. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  9265. ctx.lineWidth *= this.graphScaleInv;
  9266. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  9267. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  9268. ctx.ellipse(this.left, this.top, this.width, this.height);
  9269. ctx.fill();
  9270. ctx.stroke();
  9271. this._label(ctx, this.label, this.x, this.y);
  9272. };
  9273. Node.prototype._drawDot = function (ctx) {
  9274. this._drawShape(ctx, 'circle');
  9275. };
  9276. Node.prototype._drawTriangle = function (ctx) {
  9277. this._drawShape(ctx, 'triangle');
  9278. };
  9279. Node.prototype._drawTriangleDown = function (ctx) {
  9280. this._drawShape(ctx, 'triangleDown');
  9281. };
  9282. Node.prototype._drawSquare = function (ctx) {
  9283. this._drawShape(ctx, 'square');
  9284. };
  9285. Node.prototype._drawStar = function (ctx) {
  9286. this._drawShape(ctx, 'star');
  9287. };
  9288. Node.prototype._resizeShape = function (ctx) {
  9289. if (!this.width) {
  9290. this.radius = this.baseRadiusValue;
  9291. var size = 2 * this.radius;
  9292. this.width = size;
  9293. this.height = size;
  9294. // scaling used for clustering
  9295. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  9296. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  9297. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  9298. this.growthIndicator = this.width - size;
  9299. }
  9300. };
  9301. Node.prototype._drawShape = function (ctx, shape) {
  9302. this._resizeShape(ctx);
  9303. this.left = this.x - this.width / 2;
  9304. this.top = this.y - this.height / 2;
  9305. var clusterLineWidth = 2.5;
  9306. var selectionLineWidth = 2;
  9307. var radiusMultiplier = 2;
  9308. // choose draw method depending on the shape
  9309. switch (shape) {
  9310. case 'dot': radiusMultiplier = 2; break;
  9311. case 'square': radiusMultiplier = 2; break;
  9312. case 'triangle': radiusMultiplier = 3; break;
  9313. case 'triangleDown': radiusMultiplier = 3; break;
  9314. case 'star': radiusMultiplier = 4; break;
  9315. }
  9316. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  9317. // draw the outer border
  9318. if (this.clusterSize > 1) {
  9319. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  9320. ctx.lineWidth *= this.graphScaleInv;
  9321. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  9322. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  9323. ctx.stroke();
  9324. }
  9325. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  9326. ctx.lineWidth *= this.graphScaleInv;
  9327. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  9328. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  9329. ctx[shape](this.x, this.y, this.radius);
  9330. ctx.fill();
  9331. ctx.stroke();
  9332. if (this.label) {
  9333. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  9334. }
  9335. };
  9336. Node.prototype._resizeText = function (ctx) {
  9337. if (!this.width) {
  9338. var margin = 5;
  9339. var textSize = this.getTextSize(ctx);
  9340. this.width = textSize.width + 2 * margin;
  9341. this.height = textSize.height + 2 * margin;
  9342. // scaling used for clustering
  9343. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  9344. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  9345. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  9346. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  9347. }
  9348. };
  9349. Node.prototype._drawText = function (ctx) {
  9350. this._resizeText(ctx);
  9351. this.left = this.x - this.width / 2;
  9352. this.top = this.y - this.height / 2;
  9353. this._label(ctx, this.label, this.x, this.y);
  9354. };
  9355. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  9356. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  9357. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9358. ctx.fillStyle = this.fontColor || "black";
  9359. ctx.textAlign = align || "center";
  9360. ctx.textBaseline = baseline || "middle";
  9361. var lines = text.split('\n'),
  9362. lineCount = lines.length,
  9363. fontSize = (this.fontSize + 4),
  9364. yLine = y + (1 - lineCount) / 2 * fontSize;
  9365. for (var i = 0; i < lineCount; i++) {
  9366. ctx.fillText(lines[i], x, yLine);
  9367. yLine += fontSize;
  9368. }
  9369. }
  9370. };
  9371. Node.prototype.getTextSize = function(ctx) {
  9372. if (this.label !== undefined) {
  9373. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9374. var lines = this.label.split('\n'),
  9375. height = (this.fontSize + 4) * lines.length,
  9376. width = 0;
  9377. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  9378. width = Math.max(width, ctx.measureText(lines[i]).width);
  9379. }
  9380. return {"width": width, "height": height};
  9381. }
  9382. else {
  9383. return {"width": 0, "height": 0};
  9384. }
  9385. };
  9386. /**
  9387. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  9388. * there is a safety margin of 0.3 * width;
  9389. *
  9390. * @returns {boolean}
  9391. */
  9392. Node.prototype.inArea = function() {
  9393. if (this.width !== undefined) {
  9394. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  9395. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  9396. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  9397. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  9398. }
  9399. else {
  9400. return true;
  9401. }
  9402. };
  9403. /**
  9404. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  9405. * @returns {boolean}
  9406. */
  9407. Node.prototype.inView = function() {
  9408. return (this.x >= this.canvasTopLeft.x &&
  9409. this.x < this.canvasBottomRight.x &&
  9410. this.y >= this.canvasTopLeft.y &&
  9411. this.y < this.canvasBottomRight.y);
  9412. };
  9413. /**
  9414. * This allows the zoom level of the graph to influence the rendering
  9415. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  9416. *
  9417. * @param scale
  9418. * @param canvasTopLeft
  9419. * @param canvasBottomRight
  9420. */
  9421. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  9422. this.graphScaleInv = 1.0/scale;
  9423. this.graphScale = scale;
  9424. this.canvasTopLeft = canvasTopLeft;
  9425. this.canvasBottomRight = canvasBottomRight;
  9426. };
  9427. /**
  9428. * This allows the zoom level of the graph to influence the rendering
  9429. *
  9430. * @param scale
  9431. */
  9432. Node.prototype.setScale = function(scale) {
  9433. this.graphScaleInv = 1.0/scale;
  9434. this.graphScale = scale;
  9435. };
  9436. /**
  9437. * set the velocity at 0. Is called when this node is contained in another during clustering
  9438. */
  9439. Node.prototype.clearVelocity = function() {
  9440. this.vx = 0;
  9441. this.vy = 0;
  9442. };
  9443. /**
  9444. * Basic preservation of (kinectic) energy
  9445. *
  9446. * @param massBeforeClustering
  9447. */
  9448. Node.prototype.updateVelocity = function(massBeforeClustering) {
  9449. var energyBefore = this.vx * this.vx * massBeforeClustering;
  9450. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9451. this.vx = Math.sqrt(energyBefore/this.mass);
  9452. energyBefore = this.vy * this.vy * massBeforeClustering;
  9453. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9454. this.vy = Math.sqrt(energyBefore/this.mass);
  9455. };
  9456. /**
  9457. * @class Edge
  9458. *
  9459. * A edge connects two nodes
  9460. * @param {Object} properties Object with properties. Must contain
  9461. * At least properties from and to.
  9462. * Available properties: from (number),
  9463. * to (number), label (string, color (string),
  9464. * width (number), style (string),
  9465. * length (number), title (string)
  9466. * @param {Graph} graph A graph object, used to find and edge to
  9467. * nodes.
  9468. * @param {Object} constants An object with default values for
  9469. * example for the color
  9470. */
  9471. function Edge (properties, graph, constants) {
  9472. if (!graph) {
  9473. throw "No graph provided";
  9474. }
  9475. this.graph = graph;
  9476. // initialize constants
  9477. this.widthMin = constants.edges.widthMin;
  9478. this.widthMax = constants.edges.widthMax;
  9479. // initialize variables
  9480. this.id = undefined;
  9481. this.fromId = undefined;
  9482. this.toId = undefined;
  9483. this.style = constants.edges.style;
  9484. this.title = undefined;
  9485. this.width = constants.edges.width;
  9486. this.value = undefined;
  9487. this.length = constants.physics.springLength;
  9488. this.customLength = false;
  9489. this.selected = false;
  9490. this.smooth = constants.smoothCurves;
  9491. this.arrowScaleFactor = constants.edges.arrowScaleFactor;
  9492. this.from = null; // a node
  9493. this.to = null; // a node
  9494. this.via = null; // a temp node
  9495. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  9496. // by storing the original information we can revert to the original connection when the cluser is opened.
  9497. this.originalFromId = [];
  9498. this.originalToId = [];
  9499. this.connected = false;
  9500. // Added to support dashed lines
  9501. // David Jordan
  9502. // 2012-08-08
  9503. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  9504. this.color = {color:constants.edges.color.color,
  9505. highlight:constants.edges.color.highlight};
  9506. this.widthFixed = false;
  9507. this.lengthFixed = false;
  9508. this.setProperties(properties, constants);
  9509. }
  9510. /**
  9511. * Set or overwrite properties for the edge
  9512. * @param {Object} properties an object with properties
  9513. * @param {Object} constants and object with default, global properties
  9514. */
  9515. Edge.prototype.setProperties = function(properties, constants) {
  9516. if (!properties) {
  9517. return;
  9518. }
  9519. if (properties.from !== undefined) {this.fromId = properties.from;}
  9520. if (properties.to !== undefined) {this.toId = properties.to;}
  9521. if (properties.id !== undefined) {this.id = properties.id;}
  9522. if (properties.style !== undefined) {this.style = properties.style;}
  9523. if (properties.label !== undefined) {this.label = properties.label;}
  9524. if (this.label) {
  9525. this.fontSize = constants.edges.fontSize;
  9526. this.fontFace = constants.edges.fontFace;
  9527. this.fontColor = constants.edges.fontColor;
  9528. this.fontFill = constants.edges.fontFill;
  9529. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  9530. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  9531. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  9532. if (properties.fontFill !== undefined) {this.fontFill = properties.fontFill;}
  9533. }
  9534. if (properties.title !== undefined) {this.title = properties.title;}
  9535. if (properties.width !== undefined) {this.width = properties.width;}
  9536. if (properties.value !== undefined) {this.value = properties.value;}
  9537. if (properties.length !== undefined) {this.length = properties.length;
  9538. this.customLength = true;}
  9539. // scale the arrow
  9540. if (properties.arrowScaleFactor !== undefined) {this.arrowScaleFactor = properties.arrowScaleFactor;}
  9541. // Added to support dashed lines
  9542. // David Jordan
  9543. // 2012-08-08
  9544. if (properties.dash) {
  9545. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  9546. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  9547. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  9548. }
  9549. if (properties.color !== undefined) {
  9550. if (util.isString(properties.color)) {
  9551. this.color.color = properties.color;
  9552. this.color.highlight = properties.color;
  9553. }
  9554. else {
  9555. if (properties.color.color !== undefined) {this.color.color = properties.color.color;}
  9556. if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;}
  9557. }
  9558. }
  9559. // A node is connected when it has a from and to node.
  9560. this.connect();
  9561. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  9562. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  9563. // set draw method based on style
  9564. switch (this.style) {
  9565. case 'line': this.draw = this._drawLine; break;
  9566. case 'arrow': this.draw = this._drawArrow; break;
  9567. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  9568. case 'dash-line': this.draw = this._drawDashLine; break;
  9569. default: this.draw = this._drawLine; break;
  9570. }
  9571. };
  9572. /**
  9573. * Connect an edge to its nodes
  9574. */
  9575. Edge.prototype.connect = function () {
  9576. this.disconnect();
  9577. this.from = this.graph.nodes[this.fromId] || null;
  9578. this.to = this.graph.nodes[this.toId] || null;
  9579. this.connected = (this.from && this.to);
  9580. if (this.connected) {
  9581. this.from.attachEdge(this);
  9582. this.to.attachEdge(this);
  9583. }
  9584. else {
  9585. if (this.from) {
  9586. this.from.detachEdge(this);
  9587. }
  9588. if (this.to) {
  9589. this.to.detachEdge(this);
  9590. }
  9591. }
  9592. };
  9593. /**
  9594. * Disconnect an edge from its nodes
  9595. */
  9596. Edge.prototype.disconnect = function () {
  9597. if (this.from) {
  9598. this.from.detachEdge(this);
  9599. this.from = null;
  9600. }
  9601. if (this.to) {
  9602. this.to.detachEdge(this);
  9603. this.to = null;
  9604. }
  9605. this.connected = false;
  9606. };
  9607. /**
  9608. * get the title of this edge.
  9609. * @return {string} title The title of the edge, or undefined when no title
  9610. * has been set.
  9611. */
  9612. Edge.prototype.getTitle = function() {
  9613. return typeof this.title === "function" ? this.title() : this.title;
  9614. };
  9615. /**
  9616. * Retrieve the value of the edge. Can be undefined
  9617. * @return {Number} value
  9618. */
  9619. Edge.prototype.getValue = function() {
  9620. return this.value;
  9621. };
  9622. /**
  9623. * Adjust the value range of the edge. The edge will adjust it's width
  9624. * based on its value.
  9625. * @param {Number} min
  9626. * @param {Number} max
  9627. */
  9628. Edge.prototype.setValueRange = function(min, max) {
  9629. if (!this.widthFixed && this.value !== undefined) {
  9630. var scale = (this.widthMax - this.widthMin) / (max - min);
  9631. this.width = (this.value - min) * scale + this.widthMin;
  9632. }
  9633. };
  9634. /**
  9635. * Redraw a edge
  9636. * Draw this edge in the given canvas
  9637. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9638. * @param {CanvasRenderingContext2D} ctx
  9639. */
  9640. Edge.prototype.draw = function(ctx) {
  9641. throw "Method draw not initialized in edge";
  9642. };
  9643. /**
  9644. * Check if this object is overlapping with the provided object
  9645. * @param {Object} obj an object with parameters left, top
  9646. * @return {boolean} True if location is located on the edge
  9647. */
  9648. Edge.prototype.isOverlappingWith = function(obj) {
  9649. if (this.connected) {
  9650. var distMax = 10;
  9651. var xFrom = this.from.x;
  9652. var yFrom = this.from.y;
  9653. var xTo = this.to.x;
  9654. var yTo = this.to.y;
  9655. var xObj = obj.left;
  9656. var yObj = obj.top;
  9657. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  9658. return (dist < distMax);
  9659. }
  9660. else {
  9661. return false
  9662. }
  9663. };
  9664. /**
  9665. * Redraw a edge as a line
  9666. * Draw this edge in the given canvas
  9667. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9668. * @param {CanvasRenderingContext2D} ctx
  9669. * @private
  9670. */
  9671. Edge.prototype._drawLine = function(ctx) {
  9672. // set style
  9673. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9674. else {ctx.strokeStyle = this.color.color;}
  9675. ctx.lineWidth = this._getLineWidth();
  9676. if (this.from != this.to) {
  9677. // draw line
  9678. this._line(ctx);
  9679. // draw label
  9680. var point;
  9681. if (this.label) {
  9682. if (this.smooth == true) {
  9683. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9684. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9685. point = {x:midpointX, y:midpointY};
  9686. }
  9687. else {
  9688. point = this._pointOnLine(0.5);
  9689. }
  9690. this._label(ctx, this.label, point.x, point.y);
  9691. }
  9692. }
  9693. else {
  9694. var x, y;
  9695. var radius = this.length / 4;
  9696. var node = this.from;
  9697. if (!node.width) {
  9698. node.resize(ctx);
  9699. }
  9700. if (node.width > node.height) {
  9701. x = node.x + node.width / 2;
  9702. y = node.y - radius;
  9703. }
  9704. else {
  9705. x = node.x + radius;
  9706. y = node.y - node.height / 2;
  9707. }
  9708. this._circle(ctx, x, y, radius);
  9709. point = this._pointOnCircle(x, y, radius, 0.5);
  9710. this._label(ctx, this.label, point.x, point.y);
  9711. }
  9712. };
  9713. /**
  9714. * Get the line width of the edge. Depends on width and whether one of the
  9715. * connected nodes is selected.
  9716. * @return {Number} width
  9717. * @private
  9718. */
  9719. Edge.prototype._getLineWidth = function() {
  9720. if (this.selected == true) {
  9721. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  9722. }
  9723. else {
  9724. return this.width*this.graphScaleInv;
  9725. }
  9726. };
  9727. /**
  9728. * Draw a line between two nodes
  9729. * @param {CanvasRenderingContext2D} ctx
  9730. * @private
  9731. */
  9732. Edge.prototype._line = function (ctx) {
  9733. // draw a straight line
  9734. ctx.beginPath();
  9735. ctx.moveTo(this.from.x, this.from.y);
  9736. if (this.smooth == true) {
  9737. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9738. }
  9739. else {
  9740. ctx.lineTo(this.to.x, this.to.y);
  9741. }
  9742. ctx.stroke();
  9743. };
  9744. /**
  9745. * Draw a line from a node to itself, a circle
  9746. * @param {CanvasRenderingContext2D} ctx
  9747. * @param {Number} x
  9748. * @param {Number} y
  9749. * @param {Number} radius
  9750. * @private
  9751. */
  9752. Edge.prototype._circle = function (ctx, x, y, radius) {
  9753. // draw a circle
  9754. ctx.beginPath();
  9755. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9756. ctx.stroke();
  9757. };
  9758. /**
  9759. * Draw label with white background and with the middle at (x, y)
  9760. * @param {CanvasRenderingContext2D} ctx
  9761. * @param {String} text
  9762. * @param {Number} x
  9763. * @param {Number} y
  9764. * @private
  9765. */
  9766. Edge.prototype._label = function (ctx, text, x, y) {
  9767. if (text) {
  9768. // TODO: cache the calculated size
  9769. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  9770. this.fontSize + "px " + this.fontFace;
  9771. ctx.fillStyle = this.fontFill;
  9772. var width = ctx.measureText(text).width;
  9773. var height = this.fontSize;
  9774. var left = x - width / 2;
  9775. var top = y - height / 2;
  9776. ctx.fillRect(left, top, width, height);
  9777. // draw text
  9778. ctx.fillStyle = this.fontColor || "black";
  9779. ctx.textAlign = "left";
  9780. ctx.textBaseline = "top";
  9781. ctx.fillText(text, left, top);
  9782. }
  9783. };
  9784. /**
  9785. * Redraw a edge as a dashed line
  9786. * Draw this edge in the given canvas
  9787. * @author David Jordan
  9788. * @date 2012-08-08
  9789. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9790. * @param {CanvasRenderingContext2D} ctx
  9791. * @private
  9792. */
  9793. Edge.prototype._drawDashLine = function(ctx) {
  9794. // set style
  9795. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9796. else {ctx.strokeStyle = this.color.color;}
  9797. ctx.lineWidth = this._getLineWidth();
  9798. // only firefox and chrome support this method, else we use the legacy one.
  9799. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  9800. ctx.beginPath();
  9801. ctx.moveTo(this.from.x, this.from.y);
  9802. // configure the dash pattern
  9803. var pattern = [0];
  9804. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  9805. pattern = [this.dash.length,this.dash.gap];
  9806. }
  9807. else {
  9808. pattern = [5,5];
  9809. }
  9810. // set dash settings for chrome or firefox
  9811. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9812. ctx.setLineDash(pattern);
  9813. ctx.lineDashOffset = 0;
  9814. } else { //Firefox
  9815. ctx.mozDash = pattern;
  9816. ctx.mozDashOffset = 0;
  9817. }
  9818. // draw the line
  9819. if (this.smooth == true) {
  9820. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9821. }
  9822. else {
  9823. ctx.lineTo(this.to.x, this.to.y);
  9824. }
  9825. ctx.stroke();
  9826. // restore the dash settings.
  9827. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9828. ctx.setLineDash([0]);
  9829. ctx.lineDashOffset = 0;
  9830. } else { //Firefox
  9831. ctx.mozDash = [0];
  9832. ctx.mozDashOffset = 0;
  9833. }
  9834. }
  9835. else { // unsupporting smooth lines
  9836. // draw dashed line
  9837. ctx.beginPath();
  9838. ctx.lineCap = 'round';
  9839. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9840. {
  9841. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9842. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9843. }
  9844. 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
  9845. {
  9846. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9847. [this.dash.length,this.dash.gap]);
  9848. }
  9849. else //If all else fails draw a line
  9850. {
  9851. ctx.moveTo(this.from.x, this.from.y);
  9852. ctx.lineTo(this.to.x, this.to.y);
  9853. }
  9854. ctx.stroke();
  9855. }
  9856. // draw label
  9857. if (this.label) {
  9858. var point;
  9859. if (this.smooth == true) {
  9860. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9861. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9862. point = {x:midpointX, y:midpointY};
  9863. }
  9864. else {
  9865. point = this._pointOnLine(0.5);
  9866. }
  9867. this._label(ctx, this.label, point.x, point.y);
  9868. }
  9869. };
  9870. /**
  9871. * Get a point on a line
  9872. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9873. * @return {Object} point
  9874. * @private
  9875. */
  9876. Edge.prototype._pointOnLine = function (percentage) {
  9877. return {
  9878. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9879. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9880. }
  9881. };
  9882. /**
  9883. * Get a point on a circle
  9884. * @param {Number} x
  9885. * @param {Number} y
  9886. * @param {Number} radius
  9887. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9888. * @return {Object} point
  9889. * @private
  9890. */
  9891. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9892. var angle = (percentage - 3/8) * 2 * Math.PI;
  9893. return {
  9894. x: x + radius * Math.cos(angle),
  9895. y: y - radius * Math.sin(angle)
  9896. }
  9897. };
  9898. /**
  9899. * Redraw a edge as a line with an arrow halfway the line
  9900. * Draw this edge in the given canvas
  9901. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9902. * @param {CanvasRenderingContext2D} ctx
  9903. * @private
  9904. */
  9905. Edge.prototype._drawArrowCenter = function(ctx) {
  9906. var point;
  9907. // set style
  9908. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9909. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9910. ctx.lineWidth = this._getLineWidth();
  9911. if (this.from != this.to) {
  9912. // draw line
  9913. this._line(ctx);
  9914. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9915. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9916. // draw an arrow halfway the line
  9917. if (this.smooth == true) {
  9918. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9919. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9920. point = {x:midpointX, y:midpointY};
  9921. }
  9922. else {
  9923. point = this._pointOnLine(0.5);
  9924. }
  9925. ctx.arrow(point.x, point.y, angle, length);
  9926. ctx.fill();
  9927. ctx.stroke();
  9928. // draw label
  9929. if (this.label) {
  9930. this._label(ctx, this.label, point.x, point.y);
  9931. }
  9932. }
  9933. else {
  9934. // draw circle
  9935. var x, y;
  9936. var radius = 0.25 * Math.max(100,this.length);
  9937. var node = this.from;
  9938. if (!node.width) {
  9939. node.resize(ctx);
  9940. }
  9941. if (node.width > node.height) {
  9942. x = node.x + node.width * 0.5;
  9943. y = node.y - radius;
  9944. }
  9945. else {
  9946. x = node.x + radius;
  9947. y = node.y - node.height * 0.5;
  9948. }
  9949. this._circle(ctx, x, y, radius);
  9950. // draw all arrows
  9951. var angle = 0.2 * Math.PI;
  9952. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9953. point = this._pointOnCircle(x, y, radius, 0.5);
  9954. ctx.arrow(point.x, point.y, angle, length);
  9955. ctx.fill();
  9956. ctx.stroke();
  9957. // draw label
  9958. if (this.label) {
  9959. point = this._pointOnCircle(x, y, radius, 0.5);
  9960. this._label(ctx, this.label, point.x, point.y);
  9961. }
  9962. }
  9963. };
  9964. /**
  9965. * Redraw a edge as a line with an arrow
  9966. * Draw this edge in the given canvas
  9967. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9968. * @param {CanvasRenderingContext2D} ctx
  9969. * @private
  9970. */
  9971. Edge.prototype._drawArrow = function(ctx) {
  9972. // set style
  9973. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9974. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9975. ctx.lineWidth = this._getLineWidth();
  9976. var angle, length;
  9977. //draw a line
  9978. if (this.from != this.to) {
  9979. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9980. var dx = (this.to.x - this.from.x);
  9981. var dy = (this.to.y - this.from.y);
  9982. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9983. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9984. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9985. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9986. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9987. if (this.smooth == true) {
  9988. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9989. dx = (this.to.x - this.via.x);
  9990. dy = (this.to.y - this.via.y);
  9991. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9992. }
  9993. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9994. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9995. var xTo,yTo;
  9996. if (this.smooth == true) {
  9997. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9998. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9999. }
  10000. else {
  10001. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  10002. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  10003. }
  10004. ctx.beginPath();
  10005. ctx.moveTo(xFrom,yFrom);
  10006. if (this.smooth == true) {
  10007. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  10008. }
  10009. else {
  10010. ctx.lineTo(xTo, yTo);
  10011. }
  10012. ctx.stroke();
  10013. // draw arrow at the end of the line
  10014. length = (10 + 5 * this.width) * this.arrowScaleFactor;
  10015. ctx.arrow(xTo, yTo, angle, length);
  10016. ctx.fill();
  10017. ctx.stroke();
  10018. // draw label
  10019. if (this.label) {
  10020. var point;
  10021. if (this.smooth == true) {
  10022. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  10023. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  10024. point = {x:midpointX, y:midpointY};
  10025. }
  10026. else {
  10027. point = this._pointOnLine(0.5);
  10028. }
  10029. this._label(ctx, this.label, point.x, point.y);
  10030. }
  10031. }
  10032. else {
  10033. // draw circle
  10034. var node = this.from;
  10035. var x, y, arrow;
  10036. var radius = 0.25 * Math.max(100,this.length);
  10037. if (!node.width) {
  10038. node.resize(ctx);
  10039. }
  10040. if (node.width > node.height) {
  10041. x = node.x + node.width * 0.5;
  10042. y = node.y - radius;
  10043. arrow = {
  10044. x: x,
  10045. y: node.y,
  10046. angle: 0.9 * Math.PI
  10047. };
  10048. }
  10049. else {
  10050. x = node.x + radius;
  10051. y = node.y - node.height * 0.5;
  10052. arrow = {
  10053. x: node.x,
  10054. y: y,
  10055. angle: 0.6 * Math.PI
  10056. };
  10057. }
  10058. ctx.beginPath();
  10059. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  10060. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  10061. ctx.stroke();
  10062. // draw all arrows
  10063. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  10064. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  10065. ctx.fill();
  10066. ctx.stroke();
  10067. // draw label
  10068. if (this.label) {
  10069. point = this._pointOnCircle(x, y, radius, 0.5);
  10070. this._label(ctx, this.label, point.x, point.y);
  10071. }
  10072. }
  10073. };
  10074. /**
  10075. * Calculate the distance between a point (x3,y3) and a line segment from
  10076. * (x1,y1) to (x2,y2).
  10077. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  10078. * @param {number} x1
  10079. * @param {number} y1
  10080. * @param {number} x2
  10081. * @param {number} y2
  10082. * @param {number} x3
  10083. * @param {number} y3
  10084. * @private
  10085. */
  10086. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  10087. if (this.smooth == true) {
  10088. var minDistance = 1e9;
  10089. var i,t,x,y,dx,dy;
  10090. for (i = 0; i < 10; i++) {
  10091. t = 0.1*i;
  10092. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  10093. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  10094. dx = Math.abs(x3-x);
  10095. dy = Math.abs(y3-y);
  10096. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  10097. }
  10098. return minDistance
  10099. }
  10100. else {
  10101. var px = x2-x1,
  10102. py = y2-y1,
  10103. something = px*px + py*py,
  10104. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  10105. if (u > 1) {
  10106. u = 1;
  10107. }
  10108. else if (u < 0) {
  10109. u = 0;
  10110. }
  10111. var x = x1 + u * px,
  10112. y = y1 + u * py,
  10113. dx = x - x3,
  10114. dy = y - y3;
  10115. //# Note: If the actual distance does not matter,
  10116. //# if you only want to compare what this function
  10117. //# returns to other results of this function, you
  10118. //# can just return the squared distance instead
  10119. //# (i.e. remove the sqrt) to gain a little performance
  10120. return Math.sqrt(dx*dx + dy*dy);
  10121. }
  10122. };
  10123. /**
  10124. * This allows the zoom level of the graph to influence the rendering
  10125. *
  10126. * @param scale
  10127. */
  10128. Edge.prototype.setScale = function(scale) {
  10129. this.graphScaleInv = 1.0/scale;
  10130. };
  10131. Edge.prototype.select = function() {
  10132. this.selected = true;
  10133. };
  10134. Edge.prototype.unselect = function() {
  10135. this.selected = false;
  10136. };
  10137. Edge.prototype.positionBezierNode = function() {
  10138. if (this.via !== null) {
  10139. this.via.x = 0.5 * (this.from.x + this.to.x);
  10140. this.via.y = 0.5 * (this.from.y + this.to.y);
  10141. }
  10142. };
  10143. /**
  10144. * Popup is a class to create a popup window with some text
  10145. * @param {Element} container The container object.
  10146. * @param {Number} [x]
  10147. * @param {Number} [y]
  10148. * @param {String} [text]
  10149. * @param {Object} [style] An object containing borderColor,
  10150. * backgroundColor, etc.
  10151. */
  10152. function Popup(container, x, y, text, style) {
  10153. if (container) {
  10154. this.container = container;
  10155. }
  10156. else {
  10157. this.container = document.body;
  10158. }
  10159. // x, y and text are optional, see if a style object was passed in their place
  10160. if (style === undefined) {
  10161. if (typeof x === "object") {
  10162. style = x;
  10163. x = undefined;
  10164. } else if (typeof text === "object") {
  10165. style = text;
  10166. text = undefined;
  10167. } else {
  10168. // for backwards compatibility, in case clients other than Graph are creating Popup directly
  10169. style = {
  10170. fontColor: 'black',
  10171. fontSize: 14, // px
  10172. fontFace: 'verdana',
  10173. color: {
  10174. border: '#666',
  10175. background: '#FFFFC6'
  10176. }
  10177. }
  10178. }
  10179. }
  10180. this.x = 0;
  10181. this.y = 0;
  10182. this.padding = 5;
  10183. if (x !== undefined && y !== undefined ) {
  10184. this.setPosition(x, y);
  10185. }
  10186. if (text !== undefined) {
  10187. this.setText(text);
  10188. }
  10189. // create the frame
  10190. this.frame = document.createElement("div");
  10191. var styleAttr = this.frame.style;
  10192. styleAttr.position = "absolute";
  10193. styleAttr.visibility = "hidden";
  10194. styleAttr.border = "1px solid " + style.color.border;
  10195. styleAttr.color = style.fontColor;
  10196. styleAttr.fontSize = style.fontSize + "px";
  10197. styleAttr.fontFamily = style.fontFace;
  10198. styleAttr.padding = this.padding + "px";
  10199. styleAttr.backgroundColor = style.color.background;
  10200. styleAttr.borderRadius = "3px";
  10201. styleAttr.MozBorderRadius = "3px";
  10202. styleAttr.WebkitBorderRadius = "3px";
  10203. styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  10204. styleAttr.whiteSpace = "nowrap";
  10205. this.container.appendChild(this.frame);
  10206. }
  10207. /**
  10208. * @param {number} x Horizontal position of the popup window
  10209. * @param {number} y Vertical position of the popup window
  10210. */
  10211. Popup.prototype.setPosition = function(x, y) {
  10212. this.x = parseInt(x);
  10213. this.y = parseInt(y);
  10214. };
  10215. /**
  10216. * Set the text for the popup window. This can be HTML code
  10217. * @param {string} text
  10218. */
  10219. Popup.prototype.setText = function(text) {
  10220. this.frame.innerHTML = text;
  10221. };
  10222. /**
  10223. * Show the popup window
  10224. * @param {boolean} show Optional. Show or hide the window
  10225. */
  10226. Popup.prototype.show = function (show) {
  10227. if (show === undefined) {
  10228. show = true;
  10229. }
  10230. if (show) {
  10231. var height = this.frame.clientHeight;
  10232. var width = this.frame.clientWidth;
  10233. var maxHeight = this.frame.parentNode.clientHeight;
  10234. var maxWidth = this.frame.parentNode.clientWidth;
  10235. var top = (this.y - height);
  10236. if (top + height + this.padding > maxHeight) {
  10237. top = maxHeight - height - this.padding;
  10238. }
  10239. if (top < this.padding) {
  10240. top = this.padding;
  10241. }
  10242. var left = this.x;
  10243. if (left + width + this.padding > maxWidth) {
  10244. left = maxWidth - width - this.padding;
  10245. }
  10246. if (left < this.padding) {
  10247. left = this.padding;
  10248. }
  10249. this.frame.style.left = left + "px";
  10250. this.frame.style.top = top + "px";
  10251. this.frame.style.visibility = "visible";
  10252. }
  10253. else {
  10254. this.hide();
  10255. }
  10256. };
  10257. /**
  10258. * Hide the popup window
  10259. */
  10260. Popup.prototype.hide = function () {
  10261. this.frame.style.visibility = "hidden";
  10262. };
  10263. /**
  10264. * @class Groups
  10265. * This class can store groups and properties specific for groups.
  10266. */
  10267. function Groups() {
  10268. this.clear();
  10269. this.defaultIndex = 0;
  10270. }
  10271. /**
  10272. * default constants for group colors
  10273. */
  10274. Groups.DEFAULT = [
  10275. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  10276. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  10277. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  10278. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  10279. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  10280. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  10281. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  10282. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  10283. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  10284. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  10285. ];
  10286. /**
  10287. * Clear all groups
  10288. */
  10289. Groups.prototype.clear = function () {
  10290. this.groups = {};
  10291. this.groups.length = function()
  10292. {
  10293. var i = 0;
  10294. for ( var p in this ) {
  10295. if (this.hasOwnProperty(p)) {
  10296. i++;
  10297. }
  10298. }
  10299. return i;
  10300. }
  10301. };
  10302. /**
  10303. * get group properties of a groupname. If groupname is not found, a new group
  10304. * is added.
  10305. * @param {*} groupname Can be a number, string, Date, etc.
  10306. * @return {Object} group The created group, containing all group properties
  10307. */
  10308. Groups.prototype.get = function (groupname) {
  10309. var group = this.groups[groupname];
  10310. if (group == undefined) {
  10311. // create new group
  10312. var index = this.defaultIndex % Groups.DEFAULT.length;
  10313. this.defaultIndex++;
  10314. group = {};
  10315. group.color = Groups.DEFAULT[index];
  10316. this.groups[groupname] = group;
  10317. }
  10318. return group;
  10319. };
  10320. /**
  10321. * Add a custom group style
  10322. * @param {String} groupname
  10323. * @param {Object} style An object containing borderColor,
  10324. * backgroundColor, etc.
  10325. * @return {Object} group The created group object
  10326. */
  10327. Groups.prototype.add = function (groupname, style) {
  10328. this.groups[groupname] = style;
  10329. if (style.color) {
  10330. style.color = util.parseColor(style.color);
  10331. }
  10332. return style;
  10333. };
  10334. /**
  10335. * @class Images
  10336. * This class loads images and keeps them stored.
  10337. */
  10338. function Images() {
  10339. this.images = {};
  10340. this.callback = undefined;
  10341. }
  10342. /**
  10343. * Set an onload callback function. This will be called each time an image
  10344. * is loaded
  10345. * @param {function} callback
  10346. */
  10347. Images.prototype.setOnloadCallback = function(callback) {
  10348. this.callback = callback;
  10349. };
  10350. /**
  10351. *
  10352. * @param {string} url Url of the image
  10353. * @return {Image} img The image object
  10354. */
  10355. Images.prototype.load = function(url) {
  10356. var img = this.images[url];
  10357. if (img == undefined) {
  10358. // create the image
  10359. var images = this;
  10360. img = new Image();
  10361. this.images[url] = img;
  10362. img.onload = function() {
  10363. if (images.callback) {
  10364. images.callback(this);
  10365. }
  10366. };
  10367. img.src = url;
  10368. }
  10369. return img;
  10370. };
  10371. /**
  10372. * Created by Alex on 2/6/14.
  10373. */
  10374. var physicsMixin = {
  10375. /**
  10376. * Toggling barnes Hut calculation on and off.
  10377. *
  10378. * @private
  10379. */
  10380. _toggleBarnesHut: function () {
  10381. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  10382. this._loadSelectedForceSolver();
  10383. this.moving = true;
  10384. this.start();
  10385. },
  10386. /**
  10387. * This loads the node force solver based on the barnes hut or repulsion algorithm
  10388. *
  10389. * @private
  10390. */
  10391. _loadSelectedForceSolver: function () {
  10392. // this overloads the this._calculateNodeForces
  10393. if (this.constants.physics.barnesHut.enabled == true) {
  10394. this._clearMixin(repulsionMixin);
  10395. this._clearMixin(hierarchalRepulsionMixin);
  10396. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  10397. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  10398. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  10399. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  10400. this._loadMixin(barnesHutMixin);
  10401. }
  10402. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  10403. this._clearMixin(barnesHutMixin);
  10404. this._clearMixin(repulsionMixin);
  10405. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  10406. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  10407. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  10408. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  10409. this._loadMixin(hierarchalRepulsionMixin);
  10410. }
  10411. else {
  10412. this._clearMixin(barnesHutMixin);
  10413. this._clearMixin(hierarchalRepulsionMixin);
  10414. this.barnesHutTree = undefined;
  10415. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  10416. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  10417. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  10418. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  10419. this._loadMixin(repulsionMixin);
  10420. }
  10421. },
  10422. /**
  10423. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  10424. * if there is more than one node. If it is just one node, we dont calculate anything.
  10425. *
  10426. * @private
  10427. */
  10428. _initializeForceCalculation: function () {
  10429. // stop calculation if there is only one node
  10430. if (this.nodeIndices.length == 1) {
  10431. this.nodes[this.nodeIndices[0]]._setForce(0, 0);
  10432. }
  10433. else {
  10434. // if there are too many nodes on screen, we cluster without repositioning
  10435. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  10436. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  10437. }
  10438. // we now start the force calculation
  10439. this._calculateForces();
  10440. }
  10441. },
  10442. /**
  10443. * Calculate the external forces acting on the nodes
  10444. * Forces are caused by: edges, repulsing forces between nodes, gravity
  10445. * @private
  10446. */
  10447. _calculateForces: function () {
  10448. // Gravity is required to keep separated groups from floating off
  10449. // the forces are reset to zero in this loop by using _setForce instead
  10450. // of _addForce
  10451. this._calculateGravitationalForces();
  10452. this._calculateNodeForces();
  10453. if (this.constants.smoothCurves == true) {
  10454. this._calculateSpringForcesWithSupport();
  10455. }
  10456. else {
  10457. this._calculateSpringForces();
  10458. }
  10459. },
  10460. /**
  10461. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  10462. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  10463. * This function joins the datanodes and invisible (called support) nodes into one object.
  10464. * We do this so we do not contaminate this.nodes with the support nodes.
  10465. *
  10466. * @private
  10467. */
  10468. _updateCalculationNodes: function () {
  10469. if (this.constants.smoothCurves == true) {
  10470. this.calculationNodes = {};
  10471. this.calculationNodeIndices = [];
  10472. for (var nodeId in this.nodes) {
  10473. if (this.nodes.hasOwnProperty(nodeId)) {
  10474. this.calculationNodes[nodeId] = this.nodes[nodeId];
  10475. }
  10476. }
  10477. var supportNodes = this.sectors['support']['nodes'];
  10478. for (var supportNodeId in supportNodes) {
  10479. if (supportNodes.hasOwnProperty(supportNodeId)) {
  10480. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  10481. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  10482. }
  10483. else {
  10484. supportNodes[supportNodeId]._setForce(0, 0);
  10485. }
  10486. }
  10487. }
  10488. for (var idx in this.calculationNodes) {
  10489. if (this.calculationNodes.hasOwnProperty(idx)) {
  10490. this.calculationNodeIndices.push(idx);
  10491. }
  10492. }
  10493. }
  10494. else {
  10495. this.calculationNodes = this.nodes;
  10496. this.calculationNodeIndices = this.nodeIndices;
  10497. }
  10498. },
  10499. /**
  10500. * this function applies the central gravity effect to keep groups from floating off
  10501. *
  10502. * @private
  10503. */
  10504. _calculateGravitationalForces: function () {
  10505. var dx, dy, distance, node, i;
  10506. var nodes = this.calculationNodes;
  10507. var gravity = this.constants.physics.centralGravity;
  10508. var gravityForce = 0;
  10509. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  10510. node = nodes[this.calculationNodeIndices[i]];
  10511. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  10512. // gravity does not apply when we are in a pocket sector
  10513. if (this._sector() == "default" && gravity != 0) {
  10514. dx = -node.x;
  10515. dy = -node.y;
  10516. distance = Math.sqrt(dx * dx + dy * dy);
  10517. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  10518. node.fx = dx * gravityForce;
  10519. node.fy = dy * gravityForce;
  10520. }
  10521. else {
  10522. node.fx = 0;
  10523. node.fy = 0;
  10524. }
  10525. }
  10526. },
  10527. /**
  10528. * this function calculates the effects of the springs in the case of unsmooth curves.
  10529. *
  10530. * @private
  10531. */
  10532. _calculateSpringForces: function () {
  10533. var edgeLength, edge, edgeId;
  10534. var dx, dy, fx, fy, springForce, distance;
  10535. var edges = this.edges;
  10536. // forces caused by the edges, modelled as springs
  10537. for (edgeId in edges) {
  10538. if (edges.hasOwnProperty(edgeId)) {
  10539. edge = edges[edgeId];
  10540. if (edge.connected) {
  10541. // only calculate forces if nodes are in the same sector
  10542. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10543. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  10544. // this implies that the edges between big clusters are longer
  10545. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  10546. dx = (edge.from.x - edge.to.x);
  10547. dy = (edge.from.y - edge.to.y);
  10548. distance = Math.sqrt(dx * dx + dy * dy);
  10549. if (distance == 0) {
  10550. distance = 0.01;
  10551. }
  10552. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  10553. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  10554. fx = dx * springForce;
  10555. fy = dy * springForce;
  10556. edge.from.fx += fx;
  10557. edge.from.fy += fy;
  10558. edge.to.fx -= fx;
  10559. edge.to.fy -= fy;
  10560. }
  10561. }
  10562. }
  10563. }
  10564. },
  10565. /**
  10566. * This function calculates the springforces on the nodes, accounting for the support nodes.
  10567. *
  10568. * @private
  10569. */
  10570. _calculateSpringForcesWithSupport: function () {
  10571. var edgeLength, edge, edgeId, combinedClusterSize;
  10572. var edges = this.edges;
  10573. // forces caused by the edges, modelled as springs
  10574. for (edgeId in edges) {
  10575. if (edges.hasOwnProperty(edgeId)) {
  10576. edge = edges[edgeId];
  10577. if (edge.connected) {
  10578. // only calculate forces if nodes are in the same sector
  10579. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10580. if (edge.via != null) {
  10581. var node1 = edge.to;
  10582. var node2 = edge.via;
  10583. var node3 = edge.from;
  10584. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  10585. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  10586. // this implies that the edges between big clusters are longer
  10587. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  10588. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  10589. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  10590. }
  10591. }
  10592. }
  10593. }
  10594. }
  10595. },
  10596. /**
  10597. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  10598. *
  10599. * @param node1
  10600. * @param node2
  10601. * @param edgeLength
  10602. * @private
  10603. */
  10604. _calculateSpringForce: function (node1, node2, edgeLength) {
  10605. var dx, dy, fx, fy, springForce, distance;
  10606. dx = (node1.x - node2.x);
  10607. dy = (node1.y - node2.y);
  10608. distance = Math.sqrt(dx * dx + dy * dy);
  10609. if (distance == 0) {
  10610. distance = 0.01;
  10611. }
  10612. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  10613. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
  10614. fx = dx * springForce;
  10615. fy = dy * springForce;
  10616. node1.fx += fx;
  10617. node1.fy += fy;
  10618. node2.fx -= fx;
  10619. node2.fy -= fy;
  10620. },
  10621. /**
  10622. * Load the HTML for the physics config and bind it
  10623. * @private
  10624. */
  10625. _loadPhysicsConfiguration: function () {
  10626. if (this.physicsConfiguration === undefined) {
  10627. this.backupConstants = {};
  10628. util.copyObject(this.constants, this.backupConstants);
  10629. var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"];
  10630. this.physicsConfiguration = document.createElement('div');
  10631. this.physicsConfiguration.className = "PhysicsConfiguration";
  10632. this.physicsConfiguration.innerHTML = '' +
  10633. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  10634. '<tr>' +
  10635. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  10636. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' +
  10637. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  10638. '</tr>' +
  10639. '</table>' +
  10640. '<table id="graph_BH_table" style="display:none">' +
  10641. '<tr><td><b>Barnes Hut</b></td></tr>' +
  10642. '<tr>' +
  10643. '<td width="150px">gravitationalConstant</td><td>0</td><td><input type="range" min="0" max="20000" value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" step="25" style="width:300px" id="graph_BH_gc"></td><td width="50px">-20000</td><td><input value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" id="graph_BH_gc_value" style="width:60px"></td>' +
  10644. '</tr>' +
  10645. '<tr>' +
  10646. '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.barnesHut.centralGravity + '" step="0.05" style="width:300px" id="graph_BH_cg"></td><td>3</td><td><input value="' + this.constants.physics.barnesHut.centralGravity + '" id="graph_BH_cg_value" style="width:60px"></td>' +
  10647. '</tr>' +
  10648. '<tr>' +
  10649. '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.barnesHut.springLength + '" step="1" style="width:300px" id="graph_BH_sl"></td><td>500</td><td><input value="' + this.constants.physics.barnesHut.springLength + '" id="graph_BH_sl_value" style="width:60px"></td>' +
  10650. '</tr>' +
  10651. '<tr>' +
  10652. '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.barnesHut.springConstant + '" step="0.001" style="width:300px" id="graph_BH_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.barnesHut.springConstant + '" id="graph_BH_sc_value" style="width:60px"></td>' +
  10653. '</tr>' +
  10654. '<tr>' +
  10655. '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.barnesHut.damping + '" step="0.005" style="width:300px" id="graph_BH_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.barnesHut.damping + '" id="graph_BH_damp_value" style="width:60px"></td>' +
  10656. '</tr>' +
  10657. '</table>' +
  10658. '<table id="graph_R_table" style="display:none">' +
  10659. '<tr><td><b>Repulsion</b></td></tr>' +
  10660. '<tr>' +
  10661. '<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.repulsion.nodeDistance + '" step="1" style="width:300px" id="graph_R_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.repulsion.nodeDistance + '" id="graph_R_nd_value" style="width:60px"></td>' +
  10662. '</tr>' +
  10663. '<tr>' +
  10664. '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.repulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_R_cg"></td><td>3</td><td><input value="' + this.constants.physics.repulsion.centralGravity + '" id="graph_R_cg_value" style="width:60px"></td>' +
  10665. '</tr>' +
  10666. '<tr>' +
  10667. '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.repulsion.springLength + '" step="1" style="width:300px" id="graph_R_sl"></td><td>500</td><td><input value="' + this.constants.physics.repulsion.springLength + '" id="graph_R_sl_value" style="width:60px"></td>' +
  10668. '</tr>' +
  10669. '<tr>' +
  10670. '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.repulsion.springConstant + '" step="0.001" style="width:300px" id="graph_R_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.repulsion.springConstant + '" id="graph_R_sc_value" style="width:60px"></td>' +
  10671. '</tr>' +
  10672. '<tr>' +
  10673. '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.repulsion.damping + '" step="0.005" style="width:300px" id="graph_R_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.repulsion.damping + '" id="graph_R_damp_value" style="width:60px"></td>' +
  10674. '</tr>' +
  10675. '</table>' +
  10676. '<table id="graph_H_table" style="display:none">' +
  10677. '<tr><td width="150"><b>Hierarchical</b></td></tr>' +
  10678. '<tr>' +
  10679. '<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" step="1" style="width:300px" id="graph_H_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" id="graph_H_nd_value" style="width:60px"></td>' +
  10680. '</tr>' +
  10681. '<tr>' +
  10682. '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_H_cg"></td><td>3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" id="graph_H_cg_value" style="width:60px"></td>' +
  10683. '</tr>' +
  10684. '<tr>' +
  10685. '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" step="1" style="width:300px" id="graph_H_sl"></td><td>500</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" id="graph_H_sl_value" style="width:60px"></td>' +
  10686. '</tr>' +
  10687. '<tr>' +
  10688. '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" step="0.001" style="width:300px" id="graph_H_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" id="graph_H_sc_value" style="width:60px"></td>' +
  10689. '</tr>' +
  10690. '<tr>' +
  10691. '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.hierarchicalRepulsion.damping + '" step="0.005" style="width:300px" id="graph_H_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.damping + '" id="graph_H_damp_value" style="width:60px"></td>' +
  10692. '</tr>' +
  10693. '<tr>' +
  10694. '<td width="150px">direction</td><td>1</td><td><input type="range" min="0" max="3" value="' + hierarchicalLayoutDirections.indexOf(this.constants.hierarchicalLayout.direction) + '" step="1" style="width:300px" id="graph_H_direction"></td><td>4</td><td><input value="' + this.constants.hierarchicalLayout.direction + '" id="graph_H_direction_value" style="width:60px"></td>' +
  10695. '</tr>' +
  10696. '<tr>' +
  10697. '<td width="150px">levelSeparation</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.levelSeparation + '" step="1" style="width:300px" id="graph_H_levsep"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.levelSeparation + '" id="graph_H_levsep_value" style="width:60px"></td>' +
  10698. '</tr>' +
  10699. '<tr>' +
  10700. '<td width="150px">nodeSpacing</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.nodeSpacing + '" step="1" style="width:300px" id="graph_H_nspac"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.nodeSpacing + '" id="graph_H_nspac_value" style="width:60px"></td>' +
  10701. '</tr>' +
  10702. '</table>' +
  10703. '<table><tr><td><b>Options:</b></td></tr>' +
  10704. '<tr>' +
  10705. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  10706. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  10707. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  10708. '</tr>' +
  10709. '</table>'
  10710. this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement);
  10711. this.optionsDiv = document.createElement("div");
  10712. this.optionsDiv.style.fontSize = "14px";
  10713. this.optionsDiv.style.fontFamily = "verdana";
  10714. this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement);
  10715. var rangeElement;
  10716. rangeElement = document.getElementById('graph_BH_gc');
  10717. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant");
  10718. rangeElement = document.getElementById('graph_BH_cg');
  10719. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity");
  10720. rangeElement = document.getElementById('graph_BH_sc');
  10721. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant");
  10722. rangeElement = document.getElementById('graph_BH_sl');
  10723. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength");
  10724. rangeElement = document.getElementById('graph_BH_damp');
  10725. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping");
  10726. rangeElement = document.getElementById('graph_R_nd');
  10727. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance");
  10728. rangeElement = document.getElementById('graph_R_cg');
  10729. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity");
  10730. rangeElement = document.getElementById('graph_R_sc');
  10731. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant");
  10732. rangeElement = document.getElementById('graph_R_sl');
  10733. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength");
  10734. rangeElement = document.getElementById('graph_R_damp');
  10735. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping");
  10736. rangeElement = document.getElementById('graph_H_nd');
  10737. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  10738. rangeElement = document.getElementById('graph_H_cg');
  10739. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity");
  10740. rangeElement = document.getElementById('graph_H_sc');
  10741. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant");
  10742. rangeElement = document.getElementById('graph_H_sl');
  10743. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength");
  10744. rangeElement = document.getElementById('graph_H_damp');
  10745. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping");
  10746. rangeElement = document.getElementById('graph_H_direction');
  10747. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction");
  10748. rangeElement = document.getElementById('graph_H_levsep');
  10749. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation");
  10750. rangeElement = document.getElementById('graph_H_nspac');
  10751. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing");
  10752. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10753. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10754. var radioButton3 = document.getElementById("graph_physicsMethod3");
  10755. radioButton2.checked = true;
  10756. if (this.constants.physics.barnesHut.enabled) {
  10757. radioButton1.checked = true;
  10758. }
  10759. if (this.constants.hierarchicalLayout.enabled) {
  10760. radioButton3.checked = true;
  10761. }
  10762. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10763. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  10764. var graph_generateOptions = document.getElementById("graph_generateOptions");
  10765. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  10766. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  10767. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  10768. if (this.constants.smoothCurves == true) {
  10769. graph_toggleSmooth.style.background = "#A4FF56";
  10770. }
  10771. else {
  10772. graph_toggleSmooth.style.background = "#FF8532";
  10773. }
  10774. switchConfigurations.apply(this);
  10775. radioButton1.onchange = switchConfigurations.bind(this);
  10776. radioButton2.onchange = switchConfigurations.bind(this);
  10777. radioButton3.onchange = switchConfigurations.bind(this);
  10778. }
  10779. },
  10780. /**
  10781. * This overwrites the this.constants.
  10782. *
  10783. * @param constantsVariableName
  10784. * @param value
  10785. * @private
  10786. */
  10787. _overWriteGraphConstants: function (constantsVariableName, value) {
  10788. var nameArray = constantsVariableName.split("_");
  10789. if (nameArray.length == 1) {
  10790. this.constants[nameArray[0]] = value;
  10791. }
  10792. else if (nameArray.length == 2) {
  10793. this.constants[nameArray[0]][nameArray[1]] = value;
  10794. }
  10795. else if (nameArray.length == 3) {
  10796. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  10797. }
  10798. }
  10799. };
  10800. /**
  10801. * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype.
  10802. */
  10803. function graphToggleSmoothCurves () {
  10804. this.constants.smoothCurves = !this.constants.smoothCurves;
  10805. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10806. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10807. else {graph_toggleSmooth.style.background = "#FF8532";}
  10808. this._configureSmoothCurves(false);
  10809. };
  10810. /**
  10811. * this function is used to scramble the nodes
  10812. *
  10813. */
  10814. function graphRepositionNodes () {
  10815. for (var nodeId in this.calculationNodes) {
  10816. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  10817. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  10818. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  10819. }
  10820. }
  10821. if (this.constants.hierarchicalLayout.enabled == true) {
  10822. this._setupHierarchicalLayout();
  10823. }
  10824. else {
  10825. this.repositionNodes();
  10826. }
  10827. this.moving = true;
  10828. this.start();
  10829. };
  10830. /**
  10831. * this is used to generate an options file from the playing with physics system.
  10832. */
  10833. function graphGenerateOptions () {
  10834. var options = "No options are required, default values used.";
  10835. var optionsSpecific = [];
  10836. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10837. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10838. if (radioButton1.checked == true) {
  10839. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  10840. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10841. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10842. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10843. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10844. if (optionsSpecific.length != 0) {
  10845. options = "var options = {";
  10846. options += "physics: {barnesHut: {";
  10847. for (var i = 0; i < optionsSpecific.length; i++) {
  10848. options += optionsSpecific[i];
  10849. if (i < optionsSpecific.length - 1) {
  10850. options += ", "
  10851. }
  10852. }
  10853. options += '}}'
  10854. }
  10855. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10856. if (optionsSpecific.length == 0) {options = "var options = {";}
  10857. else {options += ", "}
  10858. options += "smoothCurves: " + this.constants.smoothCurves;
  10859. }
  10860. if (options != "No options are required, default values used.") {
  10861. options += '};'
  10862. }
  10863. }
  10864. else if (radioButton2.checked == true) {
  10865. options = "var options = {";
  10866. options += "physics: {barnesHut: {enabled: false}";
  10867. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  10868. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10869. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10870. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10871. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10872. if (optionsSpecific.length != 0) {
  10873. options += ", repulsion: {";
  10874. for (var i = 0; i < optionsSpecific.length; i++) {
  10875. options += optionsSpecific[i];
  10876. if (i < optionsSpecific.length - 1) {
  10877. options += ", "
  10878. }
  10879. }
  10880. options += '}}'
  10881. }
  10882. if (optionsSpecific.length == 0) {options += "}"}
  10883. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10884. options += ", smoothCurves: " + this.constants.smoothCurves;
  10885. }
  10886. options += '};'
  10887. }
  10888. else {
  10889. options = "var options = {";
  10890. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  10891. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10892. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10893. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10894. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10895. if (optionsSpecific.length != 0) {
  10896. options += "physics: {hierarchicalRepulsion: {";
  10897. for (var i = 0; i < optionsSpecific.length; i++) {
  10898. options += optionsSpecific[i];
  10899. if (i < optionsSpecific.length - 1) {
  10900. options += ", ";
  10901. }
  10902. }
  10903. options += '}},';
  10904. }
  10905. options += 'hierarchicalLayout: {';
  10906. optionsSpecific = [];
  10907. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  10908. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  10909. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  10910. if (optionsSpecific.length != 0) {
  10911. for (var i = 0; i < optionsSpecific.length; i++) {
  10912. options += optionsSpecific[i];
  10913. if (i < optionsSpecific.length - 1) {
  10914. options += ", "
  10915. }
  10916. }
  10917. options += '}'
  10918. }
  10919. else {
  10920. options += "enabled:true}";
  10921. }
  10922. options += '};'
  10923. }
  10924. this.optionsDiv.innerHTML = options;
  10925. };
  10926. /**
  10927. * this is used to switch between barnesHut, repulsion and hierarchical.
  10928. *
  10929. */
  10930. function switchConfigurations () {
  10931. var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"];
  10932. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  10933. var tableId = "graph_" + radioButton + "_table";
  10934. var table = document.getElementById(tableId);
  10935. table.style.display = "block";
  10936. for (var i = 0; i < ids.length; i++) {
  10937. if (ids[i] != tableId) {
  10938. table = document.getElementById(ids[i]);
  10939. table.style.display = "none";
  10940. }
  10941. }
  10942. this._restoreNodes();
  10943. if (radioButton == "R") {
  10944. this.constants.hierarchicalLayout.enabled = false;
  10945. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10946. this.constants.physics.barnesHut.enabled = false;
  10947. }
  10948. else if (radioButton == "H") {
  10949. if (this.constants.hierarchicalLayout.enabled == false) {
  10950. this.constants.hierarchicalLayout.enabled = true;
  10951. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10952. this.constants.physics.barnesHut.enabled = false;
  10953. this._setupHierarchicalLayout();
  10954. }
  10955. }
  10956. else {
  10957. this.constants.hierarchicalLayout.enabled = false;
  10958. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10959. this.constants.physics.barnesHut.enabled = true;
  10960. }
  10961. this._loadSelectedForceSolver();
  10962. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10963. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10964. else {graph_toggleSmooth.style.background = "#FF8532";}
  10965. this.moving = true;
  10966. this.start();
  10967. }
  10968. /**
  10969. * this generates the ranges depending on the iniital values.
  10970. *
  10971. * @param id
  10972. * @param map
  10973. * @param constantsVariableName
  10974. */
  10975. function showValueOfRange (id,map,constantsVariableName) {
  10976. var valueId = id + "_value";
  10977. var rangeValue = document.getElementById(id).value;
  10978. if (map instanceof Array) {
  10979. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  10980. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  10981. }
  10982. else {
  10983. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  10984. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  10985. }
  10986. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10987. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10988. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10989. this._setupHierarchicalLayout();
  10990. }
  10991. this.moving = true;
  10992. this.start();
  10993. };
  10994. /**
  10995. * Created by Alex on 2/10/14.
  10996. */
  10997. var hierarchalRepulsionMixin = {
  10998. /**
  10999. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  11000. * This field is linearly approximated.
  11001. *
  11002. * @private
  11003. */
  11004. _calculateNodeForces: function () {
  11005. var dx, dy, distance, fx, fy, combinedClusterSize,
  11006. repulsingForce, node1, node2, i, j;
  11007. var nodes = this.calculationNodes;
  11008. var nodeIndices = this.calculationNodeIndices;
  11009. // approximation constants
  11010. var b = 5;
  11011. var a_base = 0.5 * -b;
  11012. // repulsing forces between nodes
  11013. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  11014. var minimumDistance = nodeDistance;
  11015. // we loop from i over all but the last entree in the array
  11016. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  11017. for (i = 0; i < nodeIndices.length - 1; i++) {
  11018. node1 = nodes[nodeIndices[i]];
  11019. for (j = i + 1; j < nodeIndices.length; j++) {
  11020. node2 = nodes[nodeIndices[j]];
  11021. dx = node2.x - node1.x;
  11022. dy = node2.y - node1.y;
  11023. distance = Math.sqrt(dx * dx + dy * dy);
  11024. var a = a_base / minimumDistance;
  11025. if (distance < 2 * minimumDistance) {
  11026. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  11027. // normalize force with
  11028. if (distance == 0) {
  11029. distance = 0.01;
  11030. }
  11031. else {
  11032. repulsingForce = repulsingForce / distance;
  11033. }
  11034. fx = dx * repulsingForce;
  11035. fy = dy * repulsingForce;
  11036. node1.fx -= fx;
  11037. node1.fy -= fy;
  11038. node2.fx += fx;
  11039. node2.fy += fy;
  11040. }
  11041. }
  11042. }
  11043. }
  11044. };
  11045. /**
  11046. * Created by Alex on 2/10/14.
  11047. */
  11048. var barnesHutMixin = {
  11049. /**
  11050. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  11051. * The Barnes Hut method is used to speed up this N-body simulation.
  11052. *
  11053. * @private
  11054. */
  11055. _calculateNodeForces : function() {
  11056. if (this.constants.physics.barnesHut.gravitationalConstant != 0) {
  11057. var node;
  11058. var nodes = this.calculationNodes;
  11059. var nodeIndices = this.calculationNodeIndices;
  11060. var nodeCount = nodeIndices.length;
  11061. this._formBarnesHutTree(nodes,nodeIndices);
  11062. var barnesHutTree = this.barnesHutTree;
  11063. // place the nodes one by one recursively
  11064. for (var i = 0; i < nodeCount; i++) {
  11065. node = nodes[nodeIndices[i]];
  11066. // starting with root is irrelevant, it never passes the BarnesHut condition
  11067. this._getForceContribution(barnesHutTree.root.children.NW,node);
  11068. this._getForceContribution(barnesHutTree.root.children.NE,node);
  11069. this._getForceContribution(barnesHutTree.root.children.SW,node);
  11070. this._getForceContribution(barnesHutTree.root.children.SE,node);
  11071. }
  11072. }
  11073. },
  11074. /**
  11075. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  11076. * If a region contains a single node, we check if it is not itself, then we apply the force.
  11077. *
  11078. * @param parentBranch
  11079. * @param node
  11080. * @private
  11081. */
  11082. _getForceContribution : function(parentBranch,node) {
  11083. // we get no force contribution from an empty region
  11084. if (parentBranch.childrenCount > 0) {
  11085. var dx,dy,distance;
  11086. // get the distance from the center of mass to the node.
  11087. dx = parentBranch.centerOfMass.x - node.x;
  11088. dy = parentBranch.centerOfMass.y - node.y;
  11089. distance = Math.sqrt(dx * dx + dy * dy);
  11090. // BarnesHut condition
  11091. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  11092. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  11093. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  11094. // duplicate code to reduce function calls to speed up program
  11095. if (distance == 0) {
  11096. distance = 0.1*Math.random();
  11097. dx = distance;
  11098. }
  11099. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  11100. var fx = dx * gravityForce;
  11101. var fy = dy * gravityForce;
  11102. node.fx += fx;
  11103. node.fy += fy;
  11104. }
  11105. else {
  11106. // Did not pass the condition, go into children if available
  11107. if (parentBranch.childrenCount == 4) {
  11108. this._getForceContribution(parentBranch.children.NW,node);
  11109. this._getForceContribution(parentBranch.children.NE,node);
  11110. this._getForceContribution(parentBranch.children.SW,node);
  11111. this._getForceContribution(parentBranch.children.SE,node);
  11112. }
  11113. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  11114. if (parentBranch.children.data.id != node.id) { // if it is not self
  11115. // duplicate code to reduce function calls to speed up program
  11116. if (distance == 0) {
  11117. distance = 0.5*Math.random();
  11118. dx = distance;
  11119. }
  11120. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  11121. var fx = dx * gravityForce;
  11122. var fy = dy * gravityForce;
  11123. node.fx += fx;
  11124. node.fy += fy;
  11125. }
  11126. }
  11127. }
  11128. }
  11129. },
  11130. /**
  11131. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  11132. *
  11133. * @param nodes
  11134. * @param nodeIndices
  11135. * @private
  11136. */
  11137. _formBarnesHutTree : function(nodes,nodeIndices) {
  11138. var node;
  11139. var nodeCount = nodeIndices.length;
  11140. var minX = Number.MAX_VALUE,
  11141. minY = Number.MAX_VALUE,
  11142. maxX =-Number.MAX_VALUE,
  11143. maxY =-Number.MAX_VALUE;
  11144. // get the range of the nodes
  11145. for (var i = 0; i < nodeCount; i++) {
  11146. var x = nodes[nodeIndices[i]].x;
  11147. var y = nodes[nodeIndices[i]].y;
  11148. if (x < minX) { minX = x; }
  11149. if (x > maxX) { maxX = x; }
  11150. if (y < minY) { minY = y; }
  11151. if (y > maxY) { maxY = y; }
  11152. }
  11153. // make the range a square
  11154. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  11155. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  11156. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  11157. var minimumTreeSize = 1e-5;
  11158. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  11159. var halfRootSize = 0.5 * rootSize;
  11160. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  11161. // construct the barnesHutTree
  11162. var barnesHutTree = {root:{
  11163. centerOfMass:{x:0,y:0}, // Center of Mass
  11164. mass:0,
  11165. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  11166. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  11167. size: rootSize,
  11168. calcSize: 1 / rootSize,
  11169. children: {data:null},
  11170. maxWidth: 0,
  11171. level: 0,
  11172. childrenCount: 4
  11173. }};
  11174. this._splitBranch(barnesHutTree.root);
  11175. // place the nodes one by one recursively
  11176. for (i = 0; i < nodeCount; i++) {
  11177. node = nodes[nodeIndices[i]];
  11178. this._placeInTree(barnesHutTree.root,node);
  11179. }
  11180. // make global
  11181. this.barnesHutTree = barnesHutTree
  11182. },
  11183. /**
  11184. * this updates the mass of a branch. this is increased by adding a node.
  11185. *
  11186. * @param parentBranch
  11187. * @param node
  11188. * @private
  11189. */
  11190. _updateBranchMass : function(parentBranch, node) {
  11191. var totalMass = parentBranch.mass + node.mass;
  11192. var totalMassInv = 1/totalMass;
  11193. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  11194. parentBranch.centerOfMass.x *= totalMassInv;
  11195. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  11196. parentBranch.centerOfMass.y *= totalMassInv;
  11197. parentBranch.mass = totalMass;
  11198. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  11199. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  11200. },
  11201. /**
  11202. * determine in which branch the node will be placed.
  11203. *
  11204. * @param parentBranch
  11205. * @param node
  11206. * @param skipMassUpdate
  11207. * @private
  11208. */
  11209. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  11210. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  11211. // update the mass of the branch.
  11212. this._updateBranchMass(parentBranch,node);
  11213. }
  11214. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  11215. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  11216. this._placeInRegion(parentBranch,node,"NW");
  11217. }
  11218. else { // in SW
  11219. this._placeInRegion(parentBranch,node,"SW");
  11220. }
  11221. }
  11222. else { // in NE or SE
  11223. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  11224. this._placeInRegion(parentBranch,node,"NE");
  11225. }
  11226. else { // in SE
  11227. this._placeInRegion(parentBranch,node,"SE");
  11228. }
  11229. }
  11230. },
  11231. /**
  11232. * actually place the node in a region (or branch)
  11233. *
  11234. * @param parentBranch
  11235. * @param node
  11236. * @param region
  11237. * @private
  11238. */
  11239. _placeInRegion : function(parentBranch,node,region) {
  11240. switch (parentBranch.children[region].childrenCount) {
  11241. case 0: // place node here
  11242. parentBranch.children[region].children.data = node;
  11243. parentBranch.children[region].childrenCount = 1;
  11244. this._updateBranchMass(parentBranch.children[region],node);
  11245. break;
  11246. case 1: // convert into children
  11247. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  11248. // we move one node a pixel and we do not put it in the tree.
  11249. if (parentBranch.children[region].children.data.x == node.x &&
  11250. parentBranch.children[region].children.data.y == node.y) {
  11251. node.x += Math.random();
  11252. node.y += Math.random();
  11253. }
  11254. else {
  11255. this._splitBranch(parentBranch.children[region]);
  11256. this._placeInTree(parentBranch.children[region],node);
  11257. }
  11258. break;
  11259. case 4: // place in branch
  11260. this._placeInTree(parentBranch.children[region],node);
  11261. break;
  11262. }
  11263. },
  11264. /**
  11265. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  11266. * after the split is complete.
  11267. *
  11268. * @param parentBranch
  11269. * @private
  11270. */
  11271. _splitBranch : function(parentBranch) {
  11272. // if the branch is filled with a node, replace the node in the new subset.
  11273. var containedNode = null;
  11274. if (parentBranch.childrenCount == 1) {
  11275. containedNode = parentBranch.children.data;
  11276. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  11277. }
  11278. parentBranch.childrenCount = 4;
  11279. parentBranch.children.data = null;
  11280. this._insertRegion(parentBranch,"NW");
  11281. this._insertRegion(parentBranch,"NE");
  11282. this._insertRegion(parentBranch,"SW");
  11283. this._insertRegion(parentBranch,"SE");
  11284. if (containedNode != null) {
  11285. this._placeInTree(parentBranch,containedNode);
  11286. }
  11287. },
  11288. /**
  11289. * This function subdivides the region into four new segments.
  11290. * Specifically, this inserts a single new segment.
  11291. * It fills the children section of the parentBranch
  11292. *
  11293. * @param parentBranch
  11294. * @param region
  11295. * @param parentRange
  11296. * @private
  11297. */
  11298. _insertRegion : function(parentBranch, region) {
  11299. var minX,maxX,minY,maxY;
  11300. var childSize = 0.5 * parentBranch.size;
  11301. switch (region) {
  11302. case "NW":
  11303. minX = parentBranch.range.minX;
  11304. maxX = parentBranch.range.minX + childSize;
  11305. minY = parentBranch.range.minY;
  11306. maxY = parentBranch.range.minY + childSize;
  11307. break;
  11308. case "NE":
  11309. minX = parentBranch.range.minX + childSize;
  11310. maxX = parentBranch.range.maxX;
  11311. minY = parentBranch.range.minY;
  11312. maxY = parentBranch.range.minY + childSize;
  11313. break;
  11314. case "SW":
  11315. minX = parentBranch.range.minX;
  11316. maxX = parentBranch.range.minX + childSize;
  11317. minY = parentBranch.range.minY + childSize;
  11318. maxY = parentBranch.range.maxY;
  11319. break;
  11320. case "SE":
  11321. minX = parentBranch.range.minX + childSize;
  11322. maxX = parentBranch.range.maxX;
  11323. minY = parentBranch.range.minY + childSize;
  11324. maxY = parentBranch.range.maxY;
  11325. break;
  11326. }
  11327. parentBranch.children[region] = {
  11328. centerOfMass:{x:0,y:0},
  11329. mass:0,
  11330. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  11331. size: 0.5 * parentBranch.size,
  11332. calcSize: 2 * parentBranch.calcSize,
  11333. children: {data:null},
  11334. maxWidth: 0,
  11335. level: parentBranch.level+1,
  11336. childrenCount: 0
  11337. };
  11338. },
  11339. /**
  11340. * This function is for debugging purposed, it draws the tree.
  11341. *
  11342. * @param ctx
  11343. * @param color
  11344. * @private
  11345. */
  11346. _drawTree : function(ctx,color) {
  11347. if (this.barnesHutTree !== undefined) {
  11348. ctx.lineWidth = 1;
  11349. this._drawBranch(this.barnesHutTree.root,ctx,color);
  11350. }
  11351. },
  11352. /**
  11353. * This function is for debugging purposes. It draws the branches recursively.
  11354. *
  11355. * @param branch
  11356. * @param ctx
  11357. * @param color
  11358. * @private
  11359. */
  11360. _drawBranch : function(branch,ctx,color) {
  11361. if (color === undefined) {
  11362. color = "#FF0000";
  11363. }
  11364. if (branch.childrenCount == 4) {
  11365. this._drawBranch(branch.children.NW,ctx);
  11366. this._drawBranch(branch.children.NE,ctx);
  11367. this._drawBranch(branch.children.SE,ctx);
  11368. this._drawBranch(branch.children.SW,ctx);
  11369. }
  11370. ctx.strokeStyle = color;
  11371. ctx.beginPath();
  11372. ctx.moveTo(branch.range.minX,branch.range.minY);
  11373. ctx.lineTo(branch.range.maxX,branch.range.minY);
  11374. ctx.stroke();
  11375. ctx.beginPath();
  11376. ctx.moveTo(branch.range.maxX,branch.range.minY);
  11377. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  11378. ctx.stroke();
  11379. ctx.beginPath();
  11380. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  11381. ctx.lineTo(branch.range.minX,branch.range.maxY);
  11382. ctx.stroke();
  11383. ctx.beginPath();
  11384. ctx.moveTo(branch.range.minX,branch.range.maxY);
  11385. ctx.lineTo(branch.range.minX,branch.range.minY);
  11386. ctx.stroke();
  11387. /*
  11388. if (branch.mass > 0) {
  11389. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  11390. ctx.stroke();
  11391. }
  11392. */
  11393. }
  11394. };
  11395. /**
  11396. * Created by Alex on 2/10/14.
  11397. */
  11398. var repulsionMixin = {
  11399. /**
  11400. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  11401. * This field is linearly approximated.
  11402. *
  11403. * @private
  11404. */
  11405. _calculateNodeForces: function () {
  11406. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  11407. repulsingForce, node1, node2, i, j;
  11408. var nodes = this.calculationNodes;
  11409. var nodeIndices = this.calculationNodeIndices;
  11410. // approximation constants
  11411. var a_base = -2 / 3;
  11412. var b = 4 / 3;
  11413. // repulsing forces between nodes
  11414. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  11415. var minimumDistance = nodeDistance;
  11416. // we loop from i over all but the last entree in the array
  11417. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  11418. for (i = 0; i < nodeIndices.length - 1; i++) {
  11419. node1 = nodes[nodeIndices[i]];
  11420. for (j = i + 1; j < nodeIndices.length; j++) {
  11421. node2 = nodes[nodeIndices[j]];
  11422. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  11423. dx = node2.x - node1.x;
  11424. dy = node2.y - node1.y;
  11425. distance = Math.sqrt(dx * dx + dy * dy);
  11426. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  11427. var a = a_base / minimumDistance;
  11428. if (distance < 2 * minimumDistance) {
  11429. if (distance < 0.5 * minimumDistance) {
  11430. repulsingForce = 1.0;
  11431. }
  11432. else {
  11433. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  11434. }
  11435. // amplify the repulsion for clusters.
  11436. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  11437. repulsingForce = repulsingForce / distance;
  11438. fx = dx * repulsingForce;
  11439. fy = dy * repulsingForce;
  11440. node1.fx -= fx;
  11441. node1.fy -= fy;
  11442. node2.fx += fx;
  11443. node2.fy += fy;
  11444. }
  11445. }
  11446. }
  11447. }
  11448. };
  11449. var HierarchicalLayoutMixin = {
  11450. _resetLevels : function() {
  11451. for (var nodeId in this.nodes) {
  11452. if (this.nodes.hasOwnProperty(nodeId)) {
  11453. var node = this.nodes[nodeId];
  11454. if (node.preassignedLevel == false) {
  11455. node.level = -1;
  11456. }
  11457. }
  11458. }
  11459. },
  11460. /**
  11461. * This is the main function to layout the nodes in a hierarchical way.
  11462. * It checks if the node details are supplied correctly
  11463. *
  11464. * @private
  11465. */
  11466. _setupHierarchicalLayout : function() {
  11467. if (this.constants.hierarchicalLayout.enabled == true) {
  11468. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  11469. this.constants.hierarchicalLayout.levelSeparation *= -1;
  11470. }
  11471. else {
  11472. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  11473. }
  11474. // get the size of the largest hubs and check if the user has defined a level for a node.
  11475. var hubsize = 0;
  11476. var node, nodeId;
  11477. var definedLevel = false;
  11478. var undefinedLevel = false;
  11479. for (nodeId in this.nodes) {
  11480. if (this.nodes.hasOwnProperty(nodeId)) {
  11481. node = this.nodes[nodeId];
  11482. if (node.level != -1) {
  11483. definedLevel = true;
  11484. }
  11485. else {
  11486. undefinedLevel = true;
  11487. }
  11488. if (hubsize < node.edges.length) {
  11489. hubsize = node.edges.length;
  11490. }
  11491. }
  11492. }
  11493. // if the user defined some levels but not all, alert and run without hierarchical layout
  11494. if (undefinedLevel == true && definedLevel == true) {
  11495. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");
  11496. this.zoomExtent(true,this.constants.clustering.enabled);
  11497. if (!this.constants.clustering.enabled) {
  11498. this.start();
  11499. }
  11500. }
  11501. else {
  11502. // setup the system to use hierarchical method.
  11503. this._changeConstants();
  11504. // define levels if undefined by the users. Based on hubsize
  11505. if (undefinedLevel == true) {
  11506. this._determineLevels(hubsize);
  11507. }
  11508. // check the distribution of the nodes per level.
  11509. var distribution = this._getDistribution();
  11510. // place the nodes on the canvas. This also stablilizes the system.
  11511. this._placeNodesByHierarchy(distribution);
  11512. // start the simulation.
  11513. this.start();
  11514. }
  11515. }
  11516. },
  11517. /**
  11518. * This function places the nodes on the canvas based on the hierarchial distribution.
  11519. *
  11520. * @param {Object} distribution | obtained by the function this._getDistribution()
  11521. * @private
  11522. */
  11523. _placeNodesByHierarchy : function(distribution) {
  11524. var nodeId, node;
  11525. // start placing all the level 0 nodes first. Then recursively position their branches.
  11526. for (nodeId in distribution[0].nodes) {
  11527. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  11528. node = distribution[0].nodes[nodeId];
  11529. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11530. if (node.xFixed) {
  11531. node.x = distribution[0].minPos;
  11532. node.xFixed = false;
  11533. distribution[0].minPos += distribution[0].nodeSpacing;
  11534. }
  11535. }
  11536. else {
  11537. if (node.yFixed) {
  11538. node.y = distribution[0].minPos;
  11539. node.yFixed = false;
  11540. distribution[0].minPos += distribution[0].nodeSpacing;
  11541. }
  11542. }
  11543. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  11544. }
  11545. }
  11546. // stabilize the system after positioning. This function calls zoomExtent.
  11547. this._stabilize();
  11548. },
  11549. /**
  11550. * This function get the distribution of levels based on hubsize
  11551. *
  11552. * @returns {Object}
  11553. * @private
  11554. */
  11555. _getDistribution : function() {
  11556. var distribution = {};
  11557. var nodeId, node, level;
  11558. // we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time.
  11559. // the fix of X is removed after the x value has been set.
  11560. for (nodeId in this.nodes) {
  11561. if (this.nodes.hasOwnProperty(nodeId)) {
  11562. node = this.nodes[nodeId];
  11563. node.xFixed = true;
  11564. node.yFixed = true;
  11565. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11566. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  11567. }
  11568. else {
  11569. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  11570. }
  11571. if (!distribution.hasOwnProperty(node.level)) {
  11572. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  11573. }
  11574. distribution[node.level].amount += 1;
  11575. distribution[node.level].nodes[node.id] = node;
  11576. }
  11577. }
  11578. // determine the largest amount of nodes of all levels
  11579. var maxCount = 0;
  11580. for (level in distribution) {
  11581. if (distribution.hasOwnProperty(level)) {
  11582. if (maxCount < distribution[level].amount) {
  11583. maxCount = distribution[level].amount;
  11584. }
  11585. }
  11586. }
  11587. // set the initial position and spacing of each nodes accordingly
  11588. for (level in distribution) {
  11589. if (distribution.hasOwnProperty(level)) {
  11590. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  11591. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  11592. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  11593. }
  11594. }
  11595. return distribution;
  11596. },
  11597. /**
  11598. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  11599. *
  11600. * @param hubsize
  11601. * @private
  11602. */
  11603. _determineLevels : function(hubsize) {
  11604. var nodeId, node;
  11605. // determine hubs
  11606. for (nodeId in this.nodes) {
  11607. if (this.nodes.hasOwnProperty(nodeId)) {
  11608. node = this.nodes[nodeId];
  11609. if (node.edges.length == hubsize) {
  11610. node.level = 0;
  11611. }
  11612. }
  11613. }
  11614. // branch from hubs
  11615. for (nodeId in this.nodes) {
  11616. if (this.nodes.hasOwnProperty(nodeId)) {
  11617. node = this.nodes[nodeId];
  11618. if (node.level == 0) {
  11619. this._setLevel(1,node.edges,node.id);
  11620. }
  11621. }
  11622. }
  11623. },
  11624. /**
  11625. * Since hierarchical layout does not support:
  11626. * - smooth curves (based on the physics),
  11627. * - clustering (based on dynamic node counts)
  11628. *
  11629. * We disable both features so there will be no problems.
  11630. *
  11631. * @private
  11632. */
  11633. _changeConstants : function() {
  11634. this.constants.clustering.enabled = false;
  11635. this.constants.physics.barnesHut.enabled = false;
  11636. this.constants.physics.hierarchicalRepulsion.enabled = true;
  11637. this._loadSelectedForceSolver();
  11638. this.constants.smoothCurves = false;
  11639. this._configureSmoothCurves();
  11640. },
  11641. /**
  11642. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  11643. * on a X position that ensures there will be no overlap.
  11644. *
  11645. * @param edges
  11646. * @param parentId
  11647. * @param distribution
  11648. * @param parentLevel
  11649. * @private
  11650. */
  11651. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  11652. for (var i = 0; i < edges.length; i++) {
  11653. var childNode = null;
  11654. if (edges[i].toId == parentId) {
  11655. childNode = edges[i].from;
  11656. }
  11657. else {
  11658. childNode = edges[i].to;
  11659. }
  11660. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  11661. var nodeMoved = false;
  11662. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11663. if (childNode.xFixed && childNode.level > parentLevel) {
  11664. childNode.xFixed = false;
  11665. childNode.x = distribution[childNode.level].minPos;
  11666. nodeMoved = true;
  11667. }
  11668. }
  11669. else {
  11670. if (childNode.yFixed && childNode.level > parentLevel) {
  11671. childNode.yFixed = false;
  11672. childNode.y = distribution[childNode.level].minPos;
  11673. nodeMoved = true;
  11674. }
  11675. }
  11676. if (nodeMoved == true) {
  11677. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  11678. if (childNode.edges.length > 1) {
  11679. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  11680. }
  11681. }
  11682. }
  11683. },
  11684. /**
  11685. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  11686. *
  11687. * @param level
  11688. * @param edges
  11689. * @param parentId
  11690. * @private
  11691. */
  11692. _setLevel : function(level, edges, parentId) {
  11693. for (var i = 0; i < edges.length; i++) {
  11694. var childNode = null;
  11695. if (edges[i].toId == parentId) {
  11696. childNode = edges[i].from;
  11697. }
  11698. else {
  11699. childNode = edges[i].to;
  11700. }
  11701. if (childNode.level == -1 || childNode.level > level) {
  11702. childNode.level = level;
  11703. if (edges.length > 1) {
  11704. this._setLevel(level+1, childNode.edges, childNode.id);
  11705. }
  11706. }
  11707. }
  11708. },
  11709. /**
  11710. * Unfix nodes
  11711. *
  11712. * @private
  11713. */
  11714. _restoreNodes : function() {
  11715. for (nodeId in this.nodes) {
  11716. if (this.nodes.hasOwnProperty(nodeId)) {
  11717. this.nodes[nodeId].xFixed = false;
  11718. this.nodes[nodeId].yFixed = false;
  11719. }
  11720. }
  11721. }
  11722. };
  11723. /**
  11724. * Created by Alex on 2/4/14.
  11725. */
  11726. var manipulationMixin = {
  11727. /**
  11728. * clears the toolbar div element of children
  11729. *
  11730. * @private
  11731. */
  11732. _clearManipulatorBar : function() {
  11733. while (this.manipulationDiv.hasChildNodes()) {
  11734. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11735. }
  11736. },
  11737. /**
  11738. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  11739. * these functions to their original functionality, we saved them in this.cachedFunctions.
  11740. * This function restores these functions to their original function.
  11741. *
  11742. * @private
  11743. */
  11744. _restoreOverloadedFunctions : function() {
  11745. for (var functionName in this.cachedFunctions) {
  11746. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  11747. this[functionName] = this.cachedFunctions[functionName];
  11748. }
  11749. }
  11750. },
  11751. /**
  11752. * Enable or disable edit-mode.
  11753. *
  11754. * @private
  11755. */
  11756. _toggleEditMode : function() {
  11757. this.editMode = !this.editMode;
  11758. var toolbar = document.getElementById("graph-manipulationDiv");
  11759. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11760. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  11761. if (this.editMode == true) {
  11762. toolbar.style.display="block";
  11763. closeDiv.style.display="block";
  11764. editModeDiv.style.display="none";
  11765. closeDiv.onclick = this._toggleEditMode.bind(this);
  11766. }
  11767. else {
  11768. toolbar.style.display="none";
  11769. closeDiv.style.display="none";
  11770. editModeDiv.style.display="block";
  11771. closeDiv.onclick = null;
  11772. }
  11773. this._createManipulatorBar()
  11774. },
  11775. /**
  11776. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  11777. *
  11778. * @private
  11779. */
  11780. _createManipulatorBar : function() {
  11781. // remove bound functions
  11782. if (this.boundFunction) {
  11783. this.off('select', this.boundFunction);
  11784. }
  11785. // restore overloaded functions
  11786. this._restoreOverloadedFunctions();
  11787. // resume calculation
  11788. this.freezeSimulation = false;
  11789. // reset global variables
  11790. this.blockConnectingEdgeSelection = false;
  11791. this.forceAppendSelection = false;
  11792. if (this.editMode == true) {
  11793. while (this.manipulationDiv.hasChildNodes()) {
  11794. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11795. }
  11796. // add the icons to the manipulator div
  11797. this.manipulationDiv.innerHTML = "" +
  11798. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  11799. "<span class='graph-manipulationLabel'>"+this.constants.labels['add'] +"</span></span>" +
  11800. "<div class='graph-seperatorLine'></div>" +
  11801. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  11802. "<span class='graph-manipulationLabel'>"+this.constants.labels['link'] +"</span></span>";
  11803. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11804. this.manipulationDiv.innerHTML += "" +
  11805. "<div class='graph-seperatorLine'></div>" +
  11806. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  11807. "<span class='graph-manipulationLabel'>"+this.constants.labels['editNode'] +"</span></span>";
  11808. }
  11809. if (this._selectionIsEmpty() == false) {
  11810. this.manipulationDiv.innerHTML += "" +
  11811. "<div class='graph-seperatorLine'></div>" +
  11812. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  11813. "<span class='graph-manipulationLabel'>"+this.constants.labels['del'] +"</span></span>";
  11814. }
  11815. // bind the icons
  11816. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  11817. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  11818. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  11819. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  11820. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11821. var editButton = document.getElementById("graph-manipulate-editNode");
  11822. editButton.onclick = this._editNode.bind(this);
  11823. }
  11824. if (this._selectionIsEmpty() == false) {
  11825. var deleteButton = document.getElementById("graph-manipulate-delete");
  11826. deleteButton.onclick = this._deleteSelected.bind(this);
  11827. }
  11828. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11829. closeDiv.onclick = this._toggleEditMode.bind(this);
  11830. this.boundFunction = this._createManipulatorBar.bind(this);
  11831. this.on('select', this.boundFunction);
  11832. }
  11833. else {
  11834. this.editModeDiv.innerHTML = "" +
  11835. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  11836. "<span class='graph-manipulationLabel'>" + this.constants.labels['edit'] + "</span></span>";
  11837. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  11838. editModeButton.onclick = this._toggleEditMode.bind(this);
  11839. }
  11840. },
  11841. /**
  11842. * Create the toolbar for adding Nodes
  11843. *
  11844. * @private
  11845. */
  11846. _createAddNodeToolbar : function() {
  11847. // clear the toolbar
  11848. this._clearManipulatorBar();
  11849. if (this.boundFunction) {
  11850. this.off('select', this.boundFunction);
  11851. }
  11852. // create the toolbar contents
  11853. this.manipulationDiv.innerHTML = "" +
  11854. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11855. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11856. "<div class='graph-seperatorLine'></div>" +
  11857. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11858. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['addDescription'] + "</span></span>";
  11859. // bind the icon
  11860. var backButton = document.getElementById("graph-manipulate-back");
  11861. backButton.onclick = this._createManipulatorBar.bind(this);
  11862. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11863. this.boundFunction = this._addNode.bind(this);
  11864. this.on('select', this.boundFunction);
  11865. },
  11866. /**
  11867. * create the toolbar to connect nodes
  11868. *
  11869. * @private
  11870. */
  11871. _createAddEdgeToolbar : function() {
  11872. // clear the toolbar
  11873. this._clearManipulatorBar();
  11874. this._unselectAll(true);
  11875. this.freezeSimulation = true;
  11876. if (this.boundFunction) {
  11877. this.off('select', this.boundFunction);
  11878. }
  11879. this._unselectAll();
  11880. this.forceAppendSelection = false;
  11881. this.blockConnectingEdgeSelection = true;
  11882. this.manipulationDiv.innerHTML = "" +
  11883. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11884. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11885. "<div class='graph-seperatorLine'></div>" +
  11886. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11887. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['linkDescription'] + "</span></span>";
  11888. // bind the icon
  11889. var backButton = document.getElementById("graph-manipulate-back");
  11890. backButton.onclick = this._createManipulatorBar.bind(this);
  11891. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11892. this.boundFunction = this._handleConnect.bind(this);
  11893. this.on('select', this.boundFunction);
  11894. // temporarily overload functions
  11895. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  11896. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  11897. this._handleTouch = this._handleConnect;
  11898. this._handleOnRelease = this._finishConnect;
  11899. // redraw to show the unselect
  11900. this._redraw();
  11901. },
  11902. /**
  11903. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11904. * to walk the user through the process.
  11905. *
  11906. * @private
  11907. */
  11908. _handleConnect : function(pointer) {
  11909. if (this._getSelectedNodeCount() == 0) {
  11910. var node = this._getNodeAt(pointer);
  11911. if (node != null) {
  11912. if (node.clusterSize > 1) {
  11913. alert("Cannot create edges to a cluster.")
  11914. }
  11915. else {
  11916. this._selectObject(node,false);
  11917. // create a node the temporary line can look at
  11918. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11919. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11920. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11921. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11922. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11923. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11924. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11925. // create a temporary edge
  11926. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11927. this.edges['connectionEdge'].from = node;
  11928. this.edges['connectionEdge'].connected = true;
  11929. this.edges['connectionEdge'].smooth = true;
  11930. this.edges['connectionEdge'].selected = true;
  11931. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11932. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11933. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11934. this._handleOnDrag = function(event) {
  11935. var pointer = this._getPointer(event.gesture.center);
  11936. this.sectors['support']['nodes']['targetNode'].x = this._canvasToX(pointer.x);
  11937. this.sectors['support']['nodes']['targetNode'].y = this._canvasToY(pointer.y);
  11938. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._canvasToX(pointer.x) + this.edges['connectionEdge'].from.x);
  11939. this.sectors['support']['nodes']['targetViaNode'].y = this._canvasToY(pointer.y);
  11940. };
  11941. this.moving = true;
  11942. this.start();
  11943. }
  11944. }
  11945. }
  11946. },
  11947. _finishConnect : function(pointer) {
  11948. if (this._getSelectedNodeCount() == 1) {
  11949. // restore the drag function
  11950. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11951. delete this.cachedFunctions["_handleOnDrag"];
  11952. // remember the edge id
  11953. var connectFromId = this.edges['connectionEdge'].fromId;
  11954. // remove the temporary nodes and edge
  11955. delete this.edges['connectionEdge'];
  11956. delete this.sectors['support']['nodes']['targetNode'];
  11957. delete this.sectors['support']['nodes']['targetViaNode'];
  11958. var node = this._getNodeAt(pointer);
  11959. if (node != null) {
  11960. if (node.clusterSize > 1) {
  11961. alert("Cannot create edges to a cluster.")
  11962. }
  11963. else {
  11964. this._createEdge(connectFromId,node.id);
  11965. this._createManipulatorBar();
  11966. }
  11967. }
  11968. this._unselectAll();
  11969. }
  11970. },
  11971. /**
  11972. * Adds a node on the specified location
  11973. */
  11974. _addNode : function() {
  11975. if (this._selectionIsEmpty() && this.editMode == true) {
  11976. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11977. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  11978. if (this.triggerFunctions.add) {
  11979. if (this.triggerFunctions.add.length == 2) {
  11980. var me = this;
  11981. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11982. me.nodesData.add(finalizedData);
  11983. me._createManipulatorBar();
  11984. me.moving = true;
  11985. me.start();
  11986. });
  11987. }
  11988. else {
  11989. alert(this.constants.labels['addError']);
  11990. this._createManipulatorBar();
  11991. this.moving = true;
  11992. this.start();
  11993. }
  11994. }
  11995. else {
  11996. this.nodesData.add(defaultData);
  11997. this._createManipulatorBar();
  11998. this.moving = true;
  11999. this.start();
  12000. }
  12001. }
  12002. },
  12003. /**
  12004. * connect two nodes with a new edge.
  12005. *
  12006. * @private
  12007. */
  12008. _createEdge : function(sourceNodeId,targetNodeId) {
  12009. if (this.editMode == true) {
  12010. var defaultData = {from:sourceNodeId, to:targetNodeId};
  12011. if (this.triggerFunctions.connect) {
  12012. if (this.triggerFunctions.connect.length == 2) {
  12013. var me = this;
  12014. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  12015. me.edgesData.add(finalizedData);
  12016. me.moving = true;
  12017. me.start();
  12018. });
  12019. }
  12020. else {
  12021. alert(this.constants.labels["linkError"]);
  12022. this.moving = true;
  12023. this.start();
  12024. }
  12025. }
  12026. else {
  12027. this.edgesData.add(defaultData);
  12028. this.moving = true;
  12029. this.start();
  12030. }
  12031. }
  12032. },
  12033. /**
  12034. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  12035. *
  12036. * @private
  12037. */
  12038. _editNode : function() {
  12039. if (this.triggerFunctions.edit && this.editMode == true) {
  12040. var node = this._getSelectedNode();
  12041. var data = {id:node.id,
  12042. label: node.label,
  12043. group: node.group,
  12044. shape: node.shape,
  12045. color: {
  12046. background:node.color.background,
  12047. border:node.color.border,
  12048. highlight: {
  12049. background:node.color.highlight.background,
  12050. border:node.color.highlight.border
  12051. }
  12052. }};
  12053. if (this.triggerFunctions.edit.length == 2) {
  12054. var me = this;
  12055. this.triggerFunctions.edit(data, function (finalizedData) {
  12056. me.nodesData.update(finalizedData);
  12057. me._createManipulatorBar();
  12058. me.moving = true;
  12059. me.start();
  12060. });
  12061. }
  12062. else {
  12063. alert(this.constants.labels["editError"]);
  12064. }
  12065. }
  12066. else {
  12067. alert(this.constants.labels["editBoundError"]);
  12068. }
  12069. },
  12070. /**
  12071. * delete everything in the selection
  12072. *
  12073. * @private
  12074. */
  12075. _deleteSelected : function() {
  12076. if (!this._selectionIsEmpty() && this.editMode == true) {
  12077. if (!this._clusterInSelection()) {
  12078. var selectedNodes = this.getSelectedNodes();
  12079. var selectedEdges = this.getSelectedEdges();
  12080. if (this.triggerFunctions.del) {
  12081. var me = this;
  12082. var data = {nodes: selectedNodes, edges: selectedEdges};
  12083. if (this.triggerFunctions.del.length = 2) {
  12084. this.triggerFunctions.del(data, function (finalizedData) {
  12085. me.edgesData.remove(finalizedData.edges);
  12086. me.nodesData.remove(finalizedData.nodes);
  12087. me._unselectAll();
  12088. me.moving = true;
  12089. me.start();
  12090. });
  12091. }
  12092. else {
  12093. alert(this.constants.labels["deleteError"])
  12094. }
  12095. }
  12096. else {
  12097. this.edgesData.remove(selectedEdges);
  12098. this.nodesData.remove(selectedNodes);
  12099. this._unselectAll();
  12100. this.moving = true;
  12101. this.start();
  12102. }
  12103. }
  12104. else {
  12105. alert(this.constants.labels["deleteClusterError"]);
  12106. }
  12107. }
  12108. }
  12109. };
  12110. /**
  12111. * Creation of the SectorMixin var.
  12112. *
  12113. * This contains all the functions the Graph object can use to employ the sector system.
  12114. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  12115. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  12116. *
  12117. * Alex de Mulder
  12118. * 21-01-2013
  12119. */
  12120. var SectorMixin = {
  12121. /**
  12122. * This function is only called by the setData function of the Graph object.
  12123. * This loads the global references into the active sector. This initializes the sector.
  12124. *
  12125. * @private
  12126. */
  12127. _putDataInSector : function() {
  12128. this.sectors["active"][this._sector()].nodes = this.nodes;
  12129. this.sectors["active"][this._sector()].edges = this.edges;
  12130. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  12131. },
  12132. /**
  12133. * /**
  12134. * This function sets the global references to nodes, edges and nodeIndices back to
  12135. * those of the supplied (active) sector. If a type is defined, do the specific type
  12136. *
  12137. * @param {String} sectorId
  12138. * @param {String} [sectorType] | "active" or "frozen"
  12139. * @private
  12140. */
  12141. _switchToSector : function(sectorId, sectorType) {
  12142. if (sectorType === undefined || sectorType == "active") {
  12143. this._switchToActiveSector(sectorId);
  12144. }
  12145. else {
  12146. this._switchToFrozenSector(sectorId);
  12147. }
  12148. },
  12149. /**
  12150. * This function sets the global references to nodes, edges and nodeIndices back to
  12151. * those of the supplied active sector.
  12152. *
  12153. * @param sectorId
  12154. * @private
  12155. */
  12156. _switchToActiveSector : function(sectorId) {
  12157. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  12158. this.nodes = this.sectors["active"][sectorId]["nodes"];
  12159. this.edges = this.sectors["active"][sectorId]["edges"];
  12160. },
  12161. /**
  12162. * This function sets the global references to nodes, edges and nodeIndices back to
  12163. * those of the supplied active sector.
  12164. *
  12165. * @param sectorId
  12166. * @private
  12167. */
  12168. _switchToSupportSector : function() {
  12169. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  12170. this.nodes = this.sectors["support"]["nodes"];
  12171. this.edges = this.sectors["support"]["edges"];
  12172. },
  12173. /**
  12174. * This function sets the global references to nodes, edges and nodeIndices back to
  12175. * those of the supplied frozen sector.
  12176. *
  12177. * @param sectorId
  12178. * @private
  12179. */
  12180. _switchToFrozenSector : function(sectorId) {
  12181. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  12182. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  12183. this.edges = this.sectors["frozen"][sectorId]["edges"];
  12184. },
  12185. /**
  12186. * This function sets the global references to nodes, edges and nodeIndices back to
  12187. * those of the currently active sector.
  12188. *
  12189. * @private
  12190. */
  12191. _loadLatestSector : function() {
  12192. this._switchToSector(this._sector());
  12193. },
  12194. /**
  12195. * This function returns the currently active sector Id
  12196. *
  12197. * @returns {String}
  12198. * @private
  12199. */
  12200. _sector : function() {
  12201. return this.activeSector[this.activeSector.length-1];
  12202. },
  12203. /**
  12204. * This function returns the previously active sector Id
  12205. *
  12206. * @returns {String}
  12207. * @private
  12208. */
  12209. _previousSector : function() {
  12210. if (this.activeSector.length > 1) {
  12211. return this.activeSector[this.activeSector.length-2];
  12212. }
  12213. else {
  12214. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  12215. }
  12216. },
  12217. /**
  12218. * We add the active sector at the end of the this.activeSector array
  12219. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  12220. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  12221. *
  12222. * @param newId
  12223. * @private
  12224. */
  12225. _setActiveSector : function(newId) {
  12226. this.activeSector.push(newId);
  12227. },
  12228. /**
  12229. * We remove the currently active sector id from the active sector stack. This happens when
  12230. * we reactivate the previously active sector
  12231. *
  12232. * @private
  12233. */
  12234. _forgetLastSector : function() {
  12235. this.activeSector.pop();
  12236. },
  12237. /**
  12238. * This function creates a new active sector with the supplied newId. This newId
  12239. * is the expanding node id.
  12240. *
  12241. * @param {String} newId | Id of the new active sector
  12242. * @private
  12243. */
  12244. _createNewSector : function(newId) {
  12245. // create the new sector
  12246. this.sectors["active"][newId] = {"nodes":{},
  12247. "edges":{},
  12248. "nodeIndices":[],
  12249. "formationScale": this.scale,
  12250. "drawingNode": undefined};
  12251. // create the new sector render node. This gives visual feedback that you are in a new sector.
  12252. this.sectors["active"][newId]['drawingNode'] = new Node(
  12253. {id:newId,
  12254. color: {
  12255. background: "#eaefef",
  12256. border: "495c5e"
  12257. }
  12258. },{},{},this.constants);
  12259. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  12260. },
  12261. /**
  12262. * This function removes the currently active sector. This is called when we create a new
  12263. * active sector.
  12264. *
  12265. * @param {String} sectorId | Id of the active sector that will be removed
  12266. * @private
  12267. */
  12268. _deleteActiveSector : function(sectorId) {
  12269. delete this.sectors["active"][sectorId];
  12270. },
  12271. /**
  12272. * This function removes the currently active sector. This is called when we reactivate
  12273. * the previously active sector.
  12274. *
  12275. * @param {String} sectorId | Id of the active sector that will be removed
  12276. * @private
  12277. */
  12278. _deleteFrozenSector : function(sectorId) {
  12279. delete this.sectors["frozen"][sectorId];
  12280. },
  12281. /**
  12282. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  12283. * We copy the references, then delete the active entree.
  12284. *
  12285. * @param sectorId
  12286. * @private
  12287. */
  12288. _freezeSector : function(sectorId) {
  12289. // we move the set references from the active to the frozen stack.
  12290. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  12291. // we have moved the sector data into the frozen set, we now remove it from the active set
  12292. this._deleteActiveSector(sectorId);
  12293. },
  12294. /**
  12295. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  12296. * object to the "active" object.
  12297. *
  12298. * @param sectorId
  12299. * @private
  12300. */
  12301. _activateSector : function(sectorId) {
  12302. // we move the set references from the frozen to the active stack.
  12303. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  12304. // we have moved the sector data into the active set, we now remove it from the frozen stack
  12305. this._deleteFrozenSector(sectorId);
  12306. },
  12307. /**
  12308. * This function merges the data from the currently active sector with a frozen sector. This is used
  12309. * in the process of reverting back to the previously active sector.
  12310. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  12311. * upon the creation of a new active sector.
  12312. *
  12313. * @param sectorId
  12314. * @private
  12315. */
  12316. _mergeThisWithFrozen : function(sectorId) {
  12317. // copy all nodes
  12318. for (var nodeId in this.nodes) {
  12319. if (this.nodes.hasOwnProperty(nodeId)) {
  12320. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  12321. }
  12322. }
  12323. // copy all edges (if not fully clustered, else there are no edges)
  12324. for (var edgeId in this.edges) {
  12325. if (this.edges.hasOwnProperty(edgeId)) {
  12326. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  12327. }
  12328. }
  12329. // merge the nodeIndices
  12330. for (var i = 0; i < this.nodeIndices.length; i++) {
  12331. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  12332. }
  12333. },
  12334. /**
  12335. * This clusters the sector to one cluster. It was a single cluster before this process started so
  12336. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  12337. *
  12338. * @private
  12339. */
  12340. _collapseThisToSingleCluster : function() {
  12341. this.clusterToFit(1,false);
  12342. },
  12343. /**
  12344. * We create a new active sector from the node that we want to open.
  12345. *
  12346. * @param node
  12347. * @private
  12348. */
  12349. _addSector : function(node) {
  12350. // this is the currently active sector
  12351. var sector = this._sector();
  12352. // // this should allow me to select nodes from a frozen set.
  12353. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  12354. // console.log("the node is part of the active sector");
  12355. // }
  12356. // else {
  12357. // console.log("I dont know what the fuck happened!!");
  12358. // }
  12359. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  12360. delete this.nodes[node.id];
  12361. var unqiueIdentifier = util.randomUUID();
  12362. // we fully freeze the currently active sector
  12363. this._freezeSector(sector);
  12364. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  12365. this._createNewSector(unqiueIdentifier);
  12366. // we add the active sector to the sectors array to be able to revert these steps later on
  12367. this._setActiveSector(unqiueIdentifier);
  12368. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  12369. this._switchToSector(this._sector());
  12370. // finally we add the node we removed from our previous active sector to the new active sector
  12371. this.nodes[node.id] = node;
  12372. },
  12373. /**
  12374. * We close the sector that is currently open and revert back to the one before.
  12375. * If the active sector is the "default" sector, nothing happens.
  12376. *
  12377. * @private
  12378. */
  12379. _collapseSector : function() {
  12380. // the currently active sector
  12381. var sector = this._sector();
  12382. // we cannot collapse the default sector
  12383. if (sector != "default") {
  12384. if ((this.nodeIndices.length == 1) ||
  12385. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  12386. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  12387. var previousSector = this._previousSector();
  12388. // we collapse the sector back to a single cluster
  12389. this._collapseThisToSingleCluster();
  12390. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  12391. // This previous sector is the one we will reactivate
  12392. this._mergeThisWithFrozen(previousSector);
  12393. // the previously active (frozen) sector now has all the data from the currently active sector.
  12394. // we can now delete the active sector.
  12395. this._deleteActiveSector(sector);
  12396. // we activate the previously active (and currently frozen) sector.
  12397. this._activateSector(previousSector);
  12398. // we load the references from the newly active sector into the global references
  12399. this._switchToSector(previousSector);
  12400. // we forget the previously active sector because we reverted to the one before
  12401. this._forgetLastSector();
  12402. // finally, we update the node index list.
  12403. this._updateNodeIndexList();
  12404. // we refresh the list with calulation nodes and calculation node indices.
  12405. this._updateCalculationNodes();
  12406. }
  12407. }
  12408. },
  12409. /**
  12410. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  12411. *
  12412. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  12413. * | we dont pass the function itself because then the "this" is the window object
  12414. * | instead of the Graph object
  12415. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12416. * @private
  12417. */
  12418. _doInAllActiveSectors : function(runFunction,argument) {
  12419. if (argument === undefined) {
  12420. for (var sector in this.sectors["active"]) {
  12421. if (this.sectors["active"].hasOwnProperty(sector)) {
  12422. // switch the global references to those of this sector
  12423. this._switchToActiveSector(sector);
  12424. this[runFunction]();
  12425. }
  12426. }
  12427. }
  12428. else {
  12429. for (var sector in this.sectors["active"]) {
  12430. if (this.sectors["active"].hasOwnProperty(sector)) {
  12431. // switch the global references to those of this sector
  12432. this._switchToActiveSector(sector);
  12433. var args = Array.prototype.splice.call(arguments, 1);
  12434. if (args.length > 1) {
  12435. this[runFunction](args[0],args[1]);
  12436. }
  12437. else {
  12438. this[runFunction](argument);
  12439. }
  12440. }
  12441. }
  12442. }
  12443. // we revert the global references back to our active sector
  12444. this._loadLatestSector();
  12445. },
  12446. /**
  12447. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  12448. *
  12449. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  12450. * | we dont pass the function itself because then the "this" is the window object
  12451. * | instead of the Graph object
  12452. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12453. * @private
  12454. */
  12455. _doInSupportSector : function(runFunction,argument) {
  12456. if (argument === undefined) {
  12457. this._switchToSupportSector();
  12458. this[runFunction]();
  12459. }
  12460. else {
  12461. this._switchToSupportSector();
  12462. var args = Array.prototype.splice.call(arguments, 1);
  12463. if (args.length > 1) {
  12464. this[runFunction](args[0],args[1]);
  12465. }
  12466. else {
  12467. this[runFunction](argument);
  12468. }
  12469. }
  12470. // we revert the global references back to our active sector
  12471. this._loadLatestSector();
  12472. },
  12473. /**
  12474. * This runs a function in all frozen sectors. This is used in the _redraw().
  12475. *
  12476. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  12477. * | we don't pass the function itself because then the "this" is the window object
  12478. * | instead of the Graph object
  12479. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12480. * @private
  12481. */
  12482. _doInAllFrozenSectors : function(runFunction,argument) {
  12483. if (argument === undefined) {
  12484. for (var sector in this.sectors["frozen"]) {
  12485. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  12486. // switch the global references to those of this sector
  12487. this._switchToFrozenSector(sector);
  12488. this[runFunction]();
  12489. }
  12490. }
  12491. }
  12492. else {
  12493. for (var sector in this.sectors["frozen"]) {
  12494. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  12495. // switch the global references to those of this sector
  12496. this._switchToFrozenSector(sector);
  12497. var args = Array.prototype.splice.call(arguments, 1);
  12498. if (args.length > 1) {
  12499. this[runFunction](args[0],args[1]);
  12500. }
  12501. else {
  12502. this[runFunction](argument);
  12503. }
  12504. }
  12505. }
  12506. }
  12507. this._loadLatestSector();
  12508. },
  12509. /**
  12510. * This runs a function in all sectors. This is used in the _redraw().
  12511. *
  12512. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  12513. * | we don't pass the function itself because then the "this" is the window object
  12514. * | instead of the Graph object
  12515. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12516. * @private
  12517. */
  12518. _doInAllSectors : function(runFunction,argument) {
  12519. var args = Array.prototype.splice.call(arguments, 1);
  12520. if (argument === undefined) {
  12521. this._doInAllActiveSectors(runFunction);
  12522. this._doInAllFrozenSectors(runFunction);
  12523. }
  12524. else {
  12525. if (args.length > 1) {
  12526. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  12527. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  12528. }
  12529. else {
  12530. this._doInAllActiveSectors(runFunction,argument);
  12531. this._doInAllFrozenSectors(runFunction,argument);
  12532. }
  12533. }
  12534. },
  12535. /**
  12536. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  12537. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  12538. *
  12539. * @private
  12540. */
  12541. _clearNodeIndexList : function() {
  12542. var sector = this._sector();
  12543. this.sectors["active"][sector]["nodeIndices"] = [];
  12544. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  12545. },
  12546. /**
  12547. * Draw the encompassing sector node
  12548. *
  12549. * @param ctx
  12550. * @param sectorType
  12551. * @private
  12552. */
  12553. _drawSectorNodes : function(ctx,sectorType) {
  12554. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  12555. for (var sector in this.sectors[sectorType]) {
  12556. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  12557. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  12558. this._switchToSector(sector,sectorType);
  12559. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  12560. for (var nodeId in this.nodes) {
  12561. if (this.nodes.hasOwnProperty(nodeId)) {
  12562. node = this.nodes[nodeId];
  12563. node.resize(ctx);
  12564. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  12565. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  12566. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  12567. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  12568. }
  12569. }
  12570. node = this.sectors[sectorType][sector]["drawingNode"];
  12571. node.x = 0.5 * (maxX + minX);
  12572. node.y = 0.5 * (maxY + minY);
  12573. node.width = 2 * (node.x - minX);
  12574. node.height = 2 * (node.y - minY);
  12575. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  12576. node.setScale(this.scale);
  12577. node._drawCircle(ctx);
  12578. }
  12579. }
  12580. }
  12581. },
  12582. _drawAllSectorNodes : function(ctx) {
  12583. this._drawSectorNodes(ctx,"frozen");
  12584. this._drawSectorNodes(ctx,"active");
  12585. this._loadLatestSector();
  12586. }
  12587. };
  12588. /**
  12589. * Creation of the ClusterMixin var.
  12590. *
  12591. * This contains all the functions the Graph object can use to employ clustering
  12592. *
  12593. * Alex de Mulder
  12594. * 21-01-2013
  12595. */
  12596. var ClusterMixin = {
  12597. /**
  12598. * This is only called in the constructor of the graph object
  12599. *
  12600. */
  12601. startWithClustering : function() {
  12602. // cluster if the data set is big
  12603. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  12604. // updates the lables after clustering
  12605. this.updateLabels();
  12606. // this is called here because if clusterin is disabled, the start and stabilize are called in
  12607. // the setData function.
  12608. if (this.stabilize) {
  12609. this._stabilize();
  12610. }
  12611. this.start();
  12612. },
  12613. /**
  12614. * This function clusters until the initialMaxNodes has been reached
  12615. *
  12616. * @param {Number} maxNumberOfNodes
  12617. * @param {Boolean} reposition
  12618. */
  12619. clusterToFit : function(maxNumberOfNodes, reposition) {
  12620. var numberOfNodes = this.nodeIndices.length;
  12621. var maxLevels = 50;
  12622. var level = 0;
  12623. // we first cluster the hubs, then we pull in the outliers, repeat
  12624. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  12625. if (level % 3 == 0) {
  12626. this.forceAggregateHubs(true);
  12627. this.normalizeClusterLevels();
  12628. }
  12629. else {
  12630. this.increaseClusterLevel(); // this also includes a cluster normalization
  12631. }
  12632. numberOfNodes = this.nodeIndices.length;
  12633. level += 1;
  12634. }
  12635. // after the clustering we reposition the nodes to reduce the initial chaos
  12636. if (level > 0 && reposition == true) {
  12637. this.repositionNodes();
  12638. }
  12639. this._updateCalculationNodes();
  12640. },
  12641. /**
  12642. * This function can be called to open up a specific cluster. It is only called by
  12643. * It will unpack the cluster back one level.
  12644. *
  12645. * @param node | Node object: cluster to open.
  12646. */
  12647. openCluster : function(node) {
  12648. var isMovingBeforeClustering = this.moving;
  12649. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  12650. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  12651. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  12652. this._addSector(node);
  12653. var level = 0;
  12654. // we decluster until we reach a decent number of nodes
  12655. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  12656. this.decreaseClusterLevel();
  12657. level += 1;
  12658. }
  12659. }
  12660. else {
  12661. this._expandClusterNode(node,false,true);
  12662. // update the index list, dynamic edges and labels
  12663. this._updateNodeIndexList();
  12664. this._updateDynamicEdges();
  12665. this._updateCalculationNodes();
  12666. this.updateLabels();
  12667. }
  12668. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12669. if (this.moving != isMovingBeforeClustering) {
  12670. this.start();
  12671. }
  12672. },
  12673. /**
  12674. * This calls the updateClustes with default arguments
  12675. */
  12676. updateClustersDefault : function() {
  12677. if (this.constants.clustering.enabled == true) {
  12678. this.updateClusters(0,false,false);
  12679. }
  12680. },
  12681. /**
  12682. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  12683. * be clustered with their connected node. This can be repeated as many times as needed.
  12684. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  12685. */
  12686. increaseClusterLevel : function() {
  12687. this.updateClusters(-1,false,true);
  12688. },
  12689. /**
  12690. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  12691. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  12692. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  12693. */
  12694. decreaseClusterLevel : function() {
  12695. this.updateClusters(1,false,true);
  12696. },
  12697. /**
  12698. * This is the main clustering function. It clusters and declusters on zoom or forced
  12699. * This function clusters on zoom, it can be called with a predefined zoom direction
  12700. * If out, check if we can form clusters, if in, check if we can open clusters.
  12701. * This function is only called from _zoom()
  12702. *
  12703. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  12704. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  12705. * @param {Boolean} force | enabled or disable forcing
  12706. * @param {Boolean} doNotStart | if true do not call start
  12707. *
  12708. */
  12709. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  12710. var isMovingBeforeClustering = this.moving;
  12711. var amountOfNodes = this.nodeIndices.length;
  12712. // on zoom out collapse the sector if the scale is at the level the sector was made
  12713. if (this.previousScale > this.scale && zoomDirection == 0) {
  12714. this._collapseSector();
  12715. }
  12716. // check if we zoom in or out
  12717. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12718. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  12719. // outer nodes determines if it is being clustered
  12720. this._formClusters(force);
  12721. }
  12722. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  12723. if (force == true) {
  12724. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  12725. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  12726. this._openClusters(recursive,force);
  12727. }
  12728. else {
  12729. // if a cluster takes up a set percentage of the active window
  12730. this._openClustersBySize();
  12731. }
  12732. }
  12733. this._updateNodeIndexList();
  12734. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  12735. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  12736. this._aggregateHubs(force);
  12737. this._updateNodeIndexList();
  12738. }
  12739. // we now reduce chains.
  12740. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12741. this.handleChains();
  12742. this._updateNodeIndexList();
  12743. }
  12744. this.previousScale = this.scale;
  12745. // rest of the update the index list, dynamic edges and labels
  12746. this._updateDynamicEdges();
  12747. this.updateLabels();
  12748. // if a cluster was formed, we increase the clusterSession
  12749. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  12750. this.clusterSession += 1;
  12751. // if clusters have been made, we normalize the cluster level
  12752. this.normalizeClusterLevels();
  12753. }
  12754. if (doNotStart == false || doNotStart === undefined) {
  12755. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12756. if (this.moving != isMovingBeforeClustering) {
  12757. this.start();
  12758. }
  12759. }
  12760. this._updateCalculationNodes();
  12761. },
  12762. /**
  12763. * This function handles the chains. It is called on every updateClusters().
  12764. */
  12765. handleChains : function() {
  12766. // after clustering we check how many chains there are
  12767. var chainPercentage = this._getChainFraction();
  12768. if (chainPercentage > this.constants.clustering.chainThreshold) {
  12769. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  12770. }
  12771. },
  12772. /**
  12773. * this functions starts clustering by hubs
  12774. * The minimum hub threshold is set globally
  12775. *
  12776. * @private
  12777. */
  12778. _aggregateHubs : function(force) {
  12779. this._getHubSize();
  12780. this._formClustersByHub(force,false);
  12781. },
  12782. /**
  12783. * This function is fired by keypress. It forces hubs to form.
  12784. *
  12785. */
  12786. forceAggregateHubs : function(doNotStart) {
  12787. var isMovingBeforeClustering = this.moving;
  12788. var amountOfNodes = this.nodeIndices.length;
  12789. this._aggregateHubs(true);
  12790. // update the index list, dynamic edges and labels
  12791. this._updateNodeIndexList();
  12792. this._updateDynamicEdges();
  12793. this.updateLabels();
  12794. // if a cluster was formed, we increase the clusterSession
  12795. if (this.nodeIndices.length != amountOfNodes) {
  12796. this.clusterSession += 1;
  12797. }
  12798. if (doNotStart == false || doNotStart === undefined) {
  12799. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12800. if (this.moving != isMovingBeforeClustering) {
  12801. this.start();
  12802. }
  12803. }
  12804. },
  12805. /**
  12806. * If a cluster takes up more than a set percentage of the screen, open the cluster
  12807. *
  12808. * @private
  12809. */
  12810. _openClustersBySize : function() {
  12811. for (var nodeId in this.nodes) {
  12812. if (this.nodes.hasOwnProperty(nodeId)) {
  12813. var node = this.nodes[nodeId];
  12814. if (node.inView() == true) {
  12815. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  12816. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  12817. this.openCluster(node);
  12818. }
  12819. }
  12820. }
  12821. }
  12822. },
  12823. /**
  12824. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  12825. * has to be opened based on the current zoom level.
  12826. *
  12827. * @private
  12828. */
  12829. _openClusters : function(recursive,force) {
  12830. for (var i = 0; i < this.nodeIndices.length; i++) {
  12831. var node = this.nodes[this.nodeIndices[i]];
  12832. this._expandClusterNode(node,recursive,force);
  12833. this._updateCalculationNodes();
  12834. }
  12835. },
  12836. /**
  12837. * This function checks if a node has to be opened. This is done by checking the zoom level.
  12838. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  12839. * This recursive behaviour is optional and can be set by the recursive argument.
  12840. *
  12841. * @param {Node} parentNode | to check for cluster and expand
  12842. * @param {Boolean} recursive | enabled or disable recursive calling
  12843. * @param {Boolean} force | enabled or disable forcing
  12844. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  12845. * @private
  12846. */
  12847. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  12848. // first check if node is a cluster
  12849. if (parentNode.clusterSize > 1) {
  12850. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  12851. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  12852. openAll = true;
  12853. }
  12854. recursive = openAll ? true : recursive;
  12855. // if the last child has been added on a smaller scale than current scale decluster
  12856. if (parentNode.formationScale < this.scale || force == true) {
  12857. // we will check if any of the contained child nodes should be removed from the cluster
  12858. for (var containedNodeId in parentNode.containedNodes) {
  12859. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  12860. var childNode = parentNode.containedNodes[containedNodeId];
  12861. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  12862. // the largest cluster is the one that comes from outside
  12863. if (force == true) {
  12864. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  12865. || openAll) {
  12866. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12867. }
  12868. }
  12869. else {
  12870. if (this._nodeInActiveArea(parentNode)) {
  12871. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12872. }
  12873. }
  12874. }
  12875. }
  12876. }
  12877. }
  12878. },
  12879. /**
  12880. * ONLY CALLED FROM _expandClusterNode
  12881. *
  12882. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  12883. * the child node from the parent contained_node object and put it back into the global nodes object.
  12884. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  12885. *
  12886. * @param {Node} parentNode | the parent node
  12887. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  12888. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  12889. * With force and recursive both true, the entire cluster is unpacked
  12890. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  12891. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  12892. * @private
  12893. */
  12894. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  12895. var childNode = parentNode.containedNodes[containedNodeId];
  12896. // if child node has been added on smaller scale than current, kick out
  12897. if (childNode.formationScale < this.scale || force == true) {
  12898. // unselect all selected items
  12899. this._unselectAll();
  12900. // put the child node back in the global nodes object
  12901. this.nodes[containedNodeId] = childNode;
  12902. // release the contained edges from this childNode back into the global edges
  12903. this._releaseContainedEdges(parentNode,childNode);
  12904. // reconnect rerouted edges to the childNode
  12905. this._connectEdgeBackToChild(parentNode,childNode);
  12906. // validate all edges in dynamicEdges
  12907. this._validateEdges(parentNode);
  12908. // undo the changes from the clustering operation on the parent node
  12909. parentNode.mass -= childNode.mass;
  12910. parentNode.clusterSize -= childNode.clusterSize;
  12911. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12912. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12913. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12914. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12915. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12916. // remove node from the list
  12917. delete parentNode.containedNodes[containedNodeId];
  12918. // check if there are other childs with this clusterSession in the parent.
  12919. var othersPresent = false;
  12920. for (var childNodeId in parentNode.containedNodes) {
  12921. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12922. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12923. othersPresent = true;
  12924. break;
  12925. }
  12926. }
  12927. }
  12928. // if there are no others, remove the cluster session from the list
  12929. if (othersPresent == false) {
  12930. parentNode.clusterSessions.pop();
  12931. }
  12932. this._repositionBezierNodes(childNode);
  12933. // this._repositionBezierNodes(parentNode);
  12934. // remove the clusterSession from the child node
  12935. childNode.clusterSession = 0;
  12936. // recalculate the size of the node on the next time the node is rendered
  12937. parentNode.clearSizeCache();
  12938. // restart the simulation to reorganise all nodes
  12939. this.moving = true;
  12940. }
  12941. // check if a further expansion step is possible if recursivity is enabled
  12942. if (recursive == true) {
  12943. this._expandClusterNode(childNode,recursive,force,openAll);
  12944. }
  12945. },
  12946. /**
  12947. * position the bezier nodes at the center of the edges
  12948. *
  12949. * @param node
  12950. * @private
  12951. */
  12952. _repositionBezierNodes : function(node) {
  12953. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12954. node.dynamicEdges[i].positionBezierNode();
  12955. }
  12956. },
  12957. /**
  12958. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12959. * This function is called only from updateClusters()
  12960. * forceLevelCollapse ignores the length of the edge and collapses one level
  12961. * This means that a node with only one edge will be clustered with its connected node
  12962. *
  12963. * @private
  12964. * @param {Boolean} force
  12965. */
  12966. _formClusters : function(force) {
  12967. if (force == false) {
  12968. this._formClustersByZoom();
  12969. }
  12970. else {
  12971. this._forceClustersByZoom();
  12972. }
  12973. },
  12974. /**
  12975. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12976. *
  12977. * @private
  12978. */
  12979. _formClustersByZoom : function() {
  12980. var dx,dy,length,
  12981. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12982. // check if any edges are shorter than minLength and start the clustering
  12983. // the clustering favours the node with the larger mass
  12984. for (var edgeId in this.edges) {
  12985. if (this.edges.hasOwnProperty(edgeId)) {
  12986. var edge = this.edges[edgeId];
  12987. if (edge.connected) {
  12988. if (edge.toId != edge.fromId) {
  12989. dx = (edge.to.x - edge.from.x);
  12990. dy = (edge.to.y - edge.from.y);
  12991. length = Math.sqrt(dx * dx + dy * dy);
  12992. if (length < minLength) {
  12993. // first check which node is larger
  12994. var parentNode = edge.from;
  12995. var childNode = edge.to;
  12996. if (edge.to.mass > edge.from.mass) {
  12997. parentNode = edge.to;
  12998. childNode = edge.from;
  12999. }
  13000. if (childNode.dynamicEdgesLength == 1) {
  13001. this._addToCluster(parentNode,childNode,false);
  13002. }
  13003. else if (parentNode.dynamicEdgesLength == 1) {
  13004. this._addToCluster(childNode,parentNode,false);
  13005. }
  13006. }
  13007. }
  13008. }
  13009. }
  13010. }
  13011. },
  13012. /**
  13013. * This function forces the graph to cluster all nodes with only one connecting edge to their
  13014. * connected node.
  13015. *
  13016. * @private
  13017. */
  13018. _forceClustersByZoom : function() {
  13019. for (var nodeId in this.nodes) {
  13020. // another node could have absorbed this child.
  13021. if (this.nodes.hasOwnProperty(nodeId)) {
  13022. var childNode = this.nodes[nodeId];
  13023. // the edges can be swallowed by another decrease
  13024. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  13025. var edge = childNode.dynamicEdges[0];
  13026. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  13027. // group to the largest node
  13028. if (childNode.id != parentNode.id) {
  13029. if (parentNode.mass > childNode.mass) {
  13030. this._addToCluster(parentNode,childNode,true);
  13031. }
  13032. else {
  13033. this._addToCluster(childNode,parentNode,true);
  13034. }
  13035. }
  13036. }
  13037. }
  13038. }
  13039. },
  13040. /**
  13041. * To keep the nodes of roughly equal size we normalize the cluster levels.
  13042. * This function clusters a node to its smallest connected neighbour.
  13043. *
  13044. * @param node
  13045. * @private
  13046. */
  13047. _clusterToSmallestNeighbour : function(node) {
  13048. var smallestNeighbour = -1;
  13049. var smallestNeighbourNode = null;
  13050. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13051. if (node.dynamicEdges[i] !== undefined) {
  13052. var neighbour = null;
  13053. if (node.dynamicEdges[i].fromId != node.id) {
  13054. neighbour = node.dynamicEdges[i].from;
  13055. }
  13056. else if (node.dynamicEdges[i].toId != node.id) {
  13057. neighbour = node.dynamicEdges[i].to;
  13058. }
  13059. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  13060. smallestNeighbour = neighbour.clusterSessions.length;
  13061. smallestNeighbourNode = neighbour;
  13062. }
  13063. }
  13064. }
  13065. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  13066. this._addToCluster(neighbour, node, true);
  13067. }
  13068. },
  13069. /**
  13070. * This function forms clusters from hubs, it loops over all nodes
  13071. *
  13072. * @param {Boolean} force | Disregard zoom level
  13073. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  13074. * @private
  13075. */
  13076. _formClustersByHub : function(force, onlyEqual) {
  13077. // we loop over all nodes in the list
  13078. for (var nodeId in this.nodes) {
  13079. // we check if it is still available since it can be used by the clustering in this loop
  13080. if (this.nodes.hasOwnProperty(nodeId)) {
  13081. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  13082. }
  13083. }
  13084. },
  13085. /**
  13086. * This function forms a cluster from a specific preselected hub node
  13087. *
  13088. * @param {Node} hubNode | the node we will cluster as a hub
  13089. * @param {Boolean} force | Disregard zoom level
  13090. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  13091. * @param {Number} [absorptionSizeOffset] |
  13092. * @private
  13093. */
  13094. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  13095. if (absorptionSizeOffset === undefined) {
  13096. absorptionSizeOffset = 0;
  13097. }
  13098. // we decide if the node is a hub
  13099. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  13100. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  13101. // initialize variables
  13102. var dx,dy,length;
  13103. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  13104. var allowCluster = false;
  13105. // we create a list of edges because the dynamicEdges change over the course of this loop
  13106. var edgesIdarray = [];
  13107. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  13108. for (var j = 0; j < amountOfInitialEdges; j++) {
  13109. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  13110. }
  13111. // if the hub clustering is not forces, we check if one of the edges connected
  13112. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  13113. if (force == false) {
  13114. allowCluster = false;
  13115. for (j = 0; j < amountOfInitialEdges; j++) {
  13116. var edge = this.edges[edgesIdarray[j]];
  13117. if (edge !== undefined) {
  13118. if (edge.connected) {
  13119. if (edge.toId != edge.fromId) {
  13120. dx = (edge.to.x - edge.from.x);
  13121. dy = (edge.to.y - edge.from.y);
  13122. length = Math.sqrt(dx * dx + dy * dy);
  13123. if (length < minLength) {
  13124. allowCluster = true;
  13125. break;
  13126. }
  13127. }
  13128. }
  13129. }
  13130. }
  13131. }
  13132. // start the clustering if allowed
  13133. if ((!force && allowCluster) || force) {
  13134. // we loop over all edges INITIALLY connected to this hub
  13135. for (j = 0; j < amountOfInitialEdges; j++) {
  13136. edge = this.edges[edgesIdarray[j]];
  13137. // the edge can be clustered by this function in a previous loop
  13138. if (edge !== undefined) {
  13139. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  13140. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  13141. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  13142. (childNode.id != hubNode.id)) {
  13143. this._addToCluster(hubNode,childNode,force);
  13144. }
  13145. }
  13146. }
  13147. }
  13148. }
  13149. },
  13150. /**
  13151. * This function adds the child node to the parent node, creating a cluster if it is not already.
  13152. *
  13153. * @param {Node} parentNode | this is the node that will house the child node
  13154. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  13155. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  13156. * @private
  13157. */
  13158. _addToCluster : function(parentNode, childNode, force) {
  13159. // join child node in the parent node
  13160. parentNode.containedNodes[childNode.id] = childNode;
  13161. // manage all the edges connected to the child and parent nodes
  13162. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  13163. var edge = childNode.dynamicEdges[i];
  13164. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  13165. this._addToContainedEdges(parentNode,childNode,edge);
  13166. }
  13167. else {
  13168. this._connectEdgeToCluster(parentNode,childNode,edge);
  13169. }
  13170. }
  13171. // a contained node has no dynamic edges.
  13172. childNode.dynamicEdges = [];
  13173. // remove circular edges from clusters
  13174. this._containCircularEdgesFromNode(parentNode,childNode);
  13175. // remove the childNode from the global nodes object
  13176. delete this.nodes[childNode.id];
  13177. // update the properties of the child and parent
  13178. var massBefore = parentNode.mass;
  13179. childNode.clusterSession = this.clusterSession;
  13180. parentNode.mass += childNode.mass;
  13181. parentNode.clusterSize += childNode.clusterSize;
  13182. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  13183. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  13184. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  13185. parentNode.clusterSessions.push(this.clusterSession);
  13186. }
  13187. // forced clusters only open from screen size and double tap
  13188. if (force == true) {
  13189. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  13190. parentNode.formationScale = 0;
  13191. }
  13192. else {
  13193. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  13194. }
  13195. // recalculate the size of the node on the next time the node is rendered
  13196. parentNode.clearSizeCache();
  13197. // set the pop-out scale for the childnode
  13198. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  13199. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  13200. childNode.clearVelocity();
  13201. // the mass has altered, preservation of energy dictates the velocity to be updated
  13202. parentNode.updateVelocity(massBefore);
  13203. // restart the simulation to reorganise all nodes
  13204. this.moving = true;
  13205. },
  13206. /**
  13207. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  13208. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  13209. * It has to be called if a level is collapsed. It is called by _formClusters().
  13210. * @private
  13211. */
  13212. _updateDynamicEdges : function() {
  13213. for (var i = 0; i < this.nodeIndices.length; i++) {
  13214. var node = this.nodes[this.nodeIndices[i]];
  13215. node.dynamicEdgesLength = node.dynamicEdges.length;
  13216. // this corrects for multiple edges pointing at the same other node
  13217. var correction = 0;
  13218. if (node.dynamicEdgesLength > 1) {
  13219. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  13220. var edgeToId = node.dynamicEdges[j].toId;
  13221. var edgeFromId = node.dynamicEdges[j].fromId;
  13222. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  13223. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  13224. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  13225. correction += 1;
  13226. }
  13227. }
  13228. }
  13229. }
  13230. node.dynamicEdgesLength -= correction;
  13231. }
  13232. },
  13233. /**
  13234. * This adds an edge from the childNode to the contained edges of the parent node
  13235. *
  13236. * @param parentNode | Node object
  13237. * @param childNode | Node object
  13238. * @param edge | Edge object
  13239. * @private
  13240. */
  13241. _addToContainedEdges : function(parentNode, childNode, edge) {
  13242. // create an array object if it does not yet exist for this childNode
  13243. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  13244. parentNode.containedEdges[childNode.id] = []
  13245. }
  13246. // add this edge to the list
  13247. parentNode.containedEdges[childNode.id].push(edge);
  13248. // remove the edge from the global edges object
  13249. delete this.edges[edge.id];
  13250. // remove the edge from the parent object
  13251. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  13252. if (parentNode.dynamicEdges[i].id == edge.id) {
  13253. parentNode.dynamicEdges.splice(i,1);
  13254. break;
  13255. }
  13256. }
  13257. },
  13258. /**
  13259. * This function connects an edge that was connected to a child node to the parent node.
  13260. * It keeps track of which nodes it has been connected to with the originalId array.
  13261. *
  13262. * @param {Node} parentNode | Node object
  13263. * @param {Node} childNode | Node object
  13264. * @param {Edge} edge | Edge object
  13265. * @private
  13266. */
  13267. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  13268. // handle circular edges
  13269. if (edge.toId == edge.fromId) {
  13270. this._addToContainedEdges(parentNode, childNode, edge);
  13271. }
  13272. else {
  13273. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  13274. edge.originalToId.push(childNode.id);
  13275. edge.to = parentNode;
  13276. edge.toId = parentNode.id;
  13277. }
  13278. else { // edge connected to other node with the "from" side
  13279. edge.originalFromId.push(childNode.id);
  13280. edge.from = parentNode;
  13281. edge.fromId = parentNode.id;
  13282. }
  13283. this._addToReroutedEdges(parentNode,childNode,edge);
  13284. }
  13285. },
  13286. /**
  13287. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  13288. * these edges inside of the cluster.
  13289. *
  13290. * @param parentNode
  13291. * @param childNode
  13292. * @private
  13293. */
  13294. _containCircularEdgesFromNode : function(parentNode, childNode) {
  13295. // manage all the edges connected to the child and parent nodes
  13296. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  13297. var edge = parentNode.dynamicEdges[i];
  13298. // handle circular edges
  13299. if (edge.toId == edge.fromId) {
  13300. this._addToContainedEdges(parentNode, childNode, edge);
  13301. }
  13302. }
  13303. },
  13304. /**
  13305. * This adds an edge from the childNode to the rerouted edges of the parent node
  13306. *
  13307. * @param parentNode | Node object
  13308. * @param childNode | Node object
  13309. * @param edge | Edge object
  13310. * @private
  13311. */
  13312. _addToReroutedEdges : function(parentNode, childNode, edge) {
  13313. // create an array object if it does not yet exist for this childNode
  13314. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  13315. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  13316. parentNode.reroutedEdges[childNode.id] = [];
  13317. }
  13318. parentNode.reroutedEdges[childNode.id].push(edge);
  13319. // this edge becomes part of the dynamicEdges of the cluster node
  13320. parentNode.dynamicEdges.push(edge);
  13321. },
  13322. /**
  13323. * This function connects an edge that was connected to a cluster node back to the child node.
  13324. *
  13325. * @param parentNode | Node object
  13326. * @param childNode | Node object
  13327. * @private
  13328. */
  13329. _connectEdgeBackToChild : function(parentNode, childNode) {
  13330. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  13331. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  13332. var edge = parentNode.reroutedEdges[childNode.id][i];
  13333. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  13334. edge.originalFromId.pop();
  13335. edge.fromId = childNode.id;
  13336. edge.from = childNode;
  13337. }
  13338. else {
  13339. edge.originalToId.pop();
  13340. edge.toId = childNode.id;
  13341. edge.to = childNode;
  13342. }
  13343. // append this edge to the list of edges connecting to the childnode
  13344. childNode.dynamicEdges.push(edge);
  13345. // remove the edge from the parent object
  13346. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  13347. if (parentNode.dynamicEdges[j].id == edge.id) {
  13348. parentNode.dynamicEdges.splice(j,1);
  13349. break;
  13350. }
  13351. }
  13352. }
  13353. // remove the entry from the rerouted edges
  13354. delete parentNode.reroutedEdges[childNode.id];
  13355. }
  13356. },
  13357. /**
  13358. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  13359. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  13360. * parentNode
  13361. *
  13362. * @param parentNode | Node object
  13363. * @private
  13364. */
  13365. _validateEdges : function(parentNode) {
  13366. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  13367. var edge = parentNode.dynamicEdges[i];
  13368. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  13369. parentNode.dynamicEdges.splice(i,1);
  13370. }
  13371. }
  13372. },
  13373. /**
  13374. * This function released the contained edges back into the global domain and puts them back into the
  13375. * dynamic edges of both parent and child.
  13376. *
  13377. * @param {Node} parentNode |
  13378. * @param {Node} childNode |
  13379. * @private
  13380. */
  13381. _releaseContainedEdges : function(parentNode, childNode) {
  13382. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  13383. var edge = parentNode.containedEdges[childNode.id][i];
  13384. // put the edge back in the global edges object
  13385. this.edges[edge.id] = edge;
  13386. // put the edge back in the dynamic edges of the child and parent
  13387. childNode.dynamicEdges.push(edge);
  13388. parentNode.dynamicEdges.push(edge);
  13389. }
  13390. // remove the entry from the contained edges
  13391. delete parentNode.containedEdges[childNode.id];
  13392. },
  13393. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  13394. /**
  13395. * This updates the node labels for all nodes (for debugging purposes)
  13396. */
  13397. updateLabels : function() {
  13398. var nodeId;
  13399. // update node labels
  13400. for (nodeId in this.nodes) {
  13401. if (this.nodes.hasOwnProperty(nodeId)) {
  13402. var node = this.nodes[nodeId];
  13403. if (node.clusterSize > 1) {
  13404. node.label = "[".concat(String(node.clusterSize),"]");
  13405. }
  13406. }
  13407. }
  13408. // update node labels
  13409. for (nodeId in this.nodes) {
  13410. if (this.nodes.hasOwnProperty(nodeId)) {
  13411. node = this.nodes[nodeId];
  13412. if (node.clusterSize == 1) {
  13413. if (node.originalLabel !== undefined) {
  13414. node.label = node.originalLabel;
  13415. }
  13416. else {
  13417. node.label = String(node.id);
  13418. }
  13419. }
  13420. }
  13421. }
  13422. // /* Debug Override */
  13423. // for (nodeId in this.nodes) {
  13424. // if (this.nodes.hasOwnProperty(nodeId)) {
  13425. // node = this.nodes[nodeId];
  13426. // node.label = String(node.level);
  13427. // }
  13428. // }
  13429. },
  13430. /**
  13431. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  13432. * if the rest of the nodes are already a few cluster levels in.
  13433. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  13434. * clustered enough to the clusterToSmallestNeighbours function.
  13435. */
  13436. normalizeClusterLevels : function() {
  13437. var maxLevel = 0;
  13438. var minLevel = 1e9;
  13439. var clusterLevel = 0;
  13440. var nodeId;
  13441. // we loop over all nodes in the list
  13442. for (nodeId in this.nodes) {
  13443. if (this.nodes.hasOwnProperty(nodeId)) {
  13444. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  13445. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  13446. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  13447. }
  13448. }
  13449. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  13450. var amountOfNodes = this.nodeIndices.length;
  13451. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  13452. // we loop over all nodes in the list
  13453. for (nodeId in this.nodes) {
  13454. if (this.nodes.hasOwnProperty(nodeId)) {
  13455. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  13456. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  13457. }
  13458. }
  13459. }
  13460. this._updateNodeIndexList();
  13461. this._updateDynamicEdges();
  13462. // if a cluster was formed, we increase the clusterSession
  13463. if (this.nodeIndices.length != amountOfNodes) {
  13464. this.clusterSession += 1;
  13465. }
  13466. }
  13467. },
  13468. /**
  13469. * This function determines if the cluster we want to decluster is in the active area
  13470. * this means around the zoom center
  13471. *
  13472. * @param {Node} node
  13473. * @returns {boolean}
  13474. * @private
  13475. */
  13476. _nodeInActiveArea : function(node) {
  13477. return (
  13478. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  13479. &&
  13480. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  13481. )
  13482. },
  13483. /**
  13484. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  13485. * It puts large clusters away from the center and randomizes the order.
  13486. *
  13487. */
  13488. repositionNodes : function() {
  13489. for (var i = 0; i < this.nodeIndices.length; i++) {
  13490. var node = this.nodes[this.nodeIndices[i]];
  13491. if ((node.xFixed == false || node.yFixed == false)) {
  13492. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.mass);
  13493. var angle = 2 * Math.PI * Math.random();
  13494. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  13495. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  13496. this._repositionBezierNodes(node);
  13497. }
  13498. }
  13499. },
  13500. /**
  13501. * We determine how many connections denote an important hub.
  13502. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  13503. *
  13504. * @private
  13505. */
  13506. _getHubSize : function() {
  13507. var average = 0;
  13508. var averageSquared = 0;
  13509. var hubCounter = 0;
  13510. var largestHub = 0;
  13511. for (var i = 0; i < this.nodeIndices.length; i++) {
  13512. var node = this.nodes[this.nodeIndices[i]];
  13513. if (node.dynamicEdgesLength > largestHub) {
  13514. largestHub = node.dynamicEdgesLength;
  13515. }
  13516. average += node.dynamicEdgesLength;
  13517. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  13518. hubCounter += 1;
  13519. }
  13520. average = average / hubCounter;
  13521. averageSquared = averageSquared / hubCounter;
  13522. var variance = averageSquared - Math.pow(average,2);
  13523. var standardDeviation = Math.sqrt(variance);
  13524. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  13525. // always have at least one to cluster
  13526. if (this.hubThreshold > largestHub) {
  13527. this.hubThreshold = largestHub;
  13528. }
  13529. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  13530. // console.log("hubThreshold:",this.hubThreshold);
  13531. },
  13532. /**
  13533. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  13534. * with this amount we can cluster specifically on these chains.
  13535. *
  13536. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  13537. * @private
  13538. */
  13539. _reduceAmountOfChains : function(fraction) {
  13540. this.hubThreshold = 2;
  13541. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  13542. for (var nodeId in this.nodes) {
  13543. if (this.nodes.hasOwnProperty(nodeId)) {
  13544. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  13545. if (reduceAmount > 0) {
  13546. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  13547. reduceAmount -= 1;
  13548. }
  13549. }
  13550. }
  13551. }
  13552. },
  13553. /**
  13554. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  13555. * with this amount we can cluster specifically on these chains.
  13556. *
  13557. * @private
  13558. */
  13559. _getChainFraction : function() {
  13560. var chains = 0;
  13561. var total = 0;
  13562. for (var nodeId in this.nodes) {
  13563. if (this.nodes.hasOwnProperty(nodeId)) {
  13564. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  13565. chains += 1;
  13566. }
  13567. total += 1;
  13568. }
  13569. }
  13570. return chains/total;
  13571. }
  13572. };
  13573. var SelectionMixin = {
  13574. /**
  13575. * This function can be called from the _doInAllSectors function
  13576. *
  13577. * @param object
  13578. * @param overlappingNodes
  13579. * @private
  13580. */
  13581. _getNodesOverlappingWith : function(object, overlappingNodes) {
  13582. var nodes = this.nodes;
  13583. for (var nodeId in nodes) {
  13584. if (nodes.hasOwnProperty(nodeId)) {
  13585. if (nodes[nodeId].isOverlappingWith(object)) {
  13586. overlappingNodes.push(nodeId);
  13587. }
  13588. }
  13589. }
  13590. },
  13591. /**
  13592. * retrieve all nodes overlapping with given object
  13593. * @param {Object} object An object with parameters left, top, right, bottom
  13594. * @return {Number[]} An array with id's of the overlapping nodes
  13595. * @private
  13596. */
  13597. _getAllNodesOverlappingWith : function (object) {
  13598. var overlappingNodes = [];
  13599. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  13600. return overlappingNodes;
  13601. },
  13602. /**
  13603. * Return a position object in canvasspace from a single point in screenspace
  13604. *
  13605. * @param pointer
  13606. * @returns {{left: number, top: number, right: number, bottom: number}}
  13607. * @private
  13608. */
  13609. _pointerToPositionObject : function(pointer) {
  13610. var x = this._canvasToX(pointer.x);
  13611. var y = this._canvasToY(pointer.y);
  13612. return {left: x,
  13613. top: y,
  13614. right: x,
  13615. bottom: y};
  13616. },
  13617. /**
  13618. * Get the top node at the a specific point (like a click)
  13619. *
  13620. * @param {{x: Number, y: Number}} pointer
  13621. * @return {Node | null} node
  13622. * @private
  13623. */
  13624. _getNodeAt : function (pointer) {
  13625. // we first check if this is an navigation controls element
  13626. var positionObject = this._pointerToPositionObject(pointer);
  13627. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  13628. // if there are overlapping nodes, select the last one, this is the
  13629. // one which is drawn on top of the others
  13630. if (overlappingNodes.length > 0) {
  13631. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  13632. }
  13633. else {
  13634. return null;
  13635. }
  13636. },
  13637. /**
  13638. * retrieve all edges overlapping with given object, selector is around center
  13639. * @param {Object} object An object with parameters left, top, right, bottom
  13640. * @return {Number[]} An array with id's of the overlapping nodes
  13641. * @private
  13642. */
  13643. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  13644. var edges = this.edges;
  13645. for (var edgeId in edges) {
  13646. if (edges.hasOwnProperty(edgeId)) {
  13647. if (edges[edgeId].isOverlappingWith(object)) {
  13648. overlappingEdges.push(edgeId);
  13649. }
  13650. }
  13651. }
  13652. },
  13653. /**
  13654. * retrieve all nodes overlapping with given object
  13655. * @param {Object} object An object with parameters left, top, right, bottom
  13656. * @return {Number[]} An array with id's of the overlapping nodes
  13657. * @private
  13658. */
  13659. _getAllEdgesOverlappingWith : function (object) {
  13660. var overlappingEdges = [];
  13661. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  13662. return overlappingEdges;
  13663. },
  13664. /**
  13665. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  13666. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  13667. *
  13668. * @param pointer
  13669. * @returns {null}
  13670. * @private
  13671. */
  13672. _getEdgeAt : function(pointer) {
  13673. var positionObject = this._pointerToPositionObject(pointer);
  13674. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  13675. if (overlappingEdges.length > 0) {
  13676. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  13677. }
  13678. else {
  13679. return null;
  13680. }
  13681. },
  13682. /**
  13683. * Add object to the selection array.
  13684. *
  13685. * @param obj
  13686. * @private
  13687. */
  13688. _addToSelection : function(obj) {
  13689. if (obj instanceof Node) {
  13690. this.selectionObj.nodes[obj.id] = obj;
  13691. }
  13692. else {
  13693. this.selectionObj.edges[obj.id] = obj;
  13694. }
  13695. },
  13696. /**
  13697. * Remove a single option from selection.
  13698. *
  13699. * @param {Object} obj
  13700. * @private
  13701. */
  13702. _removeFromSelection : function(obj) {
  13703. if (obj instanceof Node) {
  13704. delete this.selectionObj.nodes[obj.id];
  13705. }
  13706. else {
  13707. delete this.selectionObj.edges[obj.id];
  13708. }
  13709. },
  13710. /**
  13711. * Unselect all. The selectionObj is useful for this.
  13712. *
  13713. * @param {Boolean} [doNotTrigger] | ignore trigger
  13714. * @private
  13715. */
  13716. _unselectAll : function(doNotTrigger) {
  13717. if (doNotTrigger === undefined) {
  13718. doNotTrigger = false;
  13719. }
  13720. for(var nodeId in this.selectionObj.nodes) {
  13721. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13722. this.selectionObj.nodes[nodeId].unselect();
  13723. }
  13724. }
  13725. for(var edgeId in this.selectionObj.edges) {
  13726. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13727. this.selectionObj.edges[edgeId].unselect();
  13728. }
  13729. }
  13730. this.selectionObj = {nodes:{},edges:{}};
  13731. if (doNotTrigger == false) {
  13732. this.emit('select', this.getSelection());
  13733. }
  13734. },
  13735. /**
  13736. * Unselect all clusters. The selectionObj is useful for this.
  13737. *
  13738. * @param {Boolean} [doNotTrigger] | ignore trigger
  13739. * @private
  13740. */
  13741. _unselectClusters : function(doNotTrigger) {
  13742. if (doNotTrigger === undefined) {
  13743. doNotTrigger = false;
  13744. }
  13745. for (var nodeId in this.selectionObj.nodes) {
  13746. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13747. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13748. this.selectionObj.nodes[nodeId].unselect();
  13749. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  13750. }
  13751. }
  13752. }
  13753. if (doNotTrigger == false) {
  13754. this.emit('select', this.getSelection());
  13755. }
  13756. },
  13757. /**
  13758. * return the number of selected nodes
  13759. *
  13760. * @returns {number}
  13761. * @private
  13762. */
  13763. _getSelectedNodeCount : function() {
  13764. var count = 0;
  13765. for (var nodeId in this.selectionObj.nodes) {
  13766. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13767. count += 1;
  13768. }
  13769. }
  13770. return count;
  13771. },
  13772. /**
  13773. * return the number of selected nodes
  13774. *
  13775. * @returns {number}
  13776. * @private
  13777. */
  13778. _getSelectedNode : function() {
  13779. for (var nodeId in this.selectionObj.nodes) {
  13780. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13781. return this.selectionObj.nodes[nodeId];
  13782. }
  13783. }
  13784. return null;
  13785. },
  13786. /**
  13787. * return the number of selected edges
  13788. *
  13789. * @returns {number}
  13790. * @private
  13791. */
  13792. _getSelectedEdgeCount : function() {
  13793. var count = 0;
  13794. for (var edgeId in this.selectionObj.edges) {
  13795. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13796. count += 1;
  13797. }
  13798. }
  13799. return count;
  13800. },
  13801. /**
  13802. * return the number of selected objects.
  13803. *
  13804. * @returns {number}
  13805. * @private
  13806. */
  13807. _getSelectedObjectCount : function() {
  13808. var count = 0;
  13809. for(var nodeId in this.selectionObj.nodes) {
  13810. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13811. count += 1;
  13812. }
  13813. }
  13814. for(var edgeId in this.selectionObj.edges) {
  13815. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13816. count += 1;
  13817. }
  13818. }
  13819. return count;
  13820. },
  13821. /**
  13822. * Check if anything is selected
  13823. *
  13824. * @returns {boolean}
  13825. * @private
  13826. */
  13827. _selectionIsEmpty : function() {
  13828. for(var nodeId in this.selectionObj.nodes) {
  13829. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13830. return false;
  13831. }
  13832. }
  13833. for(var edgeId in this.selectionObj.edges) {
  13834. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13835. return false;
  13836. }
  13837. }
  13838. return true;
  13839. },
  13840. /**
  13841. * check if one of the selected nodes is a cluster.
  13842. *
  13843. * @returns {boolean}
  13844. * @private
  13845. */
  13846. _clusterInSelection : function() {
  13847. for(var nodeId in this.selectionObj.nodes) {
  13848. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13849. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13850. return true;
  13851. }
  13852. }
  13853. }
  13854. return false;
  13855. },
  13856. /**
  13857. * select the edges connected to the node that is being selected
  13858. *
  13859. * @param {Node} node
  13860. * @private
  13861. */
  13862. _selectConnectedEdges : function(node) {
  13863. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13864. var edge = node.dynamicEdges[i];
  13865. edge.select();
  13866. this._addToSelection(edge);
  13867. }
  13868. },
  13869. /**
  13870. * unselect the edges connected to the node that is being selected
  13871. *
  13872. * @param {Node} node
  13873. * @private
  13874. */
  13875. _unselectConnectedEdges : function(node) {
  13876. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13877. var edge = node.dynamicEdges[i];
  13878. edge.unselect();
  13879. this._removeFromSelection(edge);
  13880. }
  13881. },
  13882. /**
  13883. * This is called when someone clicks on a node. either select or deselect it.
  13884. * If there is an existing selection and we don't want to append to it, clear the existing selection
  13885. *
  13886. * @param {Node || Edge} object
  13887. * @param {Boolean} append
  13888. * @param {Boolean} [doNotTrigger] | ignore trigger
  13889. * @private
  13890. */
  13891. _selectObject : function(object, append, doNotTrigger) {
  13892. if (doNotTrigger === undefined) {
  13893. doNotTrigger = false;
  13894. }
  13895. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  13896. this._unselectAll(true);
  13897. }
  13898. if (object.selected == false) {
  13899. object.select();
  13900. this._addToSelection(object);
  13901. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  13902. this._selectConnectedEdges(object);
  13903. }
  13904. }
  13905. else {
  13906. object.unselect();
  13907. this._removeFromSelection(object);
  13908. }
  13909. if (doNotTrigger == false) {
  13910. this.emit('select', this.getSelection());
  13911. }
  13912. },
  13913. /**
  13914. * handles the selection part of the touch, only for navigation controls elements;
  13915. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13916. * This is the most responsive solution
  13917. *
  13918. * @param {Object} pointer
  13919. * @private
  13920. */
  13921. _handleTouch : function(pointer) {
  13922. },
  13923. /**
  13924. * handles the selection part of the tap;
  13925. *
  13926. * @param {Object} pointer
  13927. * @private
  13928. */
  13929. _handleTap : function(pointer) {
  13930. var node = this._getNodeAt(pointer);
  13931. if (node != null) {
  13932. this._selectObject(node,false);
  13933. }
  13934. else {
  13935. var edge = this._getEdgeAt(pointer);
  13936. if (edge != null) {
  13937. this._selectObject(edge,false);
  13938. }
  13939. else {
  13940. this._unselectAll();
  13941. }
  13942. }
  13943. this.emit("click", this.getSelection());
  13944. this._redraw();
  13945. },
  13946. /**
  13947. * handles the selection part of the double tap and opens a cluster if needed
  13948. *
  13949. * @param {Object} pointer
  13950. * @private
  13951. */
  13952. _handleDoubleTap : function(pointer) {
  13953. var node = this._getNodeAt(pointer);
  13954. if (node != null && node !== undefined) {
  13955. // we reset the areaCenter here so the opening of the node will occur
  13956. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  13957. "y" : this._canvasToY(pointer.y)};
  13958. this.openCluster(node);
  13959. }
  13960. this.emit("doubleClick", this.getSelection());
  13961. },
  13962. /**
  13963. * Handle the onHold selection part
  13964. *
  13965. * @param pointer
  13966. * @private
  13967. */
  13968. _handleOnHold : function(pointer) {
  13969. var node = this._getNodeAt(pointer);
  13970. if (node != null) {
  13971. this._selectObject(node,true);
  13972. }
  13973. else {
  13974. var edge = this._getEdgeAt(pointer);
  13975. if (edge != null) {
  13976. this._selectObject(edge,true);
  13977. }
  13978. }
  13979. this._redraw();
  13980. },
  13981. /**
  13982. * handle the onRelease event. These functions are here for the navigation controls module.
  13983. *
  13984. * @private
  13985. */
  13986. _handleOnRelease : function(pointer) {
  13987. },
  13988. /**
  13989. *
  13990. * retrieve the currently selected objects
  13991. * @return {Number[] | String[]} selection An array with the ids of the
  13992. * selected nodes.
  13993. */
  13994. getSelection : function() {
  13995. var nodeIds = this.getSelectedNodes();
  13996. var edgeIds = this.getSelectedEdges();
  13997. return {nodes:nodeIds, edges:edgeIds};
  13998. },
  13999. /**
  14000. *
  14001. * retrieve the currently selected nodes
  14002. * @return {String} selection An array with the ids of the
  14003. * selected nodes.
  14004. */
  14005. getSelectedNodes : function() {
  14006. var idArray = [];
  14007. for(var nodeId in this.selectionObj.nodes) {
  14008. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  14009. idArray.push(nodeId);
  14010. }
  14011. }
  14012. return idArray
  14013. },
  14014. /**
  14015. *
  14016. * retrieve the currently selected edges
  14017. * @return {Array} selection An array with the ids of the
  14018. * selected nodes.
  14019. */
  14020. getSelectedEdges : function() {
  14021. var idArray = [];
  14022. for(var edgeId in this.selectionObj.edges) {
  14023. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  14024. idArray.push(edgeId);
  14025. }
  14026. }
  14027. return idArray;
  14028. },
  14029. /**
  14030. * select zero or more nodes
  14031. * @param {Number[] | String[]} selection An array with the ids of the
  14032. * selected nodes.
  14033. */
  14034. setSelection : function(selection) {
  14035. var i, iMax, id;
  14036. if (!selection || (selection.length == undefined))
  14037. throw 'Selection must be an array with ids';
  14038. // first unselect any selected node
  14039. this._unselectAll(true);
  14040. for (i = 0, iMax = selection.length; i < iMax; i++) {
  14041. id = selection[i];
  14042. var node = this.nodes[id];
  14043. if (!node) {
  14044. throw new RangeError('Node with id "' + id + '" not found');
  14045. }
  14046. this._selectObject(node,true,true);
  14047. }
  14048. this.redraw();
  14049. },
  14050. /**
  14051. * Validate the selection: remove ids of nodes which no longer exist
  14052. * @private
  14053. */
  14054. _updateSelection : function () {
  14055. for(var nodeId in this.selectionObj.nodes) {
  14056. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  14057. if (!this.nodes.hasOwnProperty(nodeId)) {
  14058. delete this.selectionObj.nodes[nodeId];
  14059. }
  14060. }
  14061. }
  14062. for(var edgeId in this.selectionObj.edges) {
  14063. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  14064. if (!this.edges.hasOwnProperty(edgeId)) {
  14065. delete this.selectionObj.edges[edgeId];
  14066. }
  14067. }
  14068. }
  14069. }
  14070. };
  14071. /**
  14072. * Created by Alex on 1/22/14.
  14073. */
  14074. var NavigationMixin = {
  14075. _cleanNavigation : function() {
  14076. // clean up previosu navigation items
  14077. var wrapper = document.getElementById('graph-navigation_wrapper');
  14078. if (wrapper != null) {
  14079. this.containerElement.removeChild(wrapper);
  14080. }
  14081. document.onmouseup = null;
  14082. },
  14083. /**
  14084. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  14085. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  14086. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  14087. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  14088. *
  14089. * @private
  14090. */
  14091. _loadNavigationElements : function() {
  14092. this._cleanNavigation();
  14093. this.navigationDivs = {};
  14094. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  14095. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  14096. this.navigationDivs['wrapper'] = document.createElement('div');
  14097. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  14098. this.navigationDivs['wrapper'].style.position = "absolute";
  14099. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  14100. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  14101. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  14102. for (var i = 0; i < navigationDivs.length; i++) {
  14103. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  14104. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  14105. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  14106. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  14107. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  14108. }
  14109. document.onmouseup = this._stopMovement.bind(this);
  14110. },
  14111. /**
  14112. * this stops all movement induced by the navigation buttons
  14113. *
  14114. * @private
  14115. */
  14116. _stopMovement : function() {
  14117. this._xStopMoving();
  14118. this._yStopMoving();
  14119. this._stopZoom();
  14120. },
  14121. /**
  14122. * stops the actions performed by page up and down etc.
  14123. *
  14124. * @param event
  14125. * @private
  14126. */
  14127. _preventDefault : function(event) {
  14128. if (event !== undefined) {
  14129. if (event.preventDefault) {
  14130. event.preventDefault();
  14131. } else {
  14132. event.returnValue = false;
  14133. }
  14134. }
  14135. },
  14136. /**
  14137. * move the screen up
  14138. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  14139. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  14140. * To avoid this behaviour, we do the translation in the start loop.
  14141. *
  14142. * @private
  14143. */
  14144. _moveUp : function(event) {
  14145. this.yIncrement = this.constants.keyboard.speed.y;
  14146. this.start(); // if there is no node movement, the calculation wont be done
  14147. this._preventDefault(event);
  14148. if (this.navigationDivs) {
  14149. this.navigationDivs['up'].className += " active";
  14150. }
  14151. },
  14152. /**
  14153. * move the screen down
  14154. * @private
  14155. */
  14156. _moveDown : function(event) {
  14157. this.yIncrement = -this.constants.keyboard.speed.y;
  14158. this.start(); // if there is no node movement, the calculation wont be done
  14159. this._preventDefault(event);
  14160. if (this.navigationDivs) {
  14161. this.navigationDivs['down'].className += " active";
  14162. }
  14163. },
  14164. /**
  14165. * move the screen left
  14166. * @private
  14167. */
  14168. _moveLeft : function(event) {
  14169. this.xIncrement = this.constants.keyboard.speed.x;
  14170. this.start(); // if there is no node movement, the calculation wont be done
  14171. this._preventDefault(event);
  14172. if (this.navigationDivs) {
  14173. this.navigationDivs['left'].className += " active";
  14174. }
  14175. },
  14176. /**
  14177. * move the screen right
  14178. * @private
  14179. */
  14180. _moveRight : function(event) {
  14181. this.xIncrement = -this.constants.keyboard.speed.y;
  14182. this.start(); // if there is no node movement, the calculation wont be done
  14183. this._preventDefault(event);
  14184. if (this.navigationDivs) {
  14185. this.navigationDivs['right'].className += " active";
  14186. }
  14187. },
  14188. /**
  14189. * Zoom in, using the same method as the movement.
  14190. * @private
  14191. */
  14192. _zoomIn : function(event) {
  14193. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  14194. this.start(); // if there is no node movement, the calculation wont be done
  14195. this._preventDefault(event);
  14196. if (this.navigationDivs) {
  14197. this.navigationDivs['zoomIn'].className += " active";
  14198. }
  14199. },
  14200. /**
  14201. * Zoom out
  14202. * @private
  14203. */
  14204. _zoomOut : function() {
  14205. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  14206. this.start(); // if there is no node movement, the calculation wont be done
  14207. this._preventDefault(event);
  14208. if (this.navigationDivs) {
  14209. this.navigationDivs['zoomOut'].className += " active";
  14210. }
  14211. },
  14212. /**
  14213. * Stop zooming and unhighlight the zoom controls
  14214. * @private
  14215. */
  14216. _stopZoom : function() {
  14217. this.zoomIncrement = 0;
  14218. if (this.navigationDivs) {
  14219. this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active","");
  14220. this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active","");
  14221. }
  14222. },
  14223. /**
  14224. * Stop moving in the Y direction and unHighlight the up and down
  14225. * @private
  14226. */
  14227. _yStopMoving : function() {
  14228. this.yIncrement = 0;
  14229. if (this.navigationDivs) {
  14230. this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active","");
  14231. this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active","");
  14232. }
  14233. },
  14234. /**
  14235. * Stop moving in the X direction and unHighlight left and right.
  14236. * @private
  14237. */
  14238. _xStopMoving : function() {
  14239. this.xIncrement = 0;
  14240. if (this.navigationDivs) {
  14241. this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active","");
  14242. this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active","");
  14243. }
  14244. }
  14245. };
  14246. /**
  14247. * Created by Alex on 2/10/14.
  14248. */
  14249. var graphMixinLoaders = {
  14250. /**
  14251. * Load a mixin into the graph object
  14252. *
  14253. * @param {Object} sourceVariable | this object has to contain functions.
  14254. * @private
  14255. */
  14256. _loadMixin: function (sourceVariable) {
  14257. for (var mixinFunction in sourceVariable) {
  14258. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  14259. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  14260. }
  14261. }
  14262. },
  14263. /**
  14264. * removes a mixin from the graph object.
  14265. *
  14266. * @param {Object} sourceVariable | this object has to contain functions.
  14267. * @private
  14268. */
  14269. _clearMixin: function (sourceVariable) {
  14270. for (var mixinFunction in sourceVariable) {
  14271. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  14272. Graph.prototype[mixinFunction] = undefined;
  14273. }
  14274. }
  14275. },
  14276. /**
  14277. * Mixin the physics system and initialize the parameters required.
  14278. *
  14279. * @private
  14280. */
  14281. _loadPhysicsSystem: function () {
  14282. this._loadMixin(physicsMixin);
  14283. this._loadSelectedForceSolver();
  14284. if (this.constants.configurePhysics == true) {
  14285. this._loadPhysicsConfiguration();
  14286. }
  14287. },
  14288. /**
  14289. * Mixin the cluster system and initialize the parameters required.
  14290. *
  14291. * @private
  14292. */
  14293. _loadClusterSystem: function () {
  14294. this.clusterSession = 0;
  14295. this.hubThreshold = 5;
  14296. this._loadMixin(ClusterMixin);
  14297. },
  14298. /**
  14299. * Mixin the sector system and initialize the parameters required
  14300. *
  14301. * @private
  14302. */
  14303. _loadSectorSystem: function () {
  14304. this.sectors = {};
  14305. this.activeSector = ["default"];
  14306. this.sectors["active"] = {};
  14307. this.sectors["active"]["default"] = {"nodes": {},
  14308. "edges": {},
  14309. "nodeIndices": [],
  14310. "formationScale": 1.0,
  14311. "drawingNode": undefined };
  14312. this.sectors["frozen"] = {};
  14313. this.sectors["support"] = {"nodes": {},
  14314. "edges": {},
  14315. "nodeIndices": [],
  14316. "formationScale": 1.0,
  14317. "drawingNode": undefined };
  14318. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  14319. this._loadMixin(SectorMixin);
  14320. },
  14321. /**
  14322. * Mixin the selection system and initialize the parameters required
  14323. *
  14324. * @private
  14325. */
  14326. _loadSelectionSystem: function () {
  14327. this.selectionObj = {nodes: {}, edges: {}};
  14328. this._loadMixin(SelectionMixin);
  14329. },
  14330. /**
  14331. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  14332. *
  14333. * @private
  14334. */
  14335. _loadManipulationSystem: function () {
  14336. // reset global variables -- these are used by the selection of nodes and edges.
  14337. this.blockConnectingEdgeSelection = false;
  14338. this.forceAppendSelection = false;
  14339. if (this.constants.dataManipulation.enabled == true) {
  14340. // load the manipulator HTML elements. All styling done in css.
  14341. if (this.manipulationDiv === undefined) {
  14342. this.manipulationDiv = document.createElement('div');
  14343. this.manipulationDiv.className = 'graph-manipulationDiv';
  14344. this.manipulationDiv.id = 'graph-manipulationDiv';
  14345. if (this.editMode == true) {
  14346. this.manipulationDiv.style.display = "block";
  14347. }
  14348. else {
  14349. this.manipulationDiv.style.display = "none";
  14350. }
  14351. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  14352. }
  14353. if (this.editModeDiv === undefined) {
  14354. this.editModeDiv = document.createElement('div');
  14355. this.editModeDiv.className = 'graph-manipulation-editMode';
  14356. this.editModeDiv.id = 'graph-manipulation-editMode';
  14357. if (this.editMode == true) {
  14358. this.editModeDiv.style.display = "none";
  14359. }
  14360. else {
  14361. this.editModeDiv.style.display = "block";
  14362. }
  14363. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  14364. }
  14365. if (this.closeDiv === undefined) {
  14366. this.closeDiv = document.createElement('div');
  14367. this.closeDiv.className = 'graph-manipulation-closeDiv';
  14368. this.closeDiv.id = 'graph-manipulation-closeDiv';
  14369. this.closeDiv.style.display = this.manipulationDiv.style.display;
  14370. this.containerElement.insertBefore(this.closeDiv, this.frame);
  14371. }
  14372. // load the manipulation functions
  14373. this._loadMixin(manipulationMixin);
  14374. // create the manipulator toolbar
  14375. this._createManipulatorBar();
  14376. }
  14377. else {
  14378. if (this.manipulationDiv !== undefined) {
  14379. // removes all the bindings and overloads
  14380. this._createManipulatorBar();
  14381. // remove the manipulation divs
  14382. this.containerElement.removeChild(this.manipulationDiv);
  14383. this.containerElement.removeChild(this.editModeDiv);
  14384. this.containerElement.removeChild(this.closeDiv);
  14385. this.manipulationDiv = undefined;
  14386. this.editModeDiv = undefined;
  14387. this.closeDiv = undefined;
  14388. // remove the mixin functions
  14389. this._clearMixin(manipulationMixin);
  14390. }
  14391. }
  14392. },
  14393. /**
  14394. * Mixin the navigation (User Interface) system and initialize the parameters required
  14395. *
  14396. * @private
  14397. */
  14398. _loadNavigationControls: function () {
  14399. this._loadMixin(NavigationMixin);
  14400. // the clean function removes the button divs, this is done to remove the bindings.
  14401. this._cleanNavigation();
  14402. if (this.constants.navigation.enabled == true) {
  14403. this._loadNavigationElements();
  14404. }
  14405. },
  14406. /**
  14407. * Mixin the hierarchical layout system.
  14408. *
  14409. * @private
  14410. */
  14411. _loadHierarchySystem: function () {
  14412. this._loadMixin(HierarchicalLayoutMixin);
  14413. }
  14414. };
  14415. /**
  14416. * @constructor Graph
  14417. * Create a graph visualization, displaying nodes and edges.
  14418. *
  14419. * @param {Element} container The DOM element in which the Graph will
  14420. * be created. Normally a div element.
  14421. * @param {Object} data An object containing parameters
  14422. * {Array} nodes
  14423. * {Array} edges
  14424. * @param {Object} options Options
  14425. */
  14426. function Graph (container, data, options) {
  14427. this._initializeMixinLoaders();
  14428. // create variables and set default values
  14429. this.containerElement = container;
  14430. this.width = '100%';
  14431. this.height = '100%';
  14432. // render and calculation settings
  14433. this.renderRefreshRate = 60; // hz (fps)
  14434. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  14435. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  14436. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  14437. this.physicsDiscreteStepsize = 0.65; // discrete stepsize of the simulation
  14438. this.stabilize = true; // stabilize before displaying the graph
  14439. this.selectable = true;
  14440. this.initializing = true;
  14441. // these functions are triggered when the dataset is edited
  14442. this.triggerFunctions = {add:null,edit:null,connect:null,del:null};
  14443. // set constant values
  14444. this.constants = {
  14445. nodes: {
  14446. radiusMin: 5,
  14447. radiusMax: 20,
  14448. radius: 5,
  14449. shape: 'ellipse',
  14450. image: undefined,
  14451. widthMin: 16, // px
  14452. widthMax: 64, // px
  14453. fixed: false,
  14454. fontColor: 'black',
  14455. fontSize: 14, // px
  14456. fontFace: 'verdana',
  14457. level: -1,
  14458. color: {
  14459. border: '#2B7CE9',
  14460. background: '#97C2FC',
  14461. highlight: {
  14462. border: '#2B7CE9',
  14463. background: '#D2E5FF'
  14464. }
  14465. },
  14466. borderColor: '#2B7CE9',
  14467. backgroundColor: '#97C2FC',
  14468. highlightColor: '#D2E5FF',
  14469. group: undefined
  14470. },
  14471. edges: {
  14472. widthMin: 1,
  14473. widthMax: 15,
  14474. width: 1,
  14475. style: 'line',
  14476. color: {
  14477. color:'#848484',
  14478. highlight:'#848484'
  14479. },
  14480. fontColor: '#343434',
  14481. fontSize: 14, // px
  14482. fontFace: 'arial',
  14483. fontFill: 'white',
  14484. arrowScaleFactor: 1,
  14485. dash: {
  14486. length: 10,
  14487. gap: 5,
  14488. altLength: undefined
  14489. }
  14490. },
  14491. configurePhysics:false,
  14492. physics: {
  14493. barnesHut: {
  14494. enabled: true,
  14495. theta: 1 / 0.6, // inverted to save time during calculation
  14496. gravitationalConstant: -2000,
  14497. centralGravity: 0.3,
  14498. springLength: 95,
  14499. springConstant: 0.04,
  14500. damping: 0.09
  14501. },
  14502. repulsion: {
  14503. centralGravity: 0.1,
  14504. springLength: 200,
  14505. springConstant: 0.05,
  14506. nodeDistance: 100,
  14507. damping: 0.09
  14508. },
  14509. hierarchicalRepulsion: {
  14510. enabled: false,
  14511. centralGravity: 0.0,
  14512. springLength: 100,
  14513. springConstant: 0.01,
  14514. nodeDistance: 60,
  14515. damping: 0.09
  14516. },
  14517. damping: null,
  14518. centralGravity: null,
  14519. springLength: null,
  14520. springConstant: null
  14521. },
  14522. clustering: { // Per Node in Cluster = PNiC
  14523. enabled: false, // (Boolean) | global on/off switch for clustering.
  14524. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  14525. clusterThreshold:500, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than this. If it is, cluster until reduced to reduceToNodes
  14526. reduceToNodes:300, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than clusterThreshold. If it is, cluster until reduced to this
  14527. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  14528. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  14529. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  14530. screenSizeThreshold: 0.2, // (% of canvas) | relative size threshold. If the width or height of a clusternode takes up this much of the screen, decluster node.
  14531. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  14532. maxFontSize: 1000,
  14533. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  14534. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  14535. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  14536. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  14537. height: 1, // (px PNiC) | growth of the height per node in cluster.
  14538. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  14539. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  14540. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  14541. clusterLevelDifference: 2
  14542. },
  14543. navigation: {
  14544. enabled: false
  14545. },
  14546. keyboard: {
  14547. enabled: false,
  14548. speed: {x: 10, y: 10, zoom: 0.02}
  14549. },
  14550. dataManipulation: {
  14551. enabled: false,
  14552. initiallyVisible: false
  14553. },
  14554. hierarchicalLayout: {
  14555. enabled:false,
  14556. levelSeparation: 150,
  14557. nodeSpacing: 100,
  14558. direction: "UD" // UD, DU, LR, RL
  14559. },
  14560. freezeForStabilization: false,
  14561. smoothCurves: true,
  14562. maxVelocity: 10,
  14563. minVelocity: 0.1, // px/s
  14564. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  14565. labels:{
  14566. add:"Add Node",
  14567. edit:"Edit",
  14568. link:"Add Link",
  14569. del:"Delete selected",
  14570. editNode:"Edit Node",
  14571. back:"Back",
  14572. addDescription:"Click in an empty space to place a new node.",
  14573. linkDescription:"Click on a node and drag the edge to another node to connect them.",
  14574. addError:"The function for add does not support two arguments (data,callback).",
  14575. linkError:"The function for connect does not support two arguments (data,callback).",
  14576. editError:"The function for edit does not support two arguments (data, callback).",
  14577. editBoundError:"No edit function has been bound to this button.",
  14578. deleteError:"The function for delete does not support two arguments (data, callback).",
  14579. deleteClusterError:"Clusters cannot be deleted."
  14580. },
  14581. tooltip: {
  14582. delay: 300,
  14583. fontColor: 'black',
  14584. fontSize: 14, // px
  14585. fontFace: 'verdana',
  14586. color: {
  14587. border: '#666',
  14588. background: '#FFFFC6'
  14589. }
  14590. },
  14591. moveable: true,
  14592. zoomable: true
  14593. };
  14594. this.editMode = this.constants.dataManipulation.initiallyVisible;
  14595. // Node variables
  14596. var graph = this;
  14597. this.groups = new Groups(); // object with groups
  14598. this.images = new Images(); // object with images
  14599. this.images.setOnloadCallback(function () {
  14600. graph._redraw();
  14601. });
  14602. // keyboard navigation variables
  14603. this.xIncrement = 0;
  14604. this.yIncrement = 0;
  14605. this.zoomIncrement = 0;
  14606. // loading all the mixins:
  14607. // load the force calculation functions, grouped under the physics system.
  14608. this._loadPhysicsSystem();
  14609. // create a frame and canvas
  14610. this._create();
  14611. // load the sector system. (mandatory, fully integrated with Graph)
  14612. this._loadSectorSystem();
  14613. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  14614. this._loadClusterSystem();
  14615. // load the selection system. (mandatory, required by Graph)
  14616. this._loadSelectionSystem();
  14617. // load the selection system. (mandatory, required by Graph)
  14618. this._loadHierarchySystem();
  14619. // apply options
  14620. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14621. this._setScale(1);
  14622. this.setOptions(options);
  14623. // other vars
  14624. this.freezeSimulation = false;// freeze the simulation
  14625. this.cachedFunctions = {};
  14626. // containers for nodes and edges
  14627. this.calculationNodes = {};
  14628. this.calculationNodeIndices = [];
  14629. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  14630. this.nodes = {}; // object with Node objects
  14631. this.edges = {}; // object with Edge objects
  14632. // position and scale variables and objects
  14633. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  14634. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  14635. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  14636. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  14637. this.scale = 1; // defining the global scale variable in the constructor
  14638. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  14639. // datasets or dataviews
  14640. this.nodesData = null; // A DataSet or DataView
  14641. this.edgesData = null; // A DataSet or DataView
  14642. // create event listeners used to subscribe on the DataSets of the nodes and edges
  14643. this.nodesListeners = {
  14644. 'add': function (event, params) {
  14645. graph._addNodes(params.items);
  14646. graph.start();
  14647. },
  14648. 'update': function (event, params) {
  14649. graph._updateNodes(params.items);
  14650. graph.start();
  14651. },
  14652. 'remove': function (event, params) {
  14653. graph._removeNodes(params.items);
  14654. graph.start();
  14655. }
  14656. };
  14657. this.edgesListeners = {
  14658. 'add': function (event, params) {
  14659. graph._addEdges(params.items);
  14660. graph.start();
  14661. },
  14662. 'update': function (event, params) {
  14663. graph._updateEdges(params.items);
  14664. graph.start();
  14665. },
  14666. 'remove': function (event, params) {
  14667. graph._removeEdges(params.items);
  14668. graph.start();
  14669. }
  14670. };
  14671. // properties for the animation
  14672. this.moving = true;
  14673. this.timer = undefined; // Scheduling function. Is definded in this.start();
  14674. // load data (the disable start variable will be the same as the enabled clustering)
  14675. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  14676. // hierarchical layout
  14677. this.initializing = false;
  14678. if (this.constants.hierarchicalLayout.enabled == true) {
  14679. this._setupHierarchicalLayout();
  14680. }
  14681. else {
  14682. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  14683. if (this.stabilize == false) {
  14684. this.zoomExtent(true,this.constants.clustering.enabled);
  14685. }
  14686. }
  14687. // if clustering is disabled, the simulation will have started in the setData function
  14688. if (this.constants.clustering.enabled) {
  14689. this.startWithClustering();
  14690. }
  14691. }
  14692. // Extend Graph with an Emitter mixin
  14693. Emitter(Graph.prototype);
  14694. /**
  14695. * Get the script path where the vis.js library is located
  14696. *
  14697. * @returns {string | null} path Path or null when not found. Path does not
  14698. * end with a slash.
  14699. * @private
  14700. */
  14701. Graph.prototype._getScriptPath = function() {
  14702. var scripts = document.getElementsByTagName( 'script' );
  14703. // find script named vis.js or vis.min.js
  14704. for (var i = 0; i < scripts.length; i++) {
  14705. var src = scripts[i].src;
  14706. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  14707. if (match) {
  14708. // return path without the script name
  14709. return src.substring(0, src.length - match[0].length);
  14710. }
  14711. }
  14712. return null;
  14713. };
  14714. /**
  14715. * Find the center position of the graph
  14716. * @private
  14717. */
  14718. Graph.prototype._getRange = function() {
  14719. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  14720. for (var nodeId in this.nodes) {
  14721. if (this.nodes.hasOwnProperty(nodeId)) {
  14722. node = this.nodes[nodeId];
  14723. if (minX > (node.x)) {minX = node.x;}
  14724. if (maxX < (node.x)) {maxX = node.x;}
  14725. if (minY > (node.y)) {minY = node.y;}
  14726. if (maxY < (node.y)) {maxY = node.y;}
  14727. }
  14728. }
  14729. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  14730. minY = 0, maxY = 0, minX = 0, maxX = 0;
  14731. }
  14732. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14733. };
  14734. /**
  14735. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14736. * @returns {{x: number, y: number}}
  14737. * @private
  14738. */
  14739. Graph.prototype._findCenter = function(range) {
  14740. return {x: (0.5 * (range.maxX + range.minX)),
  14741. y: (0.5 * (range.maxY + range.minY))};
  14742. };
  14743. /**
  14744. * center the graph
  14745. *
  14746. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14747. */
  14748. Graph.prototype._centerGraph = function(range) {
  14749. var center = this._findCenter(range);
  14750. center.x *= this.scale;
  14751. center.y *= this.scale;
  14752. center.x -= 0.5 * this.frame.canvas.clientWidth;
  14753. center.y -= 0.5 * this.frame.canvas.clientHeight;
  14754. this._setTranslation(-center.x,-center.y); // set at 0,0
  14755. };
  14756. /**
  14757. * This function zooms out to fit all data on screen based on amount of nodes
  14758. *
  14759. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  14760. * @param {Boolean} [disableStart] | If true, start is not called.
  14761. */
  14762. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  14763. if (initialZoom === undefined) {
  14764. initialZoom = false;
  14765. }
  14766. if (disableStart === undefined) {
  14767. disableStart = false;
  14768. }
  14769. var range = this._getRange();
  14770. var zoomLevel;
  14771. if (initialZoom == true) {
  14772. var numberOfNodes = this.nodeIndices.length;
  14773. if (this.constants.smoothCurves == true) {
  14774. if (this.constants.clustering.enabled == true &&
  14775. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14776. zoomLevel = 49.07548 / (numberOfNodes + 142.05338) + 9.1444e-04; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14777. }
  14778. else {
  14779. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14780. }
  14781. }
  14782. else {
  14783. if (this.constants.clustering.enabled == true &&
  14784. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14785. zoomLevel = 77.5271985 / (numberOfNodes + 187.266146) + 4.76710517e-05; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14786. }
  14787. else {
  14788. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14789. }
  14790. }
  14791. // correct for larger canvasses.
  14792. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  14793. zoomLevel *= factor;
  14794. }
  14795. else {
  14796. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  14797. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  14798. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  14799. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  14800. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  14801. }
  14802. if (zoomLevel > 1.0) {
  14803. zoomLevel = 1.0;
  14804. }
  14805. this._setScale(zoomLevel);
  14806. this._centerGraph(range);
  14807. if (disableStart == false) {
  14808. this.moving = true;
  14809. this.start();
  14810. }
  14811. };
  14812. /**
  14813. * Update the this.nodeIndices with the most recent node index list
  14814. * @private
  14815. */
  14816. Graph.prototype._updateNodeIndexList = function() {
  14817. this._clearNodeIndexList();
  14818. for (var idx in this.nodes) {
  14819. if (this.nodes.hasOwnProperty(idx)) {
  14820. this.nodeIndices.push(idx);
  14821. }
  14822. }
  14823. };
  14824. /**
  14825. * Set nodes and edges, and optionally options as well.
  14826. *
  14827. * @param {Object} data Object containing parameters:
  14828. * {Array | DataSet | DataView} [nodes] Array with nodes
  14829. * {Array | DataSet | DataView} [edges] Array with edges
  14830. * {String} [dot] String containing data in DOT format
  14831. * {Options} [options] Object with options
  14832. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  14833. */
  14834. Graph.prototype.setData = function(data, disableStart) {
  14835. if (disableStart === undefined) {
  14836. disableStart = false;
  14837. }
  14838. if (data && data.dot && (data.nodes || data.edges)) {
  14839. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  14840. ' parameter pair "nodes" and "edges", but not both.');
  14841. }
  14842. // set options
  14843. this.setOptions(data && data.options);
  14844. // set all data
  14845. if (data && data.dot) {
  14846. // parse DOT file
  14847. if(data && data.dot) {
  14848. var dotData = vis.util.DOTToGraph(data.dot);
  14849. this.setData(dotData);
  14850. return;
  14851. }
  14852. }
  14853. else {
  14854. this._setNodes(data && data.nodes);
  14855. this._setEdges(data && data.edges);
  14856. }
  14857. this._putDataInSector();
  14858. if (!disableStart) {
  14859. // find a stable position or start animating to a stable position
  14860. if (this.stabilize) {
  14861. var me = this;
  14862. setTimeout(function() {me._stabilize(); me.start();},0)
  14863. }
  14864. else {
  14865. this.start();
  14866. }
  14867. }
  14868. };
  14869. /**
  14870. * Set options
  14871. * @param {Object} options
  14872. * @param {Boolean} [initializeView] | set zoom and translation to default.
  14873. */
  14874. Graph.prototype.setOptions = function (options) {
  14875. if (options) {
  14876. var prop;
  14877. // retrieve parameter values
  14878. if (options.width !== undefined) {this.width = options.width;}
  14879. if (options.height !== undefined) {this.height = options.height;}
  14880. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14881. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14882. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14883. if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;}
  14884. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14885. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  14886. if (options.moveable !== undefined) {this.constants.moveable = options.moveable;}
  14887. if (options.zoomable !== undefined) {this.constants.zoomable = options.zoomable;}
  14888. if (options.labels !== undefined) {
  14889. for (prop in options.labels) {
  14890. if (options.labels.hasOwnProperty(prop)) {
  14891. this.constants.labels[prop] = options.labels[prop];
  14892. }
  14893. }
  14894. }
  14895. if (options.onAdd) {
  14896. this.triggerFunctions.add = options.onAdd;
  14897. }
  14898. if (options.onEdit) {
  14899. this.triggerFunctions.edit = options.onEdit;
  14900. }
  14901. if (options.onConnect) {
  14902. this.triggerFunctions.connect = options.onConnect;
  14903. }
  14904. if (options.onDelete) {
  14905. this.triggerFunctions.del = options.onDelete;
  14906. }
  14907. if (options.physics) {
  14908. if (options.physics.barnesHut) {
  14909. this.constants.physics.barnesHut.enabled = true;
  14910. for (prop in options.physics.barnesHut) {
  14911. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14912. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14913. }
  14914. }
  14915. }
  14916. if (options.physics.repulsion) {
  14917. this.constants.physics.barnesHut.enabled = false;
  14918. for (prop in options.physics.repulsion) {
  14919. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14920. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14921. }
  14922. }
  14923. }
  14924. if (options.physics.hierarchicalRepulsion) {
  14925. this.constants.hierarchicalLayout.enabled = true;
  14926. this.constants.physics.hierarchicalRepulsion.enabled = true;
  14927. this.constants.physics.barnesHut.enabled = false;
  14928. for (prop in options.physics.hierarchicalRepulsion) {
  14929. if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) {
  14930. this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop];
  14931. }
  14932. }
  14933. }
  14934. }
  14935. if (options.hierarchicalLayout) {
  14936. this.constants.hierarchicalLayout.enabled = true;
  14937. for (prop in options.hierarchicalLayout) {
  14938. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14939. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14940. }
  14941. }
  14942. }
  14943. else if (options.hierarchicalLayout !== undefined) {
  14944. this.constants.hierarchicalLayout.enabled = false;
  14945. }
  14946. if (options.clustering) {
  14947. this.constants.clustering.enabled = true;
  14948. for (prop in options.clustering) {
  14949. if (options.clustering.hasOwnProperty(prop)) {
  14950. this.constants.clustering[prop] = options.clustering[prop];
  14951. }
  14952. }
  14953. }
  14954. else if (options.clustering !== undefined) {
  14955. this.constants.clustering.enabled = false;
  14956. }
  14957. if (options.navigation) {
  14958. this.constants.navigation.enabled = true;
  14959. for (prop in options.navigation) {
  14960. if (options.navigation.hasOwnProperty(prop)) {
  14961. this.constants.navigation[prop] = options.navigation[prop];
  14962. }
  14963. }
  14964. }
  14965. else if (options.navigation !== undefined) {
  14966. this.constants.navigation.enabled = false;
  14967. }
  14968. if (options.keyboard) {
  14969. this.constants.keyboard.enabled = true;
  14970. for (prop in options.keyboard) {
  14971. if (options.keyboard.hasOwnProperty(prop)) {
  14972. this.constants.keyboard[prop] = options.keyboard[prop];
  14973. }
  14974. }
  14975. }
  14976. else if (options.keyboard !== undefined) {
  14977. this.constants.keyboard.enabled = false;
  14978. }
  14979. if (options.dataManipulation) {
  14980. this.constants.dataManipulation.enabled = true;
  14981. for (prop in options.dataManipulation) {
  14982. if (options.dataManipulation.hasOwnProperty(prop)) {
  14983. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14984. }
  14985. }
  14986. }
  14987. else if (options.dataManipulation !== undefined) {
  14988. this.constants.dataManipulation.enabled = false;
  14989. }
  14990. // TODO: work out these options and document them
  14991. if (options.edges) {
  14992. for (prop in options.edges) {
  14993. if (options.edges.hasOwnProperty(prop)) {
  14994. if (typeof options.edges[prop] != "object") {
  14995. this.constants.edges[prop] = options.edges[prop];
  14996. }
  14997. }
  14998. }
  14999. if (options.edges.color !== undefined) {
  15000. if (util.isString(options.edges.color)) {
  15001. this.constants.edges.color = {};
  15002. this.constants.edges.color.color = options.edges.color;
  15003. this.constants.edges.color.highlight = options.edges.color;
  15004. }
  15005. else {
  15006. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  15007. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  15008. }
  15009. }
  15010. if (!options.edges.fontColor) {
  15011. if (options.edges.color !== undefined) {
  15012. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  15013. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  15014. }
  15015. }
  15016. // Added to support dashed lines
  15017. // David Jordan
  15018. // 2012-08-08
  15019. if (options.edges.dash) {
  15020. if (options.edges.dash.length !== undefined) {
  15021. this.constants.edges.dash.length = options.edges.dash.length;
  15022. }
  15023. if (options.edges.dash.gap !== undefined) {
  15024. this.constants.edges.dash.gap = options.edges.dash.gap;
  15025. }
  15026. if (options.edges.dash.altLength !== undefined) {
  15027. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  15028. }
  15029. }
  15030. }
  15031. if (options.nodes) {
  15032. for (prop in options.nodes) {
  15033. if (options.nodes.hasOwnProperty(prop)) {
  15034. this.constants.nodes[prop] = options.nodes[prop];
  15035. }
  15036. }
  15037. if (options.nodes.color) {
  15038. this.constants.nodes.color = util.parseColor(options.nodes.color);
  15039. }
  15040. /*
  15041. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  15042. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  15043. */
  15044. }
  15045. if (options.groups) {
  15046. for (var groupname in options.groups) {
  15047. if (options.groups.hasOwnProperty(groupname)) {
  15048. var group = options.groups[groupname];
  15049. this.groups.add(groupname, group);
  15050. }
  15051. }
  15052. }
  15053. if (options.tooltip) {
  15054. for (prop in options.tooltip) {
  15055. if (options.tooltip.hasOwnProperty(prop)) {
  15056. this.constants.tooltip[prop] = options.tooltip[prop];
  15057. }
  15058. }
  15059. if (options.tooltip.color) {
  15060. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  15061. }
  15062. }
  15063. }
  15064. // (Re)loading the mixins that can be enabled or disabled in the options.
  15065. // load the force calculation functions, grouped under the physics system.
  15066. this._loadPhysicsSystem();
  15067. // load the navigation system.
  15068. this._loadNavigationControls();
  15069. // load the data manipulation system
  15070. this._loadManipulationSystem();
  15071. // configure the smooth curves
  15072. this._configureSmoothCurves();
  15073. // bind keys. If disabled, this will not do anything;
  15074. this._createKeyBinds();
  15075. this.setSize(this.width, this.height);
  15076. this.moving = true;
  15077. this.start();
  15078. };
  15079. /**
  15080. * Create the main frame for the Graph.
  15081. * This function is executed once when a Graph object is created. The frame
  15082. * contains a canvas, and this canvas contains all objects like the axis and
  15083. * nodes.
  15084. * @private
  15085. */
  15086. Graph.prototype._create = function () {
  15087. // remove all elements from the container element.
  15088. while (this.containerElement.hasChildNodes()) {
  15089. this.containerElement.removeChild(this.containerElement.firstChild);
  15090. }
  15091. this.frame = document.createElement('div');
  15092. this.frame.className = 'graph-frame';
  15093. this.frame.style.position = 'relative';
  15094. this.frame.style.overflow = 'hidden';
  15095. // create the graph canvas (HTML canvas element)
  15096. this.frame.canvas = document.createElement( 'canvas' );
  15097. this.frame.canvas.style.position = 'relative';
  15098. this.frame.appendChild(this.frame.canvas);
  15099. if (!this.frame.canvas.getContext) {
  15100. var noCanvas = document.createElement( 'DIV' );
  15101. noCanvas.style.color = 'red';
  15102. noCanvas.style.fontWeight = 'bold' ;
  15103. noCanvas.style.padding = '10px';
  15104. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  15105. this.frame.canvas.appendChild(noCanvas);
  15106. }
  15107. var me = this;
  15108. this.drag = {};
  15109. this.pinch = {};
  15110. this.hammer = Hammer(this.frame.canvas, {
  15111. prevent_default: true
  15112. });
  15113. this.hammer.on('tap', me._onTap.bind(me) );
  15114. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  15115. this.hammer.on('hold', me._onHold.bind(me) );
  15116. this.hammer.on('pinch', me._onPinch.bind(me) );
  15117. this.hammer.on('touch', me._onTouch.bind(me) );
  15118. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  15119. this.hammer.on('drag', me._onDrag.bind(me) );
  15120. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  15121. this.hammer.on('release', me._onRelease.bind(me) );
  15122. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  15123. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  15124. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  15125. // add the frame to the container element
  15126. this.containerElement.appendChild(this.frame);
  15127. };
  15128. /**
  15129. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  15130. * @private
  15131. */
  15132. Graph.prototype._createKeyBinds = function() {
  15133. var me = this;
  15134. this.mousetrap = mousetrap;
  15135. this.mousetrap.reset();
  15136. if (this.constants.keyboard.enabled == true) {
  15137. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  15138. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  15139. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  15140. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  15141. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  15142. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  15143. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  15144. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  15145. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  15146. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  15147. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  15148. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  15149. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  15150. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  15151. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  15152. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  15153. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  15154. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  15155. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  15156. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  15157. }
  15158. if (this.constants.dataManipulation.enabled == true) {
  15159. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  15160. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  15161. }
  15162. };
  15163. /**
  15164. * Get the pointer location from a touch location
  15165. * @param {{pageX: Number, pageY: Number}} touch
  15166. * @return {{x: Number, y: Number}} pointer
  15167. * @private
  15168. */
  15169. Graph.prototype._getPointer = function (touch) {
  15170. return {
  15171. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  15172. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  15173. };
  15174. };
  15175. /**
  15176. * On start of a touch gesture, store the pointer
  15177. * @param event
  15178. * @private
  15179. */
  15180. Graph.prototype._onTouch = function (event) {
  15181. this.drag.pointer = this._getPointer(event.gesture.center);
  15182. this.drag.pinched = false;
  15183. this.pinch.scale = this._getScale();
  15184. this._handleTouch(this.drag.pointer);
  15185. };
  15186. /**
  15187. * handle drag start event
  15188. * @private
  15189. */
  15190. Graph.prototype._onDragStart = function () {
  15191. this._handleDragStart();
  15192. };
  15193. /**
  15194. * This function is called by _onDragStart.
  15195. * It is separated out because we can then overload it for the datamanipulation system.
  15196. *
  15197. * @private
  15198. */
  15199. Graph.prototype._handleDragStart = function() {
  15200. var drag = this.drag;
  15201. var node = this._getNodeAt(drag.pointer);
  15202. // note: drag.pointer is set in _onTouch to get the initial touch location
  15203. drag.dragging = true;
  15204. drag.selection = [];
  15205. drag.translation = this._getTranslation();
  15206. drag.nodeId = null;
  15207. if (node != null) {
  15208. drag.nodeId = node.id;
  15209. // select the clicked node if not yet selected
  15210. if (!node.isSelected()) {
  15211. this._selectObject(node,false);
  15212. }
  15213. // create an array with the selected nodes and their original location and status
  15214. for (var objectId in this.selectionObj.nodes) {
  15215. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  15216. var object = this.selectionObj.nodes[objectId];
  15217. var s = {
  15218. id: object.id,
  15219. node: object,
  15220. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  15221. x: object.x,
  15222. y: object.y,
  15223. xFixed: object.xFixed,
  15224. yFixed: object.yFixed
  15225. };
  15226. object.xFixed = true;
  15227. object.yFixed = true;
  15228. drag.selection.push(s);
  15229. }
  15230. }
  15231. }
  15232. };
  15233. /**
  15234. * handle drag event
  15235. * @private
  15236. */
  15237. Graph.prototype._onDrag = function (event) {
  15238. this._handleOnDrag(event)
  15239. };
  15240. /**
  15241. * This function is called by _onDrag.
  15242. * It is separated out because we can then overload it for the datamanipulation system.
  15243. *
  15244. * @private
  15245. */
  15246. Graph.prototype._handleOnDrag = function(event) {
  15247. if (this.drag.pinched) {
  15248. return;
  15249. }
  15250. var pointer = this._getPointer(event.gesture.center);
  15251. var me = this,
  15252. drag = this.drag,
  15253. selection = drag.selection;
  15254. if (selection && selection.length) {
  15255. // calculate delta's and new location
  15256. var deltaX = pointer.x - drag.pointer.x,
  15257. deltaY = pointer.y - drag.pointer.y;
  15258. // update position of all selected nodes
  15259. selection.forEach(function (s) {
  15260. var node = s.node;
  15261. if (!s.xFixed) {
  15262. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  15263. }
  15264. if (!s.yFixed) {
  15265. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  15266. }
  15267. });
  15268. // start _animationStep if not yet running
  15269. if (!this.moving) {
  15270. this.moving = true;
  15271. this.start();
  15272. }
  15273. }
  15274. else {
  15275. if (this.constants.moveable == true) {
  15276. // move the graph
  15277. var diffX = pointer.x - this.drag.pointer.x;
  15278. var diffY = pointer.y - this.drag.pointer.y;
  15279. this._setTranslation(
  15280. this.drag.translation.x + diffX,
  15281. this.drag.translation.y + diffY);
  15282. this._redraw();
  15283. this.moving = true;
  15284. this.start();
  15285. }
  15286. }
  15287. };
  15288. /**
  15289. * handle drag start event
  15290. * @private
  15291. */
  15292. Graph.prototype._onDragEnd = function () {
  15293. this.drag.dragging = false;
  15294. var selection = this.drag.selection;
  15295. if (selection) {
  15296. selection.forEach(function (s) {
  15297. // restore original xFixed and yFixed
  15298. s.node.xFixed = s.xFixed;
  15299. s.node.yFixed = s.yFixed;
  15300. });
  15301. }
  15302. };
  15303. /**
  15304. * handle tap/click event: select/unselect a node
  15305. * @private
  15306. */
  15307. Graph.prototype._onTap = function (event) {
  15308. var pointer = this._getPointer(event.gesture.center);
  15309. this.pointerPosition = pointer;
  15310. this._handleTap(pointer);
  15311. };
  15312. /**
  15313. * handle doubletap event
  15314. * @private
  15315. */
  15316. Graph.prototype._onDoubleTap = function (event) {
  15317. var pointer = this._getPointer(event.gesture.center);
  15318. this._handleDoubleTap(pointer);
  15319. };
  15320. /**
  15321. * handle long tap event: multi select nodes
  15322. * @private
  15323. */
  15324. Graph.prototype._onHold = function (event) {
  15325. var pointer = this._getPointer(event.gesture.center);
  15326. this.pointerPosition = pointer;
  15327. this._handleOnHold(pointer);
  15328. };
  15329. /**
  15330. * handle the release of the screen
  15331. *
  15332. * @private
  15333. */
  15334. Graph.prototype._onRelease = function (event) {
  15335. var pointer = this._getPointer(event.gesture.center);
  15336. this._handleOnRelease(pointer);
  15337. };
  15338. /**
  15339. * Handle pinch event
  15340. * @param event
  15341. * @private
  15342. */
  15343. Graph.prototype._onPinch = function (event) {
  15344. var pointer = this._getPointer(event.gesture.center);
  15345. this.drag.pinched = true;
  15346. if (!('scale' in this.pinch)) {
  15347. this.pinch.scale = 1;
  15348. }
  15349. // TODO: enabled moving while pinching?
  15350. var scale = this.pinch.scale * event.gesture.scale;
  15351. this._zoom(scale, pointer)
  15352. };
  15353. /**
  15354. * Zoom the graph in or out
  15355. * @param {Number} scale a number around 1, and between 0.01 and 10
  15356. * @param {{x: Number, y: Number}} pointer Position on screen
  15357. * @return {Number} appliedScale scale is limited within the boundaries
  15358. * @private
  15359. */
  15360. Graph.prototype._zoom = function(scale, pointer) {
  15361. console.log(pointer);
  15362. if (this.constants.zoomable == true) {
  15363. var scaleOld = this._getScale();
  15364. if (scale < 0.00001) {
  15365. scale = 0.00001;
  15366. }
  15367. if (scale > 10) {
  15368. scale = 10;
  15369. }
  15370. // + this.frame.canvas.clientHeight / 2
  15371. var translation = this._getTranslation();
  15372. var scaleFrac = scale / scaleOld;
  15373. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  15374. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  15375. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  15376. "y" : this._canvasToY(pointer.y)};
  15377. this._setScale(scale);
  15378. this._setTranslation(tx, ty);
  15379. this.updateClustersDefault();
  15380. this._redraw();
  15381. if (scaleOld < scale) {
  15382. this.emit("zoom", {direction:"+"});
  15383. }
  15384. else {
  15385. this.emit("zoom", {direction:"-"});
  15386. }
  15387. return scale;
  15388. }
  15389. };
  15390. /**
  15391. * Event handler for mouse wheel event, used to zoom the timeline
  15392. * See http://adomas.org/javascript-mouse-wheel/
  15393. * https://github.com/EightMedia/hammer.js/issues/256
  15394. * @param {MouseEvent} event
  15395. * @private
  15396. */
  15397. Graph.prototype._onMouseWheel = function(event) {
  15398. // retrieve delta
  15399. var delta = 0;
  15400. if (event.wheelDelta) { /* IE/Opera. */
  15401. delta = event.wheelDelta/120;
  15402. } else if (event.detail) { /* Mozilla case. */
  15403. // In Mozilla, sign of delta is different than in IE.
  15404. // Also, delta is multiple of 3.
  15405. delta = -event.detail/3;
  15406. }
  15407. // If delta is nonzero, handle it.
  15408. // Basically, delta is now positive if wheel was scrolled up,
  15409. // and negative, if wheel was scrolled down.
  15410. if (delta) {
  15411. // calculate the new scale
  15412. var scale = this._getScale();
  15413. var zoom = delta / 10;
  15414. if (delta < 0) {
  15415. zoom = zoom / (1 - zoom);
  15416. }
  15417. scale *= (1 + zoom);
  15418. // calculate the pointer location
  15419. var gesture = util.fakeGesture(this, event);
  15420. var pointer = this._getPointer(gesture.center);
  15421. // apply the new scale
  15422. this._zoom(scale, pointer);
  15423. }
  15424. // Prevent default actions caused by mouse wheel.
  15425. event.preventDefault();
  15426. };
  15427. /**
  15428. * Mouse move handler for checking whether the title moves over a node with a title.
  15429. * @param {Event} event
  15430. * @private
  15431. */
  15432. Graph.prototype._onMouseMoveTitle = function (event) {
  15433. var gesture = util.fakeGesture(this, event);
  15434. var pointer = this._getPointer(gesture.center);
  15435. // check if the previously selected node is still selected
  15436. if (this.popupNode) {
  15437. this._checkHidePopup(pointer);
  15438. }
  15439. // start a timeout that will check if the mouse is positioned above
  15440. // an element
  15441. var me = this;
  15442. var checkShow = function() {
  15443. me._checkShowPopup(pointer);
  15444. };
  15445. if (this.popupTimer) {
  15446. clearInterval(this.popupTimer); // stop any running calculationTimer
  15447. }
  15448. if (!this.drag.dragging) {
  15449. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  15450. }
  15451. };
  15452. /**
  15453. * Check if there is an element on the given position in the graph
  15454. * (a node or edge). If so, and if this element has a title,
  15455. * show a popup window with its title.
  15456. *
  15457. * @param {{x:Number, y:Number}} pointer
  15458. * @private
  15459. */
  15460. Graph.prototype._checkShowPopup = function (pointer) {
  15461. var obj = {
  15462. left: this._canvasToX(pointer.x),
  15463. top: this._canvasToY(pointer.y),
  15464. right: this._canvasToX(pointer.x),
  15465. bottom: this._canvasToY(pointer.y)
  15466. };
  15467. var id;
  15468. var lastPopupNode = this.popupNode;
  15469. if (this.popupNode == undefined) {
  15470. // search the nodes for overlap, select the top one in case of multiple nodes
  15471. var nodes = this.nodes;
  15472. for (id in nodes) {
  15473. if (nodes.hasOwnProperty(id)) {
  15474. var node = nodes[id];
  15475. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  15476. this.popupNode = node;
  15477. break;
  15478. }
  15479. }
  15480. }
  15481. }
  15482. if (this.popupNode === undefined) {
  15483. // search the edges for overlap
  15484. var edges = this.edges;
  15485. for (id in edges) {
  15486. if (edges.hasOwnProperty(id)) {
  15487. var edge = edges[id];
  15488. if (edge.connected && (edge.getTitle() !== undefined) &&
  15489. edge.isOverlappingWith(obj)) {
  15490. this.popupNode = edge;
  15491. break;
  15492. }
  15493. }
  15494. }
  15495. }
  15496. if (this.popupNode) {
  15497. // show popup message window
  15498. if (this.popupNode != lastPopupNode) {
  15499. var me = this;
  15500. if (!me.popup) {
  15501. me.popup = new Popup(me.frame, me.constants.tooltip);
  15502. }
  15503. // adjust a small offset such that the mouse cursor is located in the
  15504. // bottom left location of the popup, and you can easily move over the
  15505. // popup area
  15506. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  15507. me.popup.setText(me.popupNode.getTitle());
  15508. me.popup.show();
  15509. }
  15510. }
  15511. else {
  15512. if (this.popup) {
  15513. this.popup.hide();
  15514. }
  15515. }
  15516. };
  15517. /**
  15518. * Check if the popup must be hided, which is the case when the mouse is no
  15519. * longer hovering on the object
  15520. * @param {{x:Number, y:Number}} pointer
  15521. * @private
  15522. */
  15523. Graph.prototype._checkHidePopup = function (pointer) {
  15524. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  15525. this.popupNode = undefined;
  15526. if (this.popup) {
  15527. this.popup.hide();
  15528. }
  15529. }
  15530. };
  15531. /**
  15532. * Set a new size for the graph
  15533. * @param {string} width Width in pixels or percentage (for example '800px'
  15534. * or '50%')
  15535. * @param {string} height Height in pixels or percentage (for example '400px'
  15536. * or '30%')
  15537. */
  15538. Graph.prototype.setSize = function(width, height) {
  15539. this.frame.style.width = width;
  15540. this.frame.style.height = height;
  15541. this.frame.canvas.style.width = '100%';
  15542. this.frame.canvas.style.height = '100%';
  15543. this.frame.canvas.width = this.frame.canvas.clientWidth;
  15544. this.frame.canvas.height = this.frame.canvas.clientHeight;
  15545. if (this.manipulationDiv !== undefined) {
  15546. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  15547. }
  15548. if (this.navigationDivs !== undefined) {
  15549. if (this.navigationDivs['wrapper'] !== undefined) {
  15550. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  15551. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  15552. }
  15553. }
  15554. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  15555. };
  15556. /**
  15557. * Set a data set with nodes for the graph
  15558. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  15559. * @private
  15560. */
  15561. Graph.prototype._setNodes = function(nodes) {
  15562. var oldNodesData = this.nodesData;
  15563. if (nodes instanceof DataSet || nodes instanceof DataView) {
  15564. this.nodesData = nodes;
  15565. }
  15566. else if (nodes instanceof Array) {
  15567. this.nodesData = new DataSet();
  15568. this.nodesData.add(nodes);
  15569. }
  15570. else if (!nodes) {
  15571. this.nodesData = new DataSet();
  15572. }
  15573. else {
  15574. throw new TypeError('Array or DataSet expected');
  15575. }
  15576. if (oldNodesData) {
  15577. // unsubscribe from old dataset
  15578. util.forEach(this.nodesListeners, function (callback, event) {
  15579. oldNodesData.off(event, callback);
  15580. });
  15581. }
  15582. // remove drawn nodes
  15583. this.nodes = {};
  15584. if (this.nodesData) {
  15585. // subscribe to new dataset
  15586. var me = this;
  15587. util.forEach(this.nodesListeners, function (callback, event) {
  15588. me.nodesData.on(event, callback);
  15589. });
  15590. // draw all new nodes
  15591. var ids = this.nodesData.getIds();
  15592. this._addNodes(ids);
  15593. }
  15594. this._updateSelection();
  15595. };
  15596. /**
  15597. * Add nodes
  15598. * @param {Number[] | String[]} ids
  15599. * @private
  15600. */
  15601. Graph.prototype._addNodes = function(ids) {
  15602. var id;
  15603. for (var i = 0, len = ids.length; i < len; i++) {
  15604. id = ids[i];
  15605. var data = this.nodesData.get(id);
  15606. var node = new Node(data, this.images, this.groups, this.constants);
  15607. this.nodes[id] = node; // note: this may replace an existing node
  15608. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  15609. var radius = 10 * 0.1*ids.length;
  15610. var angle = 2 * Math.PI * Math.random();
  15611. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  15612. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  15613. }
  15614. this.moving = true;
  15615. }
  15616. this._updateNodeIndexList();
  15617. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15618. this._resetLevels();
  15619. this._setupHierarchicalLayout();
  15620. }
  15621. this._updateCalculationNodes();
  15622. this._reconnectEdges();
  15623. this._updateValueRange(this.nodes);
  15624. this.updateLabels();
  15625. };
  15626. /**
  15627. * Update existing nodes, or create them when not yet existing
  15628. * @param {Number[] | String[]} ids
  15629. * @private
  15630. */
  15631. Graph.prototype._updateNodes = function(ids) {
  15632. var nodes = this.nodes,
  15633. nodesData = this.nodesData;
  15634. for (var i = 0, len = ids.length; i < len; i++) {
  15635. var id = ids[i];
  15636. var node = nodes[id];
  15637. var data = nodesData.get(id);
  15638. if (node) {
  15639. // update node
  15640. node.setProperties(data, this.constants);
  15641. }
  15642. else {
  15643. // create node
  15644. node = new Node(properties, this.images, this.groups, this.constants);
  15645. nodes[id] = node;
  15646. }
  15647. }
  15648. this.moving = true;
  15649. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15650. this._resetLevels();
  15651. this._setupHierarchicalLayout();
  15652. }
  15653. this._updateNodeIndexList();
  15654. this._reconnectEdges();
  15655. this._updateValueRange(nodes);
  15656. };
  15657. /**
  15658. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  15659. * @param {Number[] | String[]} ids
  15660. * @private
  15661. */
  15662. Graph.prototype._removeNodes = function(ids) {
  15663. var nodes = this.nodes;
  15664. for (var i = 0, len = ids.length; i < len; i++) {
  15665. var id = ids[i];
  15666. delete nodes[id];
  15667. }
  15668. this._updateNodeIndexList();
  15669. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15670. this._resetLevels();
  15671. this._setupHierarchicalLayout();
  15672. }
  15673. this._updateCalculationNodes();
  15674. this._reconnectEdges();
  15675. this._updateSelection();
  15676. this._updateValueRange(nodes);
  15677. };
  15678. /**
  15679. * Load edges by reading the data table
  15680. * @param {Array | DataSet | DataView} edges The data containing the edges.
  15681. * @private
  15682. * @private
  15683. */
  15684. Graph.prototype._setEdges = function(edges) {
  15685. var oldEdgesData = this.edgesData;
  15686. if (edges instanceof DataSet || edges instanceof DataView) {
  15687. this.edgesData = edges;
  15688. }
  15689. else if (edges instanceof Array) {
  15690. this.edgesData = new DataSet();
  15691. this.edgesData.add(edges);
  15692. }
  15693. else if (!edges) {
  15694. this.edgesData = new DataSet();
  15695. }
  15696. else {
  15697. throw new TypeError('Array or DataSet expected');
  15698. }
  15699. if (oldEdgesData) {
  15700. // unsubscribe from old dataset
  15701. util.forEach(this.edgesListeners, function (callback, event) {
  15702. oldEdgesData.off(event, callback);
  15703. });
  15704. }
  15705. // remove drawn edges
  15706. this.edges = {};
  15707. if (this.edgesData) {
  15708. // subscribe to new dataset
  15709. var me = this;
  15710. util.forEach(this.edgesListeners, function (callback, event) {
  15711. me.edgesData.on(event, callback);
  15712. });
  15713. // draw all new nodes
  15714. var ids = this.edgesData.getIds();
  15715. this._addEdges(ids);
  15716. }
  15717. this._reconnectEdges();
  15718. };
  15719. /**
  15720. * Add edges
  15721. * @param {Number[] | String[]} ids
  15722. * @private
  15723. */
  15724. Graph.prototype._addEdges = function (ids) {
  15725. var edges = this.edges,
  15726. edgesData = this.edgesData;
  15727. for (var i = 0, len = ids.length; i < len; i++) {
  15728. var id = ids[i];
  15729. var oldEdge = edges[id];
  15730. if (oldEdge) {
  15731. oldEdge.disconnect();
  15732. }
  15733. var data = edgesData.get(id, {"showInternalIds" : true});
  15734. edges[id] = new Edge(data, this, this.constants);
  15735. }
  15736. this.moving = true;
  15737. this._updateValueRange(edges);
  15738. this._createBezierNodes();
  15739. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15740. this._resetLevels();
  15741. this._setupHierarchicalLayout();
  15742. }
  15743. this._updateCalculationNodes();
  15744. };
  15745. /**
  15746. * Update existing edges, or create them when not yet existing
  15747. * @param {Number[] | String[]} ids
  15748. * @private
  15749. */
  15750. Graph.prototype._updateEdges = function (ids) {
  15751. var edges = this.edges,
  15752. edgesData = this.edgesData;
  15753. for (var i = 0, len = ids.length; i < len; i++) {
  15754. var id = ids[i];
  15755. var data = edgesData.get(id);
  15756. var edge = edges[id];
  15757. if (edge) {
  15758. // update edge
  15759. edge.disconnect();
  15760. edge.setProperties(data, this.constants);
  15761. edge.connect();
  15762. }
  15763. else {
  15764. // create edge
  15765. edge = new Edge(data, this, this.constants);
  15766. this.edges[id] = edge;
  15767. }
  15768. }
  15769. this._createBezierNodes();
  15770. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15771. this._resetLevels();
  15772. this._setupHierarchicalLayout();
  15773. }
  15774. this.moving = true;
  15775. this._updateValueRange(edges);
  15776. };
  15777. /**
  15778. * Remove existing edges. Non existing ids will be ignored
  15779. * @param {Number[] | String[]} ids
  15780. * @private
  15781. */
  15782. Graph.prototype._removeEdges = function (ids) {
  15783. var edges = this.edges;
  15784. for (var i = 0, len = ids.length; i < len; i++) {
  15785. var id = ids[i];
  15786. var edge = edges[id];
  15787. if (edge) {
  15788. if (edge.via != null) {
  15789. delete this.sectors['support']['nodes'][edge.via.id];
  15790. }
  15791. edge.disconnect();
  15792. delete edges[id];
  15793. }
  15794. }
  15795. this.moving = true;
  15796. this._updateValueRange(edges);
  15797. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15798. this._resetLevels();
  15799. this._setupHierarchicalLayout();
  15800. }
  15801. this._updateCalculationNodes();
  15802. };
  15803. /**
  15804. * Reconnect all edges
  15805. * @private
  15806. */
  15807. Graph.prototype._reconnectEdges = function() {
  15808. var id,
  15809. nodes = this.nodes,
  15810. edges = this.edges;
  15811. for (id in nodes) {
  15812. if (nodes.hasOwnProperty(id)) {
  15813. nodes[id].edges = [];
  15814. }
  15815. }
  15816. for (id in edges) {
  15817. if (edges.hasOwnProperty(id)) {
  15818. var edge = edges[id];
  15819. edge.from = null;
  15820. edge.to = null;
  15821. edge.connect();
  15822. }
  15823. }
  15824. };
  15825. /**
  15826. * Update the values of all object in the given array according to the current
  15827. * value range of the objects in the array.
  15828. * @param {Object} obj An object containing a set of Edges or Nodes
  15829. * The objects must have a method getValue() and
  15830. * setValueRange(min, max).
  15831. * @private
  15832. */
  15833. Graph.prototype._updateValueRange = function(obj) {
  15834. var id;
  15835. // determine the range of the objects
  15836. var valueMin = undefined;
  15837. var valueMax = undefined;
  15838. for (id in obj) {
  15839. if (obj.hasOwnProperty(id)) {
  15840. var value = obj[id].getValue();
  15841. if (value !== undefined) {
  15842. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  15843. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  15844. }
  15845. }
  15846. }
  15847. // adjust the range of all objects
  15848. if (valueMin !== undefined && valueMax !== undefined) {
  15849. for (id in obj) {
  15850. if (obj.hasOwnProperty(id)) {
  15851. obj[id].setValueRange(valueMin, valueMax);
  15852. }
  15853. }
  15854. }
  15855. };
  15856. /**
  15857. * Redraw the graph with the current data
  15858. * chart will be resized too.
  15859. */
  15860. Graph.prototype.redraw = function() {
  15861. this.setSize(this.width, this.height);
  15862. this._redraw();
  15863. };
  15864. /**
  15865. * Redraw the graph with the current data
  15866. * @private
  15867. */
  15868. Graph.prototype._redraw = function() {
  15869. var ctx = this.frame.canvas.getContext('2d');
  15870. // clear the canvas
  15871. var w = this.frame.canvas.width;
  15872. var h = this.frame.canvas.height;
  15873. ctx.clearRect(0, 0, w, h);
  15874. // set scaling and translation
  15875. ctx.save();
  15876. ctx.translate(this.translation.x, this.translation.y);
  15877. ctx.scale(this.scale, this.scale);
  15878. this.canvasTopLeft = {
  15879. "x": this._canvasToX(0),
  15880. "y": this._canvasToY(0)
  15881. };
  15882. this.canvasBottomRight = {
  15883. "x": this._canvasToX(this.frame.canvas.clientWidth),
  15884. "y": this._canvasToY(this.frame.canvas.clientHeight)
  15885. };
  15886. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15887. this._doInAllSectors("_drawEdges",ctx);
  15888. this._doInAllSectors("_drawNodes",ctx,false);
  15889. // this._doInSupportSector("_drawNodes",ctx,true);
  15890. // this._drawTree(ctx,"#F00F0F");
  15891. // restore original scaling and translation
  15892. ctx.restore();
  15893. };
  15894. /**
  15895. * Set the translation of the graph
  15896. * @param {Number} offsetX Horizontal offset
  15897. * @param {Number} offsetY Vertical offset
  15898. * @private
  15899. */
  15900. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15901. if (this.translation === undefined) {
  15902. this.translation = {
  15903. x: 0,
  15904. y: 0
  15905. };
  15906. }
  15907. if (offsetX !== undefined) {
  15908. this.translation.x = offsetX;
  15909. }
  15910. if (offsetY !== undefined) {
  15911. this.translation.y = offsetY;
  15912. }
  15913. this.emit('viewChanged');
  15914. };
  15915. /**
  15916. * Get the translation of the graph
  15917. * @return {Object} translation An object with parameters x and y, both a number
  15918. * @private
  15919. */
  15920. Graph.prototype._getTranslation = function() {
  15921. return {
  15922. x: this.translation.x,
  15923. y: this.translation.y
  15924. };
  15925. };
  15926. /**
  15927. * Scale the graph
  15928. * @param {Number} scale Scaling factor 1.0 is unscaled
  15929. * @private
  15930. */
  15931. Graph.prototype._setScale = function(scale) {
  15932. this.scale = scale;
  15933. };
  15934. /**
  15935. * Get the current scale of the graph
  15936. * @return {Number} scale Scaling factor 1.0 is unscaled
  15937. * @private
  15938. */
  15939. Graph.prototype._getScale = function() {
  15940. return this.scale;
  15941. };
  15942. /**
  15943. * Convert a horizontal point on the HTML canvas to the x-value of the model
  15944. * @param {number} x
  15945. * @returns {number}
  15946. * @private
  15947. */
  15948. Graph.prototype._canvasToX = function(x) {
  15949. return (x - this.translation.x) / this.scale;
  15950. };
  15951. /**
  15952. * Convert an x-value in the model to a horizontal point on the HTML canvas
  15953. * @param {number} x
  15954. * @returns {number}
  15955. * @private
  15956. */
  15957. Graph.prototype._xToCanvas = function(x) {
  15958. return x * this.scale + this.translation.x;
  15959. };
  15960. /**
  15961. * Convert a vertical point on the HTML canvas to the y-value of the model
  15962. * @param {number} y
  15963. * @returns {number}
  15964. * @private
  15965. */
  15966. Graph.prototype._canvasToY = function(y) {
  15967. return (y - this.translation.y) / this.scale;
  15968. };
  15969. /**
  15970. * Convert an y-value in the model to a vertical point on the HTML canvas
  15971. * @param {number} y
  15972. * @returns {number}
  15973. * @private
  15974. */
  15975. Graph.prototype._yToCanvas = function(y) {
  15976. return y * this.scale + this.translation.y ;
  15977. };
  15978. /**
  15979. *
  15980. * @param {object} pos = {x: number, y: number}
  15981. * @returns {{x: number, y: number}}
  15982. * @constructor
  15983. */
  15984. Graph.prototype.canvasToDOM = function(pos) {
  15985. return {x:this._xToCanvas(pos.x),y:this._yToCanvas(pos.y)};
  15986. }
  15987. /**
  15988. *
  15989. * @param {object} pos = {x: number, y: number}
  15990. * @returns {{x: number, y: number}}
  15991. * @constructor
  15992. */
  15993. Graph.prototype.DOMtoCanvas = function(pos) {
  15994. return {x:this._canvasToX(pos.x),y:this._canvasToY(pos.y)};
  15995. }
  15996. /**
  15997. * Redraw all nodes
  15998. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15999. * @param {CanvasRenderingContext2D} ctx
  16000. * @param {Boolean} [alwaysShow]
  16001. * @private
  16002. */
  16003. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  16004. if (alwaysShow === undefined) {
  16005. alwaysShow = false;
  16006. }
  16007. // first draw the unselected nodes
  16008. var nodes = this.nodes;
  16009. var selected = [];
  16010. for (var id in nodes) {
  16011. if (nodes.hasOwnProperty(id)) {
  16012. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  16013. if (nodes[id].isSelected()) {
  16014. selected.push(id);
  16015. }
  16016. else {
  16017. if (nodes[id].inArea() || alwaysShow) {
  16018. nodes[id].draw(ctx);
  16019. }
  16020. }
  16021. }
  16022. }
  16023. // draw the selected nodes on top
  16024. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  16025. if (nodes[selected[s]].inArea() || alwaysShow) {
  16026. nodes[selected[s]].draw(ctx);
  16027. }
  16028. }
  16029. };
  16030. /**
  16031. * Redraw all edges
  16032. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  16033. * @param {CanvasRenderingContext2D} ctx
  16034. * @private
  16035. */
  16036. Graph.prototype._drawEdges = function(ctx) {
  16037. var edges = this.edges;
  16038. for (var id in edges) {
  16039. if (edges.hasOwnProperty(id)) {
  16040. var edge = edges[id];
  16041. edge.setScale(this.scale);
  16042. if (edge.connected) {
  16043. edges[id].draw(ctx);
  16044. }
  16045. }
  16046. }
  16047. };
  16048. /**
  16049. * Find a stable position for all nodes
  16050. * @private
  16051. */
  16052. Graph.prototype._stabilize = function() {
  16053. if (this.constants.freezeForStabilization == true) {
  16054. this._freezeDefinedNodes();
  16055. }
  16056. // find stable position
  16057. var count = 0;
  16058. while (this.moving && count < this.constants.stabilizationIterations) {
  16059. this._physicsTick();
  16060. count++;
  16061. }
  16062. this.zoomExtent(false,true);
  16063. if (this.constants.freezeForStabilization == true) {
  16064. this._restoreFrozenNodes();
  16065. }
  16066. this.emit("stabilized",{iterations:count});
  16067. };
  16068. /**
  16069. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  16070. * because only the supportnodes for the smoothCurves have to settle.
  16071. *
  16072. * @private
  16073. */
  16074. Graph.prototype._freezeDefinedNodes = function() {
  16075. var nodes = this.nodes;
  16076. for (var id in nodes) {
  16077. if (nodes.hasOwnProperty(id)) {
  16078. if (nodes[id].x != null && nodes[id].y != null) {
  16079. nodes[id].fixedData.x = nodes[id].xFixed;
  16080. nodes[id].fixedData.y = nodes[id].yFixed;
  16081. nodes[id].xFixed = true;
  16082. nodes[id].yFixed = true;
  16083. }
  16084. }
  16085. }
  16086. };
  16087. /**
  16088. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  16089. *
  16090. * @private
  16091. */
  16092. Graph.prototype._restoreFrozenNodes = function() {
  16093. var nodes = this.nodes;
  16094. for (var id in nodes) {
  16095. if (nodes.hasOwnProperty(id)) {
  16096. if (nodes[id].fixedData.x != null) {
  16097. nodes[id].xFixed = nodes[id].fixedData.x;
  16098. nodes[id].yFixed = nodes[id].fixedData.y;
  16099. }
  16100. }
  16101. }
  16102. };
  16103. /**
  16104. * Check if any of the nodes is still moving
  16105. * @param {number} vmin the minimum velocity considered as 'moving'
  16106. * @return {boolean} true if moving, false if non of the nodes is moving
  16107. * @private
  16108. */
  16109. Graph.prototype._isMoving = function(vmin) {
  16110. var nodes = this.nodes;
  16111. for (var id in nodes) {
  16112. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  16113. return true;
  16114. }
  16115. }
  16116. return false;
  16117. };
  16118. /**
  16119. * /**
  16120. * Perform one discrete step for all nodes
  16121. *
  16122. * @private
  16123. */
  16124. Graph.prototype._discreteStepNodes = function() {
  16125. var interval = this.physicsDiscreteStepsize;
  16126. var nodes = this.nodes;
  16127. var nodeId;
  16128. var nodesPresent = false;
  16129. if (this.constants.maxVelocity > 0) {
  16130. for (nodeId in nodes) {
  16131. if (nodes.hasOwnProperty(nodeId)) {
  16132. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  16133. nodesPresent = true;
  16134. }
  16135. }
  16136. }
  16137. else {
  16138. for (nodeId in nodes) {
  16139. if (nodes.hasOwnProperty(nodeId)) {
  16140. nodes[nodeId].discreteStep(interval);
  16141. nodesPresent = true;
  16142. }
  16143. }
  16144. }
  16145. if (nodesPresent == true) {
  16146. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  16147. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  16148. this.moving = true;
  16149. }
  16150. else {
  16151. this.moving = this._isMoving(vminCorrected);
  16152. }
  16153. }
  16154. };
  16155. /**
  16156. * A single simulation step (or "tick") in the physics simulation
  16157. *
  16158. * @private
  16159. */
  16160. Graph.prototype._physicsTick = function() {
  16161. if (!this.freezeSimulation) {
  16162. if (this.moving) {
  16163. this._doInAllActiveSectors("_initializeForceCalculation");
  16164. this._doInAllActiveSectors("_discreteStepNodes");
  16165. if (this.constants.smoothCurves) {
  16166. this._doInSupportSector("_discreteStepNodes");
  16167. }
  16168. this._findCenter(this._getRange())
  16169. }
  16170. }
  16171. };
  16172. /**
  16173. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  16174. * It reschedules itself at the beginning of the function
  16175. *
  16176. * @private
  16177. */
  16178. Graph.prototype._animationStep = function() {
  16179. // reset the timer so a new scheduled animation step can be set
  16180. this.timer = undefined;
  16181. // handle the keyboad movement
  16182. this._handleNavigation();
  16183. // this schedules a new animation step
  16184. this.start();
  16185. // start the physics simulation
  16186. var calculationTime = Date.now();
  16187. var maxSteps = 1;
  16188. this._physicsTick();
  16189. var timeRequired = Date.now() - calculationTime;
  16190. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  16191. this._physicsTick();
  16192. timeRequired = Date.now() - calculationTime;
  16193. maxSteps++;
  16194. }
  16195. // start the rendering process
  16196. var renderTime = Date.now();
  16197. this._redraw();
  16198. this.renderTime = Date.now() - renderTime;
  16199. };
  16200. if (typeof window !== 'undefined') {
  16201. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  16202. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  16203. }
  16204. /**
  16205. * Schedule a animation step with the refreshrate interval.
  16206. */
  16207. Graph.prototype.start = function() {
  16208. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  16209. if (!this.timer) {
  16210. var ua = navigator.userAgent.toLowerCase();
  16211. var requiresTimeout = false;
  16212. if (ua.indexOf('msie 9.0') != -1) { // IE 9
  16213. requiresTimeout = true;
  16214. }
  16215. else if (ua.indexOf('safari') != -1) { // safari
  16216. if (ua.indexOf('chrome') <= -1) {
  16217. requiresTimeout = true;
  16218. }
  16219. }
  16220. if (requiresTimeout == true) {
  16221. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  16222. }
  16223. else{
  16224. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  16225. }
  16226. }
  16227. }
  16228. else {
  16229. this._redraw();
  16230. }
  16231. };
  16232. /**
  16233. * Move the graph according to the keyboard presses.
  16234. *
  16235. * @private
  16236. */
  16237. Graph.prototype._handleNavigation = function() {
  16238. if (this.xIncrement != 0 || this.yIncrement != 0) {
  16239. var translation = this._getTranslation();
  16240. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  16241. }
  16242. if (this.zoomIncrement != 0) {
  16243. var center = {
  16244. x: this.frame.canvas.clientWidth / 2,
  16245. y: this.frame.canvas.clientHeight / 2
  16246. };
  16247. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  16248. }
  16249. };
  16250. /**
  16251. * Freeze the _animationStep
  16252. */
  16253. Graph.prototype.toggleFreeze = function() {
  16254. if (this.freezeSimulation == false) {
  16255. this.freezeSimulation = true;
  16256. }
  16257. else {
  16258. this.freezeSimulation = false;
  16259. this.start();
  16260. }
  16261. };
  16262. /**
  16263. * This function cleans the support nodes if they are not needed and adds them when they are.
  16264. *
  16265. * @param {boolean} [disableStart]
  16266. * @private
  16267. */
  16268. Graph.prototype._configureSmoothCurves = function(disableStart) {
  16269. if (disableStart === undefined) {
  16270. disableStart = true;
  16271. }
  16272. if (this.constants.smoothCurves == true) {
  16273. this._createBezierNodes();
  16274. }
  16275. else {
  16276. // delete the support nodes
  16277. this.sectors['support']['nodes'] = {};
  16278. for (var edgeId in this.edges) {
  16279. if (this.edges.hasOwnProperty(edgeId)) {
  16280. this.edges[edgeId].smooth = false;
  16281. this.edges[edgeId].via = null;
  16282. }
  16283. }
  16284. }
  16285. this._updateCalculationNodes();
  16286. if (!disableStart) {
  16287. this.moving = true;
  16288. this.start();
  16289. }
  16290. };
  16291. /**
  16292. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  16293. * are used for the force calculation.
  16294. *
  16295. * @private
  16296. */
  16297. Graph.prototype._createBezierNodes = function() {
  16298. if (this.constants.smoothCurves == true) {
  16299. for (var edgeId in this.edges) {
  16300. if (this.edges.hasOwnProperty(edgeId)) {
  16301. var edge = this.edges[edgeId];
  16302. if (edge.via == null) {
  16303. edge.smooth = true;
  16304. var nodeId = "edgeId:".concat(edge.id);
  16305. this.sectors['support']['nodes'][nodeId] = new Node(
  16306. {id:nodeId,
  16307. mass:1,
  16308. shape:'circle',
  16309. image:"",
  16310. internalMultiplier:1
  16311. },{},{},this.constants);
  16312. edge.via = this.sectors['support']['nodes'][nodeId];
  16313. edge.via.parentEdgeId = edge.id;
  16314. edge.positionBezierNode();
  16315. }
  16316. }
  16317. }
  16318. }
  16319. };
  16320. /**
  16321. * load the functions that load the mixins into the prototype.
  16322. *
  16323. * @private
  16324. */
  16325. Graph.prototype._initializeMixinLoaders = function () {
  16326. for (var mixinFunction in graphMixinLoaders) {
  16327. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  16328. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  16329. }
  16330. }
  16331. };
  16332. /**
  16333. * Load the XY positions of the nodes into the dataset.
  16334. */
  16335. Graph.prototype.storePosition = function() {
  16336. var dataArray = [];
  16337. for (var nodeId in this.nodes) {
  16338. if (this.nodes.hasOwnProperty(nodeId)) {
  16339. var node = this.nodes[nodeId];
  16340. var allowedToMoveX = !this.nodes.xFixed;
  16341. var allowedToMoveY = !this.nodes.yFixed;
  16342. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  16343. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  16344. }
  16345. }
  16346. }
  16347. this.nodesData.update(dataArray);
  16348. };
  16349. /**
  16350. * vis.js module exports
  16351. */
  16352. var vis = {
  16353. util: util,
  16354. DataSet: DataSet,
  16355. DataView: DataView,
  16356. Range: Range,
  16357. stack: stack,
  16358. TimeStep: TimeStep,
  16359. components: {
  16360. items: {
  16361. Item: Item,
  16362. ItemBox: ItemBox,
  16363. ItemPoint: ItemPoint,
  16364. ItemRange: ItemRange
  16365. },
  16366. Component: Component,
  16367. Panel: Panel,
  16368. RootPanel: RootPanel,
  16369. ItemSet: ItemSet,
  16370. TimeAxis: TimeAxis
  16371. },
  16372. graph: {
  16373. Node: Node,
  16374. Edge: Edge,
  16375. Popup: Popup,
  16376. Groups: Groups,
  16377. Images: Images
  16378. },
  16379. Timeline: Timeline,
  16380. Graph: Graph
  16381. };
  16382. /**
  16383. * CommonJS module exports
  16384. */
  16385. if (typeof exports !== 'undefined') {
  16386. exports = vis;
  16387. }
  16388. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  16389. module.exports = vis;
  16390. }
  16391. /**
  16392. * AMD module exports
  16393. */
  16394. if (typeof(define) === 'function') {
  16395. define(function () {
  16396. return vis;
  16397. });
  16398. }
  16399. /**
  16400. * Window exports
  16401. */
  16402. if (typeof window !== 'undefined') {
  16403. // attach the module to the window, load as a regular javascript file
  16404. window['vis'] = vis;
  16405. }
  16406. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  16407. /**
  16408. * Expose `Emitter`.
  16409. */
  16410. module.exports = Emitter;
  16411. /**
  16412. * Initialize a new `Emitter`.
  16413. *
  16414. * @api public
  16415. */
  16416. function Emitter(obj) {
  16417. if (obj) return mixin(obj);
  16418. };
  16419. /**
  16420. * Mixin the emitter properties.
  16421. *
  16422. * @param {Object} obj
  16423. * @return {Object}
  16424. * @api private
  16425. */
  16426. function mixin(obj) {
  16427. for (var key in Emitter.prototype) {
  16428. obj[key] = Emitter.prototype[key];
  16429. }
  16430. return obj;
  16431. }
  16432. /**
  16433. * Listen on the given `event` with `fn`.
  16434. *
  16435. * @param {String} event
  16436. * @param {Function} fn
  16437. * @return {Emitter}
  16438. * @api public
  16439. */
  16440. Emitter.prototype.on =
  16441. Emitter.prototype.addEventListener = function(event, fn){
  16442. this._callbacks = this._callbacks || {};
  16443. (this._callbacks[event] = this._callbacks[event] || [])
  16444. .push(fn);
  16445. return this;
  16446. };
  16447. /**
  16448. * Adds an `event` listener that will be invoked a single
  16449. * time then automatically removed.
  16450. *
  16451. * @param {String} event
  16452. * @param {Function} fn
  16453. * @return {Emitter}
  16454. * @api public
  16455. */
  16456. Emitter.prototype.once = function(event, fn){
  16457. var self = this;
  16458. this._callbacks = this._callbacks || {};
  16459. function on() {
  16460. self.off(event, on);
  16461. fn.apply(this, arguments);
  16462. }
  16463. on.fn = fn;
  16464. this.on(event, on);
  16465. return this;
  16466. };
  16467. /**
  16468. * Remove the given callback for `event` or all
  16469. * registered callbacks.
  16470. *
  16471. * @param {String} event
  16472. * @param {Function} fn
  16473. * @return {Emitter}
  16474. * @api public
  16475. */
  16476. Emitter.prototype.off =
  16477. Emitter.prototype.removeListener =
  16478. Emitter.prototype.removeAllListeners =
  16479. Emitter.prototype.removeEventListener = function(event, fn){
  16480. this._callbacks = this._callbacks || {};
  16481. // all
  16482. if (0 == arguments.length) {
  16483. this._callbacks = {};
  16484. return this;
  16485. }
  16486. // specific event
  16487. var callbacks = this._callbacks[event];
  16488. if (!callbacks) return this;
  16489. // remove all handlers
  16490. if (1 == arguments.length) {
  16491. delete this._callbacks[event];
  16492. return this;
  16493. }
  16494. // remove specific handler
  16495. var cb;
  16496. for (var i = 0; i < callbacks.length; i++) {
  16497. cb = callbacks[i];
  16498. if (cb === fn || cb.fn === fn) {
  16499. callbacks.splice(i, 1);
  16500. break;
  16501. }
  16502. }
  16503. return this;
  16504. };
  16505. /**
  16506. * Emit `event` with the given args.
  16507. *
  16508. * @param {String} event
  16509. * @param {Mixed} ...
  16510. * @return {Emitter}
  16511. */
  16512. Emitter.prototype.emit = function(event){
  16513. this._callbacks = this._callbacks || {};
  16514. var args = [].slice.call(arguments, 1)
  16515. , callbacks = this._callbacks[event];
  16516. if (callbacks) {
  16517. callbacks = callbacks.slice(0);
  16518. for (var i = 0, len = callbacks.length; i < len; ++i) {
  16519. callbacks[i].apply(this, args);
  16520. }
  16521. }
  16522. return this;
  16523. };
  16524. /**
  16525. * Return array of callbacks for `event`.
  16526. *
  16527. * @param {String} event
  16528. * @return {Array}
  16529. * @api public
  16530. */
  16531. Emitter.prototype.listeners = function(event){
  16532. this._callbacks = this._callbacks || {};
  16533. return this._callbacks[event] || [];
  16534. };
  16535. /**
  16536. * Check if this emitter has `event` handlers.
  16537. *
  16538. * @param {String} event
  16539. * @return {Boolean}
  16540. * @api public
  16541. */
  16542. Emitter.prototype.hasListeners = function(event){
  16543. return !! this.listeners(event).length;
  16544. };
  16545. },{}],3:[function(require,module,exports){
  16546. /*! Hammer.JS - v1.0.5 - 2013-04-07
  16547. * http://eightmedia.github.com/hammer.js
  16548. *
  16549. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  16550. * Licensed under the MIT license */
  16551. (function(window, undefined) {
  16552. 'use strict';
  16553. /**
  16554. * Hammer
  16555. * use this to create instances
  16556. * @param {HTMLElement} element
  16557. * @param {Object} options
  16558. * @returns {Hammer.Instance}
  16559. * @constructor
  16560. */
  16561. var Hammer = function(element, options) {
  16562. return new Hammer.Instance(element, options || {});
  16563. };
  16564. // default settings
  16565. Hammer.defaults = {
  16566. // add styles and attributes to the element to prevent the browser from doing
  16567. // its native behavior. this doesnt prevent the scrolling, but cancels
  16568. // the contextmenu, tap highlighting etc
  16569. // set to false to disable this
  16570. stop_browser_behavior: {
  16571. // this also triggers onselectstart=false for IE
  16572. userSelect: 'none',
  16573. // this makes the element blocking in IE10 >, you could experiment with the value
  16574. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  16575. touchAction: 'none',
  16576. touchCallout: 'none',
  16577. contentZooming: 'none',
  16578. userDrag: 'none',
  16579. tapHighlightColor: 'rgba(0,0,0,0)'
  16580. }
  16581. // more settings are defined per gesture at gestures.js
  16582. };
  16583. // detect touchevents
  16584. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  16585. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  16586. // dont use mouseevents on mobile devices
  16587. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  16588. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  16589. // eventtypes per touchevent (start, move, end)
  16590. // are filled by Hammer.event.determineEventTypes on setup
  16591. Hammer.EVENT_TYPES = {};
  16592. // direction defines
  16593. Hammer.DIRECTION_DOWN = 'down';
  16594. Hammer.DIRECTION_LEFT = 'left';
  16595. Hammer.DIRECTION_UP = 'up';
  16596. Hammer.DIRECTION_RIGHT = 'right';
  16597. // pointer type
  16598. Hammer.POINTER_MOUSE = 'mouse';
  16599. Hammer.POINTER_TOUCH = 'touch';
  16600. Hammer.POINTER_PEN = 'pen';
  16601. // touch event defines
  16602. Hammer.EVENT_START = 'start';
  16603. Hammer.EVENT_MOVE = 'move';
  16604. Hammer.EVENT_END = 'end';
  16605. // hammer document where the base events are added at
  16606. Hammer.DOCUMENT = document;
  16607. // plugins namespace
  16608. Hammer.plugins = {};
  16609. // if the window events are set...
  16610. Hammer.READY = false;
  16611. /**
  16612. * setup events to detect gestures on the document
  16613. */
  16614. function setup() {
  16615. if(Hammer.READY) {
  16616. return;
  16617. }
  16618. // find what eventtypes we add listeners to
  16619. Hammer.event.determineEventTypes();
  16620. // Register all gestures inside Hammer.gestures
  16621. for(var name in Hammer.gestures) {
  16622. if(Hammer.gestures.hasOwnProperty(name)) {
  16623. Hammer.detection.register(Hammer.gestures[name]);
  16624. }
  16625. }
  16626. // Add touch events on the document
  16627. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  16628. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  16629. // Hammer is ready...!
  16630. Hammer.READY = true;
  16631. }
  16632. /**
  16633. * create new hammer instance
  16634. * all methods should return the instance itself, so it is chainable.
  16635. * @param {HTMLElement} element
  16636. * @param {Object} [options={}]
  16637. * @returns {Hammer.Instance}
  16638. * @constructor
  16639. */
  16640. Hammer.Instance = function(element, options) {
  16641. var self = this;
  16642. // setup HammerJS window events and register all gestures
  16643. // this also sets up the default options
  16644. setup();
  16645. this.element = element;
  16646. // start/stop detection option
  16647. this.enabled = true;
  16648. // merge options
  16649. this.options = Hammer.utils.extend(
  16650. Hammer.utils.extend({}, Hammer.defaults),
  16651. options || {});
  16652. // add some css to the element to prevent the browser from doing its native behavoir
  16653. if(this.options.stop_browser_behavior) {
  16654. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  16655. }
  16656. // start detection on touchstart
  16657. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  16658. if(self.enabled) {
  16659. Hammer.detection.startDetect(self, ev);
  16660. }
  16661. });
  16662. // return instance
  16663. return this;
  16664. };
  16665. Hammer.Instance.prototype = {
  16666. /**
  16667. * bind events to the instance
  16668. * @param {String} gesture
  16669. * @param {Function} handler
  16670. * @returns {Hammer.Instance}
  16671. */
  16672. on: function onEvent(gesture, handler){
  16673. var gestures = gesture.split(' ');
  16674. for(var t=0; t<gestures.length; t++) {
  16675. this.element.addEventListener(gestures[t], handler, false);
  16676. }
  16677. return this;
  16678. },
  16679. /**
  16680. * unbind events to the instance
  16681. * @param {String} gesture
  16682. * @param {Function} handler
  16683. * @returns {Hammer.Instance}
  16684. */
  16685. off: function offEvent(gesture, handler){
  16686. var gestures = gesture.split(' ');
  16687. for(var t=0; t<gestures.length; t++) {
  16688. this.element.removeEventListener(gestures[t], handler, false);
  16689. }
  16690. return this;
  16691. },
  16692. /**
  16693. * trigger gesture event
  16694. * @param {String} gesture
  16695. * @param {Object} eventData
  16696. * @returns {Hammer.Instance}
  16697. */
  16698. trigger: function triggerEvent(gesture, eventData){
  16699. // create DOM event
  16700. var event = Hammer.DOCUMENT.createEvent('Event');
  16701. event.initEvent(gesture, true, true);
  16702. event.gesture = eventData;
  16703. // trigger on the target if it is in the instance element,
  16704. // this is for event delegation tricks
  16705. var element = this.element;
  16706. if(Hammer.utils.hasParent(eventData.target, element)) {
  16707. element = eventData.target;
  16708. }
  16709. element.dispatchEvent(event);
  16710. return this;
  16711. },
  16712. /**
  16713. * enable of disable hammer.js detection
  16714. * @param {Boolean} state
  16715. * @returns {Hammer.Instance}
  16716. */
  16717. enable: function enable(state) {
  16718. this.enabled = state;
  16719. return this;
  16720. }
  16721. };
  16722. /**
  16723. * this holds the last move event,
  16724. * used to fix empty touchend issue
  16725. * see the onTouch event for an explanation
  16726. * @type {Object}
  16727. */
  16728. var last_move_event = null;
  16729. /**
  16730. * when the mouse is hold down, this is true
  16731. * @type {Boolean}
  16732. */
  16733. var enable_detect = false;
  16734. /**
  16735. * when touch events have been fired, this is true
  16736. * @type {Boolean}
  16737. */
  16738. var touch_triggered = false;
  16739. Hammer.event = {
  16740. /**
  16741. * simple addEventListener
  16742. * @param {HTMLElement} element
  16743. * @param {String} type
  16744. * @param {Function} handler
  16745. */
  16746. bindDom: function(element, type, handler) {
  16747. var types = type.split(' ');
  16748. for(var t=0; t<types.length; t++) {
  16749. element.addEventListener(types[t], handler, false);
  16750. }
  16751. },
  16752. /**
  16753. * touch events with mouse fallback
  16754. * @param {HTMLElement} element
  16755. * @param {String} eventType like Hammer.EVENT_MOVE
  16756. * @param {Function} handler
  16757. */
  16758. onTouch: function onTouch(element, eventType, handler) {
  16759. var self = this;
  16760. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  16761. var sourceEventType = ev.type.toLowerCase();
  16762. // onmouseup, but when touchend has been fired we do nothing.
  16763. // this is for touchdevices which also fire a mouseup on touchend
  16764. if(sourceEventType.match(/mouse/) && touch_triggered) {
  16765. return;
  16766. }
  16767. // mousebutton must be down or a touch event
  16768. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  16769. sourceEventType.match(/pointerdown/) || // pointerevents touch
  16770. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  16771. ){
  16772. enable_detect = true;
  16773. }
  16774. // we are in a touch event, set the touch triggered bool to true,
  16775. // this for the conflicts that may occur on ios and android
  16776. if(sourceEventType.match(/touch|pointer/)) {
  16777. touch_triggered = true;
  16778. }
  16779. // count the total touches on the screen
  16780. var count_touches = 0;
  16781. // when touch has been triggered in this detection session
  16782. // and we are now handling a mouse event, we stop that to prevent conflicts
  16783. if(enable_detect) {
  16784. // update pointerevent
  16785. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  16786. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16787. }
  16788. // touch
  16789. else if(sourceEventType.match(/touch/)) {
  16790. count_touches = ev.touches.length;
  16791. }
  16792. // mouse
  16793. else if(!touch_triggered) {
  16794. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  16795. }
  16796. // if we are in a end event, but when we remove one touch and
  16797. // we still have enough, set eventType to move
  16798. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  16799. eventType = Hammer.EVENT_MOVE;
  16800. }
  16801. // no touches, force the end event
  16802. else if(!count_touches) {
  16803. eventType = Hammer.EVENT_END;
  16804. }
  16805. // because touchend has no touches, and we often want to use these in our gestures,
  16806. // we send the last move event as our eventData in touchend
  16807. if(!count_touches && last_move_event !== null) {
  16808. ev = last_move_event;
  16809. }
  16810. // store the last move event
  16811. else {
  16812. last_move_event = ev;
  16813. }
  16814. // trigger the handler
  16815. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  16816. // remove pointerevent from list
  16817. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  16818. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16819. }
  16820. }
  16821. //debug(sourceEventType +" "+ eventType);
  16822. // on the end we reset everything
  16823. if(!count_touches) {
  16824. last_move_event = null;
  16825. enable_detect = false;
  16826. touch_triggered = false;
  16827. Hammer.PointerEvent.reset();
  16828. }
  16829. });
  16830. },
  16831. /**
  16832. * we have different events for each device/browser
  16833. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  16834. */
  16835. determineEventTypes: function determineEventTypes() {
  16836. // determine the eventtype we want to set
  16837. var types;
  16838. // pointerEvents magic
  16839. if(Hammer.HAS_POINTEREVENTS) {
  16840. types = Hammer.PointerEvent.getEvents();
  16841. }
  16842. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  16843. else if(Hammer.NO_MOUSEEVENTS) {
  16844. types = [
  16845. 'touchstart',
  16846. 'touchmove',
  16847. 'touchend touchcancel'];
  16848. }
  16849. // for non pointer events browsers and mixed browsers,
  16850. // like chrome on windows8 touch laptop
  16851. else {
  16852. types = [
  16853. 'touchstart mousedown',
  16854. 'touchmove mousemove',
  16855. 'touchend touchcancel mouseup'];
  16856. }
  16857. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  16858. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  16859. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  16860. },
  16861. /**
  16862. * create touchlist depending on the event
  16863. * @param {Object} ev
  16864. * @param {String} eventType used by the fakemultitouch plugin
  16865. */
  16866. getTouchList: function getTouchList(ev/*, eventType*/) {
  16867. // get the fake pointerEvent touchlist
  16868. if(Hammer.HAS_POINTEREVENTS) {
  16869. return Hammer.PointerEvent.getTouchList();
  16870. }
  16871. // get the touchlist
  16872. else if(ev.touches) {
  16873. return ev.touches;
  16874. }
  16875. // make fake touchlist from mouse position
  16876. else {
  16877. return [{
  16878. identifier: 1,
  16879. pageX: ev.pageX,
  16880. pageY: ev.pageY,
  16881. target: ev.target
  16882. }];
  16883. }
  16884. },
  16885. /**
  16886. * collect event data for Hammer js
  16887. * @param {HTMLElement} element
  16888. * @param {String} eventType like Hammer.EVENT_MOVE
  16889. * @param {Object} eventData
  16890. */
  16891. collectEventData: function collectEventData(element, eventType, ev) {
  16892. var touches = this.getTouchList(ev, eventType);
  16893. // find out pointerType
  16894. var pointerType = Hammer.POINTER_TOUCH;
  16895. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  16896. pointerType = Hammer.POINTER_MOUSE;
  16897. }
  16898. return {
  16899. center : Hammer.utils.getCenter(touches),
  16900. timeStamp : new Date().getTime(),
  16901. target : ev.target,
  16902. touches : touches,
  16903. eventType : eventType,
  16904. pointerType : pointerType,
  16905. srcEvent : ev,
  16906. /**
  16907. * prevent the browser default actions
  16908. * mostly used to disable scrolling of the browser
  16909. */
  16910. preventDefault: function() {
  16911. if(this.srcEvent.preventManipulation) {
  16912. this.srcEvent.preventManipulation();
  16913. }
  16914. if(this.srcEvent.preventDefault) {
  16915. this.srcEvent.preventDefault();
  16916. }
  16917. },
  16918. /**
  16919. * stop bubbling the event up to its parents
  16920. */
  16921. stopPropagation: function() {
  16922. this.srcEvent.stopPropagation();
  16923. },
  16924. /**
  16925. * immediately stop gesture detection
  16926. * might be useful after a swipe was detected
  16927. * @return {*}
  16928. */
  16929. stopDetect: function() {
  16930. return Hammer.detection.stopDetect();
  16931. }
  16932. };
  16933. }
  16934. };
  16935. Hammer.PointerEvent = {
  16936. /**
  16937. * holds all pointers
  16938. * @type {Object}
  16939. */
  16940. pointers: {},
  16941. /**
  16942. * get a list of pointers
  16943. * @returns {Array} touchlist
  16944. */
  16945. getTouchList: function() {
  16946. var self = this;
  16947. var touchlist = [];
  16948. // we can use forEach since pointerEvents only is in IE10
  16949. Object.keys(self.pointers).sort().forEach(function(id) {
  16950. touchlist.push(self.pointers[id]);
  16951. });
  16952. return touchlist;
  16953. },
  16954. /**
  16955. * update the position of a pointer
  16956. * @param {String} type Hammer.EVENT_END
  16957. * @param {Object} pointerEvent
  16958. */
  16959. updatePointer: function(type, pointerEvent) {
  16960. if(type == Hammer.EVENT_END) {
  16961. this.pointers = {};
  16962. }
  16963. else {
  16964. pointerEvent.identifier = pointerEvent.pointerId;
  16965. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16966. }
  16967. return Object.keys(this.pointers).length;
  16968. },
  16969. /**
  16970. * check if ev matches pointertype
  16971. * @param {String} pointerType Hammer.POINTER_MOUSE
  16972. * @param {PointerEvent} ev
  16973. */
  16974. matchType: function(pointerType, ev) {
  16975. if(!ev.pointerType) {
  16976. return false;
  16977. }
  16978. var types = {};
  16979. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16980. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16981. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16982. return types[pointerType];
  16983. },
  16984. /**
  16985. * get events
  16986. */
  16987. getEvents: function() {
  16988. return [
  16989. 'pointerdown MSPointerDown',
  16990. 'pointermove MSPointerMove',
  16991. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16992. ];
  16993. },
  16994. /**
  16995. * reset the list
  16996. */
  16997. reset: function() {
  16998. this.pointers = {};
  16999. }
  17000. };
  17001. Hammer.utils = {
  17002. /**
  17003. * extend method,
  17004. * also used for cloning when dest is an empty object
  17005. * @param {Object} dest
  17006. * @param {Object} src
  17007. * @parm {Boolean} merge do a merge
  17008. * @returns {Object} dest
  17009. */
  17010. extend: function extend(dest, src, merge) {
  17011. for (var key in src) {
  17012. if(dest[key] !== undefined && merge) {
  17013. continue;
  17014. }
  17015. dest[key] = src[key];
  17016. }
  17017. return dest;
  17018. },
  17019. /**
  17020. * find if a node is in the given parent
  17021. * used for event delegation tricks
  17022. * @param {HTMLElement} node
  17023. * @param {HTMLElement} parent
  17024. * @returns {boolean} has_parent
  17025. */
  17026. hasParent: function(node, parent) {
  17027. while(node){
  17028. if(node == parent) {
  17029. return true;
  17030. }
  17031. node = node.parentNode;
  17032. }
  17033. return false;
  17034. },
  17035. /**
  17036. * get the center of all the touches
  17037. * @param {Array} touches
  17038. * @returns {Object} center
  17039. */
  17040. getCenter: function getCenter(touches) {
  17041. var valuesX = [], valuesY = [];
  17042. for(var t= 0,len=touches.length; t<len; t++) {
  17043. valuesX.push(touches[t].pageX);
  17044. valuesY.push(touches[t].pageY);
  17045. }
  17046. return {
  17047. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  17048. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  17049. };
  17050. },
  17051. /**
  17052. * calculate the velocity between two points
  17053. * @param {Number} delta_time
  17054. * @param {Number} delta_x
  17055. * @param {Number} delta_y
  17056. * @returns {Object} velocity
  17057. */
  17058. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  17059. return {
  17060. x: Math.abs(delta_x / delta_time) || 0,
  17061. y: Math.abs(delta_y / delta_time) || 0
  17062. };
  17063. },
  17064. /**
  17065. * calculate the angle between two coordinates
  17066. * @param {Touch} touch1
  17067. * @param {Touch} touch2
  17068. * @returns {Number} angle
  17069. */
  17070. getAngle: function getAngle(touch1, touch2) {
  17071. var y = touch2.pageY - touch1.pageY,
  17072. x = touch2.pageX - touch1.pageX;
  17073. return Math.atan2(y, x) * 180 / Math.PI;
  17074. },
  17075. /**
  17076. * angle to direction define
  17077. * @param {Touch} touch1
  17078. * @param {Touch} touch2
  17079. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  17080. */
  17081. getDirection: function getDirection(touch1, touch2) {
  17082. var x = Math.abs(touch1.pageX - touch2.pageX),
  17083. y = Math.abs(touch1.pageY - touch2.pageY);
  17084. if(x >= y) {
  17085. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  17086. }
  17087. else {
  17088. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  17089. }
  17090. },
  17091. /**
  17092. * calculate the distance between two touches
  17093. * @param {Touch} touch1
  17094. * @param {Touch} touch2
  17095. * @returns {Number} distance
  17096. */
  17097. getDistance: function getDistance(touch1, touch2) {
  17098. var x = touch2.pageX - touch1.pageX,
  17099. y = touch2.pageY - touch1.pageY;
  17100. return Math.sqrt((x*x) + (y*y));
  17101. },
  17102. /**
  17103. * calculate the scale factor between two touchLists (fingers)
  17104. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  17105. * @param {Array} start
  17106. * @param {Array} end
  17107. * @returns {Number} scale
  17108. */
  17109. getScale: function getScale(start, end) {
  17110. // need two fingers...
  17111. if(start.length >= 2 && end.length >= 2) {
  17112. return this.getDistance(end[0], end[1]) /
  17113. this.getDistance(start[0], start[1]);
  17114. }
  17115. return 1;
  17116. },
  17117. /**
  17118. * calculate the rotation degrees between two touchLists (fingers)
  17119. * @param {Array} start
  17120. * @param {Array} end
  17121. * @returns {Number} rotation
  17122. */
  17123. getRotation: function getRotation(start, end) {
  17124. // need two fingers
  17125. if(start.length >= 2 && end.length >= 2) {
  17126. return this.getAngle(end[1], end[0]) -
  17127. this.getAngle(start[1], start[0]);
  17128. }
  17129. return 0;
  17130. },
  17131. /**
  17132. * boolean if the direction is vertical
  17133. * @param {String} direction
  17134. * @returns {Boolean} is_vertical
  17135. */
  17136. isVertical: function isVertical(direction) {
  17137. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  17138. },
  17139. /**
  17140. * stop browser default behavior with css props
  17141. * @param {HtmlElement} element
  17142. * @param {Object} css_props
  17143. */
  17144. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  17145. var prop,
  17146. vendors = ['webkit','khtml','moz','ms','o',''];
  17147. if(!css_props || !element.style) {
  17148. return;
  17149. }
  17150. // with css properties for modern browsers
  17151. for(var i = 0; i < vendors.length; i++) {
  17152. for(var p in css_props) {
  17153. if(css_props.hasOwnProperty(p)) {
  17154. prop = p;
  17155. // vender prefix at the property
  17156. if(vendors[i]) {
  17157. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  17158. }
  17159. // set the style
  17160. element.style[prop] = css_props[p];
  17161. }
  17162. }
  17163. }
  17164. // also the disable onselectstart
  17165. if(css_props.userSelect == 'none') {
  17166. element.onselectstart = function() {
  17167. return false;
  17168. };
  17169. }
  17170. }
  17171. };
  17172. Hammer.detection = {
  17173. // contains all registred Hammer.gestures in the correct order
  17174. gestures: [],
  17175. // data of the current Hammer.gesture detection session
  17176. current: null,
  17177. // the previous Hammer.gesture session data
  17178. // is a full clone of the previous gesture.current object
  17179. previous: null,
  17180. // when this becomes true, no gestures are fired
  17181. stopped: false,
  17182. /**
  17183. * start Hammer.gesture detection
  17184. * @param {Hammer.Instance} inst
  17185. * @param {Object} eventData
  17186. */
  17187. startDetect: function startDetect(inst, eventData) {
  17188. // already busy with a Hammer.gesture detection on an element
  17189. if(this.current) {
  17190. return;
  17191. }
  17192. this.stopped = false;
  17193. this.current = {
  17194. inst : inst, // reference to HammerInstance we're working for
  17195. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  17196. lastEvent : false, // last eventData
  17197. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  17198. };
  17199. this.detect(eventData);
  17200. },
  17201. /**
  17202. * Hammer.gesture detection
  17203. * @param {Object} eventData
  17204. * @param {Object} eventData
  17205. */
  17206. detect: function detect(eventData) {
  17207. if(!this.current || this.stopped) {
  17208. return;
  17209. }
  17210. // extend event data with calculations about scale, distance etc
  17211. eventData = this.extendEventData(eventData);
  17212. // instance options
  17213. var inst_options = this.current.inst.options;
  17214. // call Hammer.gesture handlers
  17215. for(var g=0,len=this.gestures.length; g<len; g++) {
  17216. var gesture = this.gestures[g];
  17217. // only when the instance options have enabled this gesture
  17218. if(!this.stopped && inst_options[gesture.name] !== false) {
  17219. // if a handler returns false, we stop with the detection
  17220. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  17221. this.stopDetect();
  17222. break;
  17223. }
  17224. }
  17225. }
  17226. // store as previous event event
  17227. if(this.current) {
  17228. this.current.lastEvent = eventData;
  17229. }
  17230. // endevent, but not the last touch, so dont stop
  17231. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  17232. this.stopDetect();
  17233. }
  17234. return eventData;
  17235. },
  17236. /**
  17237. * clear the Hammer.gesture vars
  17238. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  17239. * to stop other Hammer.gestures from being fired
  17240. */
  17241. stopDetect: function stopDetect() {
  17242. // clone current data to the store as the previous gesture
  17243. // used for the double tap gesture, since this is an other gesture detect session
  17244. this.previous = Hammer.utils.extend({}, this.current);
  17245. // reset the current
  17246. this.current = null;
  17247. // stopped!
  17248. this.stopped = true;
  17249. },
  17250. /**
  17251. * extend eventData for Hammer.gestures
  17252. * @param {Object} ev
  17253. * @returns {Object} ev
  17254. */
  17255. extendEventData: function extendEventData(ev) {
  17256. var startEv = this.current.startEvent;
  17257. // if the touches change, set the new touches over the startEvent touches
  17258. // this because touchevents don't have all the touches on touchstart, or the
  17259. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  17260. // but, sometimes it happens that both fingers are touching at the EXACT same time
  17261. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  17262. // extend 1 level deep to get the touchlist with the touch objects
  17263. startEv.touches = [];
  17264. for(var i=0,len=ev.touches.length; i<len; i++) {
  17265. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  17266. }
  17267. }
  17268. var delta_time = ev.timeStamp - startEv.timeStamp,
  17269. delta_x = ev.center.pageX - startEv.center.pageX,
  17270. delta_y = ev.center.pageY - startEv.center.pageY,
  17271. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  17272. Hammer.utils.extend(ev, {
  17273. deltaTime : delta_time,
  17274. deltaX : delta_x,
  17275. deltaY : delta_y,
  17276. velocityX : velocity.x,
  17277. velocityY : velocity.y,
  17278. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  17279. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  17280. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  17281. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  17282. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  17283. startEvent : startEv
  17284. });
  17285. return ev;
  17286. },
  17287. /**
  17288. * register new gesture
  17289. * @param {Object} gesture object, see gestures.js for documentation
  17290. * @returns {Array} gestures
  17291. */
  17292. register: function register(gesture) {
  17293. // add an enable gesture options if there is no given
  17294. var options = gesture.defaults || {};
  17295. if(options[gesture.name] === undefined) {
  17296. options[gesture.name] = true;
  17297. }
  17298. // extend Hammer default options with the Hammer.gesture options
  17299. Hammer.utils.extend(Hammer.defaults, options, true);
  17300. // set its index
  17301. gesture.index = gesture.index || 1000;
  17302. // add Hammer.gesture to the list
  17303. this.gestures.push(gesture);
  17304. // sort the list by index
  17305. this.gestures.sort(function(a, b) {
  17306. if (a.index < b.index) {
  17307. return -1;
  17308. }
  17309. if (a.index > b.index) {
  17310. return 1;
  17311. }
  17312. return 0;
  17313. });
  17314. return this.gestures;
  17315. }
  17316. };
  17317. Hammer.gestures = Hammer.gestures || {};
  17318. /**
  17319. * Custom gestures
  17320. * ==============================
  17321. *
  17322. * Gesture object
  17323. * --------------------
  17324. * The object structure of a gesture:
  17325. *
  17326. * { name: 'mygesture',
  17327. * index: 1337,
  17328. * defaults: {
  17329. * mygesture_option: true
  17330. * }
  17331. * handler: function(type, ev, inst) {
  17332. * // trigger gesture event
  17333. * inst.trigger(this.name, ev);
  17334. * }
  17335. * }
  17336. * @param {String} name
  17337. * this should be the name of the gesture, lowercase
  17338. * it is also being used to disable/enable the gesture per instance config.
  17339. *
  17340. * @param {Number} [index=1000]
  17341. * the index of the gesture, where it is going to be in the stack of gestures detection
  17342. * like when you build an gesture that depends on the drag gesture, it is a good
  17343. * idea to place it after the index of the drag gesture.
  17344. *
  17345. * @param {Object} [defaults={}]
  17346. * the default settings of the gesture. these are added to the instance settings,
  17347. * and can be overruled per instance. you can also add the name of the gesture,
  17348. * but this is also added by default (and set to true).
  17349. *
  17350. * @param {Function} handler
  17351. * this handles the gesture detection of your custom gesture and receives the
  17352. * following arguments:
  17353. *
  17354. * @param {Object} eventData
  17355. * event data containing the following properties:
  17356. * timeStamp {Number} time the event occurred
  17357. * target {HTMLElement} target element
  17358. * touches {Array} touches (fingers, pointers, mouse) on the screen
  17359. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  17360. * center {Object} center position of the touches. contains pageX and pageY
  17361. * deltaTime {Number} the total time of the touches in the screen
  17362. * deltaX {Number} the delta on x axis we haved moved
  17363. * deltaY {Number} the delta on y axis we haved moved
  17364. * velocityX {Number} the velocity on the x
  17365. * velocityY {Number} the velocity on y
  17366. * angle {Number} the angle we are moving
  17367. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  17368. * distance {Number} the distance we haved moved
  17369. * scale {Number} scaling of the touches, needs 2 touches
  17370. * rotation {Number} rotation of the touches, needs 2 touches *
  17371. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  17372. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  17373. * startEvent {Object} contains the same properties as above,
  17374. * but from the first touch. this is used to calculate
  17375. * distances, deltaTime, scaling etc
  17376. *
  17377. * @param {Hammer.Instance} inst
  17378. * the instance we are doing the detection for. you can get the options from
  17379. * the inst.options object and trigger the gesture event by calling inst.trigger
  17380. *
  17381. *
  17382. * Handle gestures
  17383. * --------------------
  17384. * inside the handler you can get/set Hammer.detection.current. This is the current
  17385. * detection session. It has the following properties
  17386. * @param {String} name
  17387. * contains the name of the gesture we have detected. it has not a real function,
  17388. * only to check in other gestures if something is detected.
  17389. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  17390. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  17391. *
  17392. * @readonly
  17393. * @param {Hammer.Instance} inst
  17394. * the instance we do the detection for
  17395. *
  17396. * @readonly
  17397. * @param {Object} startEvent
  17398. * contains the properties of the first gesture detection in this session.
  17399. * Used for calculations about timing, distance, etc.
  17400. *
  17401. * @readonly
  17402. * @param {Object} lastEvent
  17403. * contains all the properties of the last gesture detect in this session.
  17404. *
  17405. * after the gesture detection session has been completed (user has released the screen)
  17406. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  17407. * this is usefull for gestures like doubletap, where you need to know if the
  17408. * previous gesture was a tap
  17409. *
  17410. * options that have been set by the instance can be received by calling inst.options
  17411. *
  17412. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  17413. * The first param is the name of your gesture, the second the event argument
  17414. *
  17415. *
  17416. * Register gestures
  17417. * --------------------
  17418. * When an gesture is added to the Hammer.gestures object, it is auto registered
  17419. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  17420. * manually and pass your gesture object as a param
  17421. *
  17422. */
  17423. /**
  17424. * Hold
  17425. * Touch stays at the same place for x time
  17426. * @events hold
  17427. */
  17428. Hammer.gestures.Hold = {
  17429. name: 'hold',
  17430. index: 10,
  17431. defaults: {
  17432. hold_timeout : 500,
  17433. hold_threshold : 1
  17434. },
  17435. timer: null,
  17436. handler: function holdGesture(ev, inst) {
  17437. switch(ev.eventType) {
  17438. case Hammer.EVENT_START:
  17439. // clear any running timers
  17440. clearTimeout(this.timer);
  17441. // set the gesture so we can check in the timeout if it still is
  17442. Hammer.detection.current.name = this.name;
  17443. // set timer and if after the timeout it still is hold,
  17444. // we trigger the hold event
  17445. this.timer = setTimeout(function() {
  17446. if(Hammer.detection.current.name == 'hold') {
  17447. inst.trigger('hold', ev);
  17448. }
  17449. }, inst.options.hold_timeout);
  17450. break;
  17451. // when you move or end we clear the timer
  17452. case Hammer.EVENT_MOVE:
  17453. if(ev.distance > inst.options.hold_threshold) {
  17454. clearTimeout(this.timer);
  17455. }
  17456. break;
  17457. case Hammer.EVENT_END:
  17458. clearTimeout(this.timer);
  17459. break;
  17460. }
  17461. }
  17462. };
  17463. /**
  17464. * Tap/DoubleTap
  17465. * Quick touch at a place or double at the same place
  17466. * @events tap, doubletap
  17467. */
  17468. Hammer.gestures.Tap = {
  17469. name: 'tap',
  17470. index: 100,
  17471. defaults: {
  17472. tap_max_touchtime : 250,
  17473. tap_max_distance : 10,
  17474. tap_always : true,
  17475. doubletap_distance : 20,
  17476. doubletap_interval : 300
  17477. },
  17478. handler: function tapGesture(ev, inst) {
  17479. if(ev.eventType == Hammer.EVENT_END) {
  17480. // previous gesture, for the double tap since these are two different gesture detections
  17481. var prev = Hammer.detection.previous,
  17482. did_doubletap = false;
  17483. // when the touchtime is higher then the max touch time
  17484. // or when the moving distance is too much
  17485. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  17486. ev.distance > inst.options.tap_max_distance) {
  17487. return;
  17488. }
  17489. // check if double tap
  17490. if(prev && prev.name == 'tap' &&
  17491. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  17492. ev.distance < inst.options.doubletap_distance) {
  17493. inst.trigger('doubletap', ev);
  17494. did_doubletap = true;
  17495. }
  17496. // do a single tap
  17497. if(!did_doubletap || inst.options.tap_always) {
  17498. Hammer.detection.current.name = 'tap';
  17499. inst.trigger(Hammer.detection.current.name, ev);
  17500. }
  17501. }
  17502. }
  17503. };
  17504. /**
  17505. * Swipe
  17506. * triggers swipe events when the end velocity is above the threshold
  17507. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  17508. */
  17509. Hammer.gestures.Swipe = {
  17510. name: 'swipe',
  17511. index: 40,
  17512. defaults: {
  17513. // set 0 for unlimited, but this can conflict with transform
  17514. swipe_max_touches : 1,
  17515. swipe_velocity : 0.7
  17516. },
  17517. handler: function swipeGesture(ev, inst) {
  17518. if(ev.eventType == Hammer.EVENT_END) {
  17519. // max touches
  17520. if(inst.options.swipe_max_touches > 0 &&
  17521. ev.touches.length > inst.options.swipe_max_touches) {
  17522. return;
  17523. }
  17524. // when the distance we moved is too small we skip this gesture
  17525. // or we can be already in dragging
  17526. if(ev.velocityX > inst.options.swipe_velocity ||
  17527. ev.velocityY > inst.options.swipe_velocity) {
  17528. // trigger swipe events
  17529. inst.trigger(this.name, ev);
  17530. inst.trigger(this.name + ev.direction, ev);
  17531. }
  17532. }
  17533. }
  17534. };
  17535. /**
  17536. * Drag
  17537. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  17538. * moving left and right is a good practice. When all the drag events are blocking
  17539. * you disable scrolling on that area.
  17540. * @events drag, drapleft, dragright, dragup, dragdown
  17541. */
  17542. Hammer.gestures.Drag = {
  17543. name: 'drag',
  17544. index: 50,
  17545. defaults: {
  17546. drag_min_distance : 10,
  17547. // set 0 for unlimited, but this can conflict with transform
  17548. drag_max_touches : 1,
  17549. // prevent default browser behavior when dragging occurs
  17550. // be careful with it, it makes the element a blocking element
  17551. // when you are using the drag gesture, it is a good practice to set this true
  17552. drag_block_horizontal : false,
  17553. drag_block_vertical : false,
  17554. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  17555. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  17556. drag_lock_to_axis : false,
  17557. // drag lock only kicks in when distance > drag_lock_min_distance
  17558. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  17559. drag_lock_min_distance : 25
  17560. },
  17561. triggered: false,
  17562. handler: function dragGesture(ev, inst) {
  17563. // current gesture isnt drag, but dragged is true
  17564. // this means an other gesture is busy. now call dragend
  17565. if(Hammer.detection.current.name != this.name && this.triggered) {
  17566. inst.trigger(this.name +'end', ev);
  17567. this.triggered = false;
  17568. return;
  17569. }
  17570. // max touches
  17571. if(inst.options.drag_max_touches > 0 &&
  17572. ev.touches.length > inst.options.drag_max_touches) {
  17573. return;
  17574. }
  17575. switch(ev.eventType) {
  17576. case Hammer.EVENT_START:
  17577. this.triggered = false;
  17578. break;
  17579. case Hammer.EVENT_MOVE:
  17580. // when the distance we moved is too small we skip this gesture
  17581. // or we can be already in dragging
  17582. if(ev.distance < inst.options.drag_min_distance &&
  17583. Hammer.detection.current.name != this.name) {
  17584. return;
  17585. }
  17586. // we are dragging!
  17587. Hammer.detection.current.name = this.name;
  17588. // lock drag to axis?
  17589. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  17590. ev.drag_locked_to_axis = true;
  17591. }
  17592. var last_direction = Hammer.detection.current.lastEvent.direction;
  17593. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  17594. // keep direction on the axis that the drag gesture started on
  17595. if(Hammer.utils.isVertical(last_direction)) {
  17596. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  17597. }
  17598. else {
  17599. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  17600. }
  17601. }
  17602. // first time, trigger dragstart event
  17603. if(!this.triggered) {
  17604. inst.trigger(this.name +'start', ev);
  17605. this.triggered = true;
  17606. }
  17607. // trigger normal event
  17608. inst.trigger(this.name, ev);
  17609. // direction event, like dragdown
  17610. inst.trigger(this.name + ev.direction, ev);
  17611. // block the browser events
  17612. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  17613. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  17614. ev.preventDefault();
  17615. }
  17616. break;
  17617. case Hammer.EVENT_END:
  17618. // trigger dragend
  17619. if(this.triggered) {
  17620. inst.trigger(this.name +'end', ev);
  17621. }
  17622. this.triggered = false;
  17623. break;
  17624. }
  17625. }
  17626. };
  17627. /**
  17628. * Transform
  17629. * User want to scale or rotate with 2 fingers
  17630. * @events transform, pinch, pinchin, pinchout, rotate
  17631. */
  17632. Hammer.gestures.Transform = {
  17633. name: 'transform',
  17634. index: 45,
  17635. defaults: {
  17636. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  17637. transform_min_scale : 0.01,
  17638. // rotation in degrees
  17639. transform_min_rotation : 1,
  17640. // prevent default browser behavior when two touches are on the screen
  17641. // but it makes the element a blocking element
  17642. // when you are using the transform gesture, it is a good practice to set this true
  17643. transform_always_block : false
  17644. },
  17645. triggered: false,
  17646. handler: function transformGesture(ev, inst) {
  17647. // current gesture isnt drag, but dragged is true
  17648. // this means an other gesture is busy. now call dragend
  17649. if(Hammer.detection.current.name != this.name && this.triggered) {
  17650. inst.trigger(this.name +'end', ev);
  17651. this.triggered = false;
  17652. return;
  17653. }
  17654. // atleast multitouch
  17655. if(ev.touches.length < 2) {
  17656. return;
  17657. }
  17658. // prevent default when two fingers are on the screen
  17659. if(inst.options.transform_always_block) {
  17660. ev.preventDefault();
  17661. }
  17662. switch(ev.eventType) {
  17663. case Hammer.EVENT_START:
  17664. this.triggered = false;
  17665. break;
  17666. case Hammer.EVENT_MOVE:
  17667. var scale_threshold = Math.abs(1-ev.scale);
  17668. var rotation_threshold = Math.abs(ev.rotation);
  17669. // when the distance we moved is too small we skip this gesture
  17670. // or we can be already in dragging
  17671. if(scale_threshold < inst.options.transform_min_scale &&
  17672. rotation_threshold < inst.options.transform_min_rotation) {
  17673. return;
  17674. }
  17675. // we are transforming!
  17676. Hammer.detection.current.name = this.name;
  17677. // first time, trigger dragstart event
  17678. if(!this.triggered) {
  17679. inst.trigger(this.name +'start', ev);
  17680. this.triggered = true;
  17681. }
  17682. inst.trigger(this.name, ev); // basic transform event
  17683. // trigger rotate event
  17684. if(rotation_threshold > inst.options.transform_min_rotation) {
  17685. inst.trigger('rotate', ev);
  17686. }
  17687. // trigger pinch event
  17688. if(scale_threshold > inst.options.transform_min_scale) {
  17689. inst.trigger('pinch', ev);
  17690. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  17691. }
  17692. break;
  17693. case Hammer.EVENT_END:
  17694. // trigger dragend
  17695. if(this.triggered) {
  17696. inst.trigger(this.name +'end', ev);
  17697. }
  17698. this.triggered = false;
  17699. break;
  17700. }
  17701. }
  17702. };
  17703. /**
  17704. * Touch
  17705. * Called as first, tells the user has touched the screen
  17706. * @events touch
  17707. */
  17708. Hammer.gestures.Touch = {
  17709. name: 'touch',
  17710. index: -Infinity,
  17711. defaults: {
  17712. // call preventDefault at touchstart, and makes the element blocking by
  17713. // disabling the scrolling of the page, but it improves gestures like
  17714. // transforming and dragging.
  17715. // be careful with using this, it can be very annoying for users to be stuck
  17716. // on the page
  17717. prevent_default: false,
  17718. // disable mouse events, so only touch (or pen!) input triggers events
  17719. prevent_mouseevents: false
  17720. },
  17721. handler: function touchGesture(ev, inst) {
  17722. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  17723. ev.stopDetect();
  17724. return;
  17725. }
  17726. if(inst.options.prevent_default) {
  17727. ev.preventDefault();
  17728. }
  17729. if(ev.eventType == Hammer.EVENT_START) {
  17730. inst.trigger(this.name, ev);
  17731. }
  17732. }
  17733. };
  17734. /**
  17735. * Release
  17736. * Called as last, tells the user has released the screen
  17737. * @events release
  17738. */
  17739. Hammer.gestures.Release = {
  17740. name: 'release',
  17741. index: Infinity,
  17742. handler: function releaseGesture(ev, inst) {
  17743. if(ev.eventType == Hammer.EVENT_END) {
  17744. inst.trigger(this.name, ev);
  17745. }
  17746. }
  17747. };
  17748. // node export
  17749. if(typeof module === 'object' && typeof module.exports === 'object'){
  17750. module.exports = Hammer;
  17751. }
  17752. // just window export
  17753. else {
  17754. window.Hammer = Hammer;
  17755. // requireJS module definition
  17756. if(typeof window.define === 'function' && window.define.amd) {
  17757. window.define('hammer', [], function() {
  17758. return Hammer;
  17759. });
  17760. }
  17761. }
  17762. })(this);
  17763. },{}],4:[function(require,module,exports){
  17764. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};//! moment.js
  17765. //! version : 2.6.0
  17766. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  17767. //! license : MIT
  17768. //! momentjs.com
  17769. (function (undefined) {
  17770. /************************************
  17771. Constants
  17772. ************************************/
  17773. var moment,
  17774. VERSION = "2.6.0",
  17775. // the global-scope this is NOT the global object in Node.js
  17776. globalScope = typeof global !== 'undefined' ? global : this,
  17777. oldGlobalMoment,
  17778. round = Math.round,
  17779. i,
  17780. YEAR = 0,
  17781. MONTH = 1,
  17782. DATE = 2,
  17783. HOUR = 3,
  17784. MINUTE = 4,
  17785. SECOND = 5,
  17786. MILLISECOND = 6,
  17787. // internal storage for language config files
  17788. languages = {},
  17789. // moment internal properties
  17790. momentProperties = {
  17791. _isAMomentObject: null,
  17792. _i : null,
  17793. _f : null,
  17794. _l : null,
  17795. _strict : null,
  17796. _isUTC : null,
  17797. _offset : null, // optional. Combine with _isUTC
  17798. _pf : null,
  17799. _lang : null // optional
  17800. },
  17801. // check for nodeJS
  17802. hasModule = (typeof module !== 'undefined' && module.exports),
  17803. // ASP.NET json date format regex
  17804. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  17805. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  17806. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  17807. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  17808. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  17809. // format tokens
  17810. formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,
  17811. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  17812. // parsing token regexes
  17813. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  17814. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  17815. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  17816. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  17817. parseTokenDigits = /\d+/, // nonzero number of digits
  17818. 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.
  17819. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  17820. parseTokenT = /T/i, // T (ISO separator)
  17821. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  17822. parseTokenOrdinal = /\d{1,2}/,
  17823. //strict parsing regexes
  17824. parseTokenOneDigit = /\d/, // 0 - 9
  17825. parseTokenTwoDigits = /\d\d/, // 00 - 99
  17826. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  17827. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  17828. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  17829. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  17830. // iso 8601 regex
  17831. // 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)
  17832. isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
  17833. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  17834. isoDates = [
  17835. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  17836. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  17837. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  17838. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  17839. ['YYYY-DDD', /\d{4}-\d{3}/]
  17840. ],
  17841. // iso time formats and regexes
  17842. isoTimes = [
  17843. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
  17844. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  17845. ['HH:mm', /(T| )\d\d:\d\d/],
  17846. ['HH', /(T| )\d\d/]
  17847. ],
  17848. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  17849. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  17850. // getter and setter names
  17851. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  17852. unitMillisecondFactors = {
  17853. 'Milliseconds' : 1,
  17854. 'Seconds' : 1e3,
  17855. 'Minutes' : 6e4,
  17856. 'Hours' : 36e5,
  17857. 'Days' : 864e5,
  17858. 'Months' : 2592e6,
  17859. 'Years' : 31536e6
  17860. },
  17861. unitAliases = {
  17862. ms : 'millisecond',
  17863. s : 'second',
  17864. m : 'minute',
  17865. h : 'hour',
  17866. d : 'day',
  17867. D : 'date',
  17868. w : 'week',
  17869. W : 'isoWeek',
  17870. M : 'month',
  17871. Q : 'quarter',
  17872. y : 'year',
  17873. DDD : 'dayOfYear',
  17874. e : 'weekday',
  17875. E : 'isoWeekday',
  17876. gg: 'weekYear',
  17877. GG: 'isoWeekYear'
  17878. },
  17879. camelFunctions = {
  17880. dayofyear : 'dayOfYear',
  17881. isoweekday : 'isoWeekday',
  17882. isoweek : 'isoWeek',
  17883. weekyear : 'weekYear',
  17884. isoweekyear : 'isoWeekYear'
  17885. },
  17886. // format function strings
  17887. formatFunctions = {},
  17888. // tokens to ordinalize and pad
  17889. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  17890. paddedTokens = 'M D H h m s w W'.split(' '),
  17891. formatTokenFunctions = {
  17892. M : function () {
  17893. return this.month() + 1;
  17894. },
  17895. MMM : function (format) {
  17896. return this.lang().monthsShort(this, format);
  17897. },
  17898. MMMM : function (format) {
  17899. return this.lang().months(this, format);
  17900. },
  17901. D : function () {
  17902. return this.date();
  17903. },
  17904. DDD : function () {
  17905. return this.dayOfYear();
  17906. },
  17907. d : function () {
  17908. return this.day();
  17909. },
  17910. dd : function (format) {
  17911. return this.lang().weekdaysMin(this, format);
  17912. },
  17913. ddd : function (format) {
  17914. return this.lang().weekdaysShort(this, format);
  17915. },
  17916. dddd : function (format) {
  17917. return this.lang().weekdays(this, format);
  17918. },
  17919. w : function () {
  17920. return this.week();
  17921. },
  17922. W : function () {
  17923. return this.isoWeek();
  17924. },
  17925. YY : function () {
  17926. return leftZeroFill(this.year() % 100, 2);
  17927. },
  17928. YYYY : function () {
  17929. return leftZeroFill(this.year(), 4);
  17930. },
  17931. YYYYY : function () {
  17932. return leftZeroFill(this.year(), 5);
  17933. },
  17934. YYYYYY : function () {
  17935. var y = this.year(), sign = y >= 0 ? '+' : '-';
  17936. return sign + leftZeroFill(Math.abs(y), 6);
  17937. },
  17938. gg : function () {
  17939. return leftZeroFill(this.weekYear() % 100, 2);
  17940. },
  17941. gggg : function () {
  17942. return leftZeroFill(this.weekYear(), 4);
  17943. },
  17944. ggggg : function () {
  17945. return leftZeroFill(this.weekYear(), 5);
  17946. },
  17947. GG : function () {
  17948. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17949. },
  17950. GGGG : function () {
  17951. return leftZeroFill(this.isoWeekYear(), 4);
  17952. },
  17953. GGGGG : function () {
  17954. return leftZeroFill(this.isoWeekYear(), 5);
  17955. },
  17956. e : function () {
  17957. return this.weekday();
  17958. },
  17959. E : function () {
  17960. return this.isoWeekday();
  17961. },
  17962. a : function () {
  17963. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17964. },
  17965. A : function () {
  17966. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17967. },
  17968. H : function () {
  17969. return this.hours();
  17970. },
  17971. h : function () {
  17972. return this.hours() % 12 || 12;
  17973. },
  17974. m : function () {
  17975. return this.minutes();
  17976. },
  17977. s : function () {
  17978. return this.seconds();
  17979. },
  17980. S : function () {
  17981. return toInt(this.milliseconds() / 100);
  17982. },
  17983. SS : function () {
  17984. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17985. },
  17986. SSS : function () {
  17987. return leftZeroFill(this.milliseconds(), 3);
  17988. },
  17989. SSSS : function () {
  17990. return leftZeroFill(this.milliseconds(), 3);
  17991. },
  17992. Z : function () {
  17993. var a = -this.zone(),
  17994. b = "+";
  17995. if (a < 0) {
  17996. a = -a;
  17997. b = "-";
  17998. }
  17999. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  18000. },
  18001. ZZ : function () {
  18002. var a = -this.zone(),
  18003. b = "+";
  18004. if (a < 0) {
  18005. a = -a;
  18006. b = "-";
  18007. }
  18008. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  18009. },
  18010. z : function () {
  18011. return this.zoneAbbr();
  18012. },
  18013. zz : function () {
  18014. return this.zoneName();
  18015. },
  18016. X : function () {
  18017. return this.unix();
  18018. },
  18019. Q : function () {
  18020. return this.quarter();
  18021. }
  18022. },
  18023. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  18024. function defaultParsingFlags() {
  18025. // We need to deep clone this object, and es5 standard is not very
  18026. // helpful.
  18027. return {
  18028. empty : false,
  18029. unusedTokens : [],
  18030. unusedInput : [],
  18031. overflow : -2,
  18032. charsLeftOver : 0,
  18033. nullInput : false,
  18034. invalidMonth : null,
  18035. invalidFormat : false,
  18036. userInvalidated : false,
  18037. iso: false
  18038. };
  18039. }
  18040. function deprecate(msg, fn) {
  18041. var firstTime = true;
  18042. function printMsg() {
  18043. if (moment.suppressDeprecationWarnings === false &&
  18044. typeof console !== 'undefined' && console.warn) {
  18045. console.warn("Deprecation warning: " + msg);
  18046. }
  18047. }
  18048. return extend(function () {
  18049. if (firstTime) {
  18050. printMsg();
  18051. firstTime = false;
  18052. }
  18053. return fn.apply(this, arguments);
  18054. }, fn);
  18055. }
  18056. function padToken(func, count) {
  18057. return function (a) {
  18058. return leftZeroFill(func.call(this, a), count);
  18059. };
  18060. }
  18061. function ordinalizeToken(func, period) {
  18062. return function (a) {
  18063. return this.lang().ordinal(func.call(this, a), period);
  18064. };
  18065. }
  18066. while (ordinalizeTokens.length) {
  18067. i = ordinalizeTokens.pop();
  18068. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  18069. }
  18070. while (paddedTokens.length) {
  18071. i = paddedTokens.pop();
  18072. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  18073. }
  18074. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  18075. /************************************
  18076. Constructors
  18077. ************************************/
  18078. function Language() {
  18079. }
  18080. // Moment prototype object
  18081. function Moment(config) {
  18082. checkOverflow(config);
  18083. extend(this, config);
  18084. }
  18085. // Duration Constructor
  18086. function Duration(duration) {
  18087. var normalizedInput = normalizeObjectUnits(duration),
  18088. years = normalizedInput.year || 0,
  18089. quarters = normalizedInput.quarter || 0,
  18090. months = normalizedInput.month || 0,
  18091. weeks = normalizedInput.week || 0,
  18092. days = normalizedInput.day || 0,
  18093. hours = normalizedInput.hour || 0,
  18094. minutes = normalizedInput.minute || 0,
  18095. seconds = normalizedInput.second || 0,
  18096. milliseconds = normalizedInput.millisecond || 0;
  18097. // representation for dateAddRemove
  18098. this._milliseconds = +milliseconds +
  18099. seconds * 1e3 + // 1000
  18100. minutes * 6e4 + // 1000 * 60
  18101. hours * 36e5; // 1000 * 60 * 60
  18102. // Because of dateAddRemove treats 24 hours as different from a
  18103. // day when working around DST, we need to store them separately
  18104. this._days = +days +
  18105. weeks * 7;
  18106. // It is impossible translate months into days without knowing
  18107. // which months you are are talking about, so we have to store
  18108. // it separately.
  18109. this._months = +months +
  18110. quarters * 3 +
  18111. years * 12;
  18112. this._data = {};
  18113. this._bubble();
  18114. }
  18115. /************************************
  18116. Helpers
  18117. ************************************/
  18118. function extend(a, b) {
  18119. for (var i in b) {
  18120. if (b.hasOwnProperty(i)) {
  18121. a[i] = b[i];
  18122. }
  18123. }
  18124. if (b.hasOwnProperty("toString")) {
  18125. a.toString = b.toString;
  18126. }
  18127. if (b.hasOwnProperty("valueOf")) {
  18128. a.valueOf = b.valueOf;
  18129. }
  18130. return a;
  18131. }
  18132. function cloneMoment(m) {
  18133. var result = {}, i;
  18134. for (i in m) {
  18135. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  18136. result[i] = m[i];
  18137. }
  18138. }
  18139. return result;
  18140. }
  18141. function absRound(number) {
  18142. if (number < 0) {
  18143. return Math.ceil(number);
  18144. } else {
  18145. return Math.floor(number);
  18146. }
  18147. }
  18148. // left zero fill a number
  18149. // see http://jsperf.com/left-zero-filling for performance comparison
  18150. function leftZeroFill(number, targetLength, forceSign) {
  18151. var output = '' + Math.abs(number),
  18152. sign = number >= 0;
  18153. while (output.length < targetLength) {
  18154. output = '0' + output;
  18155. }
  18156. return (sign ? (forceSign ? '+' : '') : '-') + output;
  18157. }
  18158. // helper function for _.addTime and _.subtractTime
  18159. function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
  18160. var milliseconds = duration._milliseconds,
  18161. days = duration._days,
  18162. months = duration._months;
  18163. updateOffset = updateOffset == null ? true : updateOffset;
  18164. if (milliseconds) {
  18165. mom._d.setTime(+mom._d + milliseconds * isAdding);
  18166. }
  18167. if (days) {
  18168. rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
  18169. }
  18170. if (months) {
  18171. rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
  18172. }
  18173. if (updateOffset) {
  18174. moment.updateOffset(mom, days || months);
  18175. }
  18176. }
  18177. // check if is an array
  18178. function isArray(input) {
  18179. return Object.prototype.toString.call(input) === '[object Array]';
  18180. }
  18181. function isDate(input) {
  18182. return Object.prototype.toString.call(input) === '[object Date]' ||
  18183. input instanceof Date;
  18184. }
  18185. // compare two arrays, return the number of differences
  18186. function compareArrays(array1, array2, dontConvert) {
  18187. var len = Math.min(array1.length, array2.length),
  18188. lengthDiff = Math.abs(array1.length - array2.length),
  18189. diffs = 0,
  18190. i;
  18191. for (i = 0; i < len; i++) {
  18192. if ((dontConvert && array1[i] !== array2[i]) ||
  18193. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  18194. diffs++;
  18195. }
  18196. }
  18197. return diffs + lengthDiff;
  18198. }
  18199. function normalizeUnits(units) {
  18200. if (units) {
  18201. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  18202. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  18203. }
  18204. return units;
  18205. }
  18206. function normalizeObjectUnits(inputObject) {
  18207. var normalizedInput = {},
  18208. normalizedProp,
  18209. prop;
  18210. for (prop in inputObject) {
  18211. if (inputObject.hasOwnProperty(prop)) {
  18212. normalizedProp = normalizeUnits(prop);
  18213. if (normalizedProp) {
  18214. normalizedInput[normalizedProp] = inputObject[prop];
  18215. }
  18216. }
  18217. }
  18218. return normalizedInput;
  18219. }
  18220. function makeList(field) {
  18221. var count, setter;
  18222. if (field.indexOf('week') === 0) {
  18223. count = 7;
  18224. setter = 'day';
  18225. }
  18226. else if (field.indexOf('month') === 0) {
  18227. count = 12;
  18228. setter = 'month';
  18229. }
  18230. else {
  18231. return;
  18232. }
  18233. moment[field] = function (format, index) {
  18234. var i, getter,
  18235. method = moment.fn._lang[field],
  18236. results = [];
  18237. if (typeof format === 'number') {
  18238. index = format;
  18239. format = undefined;
  18240. }
  18241. getter = function (i) {
  18242. var m = moment().utc().set(setter, i);
  18243. return method.call(moment.fn._lang, m, format || '');
  18244. };
  18245. if (index != null) {
  18246. return getter(index);
  18247. }
  18248. else {
  18249. for (i = 0; i < count; i++) {
  18250. results.push(getter(i));
  18251. }
  18252. return results;
  18253. }
  18254. };
  18255. }
  18256. function toInt(argumentForCoercion) {
  18257. var coercedNumber = +argumentForCoercion,
  18258. value = 0;
  18259. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  18260. if (coercedNumber >= 0) {
  18261. value = Math.floor(coercedNumber);
  18262. } else {
  18263. value = Math.ceil(coercedNumber);
  18264. }
  18265. }
  18266. return value;
  18267. }
  18268. function daysInMonth(year, month) {
  18269. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  18270. }
  18271. function weeksInYear(year, dow, doy) {
  18272. return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
  18273. }
  18274. function daysInYear(year) {
  18275. return isLeapYear(year) ? 366 : 365;
  18276. }
  18277. function isLeapYear(year) {
  18278. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  18279. }
  18280. function checkOverflow(m) {
  18281. var overflow;
  18282. if (m._a && m._pf.overflow === -2) {
  18283. overflow =
  18284. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  18285. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  18286. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  18287. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  18288. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  18289. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  18290. -1;
  18291. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  18292. overflow = DATE;
  18293. }
  18294. m._pf.overflow = overflow;
  18295. }
  18296. }
  18297. function isValid(m) {
  18298. if (m._isValid == null) {
  18299. m._isValid = !isNaN(m._d.getTime()) &&
  18300. m._pf.overflow < 0 &&
  18301. !m._pf.empty &&
  18302. !m._pf.invalidMonth &&
  18303. !m._pf.nullInput &&
  18304. !m._pf.invalidFormat &&
  18305. !m._pf.userInvalidated;
  18306. if (m._strict) {
  18307. m._isValid = m._isValid &&
  18308. m._pf.charsLeftOver === 0 &&
  18309. m._pf.unusedTokens.length === 0;
  18310. }
  18311. }
  18312. return m._isValid;
  18313. }
  18314. function normalizeLanguage(key) {
  18315. return key ? key.toLowerCase().replace('_', '-') : key;
  18316. }
  18317. // Return a moment from input, that is local/utc/zone equivalent to model.
  18318. function makeAs(input, model) {
  18319. return model._isUTC ? moment(input).zone(model._offset || 0) :
  18320. moment(input).local();
  18321. }
  18322. /************************************
  18323. Languages
  18324. ************************************/
  18325. extend(Language.prototype, {
  18326. set : function (config) {
  18327. var prop, i;
  18328. for (i in config) {
  18329. prop = config[i];
  18330. if (typeof prop === 'function') {
  18331. this[i] = prop;
  18332. } else {
  18333. this['_' + i] = prop;
  18334. }
  18335. }
  18336. },
  18337. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  18338. months : function (m) {
  18339. return this._months[m.month()];
  18340. },
  18341. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  18342. monthsShort : function (m) {
  18343. return this._monthsShort[m.month()];
  18344. },
  18345. monthsParse : function (monthName) {
  18346. var i, mom, regex;
  18347. if (!this._monthsParse) {
  18348. this._monthsParse = [];
  18349. }
  18350. for (i = 0; i < 12; i++) {
  18351. // make the regex if we don't have it already
  18352. if (!this._monthsParse[i]) {
  18353. mom = moment.utc([2000, i]);
  18354. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  18355. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  18356. }
  18357. // test the regex
  18358. if (this._monthsParse[i].test(monthName)) {
  18359. return i;
  18360. }
  18361. }
  18362. },
  18363. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  18364. weekdays : function (m) {
  18365. return this._weekdays[m.day()];
  18366. },
  18367. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  18368. weekdaysShort : function (m) {
  18369. return this._weekdaysShort[m.day()];
  18370. },
  18371. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  18372. weekdaysMin : function (m) {
  18373. return this._weekdaysMin[m.day()];
  18374. },
  18375. weekdaysParse : function (weekdayName) {
  18376. var i, mom, regex;
  18377. if (!this._weekdaysParse) {
  18378. this._weekdaysParse = [];
  18379. }
  18380. for (i = 0; i < 7; i++) {
  18381. // make the regex if we don't have it already
  18382. if (!this._weekdaysParse[i]) {
  18383. mom = moment([2000, 1]).day(i);
  18384. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  18385. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  18386. }
  18387. // test the regex
  18388. if (this._weekdaysParse[i].test(weekdayName)) {
  18389. return i;
  18390. }
  18391. }
  18392. },
  18393. _longDateFormat : {
  18394. LT : "h:mm A",
  18395. L : "MM/DD/YYYY",
  18396. LL : "MMMM D YYYY",
  18397. LLL : "MMMM D YYYY LT",
  18398. LLLL : "dddd, MMMM D YYYY LT"
  18399. },
  18400. longDateFormat : function (key) {
  18401. var output = this._longDateFormat[key];
  18402. if (!output && this._longDateFormat[key.toUpperCase()]) {
  18403. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  18404. return val.slice(1);
  18405. });
  18406. this._longDateFormat[key] = output;
  18407. }
  18408. return output;
  18409. },
  18410. isPM : function (input) {
  18411. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  18412. // Using charAt should be more compatible.
  18413. return ((input + '').toLowerCase().charAt(0) === 'p');
  18414. },
  18415. _meridiemParse : /[ap]\.?m?\.?/i,
  18416. meridiem : function (hours, minutes, isLower) {
  18417. if (hours > 11) {
  18418. return isLower ? 'pm' : 'PM';
  18419. } else {
  18420. return isLower ? 'am' : 'AM';
  18421. }
  18422. },
  18423. _calendar : {
  18424. sameDay : '[Today at] LT',
  18425. nextDay : '[Tomorrow at] LT',
  18426. nextWeek : 'dddd [at] LT',
  18427. lastDay : '[Yesterday at] LT',
  18428. lastWeek : '[Last] dddd [at] LT',
  18429. sameElse : 'L'
  18430. },
  18431. calendar : function (key, mom) {
  18432. var output = this._calendar[key];
  18433. return typeof output === 'function' ? output.apply(mom) : output;
  18434. },
  18435. _relativeTime : {
  18436. future : "in %s",
  18437. past : "%s ago",
  18438. s : "a few seconds",
  18439. m : "a minute",
  18440. mm : "%d minutes",
  18441. h : "an hour",
  18442. hh : "%d hours",
  18443. d : "a day",
  18444. dd : "%d days",
  18445. M : "a month",
  18446. MM : "%d months",
  18447. y : "a year",
  18448. yy : "%d years"
  18449. },
  18450. relativeTime : function (number, withoutSuffix, string, isFuture) {
  18451. var output = this._relativeTime[string];
  18452. return (typeof output === 'function') ?
  18453. output(number, withoutSuffix, string, isFuture) :
  18454. output.replace(/%d/i, number);
  18455. },
  18456. pastFuture : function (diff, output) {
  18457. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  18458. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  18459. },
  18460. ordinal : function (number) {
  18461. return this._ordinal.replace("%d", number);
  18462. },
  18463. _ordinal : "%d",
  18464. preparse : function (string) {
  18465. return string;
  18466. },
  18467. postformat : function (string) {
  18468. return string;
  18469. },
  18470. week : function (mom) {
  18471. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  18472. },
  18473. _week : {
  18474. dow : 0, // Sunday is the first day of the week.
  18475. doy : 6 // The week that contains Jan 1st is the first week of the year.
  18476. },
  18477. _invalidDate: 'Invalid date',
  18478. invalidDate: function () {
  18479. return this._invalidDate;
  18480. }
  18481. });
  18482. // Loads a language definition into the `languages` cache. The function
  18483. // takes a key and optionally values. If not in the browser and no values
  18484. // are provided, it will load the language file module. As a convenience,
  18485. // this function also returns the language values.
  18486. function loadLang(key, values) {
  18487. values.abbr = key;
  18488. if (!languages[key]) {
  18489. languages[key] = new Language();
  18490. }
  18491. languages[key].set(values);
  18492. return languages[key];
  18493. }
  18494. // Remove a language from the `languages` cache. Mostly useful in tests.
  18495. function unloadLang(key) {
  18496. delete languages[key];
  18497. }
  18498. // Determines which language definition to use and returns it.
  18499. //
  18500. // With no parameters, it will return the global language. If you
  18501. // pass in a language key, such as 'en', it will return the
  18502. // definition for 'en', so long as 'en' has already been loaded using
  18503. // moment.lang.
  18504. function getLangDefinition(key) {
  18505. var i = 0, j, lang, next, split,
  18506. get = function (k) {
  18507. if (!languages[k] && hasModule) {
  18508. try {
  18509. require('./lang/' + k);
  18510. } catch (e) { }
  18511. }
  18512. return languages[k];
  18513. };
  18514. if (!key) {
  18515. return moment.fn._lang;
  18516. }
  18517. if (!isArray(key)) {
  18518. //short-circuit everything else
  18519. lang = get(key);
  18520. if (lang) {
  18521. return lang;
  18522. }
  18523. key = [key];
  18524. }
  18525. //pick the language from the array
  18526. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  18527. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  18528. while (i < key.length) {
  18529. split = normalizeLanguage(key[i]).split('-');
  18530. j = split.length;
  18531. next = normalizeLanguage(key[i + 1]);
  18532. next = next ? next.split('-') : null;
  18533. while (j > 0) {
  18534. lang = get(split.slice(0, j).join('-'));
  18535. if (lang) {
  18536. return lang;
  18537. }
  18538. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  18539. //the next array item is better than a shallower substring of this one
  18540. break;
  18541. }
  18542. j--;
  18543. }
  18544. i++;
  18545. }
  18546. return moment.fn._lang;
  18547. }
  18548. /************************************
  18549. Formatting
  18550. ************************************/
  18551. function removeFormattingTokens(input) {
  18552. if (input.match(/\[[\s\S]/)) {
  18553. return input.replace(/^\[|\]$/g, "");
  18554. }
  18555. return input.replace(/\\/g, "");
  18556. }
  18557. function makeFormatFunction(format) {
  18558. var array = format.match(formattingTokens), i, length;
  18559. for (i = 0, length = array.length; i < length; i++) {
  18560. if (formatTokenFunctions[array[i]]) {
  18561. array[i] = formatTokenFunctions[array[i]];
  18562. } else {
  18563. array[i] = removeFormattingTokens(array[i]);
  18564. }
  18565. }
  18566. return function (mom) {
  18567. var output = "";
  18568. for (i = 0; i < length; i++) {
  18569. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  18570. }
  18571. return output;
  18572. };
  18573. }
  18574. // format date using native date object
  18575. function formatMoment(m, format) {
  18576. if (!m.isValid()) {
  18577. return m.lang().invalidDate();
  18578. }
  18579. format = expandFormat(format, m.lang());
  18580. if (!formatFunctions[format]) {
  18581. formatFunctions[format] = makeFormatFunction(format);
  18582. }
  18583. return formatFunctions[format](m);
  18584. }
  18585. function expandFormat(format, lang) {
  18586. var i = 5;
  18587. function replaceLongDateFormatTokens(input) {
  18588. return lang.longDateFormat(input) || input;
  18589. }
  18590. localFormattingTokens.lastIndex = 0;
  18591. while (i >= 0 && localFormattingTokens.test(format)) {
  18592. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  18593. localFormattingTokens.lastIndex = 0;
  18594. i -= 1;
  18595. }
  18596. return format;
  18597. }
  18598. /************************************
  18599. Parsing
  18600. ************************************/
  18601. // get the regex to find the next token
  18602. function getParseRegexForToken(token, config) {
  18603. var a, strict = config._strict;
  18604. switch (token) {
  18605. case 'Q':
  18606. return parseTokenOneDigit;
  18607. case 'DDDD':
  18608. return parseTokenThreeDigits;
  18609. case 'YYYY':
  18610. case 'GGGG':
  18611. case 'gggg':
  18612. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  18613. case 'Y':
  18614. case 'G':
  18615. case 'g':
  18616. return parseTokenSignedNumber;
  18617. case 'YYYYYY':
  18618. case 'YYYYY':
  18619. case 'GGGGG':
  18620. case 'ggggg':
  18621. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  18622. case 'S':
  18623. if (strict) { return parseTokenOneDigit; }
  18624. /* falls through */
  18625. case 'SS':
  18626. if (strict) { return parseTokenTwoDigits; }
  18627. /* falls through */
  18628. case 'SSS':
  18629. if (strict) { return parseTokenThreeDigits; }
  18630. /* falls through */
  18631. case 'DDD':
  18632. return parseTokenOneToThreeDigits;
  18633. case 'MMM':
  18634. case 'MMMM':
  18635. case 'dd':
  18636. case 'ddd':
  18637. case 'dddd':
  18638. return parseTokenWord;
  18639. case 'a':
  18640. case 'A':
  18641. return getLangDefinition(config._l)._meridiemParse;
  18642. case 'X':
  18643. return parseTokenTimestampMs;
  18644. case 'Z':
  18645. case 'ZZ':
  18646. return parseTokenTimezone;
  18647. case 'T':
  18648. return parseTokenT;
  18649. case 'SSSS':
  18650. return parseTokenDigits;
  18651. case 'MM':
  18652. case 'DD':
  18653. case 'YY':
  18654. case 'GG':
  18655. case 'gg':
  18656. case 'HH':
  18657. case 'hh':
  18658. case 'mm':
  18659. case 'ss':
  18660. case 'ww':
  18661. case 'WW':
  18662. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  18663. case 'M':
  18664. case 'D':
  18665. case 'd':
  18666. case 'H':
  18667. case 'h':
  18668. case 'm':
  18669. case 's':
  18670. case 'w':
  18671. case 'W':
  18672. case 'e':
  18673. case 'E':
  18674. return parseTokenOneOrTwoDigits;
  18675. case 'Do':
  18676. return parseTokenOrdinal;
  18677. default :
  18678. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  18679. return a;
  18680. }
  18681. }
  18682. function timezoneMinutesFromString(string) {
  18683. string = string || "";
  18684. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  18685. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  18686. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  18687. minutes = +(parts[1] * 60) + toInt(parts[2]);
  18688. return parts[0] === '+' ? -minutes : minutes;
  18689. }
  18690. // function to convert string input to date
  18691. function addTimeToArrayFromToken(token, input, config) {
  18692. var a, datePartArray = config._a;
  18693. switch (token) {
  18694. // QUARTER
  18695. case 'Q':
  18696. if (input != null) {
  18697. datePartArray[MONTH] = (toInt(input) - 1) * 3;
  18698. }
  18699. break;
  18700. // MONTH
  18701. case 'M' : // fall through to MM
  18702. case 'MM' :
  18703. if (input != null) {
  18704. datePartArray[MONTH] = toInt(input) - 1;
  18705. }
  18706. break;
  18707. case 'MMM' : // fall through to MMMM
  18708. case 'MMMM' :
  18709. a = getLangDefinition(config._l).monthsParse(input);
  18710. // if we didn't find a month name, mark the date as invalid.
  18711. if (a != null) {
  18712. datePartArray[MONTH] = a;
  18713. } else {
  18714. config._pf.invalidMonth = input;
  18715. }
  18716. break;
  18717. // DAY OF MONTH
  18718. case 'D' : // fall through to DD
  18719. case 'DD' :
  18720. if (input != null) {
  18721. datePartArray[DATE] = toInt(input);
  18722. }
  18723. break;
  18724. case 'Do' :
  18725. if (input != null) {
  18726. datePartArray[DATE] = toInt(parseInt(input, 10));
  18727. }
  18728. break;
  18729. // DAY OF YEAR
  18730. case 'DDD' : // fall through to DDDD
  18731. case 'DDDD' :
  18732. if (input != null) {
  18733. config._dayOfYear = toInt(input);
  18734. }
  18735. break;
  18736. // YEAR
  18737. case 'YY' :
  18738. datePartArray[YEAR] = moment.parseTwoDigitYear(input);
  18739. break;
  18740. case 'YYYY' :
  18741. case 'YYYYY' :
  18742. case 'YYYYYY' :
  18743. datePartArray[YEAR] = toInt(input);
  18744. break;
  18745. // AM / PM
  18746. case 'a' : // fall through to A
  18747. case 'A' :
  18748. config._isPm = getLangDefinition(config._l).isPM(input);
  18749. break;
  18750. // 24 HOUR
  18751. case 'H' : // fall through to hh
  18752. case 'HH' : // fall through to hh
  18753. case 'h' : // fall through to hh
  18754. case 'hh' :
  18755. datePartArray[HOUR] = toInt(input);
  18756. break;
  18757. // MINUTE
  18758. case 'm' : // fall through to mm
  18759. case 'mm' :
  18760. datePartArray[MINUTE] = toInt(input);
  18761. break;
  18762. // SECOND
  18763. case 's' : // fall through to ss
  18764. case 'ss' :
  18765. datePartArray[SECOND] = toInt(input);
  18766. break;
  18767. // MILLISECOND
  18768. case 'S' :
  18769. case 'SS' :
  18770. case 'SSS' :
  18771. case 'SSSS' :
  18772. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  18773. break;
  18774. // UNIX TIMESTAMP WITH MS
  18775. case 'X':
  18776. config._d = new Date(parseFloat(input) * 1000);
  18777. break;
  18778. // TIMEZONE
  18779. case 'Z' : // fall through to ZZ
  18780. case 'ZZ' :
  18781. config._useUTC = true;
  18782. config._tzm = timezoneMinutesFromString(input);
  18783. break;
  18784. case 'w':
  18785. case 'ww':
  18786. case 'W':
  18787. case 'WW':
  18788. case 'd':
  18789. case 'dd':
  18790. case 'ddd':
  18791. case 'dddd':
  18792. case 'e':
  18793. case 'E':
  18794. token = token.substr(0, 1);
  18795. /* falls through */
  18796. case 'gg':
  18797. case 'gggg':
  18798. case 'GG':
  18799. case 'GGGG':
  18800. case 'GGGGG':
  18801. token = token.substr(0, 2);
  18802. if (input) {
  18803. config._w = config._w || {};
  18804. config._w[token] = input;
  18805. }
  18806. break;
  18807. }
  18808. }
  18809. // convert an array to a date.
  18810. // the array should mirror the parameters below
  18811. // note: all values past the year are optional and will default to the lowest possible value.
  18812. // [year, month, day , hour, minute, second, millisecond]
  18813. function dateFromConfig(config) {
  18814. var i, date, input = [], currentDate,
  18815. yearToUse, fixYear, w, temp, lang, weekday, week;
  18816. if (config._d) {
  18817. return;
  18818. }
  18819. currentDate = currentDateArray(config);
  18820. //compute day of the year from weeks and weekdays
  18821. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  18822. fixYear = function (val) {
  18823. var intVal = parseInt(val, 10);
  18824. return val ?
  18825. (val.length < 3 ? (intVal > 68 ? 1900 + intVal : 2000 + intVal) : intVal) :
  18826. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  18827. };
  18828. w = config._w;
  18829. if (w.GG != null || w.W != null || w.E != null) {
  18830. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  18831. }
  18832. else {
  18833. lang = getLangDefinition(config._l);
  18834. weekday = w.d != null ? parseWeekday(w.d, lang) :
  18835. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  18836. week = parseInt(w.w, 10) || 1;
  18837. //if we're parsing 'd', then the low day numbers may be next week
  18838. if (w.d != null && weekday < lang._week.dow) {
  18839. week++;
  18840. }
  18841. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  18842. }
  18843. config._a[YEAR] = temp.year;
  18844. config._dayOfYear = temp.dayOfYear;
  18845. }
  18846. //if the day of the year is set, figure out what it is
  18847. if (config._dayOfYear) {
  18848. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  18849. if (config._dayOfYear > daysInYear(yearToUse)) {
  18850. config._pf._overflowDayOfYear = true;
  18851. }
  18852. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  18853. config._a[MONTH] = date.getUTCMonth();
  18854. config._a[DATE] = date.getUTCDate();
  18855. }
  18856. // Default to current date.
  18857. // * if no year, month, day of month are given, default to today
  18858. // * if day of month is given, default month and year
  18859. // * if month is given, default only year
  18860. // * if year is given, don't default anything
  18861. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  18862. config._a[i] = input[i] = currentDate[i];
  18863. }
  18864. // Zero out whatever was not defaulted, including time
  18865. for (; i < 7; i++) {
  18866. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  18867. }
  18868. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  18869. input[HOUR] += toInt((config._tzm || 0) / 60);
  18870. input[MINUTE] += toInt((config._tzm || 0) % 60);
  18871. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  18872. }
  18873. function dateFromObject(config) {
  18874. var normalizedInput;
  18875. if (config._d) {
  18876. return;
  18877. }
  18878. normalizedInput = normalizeObjectUnits(config._i);
  18879. config._a = [
  18880. normalizedInput.year,
  18881. normalizedInput.month,
  18882. normalizedInput.day,
  18883. normalizedInput.hour,
  18884. normalizedInput.minute,
  18885. normalizedInput.second,
  18886. normalizedInput.millisecond
  18887. ];
  18888. dateFromConfig(config);
  18889. }
  18890. function currentDateArray(config) {
  18891. var now = new Date();
  18892. if (config._useUTC) {
  18893. return [
  18894. now.getUTCFullYear(),
  18895. now.getUTCMonth(),
  18896. now.getUTCDate()
  18897. ];
  18898. } else {
  18899. return [now.getFullYear(), now.getMonth(), now.getDate()];
  18900. }
  18901. }
  18902. // date from string and format string
  18903. function makeDateFromStringAndFormat(config) {
  18904. config._a = [];
  18905. config._pf.empty = true;
  18906. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  18907. var lang = getLangDefinition(config._l),
  18908. string = '' + config._i,
  18909. i, parsedInput, tokens, token, skipped,
  18910. stringLength = string.length,
  18911. totalParsedInputLength = 0;
  18912. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  18913. for (i = 0; i < tokens.length; i++) {
  18914. token = tokens[i];
  18915. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  18916. if (parsedInput) {
  18917. skipped = string.substr(0, string.indexOf(parsedInput));
  18918. if (skipped.length > 0) {
  18919. config._pf.unusedInput.push(skipped);
  18920. }
  18921. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  18922. totalParsedInputLength += parsedInput.length;
  18923. }
  18924. // don't parse if it's not a known token
  18925. if (formatTokenFunctions[token]) {
  18926. if (parsedInput) {
  18927. config._pf.empty = false;
  18928. }
  18929. else {
  18930. config._pf.unusedTokens.push(token);
  18931. }
  18932. addTimeToArrayFromToken(token, parsedInput, config);
  18933. }
  18934. else if (config._strict && !parsedInput) {
  18935. config._pf.unusedTokens.push(token);
  18936. }
  18937. }
  18938. // add remaining unparsed input length to the string
  18939. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  18940. if (string.length > 0) {
  18941. config._pf.unusedInput.push(string);
  18942. }
  18943. // handle am pm
  18944. if (config._isPm && config._a[HOUR] < 12) {
  18945. config._a[HOUR] += 12;
  18946. }
  18947. // if is 12 am, change hours to 0
  18948. if (config._isPm === false && config._a[HOUR] === 12) {
  18949. config._a[HOUR] = 0;
  18950. }
  18951. dateFromConfig(config);
  18952. checkOverflow(config);
  18953. }
  18954. function unescapeFormat(s) {
  18955. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  18956. return p1 || p2 || p3 || p4;
  18957. });
  18958. }
  18959. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  18960. function regexpEscape(s) {
  18961. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18962. }
  18963. // date from string and array of format strings
  18964. function makeDateFromStringAndArray(config) {
  18965. var tempConfig,
  18966. bestMoment,
  18967. scoreToBeat,
  18968. i,
  18969. currentScore;
  18970. if (config._f.length === 0) {
  18971. config._pf.invalidFormat = true;
  18972. config._d = new Date(NaN);
  18973. return;
  18974. }
  18975. for (i = 0; i < config._f.length; i++) {
  18976. currentScore = 0;
  18977. tempConfig = extend({}, config);
  18978. tempConfig._pf = defaultParsingFlags();
  18979. tempConfig._f = config._f[i];
  18980. makeDateFromStringAndFormat(tempConfig);
  18981. if (!isValid(tempConfig)) {
  18982. continue;
  18983. }
  18984. // if there is any input that was not parsed add a penalty for that format
  18985. currentScore += tempConfig._pf.charsLeftOver;
  18986. //or tokens
  18987. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18988. tempConfig._pf.score = currentScore;
  18989. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18990. scoreToBeat = currentScore;
  18991. bestMoment = tempConfig;
  18992. }
  18993. }
  18994. extend(config, bestMoment || tempConfig);
  18995. }
  18996. // date from iso format
  18997. function makeDateFromString(config) {
  18998. var i, l,
  18999. string = config._i,
  19000. match = isoRegex.exec(string);
  19001. if (match) {
  19002. config._pf.iso = true;
  19003. for (i = 0, l = isoDates.length; i < l; i++) {
  19004. if (isoDates[i][1].exec(string)) {
  19005. // match[5] should be "T" or undefined
  19006. config._f = isoDates[i][0] + (match[6] || " ");
  19007. break;
  19008. }
  19009. }
  19010. for (i = 0, l = isoTimes.length; i < l; i++) {
  19011. if (isoTimes[i][1].exec(string)) {
  19012. config._f += isoTimes[i][0];
  19013. break;
  19014. }
  19015. }
  19016. if (string.match(parseTokenTimezone)) {
  19017. config._f += "Z";
  19018. }
  19019. makeDateFromStringAndFormat(config);
  19020. }
  19021. else {
  19022. moment.createFromInputFallback(config);
  19023. }
  19024. }
  19025. function makeDateFromInput(config) {
  19026. var input = config._i,
  19027. matched = aspNetJsonRegex.exec(input);
  19028. if (input === undefined) {
  19029. config._d = new Date();
  19030. } else if (matched) {
  19031. config._d = new Date(+matched[1]);
  19032. } else if (typeof input === 'string') {
  19033. makeDateFromString(config);
  19034. } else if (isArray(input)) {
  19035. config._a = input.slice(0);
  19036. dateFromConfig(config);
  19037. } else if (isDate(input)) {
  19038. config._d = new Date(+input);
  19039. } else if (typeof(input) === 'object') {
  19040. dateFromObject(config);
  19041. } else if (typeof(input) === 'number') {
  19042. // from milliseconds
  19043. config._d = new Date(input);
  19044. } else {
  19045. moment.createFromInputFallback(config);
  19046. }
  19047. }
  19048. function makeDate(y, m, d, h, M, s, ms) {
  19049. //can't just apply() to create a date:
  19050. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  19051. var date = new Date(y, m, d, h, M, s, ms);
  19052. //the date constructor doesn't accept years < 1970
  19053. if (y < 1970) {
  19054. date.setFullYear(y);
  19055. }
  19056. return date;
  19057. }
  19058. function makeUTCDate(y) {
  19059. var date = new Date(Date.UTC.apply(null, arguments));
  19060. if (y < 1970) {
  19061. date.setUTCFullYear(y);
  19062. }
  19063. return date;
  19064. }
  19065. function parseWeekday(input, language) {
  19066. if (typeof input === 'string') {
  19067. if (!isNaN(input)) {
  19068. input = parseInt(input, 10);
  19069. }
  19070. else {
  19071. input = language.weekdaysParse(input);
  19072. if (typeof input !== 'number') {
  19073. return null;
  19074. }
  19075. }
  19076. }
  19077. return input;
  19078. }
  19079. /************************************
  19080. Relative Time
  19081. ************************************/
  19082. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  19083. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  19084. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  19085. }
  19086. function relativeTime(milliseconds, withoutSuffix, lang) {
  19087. var seconds = round(Math.abs(milliseconds) / 1000),
  19088. minutes = round(seconds / 60),
  19089. hours = round(minutes / 60),
  19090. days = round(hours / 24),
  19091. years = round(days / 365),
  19092. args = seconds < 45 && ['s', seconds] ||
  19093. minutes === 1 && ['m'] ||
  19094. minutes < 45 && ['mm', minutes] ||
  19095. hours === 1 && ['h'] ||
  19096. hours < 22 && ['hh', hours] ||
  19097. days === 1 && ['d'] ||
  19098. days <= 25 && ['dd', days] ||
  19099. days <= 45 && ['M'] ||
  19100. days < 345 && ['MM', round(days / 30)] ||
  19101. years === 1 && ['y'] || ['yy', years];
  19102. args[2] = withoutSuffix;
  19103. args[3] = milliseconds > 0;
  19104. args[4] = lang;
  19105. return substituteTimeAgo.apply({}, args);
  19106. }
  19107. /************************************
  19108. Week of Year
  19109. ************************************/
  19110. // firstDayOfWeek 0 = sun, 6 = sat
  19111. // the day of the week that starts the week
  19112. // (usually sunday or monday)
  19113. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  19114. // the first week is the week that contains the first
  19115. // of this day of the week
  19116. // (eg. ISO weeks use thursday (4))
  19117. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  19118. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  19119. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  19120. adjustedMoment;
  19121. if (daysToDayOfWeek > end) {
  19122. daysToDayOfWeek -= 7;
  19123. }
  19124. if (daysToDayOfWeek < end - 7) {
  19125. daysToDayOfWeek += 7;
  19126. }
  19127. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  19128. return {
  19129. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  19130. year: adjustedMoment.year()
  19131. };
  19132. }
  19133. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  19134. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  19135. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  19136. weekday = weekday != null ? weekday : firstDayOfWeek;
  19137. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  19138. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  19139. return {
  19140. year: dayOfYear > 0 ? year : year - 1,
  19141. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  19142. };
  19143. }
  19144. /************************************
  19145. Top Level Functions
  19146. ************************************/
  19147. function makeMoment(config) {
  19148. var input = config._i,
  19149. format = config._f;
  19150. if (input === null || (format === undefined && input === '')) {
  19151. return moment.invalid({nullInput: true});
  19152. }
  19153. if (typeof input === 'string') {
  19154. config._i = input = getLangDefinition().preparse(input);
  19155. }
  19156. if (moment.isMoment(input)) {
  19157. config = cloneMoment(input);
  19158. config._d = new Date(+input._d);
  19159. } else if (format) {
  19160. if (isArray(format)) {
  19161. makeDateFromStringAndArray(config);
  19162. } else {
  19163. makeDateFromStringAndFormat(config);
  19164. }
  19165. } else {
  19166. makeDateFromInput(config);
  19167. }
  19168. return new Moment(config);
  19169. }
  19170. moment = function (input, format, lang, strict) {
  19171. var c;
  19172. if (typeof(lang) === "boolean") {
  19173. strict = lang;
  19174. lang = undefined;
  19175. }
  19176. // object construction must be done this way.
  19177. // https://github.com/moment/moment/issues/1423
  19178. c = {};
  19179. c._isAMomentObject = true;
  19180. c._i = input;
  19181. c._f = format;
  19182. c._l = lang;
  19183. c._strict = strict;
  19184. c._isUTC = false;
  19185. c._pf = defaultParsingFlags();
  19186. return makeMoment(c);
  19187. };
  19188. moment.suppressDeprecationWarnings = false;
  19189. moment.createFromInputFallback = deprecate(
  19190. "moment construction falls back to js Date. This is " +
  19191. "discouraged and will be removed in upcoming major " +
  19192. "release. Please refer to " +
  19193. "https://github.com/moment/moment/issues/1407 for more info.",
  19194. function (config) {
  19195. config._d = new Date(config._i);
  19196. });
  19197. // creating with utc
  19198. moment.utc = function (input, format, lang, strict) {
  19199. var c;
  19200. if (typeof(lang) === "boolean") {
  19201. strict = lang;
  19202. lang = undefined;
  19203. }
  19204. // object construction must be done this way.
  19205. // https://github.com/moment/moment/issues/1423
  19206. c = {};
  19207. c._isAMomentObject = true;
  19208. c._useUTC = true;
  19209. c._isUTC = true;
  19210. c._l = lang;
  19211. c._i = input;
  19212. c._f = format;
  19213. c._strict = strict;
  19214. c._pf = defaultParsingFlags();
  19215. return makeMoment(c).utc();
  19216. };
  19217. // creating with unix timestamp (in seconds)
  19218. moment.unix = function (input) {
  19219. return moment(input * 1000);
  19220. };
  19221. // duration
  19222. moment.duration = function (input, key) {
  19223. var duration = input,
  19224. // matching against regexp is expensive, do it on demand
  19225. match = null,
  19226. sign,
  19227. ret,
  19228. parseIso;
  19229. if (moment.isDuration(input)) {
  19230. duration = {
  19231. ms: input._milliseconds,
  19232. d: input._days,
  19233. M: input._months
  19234. };
  19235. } else if (typeof input === 'number') {
  19236. duration = {};
  19237. if (key) {
  19238. duration[key] = input;
  19239. } else {
  19240. duration.milliseconds = input;
  19241. }
  19242. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  19243. sign = (match[1] === "-") ? -1 : 1;
  19244. duration = {
  19245. y: 0,
  19246. d: toInt(match[DATE]) * sign,
  19247. h: toInt(match[HOUR]) * sign,
  19248. m: toInt(match[MINUTE]) * sign,
  19249. s: toInt(match[SECOND]) * sign,
  19250. ms: toInt(match[MILLISECOND]) * sign
  19251. };
  19252. } else if (!!(match = isoDurationRegex.exec(input))) {
  19253. sign = (match[1] === "-") ? -1 : 1;
  19254. parseIso = function (inp) {
  19255. // We'd normally use ~~inp for this, but unfortunately it also
  19256. // converts floats to ints.
  19257. // inp may be undefined, so careful calling replace on it.
  19258. var res = inp && parseFloat(inp.replace(',', '.'));
  19259. // apply sign while we're at it
  19260. return (isNaN(res) ? 0 : res) * sign;
  19261. };
  19262. duration = {
  19263. y: parseIso(match[2]),
  19264. M: parseIso(match[3]),
  19265. d: parseIso(match[4]),
  19266. h: parseIso(match[5]),
  19267. m: parseIso(match[6]),
  19268. s: parseIso(match[7]),
  19269. w: parseIso(match[8])
  19270. };
  19271. }
  19272. ret = new Duration(duration);
  19273. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  19274. ret._lang = input._lang;
  19275. }
  19276. return ret;
  19277. };
  19278. // version number
  19279. moment.version = VERSION;
  19280. // default format
  19281. moment.defaultFormat = isoFormat;
  19282. // Plugins that add properties should also add the key here (null value),
  19283. // so we can properly clone ourselves.
  19284. moment.momentProperties = momentProperties;
  19285. // This function will be called whenever a moment is mutated.
  19286. // It is intended to keep the offset in sync with the timezone.
  19287. moment.updateOffset = function () {};
  19288. // This function will load languages and then set the global language. If
  19289. // no arguments are passed in, it will simply return the current global
  19290. // language key.
  19291. moment.lang = function (key, values) {
  19292. var r;
  19293. if (!key) {
  19294. return moment.fn._lang._abbr;
  19295. }
  19296. if (values) {
  19297. loadLang(normalizeLanguage(key), values);
  19298. } else if (values === null) {
  19299. unloadLang(key);
  19300. key = 'en';
  19301. } else if (!languages[key]) {
  19302. getLangDefinition(key);
  19303. }
  19304. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  19305. return r._abbr;
  19306. };
  19307. // returns language data
  19308. moment.langData = function (key) {
  19309. if (key && key._lang && key._lang._abbr) {
  19310. key = key._lang._abbr;
  19311. }
  19312. return getLangDefinition(key);
  19313. };
  19314. // compare moment object
  19315. moment.isMoment = function (obj) {
  19316. return obj instanceof Moment ||
  19317. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  19318. };
  19319. // for typechecking Duration objects
  19320. moment.isDuration = function (obj) {
  19321. return obj instanceof Duration;
  19322. };
  19323. for (i = lists.length - 1; i >= 0; --i) {
  19324. makeList(lists[i]);
  19325. }
  19326. moment.normalizeUnits = function (units) {
  19327. return normalizeUnits(units);
  19328. };
  19329. moment.invalid = function (flags) {
  19330. var m = moment.utc(NaN);
  19331. if (flags != null) {
  19332. extend(m._pf, flags);
  19333. }
  19334. else {
  19335. m._pf.userInvalidated = true;
  19336. }
  19337. return m;
  19338. };
  19339. moment.parseZone = function () {
  19340. return moment.apply(null, arguments).parseZone();
  19341. };
  19342. moment.parseTwoDigitYear = function (input) {
  19343. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  19344. };
  19345. /************************************
  19346. Moment Prototype
  19347. ************************************/
  19348. extend(moment.fn = Moment.prototype, {
  19349. clone : function () {
  19350. return moment(this);
  19351. },
  19352. valueOf : function () {
  19353. return +this._d + ((this._offset || 0) * 60000);
  19354. },
  19355. unix : function () {
  19356. return Math.floor(+this / 1000);
  19357. },
  19358. toString : function () {
  19359. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  19360. },
  19361. toDate : function () {
  19362. return this._offset ? new Date(+this) : this._d;
  19363. },
  19364. toISOString : function () {
  19365. var m = moment(this).utc();
  19366. if (0 < m.year() && m.year() <= 9999) {
  19367. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  19368. } else {
  19369. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  19370. }
  19371. },
  19372. toArray : function () {
  19373. var m = this;
  19374. return [
  19375. m.year(),
  19376. m.month(),
  19377. m.date(),
  19378. m.hours(),
  19379. m.minutes(),
  19380. m.seconds(),
  19381. m.milliseconds()
  19382. ];
  19383. },
  19384. isValid : function () {
  19385. return isValid(this);
  19386. },
  19387. isDSTShifted : function () {
  19388. if (this._a) {
  19389. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  19390. }
  19391. return false;
  19392. },
  19393. parsingFlags : function () {
  19394. return extend({}, this._pf);
  19395. },
  19396. invalidAt: function () {
  19397. return this._pf.overflow;
  19398. },
  19399. utc : function () {
  19400. return this.zone(0);
  19401. },
  19402. local : function () {
  19403. this.zone(0);
  19404. this._isUTC = false;
  19405. return this;
  19406. },
  19407. format : function (inputString) {
  19408. var output = formatMoment(this, inputString || moment.defaultFormat);
  19409. return this.lang().postformat(output);
  19410. },
  19411. add : function (input, val) {
  19412. var dur;
  19413. // switch args to support add('s', 1) and add(1, 's')
  19414. if (typeof input === 'string') {
  19415. dur = moment.duration(+val, input);
  19416. } else {
  19417. dur = moment.duration(input, val);
  19418. }
  19419. addOrSubtractDurationFromMoment(this, dur, 1);
  19420. return this;
  19421. },
  19422. subtract : function (input, val) {
  19423. var dur;
  19424. // switch args to support subtract('s', 1) and subtract(1, 's')
  19425. if (typeof input === 'string') {
  19426. dur = moment.duration(+val, input);
  19427. } else {
  19428. dur = moment.duration(input, val);
  19429. }
  19430. addOrSubtractDurationFromMoment(this, dur, -1);
  19431. return this;
  19432. },
  19433. diff : function (input, units, asFloat) {
  19434. var that = makeAs(input, this),
  19435. zoneDiff = (this.zone() - that.zone()) * 6e4,
  19436. diff, output;
  19437. units = normalizeUnits(units);
  19438. if (units === 'year' || units === 'month') {
  19439. // average number of days in the months in the given dates
  19440. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  19441. // difference in months
  19442. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  19443. // adjust by taking difference in days, average number of days
  19444. // and dst in the given months.
  19445. output += ((this - moment(this).startOf('month')) -
  19446. (that - moment(that).startOf('month'))) / diff;
  19447. // same as above but with zones, to negate all dst
  19448. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  19449. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  19450. if (units === 'year') {
  19451. output = output / 12;
  19452. }
  19453. } else {
  19454. diff = (this - that);
  19455. output = units === 'second' ? diff / 1e3 : // 1000
  19456. units === 'minute' ? diff / 6e4 : // 1000 * 60
  19457. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  19458. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  19459. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  19460. diff;
  19461. }
  19462. return asFloat ? output : absRound(output);
  19463. },
  19464. from : function (time, withoutSuffix) {
  19465. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  19466. },
  19467. fromNow : function (withoutSuffix) {
  19468. return this.from(moment(), withoutSuffix);
  19469. },
  19470. calendar : function () {
  19471. // We want to compare the start of today, vs this.
  19472. // Getting start-of-today depends on whether we're zone'd or not.
  19473. var sod = makeAs(moment(), this).startOf('day'),
  19474. diff = this.diff(sod, 'days', true),
  19475. format = diff < -6 ? 'sameElse' :
  19476. diff < -1 ? 'lastWeek' :
  19477. diff < 0 ? 'lastDay' :
  19478. diff < 1 ? 'sameDay' :
  19479. diff < 2 ? 'nextDay' :
  19480. diff < 7 ? 'nextWeek' : 'sameElse';
  19481. return this.format(this.lang().calendar(format, this));
  19482. },
  19483. isLeapYear : function () {
  19484. return isLeapYear(this.year());
  19485. },
  19486. isDST : function () {
  19487. return (this.zone() < this.clone().month(0).zone() ||
  19488. this.zone() < this.clone().month(5).zone());
  19489. },
  19490. day : function (input) {
  19491. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  19492. if (input != null) {
  19493. input = parseWeekday(input, this.lang());
  19494. return this.add({ d : input - day });
  19495. } else {
  19496. return day;
  19497. }
  19498. },
  19499. month : makeAccessor('Month', true),
  19500. startOf: function (units) {
  19501. units = normalizeUnits(units);
  19502. // the following switch intentionally omits break keywords
  19503. // to utilize falling through the cases.
  19504. switch (units) {
  19505. case 'year':
  19506. this.month(0);
  19507. /* falls through */
  19508. case 'quarter':
  19509. case 'month':
  19510. this.date(1);
  19511. /* falls through */
  19512. case 'week':
  19513. case 'isoWeek':
  19514. case 'day':
  19515. this.hours(0);
  19516. /* falls through */
  19517. case 'hour':
  19518. this.minutes(0);
  19519. /* falls through */
  19520. case 'minute':
  19521. this.seconds(0);
  19522. /* falls through */
  19523. case 'second':
  19524. this.milliseconds(0);
  19525. /* falls through */
  19526. }
  19527. // weeks are a special case
  19528. if (units === 'week') {
  19529. this.weekday(0);
  19530. } else if (units === 'isoWeek') {
  19531. this.isoWeekday(1);
  19532. }
  19533. // quarters are also special
  19534. if (units === 'quarter') {
  19535. this.month(Math.floor(this.month() / 3) * 3);
  19536. }
  19537. return this;
  19538. },
  19539. endOf: function (units) {
  19540. units = normalizeUnits(units);
  19541. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  19542. },
  19543. isAfter: function (input, units) {
  19544. units = typeof units !== 'undefined' ? units : 'millisecond';
  19545. return +this.clone().startOf(units) > +moment(input).startOf(units);
  19546. },
  19547. isBefore: function (input, units) {
  19548. units = typeof units !== 'undefined' ? units : 'millisecond';
  19549. return +this.clone().startOf(units) < +moment(input).startOf(units);
  19550. },
  19551. isSame: function (input, units) {
  19552. units = units || 'ms';
  19553. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  19554. },
  19555. min: function (other) {
  19556. other = moment.apply(null, arguments);
  19557. return other < this ? this : other;
  19558. },
  19559. max: function (other) {
  19560. other = moment.apply(null, arguments);
  19561. return other > this ? this : other;
  19562. },
  19563. // keepTime = true means only change the timezone, without affecting
  19564. // the local hour. So 5:31:26 +0300 --[zone(2, true)]--> 5:31:26 +0200
  19565. // It is possible that 5:31:26 doesn't exist int zone +0200, so we
  19566. // adjust the time as needed, to be valid.
  19567. //
  19568. // Keeping the time actually adds/subtracts (one hour)
  19569. // from the actual represented time. That is why we call updateOffset
  19570. // a second time. In case it wants us to change the offset again
  19571. // _changeInProgress == true case, then we have to adjust, because
  19572. // there is no such time in the given timezone.
  19573. zone : function (input, keepTime) {
  19574. var offset = this._offset || 0;
  19575. if (input != null) {
  19576. if (typeof input === "string") {
  19577. input = timezoneMinutesFromString(input);
  19578. }
  19579. if (Math.abs(input) < 16) {
  19580. input = input * 60;
  19581. }
  19582. this._offset = input;
  19583. this._isUTC = true;
  19584. if (offset !== input) {
  19585. if (!keepTime || this._changeInProgress) {
  19586. addOrSubtractDurationFromMoment(this,
  19587. moment.duration(offset - input, 'm'), 1, false);
  19588. } else if (!this._changeInProgress) {
  19589. this._changeInProgress = true;
  19590. moment.updateOffset(this, true);
  19591. this._changeInProgress = null;
  19592. }
  19593. }
  19594. } else {
  19595. return this._isUTC ? offset : this._d.getTimezoneOffset();
  19596. }
  19597. return this;
  19598. },
  19599. zoneAbbr : function () {
  19600. return this._isUTC ? "UTC" : "";
  19601. },
  19602. zoneName : function () {
  19603. return this._isUTC ? "Coordinated Universal Time" : "";
  19604. },
  19605. parseZone : function () {
  19606. if (this._tzm) {
  19607. this.zone(this._tzm);
  19608. } else if (typeof this._i === 'string') {
  19609. this.zone(this._i);
  19610. }
  19611. return this;
  19612. },
  19613. hasAlignedHourOffset : function (input) {
  19614. if (!input) {
  19615. input = 0;
  19616. }
  19617. else {
  19618. input = moment(input).zone();
  19619. }
  19620. return (this.zone() - input) % 60 === 0;
  19621. },
  19622. daysInMonth : function () {
  19623. return daysInMonth(this.year(), this.month());
  19624. },
  19625. dayOfYear : function (input) {
  19626. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  19627. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  19628. },
  19629. quarter : function (input) {
  19630. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  19631. },
  19632. weekYear : function (input) {
  19633. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  19634. return input == null ? year : this.add("y", (input - year));
  19635. },
  19636. isoWeekYear : function (input) {
  19637. var year = weekOfYear(this, 1, 4).year;
  19638. return input == null ? year : this.add("y", (input - year));
  19639. },
  19640. week : function (input) {
  19641. var week = this.lang().week(this);
  19642. return input == null ? week : this.add("d", (input - week) * 7);
  19643. },
  19644. isoWeek : function (input) {
  19645. var week = weekOfYear(this, 1, 4).week;
  19646. return input == null ? week : this.add("d", (input - week) * 7);
  19647. },
  19648. weekday : function (input) {
  19649. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  19650. return input == null ? weekday : this.add("d", input - weekday);
  19651. },
  19652. isoWeekday : function (input) {
  19653. // behaves the same as moment#day except
  19654. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  19655. // as a setter, sunday should belong to the previous week.
  19656. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  19657. },
  19658. isoWeeksInYear : function () {
  19659. return weeksInYear(this.year(), 1, 4);
  19660. },
  19661. weeksInYear : function () {
  19662. var weekInfo = this._lang._week;
  19663. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  19664. },
  19665. get : function (units) {
  19666. units = normalizeUnits(units);
  19667. return this[units]();
  19668. },
  19669. set : function (units, value) {
  19670. units = normalizeUnits(units);
  19671. if (typeof this[units] === 'function') {
  19672. this[units](value);
  19673. }
  19674. return this;
  19675. },
  19676. // If passed a language key, it will set the language for this
  19677. // instance. Otherwise, it will return the language configuration
  19678. // variables for this instance.
  19679. lang : function (key) {
  19680. if (key === undefined) {
  19681. return this._lang;
  19682. } else {
  19683. this._lang = getLangDefinition(key);
  19684. return this;
  19685. }
  19686. }
  19687. });
  19688. function rawMonthSetter(mom, value) {
  19689. var dayOfMonth;
  19690. // TODO: Move this out of here!
  19691. if (typeof value === 'string') {
  19692. value = mom.lang().monthsParse(value);
  19693. // TODO: Another silent failure?
  19694. if (typeof value !== 'number') {
  19695. return mom;
  19696. }
  19697. }
  19698. dayOfMonth = Math.min(mom.date(),
  19699. daysInMonth(mom.year(), value));
  19700. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  19701. return mom;
  19702. }
  19703. function rawGetter(mom, unit) {
  19704. return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
  19705. }
  19706. function rawSetter(mom, unit, value) {
  19707. if (unit === 'Month') {
  19708. return rawMonthSetter(mom, value);
  19709. } else {
  19710. return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  19711. }
  19712. }
  19713. function makeAccessor(unit, keepTime) {
  19714. return function (value) {
  19715. if (value != null) {
  19716. rawSetter(this, unit, value);
  19717. moment.updateOffset(this, keepTime);
  19718. return this;
  19719. } else {
  19720. return rawGetter(this, unit);
  19721. }
  19722. };
  19723. }
  19724. moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
  19725. moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
  19726. moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
  19727. // Setting the hour should keep the time, because the user explicitly
  19728. // specified which hour he wants. So trying to maintain the same hour (in
  19729. // a new timezone) makes sense. Adding/subtracting hours does not follow
  19730. // this rule.
  19731. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
  19732. // moment.fn.month is defined separately
  19733. moment.fn.date = makeAccessor('Date', true);
  19734. moment.fn.dates = deprecate("dates accessor is deprecated. Use date instead.", makeAccessor('Date', true));
  19735. moment.fn.year = makeAccessor('FullYear', true);
  19736. moment.fn.years = deprecate("years accessor is deprecated. Use year instead.", makeAccessor('FullYear', true));
  19737. // add plural methods
  19738. moment.fn.days = moment.fn.day;
  19739. moment.fn.months = moment.fn.month;
  19740. moment.fn.weeks = moment.fn.week;
  19741. moment.fn.isoWeeks = moment.fn.isoWeek;
  19742. moment.fn.quarters = moment.fn.quarter;
  19743. // add aliased format methods
  19744. moment.fn.toJSON = moment.fn.toISOString;
  19745. /************************************
  19746. Duration Prototype
  19747. ************************************/
  19748. extend(moment.duration.fn = Duration.prototype, {
  19749. _bubble : function () {
  19750. var milliseconds = this._milliseconds,
  19751. days = this._days,
  19752. months = this._months,
  19753. data = this._data,
  19754. seconds, minutes, hours, years;
  19755. // The following code bubbles up values, see the tests for
  19756. // examples of what that means.
  19757. data.milliseconds = milliseconds % 1000;
  19758. seconds = absRound(milliseconds / 1000);
  19759. data.seconds = seconds % 60;
  19760. minutes = absRound(seconds / 60);
  19761. data.minutes = minutes % 60;
  19762. hours = absRound(minutes / 60);
  19763. data.hours = hours % 24;
  19764. days += absRound(hours / 24);
  19765. data.days = days % 30;
  19766. months += absRound(days / 30);
  19767. data.months = months % 12;
  19768. years = absRound(months / 12);
  19769. data.years = years;
  19770. },
  19771. weeks : function () {
  19772. return absRound(this.days() / 7);
  19773. },
  19774. valueOf : function () {
  19775. return this._milliseconds +
  19776. this._days * 864e5 +
  19777. (this._months % 12) * 2592e6 +
  19778. toInt(this._months / 12) * 31536e6;
  19779. },
  19780. humanize : function (withSuffix) {
  19781. var difference = +this,
  19782. output = relativeTime(difference, !withSuffix, this.lang());
  19783. if (withSuffix) {
  19784. output = this.lang().pastFuture(difference, output);
  19785. }
  19786. return this.lang().postformat(output);
  19787. },
  19788. add : function (input, val) {
  19789. // supports only 2.0-style add(1, 's') or add(moment)
  19790. var dur = moment.duration(input, val);
  19791. this._milliseconds += dur._milliseconds;
  19792. this._days += dur._days;
  19793. this._months += dur._months;
  19794. this._bubble();
  19795. return this;
  19796. },
  19797. subtract : function (input, val) {
  19798. var dur = moment.duration(input, val);
  19799. this._milliseconds -= dur._milliseconds;
  19800. this._days -= dur._days;
  19801. this._months -= dur._months;
  19802. this._bubble();
  19803. return this;
  19804. },
  19805. get : function (units) {
  19806. units = normalizeUnits(units);
  19807. return this[units.toLowerCase() + 's']();
  19808. },
  19809. as : function (units) {
  19810. units = normalizeUnits(units);
  19811. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  19812. },
  19813. lang : moment.fn.lang,
  19814. toIsoString : function () {
  19815. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  19816. var years = Math.abs(this.years()),
  19817. months = Math.abs(this.months()),
  19818. days = Math.abs(this.days()),
  19819. hours = Math.abs(this.hours()),
  19820. minutes = Math.abs(this.minutes()),
  19821. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  19822. if (!this.asSeconds()) {
  19823. // this is the same as C#'s (Noda) and python (isodate)...
  19824. // but not other JS (goog.date)
  19825. return 'P0D';
  19826. }
  19827. return (this.asSeconds() < 0 ? '-' : '') +
  19828. 'P' +
  19829. (years ? years + 'Y' : '') +
  19830. (months ? months + 'M' : '') +
  19831. (days ? days + 'D' : '') +
  19832. ((hours || minutes || seconds) ? 'T' : '') +
  19833. (hours ? hours + 'H' : '') +
  19834. (minutes ? minutes + 'M' : '') +
  19835. (seconds ? seconds + 'S' : '');
  19836. }
  19837. });
  19838. function makeDurationGetter(name) {
  19839. moment.duration.fn[name] = function () {
  19840. return this._data[name];
  19841. };
  19842. }
  19843. function makeDurationAsGetter(name, factor) {
  19844. moment.duration.fn['as' + name] = function () {
  19845. return +this / factor;
  19846. };
  19847. }
  19848. for (i in unitMillisecondFactors) {
  19849. if (unitMillisecondFactors.hasOwnProperty(i)) {
  19850. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  19851. makeDurationGetter(i.toLowerCase());
  19852. }
  19853. }
  19854. makeDurationAsGetter('Weeks', 6048e5);
  19855. moment.duration.fn.asMonths = function () {
  19856. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  19857. };
  19858. /************************************
  19859. Default Lang
  19860. ************************************/
  19861. // Set default language, other languages will inherit from English.
  19862. moment.lang('en', {
  19863. ordinal : function (number) {
  19864. var b = number % 10,
  19865. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  19866. (b === 1) ? 'st' :
  19867. (b === 2) ? 'nd' :
  19868. (b === 3) ? 'rd' : 'th';
  19869. return number + output;
  19870. }
  19871. });
  19872. /* EMBED_LANGUAGES */
  19873. /************************************
  19874. Exposing Moment
  19875. ************************************/
  19876. function makeGlobal(shouldDeprecate) {
  19877. /*global ender:false */
  19878. if (typeof ender !== 'undefined') {
  19879. return;
  19880. }
  19881. oldGlobalMoment = globalScope.moment;
  19882. if (shouldDeprecate) {
  19883. globalScope.moment = deprecate(
  19884. "Accessing Moment through the global scope is " +
  19885. "deprecated, and will be removed in an upcoming " +
  19886. "release.",
  19887. moment);
  19888. } else {
  19889. globalScope.moment = moment;
  19890. }
  19891. }
  19892. // CommonJS module is defined
  19893. if (hasModule) {
  19894. module.exports = moment;
  19895. } else if (typeof define === "function" && define.amd) {
  19896. define("moment", function (require, exports, module) {
  19897. if (module.config && module.config() && module.config().noGlobal === true) {
  19898. // release the global variable
  19899. globalScope.moment = oldGlobalMoment;
  19900. }
  19901. return moment;
  19902. });
  19903. makeGlobal(true);
  19904. } else {
  19905. makeGlobal();
  19906. }
  19907. }).call(this);
  19908. },{}],5:[function(require,module,exports){
  19909. /**
  19910. * Copyright 2012 Craig Campbell
  19911. *
  19912. * Licensed under the Apache License, Version 2.0 (the "License");
  19913. * you may not use this file except in compliance with the License.
  19914. * You may obtain a copy of the License at
  19915. *
  19916. * http://www.apache.org/licenses/LICENSE-2.0
  19917. *
  19918. * Unless required by applicable law or agreed to in writing, software
  19919. * distributed under the License is distributed on an "AS IS" BASIS,
  19920. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19921. * See the License for the specific language governing permissions and
  19922. * limitations under the License.
  19923. *
  19924. * Mousetrap is a simple keyboard shortcut library for Javascript with
  19925. * no external dependencies
  19926. *
  19927. * @version 1.1.2
  19928. * @url craig.is/killing/mice
  19929. */
  19930. /**
  19931. * mapping of special keycodes to their corresponding keys
  19932. *
  19933. * everything in this dictionary cannot use keypress events
  19934. * so it has to be here to map to the correct keycodes for
  19935. * keyup/keydown events
  19936. *
  19937. * @type {Object}
  19938. */
  19939. var _MAP = {
  19940. 8: 'backspace',
  19941. 9: 'tab',
  19942. 13: 'enter',
  19943. 16: 'shift',
  19944. 17: 'ctrl',
  19945. 18: 'alt',
  19946. 20: 'capslock',
  19947. 27: 'esc',
  19948. 32: 'space',
  19949. 33: 'pageup',
  19950. 34: 'pagedown',
  19951. 35: 'end',
  19952. 36: 'home',
  19953. 37: 'left',
  19954. 38: 'up',
  19955. 39: 'right',
  19956. 40: 'down',
  19957. 45: 'ins',
  19958. 46: 'del',
  19959. 91: 'meta',
  19960. 93: 'meta',
  19961. 224: 'meta'
  19962. },
  19963. /**
  19964. * mapping for special characters so they can support
  19965. *
  19966. * this dictionary is only used incase you want to bind a
  19967. * keyup or keydown event to one of these keys
  19968. *
  19969. * @type {Object}
  19970. */
  19971. _KEYCODE_MAP = {
  19972. 106: '*',
  19973. 107: '+',
  19974. 109: '-',
  19975. 110: '.',
  19976. 111 : '/',
  19977. 186: ';',
  19978. 187: '=',
  19979. 188: ',',
  19980. 189: '-',
  19981. 190: '.',
  19982. 191: '/',
  19983. 192: '`',
  19984. 219: '[',
  19985. 220: '\\',
  19986. 221: ']',
  19987. 222: '\''
  19988. },
  19989. /**
  19990. * this is a mapping of keys that require shift on a US keypad
  19991. * back to the non shift equivelents
  19992. *
  19993. * this is so you can use keyup events with these keys
  19994. *
  19995. * note that this will only work reliably on US keyboards
  19996. *
  19997. * @type {Object}
  19998. */
  19999. _SHIFT_MAP = {
  20000. '~': '`',
  20001. '!': '1',
  20002. '@': '2',
  20003. '#': '3',
  20004. '$': '4',
  20005. '%': '5',
  20006. '^': '6',
  20007. '&': '7',
  20008. '*': '8',
  20009. '(': '9',
  20010. ')': '0',
  20011. '_': '-',
  20012. '+': '=',
  20013. ':': ';',
  20014. '\"': '\'',
  20015. '<': ',',
  20016. '>': '.',
  20017. '?': '/',
  20018. '|': '\\'
  20019. },
  20020. /**
  20021. * this is a list of special strings you can use to map
  20022. * to modifier keys when you specify your keyboard shortcuts
  20023. *
  20024. * @type {Object}
  20025. */
  20026. _SPECIAL_ALIASES = {
  20027. 'option': 'alt',
  20028. 'command': 'meta',
  20029. 'return': 'enter',
  20030. 'escape': 'esc'
  20031. },
  20032. /**
  20033. * variable to store the flipped version of _MAP from above
  20034. * needed to check if we should use keypress or not when no action
  20035. * is specified
  20036. *
  20037. * @type {Object|undefined}
  20038. */
  20039. _REVERSE_MAP,
  20040. /**
  20041. * a list of all the callbacks setup via Mousetrap.bind()
  20042. *
  20043. * @type {Object}
  20044. */
  20045. _callbacks = {},
  20046. /**
  20047. * direct map of string combinations to callbacks used for trigger()
  20048. *
  20049. * @type {Object}
  20050. */
  20051. _direct_map = {},
  20052. /**
  20053. * keeps track of what level each sequence is at since multiple
  20054. * sequences can start out with the same sequence
  20055. *
  20056. * @type {Object}
  20057. */
  20058. _sequence_levels = {},
  20059. /**
  20060. * variable to store the setTimeout call
  20061. *
  20062. * @type {null|number}
  20063. */
  20064. _reset_timer,
  20065. /**
  20066. * temporary state where we will ignore the next keyup
  20067. *
  20068. * @type {boolean|string}
  20069. */
  20070. _ignore_next_keyup = false,
  20071. /**
  20072. * are we currently inside of a sequence?
  20073. * type of action ("keyup" or "keydown" or "keypress") or false
  20074. *
  20075. * @type {boolean|string}
  20076. */
  20077. _inside_sequence = false;
  20078. /**
  20079. * loop through the f keys, f1 to f19 and add them to the map
  20080. * programatically
  20081. */
  20082. for (var i = 1; i < 20; ++i) {
  20083. _MAP[111 + i] = 'f' + i;
  20084. }
  20085. /**
  20086. * loop through to map numbers on the numeric keypad
  20087. */
  20088. for (i = 0; i <= 9; ++i) {
  20089. _MAP[i + 96] = i;
  20090. }
  20091. /**
  20092. * cross browser add event method
  20093. *
  20094. * @param {Element|HTMLDocument} object
  20095. * @param {string} type
  20096. * @param {Function} callback
  20097. * @returns void
  20098. */
  20099. function _addEvent(object, type, callback) {
  20100. if (object.addEventListener) {
  20101. return object.addEventListener(type, callback, false);
  20102. }
  20103. object.attachEvent('on' + type, callback);
  20104. }
  20105. /**
  20106. * takes the event and returns the key character
  20107. *
  20108. * @param {Event} e
  20109. * @return {string}
  20110. */
  20111. function _characterFromEvent(e) {
  20112. // for keypress events we should return the character as is
  20113. if (e.type == 'keypress') {
  20114. return String.fromCharCode(e.which);
  20115. }
  20116. // for non keypress events the special maps are needed
  20117. if (_MAP[e.which]) {
  20118. return _MAP[e.which];
  20119. }
  20120. if (_KEYCODE_MAP[e.which]) {
  20121. return _KEYCODE_MAP[e.which];
  20122. }
  20123. // if it is not in the special map
  20124. return String.fromCharCode(e.which).toLowerCase();
  20125. }
  20126. /**
  20127. * should we stop this event before firing off callbacks
  20128. *
  20129. * @param {Event} e
  20130. * @return {boolean}
  20131. */
  20132. function _stop(e) {
  20133. var element = e.target || e.srcElement,
  20134. tag_name = element.tagName;
  20135. // if the element has the class "mousetrap" then no need to stop
  20136. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  20137. return false;
  20138. }
  20139. // stop for input, select, and textarea
  20140. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  20141. }
  20142. /**
  20143. * checks if two arrays are equal
  20144. *
  20145. * @param {Array} modifiers1
  20146. * @param {Array} modifiers2
  20147. * @returns {boolean}
  20148. */
  20149. function _modifiersMatch(modifiers1, modifiers2) {
  20150. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  20151. }
  20152. /**
  20153. * resets all sequence counters except for the ones passed in
  20154. *
  20155. * @param {Object} do_not_reset
  20156. * @returns void
  20157. */
  20158. function _resetSequences(do_not_reset) {
  20159. do_not_reset = do_not_reset || {};
  20160. var active_sequences = false,
  20161. key;
  20162. for (key in _sequence_levels) {
  20163. if (do_not_reset[key]) {
  20164. active_sequences = true;
  20165. continue;
  20166. }
  20167. _sequence_levels[key] = 0;
  20168. }
  20169. if (!active_sequences) {
  20170. _inside_sequence = false;
  20171. }
  20172. }
  20173. /**
  20174. * finds all callbacks that match based on the keycode, modifiers,
  20175. * and action
  20176. *
  20177. * @param {string} character
  20178. * @param {Array} modifiers
  20179. * @param {string} action
  20180. * @param {boolean=} remove - should we remove any matches
  20181. * @param {string=} combination
  20182. * @returns {Array}
  20183. */
  20184. function _getMatches(character, modifiers, action, remove, combination) {
  20185. var i,
  20186. callback,
  20187. matches = [];
  20188. // if there are no events related to this keycode
  20189. if (!_callbacks[character]) {
  20190. return [];
  20191. }
  20192. // if a modifier key is coming up on its own we should allow it
  20193. if (action == 'keyup' && _isModifier(character)) {
  20194. modifiers = [character];
  20195. }
  20196. // loop through all callbacks for the key that was pressed
  20197. // and see if any of them match
  20198. for (i = 0; i < _callbacks[character].length; ++i) {
  20199. callback = _callbacks[character][i];
  20200. // if this is a sequence but it is not at the right level
  20201. // then move onto the next match
  20202. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  20203. continue;
  20204. }
  20205. // if the action we are looking for doesn't match the action we got
  20206. // then we should keep going
  20207. if (action != callback.action) {
  20208. continue;
  20209. }
  20210. // if this is a keypress event that means that we need to only
  20211. // look at the character, otherwise check the modifiers as
  20212. // well
  20213. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  20214. // remove is used so if you change your mind and call bind a
  20215. // second time with a new function the first one is overwritten
  20216. if (remove && callback.combo == combination) {
  20217. _callbacks[character].splice(i, 1);
  20218. }
  20219. matches.push(callback);
  20220. }
  20221. }
  20222. return matches;
  20223. }
  20224. /**
  20225. * takes a key event and figures out what the modifiers are
  20226. *
  20227. * @param {Event} e
  20228. * @returns {Array}
  20229. */
  20230. function _eventModifiers(e) {
  20231. var modifiers = [];
  20232. if (e.shiftKey) {
  20233. modifiers.push('shift');
  20234. }
  20235. if (e.altKey) {
  20236. modifiers.push('alt');
  20237. }
  20238. if (e.ctrlKey) {
  20239. modifiers.push('ctrl');
  20240. }
  20241. if (e.metaKey) {
  20242. modifiers.push('meta');
  20243. }
  20244. return modifiers;
  20245. }
  20246. /**
  20247. * actually calls the callback function
  20248. *
  20249. * if your callback function returns false this will use the jquery
  20250. * convention - prevent default and stop propogation on the event
  20251. *
  20252. * @param {Function} callback
  20253. * @param {Event} e
  20254. * @returns void
  20255. */
  20256. function _fireCallback(callback, e) {
  20257. if (callback(e) === false) {
  20258. if (e.preventDefault) {
  20259. e.preventDefault();
  20260. }
  20261. if (e.stopPropagation) {
  20262. e.stopPropagation();
  20263. }
  20264. e.returnValue = false;
  20265. e.cancelBubble = true;
  20266. }
  20267. }
  20268. /**
  20269. * handles a character key event
  20270. *
  20271. * @param {string} character
  20272. * @param {Event} e
  20273. * @returns void
  20274. */
  20275. function _handleCharacter(character, e) {
  20276. // if this event should not happen stop here
  20277. if (_stop(e)) {
  20278. return;
  20279. }
  20280. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  20281. i,
  20282. do_not_reset = {},
  20283. processed_sequence_callback = false;
  20284. // loop through matching callbacks for this key event
  20285. for (i = 0; i < callbacks.length; ++i) {
  20286. // fire for all sequence callbacks
  20287. // this is because if for example you have multiple sequences
  20288. // bound such as "g i" and "g t" they both need to fire the
  20289. // callback for matching g cause otherwise you can only ever
  20290. // match the first one
  20291. if (callbacks[i].seq) {
  20292. processed_sequence_callback = true;
  20293. // keep a list of which sequences were matches for later
  20294. do_not_reset[callbacks[i].seq] = 1;
  20295. _fireCallback(callbacks[i].callback, e);
  20296. continue;
  20297. }
  20298. // if there were no sequence matches but we are still here
  20299. // that means this is a regular match so we should fire that
  20300. if (!processed_sequence_callback && !_inside_sequence) {
  20301. _fireCallback(callbacks[i].callback, e);
  20302. }
  20303. }
  20304. // if you are inside of a sequence and the key you are pressing
  20305. // is not a modifier key then we should reset all sequences
  20306. // that were not matched by this key event
  20307. if (e.type == _inside_sequence && !_isModifier(character)) {
  20308. _resetSequences(do_not_reset);
  20309. }
  20310. }
  20311. /**
  20312. * handles a keydown event
  20313. *
  20314. * @param {Event} e
  20315. * @returns void
  20316. */
  20317. function _handleKey(e) {
  20318. // normalize e.which for key events
  20319. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  20320. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  20321. var character = _characterFromEvent(e);
  20322. // no character found then stop
  20323. if (!character) {
  20324. return;
  20325. }
  20326. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  20327. _ignore_next_keyup = false;
  20328. return;
  20329. }
  20330. _handleCharacter(character, e);
  20331. }
  20332. /**
  20333. * determines if the keycode specified is a modifier key or not
  20334. *
  20335. * @param {string} key
  20336. * @returns {boolean}
  20337. */
  20338. function _isModifier(key) {
  20339. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  20340. }
  20341. /**
  20342. * called to set a 1 second timeout on the specified sequence
  20343. *
  20344. * this is so after each key press in the sequence you have 1 second
  20345. * to press the next key before you have to start over
  20346. *
  20347. * @returns void
  20348. */
  20349. function _resetSequenceTimer() {
  20350. clearTimeout(_reset_timer);
  20351. _reset_timer = setTimeout(_resetSequences, 1000);
  20352. }
  20353. /**
  20354. * reverses the map lookup so that we can look for specific keys
  20355. * to see what can and can't use keypress
  20356. *
  20357. * @return {Object}
  20358. */
  20359. function _getReverseMap() {
  20360. if (!_REVERSE_MAP) {
  20361. _REVERSE_MAP = {};
  20362. for (var key in _MAP) {
  20363. // pull out the numeric keypad from here cause keypress should
  20364. // be able to detect the keys from the character
  20365. if (key > 95 && key < 112) {
  20366. continue;
  20367. }
  20368. if (_MAP.hasOwnProperty(key)) {
  20369. _REVERSE_MAP[_MAP[key]] = key;
  20370. }
  20371. }
  20372. }
  20373. return _REVERSE_MAP;
  20374. }
  20375. /**
  20376. * picks the best action based on the key combination
  20377. *
  20378. * @param {string} key - character for key
  20379. * @param {Array} modifiers
  20380. * @param {string=} action passed in
  20381. */
  20382. function _pickBestAction(key, modifiers, action) {
  20383. // if no action was picked in we should try to pick the one
  20384. // that we think would work best for this key
  20385. if (!action) {
  20386. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  20387. }
  20388. // modifier keys don't work as expected with keypress,
  20389. // switch to keydown
  20390. if (action == 'keypress' && modifiers.length) {
  20391. action = 'keydown';
  20392. }
  20393. return action;
  20394. }
  20395. /**
  20396. * binds a key sequence to an event
  20397. *
  20398. * @param {string} combo - combo specified in bind call
  20399. * @param {Array} keys
  20400. * @param {Function} callback
  20401. * @param {string=} action
  20402. * @returns void
  20403. */
  20404. function _bindSequence(combo, keys, callback, action) {
  20405. // start off by adding a sequence level record for this combination
  20406. // and setting the level to 0
  20407. _sequence_levels[combo] = 0;
  20408. // if there is no action pick the best one for the first key
  20409. // in the sequence
  20410. if (!action) {
  20411. action = _pickBestAction(keys[0], []);
  20412. }
  20413. /**
  20414. * callback to increase the sequence level for this sequence and reset
  20415. * all other sequences that were active
  20416. *
  20417. * @param {Event} e
  20418. * @returns void
  20419. */
  20420. var _increaseSequence = function(e) {
  20421. _inside_sequence = action;
  20422. ++_sequence_levels[combo];
  20423. _resetSequenceTimer();
  20424. },
  20425. /**
  20426. * wraps the specified callback inside of another function in order
  20427. * to reset all sequence counters as soon as this sequence is done
  20428. *
  20429. * @param {Event} e
  20430. * @returns void
  20431. */
  20432. _callbackAndReset = function(e) {
  20433. _fireCallback(callback, e);
  20434. // we should ignore the next key up if the action is key down
  20435. // or keypress. this is so if you finish a sequence and
  20436. // release the key the final key will not trigger a keyup
  20437. if (action !== 'keyup') {
  20438. _ignore_next_keyup = _characterFromEvent(e);
  20439. }
  20440. // weird race condition if a sequence ends with the key
  20441. // another sequence begins with
  20442. setTimeout(_resetSequences, 10);
  20443. },
  20444. i;
  20445. // loop through keys one at a time and bind the appropriate callback
  20446. // function. for any key leading up to the final one it should
  20447. // increase the sequence. after the final, it should reset all sequences
  20448. for (i = 0; i < keys.length; ++i) {
  20449. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  20450. }
  20451. }
  20452. /**
  20453. * binds a single keyboard combination
  20454. *
  20455. * @param {string} combination
  20456. * @param {Function} callback
  20457. * @param {string=} action
  20458. * @param {string=} sequence_name - name of sequence if part of sequence
  20459. * @param {number=} level - what part of the sequence the command is
  20460. * @returns void
  20461. */
  20462. function _bindSingle(combination, callback, action, sequence_name, level) {
  20463. // make sure multiple spaces in a row become a single space
  20464. combination = combination.replace(/\s+/g, ' ');
  20465. var sequence = combination.split(' '),
  20466. i,
  20467. key,
  20468. keys,
  20469. modifiers = [];
  20470. // if this pattern is a sequence of keys then run through this method
  20471. // to reprocess each pattern one key at a time
  20472. if (sequence.length > 1) {
  20473. return _bindSequence(combination, sequence, callback, action);
  20474. }
  20475. // take the keys from this pattern and figure out what the actual
  20476. // pattern is all about
  20477. keys = combination === '+' ? ['+'] : combination.split('+');
  20478. for (i = 0; i < keys.length; ++i) {
  20479. key = keys[i];
  20480. // normalize key names
  20481. if (_SPECIAL_ALIASES[key]) {
  20482. key = _SPECIAL_ALIASES[key];
  20483. }
  20484. // if this is not a keypress event then we should
  20485. // be smart about using shift keys
  20486. // this will only work for US keyboards however
  20487. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  20488. key = _SHIFT_MAP[key];
  20489. modifiers.push('shift');
  20490. }
  20491. // if this key is a modifier then add it to the list of modifiers
  20492. if (_isModifier(key)) {
  20493. modifiers.push(key);
  20494. }
  20495. }
  20496. // depending on what the key combination is
  20497. // we will try to pick the best event for it
  20498. action = _pickBestAction(key, modifiers, action);
  20499. // make sure to initialize array if this is the first time
  20500. // a callback is added for this key
  20501. if (!_callbacks[key]) {
  20502. _callbacks[key] = [];
  20503. }
  20504. // remove an existing match if there is one
  20505. _getMatches(key, modifiers, action, !sequence_name, combination);
  20506. // add this call back to the array
  20507. // if it is a sequence put it at the beginning
  20508. // if not put it at the end
  20509. //
  20510. // this is important because the way these are processed expects
  20511. // the sequence ones to come first
  20512. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  20513. callback: callback,
  20514. modifiers: modifiers,
  20515. action: action,
  20516. seq: sequence_name,
  20517. level: level,
  20518. combo: combination
  20519. });
  20520. }
  20521. /**
  20522. * binds multiple combinations to the same callback
  20523. *
  20524. * @param {Array} combinations
  20525. * @param {Function} callback
  20526. * @param {string|undefined} action
  20527. * @returns void
  20528. */
  20529. function _bindMultiple(combinations, callback, action) {
  20530. for (var i = 0; i < combinations.length; ++i) {
  20531. _bindSingle(combinations[i], callback, action);
  20532. }
  20533. }
  20534. // start!
  20535. _addEvent(document, 'keypress', _handleKey);
  20536. _addEvent(document, 'keydown', _handleKey);
  20537. _addEvent(document, 'keyup', _handleKey);
  20538. var mousetrap = {
  20539. /**
  20540. * binds an event to mousetrap
  20541. *
  20542. * can be a single key, a combination of keys separated with +,
  20543. * a comma separated list of keys, an array of keys, or
  20544. * a sequence of keys separated by spaces
  20545. *
  20546. * be sure to list the modifier keys first to make sure that the
  20547. * correct key ends up getting bound (the last key in the pattern)
  20548. *
  20549. * @param {string|Array} keys
  20550. * @param {Function} callback
  20551. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  20552. * @returns void
  20553. */
  20554. bind: function(keys, callback, action) {
  20555. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  20556. _direct_map[keys + ':' + action] = callback;
  20557. return this;
  20558. },
  20559. /**
  20560. * unbinds an event to mousetrap
  20561. *
  20562. * the unbinding sets the callback function of the specified key combo
  20563. * to an empty function and deletes the corresponding key in the
  20564. * _direct_map dict.
  20565. *
  20566. * the keycombo+action has to be exactly the same as
  20567. * it was defined in the bind method
  20568. *
  20569. * TODO: actually remove this from the _callbacks dictionary instead
  20570. * of binding an empty function
  20571. *
  20572. * @param {string|Array} keys
  20573. * @param {string} action
  20574. * @returns void
  20575. */
  20576. unbind: function(keys, action) {
  20577. if (_direct_map[keys + ':' + action]) {
  20578. delete _direct_map[keys + ':' + action];
  20579. this.bind(keys, function() {}, action);
  20580. }
  20581. return this;
  20582. },
  20583. /**
  20584. * triggers an event that has already been bound
  20585. *
  20586. * @param {string} keys
  20587. * @param {string=} action
  20588. * @returns void
  20589. */
  20590. trigger: function(keys, action) {
  20591. _direct_map[keys + ':' + action]();
  20592. return this;
  20593. },
  20594. /**
  20595. * resets the library back to its initial state. this is useful
  20596. * if you want to clear out the current keyboard shortcuts and bind
  20597. * new ones - for example if you switch to another page
  20598. *
  20599. * @returns void
  20600. */
  20601. reset: function() {
  20602. _callbacks = {};
  20603. _direct_map = {};
  20604. return this;
  20605. }
  20606. };
  20607. module.exports = mousetrap;
  20608. },{}]},{},[1])
  20609. (1)
  20610. });