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.

22885 lines
670 KiB

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 0.7.2-SNAPSHOT
  8. * @date 2014-04-02
  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. * Convert an object to another type
  354. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  355. * @param {String | undefined} type Name of the type. Available types:
  356. * 'Boolean', 'Number', 'String',
  357. * 'Date', 'Moment', ISODate', 'ASPDate'.
  358. * @return {*} object
  359. * @throws Error
  360. */
  361. util.convert = function convert(object, type) {
  362. var match;
  363. if (object === undefined) {
  364. return undefined;
  365. }
  366. if (object === null) {
  367. return null;
  368. }
  369. if (!type) {
  370. return object;
  371. }
  372. if (!(typeof type === 'string') && !(type instanceof String)) {
  373. throw new Error('Type must be a string');
  374. }
  375. //noinspection FallthroughInSwitchStatementJS
  376. switch (type) {
  377. case 'boolean':
  378. case 'Boolean':
  379. return Boolean(object);
  380. case 'number':
  381. case 'Number':
  382. return Number(object.valueOf());
  383. case 'string':
  384. case 'String':
  385. return String(object);
  386. case 'Date':
  387. if (util.isNumber(object)) {
  388. return new Date(object);
  389. }
  390. if (object instanceof Date) {
  391. return new Date(object.valueOf());
  392. }
  393. else if (moment.isMoment(object)) {
  394. return new Date(object.valueOf());
  395. }
  396. if (util.isString(object)) {
  397. match = ASPDateRegex.exec(object);
  398. if (match) {
  399. // object is an ASP date
  400. return new Date(Number(match[1])); // parse number
  401. }
  402. else {
  403. return moment(object).toDate(); // parse string
  404. }
  405. }
  406. else {
  407. throw new Error(
  408. 'Cannot convert object of type ' + util.getType(object) +
  409. ' to type Date');
  410. }
  411. case 'Moment':
  412. if (util.isNumber(object)) {
  413. return moment(object);
  414. }
  415. if (object instanceof Date) {
  416. return moment(object.valueOf());
  417. }
  418. else if (moment.isMoment(object)) {
  419. return moment(object);
  420. }
  421. if (util.isString(object)) {
  422. match = ASPDateRegex.exec(object);
  423. if (match) {
  424. // object is an ASP date
  425. return moment(Number(match[1])); // parse number
  426. }
  427. else {
  428. return moment(object); // parse string
  429. }
  430. }
  431. else {
  432. throw new Error(
  433. 'Cannot convert object of type ' + util.getType(object) +
  434. ' to type Date');
  435. }
  436. case 'ISODate':
  437. if (util.isNumber(object)) {
  438. return new Date(object);
  439. }
  440. else if (object instanceof Date) {
  441. return object.toISOString();
  442. }
  443. else if (moment.isMoment(object)) {
  444. return object.toDate().toISOString();
  445. }
  446. else if (util.isString(object)) {
  447. match = ASPDateRegex.exec(object);
  448. if (match) {
  449. // object is an ASP date
  450. return new Date(Number(match[1])).toISOString(); // parse number
  451. }
  452. else {
  453. return new Date(object).toISOString(); // parse string
  454. }
  455. }
  456. else {
  457. throw new Error(
  458. 'Cannot convert object of type ' + util.getType(object) +
  459. ' to type ISODate');
  460. }
  461. case 'ASPDate':
  462. if (util.isNumber(object)) {
  463. return '/Date(' + object + ')/';
  464. }
  465. else if (object instanceof Date) {
  466. return '/Date(' + object.valueOf() + ')/';
  467. }
  468. else if (util.isString(object)) {
  469. match = ASPDateRegex.exec(object);
  470. var value;
  471. if (match) {
  472. // object is an ASP date
  473. value = new Date(Number(match[1])).valueOf(); // parse number
  474. }
  475. else {
  476. value = new Date(object).valueOf(); // parse string
  477. }
  478. return '/Date(' + value + ')/';
  479. }
  480. else {
  481. throw new Error(
  482. 'Cannot convert object of type ' + util.getType(object) +
  483. ' to type ASPDate');
  484. }
  485. default:
  486. throw new Error('Cannot convert object of type ' + util.getType(object) +
  487. ' to type "' + type + '"');
  488. }
  489. };
  490. // parse ASP.Net Date pattern,
  491. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  492. // code from http://momentjs.com/
  493. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  494. /**
  495. * Get the type of an object, for example util.getType([]) returns 'Array'
  496. * @param {*} object
  497. * @return {String} type
  498. */
  499. util.getType = function getType(object) {
  500. var type = typeof object;
  501. if (type == 'object') {
  502. if (object == null) {
  503. return 'null';
  504. }
  505. if (object instanceof Boolean) {
  506. return 'Boolean';
  507. }
  508. if (object instanceof Number) {
  509. return 'Number';
  510. }
  511. if (object instanceof String) {
  512. return 'String';
  513. }
  514. if (object instanceof Array) {
  515. return 'Array';
  516. }
  517. if (object instanceof Date) {
  518. return 'Date';
  519. }
  520. return 'Object';
  521. }
  522. else if (type == 'number') {
  523. return 'Number';
  524. }
  525. else if (type == 'boolean') {
  526. return 'Boolean';
  527. }
  528. else if (type == 'string') {
  529. return 'String';
  530. }
  531. return type;
  532. };
  533. /**
  534. * Retrieve the absolute left value of a DOM element
  535. * @param {Element} elem A dom element, for example a div
  536. * @return {number} left The absolute left position of this element
  537. * in the browser page.
  538. */
  539. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  540. var doc = document.documentElement;
  541. var body = document.body;
  542. var left = elem.offsetLeft;
  543. var e = elem.offsetParent;
  544. while (e != null && e != body && e != doc) {
  545. left += e.offsetLeft;
  546. left -= e.scrollLeft;
  547. e = e.offsetParent;
  548. }
  549. return left;
  550. };
  551. /**
  552. * Retrieve the absolute top value of a DOM element
  553. * @param {Element} elem A dom element, for example a div
  554. * @return {number} top The absolute top position of this element
  555. * in the browser page.
  556. */
  557. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  558. var doc = document.documentElement;
  559. var body = document.body;
  560. var top = elem.offsetTop;
  561. var e = elem.offsetParent;
  562. while (e != null && e != body && e != doc) {
  563. top += e.offsetTop;
  564. top -= e.scrollTop;
  565. e = e.offsetParent;
  566. }
  567. return top;
  568. };
  569. /**
  570. * Get the absolute, vertical mouse position from an event.
  571. * @param {Event} event
  572. * @return {Number} pageY
  573. */
  574. util.getPageY = function getPageY (event) {
  575. if ('pageY' in event) {
  576. return event.pageY;
  577. }
  578. else {
  579. var clientY;
  580. if (('targetTouches' in event) && event.targetTouches.length) {
  581. clientY = event.targetTouches[0].clientY;
  582. }
  583. else {
  584. clientY = event.clientY;
  585. }
  586. var doc = document.documentElement;
  587. var body = document.body;
  588. return clientY +
  589. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  590. ( doc && doc.clientTop || body && body.clientTop || 0 );
  591. }
  592. };
  593. /**
  594. * Get the absolute, horizontal mouse position from an event.
  595. * @param {Event} event
  596. * @return {Number} pageX
  597. */
  598. util.getPageX = function getPageX (event) {
  599. if ('pageY' in event) {
  600. return event.pageX;
  601. }
  602. else {
  603. var clientX;
  604. if (('targetTouches' in event) && event.targetTouches.length) {
  605. clientX = event.targetTouches[0].clientX;
  606. }
  607. else {
  608. clientX = event.clientX;
  609. }
  610. var doc = document.documentElement;
  611. var body = document.body;
  612. return clientX +
  613. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  614. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  615. }
  616. };
  617. /**
  618. * add a className to the given elements style
  619. * @param {Element} elem
  620. * @param {String} className
  621. */
  622. util.addClassName = function addClassName(elem, className) {
  623. var classes = elem.className.split(' ');
  624. if (classes.indexOf(className) == -1) {
  625. classes.push(className); // add the class to the array
  626. elem.className = classes.join(' ');
  627. }
  628. };
  629. /**
  630. * add a className to the given elements style
  631. * @param {Element} elem
  632. * @param {String} className
  633. */
  634. util.removeClassName = function removeClassname(elem, className) {
  635. var classes = elem.className.split(' ');
  636. var index = classes.indexOf(className);
  637. if (index != -1) {
  638. classes.splice(index, 1); // remove the class from the array
  639. elem.className = classes.join(' ');
  640. }
  641. };
  642. /**
  643. * For each method for both arrays and objects.
  644. * In case of an array, the built-in Array.forEach() is applied.
  645. * In case of an Object, the method loops over all properties of the object.
  646. * @param {Object | Array} object An Object or Array
  647. * @param {function} callback Callback method, called for each item in
  648. * the object or array with three parameters:
  649. * callback(value, index, object)
  650. */
  651. util.forEach = function forEach (object, callback) {
  652. var i,
  653. len;
  654. if (object instanceof Array) {
  655. // array
  656. for (i = 0, len = object.length; i < len; i++) {
  657. callback(object[i], i, object);
  658. }
  659. }
  660. else {
  661. // object
  662. for (i in object) {
  663. if (object.hasOwnProperty(i)) {
  664. callback(object[i], i, object);
  665. }
  666. }
  667. }
  668. };
  669. /**
  670. * Update a property in an object
  671. * @param {Object} object
  672. * @param {String} key
  673. * @param {*} value
  674. * @return {Boolean} changed
  675. */
  676. util.updateProperty = function updateProp (object, key, value) {
  677. if (object[key] !== value) {
  678. object[key] = value;
  679. return true;
  680. }
  681. else {
  682. return false;
  683. }
  684. };
  685. /**
  686. * Add and event listener. Works for all browsers
  687. * @param {Element} element An html element
  688. * @param {string} action The action, for example "click",
  689. * without the prefix "on"
  690. * @param {function} listener The callback function to be executed
  691. * @param {boolean} [useCapture]
  692. */
  693. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  694. if (element.addEventListener) {
  695. if (useCapture === undefined)
  696. useCapture = false;
  697. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  698. action = "DOMMouseScroll"; // For Firefox
  699. }
  700. element.addEventListener(action, listener, useCapture);
  701. } else {
  702. element.attachEvent("on" + action, listener); // IE browsers
  703. }
  704. };
  705. /**
  706. * Remove an event listener from an element
  707. * @param {Element} element An html dom element
  708. * @param {string} action The name of the event, for example "mousedown"
  709. * @param {function} listener The listener function
  710. * @param {boolean} [useCapture]
  711. */
  712. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  713. if (element.removeEventListener) {
  714. // non-IE browsers
  715. if (useCapture === undefined)
  716. useCapture = false;
  717. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  718. action = "DOMMouseScroll"; // For Firefox
  719. }
  720. element.removeEventListener(action, listener, useCapture);
  721. } else {
  722. // IE browsers
  723. element.detachEvent("on" + action, listener);
  724. }
  725. };
  726. /**
  727. * Get HTML element which is the target of the event
  728. * @param {Event} event
  729. * @return {Element} target element
  730. */
  731. util.getTarget = function getTarget(event) {
  732. // code from http://www.quirksmode.org/js/events_properties.html
  733. if (!event) {
  734. event = window.event;
  735. }
  736. var target;
  737. if (event.target) {
  738. target = event.target;
  739. }
  740. else if (event.srcElement) {
  741. target = event.srcElement;
  742. }
  743. if (target.nodeType != undefined && target.nodeType == 3) {
  744. // defeat Safari bug
  745. target = target.parentNode;
  746. }
  747. return target;
  748. };
  749. /**
  750. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  751. * @param {Element} element
  752. * @param {Event} event
  753. */
  754. util.fakeGesture = function fakeGesture (element, event) {
  755. var eventType = null;
  756. // for hammer.js 1.0.5
  757. var gesture = Hammer.event.collectEventData(this, eventType, event);
  758. // for hammer.js 1.0.6
  759. //var touches = Hammer.event.getTouchList(event, eventType);
  760. // var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  761. // on IE in standards mode, no touches are recognized by hammer.js,
  762. // resulting in NaN values for center.pageX and center.pageY
  763. if (isNaN(gesture.center.pageX)) {
  764. gesture.center.pageX = event.pageX;
  765. }
  766. if (isNaN(gesture.center.pageY)) {
  767. gesture.center.pageY = event.pageY;
  768. }
  769. return gesture;
  770. };
  771. util.option = {};
  772. /**
  773. * Convert a value into a boolean
  774. * @param {Boolean | function | undefined} value
  775. * @param {Boolean} [defaultValue]
  776. * @returns {Boolean} bool
  777. */
  778. util.option.asBoolean = function (value, defaultValue) {
  779. if (typeof value == 'function') {
  780. value = value();
  781. }
  782. if (value != null) {
  783. return (value != false);
  784. }
  785. return defaultValue || null;
  786. };
  787. /**
  788. * Convert a value into a number
  789. * @param {Boolean | function | undefined} value
  790. * @param {Number} [defaultValue]
  791. * @returns {Number} number
  792. */
  793. util.option.asNumber = function (value, defaultValue) {
  794. if (typeof value == 'function') {
  795. value = value();
  796. }
  797. if (value != null) {
  798. return Number(value) || defaultValue || null;
  799. }
  800. return defaultValue || null;
  801. };
  802. /**
  803. * Convert a value into a string
  804. * @param {String | function | undefined} value
  805. * @param {String} [defaultValue]
  806. * @returns {String} str
  807. */
  808. util.option.asString = function (value, defaultValue) {
  809. if (typeof value == 'function') {
  810. value = value();
  811. }
  812. if (value != null) {
  813. return String(value);
  814. }
  815. return defaultValue || null;
  816. };
  817. /**
  818. * Convert a size or location into a string with pixels or a percentage
  819. * @param {String | Number | function | undefined} value
  820. * @param {String} [defaultValue]
  821. * @returns {String} size
  822. */
  823. util.option.asSize = function (value, defaultValue) {
  824. if (typeof value == 'function') {
  825. value = value();
  826. }
  827. if (util.isString(value)) {
  828. return value;
  829. }
  830. else if (util.isNumber(value)) {
  831. return value + 'px';
  832. }
  833. else {
  834. return defaultValue || null;
  835. }
  836. };
  837. /**
  838. * Convert a value into a DOM element
  839. * @param {HTMLElement | function | undefined} value
  840. * @param {HTMLElement} [defaultValue]
  841. * @returns {HTMLElement | null} dom
  842. */
  843. util.option.asElement = function (value, defaultValue) {
  844. if (typeof value == 'function') {
  845. value = value();
  846. }
  847. return value || defaultValue || null;
  848. };
  849. util.GiveDec = function GiveDec(Hex)
  850. {
  851. if(Hex == "A")
  852. Value = 10;
  853. else
  854. if(Hex == "B")
  855. Value = 11;
  856. else
  857. if(Hex == "C")
  858. Value = 12;
  859. else
  860. if(Hex == "D")
  861. Value = 13;
  862. else
  863. if(Hex == "E")
  864. Value = 14;
  865. else
  866. if(Hex == "F")
  867. Value = 15;
  868. else
  869. Value = eval(Hex)
  870. return Value;
  871. }
  872. util.GiveHex = function GiveHex(Dec)
  873. {
  874. if(Dec == 10)
  875. Value = "A";
  876. else
  877. if(Dec == 11)
  878. Value = "B";
  879. else
  880. if(Dec == 12)
  881. Value = "C";
  882. else
  883. if(Dec == 13)
  884. Value = "D";
  885. else
  886. if(Dec == 14)
  887. Value = "E";
  888. else
  889. if(Dec == 15)
  890. Value = "F";
  891. else
  892. Value = "" + Dec;
  893. return Value;
  894. }
  895. /**
  896. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  897. *
  898. * @param {String} hex
  899. * @returns {{r: *, g: *, b: *}}
  900. */
  901. util.hexToRGB = function hexToRGB(hex) {
  902. hex = hex.replace("#","").toUpperCase();
  903. var a = util.GiveDec(hex.substring(0, 1));
  904. var b = util.GiveDec(hex.substring(1, 2));
  905. var c = util.GiveDec(hex.substring(2, 3));
  906. var d = util.GiveDec(hex.substring(3, 4));
  907. var e = util.GiveDec(hex.substring(4, 5));
  908. var f = util.GiveDec(hex.substring(5, 6));
  909. var r = (a * 16) + b;
  910. var g = (c * 16) + d;
  911. var b = (e * 16) + f;
  912. return {r:r,g:g,b:b};
  913. };
  914. util.RGBToHex = function RGBToHex(red,green,blue) {
  915. var a = util.GiveHex(Math.floor(red / 16));
  916. var b = util.GiveHex(red % 16);
  917. var c = util.GiveHex(Math.floor(green / 16));
  918. var d = util.GiveHex(green % 16);
  919. var e = util.GiveHex(Math.floor(blue / 16));
  920. var f = util.GiveHex(blue % 16);
  921. var hex = a + b + c + d + e + f;
  922. return "#" + hex;
  923. };
  924. /**
  925. * http://www.javascripter.net/faq/rgb2hsv.htm
  926. *
  927. * @param red
  928. * @param green
  929. * @param blue
  930. * @returns {*}
  931. * @constructor
  932. */
  933. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  934. red=red/255; green=green/255; blue=blue/255;
  935. var minRGB = Math.min(red,Math.min(green,blue));
  936. var maxRGB = Math.max(red,Math.max(green,blue));
  937. // Black-gray-white
  938. if (minRGB == maxRGB) {
  939. return {h:0,s:0,v:minRGB};
  940. }
  941. // Colors other than black-gray-white:
  942. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  943. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  944. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  945. var saturation = (maxRGB - minRGB)/maxRGB;
  946. var value = maxRGB;
  947. return {h:hue,s:saturation,v:value};
  948. };
  949. /**
  950. * https://gist.github.com/mjijackson/5311256
  951. * @param hue
  952. * @param saturation
  953. * @param value
  954. * @returns {{r: number, g: number, b: number}}
  955. * @constructor
  956. */
  957. util.HSVToRGB = function HSVToRGB(h, s, v) {
  958. var r, g, b;
  959. var i = Math.floor(h * 6);
  960. var f = h * 6 - i;
  961. var p = v * (1 - s);
  962. var q = v * (1 - f * s);
  963. var t = v * (1 - (1 - f) * s);
  964. switch (i % 6) {
  965. case 0: r = v, g = t, b = p; break;
  966. case 1: r = q, g = v, b = p; break;
  967. case 2: r = p, g = v, b = t; break;
  968. case 3: r = p, g = q, b = v; break;
  969. case 4: r = t, g = p, b = v; break;
  970. case 5: r = v, g = p, b = q; break;
  971. }
  972. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  973. };
  974. util.HSVToHex = function HSVToHex(h,s,v) {
  975. var rgb = util.HSVToRGB(h,s,v);
  976. return util.RGBToHex(rgb.r,rgb.g,rgb.b);
  977. }
  978. util.hexToHSV = function hexToHSV(hex) {
  979. var rgb = util.hexToRGB(hex);
  980. return util.RGBToHSV(rgb.r,rgb.g,rgb.b);
  981. }
  982. util.isValidHex = function isValidHex(hex) {
  983. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  984. return isOk;
  985. }
  986. util.copyObject = function copyObject(objectFrom,objectTo) {
  987. for (var i in objectFrom) {
  988. if (objectFrom.hasOwnProperty(i)) {
  989. if (typeof objectFrom[i] == "object") {
  990. objectTo[i] = {};
  991. util.copyObject(objectFrom[i],objectTo[i]);
  992. }
  993. else {
  994. objectTo[i] = objectFrom[i];
  995. }
  996. }
  997. }
  998. }
  999. /**
  1000. * DataSet
  1001. *
  1002. * Usage:
  1003. * var dataSet = new DataSet({
  1004. * fieldId: '_id',
  1005. * convert: {
  1006. * // ...
  1007. * }
  1008. * });
  1009. *
  1010. * dataSet.add(item);
  1011. * dataSet.add(data);
  1012. * dataSet.update(item);
  1013. * dataSet.update(data);
  1014. * dataSet.remove(id);
  1015. * dataSet.remove(ids);
  1016. * var data = dataSet.get();
  1017. * var data = dataSet.get(id);
  1018. * var data = dataSet.get(ids);
  1019. * var data = dataSet.get(ids, options, data);
  1020. * dataSet.clear();
  1021. *
  1022. * A data set can:
  1023. * - add/remove/update data
  1024. * - gives triggers upon changes in the data
  1025. * - can import/export data in various data formats
  1026. *
  1027. * @param {Object} [options] Available options:
  1028. * {String} fieldId Field name of the id in the
  1029. * items, 'id' by default.
  1030. * {Object.<String, String} convert
  1031. * A map with field names as key,
  1032. * and the field type as value.
  1033. * @constructor DataSet
  1034. */
  1035. // TODO: add a DataSet constructor DataSet(data, options)
  1036. function DataSet (options) {
  1037. this.id = util.randomUUID();
  1038. this.options = options || {};
  1039. this.data = {}; // map with data indexed by id
  1040. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1041. this.convert = {}; // field types by field name
  1042. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1043. if (this.options.convert) {
  1044. for (var field in this.options.convert) {
  1045. if (this.options.convert.hasOwnProperty(field)) {
  1046. var value = this.options.convert[field];
  1047. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1048. this.convert[field] = 'Date';
  1049. }
  1050. else {
  1051. this.convert[field] = value;
  1052. }
  1053. }
  1054. }
  1055. }
  1056. // event subscribers
  1057. this.subscribers = {};
  1058. this.internalIds = {}; // internally generated id's
  1059. }
  1060. /**
  1061. * Subscribe to an event, add an event listener
  1062. * @param {String} event Event name. Available events: 'put', 'update',
  1063. * 'remove'
  1064. * @param {function} callback Callback method. Called with three parameters:
  1065. * {String} event
  1066. * {Object | null} params
  1067. * {String | Number} senderId
  1068. */
  1069. DataSet.prototype.on = function on (event, callback) {
  1070. var subscribers = this.subscribers[event];
  1071. if (!subscribers) {
  1072. subscribers = [];
  1073. this.subscribers[event] = subscribers;
  1074. }
  1075. subscribers.push({
  1076. callback: callback
  1077. });
  1078. };
  1079. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1080. DataSet.prototype.subscribe = DataSet.prototype.on;
  1081. /**
  1082. * Unsubscribe from an event, remove an event listener
  1083. * @param {String} event
  1084. * @param {function} callback
  1085. */
  1086. DataSet.prototype.off = function off(event, callback) {
  1087. var subscribers = this.subscribers[event];
  1088. if (subscribers) {
  1089. this.subscribers[event] = subscribers.filter(function (listener) {
  1090. return (listener.callback != callback);
  1091. });
  1092. }
  1093. };
  1094. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1095. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1096. /**
  1097. * Trigger an event
  1098. * @param {String} event
  1099. * @param {Object | null} params
  1100. * @param {String} [senderId] Optional id of the sender.
  1101. * @private
  1102. */
  1103. DataSet.prototype._trigger = function (event, params, senderId) {
  1104. if (event == '*') {
  1105. throw new Error('Cannot trigger event *');
  1106. }
  1107. var subscribers = [];
  1108. if (event in this.subscribers) {
  1109. subscribers = subscribers.concat(this.subscribers[event]);
  1110. }
  1111. if ('*' in this.subscribers) {
  1112. subscribers = subscribers.concat(this.subscribers['*']);
  1113. }
  1114. for (var i = 0; i < subscribers.length; i++) {
  1115. var subscriber = subscribers[i];
  1116. if (subscriber.callback) {
  1117. subscriber.callback(event, params, senderId || null);
  1118. }
  1119. }
  1120. };
  1121. /**
  1122. * Add data.
  1123. * Adding an item will fail when there already is an item with the same id.
  1124. * @param {Object | Array | DataTable} data
  1125. * @param {String} [senderId] Optional sender id
  1126. * @return {Array} addedIds Array with the ids of the added items
  1127. */
  1128. DataSet.prototype.add = function (data, senderId) {
  1129. var addedIds = [],
  1130. id,
  1131. me = this;
  1132. if (data instanceof Array) {
  1133. // Array
  1134. for (var i = 0, len = data.length; i < len; i++) {
  1135. id = me._addItem(data[i]);
  1136. addedIds.push(id);
  1137. }
  1138. }
  1139. else if (util.isDataTable(data)) {
  1140. // Google DataTable
  1141. var columns = this._getColumnNames(data);
  1142. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1143. var item = {};
  1144. for (var col = 0, cols = columns.length; col < cols; col++) {
  1145. var field = columns[col];
  1146. item[field] = data.getValue(row, col);
  1147. }
  1148. id = me._addItem(item);
  1149. addedIds.push(id);
  1150. }
  1151. }
  1152. else if (data instanceof Object) {
  1153. // Single item
  1154. id = me._addItem(data);
  1155. addedIds.push(id);
  1156. }
  1157. else {
  1158. throw new Error('Unknown dataType');
  1159. }
  1160. if (addedIds.length) {
  1161. this._trigger('add', {items: addedIds}, senderId);
  1162. }
  1163. return addedIds;
  1164. };
  1165. /**
  1166. * Update existing items. When an item does not exist, it will be created
  1167. * @param {Object | Array | DataTable} data
  1168. * @param {String} [senderId] Optional sender id
  1169. * @return {Array} updatedIds The ids of the added or updated items
  1170. */
  1171. DataSet.prototype.update = function (data, senderId) {
  1172. var addedIds = [],
  1173. updatedIds = [],
  1174. me = this,
  1175. fieldId = me.fieldId;
  1176. var addOrUpdate = function (item) {
  1177. var id = item[fieldId];
  1178. if (me.data[id]) {
  1179. // update item
  1180. id = me._updateItem(item);
  1181. updatedIds.push(id);
  1182. }
  1183. else {
  1184. // add new item
  1185. id = me._addItem(item);
  1186. addedIds.push(id);
  1187. }
  1188. };
  1189. if (data instanceof Array) {
  1190. // Array
  1191. for (var i = 0, len = data.length; i < len; i++) {
  1192. addOrUpdate(data[i]);
  1193. }
  1194. }
  1195. else if (util.isDataTable(data)) {
  1196. // Google DataTable
  1197. var columns = this._getColumnNames(data);
  1198. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1199. var item = {};
  1200. for (var col = 0, cols = columns.length; col < cols; col++) {
  1201. var field = columns[col];
  1202. item[field] = data.getValue(row, col);
  1203. }
  1204. addOrUpdate(item);
  1205. }
  1206. }
  1207. else if (data instanceof Object) {
  1208. // Single item
  1209. addOrUpdate(data);
  1210. }
  1211. else {
  1212. throw new Error('Unknown dataType');
  1213. }
  1214. if (addedIds.length) {
  1215. this._trigger('add', {items: addedIds}, senderId);
  1216. }
  1217. if (updatedIds.length) {
  1218. this._trigger('update', {items: updatedIds}, senderId);
  1219. }
  1220. return addedIds.concat(updatedIds);
  1221. };
  1222. /**
  1223. * Get a data item or multiple items.
  1224. *
  1225. * Usage:
  1226. *
  1227. * get()
  1228. * get(options: Object)
  1229. * get(options: Object, data: Array | DataTable)
  1230. *
  1231. * get(id: Number | String)
  1232. * get(id: Number | String, options: Object)
  1233. * get(id: Number | String, options: Object, data: Array | DataTable)
  1234. *
  1235. * get(ids: Number[] | String[])
  1236. * get(ids: Number[] | String[], options: Object)
  1237. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1238. *
  1239. * Where:
  1240. *
  1241. * {Number | String} id The id of an item
  1242. * {Number[] | String{}} ids An array with ids of items
  1243. * {Object} options An Object with options. Available options:
  1244. * {String} [type] Type of data to be returned. Can
  1245. * be 'DataTable' or 'Array' (default)
  1246. * {Object.<String, String>} [convert]
  1247. * {String[]} [fields] field names to be returned
  1248. * {function} [filter] filter items
  1249. * {String | function} [order] Order the items by
  1250. * a field name or custom sort function.
  1251. * {Array | DataTable} [data] If provided, items will be appended to this
  1252. * array or table. Required in case of Google
  1253. * DataTable.
  1254. *
  1255. * @throws Error
  1256. */
  1257. DataSet.prototype.get = function (args) {
  1258. var me = this;
  1259. var globalShowInternalIds = this.showInternalIds;
  1260. // parse the arguments
  1261. var id, ids, options, data;
  1262. var firstType = util.getType(arguments[0]);
  1263. if (firstType == 'String' || firstType == 'Number') {
  1264. // get(id [, options] [, data])
  1265. id = arguments[0];
  1266. options = arguments[1];
  1267. data = arguments[2];
  1268. }
  1269. else if (firstType == 'Array') {
  1270. // get(ids [, options] [, data])
  1271. ids = arguments[0];
  1272. options = arguments[1];
  1273. data = arguments[2];
  1274. }
  1275. else {
  1276. // get([, options] [, data])
  1277. options = arguments[0];
  1278. data = arguments[1];
  1279. }
  1280. // determine the return type
  1281. var type;
  1282. if (options && options.type) {
  1283. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1284. if (data && (type != util.getType(data))) {
  1285. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1286. 'does not correspond with specified options.type (' + options.type + ')');
  1287. }
  1288. if (type == 'DataTable' && !util.isDataTable(data)) {
  1289. throw new Error('Parameter "data" must be a DataTable ' +
  1290. 'when options.type is "DataTable"');
  1291. }
  1292. }
  1293. else if (data) {
  1294. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1295. }
  1296. else {
  1297. type = 'Array';
  1298. }
  1299. // we allow the setting of this value for a single get request.
  1300. if (options != undefined) {
  1301. if (options.showInternalIds != undefined) {
  1302. this.showInternalIds = options.showInternalIds;
  1303. }
  1304. }
  1305. // build options
  1306. var convert = options && options.convert || this.options.convert;
  1307. var filter = options && options.filter;
  1308. var items = [], item, itemId, i, len;
  1309. // convert items
  1310. if (id != undefined) {
  1311. // return a single item
  1312. item = me._getItem(id, convert);
  1313. if (filter && !filter(item)) {
  1314. item = null;
  1315. }
  1316. }
  1317. else if (ids != undefined) {
  1318. // return a subset of items
  1319. for (i = 0, len = ids.length; i < len; i++) {
  1320. item = me._getItem(ids[i], convert);
  1321. if (!filter || filter(item)) {
  1322. items.push(item);
  1323. }
  1324. }
  1325. }
  1326. else {
  1327. // return all items
  1328. for (itemId in this.data) {
  1329. if (this.data.hasOwnProperty(itemId)) {
  1330. item = me._getItem(itemId, convert);
  1331. if (!filter || filter(item)) {
  1332. items.push(item);
  1333. }
  1334. }
  1335. }
  1336. }
  1337. // restore the global value of showInternalIds
  1338. this.showInternalIds = globalShowInternalIds;
  1339. // order the results
  1340. if (options && options.order && id == undefined) {
  1341. this._sort(items, options.order);
  1342. }
  1343. // filter fields of the items
  1344. if (options && options.fields) {
  1345. var fields = options.fields;
  1346. if (id != undefined) {
  1347. item = this._filterFields(item, fields);
  1348. }
  1349. else {
  1350. for (i = 0, len = items.length; i < len; i++) {
  1351. items[i] = this._filterFields(items[i], fields);
  1352. }
  1353. }
  1354. }
  1355. // return the results
  1356. if (type == 'DataTable') {
  1357. var columns = this._getColumnNames(data);
  1358. if (id != undefined) {
  1359. // append a single item to the data table
  1360. me._appendRow(data, columns, item);
  1361. }
  1362. else {
  1363. // copy the items to the provided data table
  1364. for (i = 0, len = items.length; i < len; i++) {
  1365. me._appendRow(data, columns, items[i]);
  1366. }
  1367. }
  1368. return data;
  1369. }
  1370. else {
  1371. // return an array
  1372. if (id != undefined) {
  1373. // a single item
  1374. return item;
  1375. }
  1376. else {
  1377. // multiple items
  1378. if (data) {
  1379. // copy the items to the provided array
  1380. for (i = 0, len = items.length; i < len; i++) {
  1381. data.push(items[i]);
  1382. }
  1383. return data;
  1384. }
  1385. else {
  1386. // just return our array
  1387. return items;
  1388. }
  1389. }
  1390. }
  1391. };
  1392. /**
  1393. * Get ids of all items or from a filtered set of items.
  1394. * @param {Object} [options] An Object with options. Available options:
  1395. * {function} [filter] filter items
  1396. * {String | function} [order] Order the items by
  1397. * a field name or custom sort function.
  1398. * @return {Array} ids
  1399. */
  1400. DataSet.prototype.getIds = function (options) {
  1401. var data = this.data,
  1402. filter = options && options.filter,
  1403. order = options && options.order,
  1404. convert = options && options.convert || this.options.convert,
  1405. i,
  1406. len,
  1407. id,
  1408. item,
  1409. items,
  1410. ids = [];
  1411. if (filter) {
  1412. // get filtered items
  1413. if (order) {
  1414. // create ordered list
  1415. items = [];
  1416. for (id in data) {
  1417. if (data.hasOwnProperty(id)) {
  1418. item = this._getItem(id, convert);
  1419. if (filter(item)) {
  1420. items.push(item);
  1421. }
  1422. }
  1423. }
  1424. this._sort(items, order);
  1425. for (i = 0, len = items.length; i < len; i++) {
  1426. ids[i] = items[i][this.fieldId];
  1427. }
  1428. }
  1429. else {
  1430. // create unordered list
  1431. for (id in data) {
  1432. if (data.hasOwnProperty(id)) {
  1433. item = this._getItem(id, convert);
  1434. if (filter(item)) {
  1435. ids.push(item[this.fieldId]);
  1436. }
  1437. }
  1438. }
  1439. }
  1440. }
  1441. else {
  1442. // get all items
  1443. if (order) {
  1444. // create an ordered list
  1445. items = [];
  1446. for (id in data) {
  1447. if (data.hasOwnProperty(id)) {
  1448. items.push(data[id]);
  1449. }
  1450. }
  1451. this._sort(items, order);
  1452. for (i = 0, len = items.length; i < len; i++) {
  1453. ids[i] = items[i][this.fieldId];
  1454. }
  1455. }
  1456. else {
  1457. // create unordered list
  1458. for (id in data) {
  1459. if (data.hasOwnProperty(id)) {
  1460. item = data[id];
  1461. ids.push(item[this.fieldId]);
  1462. }
  1463. }
  1464. }
  1465. }
  1466. return ids;
  1467. };
  1468. /**
  1469. * Execute a callback function for every item in the dataset.
  1470. * The order of the items is not determined.
  1471. * @param {function} callback
  1472. * @param {Object} [options] Available options:
  1473. * {Object.<String, String>} [convert]
  1474. * {String[]} [fields] filter fields
  1475. * {function} [filter] filter items
  1476. * {String | function} [order] Order the items by
  1477. * a field name or custom sort function.
  1478. */
  1479. DataSet.prototype.forEach = function (callback, options) {
  1480. var filter = options && options.filter,
  1481. convert = options && options.convert || this.options.convert,
  1482. data = this.data,
  1483. item,
  1484. id;
  1485. if (options && options.order) {
  1486. // execute forEach on ordered list
  1487. var items = this.get(options);
  1488. for (var i = 0, len = items.length; i < len; i++) {
  1489. item = items[i];
  1490. id = item[this.fieldId];
  1491. callback(item, id);
  1492. }
  1493. }
  1494. else {
  1495. // unordered
  1496. for (id in data) {
  1497. if (data.hasOwnProperty(id)) {
  1498. item = this._getItem(id, convert);
  1499. if (!filter || filter(item)) {
  1500. callback(item, id);
  1501. }
  1502. }
  1503. }
  1504. }
  1505. };
  1506. /**
  1507. * Map every item in the dataset.
  1508. * @param {function} callback
  1509. * @param {Object} [options] Available options:
  1510. * {Object.<String, String>} [convert]
  1511. * {String[]} [fields] filter fields
  1512. * {function} [filter] filter items
  1513. * {String | function} [order] Order the items by
  1514. * a field name or custom sort function.
  1515. * @return {Object[]} mappedItems
  1516. */
  1517. DataSet.prototype.map = function (callback, options) {
  1518. var filter = options && options.filter,
  1519. convert = options && options.convert || this.options.convert,
  1520. mappedItems = [],
  1521. data = this.data,
  1522. item;
  1523. // convert and filter items
  1524. for (var id in data) {
  1525. if (data.hasOwnProperty(id)) {
  1526. item = this._getItem(id, convert);
  1527. if (!filter || filter(item)) {
  1528. mappedItems.push(callback(item, id));
  1529. }
  1530. }
  1531. }
  1532. // order items
  1533. if (options && options.order) {
  1534. this._sort(mappedItems, options.order);
  1535. }
  1536. return mappedItems;
  1537. };
  1538. /**
  1539. * Filter the fields of an item
  1540. * @param {Object} item
  1541. * @param {String[]} fields Field names
  1542. * @return {Object} filteredItem
  1543. * @private
  1544. */
  1545. DataSet.prototype._filterFields = function (item, fields) {
  1546. var filteredItem = {};
  1547. for (var field in item) {
  1548. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1549. filteredItem[field] = item[field];
  1550. }
  1551. }
  1552. return filteredItem;
  1553. };
  1554. /**
  1555. * Sort the provided array with items
  1556. * @param {Object[]} items
  1557. * @param {String | function} order A field name or custom sort function.
  1558. * @private
  1559. */
  1560. DataSet.prototype._sort = function (items, order) {
  1561. if (util.isString(order)) {
  1562. // order by provided field name
  1563. var name = order; // field name
  1564. items.sort(function (a, b) {
  1565. var av = a[name];
  1566. var bv = b[name];
  1567. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1568. });
  1569. }
  1570. else if (typeof order === 'function') {
  1571. // order by sort function
  1572. items.sort(order);
  1573. }
  1574. // TODO: extend order by an Object {field:String, direction:String}
  1575. // where direction can be 'asc' or 'desc'
  1576. else {
  1577. throw new TypeError('Order must be a function or a string');
  1578. }
  1579. };
  1580. /**
  1581. * Remove an object by pointer or by id
  1582. * @param {String | Number | Object | Array} id Object or id, or an array with
  1583. * objects or ids to be removed
  1584. * @param {String} [senderId] Optional sender id
  1585. * @return {Array} removedIds
  1586. */
  1587. DataSet.prototype.remove = function (id, senderId) {
  1588. var removedIds = [],
  1589. i, len, removedId;
  1590. if (id instanceof Array) {
  1591. for (i = 0, len = id.length; i < len; i++) {
  1592. removedId = this._remove(id[i]);
  1593. if (removedId != null) {
  1594. removedIds.push(removedId);
  1595. }
  1596. }
  1597. }
  1598. else {
  1599. removedId = this._remove(id);
  1600. if (removedId != null) {
  1601. removedIds.push(removedId);
  1602. }
  1603. }
  1604. if (removedIds.length) {
  1605. this._trigger('remove', {items: removedIds}, senderId);
  1606. }
  1607. return removedIds;
  1608. };
  1609. /**
  1610. * Remove an item by its id
  1611. * @param {Number | String | Object} id id or item
  1612. * @returns {Number | String | null} id
  1613. * @private
  1614. */
  1615. DataSet.prototype._remove = function (id) {
  1616. if (util.isNumber(id) || util.isString(id)) {
  1617. if (this.data[id]) {
  1618. delete this.data[id];
  1619. delete this.internalIds[id];
  1620. return id;
  1621. }
  1622. }
  1623. else if (id instanceof Object) {
  1624. var itemId = id[this.fieldId];
  1625. if (itemId && this.data[itemId]) {
  1626. delete this.data[itemId];
  1627. delete this.internalIds[itemId];
  1628. return itemId;
  1629. }
  1630. }
  1631. return null;
  1632. };
  1633. /**
  1634. * Clear the data
  1635. * @param {String} [senderId] Optional sender id
  1636. * @return {Array} removedIds The ids of all removed items
  1637. */
  1638. DataSet.prototype.clear = function (senderId) {
  1639. var ids = Object.keys(this.data);
  1640. this.data = {};
  1641. this.internalIds = {};
  1642. this._trigger('remove', {items: ids}, senderId);
  1643. return ids;
  1644. };
  1645. /**
  1646. * Find the item with maximum value of a specified field
  1647. * @param {String} field
  1648. * @return {Object | null} item Item containing max value, or null if no items
  1649. */
  1650. DataSet.prototype.max = function (field) {
  1651. var data = this.data,
  1652. max = null,
  1653. maxField = null;
  1654. for (var id in data) {
  1655. if (data.hasOwnProperty(id)) {
  1656. var item = data[id];
  1657. var itemField = item[field];
  1658. if (itemField != null && (!max || itemField > maxField)) {
  1659. max = item;
  1660. maxField = itemField;
  1661. }
  1662. }
  1663. }
  1664. return max;
  1665. };
  1666. /**
  1667. * Find the item with minimum value of a specified field
  1668. * @param {String} field
  1669. * @return {Object | null} item Item containing max value, or null if no items
  1670. */
  1671. DataSet.prototype.min = function (field) {
  1672. var data = this.data,
  1673. min = null,
  1674. minField = null;
  1675. for (var id in data) {
  1676. if (data.hasOwnProperty(id)) {
  1677. var item = data[id];
  1678. var itemField = item[field];
  1679. if (itemField != null && (!min || itemField < minField)) {
  1680. min = item;
  1681. minField = itemField;
  1682. }
  1683. }
  1684. }
  1685. return min;
  1686. };
  1687. /**
  1688. * Find all distinct values of a specified field
  1689. * @param {String} field
  1690. * @return {Array} values Array containing all distinct values. If the data
  1691. * items do not contain the specified field, an array
  1692. * containing a single value undefined is returned.
  1693. * The returned array is unordered.
  1694. */
  1695. DataSet.prototype.distinct = function (field) {
  1696. var data = this.data,
  1697. values = [],
  1698. fieldType = this.options.convert[field],
  1699. count = 0;
  1700. for (var prop in data) {
  1701. if (data.hasOwnProperty(prop)) {
  1702. var item = data[prop];
  1703. var value = util.convert(item[field], fieldType);
  1704. var exists = false;
  1705. for (var i = 0; i < count; i++) {
  1706. if (values[i] == value) {
  1707. exists = true;
  1708. break;
  1709. }
  1710. }
  1711. if (!exists) {
  1712. values[count] = value;
  1713. count++;
  1714. }
  1715. }
  1716. }
  1717. return values;
  1718. };
  1719. /**
  1720. * Add a single item. Will fail when an item with the same id already exists.
  1721. * @param {Object} item
  1722. * @return {String} id
  1723. * @private
  1724. */
  1725. DataSet.prototype._addItem = function (item) {
  1726. var id = item[this.fieldId];
  1727. if (id != undefined) {
  1728. // check whether this id is already taken
  1729. if (this.data[id]) {
  1730. // item already exists
  1731. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1732. }
  1733. }
  1734. else {
  1735. // generate an id
  1736. id = util.randomUUID();
  1737. item[this.fieldId] = id;
  1738. this.internalIds[id] = item;
  1739. }
  1740. var d = {};
  1741. for (var field in item) {
  1742. if (item.hasOwnProperty(field)) {
  1743. var fieldType = this.convert[field]; // type may be undefined
  1744. d[field] = util.convert(item[field], fieldType);
  1745. }
  1746. }
  1747. this.data[id] = d;
  1748. return id;
  1749. };
  1750. /**
  1751. * Get an item. Fields can be converted to a specific type
  1752. * @param {String} id
  1753. * @param {Object.<String, String>} [convert] field types to convert
  1754. * @return {Object | null} item
  1755. * @private
  1756. */
  1757. DataSet.prototype._getItem = function (id, convert) {
  1758. var field, value;
  1759. // get the item from the dataset
  1760. var raw = this.data[id];
  1761. if (!raw) {
  1762. return null;
  1763. }
  1764. // convert the items field types
  1765. var converted = {},
  1766. fieldId = this.fieldId,
  1767. internalIds = this.internalIds;
  1768. if (convert) {
  1769. for (field in raw) {
  1770. if (raw.hasOwnProperty(field)) {
  1771. value = raw[field];
  1772. // output all fields, except internal ids
  1773. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1774. converted[field] = util.convert(value, convert[field]);
  1775. }
  1776. }
  1777. }
  1778. }
  1779. else {
  1780. // no field types specified, no converting needed
  1781. for (field in raw) {
  1782. if (raw.hasOwnProperty(field)) {
  1783. value = raw[field];
  1784. // output all fields, except internal ids
  1785. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1786. converted[field] = value;
  1787. }
  1788. }
  1789. }
  1790. }
  1791. return converted;
  1792. };
  1793. /**
  1794. * Update a single item: merge with existing item.
  1795. * Will fail when the item has no id, or when there does not exist an item
  1796. * with the same id.
  1797. * @param {Object} item
  1798. * @return {String} id
  1799. * @private
  1800. */
  1801. DataSet.prototype._updateItem = function (item) {
  1802. var id = item[this.fieldId];
  1803. if (id == undefined) {
  1804. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1805. }
  1806. var d = this.data[id];
  1807. if (!d) {
  1808. // item doesn't exist
  1809. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1810. }
  1811. // merge with current item
  1812. for (var field in item) {
  1813. if (item.hasOwnProperty(field)) {
  1814. var fieldType = this.convert[field]; // type may be undefined
  1815. d[field] = util.convert(item[field], fieldType);
  1816. }
  1817. }
  1818. return id;
  1819. };
  1820. /**
  1821. * check if an id is an internal or external id
  1822. * @param id
  1823. * @returns {boolean}
  1824. * @private
  1825. */
  1826. DataSet.prototype.isInternalId = function(id) {
  1827. return (id in this.internalIds);
  1828. };
  1829. /**
  1830. * Get an array with the column names of a Google DataTable
  1831. * @param {DataTable} dataTable
  1832. * @return {String[]} columnNames
  1833. * @private
  1834. */
  1835. DataSet.prototype._getColumnNames = function (dataTable) {
  1836. var columns = [];
  1837. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1838. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1839. }
  1840. return columns;
  1841. };
  1842. /**
  1843. * Append an item as a row to the dataTable
  1844. * @param dataTable
  1845. * @param columns
  1846. * @param item
  1847. * @private
  1848. */
  1849. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1850. var row = dataTable.addRow();
  1851. for (var col = 0, cols = columns.length; col < cols; col++) {
  1852. var field = columns[col];
  1853. dataTable.setValue(row, col, item[field]);
  1854. }
  1855. };
  1856. /**
  1857. * DataView
  1858. *
  1859. * a dataview offers a filtered view on a dataset or an other dataview.
  1860. *
  1861. * @param {DataSet | DataView} data
  1862. * @param {Object} [options] Available options: see method get
  1863. *
  1864. * @constructor DataView
  1865. */
  1866. function DataView (data, options) {
  1867. this.id = util.randomUUID();
  1868. this.data = null;
  1869. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1870. this.options = options || {};
  1871. this.fieldId = 'id'; // name of the field containing id
  1872. this.subscribers = {}; // event subscribers
  1873. var me = this;
  1874. this.listener = function () {
  1875. me._onEvent.apply(me, arguments);
  1876. };
  1877. this.setData(data);
  1878. }
  1879. // TODO: implement a function .config() to dynamically update things like configured filter
  1880. // and trigger changes accordingly
  1881. /**
  1882. * Set a data source for the view
  1883. * @param {DataSet | DataView} data
  1884. */
  1885. DataView.prototype.setData = function (data) {
  1886. var ids, dataItems, i, len;
  1887. if (this.data) {
  1888. // unsubscribe from current dataset
  1889. if (this.data.unsubscribe) {
  1890. this.data.unsubscribe('*', this.listener);
  1891. }
  1892. // trigger a remove of all items in memory
  1893. ids = [];
  1894. for (var id in this.ids) {
  1895. if (this.ids.hasOwnProperty(id)) {
  1896. ids.push(id);
  1897. }
  1898. }
  1899. this.ids = {};
  1900. this._trigger('remove', {items: ids});
  1901. }
  1902. this.data = data;
  1903. if (this.data) {
  1904. // update fieldId
  1905. this.fieldId = this.options.fieldId ||
  1906. (this.data && this.data.options && this.data.options.fieldId) ||
  1907. 'id';
  1908. // trigger an add of all added items
  1909. ids = this.data.getIds({filter: this.options && this.options.filter});
  1910. for (i = 0, len = ids.length; i < len; i++) {
  1911. id = ids[i];
  1912. this.ids[id] = true;
  1913. }
  1914. this._trigger('add', {items: ids});
  1915. // subscribe to new dataset
  1916. if (this.data.on) {
  1917. this.data.on('*', this.listener);
  1918. }
  1919. }
  1920. };
  1921. /**
  1922. * Get data from the data view
  1923. *
  1924. * Usage:
  1925. *
  1926. * get()
  1927. * get(options: Object)
  1928. * get(options: Object, data: Array | DataTable)
  1929. *
  1930. * get(id: Number)
  1931. * get(id: Number, options: Object)
  1932. * get(id: Number, options: Object, data: Array | DataTable)
  1933. *
  1934. * get(ids: Number[])
  1935. * get(ids: Number[], options: Object)
  1936. * get(ids: Number[], options: Object, data: Array | DataTable)
  1937. *
  1938. * Where:
  1939. *
  1940. * {Number | String} id The id of an item
  1941. * {Number[] | String{}} ids An array with ids of items
  1942. * {Object} options An Object with options. Available options:
  1943. * {String} [type] Type of data to be returned. Can
  1944. * be 'DataTable' or 'Array' (default)
  1945. * {Object.<String, String>} [convert]
  1946. * {String[]} [fields] field names to be returned
  1947. * {function} [filter] filter items
  1948. * {String | function} [order] Order the items by
  1949. * a field name or custom sort function.
  1950. * {Array | DataTable} [data] If provided, items will be appended to this
  1951. * array or table. Required in case of Google
  1952. * DataTable.
  1953. * @param args
  1954. */
  1955. DataView.prototype.get = function (args) {
  1956. var me = this;
  1957. // parse the arguments
  1958. var ids, options, data;
  1959. var firstType = util.getType(arguments[0]);
  1960. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  1961. // get(id(s) [, options] [, data])
  1962. ids = arguments[0]; // can be a single id or an array with ids
  1963. options = arguments[1];
  1964. data = arguments[2];
  1965. }
  1966. else {
  1967. // get([, options] [, data])
  1968. options = arguments[0];
  1969. data = arguments[1];
  1970. }
  1971. // extend the options with the default options and provided options
  1972. var viewOptions = util.extend({}, this.options, options);
  1973. // create a combined filter method when needed
  1974. if (this.options.filter && options && options.filter) {
  1975. viewOptions.filter = function (item) {
  1976. return me.options.filter(item) && options.filter(item);
  1977. }
  1978. }
  1979. // build up the call to the linked data set
  1980. var getArguments = [];
  1981. if (ids != undefined) {
  1982. getArguments.push(ids);
  1983. }
  1984. getArguments.push(viewOptions);
  1985. getArguments.push(data);
  1986. return this.data && this.data.get.apply(this.data, getArguments);
  1987. };
  1988. /**
  1989. * Get ids of all items or from a filtered set of items.
  1990. * @param {Object} [options] An Object with options. Available options:
  1991. * {function} [filter] filter items
  1992. * {String | function} [order] Order the items by
  1993. * a field name or custom sort function.
  1994. * @return {Array} ids
  1995. */
  1996. DataView.prototype.getIds = function (options) {
  1997. var ids;
  1998. if (this.data) {
  1999. var defaultFilter = this.options.filter;
  2000. var filter;
  2001. if (options && options.filter) {
  2002. if (defaultFilter) {
  2003. filter = function (item) {
  2004. return defaultFilter(item) && options.filter(item);
  2005. }
  2006. }
  2007. else {
  2008. filter = options.filter;
  2009. }
  2010. }
  2011. else {
  2012. filter = defaultFilter;
  2013. }
  2014. ids = this.data.getIds({
  2015. filter: filter,
  2016. order: options && options.order
  2017. });
  2018. }
  2019. else {
  2020. ids = [];
  2021. }
  2022. return ids;
  2023. };
  2024. /**
  2025. * Event listener. Will propagate all events from the connected data set to
  2026. * the subscribers of the DataView, but will filter the items and only trigger
  2027. * when there are changes in the filtered data set.
  2028. * @param {String} event
  2029. * @param {Object | null} params
  2030. * @param {String} senderId
  2031. * @private
  2032. */
  2033. DataView.prototype._onEvent = function (event, params, senderId) {
  2034. var i, len, id, item,
  2035. ids = params && params.items,
  2036. data = this.data,
  2037. added = [],
  2038. updated = [],
  2039. removed = [];
  2040. if (ids && data) {
  2041. switch (event) {
  2042. case 'add':
  2043. // filter the ids of the added items
  2044. for (i = 0, len = ids.length; i < len; i++) {
  2045. id = ids[i];
  2046. item = this.get(id);
  2047. if (item) {
  2048. this.ids[id] = true;
  2049. added.push(id);
  2050. }
  2051. }
  2052. break;
  2053. case 'update':
  2054. // determine the event from the views viewpoint: an updated
  2055. // item can be added, updated, or removed from this view.
  2056. for (i = 0, len = ids.length; i < len; i++) {
  2057. id = ids[i];
  2058. item = this.get(id);
  2059. if (item) {
  2060. if (this.ids[id]) {
  2061. updated.push(id);
  2062. }
  2063. else {
  2064. this.ids[id] = true;
  2065. added.push(id);
  2066. }
  2067. }
  2068. else {
  2069. if (this.ids[id]) {
  2070. delete this.ids[id];
  2071. removed.push(id);
  2072. }
  2073. else {
  2074. // nothing interesting for me :-(
  2075. }
  2076. }
  2077. }
  2078. break;
  2079. case 'remove':
  2080. // filter the ids of the removed items
  2081. for (i = 0, len = ids.length; i < len; i++) {
  2082. id = ids[i];
  2083. if (this.ids[id]) {
  2084. delete this.ids[id];
  2085. removed.push(id);
  2086. }
  2087. }
  2088. break;
  2089. }
  2090. if (added.length) {
  2091. this._trigger('add', {items: added}, senderId);
  2092. }
  2093. if (updated.length) {
  2094. this._trigger('update', {items: updated}, senderId);
  2095. }
  2096. if (removed.length) {
  2097. this._trigger('remove', {items: removed}, senderId);
  2098. }
  2099. }
  2100. };
  2101. // copy subscription functionality from DataSet
  2102. DataView.prototype.on = DataSet.prototype.on;
  2103. DataView.prototype.off = DataSet.prototype.off;
  2104. DataView.prototype._trigger = DataSet.prototype._trigger;
  2105. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2106. DataView.prototype.subscribe = DataView.prototype.on;
  2107. DataView.prototype.unsubscribe = DataView.prototype.off;
  2108. /**
  2109. * @constructor TimeStep
  2110. * The class TimeStep is an iterator for dates. You provide a start date and an
  2111. * end date. The class itself determines the best scale (step size) based on the
  2112. * provided start Date, end Date, and minimumStep.
  2113. *
  2114. * If minimumStep is provided, the step size is chosen as close as possible
  2115. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2116. * provided, the scale is set to 1 DAY.
  2117. * The minimumStep should correspond with the onscreen size of about 6 characters
  2118. *
  2119. * Alternatively, you can set a scale by hand.
  2120. * After creation, you can initialize the class by executing first(). Then you
  2121. * can iterate from the start date to the end date via next(). You can check if
  2122. * the end date is reached with the function hasNext(). After each step, you can
  2123. * retrieve the current date via getCurrent().
  2124. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2125. * days, to years.
  2126. *
  2127. * Version: 1.2
  2128. *
  2129. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2130. * or new Date(2010, 9, 21, 23, 45, 00)
  2131. * @param {Date} [end] The end date
  2132. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2133. */
  2134. TimeStep = function(start, end, minimumStep) {
  2135. // variables
  2136. this.current = new Date();
  2137. this._start = new Date();
  2138. this._end = new Date();
  2139. this.autoScale = true;
  2140. this.scale = TimeStep.SCALE.DAY;
  2141. this.step = 1;
  2142. // initialize the range
  2143. this.setRange(start, end, minimumStep);
  2144. };
  2145. /// enum scale
  2146. TimeStep.SCALE = {
  2147. MILLISECOND: 1,
  2148. SECOND: 2,
  2149. MINUTE: 3,
  2150. HOUR: 4,
  2151. DAY: 5,
  2152. WEEKDAY: 6,
  2153. MONTH: 7,
  2154. YEAR: 8
  2155. };
  2156. /**
  2157. * Set a new range
  2158. * If minimumStep is provided, the step size is chosen as close as possible
  2159. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2160. * provided, the scale is set to 1 DAY.
  2161. * The minimumStep should correspond with the onscreen size of about 6 characters
  2162. * @param {Date} [start] The start date and time.
  2163. * @param {Date} [end] The end date and time.
  2164. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2165. */
  2166. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2167. if (!(start instanceof Date) || !(end instanceof Date)) {
  2168. throw "No legal start or end date in method setRange";
  2169. }
  2170. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2171. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2172. if (this.autoScale) {
  2173. this.setMinimumStep(minimumStep);
  2174. }
  2175. };
  2176. /**
  2177. * Set the range iterator to the start date.
  2178. */
  2179. TimeStep.prototype.first = function() {
  2180. this.current = new Date(this._start.valueOf());
  2181. this.roundToMinor();
  2182. };
  2183. /**
  2184. * Round the current date to the first minor date value
  2185. * This must be executed once when the current date is set to start Date
  2186. */
  2187. TimeStep.prototype.roundToMinor = function() {
  2188. // round to floor
  2189. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2190. //noinspection FallthroughInSwitchStatementJS
  2191. switch (this.scale) {
  2192. case TimeStep.SCALE.YEAR:
  2193. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2194. this.current.setMonth(0);
  2195. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2196. case TimeStep.SCALE.DAY: // intentional fall through
  2197. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2198. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2199. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2200. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2201. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2202. }
  2203. if (this.step != 1) {
  2204. // round down to the first minor value that is a multiple of the current step size
  2205. switch (this.scale) {
  2206. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2207. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2208. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2209. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2210. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2211. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2212. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2213. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2214. default: break;
  2215. }
  2216. }
  2217. };
  2218. /**
  2219. * Check if the there is a next step
  2220. * @return {boolean} true if the current date has not passed the end date
  2221. */
  2222. TimeStep.prototype.hasNext = function () {
  2223. return (this.current.valueOf() <= this._end.valueOf());
  2224. };
  2225. /**
  2226. * Do the next step
  2227. */
  2228. TimeStep.prototype.next = function() {
  2229. var prev = this.current.valueOf();
  2230. // Two cases, needed to prevent issues with switching daylight savings
  2231. // (end of March and end of October)
  2232. if (this.current.getMonth() < 6) {
  2233. switch (this.scale) {
  2234. case TimeStep.SCALE.MILLISECOND:
  2235. this.current = new Date(this.current.valueOf() + this.step); break;
  2236. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2237. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2238. case TimeStep.SCALE.HOUR:
  2239. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2240. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2241. var h = this.current.getHours();
  2242. this.current.setHours(h - (h % this.step));
  2243. break;
  2244. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2245. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2246. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2247. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2248. default: break;
  2249. }
  2250. }
  2251. else {
  2252. switch (this.scale) {
  2253. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2254. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2255. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2256. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2257. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2258. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2259. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2260. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2261. default: break;
  2262. }
  2263. }
  2264. if (this.step != 1) {
  2265. // round down to the correct major value
  2266. switch (this.scale) {
  2267. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2268. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2269. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2270. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2271. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2272. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2273. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2274. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2275. default: break;
  2276. }
  2277. }
  2278. // safety mechanism: if current time is still unchanged, move to the end
  2279. if (this.current.valueOf() == prev) {
  2280. this.current = new Date(this._end.valueOf());
  2281. }
  2282. };
  2283. /**
  2284. * Get the current datetime
  2285. * @return {Date} current The current date
  2286. */
  2287. TimeStep.prototype.getCurrent = function() {
  2288. return this.current;
  2289. };
  2290. /**
  2291. * Set a custom scale. Autoscaling will be disabled.
  2292. * For example setScale(SCALE.MINUTES, 5) will result
  2293. * in minor steps of 5 minutes, and major steps of an hour.
  2294. *
  2295. * @param {TimeStep.SCALE} newScale
  2296. * A scale. Choose from SCALE.MILLISECOND,
  2297. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2298. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2299. * SCALE.YEAR.
  2300. * @param {Number} newStep A step size, by default 1. Choose for
  2301. * example 1, 2, 5, or 10.
  2302. */
  2303. TimeStep.prototype.setScale = function(newScale, newStep) {
  2304. this.scale = newScale;
  2305. if (newStep > 0) {
  2306. this.step = newStep;
  2307. }
  2308. this.autoScale = false;
  2309. };
  2310. /**
  2311. * Enable or disable autoscaling
  2312. * @param {boolean} enable If true, autoascaling is set true
  2313. */
  2314. TimeStep.prototype.setAutoScale = function (enable) {
  2315. this.autoScale = enable;
  2316. };
  2317. /**
  2318. * Automatically determine the scale that bests fits the provided minimum step
  2319. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2320. */
  2321. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2322. if (minimumStep == undefined) {
  2323. return;
  2324. }
  2325. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2326. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2327. var stepDay = (1000 * 60 * 60 * 24);
  2328. var stepHour = (1000 * 60 * 60);
  2329. var stepMinute = (1000 * 60);
  2330. var stepSecond = (1000);
  2331. var stepMillisecond= (1);
  2332. // find the smallest step that is larger than the provided minimumStep
  2333. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2334. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2335. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2336. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2337. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2338. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2339. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2340. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2341. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2342. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2343. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2344. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2345. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2346. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2347. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2348. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2349. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2350. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2351. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2352. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2353. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2354. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2355. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2356. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2357. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2358. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2359. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2360. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2361. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2362. };
  2363. /**
  2364. * Snap a date to a rounded value.
  2365. * The snap intervals are dependent on the current scale and step.
  2366. * @param {Date} date the date to be snapped.
  2367. * @return {Date} snappedDate
  2368. */
  2369. TimeStep.prototype.snap = function(date) {
  2370. var clone = new Date(date.valueOf());
  2371. if (this.scale == TimeStep.SCALE.YEAR) {
  2372. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2373. clone.setFullYear(Math.round(year / this.step) * this.step);
  2374. clone.setMonth(0);
  2375. clone.setDate(0);
  2376. clone.setHours(0);
  2377. clone.setMinutes(0);
  2378. clone.setSeconds(0);
  2379. clone.setMilliseconds(0);
  2380. }
  2381. else if (this.scale == TimeStep.SCALE.MONTH) {
  2382. if (clone.getDate() > 15) {
  2383. clone.setDate(1);
  2384. clone.setMonth(clone.getMonth() + 1);
  2385. // important: first set Date to 1, after that change the month.
  2386. }
  2387. else {
  2388. clone.setDate(1);
  2389. }
  2390. clone.setHours(0);
  2391. clone.setMinutes(0);
  2392. clone.setSeconds(0);
  2393. clone.setMilliseconds(0);
  2394. }
  2395. else if (this.scale == TimeStep.SCALE.DAY ||
  2396. this.scale == TimeStep.SCALE.WEEKDAY) {
  2397. //noinspection FallthroughInSwitchStatementJS
  2398. switch (this.step) {
  2399. case 5:
  2400. case 2:
  2401. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2402. default:
  2403. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2404. }
  2405. clone.setMinutes(0);
  2406. clone.setSeconds(0);
  2407. clone.setMilliseconds(0);
  2408. }
  2409. else if (this.scale == TimeStep.SCALE.HOUR) {
  2410. switch (this.step) {
  2411. case 4:
  2412. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2413. default:
  2414. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2415. }
  2416. clone.setSeconds(0);
  2417. clone.setMilliseconds(0);
  2418. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2419. //noinspection FallthroughInSwitchStatementJS
  2420. switch (this.step) {
  2421. case 15:
  2422. case 10:
  2423. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2424. clone.setSeconds(0);
  2425. break;
  2426. case 5:
  2427. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2428. default:
  2429. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2430. }
  2431. clone.setMilliseconds(0);
  2432. }
  2433. else if (this.scale == TimeStep.SCALE.SECOND) {
  2434. //noinspection FallthroughInSwitchStatementJS
  2435. switch (this.step) {
  2436. case 15:
  2437. case 10:
  2438. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2439. clone.setMilliseconds(0);
  2440. break;
  2441. case 5:
  2442. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2443. default:
  2444. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2445. }
  2446. }
  2447. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2448. var step = this.step > 5 ? this.step / 2 : 1;
  2449. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2450. }
  2451. return clone;
  2452. };
  2453. /**
  2454. * Check if the current value is a major value (for example when the step
  2455. * is DAY, a major value is each first day of the MONTH)
  2456. * @return {boolean} true if current date is major, else false.
  2457. */
  2458. TimeStep.prototype.isMajor = function() {
  2459. switch (this.scale) {
  2460. case TimeStep.SCALE.MILLISECOND:
  2461. return (this.current.getMilliseconds() == 0);
  2462. case TimeStep.SCALE.SECOND:
  2463. return (this.current.getSeconds() == 0);
  2464. case TimeStep.SCALE.MINUTE:
  2465. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2466. // Note: this is no bug. Major label is equal for both minute and hour scale
  2467. case TimeStep.SCALE.HOUR:
  2468. return (this.current.getHours() == 0);
  2469. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2470. case TimeStep.SCALE.DAY:
  2471. return (this.current.getDate() == 1);
  2472. case TimeStep.SCALE.MONTH:
  2473. return (this.current.getMonth() == 0);
  2474. case TimeStep.SCALE.YEAR:
  2475. return false;
  2476. default:
  2477. return false;
  2478. }
  2479. };
  2480. /**
  2481. * Returns formatted text for the minor axislabel, depending on the current
  2482. * date and the scale. For example when scale is MINUTE, the current time is
  2483. * formatted as "hh:mm".
  2484. * @param {Date} [date] custom date. if not provided, current date is taken
  2485. */
  2486. TimeStep.prototype.getLabelMinor = function(date) {
  2487. if (date == undefined) {
  2488. date = this.current;
  2489. }
  2490. switch (this.scale) {
  2491. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2492. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2493. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2494. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2495. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2496. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2497. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2498. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2499. default: return '';
  2500. }
  2501. };
  2502. /**
  2503. * Returns formatted text for the major axis label, depending on the current
  2504. * date and the scale. For example when scale is MINUTE, the major scale is
  2505. * hours, and the hour will be formatted as "hh".
  2506. * @param {Date} [date] custom date. if not provided, current date is taken
  2507. */
  2508. TimeStep.prototype.getLabelMajor = function(date) {
  2509. if (date == undefined) {
  2510. date = this.current;
  2511. }
  2512. //noinspection FallthroughInSwitchStatementJS
  2513. switch (this.scale) {
  2514. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2515. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2516. case TimeStep.SCALE.MINUTE:
  2517. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2518. case TimeStep.SCALE.WEEKDAY:
  2519. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2520. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2521. case TimeStep.SCALE.YEAR: return '';
  2522. default: return '';
  2523. }
  2524. };
  2525. /**
  2526. * @constructor Stack
  2527. * Stacks items on top of each other.
  2528. * @param {ItemSet} itemset
  2529. * @param {Object} [options]
  2530. */
  2531. function Stack (itemset, options) {
  2532. this.itemset = itemset;
  2533. this.options = options || {};
  2534. this.defaultOptions = {
  2535. order: function (a, b) {
  2536. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  2537. // Order: ranges over non-ranges, ranged ordered by width, and
  2538. // lastly ordered by start.
  2539. if (a instanceof ItemRange) {
  2540. if (b instanceof ItemRange) {
  2541. var aInt = (a.data.end - a.data.start);
  2542. var bInt = (b.data.end - b.data.start);
  2543. return (aInt - bInt) || (a.data.start - b.data.start);
  2544. }
  2545. else {
  2546. return -1;
  2547. }
  2548. }
  2549. else {
  2550. if (b instanceof ItemRange) {
  2551. return 1;
  2552. }
  2553. else {
  2554. return (a.data.start - b.data.start);
  2555. }
  2556. }
  2557. },
  2558. margin: {
  2559. item: 10
  2560. }
  2561. };
  2562. this.ordered = []; // ordered items
  2563. }
  2564. /**
  2565. * Set options for the stack
  2566. * @param {Object} options Available options:
  2567. * {ItemSet} itemset
  2568. * {Number} margin
  2569. * {function} order Stacking order
  2570. */
  2571. Stack.prototype.setOptions = function setOptions (options) {
  2572. util.extend(this.options, options);
  2573. // TODO: register on data changes at the connected itemset, and update the changed part only and immediately
  2574. };
  2575. /**
  2576. * Stack the items such that they don't overlap. The items will have a minimal
  2577. * distance equal to options.margin.item.
  2578. */
  2579. Stack.prototype.update = function update() {
  2580. this._order();
  2581. this._stack();
  2582. };
  2583. /**
  2584. * Order the items. If a custom order function has been provided via the options,
  2585. * then this will be used.
  2586. * @private
  2587. */
  2588. Stack.prototype._order = function _order () {
  2589. var items = this.itemset.items;
  2590. if (!items) {
  2591. throw new Error('Cannot stack items: ItemSet does not contain items');
  2592. }
  2593. // TODO: store the sorted items, to have less work later on
  2594. var ordered = [];
  2595. var index = 0;
  2596. // items is a map (no array)
  2597. util.forEach(items, function (item) {
  2598. if (item.visible) {
  2599. ordered[index] = item;
  2600. index++;
  2601. }
  2602. });
  2603. //if a customer stack order function exists, use it.
  2604. var order = this.options.order || this.defaultOptions.order;
  2605. if (!(typeof order === 'function')) {
  2606. throw new Error('Option order must be a function');
  2607. }
  2608. ordered.sort(order);
  2609. this.ordered = ordered;
  2610. };
  2611. /**
  2612. * Adjust vertical positions of the events such that they don't overlap each
  2613. * other.
  2614. * @private
  2615. */
  2616. Stack.prototype._stack = function _stack () {
  2617. var i,
  2618. iMax,
  2619. ordered = this.ordered,
  2620. options = this.options,
  2621. orientation = options.orientation || this.defaultOptions.orientation,
  2622. axisOnTop = (orientation == 'top'),
  2623. margin;
  2624. if (options.margin && options.margin.item !== undefined) {
  2625. margin = options.margin.item;
  2626. }
  2627. else {
  2628. margin = this.defaultOptions.margin.item
  2629. }
  2630. // calculate new, non-overlapping positions
  2631. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  2632. var item = ordered[i];
  2633. var collidingItem = null;
  2634. do {
  2635. // TODO: optimize checking for overlap. when there is a gap without items,
  2636. // you only need to check for items from the next item on, not from zero
  2637. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  2638. if (collidingItem != null) {
  2639. // There is a collision. Reposition the event above the colliding element
  2640. if (axisOnTop) {
  2641. item.top = collidingItem.top + collidingItem.height + margin;
  2642. }
  2643. else {
  2644. item.top = collidingItem.top - item.height - margin;
  2645. }
  2646. }
  2647. } while (collidingItem);
  2648. }
  2649. };
  2650. /**
  2651. * Check if the destiny position of given item overlaps with any
  2652. * of the other items from index itemStart to itemEnd.
  2653. * @param {Array} items Array with items
  2654. * @param {int} itemIndex Number of the item to be checked for overlap
  2655. * @param {int} itemStart First item to be checked.
  2656. * @param {int} itemEnd Last item to be checked.
  2657. * @return {Object | null} colliding item, or undefined when no collisions
  2658. * @param {Number} margin A minimum required margin.
  2659. * If margin is provided, the two items will be
  2660. * marked colliding when they overlap or
  2661. * when the margin between the two is smaller than
  2662. * the requested margin.
  2663. */
  2664. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  2665. itemStart, itemEnd, margin) {
  2666. var collision = this.collision;
  2667. // we loop from end to start, as we suppose that the chance of a
  2668. // collision is larger for items at the end, so check these first.
  2669. var a = items[itemIndex];
  2670. for (var i = itemEnd; i >= itemStart; i--) {
  2671. var b = items[i];
  2672. if (collision(a, b, margin)) {
  2673. if (i != itemIndex) {
  2674. return b;
  2675. }
  2676. }
  2677. }
  2678. return null;
  2679. };
  2680. /**
  2681. * Test if the two provided items collide
  2682. * The items must have parameters left, width, top, and height.
  2683. * @param {Component} a The first item
  2684. * @param {Component} b The second item
  2685. * @param {Number} margin A minimum required margin.
  2686. * If margin is provided, the two items will be
  2687. * marked colliding when they overlap or
  2688. * when the margin between the two is smaller than
  2689. * the requested margin.
  2690. * @return {boolean} true if a and b collide, else false
  2691. */
  2692. Stack.prototype.collision = function collision (a, b, margin) {
  2693. return ((a.left - margin) < (b.left + b.width) &&
  2694. (a.left + a.width + margin) > b.left &&
  2695. (a.top - margin) < (b.top + b.height) &&
  2696. (a.top + a.height + margin) > b.top);
  2697. };
  2698. /**
  2699. * @constructor Range
  2700. * A Range controls a numeric range with a start and end value.
  2701. * The Range adjusts the range based on mouse events or programmatic changes,
  2702. * and triggers events when the range is changing or has been changed.
  2703. * @param {Object} [options] See description at Range.setOptions
  2704. * @extends Controller
  2705. */
  2706. function Range(options) {
  2707. this.id = util.randomUUID();
  2708. this.start = null; // Number
  2709. this.end = null; // Number
  2710. this.options = options || {};
  2711. this.setOptions(options);
  2712. }
  2713. // extend the Range prototype with an event emitter mixin
  2714. Emitter(Range.prototype);
  2715. /**
  2716. * Set options for the range controller
  2717. * @param {Object} options Available options:
  2718. * {Number} min Minimum value for start
  2719. * {Number} max Maximum value for end
  2720. * {Number} zoomMin Set a minimum value for
  2721. * (end - start).
  2722. * {Number} zoomMax Set a maximum value for
  2723. * (end - start).
  2724. */
  2725. Range.prototype.setOptions = function (options) {
  2726. util.extend(this.options, options);
  2727. // re-apply range with new limitations
  2728. if (this.start !== null && this.end !== null) {
  2729. this.setRange(this.start, this.end);
  2730. }
  2731. };
  2732. /**
  2733. * Test whether direction has a valid value
  2734. * @param {String} direction 'horizontal' or 'vertical'
  2735. */
  2736. function validateDirection (direction) {
  2737. if (direction != 'horizontal' && direction != 'vertical') {
  2738. throw new TypeError('Unknown direction "' + direction + '". ' +
  2739. 'Choose "horizontal" or "vertical".');
  2740. }
  2741. }
  2742. /**
  2743. * Add listeners for mouse and touch events to the component
  2744. * @param {Controller} controller
  2745. * @param {Component} component Should be a rootpanel
  2746. * @param {String} event Available events: 'move', 'zoom'
  2747. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2748. */
  2749. Range.prototype.subscribe = function (controller, component, event, direction) {
  2750. var me = this;
  2751. if (event == 'move') {
  2752. // drag start listener
  2753. controller.on('dragstart', function (event) {
  2754. me._onDragStart(event, component);
  2755. });
  2756. // drag listener
  2757. controller.on('drag', function (event) {
  2758. me._onDrag(event, component, direction);
  2759. });
  2760. // drag end listener
  2761. controller.on('dragend', function (event) {
  2762. me._onDragEnd(event, component);
  2763. });
  2764. // ignore dragging when holding
  2765. controller.on('hold', function (event) {
  2766. me._onHold();
  2767. });
  2768. }
  2769. else if (event == 'zoom') {
  2770. // mouse wheel
  2771. function mousewheel (event) {
  2772. me._onMouseWheel(event, component, direction);
  2773. }
  2774. controller.on('mousewheel', mousewheel);
  2775. controller.on('DOMMouseScroll', mousewheel); // For FF
  2776. // pinch
  2777. controller.on('touch', function (event) {
  2778. me._onTouch(event);
  2779. });
  2780. controller.on('pinch', function (event) {
  2781. me._onPinch(event, component, direction);
  2782. });
  2783. }
  2784. else {
  2785. throw new TypeError('Unknown event "' + event + '". ' +
  2786. 'Choose "move" or "zoom".');
  2787. }
  2788. };
  2789. /**
  2790. * Set a new start and end range
  2791. * @param {Number} [start]
  2792. * @param {Number} [end]
  2793. */
  2794. Range.prototype.setRange = function(start, end) {
  2795. var changed = this._applyRange(start, end);
  2796. if (changed) {
  2797. var params = {
  2798. start: this.start,
  2799. end: this.end
  2800. };
  2801. this.emit('rangechange', params);
  2802. this.emit('rangechanged', params);
  2803. }
  2804. };
  2805. /**
  2806. * Set a new start and end range. This method is the same as setRange, but
  2807. * does not trigger a range change and range changed event, and it returns
  2808. * true when the range is changed
  2809. * @param {Number} [start]
  2810. * @param {Number} [end]
  2811. * @return {Boolean} changed
  2812. * @private
  2813. */
  2814. Range.prototype._applyRange = function(start, end) {
  2815. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2816. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2817. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2818. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2819. diff;
  2820. // check for valid number
  2821. if (isNaN(newStart) || newStart === null) {
  2822. throw new Error('Invalid start "' + start + '"');
  2823. }
  2824. if (isNaN(newEnd) || newEnd === null) {
  2825. throw new Error('Invalid end "' + end + '"');
  2826. }
  2827. // prevent start < end
  2828. if (newEnd < newStart) {
  2829. newEnd = newStart;
  2830. }
  2831. // prevent start < min
  2832. if (min !== null) {
  2833. if (newStart < min) {
  2834. diff = (min - newStart);
  2835. newStart += diff;
  2836. newEnd += diff;
  2837. // prevent end > max
  2838. if (max != null) {
  2839. if (newEnd > max) {
  2840. newEnd = max;
  2841. }
  2842. }
  2843. }
  2844. }
  2845. // prevent end > max
  2846. if (max !== null) {
  2847. if (newEnd > max) {
  2848. diff = (newEnd - max);
  2849. newStart -= diff;
  2850. newEnd -= diff;
  2851. // prevent start < min
  2852. if (min != null) {
  2853. if (newStart < min) {
  2854. newStart = min;
  2855. }
  2856. }
  2857. }
  2858. }
  2859. // prevent (end-start) < zoomMin
  2860. if (this.options.zoomMin !== null) {
  2861. var zoomMin = parseFloat(this.options.zoomMin);
  2862. if (zoomMin < 0) {
  2863. zoomMin = 0;
  2864. }
  2865. if ((newEnd - newStart) < zoomMin) {
  2866. if ((this.end - this.start) === zoomMin) {
  2867. // ignore this action, we are already zoomed to the minimum
  2868. newStart = this.start;
  2869. newEnd = this.end;
  2870. }
  2871. else {
  2872. // zoom to the minimum
  2873. diff = (zoomMin - (newEnd - newStart));
  2874. newStart -= diff / 2;
  2875. newEnd += diff / 2;
  2876. }
  2877. }
  2878. }
  2879. // prevent (end-start) > zoomMax
  2880. if (this.options.zoomMax !== null) {
  2881. var zoomMax = parseFloat(this.options.zoomMax);
  2882. if (zoomMax < 0) {
  2883. zoomMax = 0;
  2884. }
  2885. if ((newEnd - newStart) > zoomMax) {
  2886. if ((this.end - this.start) === zoomMax) {
  2887. // ignore this action, we are already zoomed to the maximum
  2888. newStart = this.start;
  2889. newEnd = this.end;
  2890. }
  2891. else {
  2892. // zoom to the maximum
  2893. diff = ((newEnd - newStart) - zoomMax);
  2894. newStart += diff / 2;
  2895. newEnd -= diff / 2;
  2896. }
  2897. }
  2898. }
  2899. var changed = (this.start != newStart || this.end != newEnd);
  2900. this.start = newStart;
  2901. this.end = newEnd;
  2902. return changed;
  2903. };
  2904. /**
  2905. * Retrieve the current range.
  2906. * @return {Object} An object with start and end properties
  2907. */
  2908. Range.prototype.getRange = function() {
  2909. return {
  2910. start: this.start,
  2911. end: this.end
  2912. };
  2913. };
  2914. /**
  2915. * Calculate the conversion offset and scale for current range, based on
  2916. * the provided width
  2917. * @param {Number} width
  2918. * @returns {{offset: number, scale: number}} conversion
  2919. */
  2920. Range.prototype.conversion = function (width) {
  2921. return Range.conversion(this.start, this.end, width);
  2922. };
  2923. /**
  2924. * Static method to calculate the conversion offset and scale for a range,
  2925. * based on the provided start, end, and width
  2926. * @param {Number} start
  2927. * @param {Number} end
  2928. * @param {Number} width
  2929. * @returns {{offset: number, scale: number}} conversion
  2930. */
  2931. Range.conversion = function (start, end, width) {
  2932. if (width != 0 && (end - start != 0)) {
  2933. return {
  2934. offset: start,
  2935. scale: width / (end - start)
  2936. }
  2937. }
  2938. else {
  2939. return {
  2940. offset: 0,
  2941. scale: 1
  2942. };
  2943. }
  2944. };
  2945. // global (private) object to store drag params
  2946. var touchParams = {};
  2947. /**
  2948. * Start dragging horizontally or vertically
  2949. * @param {Event} event
  2950. * @param {Object} component
  2951. * @private
  2952. */
  2953. Range.prototype._onDragStart = function(event, component) {
  2954. // refuse to drag when we where pinching to prevent the timeline make a jump
  2955. // when releasing the fingers in opposite order from the touch screen
  2956. if (touchParams.ignore) return;
  2957. // TODO: reckon with option movable
  2958. touchParams.start = this.start;
  2959. touchParams.end = this.end;
  2960. var frame = component.frame;
  2961. if (frame) {
  2962. frame.style.cursor = 'move';
  2963. }
  2964. };
  2965. /**
  2966. * Perform dragging operating.
  2967. * @param {Event} event
  2968. * @param {Component} component
  2969. * @param {String} direction 'horizontal' or 'vertical'
  2970. * @private
  2971. */
  2972. Range.prototype._onDrag = function (event, component, direction) {
  2973. validateDirection(direction);
  2974. // TODO: reckon with option movable
  2975. // refuse to drag when we where pinching to prevent the timeline make a jump
  2976. // when releasing the fingers in opposite order from the touch screen
  2977. if (touchParams.ignore) return;
  2978. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  2979. interval = (touchParams.end - touchParams.start),
  2980. width = (direction == 'horizontal') ? component.width : component.height,
  2981. diffRange = -delta / width * interval;
  2982. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  2983. this.emit('rangechange', {
  2984. start: this.start,
  2985. end: this.end
  2986. });
  2987. };
  2988. /**
  2989. * Stop dragging operating.
  2990. * @param {event} event
  2991. * @param {Component} component
  2992. * @private
  2993. */
  2994. Range.prototype._onDragEnd = function (event, component) {
  2995. // refuse to drag when we where pinching to prevent the timeline make a jump
  2996. // when releasing the fingers in opposite order from the touch screen
  2997. if (touchParams.ignore) return;
  2998. // TODO: reckon with option movable
  2999. if (component.frame) {
  3000. component.frame.style.cursor = 'auto';
  3001. }
  3002. // fire a rangechanged event
  3003. this.emit('rangechanged', {
  3004. start: this.start,
  3005. end: this.end
  3006. });
  3007. };
  3008. /**
  3009. * Event handler for mouse wheel event, used to zoom
  3010. * Code from http://adomas.org/javascript-mouse-wheel/
  3011. * @param {Event} event
  3012. * @param {Component} component
  3013. * @param {String} direction 'horizontal' or 'vertical'
  3014. * @private
  3015. */
  3016. Range.prototype._onMouseWheel = function(event, component, direction) {
  3017. validateDirection(direction);
  3018. // TODO: reckon with option zoomable
  3019. // retrieve delta
  3020. var delta = 0;
  3021. if (event.wheelDelta) { /* IE/Opera. */
  3022. delta = event.wheelDelta / 120;
  3023. } else if (event.detail) { /* Mozilla case. */
  3024. // In Mozilla, sign of delta is different than in IE.
  3025. // Also, delta is multiple of 3.
  3026. delta = -event.detail / 3;
  3027. }
  3028. // If delta is nonzero, handle it.
  3029. // Basically, delta is now positive if wheel was scrolled up,
  3030. // and negative, if wheel was scrolled down.
  3031. if (delta) {
  3032. // perform the zoom action. Delta is normally 1 or -1
  3033. // adjust a negative delta such that zooming in with delta 0.1
  3034. // equals zooming out with a delta -0.1
  3035. var scale;
  3036. if (delta < 0) {
  3037. scale = 1 - (delta / 5);
  3038. }
  3039. else {
  3040. scale = 1 / (1 + (delta / 5)) ;
  3041. }
  3042. // calculate center, the date to zoom around
  3043. var gesture = util.fakeGesture(this, event),
  3044. pointer = getPointer(gesture.center, component.frame),
  3045. pointerDate = this._pointerToDate(component, direction, pointer);
  3046. this.zoom(scale, pointerDate);
  3047. }
  3048. // Prevent default actions caused by mouse wheel
  3049. // (else the page and timeline both zoom and scroll)
  3050. event.preventDefault();
  3051. };
  3052. /**
  3053. * Start of a touch gesture
  3054. * @private
  3055. */
  3056. Range.prototype._onTouch = function (event) {
  3057. touchParams.start = this.start;
  3058. touchParams.end = this.end;
  3059. touchParams.ignore = false;
  3060. touchParams.center = null;
  3061. // don't move the range when dragging a selected event
  3062. // TODO: it's not so neat to have to know about the state of the ItemSet
  3063. var item = ItemSet.itemFromTarget(event);
  3064. if (item && item.selected && this.options.editable) {
  3065. touchParams.ignore = true;
  3066. }
  3067. };
  3068. /**
  3069. * On start of a hold gesture
  3070. * @private
  3071. */
  3072. Range.prototype._onHold = function () {
  3073. touchParams.ignore = true;
  3074. };
  3075. /**
  3076. * Handle pinch event
  3077. * @param {Event} event
  3078. * @param {Component} component
  3079. * @param {String} direction 'horizontal' or 'vertical'
  3080. * @private
  3081. */
  3082. Range.prototype._onPinch = function (event, component, direction) {
  3083. touchParams.ignore = true;
  3084. // TODO: reckon with option zoomable
  3085. if (event.gesture.touches.length > 1) {
  3086. if (!touchParams.center) {
  3087. touchParams.center = getPointer(event.gesture.center, component.frame);
  3088. }
  3089. var scale = 1 / event.gesture.scale,
  3090. initDate = this._pointerToDate(component, direction, touchParams.center),
  3091. center = getPointer(event.gesture.center, component.frame),
  3092. date = this._pointerToDate(component, direction, center),
  3093. delta = date - initDate; // TODO: utilize delta
  3094. // calculate new start and end
  3095. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3096. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3097. // apply new range
  3098. this.setRange(newStart, newEnd);
  3099. }
  3100. };
  3101. /**
  3102. * Helper function to calculate the center date for zooming
  3103. * @param {Component} component
  3104. * @param {{x: Number, y: Number}} pointer
  3105. * @param {String} direction 'horizontal' or 'vertical'
  3106. * @return {number} date
  3107. * @private
  3108. */
  3109. Range.prototype._pointerToDate = function (component, direction, pointer) {
  3110. var conversion;
  3111. if (direction == 'horizontal') {
  3112. var width = component.width;
  3113. conversion = this.conversion(width);
  3114. return pointer.x / conversion.scale + conversion.offset;
  3115. }
  3116. else {
  3117. var height = component.height;
  3118. conversion = this.conversion(height);
  3119. return pointer.y / conversion.scale + conversion.offset;
  3120. }
  3121. };
  3122. /**
  3123. * Get the pointer location relative to the location of the dom element
  3124. * @param {{pageX: Number, pageY: Number}} touch
  3125. * @param {Element} element HTML DOM element
  3126. * @return {{x: Number, y: Number}} pointer
  3127. * @private
  3128. */
  3129. function getPointer (touch, element) {
  3130. return {
  3131. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3132. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3133. };
  3134. }
  3135. /**
  3136. * Zoom the range the given scale in or out. Start and end date will
  3137. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3138. * date around which to zoom.
  3139. * For example, try scale = 0.9 or 1.1
  3140. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3141. * values below 1 will zoom in.
  3142. * @param {Number} [center] Value representing a date around which will
  3143. * be zoomed.
  3144. */
  3145. Range.prototype.zoom = function(scale, center) {
  3146. // if centerDate is not provided, take it half between start Date and end Date
  3147. if (center == null) {
  3148. center = (this.start + this.end) / 2;
  3149. }
  3150. // calculate new start and end
  3151. var newStart = center + (this.start - center) * scale;
  3152. var newEnd = center + (this.end - center) * scale;
  3153. this.setRange(newStart, newEnd);
  3154. };
  3155. /**
  3156. * Move the range with a given delta to the left or right. Start and end
  3157. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3158. * @param {Number} delta Moving amount. Positive value will move right,
  3159. * negative value will move left
  3160. */
  3161. Range.prototype.move = function(delta) {
  3162. // zoom start Date and end Date relative to the centerDate
  3163. var diff = (this.end - this.start);
  3164. // apply new values
  3165. var newStart = this.start + diff * delta;
  3166. var newEnd = this.end + diff * delta;
  3167. // TODO: reckon with min and max range
  3168. this.start = newStart;
  3169. this.end = newEnd;
  3170. };
  3171. /**
  3172. * Move the range to a new center point
  3173. * @param {Number} moveTo New center point of the range
  3174. */
  3175. Range.prototype.moveTo = function(moveTo) {
  3176. var center = (this.start + this.end) / 2;
  3177. var diff = center - moveTo;
  3178. // calculate new start and end
  3179. var newStart = this.start - diff;
  3180. var newEnd = this.end - diff;
  3181. this.setRange(newStart, newEnd);
  3182. };
  3183. /**
  3184. * @constructor Controller
  3185. *
  3186. * A Controller controls the reflows and repaints of all components,
  3187. * and is used as an event bus for all components.
  3188. */
  3189. function Controller () {
  3190. var me = this;
  3191. this.id = util.randomUUID();
  3192. this.components = {};
  3193. /**
  3194. * Listen for a 'request-reflow' event. The controller will schedule a reflow
  3195. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3196. * is false.
  3197. */
  3198. var reflowTimer = null;
  3199. this.on('request-reflow', function requestReflow(force) {
  3200. if (force) {
  3201. me.reflow();
  3202. }
  3203. else {
  3204. if (!reflowTimer) {
  3205. reflowTimer = setTimeout(function () {
  3206. reflowTimer = null;
  3207. me.reflow();
  3208. }, 0);
  3209. }
  3210. }
  3211. });
  3212. /**
  3213. * Request a repaint. The controller will schedule a repaint
  3214. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3215. * is false.
  3216. */
  3217. var repaintTimer = null;
  3218. this.on('request-repaint', function requestRepaint(force) {
  3219. if (force) {
  3220. me.repaint();
  3221. }
  3222. else {
  3223. if (!repaintTimer) {
  3224. repaintTimer = setTimeout(function () {
  3225. repaintTimer = null;
  3226. me.repaint();
  3227. }, 0);
  3228. }
  3229. }
  3230. });
  3231. }
  3232. // Extend controller with Emitter mixin
  3233. Emitter(Controller.prototype);
  3234. /**
  3235. * Add a component to the controller
  3236. * @param {Component} component
  3237. */
  3238. Controller.prototype.add = function add(component) {
  3239. // validate the component
  3240. if (component.id == undefined) {
  3241. throw new Error('Component has no field id');
  3242. }
  3243. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3244. throw new TypeError('Component must be an instance of ' +
  3245. 'prototype Component or Controller');
  3246. }
  3247. // add the component
  3248. component.setController(this);
  3249. this.components[component.id] = component;
  3250. };
  3251. /**
  3252. * Remove a component from the controller
  3253. * @param {Component | String} component
  3254. */
  3255. Controller.prototype.remove = function remove(component) {
  3256. var id;
  3257. for (id in this.components) {
  3258. if (this.components.hasOwnProperty(id)) {
  3259. if (id == component || this.components[id] === component) {
  3260. break;
  3261. }
  3262. }
  3263. }
  3264. if (id) {
  3265. // unregister the controller (gives the component the ability to unregister
  3266. // event listeners and clean up other stuff)
  3267. this.components[id].setController(null);
  3268. delete this.components[id];
  3269. }
  3270. };
  3271. /**
  3272. * Repaint all components
  3273. */
  3274. Controller.prototype.repaint = function repaint() {
  3275. var changed = false;
  3276. // cancel any running repaint request
  3277. if (this.repaintTimer) {
  3278. clearTimeout(this.repaintTimer);
  3279. this.repaintTimer = undefined;
  3280. }
  3281. var done = {};
  3282. function repaint(component, id) {
  3283. if (!(id in done)) {
  3284. // first repaint the components on which this component is dependent
  3285. if (component.depends) {
  3286. component.depends.forEach(function (dep) {
  3287. repaint(dep, dep.id);
  3288. });
  3289. }
  3290. if (component.parent) {
  3291. repaint(component.parent, component.parent.id);
  3292. }
  3293. // repaint the component itself and mark as done
  3294. changed = component.repaint() || changed;
  3295. done[id] = true;
  3296. }
  3297. }
  3298. util.forEach(this.components, repaint);
  3299. this.emit('repaint');
  3300. // immediately reflow when needed
  3301. if (changed) {
  3302. this.reflow();
  3303. }
  3304. // TODO: limit the number of nested reflows/repaints, prevent loop
  3305. };
  3306. /**
  3307. * Reflow all components
  3308. */
  3309. Controller.prototype.reflow = function reflow() {
  3310. var resized = false;
  3311. // cancel any running repaint request
  3312. if (this.reflowTimer) {
  3313. clearTimeout(this.reflowTimer);
  3314. this.reflowTimer = undefined;
  3315. }
  3316. var done = {};
  3317. function reflow(component, id) {
  3318. if (!(id in done)) {
  3319. // first reflow the components on which this component is dependent
  3320. if (component.depends) {
  3321. component.depends.forEach(function (dep) {
  3322. reflow(dep, dep.id);
  3323. });
  3324. }
  3325. if (component.parent) {
  3326. reflow(component.parent, component.parent.id);
  3327. }
  3328. // reflow the component itself and mark as done
  3329. resized = component.reflow() || resized;
  3330. done[id] = true;
  3331. }
  3332. }
  3333. util.forEach(this.components, reflow);
  3334. this.emit('reflow');
  3335. // immediately repaint when needed
  3336. if (resized) {
  3337. this.repaint();
  3338. }
  3339. // TODO: limit the number of nested reflows/repaints, prevent loop
  3340. };
  3341. /**
  3342. * Prototype for visual components
  3343. */
  3344. function Component () {
  3345. this.id = null;
  3346. this.parent = null;
  3347. this.depends = null;
  3348. this.controller = null;
  3349. this.options = null;
  3350. this.frame = null; // main DOM element
  3351. this.top = 0;
  3352. this.left = 0;
  3353. this.width = 0;
  3354. this.height = 0;
  3355. }
  3356. /**
  3357. * Set parameters for the frame. Parameters will be merged in current parameter
  3358. * set.
  3359. * @param {Object} options Available parameters:
  3360. * {String | function} [className]
  3361. * {String | Number | function} [left]
  3362. * {String | Number | function} [top]
  3363. * {String | Number | function} [width]
  3364. * {String | Number | function} [height]
  3365. */
  3366. Component.prototype.setOptions = function setOptions(options) {
  3367. if (options) {
  3368. util.extend(this.options, options);
  3369. if (this.controller) {
  3370. this.requestRepaint();
  3371. this.requestReflow();
  3372. }
  3373. }
  3374. };
  3375. /**
  3376. * Get an option value by name
  3377. * The function will first check this.options object, and else will check
  3378. * this.defaultOptions.
  3379. * @param {String} name
  3380. * @return {*} value
  3381. */
  3382. Component.prototype.getOption = function getOption(name) {
  3383. var value;
  3384. if (this.options) {
  3385. value = this.options[name];
  3386. }
  3387. if (value === undefined && this.defaultOptions) {
  3388. value = this.defaultOptions[name];
  3389. }
  3390. return value;
  3391. };
  3392. /**
  3393. * Set controller for this component, or remove current controller by passing
  3394. * null as parameter value.
  3395. * @param {Controller | null} controller
  3396. */
  3397. Component.prototype.setController = function setController (controller) {
  3398. this.controller = controller || null;
  3399. };
  3400. /**
  3401. * Get controller of this component
  3402. * @return {Controller} controller
  3403. */
  3404. Component.prototype.getController = function getController () {
  3405. return this.controller;
  3406. };
  3407. /**
  3408. * Get the container element of the component, which can be used by a child to
  3409. * add its own widgets. Not all components do have a container for childs, in
  3410. * that case null is returned.
  3411. * @returns {HTMLElement | null} container
  3412. */
  3413. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3414. Component.prototype.getContainer = function getContainer() {
  3415. // should be implemented by the component
  3416. return null;
  3417. };
  3418. /**
  3419. * Get the frame element of the component, the outer HTML DOM element.
  3420. * @returns {HTMLElement | null} frame
  3421. */
  3422. Component.prototype.getFrame = function getFrame() {
  3423. return this.frame;
  3424. };
  3425. /**
  3426. * Repaint the component
  3427. * @return {Boolean} changed
  3428. */
  3429. Component.prototype.repaint = function repaint() {
  3430. // should be implemented by the component
  3431. return false;
  3432. };
  3433. /**
  3434. * Reflow the component
  3435. * @return {Boolean} resized
  3436. */
  3437. Component.prototype.reflow = function reflow() {
  3438. // should be implemented by the component
  3439. return false;
  3440. };
  3441. /**
  3442. * Hide the component from the DOM
  3443. * @return {Boolean} changed
  3444. */
  3445. Component.prototype.hide = function hide() {
  3446. if (this.frame && this.frame.parentNode) {
  3447. this.frame.parentNode.removeChild(this.frame);
  3448. return true;
  3449. }
  3450. else {
  3451. return false;
  3452. }
  3453. };
  3454. /**
  3455. * Show the component in the DOM (when not already visible).
  3456. * A repaint will be executed when the component is not visible
  3457. * @return {Boolean} changed
  3458. */
  3459. Component.prototype.show = function show() {
  3460. if (!this.frame || !this.frame.parentNode) {
  3461. return this.repaint();
  3462. }
  3463. else {
  3464. return false;
  3465. }
  3466. };
  3467. /**
  3468. * Request a repaint. The controller will schedule a repaint
  3469. */
  3470. Component.prototype.requestRepaint = function requestRepaint() {
  3471. if (this.controller) {
  3472. this.controller.emit('request-repaint');
  3473. }
  3474. else {
  3475. throw new Error('Cannot request a repaint: no controller configured');
  3476. // TODO: just do a repaint when no parent is configured?
  3477. }
  3478. };
  3479. /**
  3480. * Request a reflow. The controller will schedule a reflow
  3481. */
  3482. Component.prototype.requestReflow = function requestReflow() {
  3483. if (this.controller) {
  3484. this.controller.emit('request-reflow');
  3485. }
  3486. else {
  3487. throw new Error('Cannot request a reflow: no controller configured');
  3488. // TODO: just do a reflow when no parent is configured?
  3489. }
  3490. };
  3491. /**
  3492. * A panel can contain components
  3493. * @param {Component} [parent]
  3494. * @param {Component[]} [depends] Components on which this components depends
  3495. * (except for the parent)
  3496. * @param {Object} [options] Available parameters:
  3497. * {String | Number | function} [left]
  3498. * {String | Number | function} [top]
  3499. * {String | Number | function} [width]
  3500. * {String | Number | function} [height]
  3501. * {String | function} [className]
  3502. * @constructor Panel
  3503. * @extends Component
  3504. */
  3505. function Panel(parent, depends, options) {
  3506. this.id = util.randomUUID();
  3507. this.parent = parent;
  3508. this.depends = depends;
  3509. this.options = options || {};
  3510. }
  3511. Panel.prototype = new Component();
  3512. /**
  3513. * Set options. Will extend the current options.
  3514. * @param {Object} [options] Available parameters:
  3515. * {String | function} [className]
  3516. * {String | Number | function} [left]
  3517. * {String | Number | function} [top]
  3518. * {String | Number | function} [width]
  3519. * {String | Number | function} [height]
  3520. */
  3521. Panel.prototype.setOptions = Component.prototype.setOptions;
  3522. /**
  3523. * Get the container element of the panel, which can be used by a child to
  3524. * add its own widgets.
  3525. * @returns {HTMLElement} container
  3526. */
  3527. Panel.prototype.getContainer = function () {
  3528. return this.frame;
  3529. };
  3530. /**
  3531. * Repaint the component
  3532. * @return {Boolean} changed
  3533. */
  3534. Panel.prototype.repaint = function () {
  3535. var changed = 0,
  3536. update = util.updateProperty,
  3537. asSize = util.option.asSize,
  3538. options = this.options,
  3539. frame = this.frame;
  3540. if (!frame) {
  3541. frame = document.createElement('div');
  3542. frame.className = 'vpanel';
  3543. var className = options.className;
  3544. if (className) {
  3545. if (typeof className == 'function') {
  3546. util.addClassName(frame, String(className()));
  3547. }
  3548. else {
  3549. util.addClassName(frame, String(className));
  3550. }
  3551. }
  3552. this.frame = frame;
  3553. changed += 1;
  3554. }
  3555. if (!frame.parentNode) {
  3556. if (!this.parent) {
  3557. throw new Error('Cannot repaint panel: no parent attached');
  3558. }
  3559. var parentContainer = this.parent.getContainer();
  3560. if (!parentContainer) {
  3561. throw new Error('Cannot repaint panel: parent has no container element');
  3562. }
  3563. parentContainer.appendChild(frame);
  3564. changed += 1;
  3565. }
  3566. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3567. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3568. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3569. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3570. return (changed > 0);
  3571. };
  3572. /**
  3573. * Reflow the component
  3574. * @return {Boolean} resized
  3575. */
  3576. Panel.prototype.reflow = function () {
  3577. var changed = 0,
  3578. update = util.updateProperty,
  3579. frame = this.frame;
  3580. if (frame) {
  3581. changed += update(this, 'top', frame.offsetTop);
  3582. changed += update(this, 'left', frame.offsetLeft);
  3583. changed += update(this, 'width', frame.offsetWidth);
  3584. changed += update(this, 'height', frame.offsetHeight);
  3585. }
  3586. else {
  3587. changed += 1;
  3588. }
  3589. return (changed > 0);
  3590. };
  3591. /**
  3592. * A root panel can hold components. The root panel must be initialized with
  3593. * a DOM element as container.
  3594. * @param {HTMLElement} container
  3595. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3596. * @constructor RootPanel
  3597. * @extends Panel
  3598. */
  3599. function RootPanel(container, options) {
  3600. this.id = util.randomUUID();
  3601. this.container = container;
  3602. // create functions to be used as DOM event listeners
  3603. var me = this;
  3604. this.hammer = null;
  3605. // create listeners for all interesting events, these events will be emitted
  3606. // via the controller
  3607. var events = [
  3608. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3609. 'dragstart', 'drag', 'dragend',
  3610. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3611. ];
  3612. this.listeners = {};
  3613. events.forEach(function (event) {
  3614. me.listeners[event] = function () {
  3615. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3616. me.controller.emit.apply(me.controller, args);
  3617. };
  3618. });
  3619. this.options = options || {};
  3620. this.defaultOptions = {
  3621. autoResize: true
  3622. };
  3623. }
  3624. RootPanel.prototype = new Panel();
  3625. /**
  3626. * Set options. Will extend the current options.
  3627. * @param {Object} [options] Available parameters:
  3628. * {String | function} [className]
  3629. * {String | Number | function} [left]
  3630. * {String | Number | function} [top]
  3631. * {String | Number | function} [width]
  3632. * {String | Number | function} [height]
  3633. * {Boolean | function} [autoResize]
  3634. */
  3635. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3636. /**
  3637. * Repaint the component
  3638. * @return {Boolean} changed
  3639. */
  3640. RootPanel.prototype.repaint = function () {
  3641. var changed = 0,
  3642. update = util.updateProperty,
  3643. asSize = util.option.asSize,
  3644. options = this.options,
  3645. frame = this.frame;
  3646. if (!frame) {
  3647. frame = document.createElement('div');
  3648. this.frame = frame;
  3649. this._registerListeners();
  3650. changed += 1;
  3651. }
  3652. if (!frame.parentNode) {
  3653. if (!this.container) {
  3654. throw new Error('Cannot repaint root panel: no container attached');
  3655. }
  3656. this.container.appendChild(frame);
  3657. changed += 1;
  3658. }
  3659. frame.className = 'vis timeline rootpanel ' + options.orientation +
  3660. (options.editable ? ' editable' : '');
  3661. var className = options.className;
  3662. if (className) {
  3663. util.addClassName(frame, util.option.asString(className));
  3664. }
  3665. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3666. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3667. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3668. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3669. this._updateWatch();
  3670. return (changed > 0);
  3671. };
  3672. /**
  3673. * Reflow the component
  3674. * @return {Boolean} resized
  3675. */
  3676. RootPanel.prototype.reflow = function () {
  3677. var changed = 0,
  3678. update = util.updateProperty,
  3679. frame = this.frame;
  3680. if (frame) {
  3681. changed += update(this, 'top', frame.offsetTop);
  3682. changed += update(this, 'left', frame.offsetLeft);
  3683. changed += update(this, 'width', frame.offsetWidth);
  3684. changed += update(this, 'height', frame.offsetHeight);
  3685. }
  3686. else {
  3687. changed += 1;
  3688. }
  3689. return (changed > 0);
  3690. };
  3691. /**
  3692. * Update watching for resize, depending on the current option
  3693. * @private
  3694. */
  3695. RootPanel.prototype._updateWatch = function () {
  3696. var autoResize = this.getOption('autoResize');
  3697. if (autoResize) {
  3698. this._watch();
  3699. }
  3700. else {
  3701. this._unwatch();
  3702. }
  3703. };
  3704. /**
  3705. * Watch for changes in the size of the frame. On resize, the Panel will
  3706. * automatically redraw itself.
  3707. * @private
  3708. */
  3709. RootPanel.prototype._watch = function () {
  3710. var me = this;
  3711. this._unwatch();
  3712. var checkSize = function () {
  3713. var autoResize = me.getOption('autoResize');
  3714. if (!autoResize) {
  3715. // stop watching when the option autoResize is changed to false
  3716. me._unwatch();
  3717. return;
  3718. }
  3719. if (me.frame) {
  3720. // check whether the frame is resized
  3721. if ((me.frame.clientWidth != me.width) ||
  3722. (me.frame.clientHeight != me.height)) {
  3723. me.requestReflow();
  3724. }
  3725. }
  3726. };
  3727. // TODO: automatically cleanup the event listener when the frame is deleted
  3728. util.addEventListener(window, 'resize', checkSize);
  3729. this.watchTimer = setInterval(checkSize, 1000);
  3730. };
  3731. /**
  3732. * Stop watching for a resize of the frame.
  3733. * @private
  3734. */
  3735. RootPanel.prototype._unwatch = function () {
  3736. if (this.watchTimer) {
  3737. clearInterval(this.watchTimer);
  3738. this.watchTimer = undefined;
  3739. }
  3740. // TODO: remove event listener on window.resize
  3741. };
  3742. /**
  3743. * Set controller for this component, or remove current controller by passing
  3744. * null as parameter value.
  3745. * @param {Controller | null} controller
  3746. */
  3747. RootPanel.prototype.setController = function setController (controller) {
  3748. this.controller = controller || null;
  3749. if (this.controller) {
  3750. this._registerListeners();
  3751. }
  3752. else {
  3753. this._unregisterListeners();
  3754. }
  3755. };
  3756. /**
  3757. * Register event emitters emitted by the rootpanel
  3758. * @private
  3759. */
  3760. RootPanel.prototype._registerListeners = function () {
  3761. if (this.frame && this.controller && !this.hammer) {
  3762. this.hammer = Hammer(this.frame, {
  3763. prevent_default: true
  3764. });
  3765. for (var event in this.listeners) {
  3766. if (this.listeners.hasOwnProperty(event)) {
  3767. this.hammer.on(event, this.listeners[event]);
  3768. }
  3769. }
  3770. }
  3771. };
  3772. /**
  3773. * Unregister event emitters from the rootpanel
  3774. * @private
  3775. */
  3776. RootPanel.prototype._unregisterListeners = function () {
  3777. if (this.hammer) {
  3778. for (var event in this.listeners) {
  3779. if (this.listeners.hasOwnProperty(event)) {
  3780. this.hammer.off(event, this.listeners[event]);
  3781. }
  3782. }
  3783. this.hammer = null;
  3784. }
  3785. };
  3786. /**
  3787. * A horizontal time axis
  3788. * @param {Component} parent
  3789. * @param {Component[]} [depends] Components on which this components depends
  3790. * (except for the parent)
  3791. * @param {Object} [options] See TimeAxis.setOptions for the available
  3792. * options.
  3793. * @constructor TimeAxis
  3794. * @extends Component
  3795. */
  3796. function TimeAxis (parent, depends, options) {
  3797. this.id = util.randomUUID();
  3798. this.parent = parent;
  3799. this.depends = depends;
  3800. this.dom = {
  3801. majorLines: [],
  3802. majorTexts: [],
  3803. minorLines: [],
  3804. minorTexts: [],
  3805. redundant: {
  3806. majorLines: [],
  3807. majorTexts: [],
  3808. minorLines: [],
  3809. minorTexts: []
  3810. }
  3811. };
  3812. this.props = {
  3813. range: {
  3814. start: 0,
  3815. end: 0,
  3816. minimumStep: 0
  3817. },
  3818. lineTop: 0
  3819. };
  3820. this.options = options || {};
  3821. this.defaultOptions = {
  3822. orientation: 'bottom', // supported: 'top', 'bottom'
  3823. // TODO: implement timeaxis orientations 'left' and 'right'
  3824. showMinorLabels: true,
  3825. showMajorLabels: true
  3826. };
  3827. this.conversion = null;
  3828. this.range = null;
  3829. }
  3830. TimeAxis.prototype = new Component();
  3831. // TODO: comment options
  3832. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3833. /**
  3834. * Set a range (start and end)
  3835. * @param {Range | Object} range A Range or an object containing start and end.
  3836. */
  3837. TimeAxis.prototype.setRange = function (range) {
  3838. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3839. throw new TypeError('Range must be an instance of Range, ' +
  3840. 'or an object containing start and end.');
  3841. }
  3842. this.range = range;
  3843. };
  3844. /**
  3845. * Convert a position on screen (pixels) to a datetime
  3846. * @param {int} x Position on the screen in pixels
  3847. * @return {Date} time The datetime the corresponds with given position x
  3848. */
  3849. TimeAxis.prototype.toTime = function(x) {
  3850. var conversion = this.conversion;
  3851. return new Date(x / conversion.scale + conversion.offset);
  3852. };
  3853. /**
  3854. * Convert a datetime (Date object) into a position on the screen
  3855. * @param {Date} time A date
  3856. * @return {int} x The position on the screen in pixels which corresponds
  3857. * with the given date.
  3858. * @private
  3859. */
  3860. TimeAxis.prototype.toScreen = function(time) {
  3861. var conversion = this.conversion;
  3862. return (time.valueOf() - conversion.offset) * conversion.scale;
  3863. };
  3864. /**
  3865. * Repaint the component
  3866. * @return {Boolean} changed
  3867. */
  3868. TimeAxis.prototype.repaint = function () {
  3869. var changed = 0,
  3870. update = util.updateProperty,
  3871. asSize = util.option.asSize,
  3872. options = this.options,
  3873. orientation = this.getOption('orientation'),
  3874. props = this.props,
  3875. step = this.step;
  3876. var frame = this.frame;
  3877. if (!frame) {
  3878. frame = document.createElement('div');
  3879. this.frame = frame;
  3880. changed += 1;
  3881. }
  3882. frame.className = 'axis';
  3883. // TODO: custom className?
  3884. if (!frame.parentNode) {
  3885. if (!this.parent) {
  3886. throw new Error('Cannot repaint time axis: no parent attached');
  3887. }
  3888. var parentContainer = this.parent.getContainer();
  3889. if (!parentContainer) {
  3890. throw new Error('Cannot repaint time axis: parent has no container element');
  3891. }
  3892. parentContainer.appendChild(frame);
  3893. changed += 1;
  3894. }
  3895. var parent = frame.parentNode;
  3896. if (parent) {
  3897. var beforeChild = frame.nextSibling;
  3898. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3899. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3900. (this.props.parentHeight - this.height) + 'px' :
  3901. '0px';
  3902. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3903. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3904. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3905. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3906. // get characters width and height
  3907. this._repaintMeasureChars();
  3908. if (this.step) {
  3909. this._repaintStart();
  3910. step.first();
  3911. var xFirstMajorLabel = undefined;
  3912. var max = 0;
  3913. while (step.hasNext() && max < 1000) {
  3914. max++;
  3915. var cur = step.getCurrent(),
  3916. x = this.toScreen(cur),
  3917. isMajor = step.isMajor();
  3918. // TODO: lines must have a width, such that we can create css backgrounds
  3919. if (this.getOption('showMinorLabels')) {
  3920. this._repaintMinorText(x, step.getLabelMinor());
  3921. }
  3922. if (isMajor && this.getOption('showMajorLabels')) {
  3923. if (x > 0) {
  3924. if (xFirstMajorLabel == undefined) {
  3925. xFirstMajorLabel = x;
  3926. }
  3927. this._repaintMajorText(x, step.getLabelMajor());
  3928. }
  3929. this._repaintMajorLine(x);
  3930. }
  3931. else {
  3932. this._repaintMinorLine(x);
  3933. }
  3934. step.next();
  3935. }
  3936. // create a major label on the left when needed
  3937. if (this.getOption('showMajorLabels')) {
  3938. var leftTime = this.toTime(0),
  3939. leftText = step.getLabelMajor(leftTime),
  3940. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3941. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3942. this._repaintMajorText(0, leftText);
  3943. }
  3944. }
  3945. this._repaintEnd();
  3946. }
  3947. this._repaintLine();
  3948. // put frame online again
  3949. if (beforeChild) {
  3950. parent.insertBefore(frame, beforeChild);
  3951. }
  3952. else {
  3953. parent.appendChild(frame)
  3954. }
  3955. }
  3956. return (changed > 0);
  3957. };
  3958. /**
  3959. * Start a repaint. Move all DOM elements to a redundant list, where they
  3960. * can be picked for re-use, or can be cleaned up in the end
  3961. * @private
  3962. */
  3963. TimeAxis.prototype._repaintStart = function () {
  3964. var dom = this.dom,
  3965. redundant = dom.redundant;
  3966. redundant.majorLines = dom.majorLines;
  3967. redundant.majorTexts = dom.majorTexts;
  3968. redundant.minorLines = dom.minorLines;
  3969. redundant.minorTexts = dom.minorTexts;
  3970. dom.majorLines = [];
  3971. dom.majorTexts = [];
  3972. dom.minorLines = [];
  3973. dom.minorTexts = [];
  3974. };
  3975. /**
  3976. * End a repaint. Cleanup leftover DOM elements in the redundant list
  3977. * @private
  3978. */
  3979. TimeAxis.prototype._repaintEnd = function () {
  3980. util.forEach(this.dom.redundant, function (arr) {
  3981. while (arr.length) {
  3982. var elem = arr.pop();
  3983. if (elem && elem.parentNode) {
  3984. elem.parentNode.removeChild(elem);
  3985. }
  3986. }
  3987. });
  3988. };
  3989. /**
  3990. * Create a minor label for the axis at position x
  3991. * @param {Number} x
  3992. * @param {String} text
  3993. * @private
  3994. */
  3995. TimeAxis.prototype._repaintMinorText = function (x, text) {
  3996. // reuse redundant label
  3997. var label = this.dom.redundant.minorTexts.shift();
  3998. if (!label) {
  3999. // create new label
  4000. var content = document.createTextNode('');
  4001. label = document.createElement('div');
  4002. label.appendChild(content);
  4003. label.className = 'text minor';
  4004. this.frame.appendChild(label);
  4005. }
  4006. this.dom.minorTexts.push(label);
  4007. label.childNodes[0].nodeValue = text;
  4008. label.style.left = x + 'px';
  4009. label.style.top = this.props.minorLabelTop + 'px';
  4010. //label.title = title; // TODO: this is a heavy operation
  4011. };
  4012. /**
  4013. * Create a Major label for the axis at position x
  4014. * @param {Number} x
  4015. * @param {String} text
  4016. * @private
  4017. */
  4018. TimeAxis.prototype._repaintMajorText = function (x, text) {
  4019. // reuse redundant label
  4020. var label = this.dom.redundant.majorTexts.shift();
  4021. if (!label) {
  4022. // create label
  4023. var content = document.createTextNode(text);
  4024. label = document.createElement('div');
  4025. label.className = 'text major';
  4026. label.appendChild(content);
  4027. this.frame.appendChild(label);
  4028. }
  4029. this.dom.majorTexts.push(label);
  4030. label.childNodes[0].nodeValue = text;
  4031. label.style.top = this.props.majorLabelTop + 'px';
  4032. label.style.left = x + 'px';
  4033. //label.title = title; // TODO: this is a heavy operation
  4034. };
  4035. /**
  4036. * Create a minor line for the axis at position x
  4037. * @param {Number} x
  4038. * @private
  4039. */
  4040. TimeAxis.prototype._repaintMinorLine = function (x) {
  4041. // reuse redundant line
  4042. var line = this.dom.redundant.minorLines.shift();
  4043. if (!line) {
  4044. // create vertical line
  4045. line = document.createElement('div');
  4046. line.className = 'grid vertical minor';
  4047. this.frame.appendChild(line);
  4048. }
  4049. this.dom.minorLines.push(line);
  4050. var props = this.props;
  4051. line.style.top = props.minorLineTop + 'px';
  4052. line.style.height = props.minorLineHeight + 'px';
  4053. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  4054. };
  4055. /**
  4056. * Create a Major line for the axis at position x
  4057. * @param {Number} x
  4058. * @private
  4059. */
  4060. TimeAxis.prototype._repaintMajorLine = function (x) {
  4061. // reuse redundant line
  4062. var line = this.dom.redundant.majorLines.shift();
  4063. if (!line) {
  4064. // create vertical line
  4065. line = document.createElement('DIV');
  4066. line.className = 'grid vertical major';
  4067. this.frame.appendChild(line);
  4068. }
  4069. this.dom.majorLines.push(line);
  4070. var props = this.props;
  4071. line.style.top = props.majorLineTop + 'px';
  4072. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4073. line.style.height = props.majorLineHeight + 'px';
  4074. };
  4075. /**
  4076. * Repaint the horizontal line for the axis
  4077. * @private
  4078. */
  4079. TimeAxis.prototype._repaintLine = function() {
  4080. var line = this.dom.line,
  4081. frame = this.frame,
  4082. options = this.options;
  4083. // line before all axis elements
  4084. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4085. if (line) {
  4086. // put this line at the end of all childs
  4087. frame.removeChild(line);
  4088. frame.appendChild(line);
  4089. }
  4090. else {
  4091. // create the axis line
  4092. line = document.createElement('div');
  4093. line.className = 'grid horizontal major';
  4094. frame.appendChild(line);
  4095. this.dom.line = line;
  4096. }
  4097. line.style.top = this.props.lineTop + 'px';
  4098. }
  4099. else {
  4100. if (line && line.parentElement) {
  4101. frame.removeChild(line.line);
  4102. delete this.dom.line;
  4103. }
  4104. }
  4105. };
  4106. /**
  4107. * Create characters used to determine the size of text on the axis
  4108. * @private
  4109. */
  4110. TimeAxis.prototype._repaintMeasureChars = function () {
  4111. // calculate the width and height of a single character
  4112. // this is used to calculate the step size, and also the positioning of the
  4113. // axis
  4114. var dom = this.dom,
  4115. text;
  4116. if (!dom.measureCharMinor) {
  4117. text = document.createTextNode('0');
  4118. var measureCharMinor = document.createElement('DIV');
  4119. measureCharMinor.className = 'text minor measure';
  4120. measureCharMinor.appendChild(text);
  4121. this.frame.appendChild(measureCharMinor);
  4122. dom.measureCharMinor = measureCharMinor;
  4123. }
  4124. if (!dom.measureCharMajor) {
  4125. text = document.createTextNode('0');
  4126. var measureCharMajor = document.createElement('DIV');
  4127. measureCharMajor.className = 'text major measure';
  4128. measureCharMajor.appendChild(text);
  4129. this.frame.appendChild(measureCharMajor);
  4130. dom.measureCharMajor = measureCharMajor;
  4131. }
  4132. };
  4133. /**
  4134. * Reflow the component
  4135. * @return {Boolean} resized
  4136. */
  4137. TimeAxis.prototype.reflow = function () {
  4138. var changed = 0,
  4139. update = util.updateProperty,
  4140. frame = this.frame,
  4141. range = this.range;
  4142. if (!range) {
  4143. throw new Error('Cannot repaint time axis: no range configured');
  4144. }
  4145. if (frame) {
  4146. changed += update(this, 'top', frame.offsetTop);
  4147. changed += update(this, 'left', frame.offsetLeft);
  4148. // calculate size of a character
  4149. var props = this.props,
  4150. showMinorLabels = this.getOption('showMinorLabels'),
  4151. showMajorLabels = this.getOption('showMajorLabels'),
  4152. measureCharMinor = this.dom.measureCharMinor,
  4153. measureCharMajor = this.dom.measureCharMajor;
  4154. if (measureCharMinor) {
  4155. props.minorCharHeight = measureCharMinor.clientHeight;
  4156. props.minorCharWidth = measureCharMinor.clientWidth;
  4157. }
  4158. if (measureCharMajor) {
  4159. props.majorCharHeight = measureCharMajor.clientHeight;
  4160. props.majorCharWidth = measureCharMajor.clientWidth;
  4161. }
  4162. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4163. if (parentHeight != props.parentHeight) {
  4164. props.parentHeight = parentHeight;
  4165. changed += 1;
  4166. }
  4167. switch (this.getOption('orientation')) {
  4168. case 'bottom':
  4169. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4170. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4171. props.minorLabelTop = 0;
  4172. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4173. props.minorLineTop = -this.top;
  4174. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4175. props.minorLineWidth = 1; // TODO: really calculate width
  4176. props.majorLineTop = -this.top;
  4177. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4178. props.majorLineWidth = 1; // TODO: really calculate width
  4179. props.lineTop = 0;
  4180. break;
  4181. case 'top':
  4182. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4183. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4184. props.majorLabelTop = 0;
  4185. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4186. props.minorLineTop = props.minorLabelTop;
  4187. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4188. props.minorLineWidth = 1; // TODO: really calculate width
  4189. props.majorLineTop = 0;
  4190. props.majorLineHeight = Math.max(parentHeight - this.top);
  4191. props.majorLineWidth = 1; // TODO: really calculate width
  4192. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4193. break;
  4194. default:
  4195. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4196. }
  4197. var height = props.minorLabelHeight + props.majorLabelHeight;
  4198. changed += update(this, 'width', frame.offsetWidth);
  4199. changed += update(this, 'height', height);
  4200. // calculate range and step
  4201. this._updateConversion();
  4202. var start = util.convert(range.start, 'Number'),
  4203. end = util.convert(range.end, 'Number'),
  4204. minimumStep = this.toTime((props.minorCharWidth || 10) * 5).valueOf()
  4205. -this.toTime(0).valueOf();
  4206. this.step = new TimeStep(new Date(start), new Date(end), minimumStep);
  4207. changed += update(props.range, 'start', start);
  4208. changed += update(props.range, 'end', end);
  4209. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4210. }
  4211. return (changed > 0);
  4212. };
  4213. /**
  4214. * Calculate the scale and offset to convert a position on screen to the
  4215. * corresponding date and vice versa.
  4216. * After the method _updateConversion is executed once, the methods toTime
  4217. * and toScreen can be used.
  4218. * @private
  4219. */
  4220. TimeAxis.prototype._updateConversion = function() {
  4221. var range = this.range;
  4222. if (!range) {
  4223. throw new Error('No range configured');
  4224. }
  4225. if (range.conversion) {
  4226. this.conversion = range.conversion(this.width);
  4227. }
  4228. else {
  4229. this.conversion = Range.conversion(range.start, range.end, this.width);
  4230. }
  4231. };
  4232. /**
  4233. * Snap a date to a rounded value.
  4234. * The snap intervals are dependent on the current scale and step.
  4235. * @param {Date} date the date to be snapped.
  4236. * @return {Date} snappedDate
  4237. */
  4238. TimeAxis.prototype.snap = function snap (date) {
  4239. return this.step.snap(date);
  4240. };
  4241. /**
  4242. * A current time bar
  4243. * @param {Component} parent
  4244. * @param {Component[]} [depends] Components on which this components depends
  4245. * (except for the parent)
  4246. * @param {Object} [options] Available parameters:
  4247. * {Boolean} [showCurrentTime]
  4248. * @constructor CurrentTime
  4249. * @extends Component
  4250. */
  4251. function CurrentTime (parent, depends, options) {
  4252. this.id = util.randomUUID();
  4253. this.parent = parent;
  4254. this.depends = depends;
  4255. this.options = options || {};
  4256. this.defaultOptions = {
  4257. showCurrentTime: false
  4258. };
  4259. }
  4260. CurrentTime.prototype = new Component();
  4261. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  4262. /**
  4263. * Get the container element of the bar, which can be used by a child to
  4264. * add its own widgets.
  4265. * @returns {HTMLElement} container
  4266. */
  4267. CurrentTime.prototype.getContainer = function () {
  4268. return this.frame;
  4269. };
  4270. /**
  4271. * Repaint the component
  4272. * @return {Boolean} changed
  4273. */
  4274. CurrentTime.prototype.repaint = function () {
  4275. var bar = this.frame,
  4276. parent = this.parent,
  4277. parentContainer = parent.parent.getContainer();
  4278. if (!parent) {
  4279. throw new Error('Cannot repaint bar: no parent attached');
  4280. }
  4281. if (!parentContainer) {
  4282. throw new Error('Cannot repaint bar: parent has no container element');
  4283. }
  4284. if (!this.getOption('showCurrentTime')) {
  4285. if (bar) {
  4286. parentContainer.removeChild(bar);
  4287. delete this.frame;
  4288. }
  4289. return false;
  4290. }
  4291. if (!bar) {
  4292. bar = document.createElement('div');
  4293. bar.className = 'currenttime';
  4294. bar.style.position = 'absolute';
  4295. bar.style.top = '0px';
  4296. bar.style.height = '100%';
  4297. parentContainer.appendChild(bar);
  4298. this.frame = bar;
  4299. }
  4300. if (!parent.conversion) {
  4301. parent._updateConversion();
  4302. }
  4303. var now = new Date();
  4304. var x = parent.toScreen(now);
  4305. bar.style.left = x + 'px';
  4306. bar.title = 'Current time: ' + now;
  4307. // start a timer to adjust for the new time
  4308. if (this.currentTimeTimer !== undefined) {
  4309. clearTimeout(this.currentTimeTimer);
  4310. delete this.currentTimeTimer;
  4311. }
  4312. var timeline = this;
  4313. var interval = 1 / parent.conversion.scale / 2;
  4314. if (interval < 30) {
  4315. interval = 30;
  4316. }
  4317. this.currentTimeTimer = setTimeout(function() {
  4318. timeline.repaint();
  4319. }, interval);
  4320. return false;
  4321. };
  4322. /**
  4323. * A custom time bar
  4324. * @param {Component} parent
  4325. * @param {Component[]} [depends] Components on which this components depends
  4326. * (except for the parent)
  4327. * @param {Object} [options] Available parameters:
  4328. * {Boolean} [showCustomTime]
  4329. * @constructor CustomTime
  4330. * @extends Component
  4331. */
  4332. function CustomTime (parent, depends, options) {
  4333. this.id = util.randomUUID();
  4334. this.parent = parent;
  4335. this.depends = depends;
  4336. this.options = options || {};
  4337. this.defaultOptions = {
  4338. showCustomTime: false
  4339. };
  4340. this.customTime = new Date();
  4341. this.eventParams = {}; // stores state parameters while dragging the bar
  4342. }
  4343. CustomTime.prototype = new Component();
  4344. Emitter(CustomTime.prototype);
  4345. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4346. /**
  4347. * Get the container element of the bar, which can be used by a child to
  4348. * add its own widgets.
  4349. * @returns {HTMLElement} container
  4350. */
  4351. CustomTime.prototype.getContainer = function () {
  4352. return this.frame;
  4353. };
  4354. /**
  4355. * Repaint the component
  4356. * @return {Boolean} changed
  4357. */
  4358. CustomTime.prototype.repaint = function () {
  4359. var bar = this.frame,
  4360. parent = this.parent;
  4361. if (!parent) {
  4362. throw new Error('Cannot repaint bar: no parent attached');
  4363. }
  4364. var parentContainer = parent.parent.getContainer();
  4365. if (!parentContainer) {
  4366. throw new Error('Cannot repaint bar: parent has no container element');
  4367. }
  4368. if (!this.getOption('showCustomTime')) {
  4369. if (bar) {
  4370. parentContainer.removeChild(bar);
  4371. delete this.frame;
  4372. }
  4373. return false;
  4374. }
  4375. if (!bar) {
  4376. bar = document.createElement('div');
  4377. bar.className = 'customtime';
  4378. bar.style.position = 'absolute';
  4379. bar.style.top = '0px';
  4380. bar.style.height = '100%';
  4381. parentContainer.appendChild(bar);
  4382. var drag = document.createElement('div');
  4383. drag.style.position = 'relative';
  4384. drag.style.top = '0px';
  4385. drag.style.left = '-10px';
  4386. drag.style.height = '100%';
  4387. drag.style.width = '20px';
  4388. bar.appendChild(drag);
  4389. this.frame = bar;
  4390. // attach event listeners
  4391. this.hammer = Hammer(bar, {
  4392. prevent_default: true
  4393. });
  4394. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4395. this.hammer.on('drag', this._onDrag.bind(this));
  4396. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4397. }
  4398. if (!parent.conversion) {
  4399. parent._updateConversion();
  4400. }
  4401. var x = parent.toScreen(this.customTime);
  4402. bar.style.left = x + 'px';
  4403. bar.title = 'Time: ' + this.customTime;
  4404. return false;
  4405. };
  4406. /**
  4407. * Set custom time.
  4408. * @param {Date} time
  4409. */
  4410. CustomTime.prototype.setCustomTime = function(time) {
  4411. this.customTime = new Date(time.valueOf());
  4412. this.repaint();
  4413. };
  4414. /**
  4415. * Retrieve the current custom time.
  4416. * @return {Date} customTime
  4417. */
  4418. CustomTime.prototype.getCustomTime = function() {
  4419. return new Date(this.customTime.valueOf());
  4420. };
  4421. /**
  4422. * Start moving horizontally
  4423. * @param {Event} event
  4424. * @private
  4425. */
  4426. CustomTime.prototype._onDragStart = function(event) {
  4427. this.eventParams.customTime = this.customTime;
  4428. event.stopPropagation();
  4429. event.preventDefault();
  4430. };
  4431. /**
  4432. * Perform moving operating.
  4433. * @param {Event} event
  4434. * @private
  4435. */
  4436. CustomTime.prototype._onDrag = function (event) {
  4437. var deltaX = event.gesture.deltaX,
  4438. x = this.parent.toScreen(this.eventParams.customTime) + deltaX,
  4439. time = this.parent.toTime(x);
  4440. this.setCustomTime(time);
  4441. // fire a timechange event
  4442. if (this.controller) {
  4443. this.controller.emit('timechange', {
  4444. time: this.customTime
  4445. })
  4446. }
  4447. event.stopPropagation();
  4448. event.preventDefault();
  4449. };
  4450. /**
  4451. * Stop moving operating.
  4452. * @param {event} event
  4453. * @private
  4454. */
  4455. CustomTime.prototype._onDragEnd = function (event) {
  4456. // fire a timechanged event
  4457. if (this.controller) {
  4458. this.controller.emit('timechanged', {
  4459. time: this.customTime
  4460. })
  4461. }
  4462. event.stopPropagation();
  4463. event.preventDefault();
  4464. };
  4465. /**
  4466. * An ItemSet holds a set of items and ranges which can be displayed in a
  4467. * range. The width is determined by the parent of the ItemSet, and the height
  4468. * is determined by the size of the items.
  4469. * @param {Component} parent
  4470. * @param {Component[]} [depends] Components on which this components depends
  4471. * (except for the parent)
  4472. * @param {Object} [options] See ItemSet.setOptions for the available
  4473. * options.
  4474. * @constructor ItemSet
  4475. * @extends Panel
  4476. */
  4477. // TODO: improve performance by replacing all Array.forEach with a for loop
  4478. function ItemSet(parent, depends, options) {
  4479. this.id = util.randomUUID();
  4480. this.parent = parent;
  4481. this.depends = depends;
  4482. // event listeners
  4483. this.eventListeners = {
  4484. dragstart: this._onDragStart.bind(this),
  4485. drag: this._onDrag.bind(this),
  4486. dragend: this._onDragEnd.bind(this)
  4487. };
  4488. // one options object is shared by this itemset and all its items
  4489. this.options = options || {};
  4490. this.defaultOptions = {
  4491. type: 'box',
  4492. align: 'center',
  4493. orientation: 'bottom',
  4494. margin: {
  4495. axis: 20,
  4496. item: 10
  4497. },
  4498. padding: 5
  4499. };
  4500. this.dom = {};
  4501. var me = this;
  4502. this.itemsData = null; // DataSet
  4503. this.range = null; // Range or Object {start: number, end: number}
  4504. // data change listeners
  4505. this.listeners = {
  4506. 'add': function (event, params, senderId) {
  4507. if (senderId != me.id) {
  4508. me._onAdd(params.items);
  4509. }
  4510. },
  4511. 'update': function (event, params, senderId) {
  4512. if (senderId != me.id) {
  4513. me._onUpdate(params.items);
  4514. }
  4515. },
  4516. 'remove': function (event, params, senderId) {
  4517. if (senderId != me.id) {
  4518. me._onRemove(params.items);
  4519. }
  4520. }
  4521. };
  4522. this.items = {}; // object with an Item for every data item
  4523. this.selection = []; // list with the ids of all selected nodes
  4524. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4525. this.stack = new Stack(this, Object.create(this.options));
  4526. this.conversion = null;
  4527. this.touchParams = {}; // stores properties while dragging
  4528. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4529. }
  4530. ItemSet.prototype = new Panel();
  4531. // available item types will be registered here
  4532. ItemSet.types = {
  4533. box: ItemBox,
  4534. range: ItemRange,
  4535. rangeoverflow: ItemRangeOverflow,
  4536. point: ItemPoint
  4537. };
  4538. /**
  4539. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4540. * @param {Object} [options] The following options are available:
  4541. * {String | function} [className]
  4542. * class name for the itemset
  4543. * {String} [type]
  4544. * Default type for the items. Choose from 'box'
  4545. * (default), 'point', or 'range'. The default
  4546. * Style can be overwritten by individual items.
  4547. * {String} align
  4548. * Alignment for the items, only applicable for
  4549. * ItemBox. Choose 'center' (default), 'left', or
  4550. * 'right'.
  4551. * {String} orientation
  4552. * Orientation of the item set. Choose 'top' or
  4553. * 'bottom' (default).
  4554. * {Number} margin.axis
  4555. * Margin between the axis and the items in pixels.
  4556. * Default is 20.
  4557. * {Number} margin.item
  4558. * Margin between items in pixels. Default is 10.
  4559. * {Number} padding
  4560. * Padding of the contents of an item in pixels.
  4561. * Must correspond with the items css. Default is 5.
  4562. * {Function} snap
  4563. * Function to let items snap to nice dates when
  4564. * dragging items.
  4565. */
  4566. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4567. /**
  4568. * Set controller for this component
  4569. * @param {Controller | null} controller
  4570. */
  4571. ItemSet.prototype.setController = function setController (controller) {
  4572. var event;
  4573. // unregister old event listeners
  4574. if (this.controller) {
  4575. for (event in this.eventListeners) {
  4576. if (this.eventListeners.hasOwnProperty(event)) {
  4577. this.controller.off(event, this.eventListeners[event]);
  4578. }
  4579. }
  4580. }
  4581. this.controller = controller || null;
  4582. // register new event listeners
  4583. if (this.controller) {
  4584. for (event in this.eventListeners) {
  4585. if (this.eventListeners.hasOwnProperty(event)) {
  4586. this.controller.on(event, this.eventListeners[event]);
  4587. }
  4588. }
  4589. }
  4590. };
  4591. // attach event listeners for dragging items to the controller
  4592. (function (me) {
  4593. var _controller = null;
  4594. var _onDragStart = null;
  4595. var _onDrag = null;
  4596. var _onDragEnd = null;
  4597. Object.defineProperty(me, 'controller', {
  4598. get: function () {
  4599. return _controller;
  4600. },
  4601. set: function (controller) {
  4602. }
  4603. });
  4604. }) (this);
  4605. /**
  4606. * Set range (start and end).
  4607. * @param {Range | Object} range A Range or an object containing start and end.
  4608. */
  4609. ItemSet.prototype.setRange = function setRange(range) {
  4610. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4611. throw new TypeError('Range must be an instance of Range, ' +
  4612. 'or an object containing start and end.');
  4613. }
  4614. this.range = range;
  4615. };
  4616. /**
  4617. * Set selected items by their id. Replaces the current selection
  4618. * Unknown id's are silently ignored.
  4619. * @param {Array} [ids] An array with zero or more id's of the items to be
  4620. * selected. If ids is an empty array, all items will be
  4621. * unselected.
  4622. */
  4623. ItemSet.prototype.setSelection = function setSelection(ids) {
  4624. var i, ii, id, item, selection;
  4625. if (ids) {
  4626. if (!Array.isArray(ids)) {
  4627. throw new TypeError('Array expected');
  4628. }
  4629. // unselect currently selected items
  4630. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4631. id = this.selection[i];
  4632. item = this.items[id];
  4633. if (item) item.unselect();
  4634. }
  4635. // select items
  4636. this.selection = [];
  4637. for (i = 0, ii = ids.length; i < ii; i++) {
  4638. id = ids[i];
  4639. item = this.items[id];
  4640. if (item) {
  4641. this.selection.push(id);
  4642. item.select();
  4643. }
  4644. }
  4645. if (this.controller) {
  4646. this.requestRepaint();
  4647. }
  4648. }
  4649. };
  4650. /**
  4651. * Get the selected items by their id
  4652. * @return {Array} ids The ids of the selected items
  4653. */
  4654. ItemSet.prototype.getSelection = function getSelection() {
  4655. return this.selection.concat([]);
  4656. };
  4657. /**
  4658. * Deselect a selected item
  4659. * @param {String | Number} id
  4660. * @private
  4661. */
  4662. ItemSet.prototype._deselect = function _deselect(id) {
  4663. var selection = this.selection;
  4664. for (var i = 0, ii = selection.length; i < ii; i++) {
  4665. if (selection[i] == id) { // non-strict comparison!
  4666. selection.splice(i, 1);
  4667. break;
  4668. }
  4669. }
  4670. };
  4671. /**
  4672. * Repaint the component
  4673. * @return {Boolean} changed
  4674. */
  4675. ItemSet.prototype.repaint = function repaint() {
  4676. var changed = 0,
  4677. update = util.updateProperty,
  4678. asSize = util.option.asSize,
  4679. options = this.options,
  4680. orientation = this.getOption('orientation'),
  4681. defaultOptions = this.defaultOptions,
  4682. frame = this.frame;
  4683. if (!frame) {
  4684. frame = document.createElement('div');
  4685. frame.className = 'itemset';
  4686. frame['timeline-itemset'] = this;
  4687. var className = options.className;
  4688. if (className) {
  4689. util.addClassName(frame, util.option.asString(className));
  4690. }
  4691. // create background panel
  4692. var background = document.createElement('div');
  4693. background.className = 'background';
  4694. frame.appendChild(background);
  4695. this.dom.background = background;
  4696. // create foreground panel
  4697. var foreground = document.createElement('div');
  4698. foreground.className = 'foreground';
  4699. frame.appendChild(foreground);
  4700. this.dom.foreground = foreground;
  4701. // create axis panel
  4702. var axis = document.createElement('div');
  4703. axis.className = 'itemset-axis';
  4704. //frame.appendChild(axis);
  4705. this.dom.axis = axis;
  4706. this.frame = frame;
  4707. changed += 1;
  4708. }
  4709. if (!this.parent) {
  4710. throw new Error('Cannot repaint itemset: no parent attached');
  4711. }
  4712. var parentContainer = this.parent.getContainer();
  4713. if (!parentContainer) {
  4714. throw new Error('Cannot repaint itemset: parent has no container element');
  4715. }
  4716. if (!frame.parentNode) {
  4717. parentContainer.appendChild(frame);
  4718. changed += 1;
  4719. }
  4720. if (!this.dom.axis.parentNode) {
  4721. parentContainer.appendChild(this.dom.axis);
  4722. changed += 1;
  4723. }
  4724. // reposition frame
  4725. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4726. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4727. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4728. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4729. // reposition axis
  4730. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4731. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4732. if (orientation == 'bottom') {
  4733. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4734. }
  4735. else { // orientation == 'top'
  4736. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4737. }
  4738. this._updateConversion();
  4739. var me = this,
  4740. queue = this.queue,
  4741. itemsData = this.itemsData,
  4742. items = this.items,
  4743. dataOptions = {
  4744. // TODO: cleanup
  4745. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  4746. };
  4747. // show/hide added/changed/removed items
  4748. for (var id in queue) {
  4749. if (queue.hasOwnProperty(id)) {
  4750. var entry = queue[id],
  4751. item = items[id],
  4752. action = entry.action;
  4753. //noinspection FallthroughInSwitchStatementJS
  4754. switch (action) {
  4755. case 'add':
  4756. case 'update':
  4757. var itemData = itemsData && itemsData.get(id, dataOptions);
  4758. if (itemData) {
  4759. var type = itemData.type ||
  4760. (itemData.start && itemData.end && 'range') ||
  4761. options.type ||
  4762. 'box';
  4763. var constructor = ItemSet.types[type];
  4764. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4765. if (item) {
  4766. // update item
  4767. if (!constructor || !(item instanceof constructor)) {
  4768. // item type has changed, hide and delete the item
  4769. changed += item.hide();
  4770. item = null;
  4771. }
  4772. else {
  4773. item.data = itemData; // TODO: create a method item.setData ?
  4774. changed++;
  4775. }
  4776. }
  4777. if (!item) {
  4778. // create item
  4779. if (constructor) {
  4780. item = new constructor(me, itemData, options, defaultOptions);
  4781. item.id = entry.id; // we take entry.id, as id itself is stringified
  4782. changed++;
  4783. }
  4784. else {
  4785. throw new TypeError('Unknown item type "' + type + '"');
  4786. }
  4787. }
  4788. // force a repaint (not only a reposition)
  4789. item.repaint();
  4790. items[id] = item;
  4791. }
  4792. // update queue
  4793. delete queue[id];
  4794. break;
  4795. case 'remove':
  4796. if (item) {
  4797. // remove the item from the set selected items
  4798. if (item.selected) {
  4799. me._deselect(id);
  4800. }
  4801. // remove DOM of the item
  4802. changed += item.hide();
  4803. }
  4804. // update lists
  4805. delete items[id];
  4806. delete queue[id];
  4807. break;
  4808. default:
  4809. console.log('Error: unknown action "' + action + '"');
  4810. }
  4811. }
  4812. }
  4813. // reposition all items. Show items only when in the visible area
  4814. util.forEach(this.items, function (item) {
  4815. if (item.visible) {
  4816. changed += item.show();
  4817. item.reposition();
  4818. }
  4819. else {
  4820. changed += item.hide();
  4821. }
  4822. });
  4823. return (changed > 0);
  4824. };
  4825. /**
  4826. * Get the foreground container element
  4827. * @return {HTMLElement} foreground
  4828. */
  4829. ItemSet.prototype.getForeground = function getForeground() {
  4830. return this.dom.foreground;
  4831. };
  4832. /**
  4833. * Get the background container element
  4834. * @return {HTMLElement} background
  4835. */
  4836. ItemSet.prototype.getBackground = function getBackground() {
  4837. return this.dom.background;
  4838. };
  4839. /**
  4840. * Get the axis container element
  4841. * @return {HTMLElement} axis
  4842. */
  4843. ItemSet.prototype.getAxis = function getAxis() {
  4844. return this.dom.axis;
  4845. };
  4846. /**
  4847. * Reflow the component
  4848. * @return {Boolean} resized
  4849. */
  4850. ItemSet.prototype.reflow = function reflow () {
  4851. var changed = 0,
  4852. options = this.options,
  4853. marginAxis = (options.margin && 'axis' in options.margin) ? options.margin.axis : this.defaultOptions.margin.axis,
  4854. marginItem = (options.margin && 'item' in options.margin) ? options.margin.item : this.defaultOptions.margin.item,
  4855. update = util.updateProperty,
  4856. asNumber = util.option.asNumber,
  4857. asSize = util.option.asSize,
  4858. frame = this.frame;
  4859. if (frame) {
  4860. this._updateConversion();
  4861. util.forEach(this.items, function (item) {
  4862. changed += item.reflow();
  4863. });
  4864. // TODO: stack.update should be triggered via an event, in stack itself
  4865. // TODO: only update the stack when there are changed items
  4866. this.stack.update();
  4867. var maxHeight = asNumber(options.maxHeight);
  4868. var fixedHeight = (asSize(options.height) != null);
  4869. var height;
  4870. if (fixedHeight) {
  4871. height = frame.offsetHeight;
  4872. }
  4873. else {
  4874. // height is not specified, determine the height from the height and positioned items
  4875. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4876. if (visibleItems.length) {
  4877. var min = visibleItems[0].top;
  4878. var max = visibleItems[0].top + visibleItems[0].height;
  4879. util.forEach(visibleItems, function (item) {
  4880. min = Math.min(min, item.top);
  4881. max = Math.max(max, (item.top + item.height));
  4882. });
  4883. height = (max - min) + marginAxis + marginItem;
  4884. }
  4885. else {
  4886. height = marginAxis + marginItem;
  4887. }
  4888. }
  4889. if (maxHeight != null) {
  4890. height = Math.min(height, maxHeight);
  4891. }
  4892. changed += update(this, 'height', height);
  4893. // calculate height from items
  4894. changed += update(this, 'top', frame.offsetTop);
  4895. changed += update(this, 'left', frame.offsetLeft);
  4896. changed += update(this, 'width', frame.offsetWidth);
  4897. }
  4898. else {
  4899. changed += 1;
  4900. }
  4901. return (changed > 0);
  4902. };
  4903. /**
  4904. * Hide this component from the DOM
  4905. * @return {Boolean} changed
  4906. */
  4907. ItemSet.prototype.hide = function hide() {
  4908. var changed = false;
  4909. // remove the DOM
  4910. if (this.frame && this.frame.parentNode) {
  4911. this.frame.parentNode.removeChild(this.frame);
  4912. changed = true;
  4913. }
  4914. if (this.dom.axis && this.dom.axis.parentNode) {
  4915. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4916. changed = true;
  4917. }
  4918. return changed;
  4919. };
  4920. /**
  4921. * Set items
  4922. * @param {vis.DataSet | null} items
  4923. */
  4924. ItemSet.prototype.setItems = function setItems(items) {
  4925. var me = this,
  4926. ids,
  4927. oldItemsData = this.itemsData;
  4928. // replace the dataset
  4929. if (!items) {
  4930. this.itemsData = null;
  4931. }
  4932. else if (items instanceof DataSet || items instanceof DataView) {
  4933. this.itemsData = items;
  4934. }
  4935. else {
  4936. throw new TypeError('Data must be an instance of DataSet');
  4937. }
  4938. if (oldItemsData) {
  4939. // unsubscribe from old dataset
  4940. util.forEach(this.listeners, function (callback, event) {
  4941. oldItemsData.unsubscribe(event, callback);
  4942. });
  4943. // remove all drawn items
  4944. ids = oldItemsData.getIds();
  4945. this._onRemove(ids);
  4946. }
  4947. if (this.itemsData) {
  4948. // subscribe to new dataset
  4949. var id = this.id;
  4950. util.forEach(this.listeners, function (callback, event) {
  4951. me.itemsData.on(event, callback, id);
  4952. });
  4953. // draw all new items
  4954. ids = this.itemsData.getIds();
  4955. this._onAdd(ids);
  4956. }
  4957. };
  4958. /**
  4959. * Get the current items items
  4960. * @returns {vis.DataSet | null}
  4961. */
  4962. ItemSet.prototype.getItems = function getItems() {
  4963. return this.itemsData;
  4964. };
  4965. /**
  4966. * Remove an item by its id
  4967. * @param {String | Number} id
  4968. */
  4969. ItemSet.prototype.removeItem = function removeItem (id) {
  4970. var item = this.itemsData.get(id),
  4971. dataset = this._myDataSet();
  4972. if (item) {
  4973. // confirm deletion
  4974. this.options.onRemove(item, function (item) {
  4975. if (item) {
  4976. dataset.remove(item);
  4977. }
  4978. });
  4979. }
  4980. };
  4981. /**
  4982. * Handle updated items
  4983. * @param {Number[]} ids
  4984. * @private
  4985. */
  4986. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4987. this._toQueue('update', ids);
  4988. };
  4989. /**
  4990. * Handle changed items
  4991. * @param {Number[]} ids
  4992. * @private
  4993. */
  4994. ItemSet.prototype._onAdd = function _onAdd(ids) {
  4995. this._toQueue('add', ids);
  4996. };
  4997. /**
  4998. * Handle removed items
  4999. * @param {Number[]} ids
  5000. * @private
  5001. */
  5002. ItemSet.prototype._onRemove = function _onRemove(ids) {
  5003. this._toQueue('remove', ids);
  5004. };
  5005. /**
  5006. * Put items in the queue to be added/updated/remove
  5007. * @param {String} action can be 'add', 'update', 'remove'
  5008. * @param {Number[]} ids
  5009. */
  5010. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  5011. var queue = this.queue;
  5012. ids.forEach(function (id) {
  5013. queue[id] = {
  5014. id: id,
  5015. action: action
  5016. };
  5017. });
  5018. if (this.controller) {
  5019. //this.requestReflow();
  5020. this.requestRepaint();
  5021. }
  5022. };
  5023. /**
  5024. * Calculate the scale and offset to convert a position on screen to the
  5025. * corresponding date and vice versa.
  5026. * After the method _updateConversion is executed once, the methods toTime
  5027. * and toScreen can be used.
  5028. * @private
  5029. */
  5030. ItemSet.prototype._updateConversion = function _updateConversion() {
  5031. var range = this.range;
  5032. if (!range) {
  5033. throw new Error('No range configured');
  5034. }
  5035. if (range.conversion) {
  5036. this.conversion = range.conversion(this.width);
  5037. }
  5038. else {
  5039. this.conversion = Range.conversion(range.start, range.end, this.width);
  5040. }
  5041. };
  5042. /**
  5043. * Convert a position on screen (pixels) to a datetime
  5044. * Before this method can be used, the method _updateConversion must be
  5045. * executed once.
  5046. * @param {int} x Position on the screen in pixels
  5047. * @return {Date} time The datetime the corresponds with given position x
  5048. */
  5049. ItemSet.prototype.toTime = function toTime(x) {
  5050. var conversion = this.conversion;
  5051. return new Date(x / conversion.scale + conversion.offset);
  5052. };
  5053. /**
  5054. * Convert a datetime (Date object) into a position on the screen
  5055. * Before this method can be used, the method _updateConversion must be
  5056. * executed once.
  5057. * @param {Date} time A date
  5058. * @return {int} x The position on the screen in pixels which corresponds
  5059. * with the given date.
  5060. */
  5061. ItemSet.prototype.toScreen = function toScreen(time) {
  5062. var conversion = this.conversion;
  5063. return (time.valueOf() - conversion.offset) * conversion.scale;
  5064. };
  5065. /**
  5066. * Start dragging the selected events
  5067. * @param {Event} event
  5068. * @private
  5069. */
  5070. ItemSet.prototype._onDragStart = function (event) {
  5071. if (!this.options.editable) {
  5072. return;
  5073. }
  5074. var item = ItemSet.itemFromTarget(event),
  5075. me = this;
  5076. if (item && item.selected) {
  5077. var dragLeftItem = event.target.dragLeftItem;
  5078. var dragRightItem = event.target.dragRightItem;
  5079. if (dragLeftItem) {
  5080. this.touchParams.itemProps = [{
  5081. item: dragLeftItem,
  5082. start: item.data.start.valueOf()
  5083. }];
  5084. }
  5085. else if (dragRightItem) {
  5086. this.touchParams.itemProps = [{
  5087. item: dragRightItem,
  5088. end: item.data.end.valueOf()
  5089. }];
  5090. }
  5091. else {
  5092. this.touchParams.itemProps = this.getSelection().map(function (id) {
  5093. var item = me.items[id];
  5094. var props = {
  5095. item: item
  5096. };
  5097. if ('start' in item.data) {
  5098. props.start = item.data.start.valueOf()
  5099. }
  5100. if ('end' in item.data) {
  5101. props.end = item.data.end.valueOf()
  5102. }
  5103. return props;
  5104. });
  5105. }
  5106. event.stopPropagation();
  5107. }
  5108. };
  5109. /**
  5110. * Drag selected items
  5111. * @param {Event} event
  5112. * @private
  5113. */
  5114. ItemSet.prototype._onDrag = function (event) {
  5115. if (this.touchParams.itemProps) {
  5116. var snap = this.options.snap || null,
  5117. deltaX = event.gesture.deltaX,
  5118. offset = deltaX / this.conversion.scale;
  5119. // move
  5120. this.touchParams.itemProps.forEach(function (props) {
  5121. if ('start' in props) {
  5122. var start = new Date(props.start + offset);
  5123. props.item.data.start = snap ? snap(start) : start;
  5124. }
  5125. if ('end' in props) {
  5126. var end = new Date(props.end + offset);
  5127. props.item.data.end = snap ? snap(end) : end;
  5128. }
  5129. });
  5130. // TODO: implement onMoving handler
  5131. // TODO: implement dragging from one group to another
  5132. this.requestReflow();
  5133. event.stopPropagation();
  5134. }
  5135. };
  5136. /**
  5137. * End of dragging selected items
  5138. * @param {Event} event
  5139. * @private
  5140. */
  5141. ItemSet.prototype._onDragEnd = function (event) {
  5142. if (this.touchParams.itemProps) {
  5143. // prepare a change set for the changed items
  5144. var changes = [],
  5145. me = this,
  5146. dataset = this._myDataSet(),
  5147. type;
  5148. this.touchParams.itemProps.forEach(function (props) {
  5149. var id = props.item.id,
  5150. item = me.itemsData.get(id);
  5151. var changed = false;
  5152. if ('start' in props.item.data) {
  5153. changed = (props.start != props.item.data.start.valueOf());
  5154. item.start = util.convert(props.item.data.start, dataset.convert['start']);
  5155. }
  5156. if ('end' in props.item.data) {
  5157. changed = changed || (props.end != props.item.data.end.valueOf());
  5158. item.end = util.convert(props.item.data.end, dataset.convert['end']);
  5159. }
  5160. // only apply changes when start or end is actually changed
  5161. if (changed) {
  5162. me.options.onMove(item, function (item) {
  5163. if (item) {
  5164. // apply changes
  5165. changes.push(item);
  5166. }
  5167. else {
  5168. // restore original values
  5169. if ('start' in props) props.item.data.start = props.start;
  5170. if ('end' in props) props.item.data.end = props.end;
  5171. me.requestReflow();
  5172. }
  5173. });
  5174. }
  5175. });
  5176. this.touchParams.itemProps = null;
  5177. // apply the changes to the data (if there are changes)
  5178. if (changes.length) {
  5179. dataset.update(changes);
  5180. }
  5181. event.stopPropagation();
  5182. }
  5183. };
  5184. /**
  5185. * Find an item from an event target:
  5186. * searches for the attribute 'timeline-item' in the event target's element tree
  5187. * @param {Event} event
  5188. * @return {Item | null} item
  5189. */
  5190. ItemSet.itemFromTarget = function itemFromTarget (event) {
  5191. var target = event.target;
  5192. while (target) {
  5193. if (target.hasOwnProperty('timeline-item')) {
  5194. return target['timeline-item'];
  5195. }
  5196. target = target.parentNode;
  5197. }
  5198. return null;
  5199. };
  5200. /**
  5201. * Find the ItemSet from an event target:
  5202. * searches for the attribute 'timeline-itemset' in the event target's element tree
  5203. * @param {Event} event
  5204. * @return {ItemSet | null} item
  5205. */
  5206. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  5207. var target = event.target;
  5208. while (target) {
  5209. if (target.hasOwnProperty('timeline-itemset')) {
  5210. return target['timeline-itemset'];
  5211. }
  5212. target = target.parentNode;
  5213. }
  5214. return null;
  5215. };
  5216. /**
  5217. * Find the DataSet to which this ItemSet is connected
  5218. * @returns {null | DataSet} dataset
  5219. * @private
  5220. */
  5221. ItemSet.prototype._myDataSet = function _myDataSet() {
  5222. // find the root DataSet
  5223. var dataset = this.itemsData;
  5224. while (dataset instanceof DataView) {
  5225. dataset = dataset.data;
  5226. }
  5227. return dataset;
  5228. };
  5229. /**
  5230. * @constructor Item
  5231. * @param {ItemSet} parent
  5232. * @param {Object} data Object containing (optional) parameters type,
  5233. * start, end, content, group, className.
  5234. * @param {Object} [options] Options to set initial property values
  5235. * @param {Object} [defaultOptions] default options
  5236. * // TODO: describe available options
  5237. */
  5238. function Item (parent, data, options, defaultOptions) {
  5239. this.parent = parent;
  5240. this.data = data;
  5241. this.dom = null;
  5242. this.options = options || {};
  5243. this.defaultOptions = defaultOptions || {};
  5244. this.selected = false;
  5245. this.visible = false;
  5246. this.top = 0;
  5247. this.left = 0;
  5248. this.width = 0;
  5249. this.height = 0;
  5250. this.offset = 0;
  5251. }
  5252. /**
  5253. * Select current item
  5254. */
  5255. Item.prototype.select = function select() {
  5256. this.selected = true;
  5257. if (this.visible) this.repaint();
  5258. };
  5259. /**
  5260. * Unselect current item
  5261. */
  5262. Item.prototype.unselect = function unselect() {
  5263. this.selected = false;
  5264. if (this.visible) this.repaint();
  5265. };
  5266. /**
  5267. * Show the Item in the DOM (when not already visible)
  5268. * @return {Boolean} changed
  5269. */
  5270. Item.prototype.show = function show() {
  5271. return false;
  5272. };
  5273. /**
  5274. * Hide the Item from the DOM (when visible)
  5275. * @return {Boolean} changed
  5276. */
  5277. Item.prototype.hide = function hide() {
  5278. return false;
  5279. };
  5280. /**
  5281. * Repaint the item
  5282. * @return {Boolean} changed
  5283. */
  5284. Item.prototype.repaint = function repaint() {
  5285. // should be implemented by the item
  5286. return false;
  5287. };
  5288. /**
  5289. * Reflow the item
  5290. * @return {Boolean} resized
  5291. */
  5292. Item.prototype.reflow = function reflow() {
  5293. // should be implemented by the item
  5294. return false;
  5295. };
  5296. /**
  5297. * Give the item a display offset in pixels
  5298. * @param {Number} offset Offset on screen in pixels
  5299. */
  5300. Item.prototype.setOffset = function setOffset(offset) {
  5301. this.offset = offset;
  5302. };
  5303. /**
  5304. * Repaint a delete button on the top right of the item when the item is selected
  5305. * @param {HTMLElement} anchor
  5306. * @private
  5307. */
  5308. Item.prototype._repaintDeleteButton = function (anchor) {
  5309. if (this.selected && this.options.editable && !this.dom.deleteButton) {
  5310. // create and show button
  5311. var parent = this.parent;
  5312. var id = this.id;
  5313. var deleteButton = document.createElement('div');
  5314. deleteButton.className = 'delete';
  5315. deleteButton.title = 'Delete this item';
  5316. Hammer(deleteButton, {
  5317. preventDefault: true
  5318. }).on('tap', function (event) {
  5319. parent.removeItem(id);
  5320. event.stopPropagation();
  5321. });
  5322. anchor.appendChild(deleteButton);
  5323. this.dom.deleteButton = deleteButton;
  5324. }
  5325. else if (!this.selected && this.dom.deleteButton) {
  5326. // remove button
  5327. if (this.dom.deleteButton.parentNode) {
  5328. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5329. }
  5330. this.dom.deleteButton = null;
  5331. }
  5332. };
  5333. /**
  5334. * @constructor ItemBox
  5335. * @extends Item
  5336. * @param {ItemSet} parent
  5337. * @param {Object} data Object containing parameters start
  5338. * content, className.
  5339. * @param {Object} [options] Options to set initial property values
  5340. * @param {Object} [defaultOptions] default options
  5341. * // TODO: describe available options
  5342. */
  5343. function ItemBox (parent, data, options, defaultOptions) {
  5344. this.props = {
  5345. dot: {
  5346. left: 0,
  5347. top: 0,
  5348. width: 0,
  5349. height: 0
  5350. },
  5351. line: {
  5352. top: 0,
  5353. left: 0,
  5354. width: 0,
  5355. height: 0
  5356. }
  5357. };
  5358. Item.call(this, parent, data, options, defaultOptions);
  5359. }
  5360. ItemBox.prototype = new Item (null, null);
  5361. /**
  5362. * Repaint the item
  5363. * @return {Boolean} changed
  5364. */
  5365. ItemBox.prototype.repaint = function repaint() {
  5366. // TODO: make an efficient repaint
  5367. var changed = false;
  5368. var dom = this.dom;
  5369. if (!dom) {
  5370. this._create();
  5371. dom = this.dom;
  5372. changed = true;
  5373. }
  5374. if (dom) {
  5375. if (!this.parent) {
  5376. throw new Error('Cannot repaint item: no parent attached');
  5377. }
  5378. if (!dom.box.parentNode) {
  5379. var foreground = this.parent.getForeground();
  5380. if (!foreground) {
  5381. throw new Error('Cannot repaint time axis: ' +
  5382. 'parent has no foreground container element');
  5383. }
  5384. foreground.appendChild(dom.box);
  5385. changed = true;
  5386. }
  5387. if (!dom.line.parentNode) {
  5388. var background = this.parent.getBackground();
  5389. if (!background) {
  5390. throw new Error('Cannot repaint time axis: ' +
  5391. 'parent has no background container element');
  5392. }
  5393. background.appendChild(dom.line);
  5394. changed = true;
  5395. }
  5396. if (!dom.dot.parentNode) {
  5397. var axis = this.parent.getAxis();
  5398. if (!background) {
  5399. throw new Error('Cannot repaint time axis: ' +
  5400. 'parent has no axis container element');
  5401. }
  5402. axis.appendChild(dom.dot);
  5403. changed = true;
  5404. }
  5405. this._repaintDeleteButton(dom.box);
  5406. // update contents
  5407. if (this.data.content != this.content) {
  5408. this.content = this.data.content;
  5409. if (this.content instanceof Element) {
  5410. dom.content.innerHTML = '';
  5411. dom.content.appendChild(this.content);
  5412. }
  5413. else if (this.data.content != undefined) {
  5414. dom.content.innerHTML = this.content;
  5415. }
  5416. else {
  5417. throw new Error('Property "content" missing in item ' + this.data.id);
  5418. }
  5419. changed = true;
  5420. }
  5421. // update class
  5422. var className = (this.data.className? ' ' + this.data.className : '') +
  5423. (this.selected ? ' selected' : '');
  5424. if (this.className != className) {
  5425. this.className = className;
  5426. dom.box.className = 'item box' + className;
  5427. dom.line.className = 'item line' + className;
  5428. dom.dot.className = 'item dot' + className;
  5429. changed = true;
  5430. }
  5431. }
  5432. return changed;
  5433. };
  5434. /**
  5435. * Show the item in the DOM (when not already visible). The items DOM will
  5436. * be created when needed.
  5437. * @return {Boolean} changed
  5438. */
  5439. ItemBox.prototype.show = function show() {
  5440. if (!this.dom || !this.dom.box.parentNode) {
  5441. return this.repaint();
  5442. }
  5443. else {
  5444. return false;
  5445. }
  5446. };
  5447. /**
  5448. * Hide the item from the DOM (when visible)
  5449. * @return {Boolean} changed
  5450. */
  5451. ItemBox.prototype.hide = function hide() {
  5452. var changed = false,
  5453. dom = this.dom;
  5454. if (dom) {
  5455. if (dom.box.parentNode) {
  5456. dom.box.parentNode.removeChild(dom.box);
  5457. changed = true;
  5458. }
  5459. if (dom.line.parentNode) {
  5460. dom.line.parentNode.removeChild(dom.line);
  5461. }
  5462. if (dom.dot.parentNode) {
  5463. dom.dot.parentNode.removeChild(dom.dot);
  5464. }
  5465. }
  5466. return changed;
  5467. };
  5468. /**
  5469. * Reflow the item: calculate its actual size and position from the DOM
  5470. * @return {boolean} resized returns true if the axis is resized
  5471. * @override
  5472. */
  5473. ItemBox.prototype.reflow = function reflow() {
  5474. var changed = 0,
  5475. update,
  5476. dom,
  5477. props,
  5478. options,
  5479. margin,
  5480. start,
  5481. align,
  5482. orientation,
  5483. top,
  5484. left,
  5485. data,
  5486. range;
  5487. if (this.data.start == undefined) {
  5488. throw new Error('Property "start" missing in item ' + this.data.id);
  5489. }
  5490. data = this.data;
  5491. range = this.parent && this.parent.range;
  5492. if (data && range) {
  5493. // TODO: account for the width of the item
  5494. var interval = (range.end - range.start);
  5495. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  5496. }
  5497. else {
  5498. this.visible = false;
  5499. }
  5500. if (this.visible) {
  5501. dom = this.dom;
  5502. if (dom) {
  5503. update = util.updateProperty;
  5504. props = this.props;
  5505. options = this.options;
  5506. start = this.parent.toScreen(this.data.start) + this.offset;
  5507. align = options.align || this.defaultOptions.align;
  5508. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5509. orientation = options.orientation || this.defaultOptions.orientation;
  5510. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5511. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5512. changed += update(props.line, 'width', dom.line.offsetWidth);
  5513. changed += update(props.line, 'height', dom.line.offsetHeight);
  5514. changed += update(props.line, 'top', dom.line.offsetTop);
  5515. changed += update(this, 'width', dom.box.offsetWidth);
  5516. changed += update(this, 'height', dom.box.offsetHeight);
  5517. if (align == 'right') {
  5518. left = start - this.width;
  5519. }
  5520. else if (align == 'left') {
  5521. left = start;
  5522. }
  5523. else {
  5524. // default or 'center'
  5525. left = start - this.width / 2;
  5526. }
  5527. changed += update(this, 'left', left);
  5528. changed += update(props.line, 'left', start - props.line.width / 2);
  5529. changed += update(props.dot, 'left', start - props.dot.width / 2);
  5530. changed += update(props.dot, 'top', -props.dot.height / 2);
  5531. if (orientation == 'top') {
  5532. top = margin;
  5533. changed += update(this, 'top', top);
  5534. }
  5535. else {
  5536. // default or 'bottom'
  5537. var parentHeight = this.parent.height;
  5538. top = parentHeight - this.height - margin;
  5539. changed += update(this, 'top', top);
  5540. }
  5541. }
  5542. else {
  5543. changed += 1;
  5544. }
  5545. }
  5546. return (changed > 0);
  5547. };
  5548. /**
  5549. * Create an items DOM
  5550. * @private
  5551. */
  5552. ItemBox.prototype._create = function _create() {
  5553. var dom = this.dom;
  5554. if (!dom) {
  5555. this.dom = dom = {};
  5556. // create the box
  5557. dom.box = document.createElement('DIV');
  5558. // className is updated in repaint()
  5559. // contents box (inside the background box). used for making margins
  5560. dom.content = document.createElement('DIV');
  5561. dom.content.className = 'content';
  5562. dom.box.appendChild(dom.content);
  5563. // line to axis
  5564. dom.line = document.createElement('DIV');
  5565. dom.line.className = 'line';
  5566. // dot on axis
  5567. dom.dot = document.createElement('DIV');
  5568. dom.dot.className = 'dot';
  5569. // attach this item as attribute
  5570. dom.box['timeline-item'] = this;
  5571. }
  5572. };
  5573. /**
  5574. * Reposition the item, recalculate its left, top, and width, using the current
  5575. * range and size of the items itemset
  5576. * @override
  5577. */
  5578. ItemBox.prototype.reposition = function reposition() {
  5579. var dom = this.dom,
  5580. props = this.props,
  5581. orientation = this.options.orientation || this.defaultOptions.orientation;
  5582. if (dom) {
  5583. var box = dom.box,
  5584. line = dom.line,
  5585. dot = dom.dot;
  5586. box.style.left = this.left + 'px';
  5587. box.style.top = this.top + 'px';
  5588. line.style.left = props.line.left + 'px';
  5589. if (orientation == 'top') {
  5590. line.style.top = 0 + 'px';
  5591. line.style.height = this.top + 'px';
  5592. }
  5593. else {
  5594. // orientation 'bottom'
  5595. line.style.top = (this.top + this.height) + 'px';
  5596. line.style.height = Math.max(this.parent.height - this.top - this.height +
  5597. this.props.dot.height / 2, 0) + 'px';
  5598. }
  5599. dot.style.left = props.dot.left + 'px';
  5600. dot.style.top = props.dot.top + 'px';
  5601. }
  5602. };
  5603. /**
  5604. * @constructor ItemPoint
  5605. * @extends Item
  5606. * @param {ItemSet} parent
  5607. * @param {Object} data Object containing parameters start
  5608. * content, className.
  5609. * @param {Object} [options] Options to set initial property values
  5610. * @param {Object} [defaultOptions] default options
  5611. * // TODO: describe available options
  5612. */
  5613. function ItemPoint (parent, data, options, defaultOptions) {
  5614. this.props = {
  5615. dot: {
  5616. top: 0,
  5617. width: 0,
  5618. height: 0
  5619. },
  5620. content: {
  5621. height: 0,
  5622. marginLeft: 0
  5623. }
  5624. };
  5625. Item.call(this, parent, data, options, defaultOptions);
  5626. }
  5627. ItemPoint.prototype = new Item (null, null);
  5628. /**
  5629. * Repaint the item
  5630. * @return {Boolean} changed
  5631. */
  5632. ItemPoint.prototype.repaint = function repaint() {
  5633. // TODO: make an efficient repaint
  5634. var changed = false;
  5635. var dom = this.dom;
  5636. if (!dom) {
  5637. this._create();
  5638. dom = this.dom;
  5639. changed = true;
  5640. }
  5641. if (dom) {
  5642. if (!this.parent) {
  5643. throw new Error('Cannot repaint item: no parent attached');
  5644. }
  5645. var foreground = this.parent.getForeground();
  5646. if (!foreground) {
  5647. throw new Error('Cannot repaint time axis: ' +
  5648. 'parent has no foreground container element');
  5649. }
  5650. if (!dom.point.parentNode) {
  5651. foreground.appendChild(dom.point);
  5652. foreground.appendChild(dom.point);
  5653. changed = true;
  5654. }
  5655. // update contents
  5656. if (this.data.content != this.content) {
  5657. this.content = this.data.content;
  5658. if (this.content instanceof Element) {
  5659. dom.content.innerHTML = '';
  5660. dom.content.appendChild(this.content);
  5661. }
  5662. else if (this.data.content != undefined) {
  5663. dom.content.innerHTML = this.content;
  5664. }
  5665. else {
  5666. throw new Error('Property "content" missing in item ' + this.data.id);
  5667. }
  5668. changed = true;
  5669. }
  5670. this._repaintDeleteButton(dom.point);
  5671. // update class
  5672. var className = (this.data.className? ' ' + this.data.className : '') +
  5673. (this.selected ? ' selected' : '');
  5674. if (this.className != className) {
  5675. this.className = className;
  5676. dom.point.className = 'item point' + className;
  5677. changed = true;
  5678. }
  5679. }
  5680. return changed;
  5681. };
  5682. /**
  5683. * Show the item in the DOM (when not already visible). The items DOM will
  5684. * be created when needed.
  5685. * @return {Boolean} changed
  5686. */
  5687. ItemPoint.prototype.show = function show() {
  5688. if (!this.dom || !this.dom.point.parentNode) {
  5689. return this.repaint();
  5690. }
  5691. else {
  5692. return false;
  5693. }
  5694. };
  5695. /**
  5696. * Hide the item from the DOM (when visible)
  5697. * @return {Boolean} changed
  5698. */
  5699. ItemPoint.prototype.hide = function hide() {
  5700. var changed = false,
  5701. dom = this.dom;
  5702. if (dom) {
  5703. if (dom.point.parentNode) {
  5704. dom.point.parentNode.removeChild(dom.point);
  5705. changed = true;
  5706. }
  5707. }
  5708. return changed;
  5709. };
  5710. /**
  5711. * Reflow the item: calculate its actual size from the DOM
  5712. * @return {boolean} resized returns true if the axis is resized
  5713. * @override
  5714. */
  5715. ItemPoint.prototype.reflow = function reflow() {
  5716. var changed = 0,
  5717. update,
  5718. dom,
  5719. props,
  5720. options,
  5721. margin,
  5722. orientation,
  5723. start,
  5724. top,
  5725. data,
  5726. range;
  5727. if (this.data.start == undefined) {
  5728. throw new Error('Property "start" missing in item ' + this.data.id);
  5729. }
  5730. data = this.data;
  5731. range = this.parent && this.parent.range;
  5732. if (data && range) {
  5733. // TODO: account for the width of the item
  5734. var interval = (range.end - range.start);
  5735. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  5736. }
  5737. else {
  5738. this.visible = false;
  5739. }
  5740. if (this.visible) {
  5741. dom = this.dom;
  5742. if (dom) {
  5743. update = util.updateProperty;
  5744. props = this.props;
  5745. options = this.options;
  5746. orientation = options.orientation || this.defaultOptions.orientation;
  5747. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5748. start = this.parent.toScreen(this.data.start) + this.offset;
  5749. changed += update(this, 'width', dom.point.offsetWidth);
  5750. changed += update(this, 'height', dom.point.offsetHeight);
  5751. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5752. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5753. changed += update(props.content, 'height', dom.content.offsetHeight);
  5754. if (orientation == 'top') {
  5755. top = margin;
  5756. }
  5757. else {
  5758. // default or 'bottom'
  5759. var parentHeight = this.parent.height;
  5760. top = Math.max(parentHeight - this.height - margin, 0);
  5761. }
  5762. changed += update(this, 'top', top);
  5763. changed += update(this, 'left', start - props.dot.width / 2);
  5764. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5765. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5766. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5767. }
  5768. else {
  5769. changed += 1;
  5770. }
  5771. }
  5772. return (changed > 0);
  5773. };
  5774. /**
  5775. * Create an items DOM
  5776. * @private
  5777. */
  5778. ItemPoint.prototype._create = function _create() {
  5779. var dom = this.dom;
  5780. if (!dom) {
  5781. this.dom = dom = {};
  5782. // background box
  5783. dom.point = document.createElement('div');
  5784. // className is updated in repaint()
  5785. // contents box, right from the dot
  5786. dom.content = document.createElement('div');
  5787. dom.content.className = 'content';
  5788. dom.point.appendChild(dom.content);
  5789. // dot at start
  5790. dom.dot = document.createElement('div');
  5791. dom.dot.className = 'dot';
  5792. dom.point.appendChild(dom.dot);
  5793. // attach this item as attribute
  5794. dom.point['timeline-item'] = this;
  5795. }
  5796. };
  5797. /**
  5798. * Reposition the item, recalculate its left, top, and width, using the current
  5799. * range and size of the items itemset
  5800. * @override
  5801. */
  5802. ItemPoint.prototype.reposition = function reposition() {
  5803. var dom = this.dom,
  5804. props = this.props;
  5805. if (dom) {
  5806. dom.point.style.top = this.top + 'px';
  5807. dom.point.style.left = this.left + 'px';
  5808. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5809. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5810. dom.dot.style.top = props.dot.top + 'px';
  5811. }
  5812. };
  5813. /**
  5814. * @constructor ItemRange
  5815. * @extends Item
  5816. * @param {ItemSet} parent
  5817. * @param {Object} data Object containing parameters start, end
  5818. * content, className.
  5819. * @param {Object} [options] Options to set initial property values
  5820. * @param {Object} [defaultOptions] default options
  5821. * // TODO: describe available options
  5822. */
  5823. function ItemRange (parent, data, options, defaultOptions) {
  5824. this.props = {
  5825. content: {
  5826. left: 0,
  5827. width: 0
  5828. }
  5829. };
  5830. Item.call(this, parent, data, options, defaultOptions);
  5831. }
  5832. ItemRange.prototype = new Item (null, null);
  5833. /**
  5834. * Repaint the item
  5835. * @return {Boolean} changed
  5836. */
  5837. ItemRange.prototype.repaint = function repaint() {
  5838. // TODO: make an efficient repaint
  5839. var changed = false;
  5840. var dom = this.dom;
  5841. if (!dom) {
  5842. this._create();
  5843. dom = this.dom;
  5844. changed = true;
  5845. }
  5846. if (dom) {
  5847. if (!this.parent) {
  5848. throw new Error('Cannot repaint item: no parent attached');
  5849. }
  5850. var foreground = this.parent.getForeground();
  5851. if (!foreground) {
  5852. throw new Error('Cannot repaint time axis: ' +
  5853. 'parent has no foreground container element');
  5854. }
  5855. if (!dom.box.parentNode) {
  5856. foreground.appendChild(dom.box);
  5857. changed = true;
  5858. }
  5859. // update content
  5860. if (this.data.content != this.content) {
  5861. this.content = this.data.content;
  5862. if (this.content instanceof Element) {
  5863. dom.content.innerHTML = '';
  5864. dom.content.appendChild(this.content);
  5865. }
  5866. else if (this.data.content != undefined) {
  5867. dom.content.innerHTML = this.content;
  5868. }
  5869. else {
  5870. throw new Error('Property "content" missing in item ' + this.data.id);
  5871. }
  5872. changed = true;
  5873. }
  5874. this._repaintDeleteButton(dom.box);
  5875. this._repaintDragLeft();
  5876. this._repaintDragRight();
  5877. // update class
  5878. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5879. (this.selected ? ' selected' : '');
  5880. if (this.className != className) {
  5881. this.className = className;
  5882. dom.box.className = 'item range' + className;
  5883. changed = true;
  5884. }
  5885. }
  5886. return changed;
  5887. };
  5888. /**
  5889. * Show the item in the DOM (when not already visible). The items DOM will
  5890. * be created when needed.
  5891. * @return {Boolean} changed
  5892. */
  5893. ItemRange.prototype.show = function show() {
  5894. if (!this.dom || !this.dom.box.parentNode) {
  5895. return this.repaint();
  5896. }
  5897. else {
  5898. return false;
  5899. }
  5900. };
  5901. /**
  5902. * Hide the item from the DOM (when visible)
  5903. * @return {Boolean} changed
  5904. */
  5905. ItemRange.prototype.hide = function hide() {
  5906. var changed = false,
  5907. dom = this.dom;
  5908. if (dom) {
  5909. if (dom.box.parentNode) {
  5910. dom.box.parentNode.removeChild(dom.box);
  5911. changed = true;
  5912. }
  5913. }
  5914. return changed;
  5915. };
  5916. /**
  5917. * Reflow the item: calculate its actual size from the DOM
  5918. * @return {boolean} resized returns true if the axis is resized
  5919. * @override
  5920. */
  5921. ItemRange.prototype.reflow = function reflow() {
  5922. var changed = 0,
  5923. dom,
  5924. props,
  5925. options,
  5926. margin,
  5927. padding,
  5928. parent,
  5929. start,
  5930. end,
  5931. data,
  5932. range,
  5933. update,
  5934. box,
  5935. parentWidth,
  5936. contentLeft,
  5937. orientation,
  5938. top;
  5939. if (this.data.start == undefined) {
  5940. throw new Error('Property "start" missing in item ' + this.data.id);
  5941. }
  5942. if (this.data.end == undefined) {
  5943. throw new Error('Property "end" missing in item ' + this.data.id);
  5944. }
  5945. data = this.data;
  5946. range = this.parent && this.parent.range;
  5947. if (data && range) {
  5948. // TODO: account for the width of the item. Take some margin
  5949. this.visible = (data.start < range.end) && (data.end > range.start);
  5950. }
  5951. else {
  5952. this.visible = false;
  5953. }
  5954. if (this.visible) {
  5955. dom = this.dom;
  5956. if (dom) {
  5957. props = this.props;
  5958. options = this.options;
  5959. parent = this.parent;
  5960. start = parent.toScreen(this.data.start) + this.offset;
  5961. end = parent.toScreen(this.data.end) + this.offset;
  5962. update = util.updateProperty;
  5963. box = dom.box;
  5964. parentWidth = parent.width;
  5965. orientation = options.orientation || this.defaultOptions.orientation;
  5966. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5967. padding = options.padding || this.defaultOptions.padding;
  5968. changed += update(props.content, 'width', dom.content.offsetWidth);
  5969. changed += update(this, 'height', box.offsetHeight);
  5970. // limit the width of the this, as browsers cannot draw very wide divs
  5971. if (start < -parentWidth) {
  5972. start = -parentWidth;
  5973. }
  5974. if (end > 2 * parentWidth) {
  5975. end = 2 * parentWidth;
  5976. }
  5977. // when range exceeds left of the window, position the contents at the left of the visible area
  5978. if (start < 0) {
  5979. contentLeft = Math.min(-start,
  5980. (end - start - props.content.width - 2 * padding));
  5981. // TODO: remove the need for options.padding. it's terrible.
  5982. }
  5983. else {
  5984. contentLeft = 0;
  5985. }
  5986. changed += update(props.content, 'left', contentLeft);
  5987. if (orientation == 'top') {
  5988. top = margin;
  5989. changed += update(this, 'top', top);
  5990. }
  5991. else {
  5992. // default or 'bottom'
  5993. top = parent.height - this.height - margin;
  5994. changed += update(this, 'top', top);
  5995. }
  5996. changed += update(this, 'left', start);
  5997. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  5998. }
  5999. else {
  6000. changed += 1;
  6001. }
  6002. }
  6003. return (changed > 0);
  6004. };
  6005. /**
  6006. * Create an items DOM
  6007. * @private
  6008. */
  6009. ItemRange.prototype._create = function _create() {
  6010. var dom = this.dom;
  6011. if (!dom) {
  6012. this.dom = dom = {};
  6013. // background box
  6014. dom.box = document.createElement('div');
  6015. // className is updated in repaint()
  6016. // contents box
  6017. dom.content = document.createElement('div');
  6018. dom.content.className = 'content';
  6019. dom.box.appendChild(dom.content);
  6020. // attach this item as attribute
  6021. dom.box['timeline-item'] = this;
  6022. }
  6023. };
  6024. /**
  6025. * Reposition the item, recalculate its left, top, and width, using the current
  6026. * range and size of the items itemset
  6027. * @override
  6028. */
  6029. ItemRange.prototype.reposition = function reposition() {
  6030. var dom = this.dom,
  6031. props = this.props;
  6032. if (dom) {
  6033. dom.box.style.top = this.top + 'px';
  6034. dom.box.style.left = this.left + 'px';
  6035. dom.box.style.width = this.width + 'px';
  6036. dom.content.style.left = props.content.left + 'px';
  6037. }
  6038. };
  6039. /**
  6040. * Repaint a drag area on the left side of the range when the range is selected
  6041. * @private
  6042. */
  6043. ItemRange.prototype._repaintDragLeft = function () {
  6044. if (this.selected && this.options.editable && !this.dom.dragLeft) {
  6045. // create and show drag area
  6046. var dragLeft = document.createElement('div');
  6047. dragLeft.className = 'drag-left';
  6048. dragLeft.dragLeftItem = this;
  6049. // TODO: this should be redundant?
  6050. Hammer(dragLeft, {
  6051. preventDefault: true
  6052. }).on('drag', function () {
  6053. //console.log('drag left')
  6054. });
  6055. this.dom.box.appendChild(dragLeft);
  6056. this.dom.dragLeft = dragLeft;
  6057. }
  6058. else if (!this.selected && this.dom.dragLeft) {
  6059. // delete drag area
  6060. if (this.dom.dragLeft.parentNode) {
  6061. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  6062. }
  6063. this.dom.dragLeft = null;
  6064. }
  6065. };
  6066. /**
  6067. * Repaint a drag area on the right side of the range when the range is selected
  6068. * @private
  6069. */
  6070. ItemRange.prototype._repaintDragRight = function () {
  6071. if (this.selected && this.options.editable && !this.dom.dragRight) {
  6072. // create and show drag area
  6073. var dragRight = document.createElement('div');
  6074. dragRight.className = 'drag-right';
  6075. dragRight.dragRightItem = this;
  6076. // TODO: this should be redundant?
  6077. Hammer(dragRight, {
  6078. preventDefault: true
  6079. }).on('drag', function () {
  6080. //console.log('drag right')
  6081. });
  6082. this.dom.box.appendChild(dragRight);
  6083. this.dom.dragRight = dragRight;
  6084. }
  6085. else if (!this.selected && this.dom.dragRight) {
  6086. // delete drag area
  6087. if (this.dom.dragRight.parentNode) {
  6088. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  6089. }
  6090. this.dom.dragRight = null;
  6091. }
  6092. };
  6093. /**
  6094. * @constructor ItemRangeOverflow
  6095. * @extends ItemRange
  6096. * @param {ItemSet} parent
  6097. * @param {Object} data Object containing parameters start, end
  6098. * content, className.
  6099. * @param {Object} [options] Options to set initial property values
  6100. * @param {Object} [defaultOptions] default options
  6101. * // TODO: describe available options
  6102. */
  6103. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  6104. this.props = {
  6105. content: {
  6106. left: 0,
  6107. width: 0
  6108. }
  6109. };
  6110. // define a private property _width, which is the with of the range box
  6111. // adhering to the ranges start and end date. The property width has a
  6112. // getter which returns the max of border width and content width
  6113. this._width = 0;
  6114. Object.defineProperty(this, 'width', {
  6115. get: function () {
  6116. return (this.props.content && this._width < this.props.content.width) ?
  6117. this.props.content.width :
  6118. this._width;
  6119. },
  6120. set: function (width) {
  6121. this._width = width;
  6122. }
  6123. });
  6124. ItemRange.call(this, parent, data, options, defaultOptions);
  6125. }
  6126. ItemRangeOverflow.prototype = new ItemRange (null, null);
  6127. /**
  6128. * Repaint the item
  6129. * @return {Boolean} changed
  6130. */
  6131. ItemRangeOverflow.prototype.repaint = function repaint() {
  6132. // TODO: make an efficient repaint
  6133. var changed = false;
  6134. var dom = this.dom;
  6135. if (!dom) {
  6136. this._create();
  6137. dom = this.dom;
  6138. changed = true;
  6139. }
  6140. if (dom) {
  6141. if (!this.parent) {
  6142. throw new Error('Cannot repaint item: no parent attached');
  6143. }
  6144. var foreground = this.parent.getForeground();
  6145. if (!foreground) {
  6146. throw new Error('Cannot repaint time axis: ' +
  6147. 'parent has no foreground container element');
  6148. }
  6149. if (!dom.box.parentNode) {
  6150. foreground.appendChild(dom.box);
  6151. changed = true;
  6152. }
  6153. // update content
  6154. if (this.data.content != this.content) {
  6155. this.content = this.data.content;
  6156. if (this.content instanceof Element) {
  6157. dom.content.innerHTML = '';
  6158. dom.content.appendChild(this.content);
  6159. }
  6160. else if (this.data.content != undefined) {
  6161. dom.content.innerHTML = this.content;
  6162. }
  6163. else {
  6164. throw new Error('Property "content" missing in item ' + this.id);
  6165. }
  6166. changed = true;
  6167. }
  6168. this._repaintDeleteButton(dom.box);
  6169. this._repaintDragLeft();
  6170. this._repaintDragRight();
  6171. // update class
  6172. var className = (this.data.className? ' ' + this.data.className : '') +
  6173. (this.selected ? ' selected' : '');
  6174. if (this.className != className) {
  6175. this.className = className;
  6176. dom.box.className = 'item rangeoverflow' + className;
  6177. changed = true;
  6178. }
  6179. }
  6180. return changed;
  6181. };
  6182. /**
  6183. * Reposition the item, recalculate its left, top, and width, using the current
  6184. * range and size of the items itemset
  6185. * @override
  6186. */
  6187. ItemRangeOverflow.prototype.reposition = function reposition() {
  6188. var dom = this.dom,
  6189. props = this.props;
  6190. if (dom) {
  6191. dom.box.style.top = this.top + 'px';
  6192. dom.box.style.left = this.left + 'px';
  6193. dom.box.style.width = this._width + 'px';
  6194. dom.content.style.left = props.content.left + 'px';
  6195. }
  6196. };
  6197. /**
  6198. * @constructor Group
  6199. * @param {GroupSet} parent
  6200. * @param {Number | String} groupId
  6201. * @param {Object} [options] Options to set initial property values
  6202. * // TODO: describe available options
  6203. * @extends Component
  6204. */
  6205. function Group (parent, groupId, options) {
  6206. this.id = util.randomUUID();
  6207. this.parent = parent;
  6208. this.groupId = groupId;
  6209. this.itemset = null; // ItemSet
  6210. this.options = options || {};
  6211. this.options.top = 0;
  6212. this.props = {
  6213. label: {
  6214. width: 0,
  6215. height: 0
  6216. }
  6217. };
  6218. this.top = 0;
  6219. this.left = 0;
  6220. this.width = 0;
  6221. this.height = 0;
  6222. }
  6223. Group.prototype = new Component();
  6224. // TODO: comment
  6225. Group.prototype.setOptions = Component.prototype.setOptions;
  6226. /**
  6227. * Get the container element of the panel, which can be used by a child to
  6228. * add its own widgets.
  6229. * @returns {HTMLElement} container
  6230. */
  6231. Group.prototype.getContainer = function () {
  6232. return this.parent.getContainer();
  6233. };
  6234. /**
  6235. * Set item set for the group. The group will create a view on the itemset,
  6236. * filtered by the groups id.
  6237. * @param {DataSet | DataView} items
  6238. */
  6239. Group.prototype.setItems = function setItems(items) {
  6240. if (this.itemset) {
  6241. // remove current item set
  6242. this.itemset.hide();
  6243. this.itemset.setItems();
  6244. this.parent.controller.remove(this.itemset);
  6245. this.itemset = null;
  6246. }
  6247. if (items) {
  6248. var groupId = this.groupId;
  6249. var itemsetOptions = Object.create(this.options);
  6250. this.itemset = new ItemSet(this, null, itemsetOptions);
  6251. this.itemset.setRange(this.parent.range);
  6252. this.view = new DataView(items, {
  6253. filter: function (item) {
  6254. return item.group == groupId;
  6255. }
  6256. });
  6257. this.itemset.setItems(this.view);
  6258. this.parent.controller.add(this.itemset);
  6259. }
  6260. };
  6261. /**
  6262. * Set selected items by their id. Replaces the current selection.
  6263. * Unknown id's are silently ignored.
  6264. * @param {Array} [ids] An array with zero or more id's of the items to be
  6265. * selected. If ids is an empty array, all items will be
  6266. * unselected.
  6267. */
  6268. Group.prototype.setSelection = function setSelection(ids) {
  6269. if (this.itemset) this.itemset.setSelection(ids);
  6270. };
  6271. /**
  6272. * Get the selected items by their id
  6273. * @return {Array} ids The ids of the selected items
  6274. */
  6275. Group.prototype.getSelection = function getSelection() {
  6276. return this.itemset ? this.itemset.getSelection() : [];
  6277. };
  6278. /**
  6279. * Repaint the item
  6280. * @return {Boolean} changed
  6281. */
  6282. Group.prototype.repaint = function repaint() {
  6283. return false;
  6284. };
  6285. /**
  6286. * Reflow the item
  6287. * @return {Boolean} resized
  6288. */
  6289. Group.prototype.reflow = function reflow() {
  6290. var changed = 0,
  6291. update = util.updateProperty;
  6292. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  6293. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  6294. // TODO: reckon with the height of the group label
  6295. if (this.label) {
  6296. var inner = this.label.firstChild;
  6297. changed += update(this.props.label, 'width', inner.clientWidth);
  6298. changed += update(this.props.label, 'height', inner.clientHeight);
  6299. }
  6300. else {
  6301. changed += update(this.props.label, 'width', 0);
  6302. changed += update(this.props.label, 'height', 0);
  6303. }
  6304. return (changed > 0);
  6305. };
  6306. /**
  6307. * An GroupSet holds a set of groups
  6308. * @param {Component} parent
  6309. * @param {Component[]} [depends] Components on which this components depends
  6310. * (except for the parent)
  6311. * @param {Object} [options] See GroupSet.setOptions for the available
  6312. * options.
  6313. * @constructor GroupSet
  6314. * @extends Panel
  6315. */
  6316. function GroupSet(parent, depends, options) {
  6317. this.id = util.randomUUID();
  6318. this.parent = parent;
  6319. this.depends = depends;
  6320. this.options = options || {};
  6321. this.range = null; // Range or Object {start: number, end: number}
  6322. this.itemsData = null; // DataSet with items
  6323. this.groupsData = null; // DataSet with groups
  6324. this.groups = {}; // map with groups
  6325. this.dom = {};
  6326. this.props = {
  6327. labels: {
  6328. width: 0
  6329. }
  6330. };
  6331. // TODO: implement right orientation of the labels
  6332. // changes in groups are queued key/value map containing id/action
  6333. this.queue = {};
  6334. var me = this;
  6335. this.listeners = {
  6336. 'add': function (event, params) {
  6337. me._onAdd(params.items);
  6338. },
  6339. 'update': function (event, params) {
  6340. me._onUpdate(params.items);
  6341. },
  6342. 'remove': function (event, params) {
  6343. me._onRemove(params.items);
  6344. }
  6345. };
  6346. }
  6347. GroupSet.prototype = new Panel();
  6348. /**
  6349. * Set options for the GroupSet. Existing options will be extended/overwritten.
  6350. * @param {Object} [options] The following options are available:
  6351. * {String | function} groupsOrder
  6352. * TODO: describe options
  6353. */
  6354. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  6355. GroupSet.prototype.setRange = function (range) {
  6356. // TODO: implement setRange
  6357. };
  6358. /**
  6359. * Set items
  6360. * @param {vis.DataSet | null} items
  6361. */
  6362. GroupSet.prototype.setItems = function setItems(items) {
  6363. this.itemsData = items;
  6364. for (var id in this.groups) {
  6365. if (this.groups.hasOwnProperty(id)) {
  6366. var group = this.groups[id];
  6367. group.setItems(items);
  6368. }
  6369. }
  6370. };
  6371. /**
  6372. * Get items
  6373. * @return {vis.DataSet | null} items
  6374. */
  6375. GroupSet.prototype.getItems = function getItems() {
  6376. return this.itemsData;
  6377. };
  6378. /**
  6379. * Set range (start and end).
  6380. * @param {Range | Object} range A Range or an object containing start and end.
  6381. */
  6382. GroupSet.prototype.setRange = function setRange(range) {
  6383. this.range = range;
  6384. };
  6385. /**
  6386. * Set groups
  6387. * @param {vis.DataSet} groups
  6388. */
  6389. GroupSet.prototype.setGroups = function setGroups(groups) {
  6390. var me = this,
  6391. ids;
  6392. // unsubscribe from current dataset
  6393. if (this.groupsData) {
  6394. util.forEach(this.listeners, function (callback, event) {
  6395. me.groupsData.unsubscribe(event, callback);
  6396. });
  6397. // remove all drawn groups
  6398. ids = this.groupsData.getIds();
  6399. this._onRemove(ids);
  6400. }
  6401. // replace the dataset
  6402. if (!groups) {
  6403. this.groupsData = null;
  6404. }
  6405. else if (groups instanceof DataSet) {
  6406. this.groupsData = groups;
  6407. }
  6408. else {
  6409. this.groupsData = new DataSet({
  6410. convert: {
  6411. start: 'Date',
  6412. end: 'Date'
  6413. }
  6414. });
  6415. this.groupsData.add(groups);
  6416. }
  6417. if (this.groupsData) {
  6418. // subscribe to new dataset
  6419. var id = this.id;
  6420. util.forEach(this.listeners, function (callback, event) {
  6421. me.groupsData.on(event, callback, id);
  6422. });
  6423. // draw all new groups
  6424. ids = this.groupsData.getIds();
  6425. this._onAdd(ids);
  6426. }
  6427. };
  6428. /**
  6429. * Get groups
  6430. * @return {vis.DataSet | null} groups
  6431. */
  6432. GroupSet.prototype.getGroups = function getGroups() {
  6433. return this.groupsData;
  6434. };
  6435. /**
  6436. * Set selected items by their id. Replaces the current selection.
  6437. * Unknown id's are silently ignored.
  6438. * @param {Array} [ids] An array with zero or more id's of the items to be
  6439. * selected. If ids is an empty array, all items will be
  6440. * unselected.
  6441. */
  6442. GroupSet.prototype.setSelection = function setSelection(ids) {
  6443. var selection = [],
  6444. groups = this.groups;
  6445. // iterate over each of the groups
  6446. for (var id in groups) {
  6447. if (groups.hasOwnProperty(id)) {
  6448. var group = groups[id];
  6449. group.setSelection(ids);
  6450. }
  6451. }
  6452. return selection;
  6453. };
  6454. /**
  6455. * Get the selected items by their id
  6456. * @return {Array} ids The ids of the selected items
  6457. */
  6458. GroupSet.prototype.getSelection = function getSelection() {
  6459. var selection = [],
  6460. groups = this.groups;
  6461. // iterate over each of the groups
  6462. for (var id in groups) {
  6463. if (groups.hasOwnProperty(id)) {
  6464. var group = groups[id];
  6465. selection = selection.concat(group.getSelection());
  6466. }
  6467. }
  6468. return selection;
  6469. };
  6470. /**
  6471. * Repaint the component
  6472. * @return {Boolean} changed
  6473. */
  6474. GroupSet.prototype.repaint = function repaint() {
  6475. var changed = 0,
  6476. i, id, group, label,
  6477. update = util.updateProperty,
  6478. asSize = util.option.asSize,
  6479. asElement = util.option.asElement,
  6480. options = this.options,
  6481. frame = this.dom.frame,
  6482. labels = this.dom.labels,
  6483. labelSet = this.dom.labelSet;
  6484. // create frame
  6485. if (!this.parent) {
  6486. throw new Error('Cannot repaint groupset: no parent attached');
  6487. }
  6488. var parentContainer = this.parent.getContainer();
  6489. if (!parentContainer) {
  6490. throw new Error('Cannot repaint groupset: parent has no container element');
  6491. }
  6492. if (!frame) {
  6493. frame = document.createElement('div');
  6494. frame.className = 'groupset';
  6495. frame['timeline-groupset'] = this;
  6496. this.dom.frame = frame;
  6497. var className = options.className;
  6498. if (className) {
  6499. util.addClassName(frame, util.option.asString(className));
  6500. }
  6501. changed += 1;
  6502. }
  6503. if (!frame.parentNode) {
  6504. parentContainer.appendChild(frame);
  6505. changed += 1;
  6506. }
  6507. // create labels
  6508. var labelContainer = asElement(options.labelContainer);
  6509. if (!labelContainer) {
  6510. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  6511. }
  6512. if (!labels) {
  6513. labels = document.createElement('div');
  6514. labels.className = 'labels';
  6515. this.dom.labels = labels;
  6516. }
  6517. if (!labelSet) {
  6518. labelSet = document.createElement('div');
  6519. labelSet.className = 'label-set';
  6520. labels.appendChild(labelSet);
  6521. this.dom.labelSet = labelSet;
  6522. }
  6523. if (!labels.parentNode || labels.parentNode != labelContainer) {
  6524. if (labels.parentNode) {
  6525. labels.parentNode.removeChild(labels.parentNode);
  6526. }
  6527. labelContainer.appendChild(labels);
  6528. }
  6529. // reposition frame
  6530. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  6531. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6532. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6533. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6534. // reposition labels
  6535. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  6536. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  6537. var me = this,
  6538. queue = this.queue,
  6539. groups = this.groups,
  6540. groupsData = this.groupsData;
  6541. // show/hide added/changed/removed groups
  6542. var ids = Object.keys(queue);
  6543. if (ids.length) {
  6544. ids.forEach(function (id) {
  6545. var action = queue[id];
  6546. var group = groups[id];
  6547. //noinspection FallthroughInSwitchStatementJS
  6548. switch (action) {
  6549. case 'add':
  6550. case 'update':
  6551. if (!group) {
  6552. var groupOptions = Object.create(me.options);
  6553. util.extend(groupOptions, {
  6554. height: null,
  6555. maxHeight: null
  6556. });
  6557. group = new Group(me, id, groupOptions);
  6558. group.setItems(me.itemsData); // attach items data
  6559. groups[id] = group;
  6560. me.controller.add(group);
  6561. }
  6562. // TODO: update group data
  6563. group.data = groupsData.get(id);
  6564. delete queue[id];
  6565. break;
  6566. case 'remove':
  6567. if (group) {
  6568. group.setItems(); // detach items data
  6569. delete groups[id];
  6570. me.controller.remove(group);
  6571. }
  6572. // update lists
  6573. delete queue[id];
  6574. break;
  6575. default:
  6576. console.log('Error: unknown action "' + action + '"');
  6577. }
  6578. });
  6579. // the groupset depends on each of the groups
  6580. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  6581. // TODO: apply dependencies of the groupset
  6582. // update the top positions of the groups in the correct order
  6583. var orderedGroups = this.groupsData.getIds({
  6584. order: this.options.groupOrder
  6585. });
  6586. for (i = 0; i < orderedGroups.length; i++) {
  6587. (function (group, prevGroup) {
  6588. var top = 0;
  6589. if (prevGroup) {
  6590. top = function () {
  6591. // TODO: top must reckon with options.maxHeight
  6592. return prevGroup.top + prevGroup.height;
  6593. }
  6594. }
  6595. group.setOptions({
  6596. top: top
  6597. });
  6598. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  6599. }
  6600. // (re)create the labels
  6601. while (labelSet.firstChild) {
  6602. labelSet.removeChild(labelSet.firstChild);
  6603. }
  6604. for (i = 0; i < orderedGroups.length; i++) {
  6605. id = orderedGroups[i];
  6606. label = this._createLabel(id);
  6607. labelSet.appendChild(label);
  6608. }
  6609. changed++;
  6610. }
  6611. // reposition the labels
  6612. // TODO: labels are not displayed correctly when orientation=='top'
  6613. // TODO: width of labelPanel is not immediately updated on a change in groups
  6614. for (id in groups) {
  6615. if (groups.hasOwnProperty(id)) {
  6616. group = groups[id];
  6617. label = group.label;
  6618. if (label) {
  6619. label.style.top = group.top + 'px';
  6620. label.style.height = group.height + 'px';
  6621. }
  6622. }
  6623. }
  6624. return (changed > 0);
  6625. };
  6626. /**
  6627. * Create a label for group with given id
  6628. * @param {Number} id
  6629. * @return {Element} label
  6630. * @private
  6631. */
  6632. GroupSet.prototype._createLabel = function(id) {
  6633. var group = this.groups[id];
  6634. var label = document.createElement('div');
  6635. label.className = 'vlabel';
  6636. var inner = document.createElement('div');
  6637. inner.className = 'inner';
  6638. label.appendChild(inner);
  6639. var content = group.data && group.data.content;
  6640. if (content instanceof Element) {
  6641. inner.appendChild(content);
  6642. }
  6643. else if (content != undefined) {
  6644. inner.innerHTML = content;
  6645. }
  6646. var className = group.data && group.data.className;
  6647. if (className) {
  6648. util.addClassName(label, className);
  6649. }
  6650. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  6651. return label;
  6652. };
  6653. /**
  6654. * Get container element
  6655. * @return {HTMLElement} container
  6656. */
  6657. GroupSet.prototype.getContainer = function getContainer() {
  6658. return this.dom.frame;
  6659. };
  6660. /**
  6661. * Get the width of the group labels
  6662. * @return {Number} width
  6663. */
  6664. GroupSet.prototype.getLabelsWidth = function getContainer() {
  6665. return this.props.labels.width;
  6666. };
  6667. /**
  6668. * Reflow the component
  6669. * @return {Boolean} resized
  6670. */
  6671. GroupSet.prototype.reflow = function reflow() {
  6672. var changed = 0,
  6673. id, group,
  6674. options = this.options,
  6675. update = util.updateProperty,
  6676. asNumber = util.option.asNumber,
  6677. asSize = util.option.asSize,
  6678. frame = this.dom.frame;
  6679. if (frame) {
  6680. var maxHeight = asNumber(options.maxHeight);
  6681. var fixedHeight = (asSize(options.height) != null);
  6682. var height;
  6683. if (fixedHeight) {
  6684. height = frame.offsetHeight;
  6685. }
  6686. else {
  6687. // height is not specified, calculate the sum of the height of all groups
  6688. height = 0;
  6689. for (id in this.groups) {
  6690. if (this.groups.hasOwnProperty(id)) {
  6691. group = this.groups[id];
  6692. height += group.height;
  6693. }
  6694. }
  6695. }
  6696. if (maxHeight != null) {
  6697. height = Math.min(height, maxHeight);
  6698. }
  6699. changed += update(this, 'height', height);
  6700. changed += update(this, 'top', frame.offsetTop);
  6701. changed += update(this, 'left', frame.offsetLeft);
  6702. changed += update(this, 'width', frame.offsetWidth);
  6703. }
  6704. // calculate the maximum width of the labels
  6705. var width = 0;
  6706. for (id in this.groups) {
  6707. if (this.groups.hasOwnProperty(id)) {
  6708. group = this.groups[id];
  6709. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  6710. width = Math.max(width, labelWidth);
  6711. }
  6712. }
  6713. changed += update(this.props.labels, 'width', width);
  6714. return (changed > 0);
  6715. };
  6716. /**
  6717. * Hide the component from the DOM
  6718. * @return {Boolean} changed
  6719. */
  6720. GroupSet.prototype.hide = function hide() {
  6721. if (this.dom.frame && this.dom.frame.parentNode) {
  6722. this.dom.frame.parentNode.removeChild(this.dom.frame);
  6723. return true;
  6724. }
  6725. else {
  6726. return false;
  6727. }
  6728. };
  6729. /**
  6730. * Show the component in the DOM (when not already visible).
  6731. * A repaint will be executed when the component is not visible
  6732. * @return {Boolean} changed
  6733. */
  6734. GroupSet.prototype.show = function show() {
  6735. if (!this.dom.frame || !this.dom.frame.parentNode) {
  6736. return this.repaint();
  6737. }
  6738. else {
  6739. return false;
  6740. }
  6741. };
  6742. /**
  6743. * Handle updated groups
  6744. * @param {Number[]} ids
  6745. * @private
  6746. */
  6747. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  6748. this._toQueue(ids, 'update');
  6749. };
  6750. /**
  6751. * Handle changed groups
  6752. * @param {Number[]} ids
  6753. * @private
  6754. */
  6755. GroupSet.prototype._onAdd = function _onAdd(ids) {
  6756. this._toQueue(ids, 'add');
  6757. };
  6758. /**
  6759. * Handle removed groups
  6760. * @param {Number[]} ids
  6761. * @private
  6762. */
  6763. GroupSet.prototype._onRemove = function _onRemove(ids) {
  6764. this._toQueue(ids, 'remove');
  6765. };
  6766. /**
  6767. * Put groups in the queue to be added/updated/remove
  6768. * @param {Number[]} ids
  6769. * @param {String} action can be 'add', 'update', 'remove'
  6770. */
  6771. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  6772. var queue = this.queue;
  6773. ids.forEach(function (id) {
  6774. queue[id] = action;
  6775. });
  6776. if (this.controller) {
  6777. //this.requestReflow();
  6778. this.requestRepaint();
  6779. }
  6780. };
  6781. /**
  6782. * Find the Group from an event target:
  6783. * searches for the attribute 'timeline-groupset' in the event target's element
  6784. * tree, then finds the right group in this groupset
  6785. * @param {Event} event
  6786. * @return {Group | null} group
  6787. */
  6788. GroupSet.groupFromTarget = function groupFromTarget (event) {
  6789. var groupset,
  6790. target = event.target;
  6791. while (target) {
  6792. if (target.hasOwnProperty('timeline-groupset')) {
  6793. groupset = target['timeline-groupset'];
  6794. break;
  6795. }
  6796. target = target.parentNode;
  6797. }
  6798. if (groupset) {
  6799. for (var groupId in groupset.groups) {
  6800. if (groupset.groups.hasOwnProperty(groupId)) {
  6801. var group = groupset.groups[groupId];
  6802. if (group.itemset && ItemSet.itemSetFromTarget(event) == group.itemset) {
  6803. return group;
  6804. }
  6805. }
  6806. }
  6807. }
  6808. return null;
  6809. };
  6810. /**
  6811. * Create a timeline visualization
  6812. * @param {HTMLElement} container
  6813. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6814. * @param {Object} [options] See Timeline.setOptions for the available options.
  6815. * @constructor
  6816. */
  6817. function Timeline (container, items, options) {
  6818. var me = this;
  6819. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6820. this.options = {
  6821. orientation: 'bottom',
  6822. autoResize: true,
  6823. editable: false,
  6824. selectable: true,
  6825. snap: null, // will be specified after timeaxis is created
  6826. min: null,
  6827. max: null,
  6828. zoomMin: 10, // milliseconds
  6829. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6830. // moveable: true, // TODO: option moveable
  6831. // zoomable: true, // TODO: option zoomable
  6832. showMinorLabels: true,
  6833. showMajorLabels: true,
  6834. showCurrentTime: false,
  6835. showCustomTime: false,
  6836. onAdd: function (item, callback) {
  6837. callback(item);
  6838. },
  6839. onUpdate: function (item, callback) {
  6840. callback(item);
  6841. },
  6842. onMove: function (item, callback) {
  6843. callback(item);
  6844. },
  6845. onRemove: function (item, callback) {
  6846. callback(item);
  6847. }
  6848. };
  6849. // controller
  6850. this.controller = new Controller();
  6851. // root panel
  6852. if (!container) {
  6853. throw new Error('No container element provided');
  6854. }
  6855. var rootOptions = Object.create(this.options);
  6856. rootOptions.height = function () {
  6857. // TODO: change to height
  6858. if (me.options.height) {
  6859. // fixed height
  6860. return me.options.height;
  6861. }
  6862. else {
  6863. // auto height
  6864. return (me.timeaxis.height + me.content.height) + 'px';
  6865. }
  6866. };
  6867. this.rootPanel = new RootPanel(container, rootOptions);
  6868. this.controller.add(this.rootPanel);
  6869. // single select (or unselect) when tapping an item
  6870. this.controller.on('tap', this._onSelectItem.bind(this));
  6871. // multi select when holding mouse/touch, or on ctrl+click
  6872. this.controller.on('hold', this._onMultiSelectItem.bind(this));
  6873. // add item on doubletap
  6874. this.controller.on('doubletap', this._onAddItem.bind(this));
  6875. // item panel
  6876. var itemOptions = Object.create(this.options);
  6877. itemOptions.left = function () {
  6878. return me.labelPanel.width;
  6879. };
  6880. itemOptions.width = function () {
  6881. return me.rootPanel.width - me.labelPanel.width;
  6882. };
  6883. itemOptions.top = null;
  6884. itemOptions.height = null;
  6885. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  6886. this.controller.add(this.itemPanel);
  6887. // label panel
  6888. var labelOptions = Object.create(this.options);
  6889. labelOptions.top = null;
  6890. labelOptions.left = null;
  6891. labelOptions.height = null;
  6892. labelOptions.width = function () {
  6893. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  6894. return me.content.getLabelsWidth();
  6895. }
  6896. else {
  6897. return 0;
  6898. }
  6899. };
  6900. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  6901. this.controller.add(this.labelPanel);
  6902. // range
  6903. var rangeOptions = Object.create(this.options);
  6904. this.range = new Range(rangeOptions);
  6905. this.range.setRange(
  6906. now.clone().add('days', -3).valueOf(),
  6907. now.clone().add('days', 4).valueOf()
  6908. );
  6909. this.range.subscribe(this.controller, this.rootPanel, 'move', 'horizontal');
  6910. this.range.subscribe(this.controller, this.rootPanel, 'zoom', 'horizontal');
  6911. this.range.on('rangechange', function (properties) {
  6912. var force = true;
  6913. me.controller.emit('rangechange', properties);
  6914. me.controller.emit('request-reflow', force);
  6915. });
  6916. this.range.on('rangechanged', function (properties) {
  6917. var force = true;
  6918. me.controller.emit('rangechanged', properties);
  6919. me.controller.emit('request-reflow', force);
  6920. });
  6921. // time axis
  6922. var timeaxisOptions = Object.create(rootOptions);
  6923. timeaxisOptions.range = this.range;
  6924. timeaxisOptions.left = null;
  6925. timeaxisOptions.top = null;
  6926. timeaxisOptions.width = '100%';
  6927. timeaxisOptions.height = null;
  6928. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6929. this.timeaxis.setRange(this.range);
  6930. this.controller.add(this.timeaxis);
  6931. this.options.snap = this.timeaxis.snap.bind(this.timeaxis);
  6932. // current time bar
  6933. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  6934. this.controller.add(this.currenttime);
  6935. // custom time bar
  6936. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  6937. this.controller.add(this.customtime);
  6938. // create groupset
  6939. this.setGroups(null);
  6940. this.itemsData = null; // DataSet
  6941. this.groupsData = null; // DataSet
  6942. // apply options
  6943. if (options) {
  6944. this.setOptions(options);
  6945. }
  6946. // create itemset and groupset
  6947. if (items) {
  6948. this.setItems(items);
  6949. }
  6950. }
  6951. /**
  6952. * Add an event listener to the timeline
  6953. * @param {String} event Available events: select, rangechange, rangechanged,
  6954. * timechange, timechanged
  6955. * @param {function} callback
  6956. */
  6957. Timeline.prototype.on = function on (event, callback) {
  6958. this.controller.on(event, callback);
  6959. };
  6960. /**
  6961. * Add an event listener from the timeline
  6962. * @param {String} event
  6963. * @param {function} callback
  6964. */
  6965. Timeline.prototype.off = function off (event, callback) {
  6966. this.controller.off(event, callback);
  6967. };
  6968. /**
  6969. * Set options
  6970. * @param {Object} options TODO: describe the available options
  6971. */
  6972. Timeline.prototype.setOptions = function (options) {
  6973. util.extend(this.options, options);
  6974. // force update of range (apply new min/max etc.)
  6975. // both start and end are optional
  6976. this.range.setRange(options.start, options.end);
  6977. if ('editable' in options || 'selectable' in options) {
  6978. if (this.options.selectable) {
  6979. // force update of selection
  6980. this.setSelection(this.getSelection());
  6981. }
  6982. else {
  6983. // remove selection
  6984. this.setSelection([]);
  6985. }
  6986. }
  6987. // validate the callback functions
  6988. var validateCallback = (function (fn) {
  6989. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  6990. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  6991. }
  6992. }).bind(this);
  6993. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  6994. this.controller.reflow();
  6995. this.controller.repaint();
  6996. };
  6997. /**
  6998. * Set a custom time bar
  6999. * @param {Date} time
  7000. */
  7001. Timeline.prototype.setCustomTime = function (time) {
  7002. if (!this.customtime) {
  7003. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  7004. }
  7005. this.customtime.setCustomTime(time);
  7006. };
  7007. /**
  7008. * Retrieve the current custom time.
  7009. * @return {Date} customTime
  7010. */
  7011. Timeline.prototype.getCustomTime = function() {
  7012. if (!this.customtime) {
  7013. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  7014. }
  7015. return this.customtime.getCustomTime();
  7016. };
  7017. /**
  7018. * Set items
  7019. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  7020. */
  7021. Timeline.prototype.setItems = function(items) {
  7022. var initialLoad = (this.itemsData == null);
  7023. // convert to type DataSet when needed
  7024. var newDataSet;
  7025. if (!items) {
  7026. newDataSet = null;
  7027. }
  7028. else if (items instanceof DataSet) {
  7029. newDataSet = items;
  7030. }
  7031. if (!(items instanceof DataSet)) {
  7032. newDataSet = new DataSet({
  7033. convert: {
  7034. start: 'Date',
  7035. end: 'Date'
  7036. }
  7037. });
  7038. newDataSet.add(items);
  7039. }
  7040. // set items
  7041. this.itemsData = newDataSet;
  7042. this.content.setItems(newDataSet);
  7043. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  7044. // apply the data range as range
  7045. var dataRange = this.getItemRange();
  7046. // add 5% space on both sides
  7047. var start = dataRange.min;
  7048. var end = dataRange.max;
  7049. if (start != null && end != null) {
  7050. var interval = (end.valueOf() - start.valueOf());
  7051. if (interval <= 0) {
  7052. // prevent an empty interval
  7053. interval = 24 * 60 * 60 * 1000; // 1 day
  7054. }
  7055. start = new Date(start.valueOf() - interval * 0.05);
  7056. end = new Date(end.valueOf() + interval * 0.05);
  7057. }
  7058. // override specified start and/or end date
  7059. if (this.options.start != undefined) {
  7060. start = util.convert(this.options.start, 'Date');
  7061. }
  7062. if (this.options.end != undefined) {
  7063. end = util.convert(this.options.end, 'Date');
  7064. }
  7065. // apply range if there is a min or max available
  7066. if (start != null || end != null) {
  7067. this.range.setRange(start, end);
  7068. }
  7069. }
  7070. };
  7071. /**
  7072. * Set groups
  7073. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  7074. */
  7075. Timeline.prototype.setGroups = function(groups) {
  7076. var me = this;
  7077. this.groupsData = groups;
  7078. // switch content type between ItemSet or GroupSet when needed
  7079. var Type = this.groupsData ? GroupSet : ItemSet;
  7080. if (!(this.content instanceof Type)) {
  7081. // remove old content set
  7082. if (this.content) {
  7083. this.content.hide();
  7084. if (this.content.setItems) {
  7085. this.content.setItems(); // disconnect from items
  7086. }
  7087. if (this.content.setGroups) {
  7088. this.content.setGroups(); // disconnect from groups
  7089. }
  7090. this.controller.remove(this.content);
  7091. }
  7092. // create new content set
  7093. var options = Object.create(this.options);
  7094. util.extend(options, {
  7095. top: function () {
  7096. if (me.options.orientation == 'top') {
  7097. return me.timeaxis.height;
  7098. }
  7099. else {
  7100. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  7101. }
  7102. },
  7103. left: null,
  7104. width: '100%',
  7105. height: function () {
  7106. if (me.options.height) {
  7107. // fixed height
  7108. return me.itemPanel.height - me.timeaxis.height;
  7109. }
  7110. else {
  7111. // auto height
  7112. return null;
  7113. }
  7114. },
  7115. maxHeight: function () {
  7116. // TODO: change maxHeight to be a css string like '100%' or '300px'
  7117. if (me.options.maxHeight) {
  7118. if (!util.isNumber(me.options.maxHeight)) {
  7119. throw new TypeError('Number expected for property maxHeight');
  7120. }
  7121. return me.options.maxHeight - me.timeaxis.height;
  7122. }
  7123. else {
  7124. return null;
  7125. }
  7126. },
  7127. labelContainer: function () {
  7128. return me.labelPanel.getContainer();
  7129. }
  7130. });
  7131. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  7132. if (this.content.setRange) {
  7133. this.content.setRange(this.range);
  7134. }
  7135. if (this.content.setItems) {
  7136. this.content.setItems(this.itemsData);
  7137. }
  7138. if (this.content.setGroups) {
  7139. this.content.setGroups(this.groupsData);
  7140. }
  7141. this.controller.add(this.content);
  7142. }
  7143. };
  7144. /**
  7145. * Get the data range of the item set.
  7146. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  7147. * When no minimum is found, min==null
  7148. * When no maximum is found, max==null
  7149. */
  7150. Timeline.prototype.getItemRange = function getItemRange() {
  7151. // calculate min from start filed
  7152. var itemsData = this.itemsData,
  7153. min = null,
  7154. max = null;
  7155. if (itemsData) {
  7156. // calculate the minimum value of the field 'start'
  7157. var minItem = itemsData.min('start');
  7158. min = minItem ? minItem.start.valueOf() : null;
  7159. // calculate maximum value of fields 'start' and 'end'
  7160. var maxStartItem = itemsData.max('start');
  7161. if (maxStartItem) {
  7162. max = maxStartItem.start.valueOf();
  7163. }
  7164. var maxEndItem = itemsData.max('end');
  7165. if (maxEndItem) {
  7166. if (max == null) {
  7167. max = maxEndItem.end.valueOf();
  7168. }
  7169. else {
  7170. max = Math.max(max, maxEndItem.end.valueOf());
  7171. }
  7172. }
  7173. }
  7174. return {
  7175. min: (min != null) ? new Date(min) : null,
  7176. max: (max != null) ? new Date(max) : null
  7177. };
  7178. };
  7179. /**
  7180. * Set selected items by their id. Replaces the current selection
  7181. * Unknown id's are silently ignored.
  7182. * @param {Array} [ids] An array with zero or more id's of the items to be
  7183. * selected. If ids is an empty array, all items will be
  7184. * unselected.
  7185. */
  7186. Timeline.prototype.setSelection = function setSelection (ids) {
  7187. if (this.content) this.content.setSelection(ids);
  7188. };
  7189. /**
  7190. * Get the selected items by their id
  7191. * @return {Array} ids The ids of the selected items
  7192. */
  7193. Timeline.prototype.getSelection = function getSelection() {
  7194. return this.content ? this.content.getSelection() : [];
  7195. };
  7196. /**
  7197. * Set the visible window. Both parameters are optional, you can change only
  7198. * start or only end.
  7199. * @param {Date | Number | String} [start] Start date of visible window
  7200. * @param {Date | Number | String} [end] End date of visible window
  7201. */
  7202. Timeline.prototype.setWindow = function setWindow(start, end) {
  7203. this.range.setRange(start, end);
  7204. };
  7205. /**
  7206. * Get the visible window
  7207. * @return {{start: Date, end: Date}} Visible range
  7208. */
  7209. Timeline.prototype.getWindow = function setWindow() {
  7210. var range = this.range.getRange();
  7211. return {
  7212. start: new Date(range.start),
  7213. end: new Date(range.end)
  7214. };
  7215. };
  7216. /**
  7217. * Handle selecting/deselecting an item when tapping it
  7218. * @param {Event} event
  7219. * @private
  7220. */
  7221. // TODO: move this function to ItemSet
  7222. Timeline.prototype._onSelectItem = function (event) {
  7223. if (!this.options.selectable) return;
  7224. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  7225. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  7226. if (ctrlKey || shiftKey) {
  7227. this._onMultiSelectItem(event);
  7228. return;
  7229. }
  7230. var item = ItemSet.itemFromTarget(event);
  7231. var selection = item ? [item.id] : [];
  7232. this.setSelection(selection);
  7233. this.controller.emit('select', {
  7234. items: this.getSelection()
  7235. });
  7236. event.stopPropagation();
  7237. };
  7238. /**
  7239. * Handle creation and updates of an item on double tap
  7240. * @param event
  7241. * @private
  7242. */
  7243. Timeline.prototype._onAddItem = function (event) {
  7244. if (!this.options.selectable) return;
  7245. if (!this.options.editable) return;
  7246. var me = this,
  7247. item = ItemSet.itemFromTarget(event);
  7248. if (item) {
  7249. // update item
  7250. // execute async handler to update the item (or cancel it)
  7251. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  7252. this.options.onUpdate(itemData, function (itemData) {
  7253. if (itemData) {
  7254. me.itemsData.update(itemData);
  7255. }
  7256. });
  7257. }
  7258. else {
  7259. // add item
  7260. var xAbs = vis.util.getAbsoluteLeft(this.rootPanel.frame);
  7261. var x = event.gesture.center.pageX - xAbs;
  7262. var newItem = {
  7263. start: this.timeaxis.snap(this._toTime(x)),
  7264. content: 'new item'
  7265. };
  7266. var id = util.randomUUID();
  7267. newItem[this.itemsData.fieldId] = id;
  7268. var group = GroupSet.groupFromTarget(event);
  7269. if (group) {
  7270. newItem.group = group.groupId;
  7271. }
  7272. // execute async handler to customize (or cancel) adding an item
  7273. this.options.onAdd(newItem, function (item) {
  7274. if (item) {
  7275. me.itemsData.add(newItem);
  7276. // select the created item after it is repainted
  7277. me.controller.once('repaint', function () {
  7278. me.setSelection([id]);
  7279. me.controller.emit('select', {
  7280. items: me.getSelection()
  7281. });
  7282. }.bind(me));
  7283. }
  7284. });
  7285. }
  7286. };
  7287. /**
  7288. * Handle selecting/deselecting multiple items when holding an item
  7289. * @param {Event} event
  7290. * @private
  7291. */
  7292. // TODO: move this function to ItemSet
  7293. Timeline.prototype._onMultiSelectItem = function (event) {
  7294. if (!this.options.selectable) return;
  7295. var selection,
  7296. item = ItemSet.itemFromTarget(event);
  7297. if (item) {
  7298. // multi select items
  7299. selection = this.getSelection(); // current selection
  7300. var index = selection.indexOf(item.id);
  7301. if (index == -1) {
  7302. // item is not yet selected -> select it
  7303. selection.push(item.id);
  7304. }
  7305. else {
  7306. // item is already selected -> deselect it
  7307. selection.splice(index, 1);
  7308. }
  7309. this.setSelection(selection);
  7310. this.controller.emit('select', {
  7311. items: this.getSelection()
  7312. });
  7313. event.stopPropagation();
  7314. }
  7315. };
  7316. /**
  7317. * Convert a position on screen (pixels) to a datetime
  7318. * @param {int} x Position on the screen in pixels
  7319. * @return {Date} time The datetime the corresponds with given position x
  7320. * @private
  7321. */
  7322. Timeline.prototype._toTime = function _toTime(x) {
  7323. var conversion = this.range.conversion(this.content.width);
  7324. return new Date(x / conversion.scale + conversion.offset);
  7325. };
  7326. /**
  7327. * Convert a datetime (Date object) into a position on the screen
  7328. * @param {Date} time A date
  7329. * @return {int} x The position on the screen in pixels which corresponds
  7330. * with the given date.
  7331. * @private
  7332. */
  7333. Timeline.prototype._toScreen = function _toScreen(time) {
  7334. var conversion = this.range.conversion(this.content.width);
  7335. return (time.valueOf() - conversion.offset) * conversion.scale;
  7336. };
  7337. (function(exports) {
  7338. /**
  7339. * Parse a text source containing data in DOT language into a JSON object.
  7340. * The object contains two lists: one with nodes and one with edges.
  7341. *
  7342. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  7343. *
  7344. * @param {String} data Text containing a graph in DOT-notation
  7345. * @return {Object} graph An object containing two parameters:
  7346. * {Object[]} nodes
  7347. * {Object[]} edges
  7348. */
  7349. function parseDOT (data) {
  7350. dot = data;
  7351. return parseGraph();
  7352. }
  7353. // token types enumeration
  7354. var TOKENTYPE = {
  7355. NULL : 0,
  7356. DELIMITER : 1,
  7357. IDENTIFIER: 2,
  7358. UNKNOWN : 3
  7359. };
  7360. // map with all delimiters
  7361. var DELIMITERS = {
  7362. '{': true,
  7363. '}': true,
  7364. '[': true,
  7365. ']': true,
  7366. ';': true,
  7367. '=': true,
  7368. ',': true,
  7369. '->': true,
  7370. '--': true
  7371. };
  7372. var dot = ''; // current dot file
  7373. var index = 0; // current index in dot file
  7374. var c = ''; // current token character in expr
  7375. var token = ''; // current token
  7376. var tokenType = TOKENTYPE.NULL; // type of the token
  7377. /**
  7378. * Get the first character from the dot file.
  7379. * The character is stored into the char c. If the end of the dot file is
  7380. * reached, the function puts an empty string in c.
  7381. */
  7382. function first() {
  7383. index = 0;
  7384. c = dot.charAt(0);
  7385. }
  7386. /**
  7387. * Get the next character from the dot file.
  7388. * The character is stored into the char c. If the end of the dot file is
  7389. * reached, the function puts an empty string in c.
  7390. */
  7391. function next() {
  7392. index++;
  7393. c = dot.charAt(index);
  7394. }
  7395. /**
  7396. * Preview the next character from the dot file.
  7397. * @return {String} cNext
  7398. */
  7399. function nextPreview() {
  7400. return dot.charAt(index + 1);
  7401. }
  7402. /**
  7403. * Test whether given character is alphabetic or numeric
  7404. * @param {String} c
  7405. * @return {Boolean} isAlphaNumeric
  7406. */
  7407. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  7408. function isAlphaNumeric(c) {
  7409. return regexAlphaNumeric.test(c);
  7410. }
  7411. /**
  7412. * Merge all properties of object b into object b
  7413. * @param {Object} a
  7414. * @param {Object} b
  7415. * @return {Object} a
  7416. */
  7417. function merge (a, b) {
  7418. if (!a) {
  7419. a = {};
  7420. }
  7421. if (b) {
  7422. for (var name in b) {
  7423. if (b.hasOwnProperty(name)) {
  7424. a[name] = b[name];
  7425. }
  7426. }
  7427. }
  7428. return a;
  7429. }
  7430. /**
  7431. * Set a value in an object, where the provided parameter name can be a
  7432. * path with nested parameters. For example:
  7433. *
  7434. * var obj = {a: 2};
  7435. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  7436. *
  7437. * @param {Object} obj
  7438. * @param {String} path A parameter name or dot-separated parameter path,
  7439. * like "color.highlight.border".
  7440. * @param {*} value
  7441. */
  7442. function setValue(obj, path, value) {
  7443. var keys = path.split('.');
  7444. var o = obj;
  7445. while (keys.length) {
  7446. var key = keys.shift();
  7447. if (keys.length) {
  7448. // this isn't the end point
  7449. if (!o[key]) {
  7450. o[key] = {};
  7451. }
  7452. o = o[key];
  7453. }
  7454. else {
  7455. // this is the end point
  7456. o[key] = value;
  7457. }
  7458. }
  7459. }
  7460. /**
  7461. * Add a node to a graph object. If there is already a node with
  7462. * the same id, their attributes will be merged.
  7463. * @param {Object} graph
  7464. * @param {Object} node
  7465. */
  7466. function addNode(graph, node) {
  7467. var i, len;
  7468. var current = null;
  7469. // find root graph (in case of subgraph)
  7470. var graphs = [graph]; // list with all graphs from current graph to root graph
  7471. var root = graph;
  7472. while (root.parent) {
  7473. graphs.push(root.parent);
  7474. root = root.parent;
  7475. }
  7476. // find existing node (at root level) by its id
  7477. if (root.nodes) {
  7478. for (i = 0, len = root.nodes.length; i < len; i++) {
  7479. if (node.id === root.nodes[i].id) {
  7480. current = root.nodes[i];
  7481. break;
  7482. }
  7483. }
  7484. }
  7485. if (!current) {
  7486. // this is a new node
  7487. current = {
  7488. id: node.id
  7489. };
  7490. if (graph.node) {
  7491. // clone default attributes
  7492. current.attr = merge(current.attr, graph.node);
  7493. }
  7494. }
  7495. // add node to this (sub)graph and all its parent graphs
  7496. for (i = graphs.length - 1; i >= 0; i--) {
  7497. var g = graphs[i];
  7498. if (!g.nodes) {
  7499. g.nodes = [];
  7500. }
  7501. if (g.nodes.indexOf(current) == -1) {
  7502. g.nodes.push(current);
  7503. }
  7504. }
  7505. // merge attributes
  7506. if (node.attr) {
  7507. current.attr = merge(current.attr, node.attr);
  7508. }
  7509. }
  7510. /**
  7511. * Add an edge to a graph object
  7512. * @param {Object} graph
  7513. * @param {Object} edge
  7514. */
  7515. function addEdge(graph, edge) {
  7516. if (!graph.edges) {
  7517. graph.edges = [];
  7518. }
  7519. graph.edges.push(edge);
  7520. if (graph.edge) {
  7521. var attr = merge({}, graph.edge); // clone default attributes
  7522. edge.attr = merge(attr, edge.attr); // merge attributes
  7523. }
  7524. }
  7525. /**
  7526. * Create an edge to a graph object
  7527. * @param {Object} graph
  7528. * @param {String | Number | Object} from
  7529. * @param {String | Number | Object} to
  7530. * @param {String} type
  7531. * @param {Object | null} attr
  7532. * @return {Object} edge
  7533. */
  7534. function createEdge(graph, from, to, type, attr) {
  7535. var edge = {
  7536. from: from,
  7537. to: to,
  7538. type: type
  7539. };
  7540. if (graph.edge) {
  7541. edge.attr = merge({}, graph.edge); // clone default attributes
  7542. }
  7543. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7544. return edge;
  7545. }
  7546. /**
  7547. * Get next token in the current dot file.
  7548. * The token and token type are available as token and tokenType
  7549. */
  7550. function getToken() {
  7551. tokenType = TOKENTYPE.NULL;
  7552. token = '';
  7553. // skip over whitespaces
  7554. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7555. next();
  7556. }
  7557. do {
  7558. var isComment = false;
  7559. // skip comment
  7560. if (c == '#') {
  7561. // find the previous non-space character
  7562. var i = index - 1;
  7563. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7564. i--;
  7565. }
  7566. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7567. // the # is at the start of a line, this is indeed a line comment
  7568. while (c != '' && c != '\n') {
  7569. next();
  7570. }
  7571. isComment = true;
  7572. }
  7573. }
  7574. if (c == '/' && nextPreview() == '/') {
  7575. // skip line comment
  7576. while (c != '' && c != '\n') {
  7577. next();
  7578. }
  7579. isComment = true;
  7580. }
  7581. if (c == '/' && nextPreview() == '*') {
  7582. // skip block comment
  7583. while (c != '') {
  7584. if (c == '*' && nextPreview() == '/') {
  7585. // end of block comment found. skip these last two characters
  7586. next();
  7587. next();
  7588. break;
  7589. }
  7590. else {
  7591. next();
  7592. }
  7593. }
  7594. isComment = true;
  7595. }
  7596. // skip over whitespaces
  7597. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7598. next();
  7599. }
  7600. }
  7601. while (isComment);
  7602. // check for end of dot file
  7603. if (c == '') {
  7604. // token is still empty
  7605. tokenType = TOKENTYPE.DELIMITER;
  7606. return;
  7607. }
  7608. // check for delimiters consisting of 2 characters
  7609. var c2 = c + nextPreview();
  7610. if (DELIMITERS[c2]) {
  7611. tokenType = TOKENTYPE.DELIMITER;
  7612. token = c2;
  7613. next();
  7614. next();
  7615. return;
  7616. }
  7617. // check for delimiters consisting of 1 character
  7618. if (DELIMITERS[c]) {
  7619. tokenType = TOKENTYPE.DELIMITER;
  7620. token = c;
  7621. next();
  7622. return;
  7623. }
  7624. // check for an identifier (number or string)
  7625. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7626. if (isAlphaNumeric(c) || c == '-') {
  7627. token += c;
  7628. next();
  7629. while (isAlphaNumeric(c)) {
  7630. token += c;
  7631. next();
  7632. }
  7633. if (token == 'false') {
  7634. token = false; // convert to boolean
  7635. }
  7636. else if (token == 'true') {
  7637. token = true; // convert to boolean
  7638. }
  7639. else if (!isNaN(Number(token))) {
  7640. token = Number(token); // convert to number
  7641. }
  7642. tokenType = TOKENTYPE.IDENTIFIER;
  7643. return;
  7644. }
  7645. // check for a string enclosed by double quotes
  7646. if (c == '"') {
  7647. next();
  7648. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7649. token += c;
  7650. if (c == '"') { // skip the escape character
  7651. next();
  7652. }
  7653. next();
  7654. }
  7655. if (c != '"') {
  7656. throw newSyntaxError('End of string " expected');
  7657. }
  7658. next();
  7659. tokenType = TOKENTYPE.IDENTIFIER;
  7660. return;
  7661. }
  7662. // something unknown is found, wrong characters, a syntax error
  7663. tokenType = TOKENTYPE.UNKNOWN;
  7664. while (c != '') {
  7665. token += c;
  7666. next();
  7667. }
  7668. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7669. }
  7670. /**
  7671. * Parse a graph.
  7672. * @returns {Object} graph
  7673. */
  7674. function parseGraph() {
  7675. var graph = {};
  7676. first();
  7677. getToken();
  7678. // optional strict keyword
  7679. if (token == 'strict') {
  7680. graph.strict = true;
  7681. getToken();
  7682. }
  7683. // graph or digraph keyword
  7684. if (token == 'graph' || token == 'digraph') {
  7685. graph.type = token;
  7686. getToken();
  7687. }
  7688. // optional graph id
  7689. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7690. graph.id = token;
  7691. getToken();
  7692. }
  7693. // open angle bracket
  7694. if (token != '{') {
  7695. throw newSyntaxError('Angle bracket { expected');
  7696. }
  7697. getToken();
  7698. // statements
  7699. parseStatements(graph);
  7700. // close angle bracket
  7701. if (token != '}') {
  7702. throw newSyntaxError('Angle bracket } expected');
  7703. }
  7704. getToken();
  7705. // end of file
  7706. if (token !== '') {
  7707. throw newSyntaxError('End of file expected');
  7708. }
  7709. getToken();
  7710. // remove temporary default properties
  7711. delete graph.node;
  7712. delete graph.edge;
  7713. delete graph.graph;
  7714. return graph;
  7715. }
  7716. /**
  7717. * Parse a list with statements.
  7718. * @param {Object} graph
  7719. */
  7720. function parseStatements (graph) {
  7721. while (token !== '' && token != '}') {
  7722. parseStatement(graph);
  7723. if (token == ';') {
  7724. getToken();
  7725. }
  7726. }
  7727. }
  7728. /**
  7729. * Parse a single statement. Can be a an attribute statement, node
  7730. * statement, a series of node statements and edge statements, or a
  7731. * parameter.
  7732. * @param {Object} graph
  7733. */
  7734. function parseStatement(graph) {
  7735. // parse subgraph
  7736. var subgraph = parseSubgraph(graph);
  7737. if (subgraph) {
  7738. // edge statements
  7739. parseEdge(graph, subgraph);
  7740. return;
  7741. }
  7742. // parse an attribute statement
  7743. var attr = parseAttributeStatement(graph);
  7744. if (attr) {
  7745. return;
  7746. }
  7747. // parse node
  7748. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7749. throw newSyntaxError('Identifier expected');
  7750. }
  7751. var id = token; // id can be a string or a number
  7752. getToken();
  7753. if (token == '=') {
  7754. // id statement
  7755. getToken();
  7756. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7757. throw newSyntaxError('Identifier expected');
  7758. }
  7759. graph[id] = token;
  7760. getToken();
  7761. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7762. }
  7763. else {
  7764. parseNodeStatement(graph, id);
  7765. }
  7766. }
  7767. /**
  7768. * Parse a subgraph
  7769. * @param {Object} graph parent graph object
  7770. * @return {Object | null} subgraph
  7771. */
  7772. function parseSubgraph (graph) {
  7773. var subgraph = null;
  7774. // optional subgraph keyword
  7775. if (token == 'subgraph') {
  7776. subgraph = {};
  7777. subgraph.type = 'subgraph';
  7778. getToken();
  7779. // optional graph id
  7780. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7781. subgraph.id = token;
  7782. getToken();
  7783. }
  7784. }
  7785. // open angle bracket
  7786. if (token == '{') {
  7787. getToken();
  7788. if (!subgraph) {
  7789. subgraph = {};
  7790. }
  7791. subgraph.parent = graph;
  7792. subgraph.node = graph.node;
  7793. subgraph.edge = graph.edge;
  7794. subgraph.graph = graph.graph;
  7795. // statements
  7796. parseStatements(subgraph);
  7797. // close angle bracket
  7798. if (token != '}') {
  7799. throw newSyntaxError('Angle bracket } expected');
  7800. }
  7801. getToken();
  7802. // remove temporary default properties
  7803. delete subgraph.node;
  7804. delete subgraph.edge;
  7805. delete subgraph.graph;
  7806. delete subgraph.parent;
  7807. // register at the parent graph
  7808. if (!graph.subgraphs) {
  7809. graph.subgraphs = [];
  7810. }
  7811. graph.subgraphs.push(subgraph);
  7812. }
  7813. return subgraph;
  7814. }
  7815. /**
  7816. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7817. * Available keywords are 'node', 'edge', 'graph'.
  7818. * The previous list with default attributes will be replaced
  7819. * @param {Object} graph
  7820. * @returns {String | null} keyword Returns the name of the parsed attribute
  7821. * (node, edge, graph), or null if nothing
  7822. * is parsed.
  7823. */
  7824. function parseAttributeStatement (graph) {
  7825. // attribute statements
  7826. if (token == 'node') {
  7827. getToken();
  7828. // node attributes
  7829. graph.node = parseAttributeList();
  7830. return 'node';
  7831. }
  7832. else if (token == 'edge') {
  7833. getToken();
  7834. // edge attributes
  7835. graph.edge = parseAttributeList();
  7836. return 'edge';
  7837. }
  7838. else if (token == 'graph') {
  7839. getToken();
  7840. // graph attributes
  7841. graph.graph = parseAttributeList();
  7842. return 'graph';
  7843. }
  7844. return null;
  7845. }
  7846. /**
  7847. * parse a node statement
  7848. * @param {Object} graph
  7849. * @param {String | Number} id
  7850. */
  7851. function parseNodeStatement(graph, id) {
  7852. // node statement
  7853. var node = {
  7854. id: id
  7855. };
  7856. var attr = parseAttributeList();
  7857. if (attr) {
  7858. node.attr = attr;
  7859. }
  7860. addNode(graph, node);
  7861. // edge statements
  7862. parseEdge(graph, id);
  7863. }
  7864. /**
  7865. * Parse an edge or a series of edges
  7866. * @param {Object} graph
  7867. * @param {String | Number} from Id of the from node
  7868. */
  7869. function parseEdge(graph, from) {
  7870. while (token == '->' || token == '--') {
  7871. var to;
  7872. var type = token;
  7873. getToken();
  7874. var subgraph = parseSubgraph(graph);
  7875. if (subgraph) {
  7876. to = subgraph;
  7877. }
  7878. else {
  7879. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7880. throw newSyntaxError('Identifier or subgraph expected');
  7881. }
  7882. to = token;
  7883. addNode(graph, {
  7884. id: to
  7885. });
  7886. getToken();
  7887. }
  7888. // parse edge attributes
  7889. var attr = parseAttributeList();
  7890. // create edge
  7891. var edge = createEdge(graph, from, to, type, attr);
  7892. addEdge(graph, edge);
  7893. from = to;
  7894. }
  7895. }
  7896. /**
  7897. * Parse a set with attributes,
  7898. * for example [label="1.000", shape=solid]
  7899. * @return {Object | null} attr
  7900. */
  7901. function parseAttributeList() {
  7902. var attr = null;
  7903. while (token == '[') {
  7904. getToken();
  7905. attr = {};
  7906. while (token !== '' && token != ']') {
  7907. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7908. throw newSyntaxError('Attribute name expected');
  7909. }
  7910. var name = token;
  7911. getToken();
  7912. if (token != '=') {
  7913. throw newSyntaxError('Equal sign = expected');
  7914. }
  7915. getToken();
  7916. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7917. throw newSyntaxError('Attribute value expected');
  7918. }
  7919. var value = token;
  7920. setValue(attr, name, value); // name can be a path
  7921. getToken();
  7922. if (token ==',') {
  7923. getToken();
  7924. }
  7925. }
  7926. if (token != ']') {
  7927. throw newSyntaxError('Bracket ] expected');
  7928. }
  7929. getToken();
  7930. }
  7931. return attr;
  7932. }
  7933. /**
  7934. * Create a syntax error with extra information on current token and index.
  7935. * @param {String} message
  7936. * @returns {SyntaxError} err
  7937. */
  7938. function newSyntaxError(message) {
  7939. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7940. }
  7941. /**
  7942. * Chop off text after a maximum length
  7943. * @param {String} text
  7944. * @param {Number} maxLength
  7945. * @returns {String}
  7946. */
  7947. function chop (text, maxLength) {
  7948. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7949. }
  7950. /**
  7951. * Execute a function fn for each pair of elements in two arrays
  7952. * @param {Array | *} array1
  7953. * @param {Array | *} array2
  7954. * @param {function} fn
  7955. */
  7956. function forEach2(array1, array2, fn) {
  7957. if (array1 instanceof Array) {
  7958. array1.forEach(function (elem1) {
  7959. if (array2 instanceof Array) {
  7960. array2.forEach(function (elem2) {
  7961. fn(elem1, elem2);
  7962. });
  7963. }
  7964. else {
  7965. fn(elem1, array2);
  7966. }
  7967. });
  7968. }
  7969. else {
  7970. if (array2 instanceof Array) {
  7971. array2.forEach(function (elem2) {
  7972. fn(array1, elem2);
  7973. });
  7974. }
  7975. else {
  7976. fn(array1, array2);
  7977. }
  7978. }
  7979. }
  7980. /**
  7981. * Convert a string containing a graph in DOT language into a map containing
  7982. * with nodes and edges in the format of graph.
  7983. * @param {String} data Text containing a graph in DOT-notation
  7984. * @return {Object} graphData
  7985. */
  7986. function DOTToGraph (data) {
  7987. // parse the DOT file
  7988. var dotData = parseDOT(data);
  7989. var graphData = {
  7990. nodes: [],
  7991. edges: [],
  7992. options: {}
  7993. };
  7994. // copy the nodes
  7995. if (dotData.nodes) {
  7996. dotData.nodes.forEach(function (dotNode) {
  7997. var graphNode = {
  7998. id: dotNode.id,
  7999. label: String(dotNode.label || dotNode.id)
  8000. };
  8001. merge(graphNode, dotNode.attr);
  8002. if (graphNode.image) {
  8003. graphNode.shape = 'image';
  8004. }
  8005. graphData.nodes.push(graphNode);
  8006. });
  8007. }
  8008. // copy the edges
  8009. if (dotData.edges) {
  8010. /**
  8011. * Convert an edge in DOT format to an edge with VisGraph format
  8012. * @param {Object} dotEdge
  8013. * @returns {Object} graphEdge
  8014. */
  8015. function convertEdge(dotEdge) {
  8016. var graphEdge = {
  8017. from: dotEdge.from,
  8018. to: dotEdge.to
  8019. };
  8020. merge(graphEdge, dotEdge.attr);
  8021. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  8022. return graphEdge;
  8023. }
  8024. dotData.edges.forEach(function (dotEdge) {
  8025. var from, to;
  8026. if (dotEdge.from instanceof Object) {
  8027. from = dotEdge.from.nodes;
  8028. }
  8029. else {
  8030. from = {
  8031. id: dotEdge.from
  8032. }
  8033. }
  8034. if (dotEdge.to instanceof Object) {
  8035. to = dotEdge.to.nodes;
  8036. }
  8037. else {
  8038. to = {
  8039. id: dotEdge.to
  8040. }
  8041. }
  8042. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  8043. dotEdge.from.edges.forEach(function (subEdge) {
  8044. var graphEdge = convertEdge(subEdge);
  8045. graphData.edges.push(graphEdge);
  8046. });
  8047. }
  8048. forEach2(from, to, function (from, to) {
  8049. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  8050. var graphEdge = convertEdge(subEdge);
  8051. graphData.edges.push(graphEdge);
  8052. });
  8053. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  8054. dotEdge.to.edges.forEach(function (subEdge) {
  8055. var graphEdge = convertEdge(subEdge);
  8056. graphData.edges.push(graphEdge);
  8057. });
  8058. }
  8059. });
  8060. }
  8061. // copy the options
  8062. if (dotData.attr) {
  8063. graphData.options = dotData.attr;
  8064. }
  8065. return graphData;
  8066. }
  8067. // exports
  8068. exports.parseDOT = parseDOT;
  8069. exports.DOTToGraph = DOTToGraph;
  8070. })(typeof util !== 'undefined' ? util : exports);
  8071. /**
  8072. * Canvas shapes used by the Graph
  8073. */
  8074. if (typeof CanvasRenderingContext2D !== 'undefined') {
  8075. /**
  8076. * Draw a circle shape
  8077. */
  8078. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  8079. this.beginPath();
  8080. this.arc(x, y, r, 0, 2*Math.PI, false);
  8081. };
  8082. /**
  8083. * Draw a square shape
  8084. * @param {Number} x horizontal center
  8085. * @param {Number} y vertical center
  8086. * @param {Number} r size, width and height of the square
  8087. */
  8088. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  8089. this.beginPath();
  8090. this.rect(x - r, y - r, r * 2, r * 2);
  8091. };
  8092. /**
  8093. * Draw a triangle shape
  8094. * @param {Number} x horizontal center
  8095. * @param {Number} y vertical center
  8096. * @param {Number} r radius, half the length of the sides of the triangle
  8097. */
  8098. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  8099. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8100. this.beginPath();
  8101. var s = r * 2;
  8102. var s2 = s / 2;
  8103. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8104. var h = Math.sqrt(s * s - s2 * s2); // height
  8105. this.moveTo(x, y - (h - ir));
  8106. this.lineTo(x + s2, y + ir);
  8107. this.lineTo(x - s2, y + ir);
  8108. this.lineTo(x, y - (h - ir));
  8109. this.closePath();
  8110. };
  8111. /**
  8112. * Draw a triangle shape in downward orientation
  8113. * @param {Number} x horizontal center
  8114. * @param {Number} y vertical center
  8115. * @param {Number} r radius
  8116. */
  8117. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  8118. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8119. this.beginPath();
  8120. var s = r * 2;
  8121. var s2 = s / 2;
  8122. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8123. var h = Math.sqrt(s * s - s2 * s2); // height
  8124. this.moveTo(x, y + (h - ir));
  8125. this.lineTo(x + s2, y - ir);
  8126. this.lineTo(x - s2, y - ir);
  8127. this.lineTo(x, y + (h - ir));
  8128. this.closePath();
  8129. };
  8130. /**
  8131. * Draw a star shape, a star with 5 points
  8132. * @param {Number} x horizontal center
  8133. * @param {Number} y vertical center
  8134. * @param {Number} r radius, half the length of the sides of the triangle
  8135. */
  8136. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  8137. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  8138. this.beginPath();
  8139. for (var n = 0; n < 10; n++) {
  8140. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  8141. this.lineTo(
  8142. x + radius * Math.sin(n * 2 * Math.PI / 10),
  8143. y - radius * Math.cos(n * 2 * Math.PI / 10)
  8144. );
  8145. }
  8146. this.closePath();
  8147. };
  8148. /**
  8149. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  8150. */
  8151. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  8152. var r2d = Math.PI/180;
  8153. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  8154. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  8155. this.beginPath();
  8156. this.moveTo(x+r,y);
  8157. this.lineTo(x+w-r,y);
  8158. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  8159. this.lineTo(x+w,y+h-r);
  8160. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  8161. this.lineTo(x+r,y+h);
  8162. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  8163. this.lineTo(x,y+r);
  8164. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  8165. };
  8166. /**
  8167. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8168. */
  8169. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  8170. var kappa = .5522848,
  8171. ox = (w / 2) * kappa, // control point offset horizontal
  8172. oy = (h / 2) * kappa, // control point offset vertical
  8173. xe = x + w, // x-end
  8174. ye = y + h, // y-end
  8175. xm = x + w / 2, // x-middle
  8176. ym = y + h / 2; // y-middle
  8177. this.beginPath();
  8178. this.moveTo(x, ym);
  8179. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8180. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8181. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8182. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8183. };
  8184. /**
  8185. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8186. */
  8187. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  8188. var f = 1/3;
  8189. var wEllipse = w;
  8190. var hEllipse = h * f;
  8191. var kappa = .5522848,
  8192. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  8193. oy = (hEllipse / 2) * kappa, // control point offset vertical
  8194. xe = x + wEllipse, // x-end
  8195. ye = y + hEllipse, // y-end
  8196. xm = x + wEllipse / 2, // x-middle
  8197. ym = y + hEllipse / 2, // y-middle
  8198. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  8199. yeb = y + h; // y-end, bottom ellipse
  8200. this.beginPath();
  8201. this.moveTo(xe, ym);
  8202. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8203. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8204. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8205. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8206. this.lineTo(xe, ymb);
  8207. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  8208. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  8209. this.lineTo(x, ym);
  8210. };
  8211. /**
  8212. * Draw an arrow point (no line)
  8213. */
  8214. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  8215. // tail
  8216. var xt = x - length * Math.cos(angle);
  8217. var yt = y - length * Math.sin(angle);
  8218. // inner tail
  8219. // TODO: allow to customize different shapes
  8220. var xi = x - length * 0.9 * Math.cos(angle);
  8221. var yi = y - length * 0.9 * Math.sin(angle);
  8222. // left
  8223. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  8224. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  8225. // right
  8226. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  8227. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  8228. this.beginPath();
  8229. this.moveTo(x, y);
  8230. this.lineTo(xl, yl);
  8231. this.lineTo(xi, yi);
  8232. this.lineTo(xr, yr);
  8233. this.closePath();
  8234. };
  8235. /**
  8236. * Sets up the dashedLine functionality for drawing
  8237. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  8238. * @author David Jordan
  8239. * @date 2012-08-08
  8240. */
  8241. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  8242. if (!dashArray) dashArray=[10,5];
  8243. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  8244. var dashCount = dashArray.length;
  8245. this.moveTo(x, y);
  8246. var dx = (x2-x), dy = (y2-y);
  8247. var slope = dy/dx;
  8248. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  8249. var dashIndex=0, draw=true;
  8250. while (distRemaining>=0.1){
  8251. var dashLength = dashArray[dashIndex++%dashCount];
  8252. if (dashLength > distRemaining) dashLength = distRemaining;
  8253. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  8254. if (dx<0) xStep = -xStep;
  8255. x += xStep;
  8256. y += slope*xStep;
  8257. this[draw ? 'lineTo' : 'moveTo'](x,y);
  8258. distRemaining -= dashLength;
  8259. draw = !draw;
  8260. }
  8261. };
  8262. // TODO: add diamond shape
  8263. }
  8264. /**
  8265. * @class Node
  8266. * A node. A node can be connected to other nodes via one or multiple edges.
  8267. * @param {object} properties An object containing properties for the node. All
  8268. * properties are optional, except for the id.
  8269. * {number} id Id of the node. Required
  8270. * {string} label Text label for the node
  8271. * {number} x Horizontal position of the node
  8272. * {number} y Vertical position of the node
  8273. * {string} shape Node shape, available:
  8274. * "database", "circle", "ellipse",
  8275. * "box", "image", "text", "dot",
  8276. * "star", "triangle", "triangleDown",
  8277. * "square"
  8278. * {string} image An image url
  8279. * {string} title An title text, can be HTML
  8280. * {anytype} group A group name or number
  8281. * @param {Graph.Images} imagelist A list with images. Only needed
  8282. * when the node has an image
  8283. * @param {Graph.Groups} grouplist A list with groups. Needed for
  8284. * retrieving group properties
  8285. * @param {Object} constants An object with default values for
  8286. * example for the color
  8287. *
  8288. */
  8289. function Node(properties, imagelist, grouplist, constants) {
  8290. this.selected = false;
  8291. this.edges = []; // all edges connected to this node
  8292. this.dynamicEdges = [];
  8293. this.reroutedEdges = {};
  8294. this.group = constants.nodes.group;
  8295. this.fontSize = constants.nodes.fontSize;
  8296. this.fontFace = constants.nodes.fontFace;
  8297. this.fontColor = constants.nodes.fontColor;
  8298. this.fontDrawThreshold = 3;
  8299. this.color = constants.nodes.color;
  8300. // set defaults for the properties
  8301. this.id = undefined;
  8302. this.shape = constants.nodes.shape;
  8303. this.image = constants.nodes.image;
  8304. this.x = null;
  8305. this.y = null;
  8306. this.xFixed = false;
  8307. this.yFixed = false;
  8308. this.horizontalAlignLeft = true; // these are for the navigation controls
  8309. this.verticalAlignTop = true; // these are for the navigation controls
  8310. this.radius = constants.nodes.radius;
  8311. this.baseRadiusValue = constants.nodes.radius;
  8312. this.radiusFixed = false;
  8313. this.radiusMin = constants.nodes.radiusMin;
  8314. this.radiusMax = constants.nodes.radiusMax;
  8315. this.level = -1;
  8316. this.imagelist = imagelist;
  8317. this.grouplist = grouplist;
  8318. // physics properties
  8319. this.fx = 0.0; // external force x
  8320. this.fy = 0.0; // external force y
  8321. this.vx = 0.0; // velocity x
  8322. this.vy = 0.0; // velocity y
  8323. this.minForce = constants.minForce;
  8324. this.damping = constants.physics.damping;
  8325. this.mass = 1; // kg
  8326. this.fixedData = {x:null,y:null};
  8327. this.setProperties(properties, constants);
  8328. // creating the variables for clustering
  8329. this.resetCluster();
  8330. this.dynamicEdgesLength = 0;
  8331. this.clusterSession = 0;
  8332. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  8333. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  8334. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  8335. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  8336. this.growthIndicator = 0;
  8337. // variables to tell the node about the graph.
  8338. this.graphScaleInv = 1;
  8339. this.graphScale = 1;
  8340. this.canvasTopLeft = {"x": -300, "y": -300};
  8341. this.canvasBottomRight = {"x": 300, "y": 300};
  8342. this.parentEdgeId = null;
  8343. }
  8344. /**
  8345. * (re)setting the clustering variables and objects
  8346. */
  8347. Node.prototype.resetCluster = function() {
  8348. // clustering variables
  8349. this.formationScale = undefined; // this is used to determine when to open the cluster
  8350. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  8351. this.containedNodes = {};
  8352. this.containedEdges = {};
  8353. this.clusterSessions = [];
  8354. };
  8355. /**
  8356. * Attach a edge to the node
  8357. * @param {Edge} edge
  8358. */
  8359. Node.prototype.attachEdge = function(edge) {
  8360. if (this.edges.indexOf(edge) == -1) {
  8361. this.edges.push(edge);
  8362. }
  8363. if (this.dynamicEdges.indexOf(edge) == -1) {
  8364. this.dynamicEdges.push(edge);
  8365. }
  8366. this.dynamicEdgesLength = this.dynamicEdges.length;
  8367. };
  8368. /**
  8369. * Detach a edge from the node
  8370. * @param {Edge} edge
  8371. */
  8372. Node.prototype.detachEdge = function(edge) {
  8373. var index = this.edges.indexOf(edge);
  8374. if (index != -1) {
  8375. this.edges.splice(index, 1);
  8376. this.dynamicEdges.splice(index, 1);
  8377. }
  8378. this.dynamicEdgesLength = this.dynamicEdges.length;
  8379. };
  8380. /**
  8381. * Set or overwrite properties for the node
  8382. * @param {Object} properties an object with properties
  8383. * @param {Object} constants and object with default, global properties
  8384. */
  8385. Node.prototype.setProperties = function(properties, constants) {
  8386. if (!properties) {
  8387. return;
  8388. }
  8389. this.originalLabel = undefined;
  8390. // basic properties
  8391. if (properties.id !== undefined) {this.id = properties.id;}
  8392. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  8393. if (properties.title !== undefined) {this.title = properties.title;}
  8394. if (properties.group !== undefined) {this.group = properties.group;}
  8395. if (properties.x !== undefined) {this.x = properties.x;}
  8396. if (properties.y !== undefined) {this.y = properties.y;}
  8397. if (properties.value !== undefined) {this.value = properties.value;}
  8398. if (properties.level !== undefined) {this.level = properties.level;}
  8399. // physics
  8400. if (properties.mass !== undefined) {this.mass = properties.mass;}
  8401. // navigation controls properties
  8402. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  8403. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  8404. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  8405. if (this.id === undefined) {
  8406. throw "Node must have an id";
  8407. }
  8408. // copy group properties
  8409. if (this.group) {
  8410. var groupObj = this.grouplist.get(this.group);
  8411. for (var prop in groupObj) {
  8412. if (groupObj.hasOwnProperty(prop)) {
  8413. this[prop] = groupObj[prop];
  8414. }
  8415. }
  8416. }
  8417. // individual shape properties
  8418. if (properties.shape !== undefined) {this.shape = properties.shape;}
  8419. if (properties.image !== undefined) {this.image = properties.image;}
  8420. if (properties.radius !== undefined) {this.radius = properties.radius;}
  8421. if (properties.color !== undefined) {this.color = Node.parseColor(properties.color);}
  8422. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8423. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8424. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8425. if (this.image !== undefined && this.image != "") {
  8426. if (this.imagelist) {
  8427. this.imageObj = this.imagelist.load(this.image);
  8428. }
  8429. else {
  8430. throw "No imagelist provided";
  8431. }
  8432. }
  8433. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX);
  8434. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  8435. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  8436. if (this.shape == 'image') {
  8437. this.radiusMin = constants.nodes.widthMin;
  8438. this.radiusMax = constants.nodes.widthMax;
  8439. }
  8440. // choose draw method depending on the shape
  8441. switch (this.shape) {
  8442. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  8443. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  8444. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  8445. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8446. // TODO: add diamond shape
  8447. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  8448. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  8449. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  8450. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  8451. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  8452. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  8453. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  8454. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8455. }
  8456. // reset the size of the node, this can be changed
  8457. this._reset();
  8458. };
  8459. /**
  8460. * Parse a color property into an object with border, background, and
  8461. * hightlight colors
  8462. * @param {Object | String} color
  8463. * @return {Object} colorObject
  8464. */
  8465. Node.parseColor = function(color) {
  8466. var c;
  8467. if (util.isString(color)) {
  8468. if (util.isValidHex(color)) {
  8469. var hsv = util.hexToHSV(color);
  8470. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  8471. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  8472. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  8473. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  8474. c = {
  8475. background: color,
  8476. border:darkerColorHex,
  8477. highlight: {
  8478. background:lighterColorHex,
  8479. border:darkerColorHex
  8480. }
  8481. };
  8482. }
  8483. else {
  8484. c = {
  8485. background:color,
  8486. border:color,
  8487. highlight: {
  8488. background:color,
  8489. border:color
  8490. }
  8491. };
  8492. }
  8493. }
  8494. else {
  8495. c = {};
  8496. c.background = color.background || 'white';
  8497. c.border = color.border || c.background;
  8498. if (util.isString(color.highlight)) {
  8499. c.highlight = {
  8500. border: color.highlight,
  8501. background: color.highlight
  8502. }
  8503. }
  8504. else {
  8505. c.highlight = {};
  8506. c.highlight.background = color.highlight && color.highlight.background || c.background;
  8507. c.highlight.border = color.highlight && color.highlight.border || c.border;
  8508. }
  8509. }
  8510. return c;
  8511. };
  8512. /**
  8513. * select this node
  8514. */
  8515. Node.prototype.select = function() {
  8516. this.selected = true;
  8517. this._reset();
  8518. };
  8519. /**
  8520. * unselect this node
  8521. */
  8522. Node.prototype.unselect = function() {
  8523. this.selected = false;
  8524. this._reset();
  8525. };
  8526. /**
  8527. * Reset the calculated size of the node, forces it to recalculate its size
  8528. */
  8529. Node.prototype.clearSizeCache = function() {
  8530. this._reset();
  8531. };
  8532. /**
  8533. * Reset the calculated size of the node, forces it to recalculate its size
  8534. * @private
  8535. */
  8536. Node.prototype._reset = function() {
  8537. this.width = undefined;
  8538. this.height = undefined;
  8539. };
  8540. /**
  8541. * get the title of this node.
  8542. * @return {string} title The title of the node, or undefined when no title
  8543. * has been set.
  8544. */
  8545. Node.prototype.getTitle = function() {
  8546. return this.title;
  8547. };
  8548. /**
  8549. * Calculate the distance to the border of the Node
  8550. * @param {CanvasRenderingContext2D} ctx
  8551. * @param {Number} angle Angle in radians
  8552. * @returns {number} distance Distance to the border in pixels
  8553. */
  8554. Node.prototype.distanceToBorder = function (ctx, angle) {
  8555. var borderWidth = 1;
  8556. if (!this.width) {
  8557. this.resize(ctx);
  8558. }
  8559. switch (this.shape) {
  8560. case 'circle':
  8561. case 'dot':
  8562. return this.radius + borderWidth;
  8563. case 'ellipse':
  8564. var a = this.width / 2;
  8565. var b = this.height / 2;
  8566. var w = (Math.sin(angle) * a);
  8567. var h = (Math.cos(angle) * b);
  8568. return a * b / Math.sqrt(w * w + h * h);
  8569. // TODO: implement distanceToBorder for database
  8570. // TODO: implement distanceToBorder for triangle
  8571. // TODO: implement distanceToBorder for triangleDown
  8572. case 'box':
  8573. case 'image':
  8574. case 'text':
  8575. default:
  8576. if (this.width) {
  8577. return Math.min(
  8578. Math.abs(this.width / 2 / Math.cos(angle)),
  8579. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8580. // TODO: reckon with border radius too in case of box
  8581. }
  8582. else {
  8583. return 0;
  8584. }
  8585. }
  8586. // TODO: implement calculation of distance to border for all shapes
  8587. };
  8588. /**
  8589. * Set forces acting on the node
  8590. * @param {number} fx Force in horizontal direction
  8591. * @param {number} fy Force in vertical direction
  8592. */
  8593. Node.prototype._setForce = function(fx, fy) {
  8594. this.fx = fx;
  8595. this.fy = fy;
  8596. };
  8597. /**
  8598. * Add forces acting on the node
  8599. * @param {number} fx Force in horizontal direction
  8600. * @param {number} fy Force in vertical direction
  8601. * @private
  8602. */
  8603. Node.prototype._addForce = function(fx, fy) {
  8604. this.fx += fx;
  8605. this.fy += fy;
  8606. };
  8607. /**
  8608. * Perform one discrete step for the node
  8609. * @param {number} interval Time interval in seconds
  8610. */
  8611. Node.prototype.discreteStep = function(interval) {
  8612. if (!this.xFixed) {
  8613. var dx = this.damping * this.vx; // damping force
  8614. var ax = (this.fx - dx) / this.mass; // acceleration
  8615. this.vx += ax * interval; // velocity
  8616. this.x += this.vx * interval; // position
  8617. }
  8618. if (!this.yFixed) {
  8619. var dy = this.damping * this.vy; // damping force
  8620. var ay = (this.fy - dy) / this.mass; // acceleration
  8621. this.vy += ay * interval; // velocity
  8622. this.y += this.vy * interval; // position
  8623. }
  8624. };
  8625. /**
  8626. * Perform one discrete step for the node
  8627. * @param {number} interval Time interval in seconds
  8628. */
  8629. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8630. if (!this.xFixed) {
  8631. var dx = this.damping * this.vx; // damping force
  8632. var ax = (this.fx - dx) / this.mass; // acceleration
  8633. this.vx += ax * interval; // velocity
  8634. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8635. this.x += this.vx * interval; // position
  8636. }
  8637. else {
  8638. this.fx = 0;
  8639. }
  8640. if (!this.yFixed) {
  8641. var dy = this.damping * this.vy; // damping force
  8642. var ay = (this.fy - dy) / this.mass; // acceleration
  8643. this.vy += ay * interval; // velocity
  8644. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8645. this.y += this.vy * interval; // position
  8646. }
  8647. else {
  8648. this.fy = 0;
  8649. }
  8650. };
  8651. /**
  8652. * Check if this node has a fixed x and y position
  8653. * @return {boolean} true if fixed, false if not
  8654. */
  8655. Node.prototype.isFixed = function() {
  8656. return (this.xFixed && this.yFixed);
  8657. };
  8658. /**
  8659. * Check if this node is moving
  8660. * @param {number} vmin the minimum velocity considered as "moving"
  8661. * @return {boolean} true if moving, false if it has no velocity
  8662. */
  8663. // TODO: replace this method with calculating the kinetic energy
  8664. Node.prototype.isMoving = function(vmin) {
  8665. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8666. };
  8667. /**
  8668. * check if this node is selecte
  8669. * @return {boolean} selected True if node is selected, else false
  8670. */
  8671. Node.prototype.isSelected = function() {
  8672. return this.selected;
  8673. };
  8674. /**
  8675. * Retrieve the value of the node. Can be undefined
  8676. * @return {Number} value
  8677. */
  8678. Node.prototype.getValue = function() {
  8679. return this.value;
  8680. };
  8681. /**
  8682. * Calculate the distance from the nodes location to the given location (x,y)
  8683. * @param {Number} x
  8684. * @param {Number} y
  8685. * @return {Number} value
  8686. */
  8687. Node.prototype.getDistance = function(x, y) {
  8688. var dx = this.x - x,
  8689. dy = this.y - y;
  8690. return Math.sqrt(dx * dx + dy * dy);
  8691. };
  8692. /**
  8693. * Adjust the value range of the node. The node will adjust it's radius
  8694. * based on its value.
  8695. * @param {Number} min
  8696. * @param {Number} max
  8697. */
  8698. Node.prototype.setValueRange = function(min, max) {
  8699. if (!this.radiusFixed && this.value !== undefined) {
  8700. if (max == min) {
  8701. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8702. }
  8703. else {
  8704. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8705. this.radius = (this.value - min) * scale + this.radiusMin;
  8706. }
  8707. }
  8708. this.baseRadiusValue = this.radius;
  8709. };
  8710. /**
  8711. * Draw this node in the given canvas
  8712. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8713. * @param {CanvasRenderingContext2D} ctx
  8714. */
  8715. Node.prototype.draw = function(ctx) {
  8716. throw "Draw method not initialized for node";
  8717. };
  8718. /**
  8719. * Recalculate the size of this node in the given canvas
  8720. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8721. * @param {CanvasRenderingContext2D} ctx
  8722. */
  8723. Node.prototype.resize = function(ctx) {
  8724. throw "Resize method not initialized for node";
  8725. };
  8726. /**
  8727. * Check if this object is overlapping with the provided object
  8728. * @param {Object} obj an object with parameters left, top, right, bottom
  8729. * @return {boolean} True if location is located on node
  8730. */
  8731. Node.prototype.isOverlappingWith = function(obj) {
  8732. return (this.left < obj.right &&
  8733. this.left + this.width > obj.left &&
  8734. this.top < obj.bottom &&
  8735. this.top + this.height > obj.top);
  8736. };
  8737. Node.prototype._resizeImage = function (ctx) {
  8738. // TODO: pre calculate the image size
  8739. if (!this.width || !this.height) { // undefined or 0
  8740. var width, height;
  8741. if (this.value) {
  8742. this.radius = this.baseRadiusValue;
  8743. var scale = this.imageObj.height / this.imageObj.width;
  8744. if (scale !== undefined) {
  8745. width = this.radius || this.imageObj.width;
  8746. height = this.radius * scale || this.imageObj.height;
  8747. }
  8748. else {
  8749. width = 0;
  8750. height = 0;
  8751. }
  8752. }
  8753. else {
  8754. width = this.imageObj.width;
  8755. height = this.imageObj.height;
  8756. }
  8757. this.width = width;
  8758. this.height = height;
  8759. this.growthIndicator = 0;
  8760. if (this.width > 0 && this.height > 0) {
  8761. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8762. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8763. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8764. this.growthIndicator = this.width - width;
  8765. }
  8766. }
  8767. };
  8768. Node.prototype._drawImage = function (ctx) {
  8769. this._resizeImage(ctx);
  8770. this.left = this.x - this.width / 2;
  8771. this.top = this.y - this.height / 2;
  8772. var yLabel;
  8773. if (this.imageObj.width != 0 ) {
  8774. // draw the shade
  8775. if (this.clusterSize > 1) {
  8776. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8777. lineWidth *= this.graphScaleInv;
  8778. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8779. ctx.globalAlpha = 0.5;
  8780. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8781. }
  8782. // draw the image
  8783. ctx.globalAlpha = 1.0;
  8784. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8785. yLabel = this.y + this.height / 2;
  8786. }
  8787. else {
  8788. // image still loading... just draw the label for now
  8789. yLabel = this.y;
  8790. }
  8791. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8792. };
  8793. Node.prototype._resizeBox = function (ctx) {
  8794. if (!this.width) {
  8795. var margin = 5;
  8796. var textSize = this.getTextSize(ctx);
  8797. this.width = textSize.width + 2 * margin;
  8798. this.height = textSize.height + 2 * margin;
  8799. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8800. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8801. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8802. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8803. }
  8804. };
  8805. Node.prototype._drawBox = function (ctx) {
  8806. this._resizeBox(ctx);
  8807. this.left = this.x - this.width / 2;
  8808. this.top = this.y - this.height / 2;
  8809. var clusterLineWidth = 2.5;
  8810. var selectionLineWidth = 2;
  8811. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8812. // draw the outer border
  8813. if (this.clusterSize > 1) {
  8814. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8815. ctx.lineWidth *= this.graphScaleInv;
  8816. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8817. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8818. ctx.stroke();
  8819. }
  8820. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8821. ctx.lineWidth *= this.graphScaleInv;
  8822. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8823. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8824. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8825. ctx.fill();
  8826. ctx.stroke();
  8827. this._label(ctx, this.label, this.x, this.y);
  8828. };
  8829. Node.prototype._resizeDatabase = function (ctx) {
  8830. if (!this.width) {
  8831. var margin = 5;
  8832. var textSize = this.getTextSize(ctx);
  8833. var size = textSize.width + 2 * margin;
  8834. this.width = size;
  8835. this.height = size;
  8836. // scaling used for clustering
  8837. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8838. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8839. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8840. this.growthIndicator = this.width - size;
  8841. }
  8842. };
  8843. Node.prototype._drawDatabase = function (ctx) {
  8844. this._resizeDatabase(ctx);
  8845. this.left = this.x - this.width / 2;
  8846. this.top = this.y - this.height / 2;
  8847. var clusterLineWidth = 2.5;
  8848. var selectionLineWidth = 2;
  8849. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8850. // draw the outer border
  8851. if (this.clusterSize > 1) {
  8852. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8853. ctx.lineWidth *= this.graphScaleInv;
  8854. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8855. 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);
  8856. ctx.stroke();
  8857. }
  8858. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8859. ctx.lineWidth *= this.graphScaleInv;
  8860. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8861. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8862. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8863. ctx.fill();
  8864. ctx.stroke();
  8865. this._label(ctx, this.label, this.x, this.y);
  8866. };
  8867. Node.prototype._resizeCircle = function (ctx) {
  8868. if (!this.width) {
  8869. var margin = 5;
  8870. var textSize = this.getTextSize(ctx);
  8871. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8872. this.radius = diameter / 2;
  8873. this.width = diameter;
  8874. this.height = diameter;
  8875. // scaling used for clustering
  8876. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8877. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8878. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8879. this.growthIndicator = this.radius - 0.5*diameter;
  8880. }
  8881. };
  8882. Node.prototype._drawCircle = function (ctx) {
  8883. this._resizeCircle(ctx);
  8884. this.left = this.x - this.width / 2;
  8885. this.top = this.y - this.height / 2;
  8886. var clusterLineWidth = 2.5;
  8887. var selectionLineWidth = 2;
  8888. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8889. // draw the outer border
  8890. if (this.clusterSize > 1) {
  8891. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8892. ctx.lineWidth *= this.graphScaleInv;
  8893. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8894. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8895. ctx.stroke();
  8896. }
  8897. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8898. ctx.lineWidth *= this.graphScaleInv;
  8899. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8900. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8901. ctx.circle(this.x, this.y, this.radius);
  8902. ctx.fill();
  8903. ctx.stroke();
  8904. this._label(ctx, this.label, this.x, this.y);
  8905. };
  8906. Node.prototype._resizeEllipse = function (ctx) {
  8907. if (!this.width) {
  8908. var textSize = this.getTextSize(ctx);
  8909. this.width = textSize.width * 1.5;
  8910. this.height = textSize.height * 2;
  8911. if (this.width < this.height) {
  8912. this.width = this.height;
  8913. }
  8914. var defaultSize = this.width;
  8915. // scaling used for clustering
  8916. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8917. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8918. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8919. this.growthIndicator = this.width - defaultSize;
  8920. }
  8921. };
  8922. Node.prototype._drawEllipse = function (ctx) {
  8923. this._resizeEllipse(ctx);
  8924. this.left = this.x - this.width / 2;
  8925. this.top = this.y - this.height / 2;
  8926. var clusterLineWidth = 2.5;
  8927. var selectionLineWidth = 2;
  8928. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8929. // draw the outer border
  8930. if (this.clusterSize > 1) {
  8931. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8932. ctx.lineWidth *= this.graphScaleInv;
  8933. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8934. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8935. ctx.stroke();
  8936. }
  8937. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8938. ctx.lineWidth *= this.graphScaleInv;
  8939. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8940. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8941. ctx.ellipse(this.left, this.top, this.width, this.height);
  8942. ctx.fill();
  8943. ctx.stroke();
  8944. this._label(ctx, this.label, this.x, this.y);
  8945. };
  8946. Node.prototype._drawDot = function (ctx) {
  8947. this._drawShape(ctx, 'circle');
  8948. };
  8949. Node.prototype._drawTriangle = function (ctx) {
  8950. this._drawShape(ctx, 'triangle');
  8951. };
  8952. Node.prototype._drawTriangleDown = function (ctx) {
  8953. this._drawShape(ctx, 'triangleDown');
  8954. };
  8955. Node.prototype._drawSquare = function (ctx) {
  8956. this._drawShape(ctx, 'square');
  8957. };
  8958. Node.prototype._drawStar = function (ctx) {
  8959. this._drawShape(ctx, 'star');
  8960. };
  8961. Node.prototype._resizeShape = function (ctx) {
  8962. if (!this.width) {
  8963. this.radius = this.baseRadiusValue;
  8964. var size = 2 * this.radius;
  8965. this.width = size;
  8966. this.height = size;
  8967. // scaling used for clustering
  8968. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8969. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8970. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8971. this.growthIndicator = this.width - size;
  8972. }
  8973. };
  8974. Node.prototype._drawShape = function (ctx, shape) {
  8975. this._resizeShape(ctx);
  8976. this.left = this.x - this.width / 2;
  8977. this.top = this.y - this.height / 2;
  8978. var clusterLineWidth = 2.5;
  8979. var selectionLineWidth = 2;
  8980. var radiusMultiplier = 2;
  8981. // choose draw method depending on the shape
  8982. switch (shape) {
  8983. case 'dot': radiusMultiplier = 2; break;
  8984. case 'square': radiusMultiplier = 2; break;
  8985. case 'triangle': radiusMultiplier = 3; break;
  8986. case 'triangleDown': radiusMultiplier = 3; break;
  8987. case 'star': radiusMultiplier = 4; break;
  8988. }
  8989. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8990. // draw the outer border
  8991. if (this.clusterSize > 1) {
  8992. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8993. ctx.lineWidth *= this.graphScaleInv;
  8994. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8995. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8996. ctx.stroke();
  8997. }
  8998. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8999. ctx.lineWidth *= this.graphScaleInv;
  9000. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  9001. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  9002. ctx[shape](this.x, this.y, this.radius);
  9003. ctx.fill();
  9004. ctx.stroke();
  9005. if (this.label) {
  9006. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  9007. }
  9008. };
  9009. Node.prototype._resizeText = function (ctx) {
  9010. if (!this.width) {
  9011. var margin = 5;
  9012. var textSize = this.getTextSize(ctx);
  9013. this.width = textSize.width + 2 * margin;
  9014. this.height = textSize.height + 2 * margin;
  9015. // scaling used for clustering
  9016. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  9017. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  9018. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  9019. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  9020. }
  9021. };
  9022. Node.prototype._drawText = function (ctx) {
  9023. this._resizeText(ctx);
  9024. this.left = this.x - this.width / 2;
  9025. this.top = this.y - this.height / 2;
  9026. this._label(ctx, this.label, this.x, this.y);
  9027. };
  9028. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  9029. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  9030. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9031. ctx.fillStyle = this.fontColor || "black";
  9032. ctx.textAlign = align || "center";
  9033. ctx.textBaseline = baseline || "middle";
  9034. var lines = text.split('\n'),
  9035. lineCount = lines.length,
  9036. fontSize = (this.fontSize + 4),
  9037. yLine = y + (1 - lineCount) / 2 * fontSize;
  9038. for (var i = 0; i < lineCount; i++) {
  9039. ctx.fillText(lines[i], x, yLine);
  9040. yLine += fontSize;
  9041. }
  9042. }
  9043. };
  9044. Node.prototype.getTextSize = function(ctx) {
  9045. if (this.label !== undefined) {
  9046. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9047. var lines = this.label.split('\n'),
  9048. height = (this.fontSize + 4) * lines.length,
  9049. width = 0;
  9050. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  9051. width = Math.max(width, ctx.measureText(lines[i]).width);
  9052. }
  9053. return {"width": width, "height": height};
  9054. }
  9055. else {
  9056. return {"width": 0, "height": 0};
  9057. }
  9058. };
  9059. /**
  9060. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  9061. * there is a safety margin of 0.3 * width;
  9062. *
  9063. * @returns {boolean}
  9064. */
  9065. Node.prototype.inArea = function() {
  9066. if (this.width !== undefined) {
  9067. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  9068. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  9069. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  9070. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  9071. }
  9072. else {
  9073. return true;
  9074. }
  9075. };
  9076. /**
  9077. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  9078. * @returns {boolean}
  9079. */
  9080. Node.prototype.inView = function() {
  9081. return (this.x >= this.canvasTopLeft.x &&
  9082. this.x < this.canvasBottomRight.x &&
  9083. this.y >= this.canvasTopLeft.y &&
  9084. this.y < this.canvasBottomRight.y);
  9085. };
  9086. /**
  9087. * This allows the zoom level of the graph to influence the rendering
  9088. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  9089. *
  9090. * @param scale
  9091. * @param canvasTopLeft
  9092. * @param canvasBottomRight
  9093. */
  9094. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  9095. this.graphScaleInv = 1.0/scale;
  9096. this.graphScale = scale;
  9097. this.canvasTopLeft = canvasTopLeft;
  9098. this.canvasBottomRight = canvasBottomRight;
  9099. };
  9100. /**
  9101. * This allows the zoom level of the graph to influence the rendering
  9102. *
  9103. * @param scale
  9104. */
  9105. Node.prototype.setScale = function(scale) {
  9106. this.graphScaleInv = 1.0/scale;
  9107. this.graphScale = scale;
  9108. };
  9109. /**
  9110. * set the velocity at 0. Is called when this node is contained in another during clustering
  9111. */
  9112. Node.prototype.clearVelocity = function() {
  9113. this.vx = 0;
  9114. this.vy = 0;
  9115. };
  9116. /**
  9117. * Basic preservation of (kinectic) energy
  9118. *
  9119. * @param massBeforeClustering
  9120. */
  9121. Node.prototype.updateVelocity = function(massBeforeClustering) {
  9122. var energyBefore = this.vx * this.vx * massBeforeClustering;
  9123. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9124. this.vx = Math.sqrt(energyBefore/this.mass);
  9125. energyBefore = this.vy * this.vy * massBeforeClustering;
  9126. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9127. this.vy = Math.sqrt(energyBefore/this.mass);
  9128. };
  9129. /**
  9130. * @class Edge
  9131. *
  9132. * A edge connects two nodes
  9133. * @param {Object} properties Object with properties. Must contain
  9134. * At least properties from and to.
  9135. * Available properties: from (number),
  9136. * to (number), label (string, color (string),
  9137. * width (number), style (string),
  9138. * length (number), title (string)
  9139. * @param {Graph} graph A graph object, used to find and edge to
  9140. * nodes.
  9141. * @param {Object} constants An object with default values for
  9142. * example for the color
  9143. */
  9144. function Edge (properties, graph, constants) {
  9145. if (!graph) {
  9146. throw "No graph provided";
  9147. }
  9148. this.graph = graph;
  9149. // initialize constants
  9150. this.widthMin = constants.edges.widthMin;
  9151. this.widthMax = constants.edges.widthMax;
  9152. // initialize variables
  9153. this.id = undefined;
  9154. this.fromId = undefined;
  9155. this.toId = undefined;
  9156. this.style = constants.edges.style;
  9157. this.title = undefined;
  9158. this.width = constants.edges.width;
  9159. this.value = undefined;
  9160. this.length = constants.physics.springLength;
  9161. this.customLength = false;
  9162. this.selected = false;
  9163. this.smooth = constants.smoothCurves;
  9164. this.from = null; // a node
  9165. this.to = null; // a node
  9166. this.via = null; // a temp node
  9167. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  9168. // by storing the original information we can revert to the original connection when the cluser is opened.
  9169. this.originalFromId = [];
  9170. this.originalToId = [];
  9171. this.connected = false;
  9172. // Added to support dashed lines
  9173. // David Jordan
  9174. // 2012-08-08
  9175. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  9176. this.color = {color:constants.edges.color.color,
  9177. highlight:constants.edges.color.highlight};
  9178. this.widthFixed = false;
  9179. this.lengthFixed = false;
  9180. this.setProperties(properties, constants);
  9181. }
  9182. /**
  9183. * Set or overwrite properties for the edge
  9184. * @param {Object} properties an object with properties
  9185. * @param {Object} constants and object with default, global properties
  9186. */
  9187. Edge.prototype.setProperties = function(properties, constants) {
  9188. if (!properties) {
  9189. return;
  9190. }
  9191. if (properties.from !== undefined) {this.fromId = properties.from;}
  9192. if (properties.to !== undefined) {this.toId = properties.to;}
  9193. if (properties.id !== undefined) {this.id = properties.id;}
  9194. if (properties.style !== undefined) {this.style = properties.style;}
  9195. if (properties.label !== undefined) {this.label = properties.label;}
  9196. if (this.label) {
  9197. this.fontSize = constants.edges.fontSize;
  9198. this.fontFace = constants.edges.fontFace;
  9199. this.fontColor = constants.edges.fontColor;
  9200. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  9201. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  9202. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  9203. }
  9204. if (properties.title !== undefined) {this.title = properties.title;}
  9205. if (properties.width !== undefined) {this.width = properties.width;}
  9206. if (properties.value !== undefined) {this.value = properties.value;}
  9207. if (properties.length !== undefined) {this.length = properties.length;
  9208. this.customLength = true;}
  9209. // Added to support dashed lines
  9210. // David Jordan
  9211. // 2012-08-08
  9212. if (properties.dash) {
  9213. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  9214. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  9215. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  9216. }
  9217. if (properties.color !== undefined) {
  9218. if (util.isString(properties.color)) {
  9219. this.color.color = properties.color;
  9220. this.color.highlight = properties.color;
  9221. }
  9222. else {
  9223. if (properties.color.color !== undefined) {this.color.color = properties.color.color;}
  9224. if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;}
  9225. }
  9226. }
  9227. // A node is connected when it has a from and to node.
  9228. this.connect();
  9229. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  9230. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  9231. // set draw method based on style
  9232. switch (this.style) {
  9233. case 'line': this.draw = this._drawLine; break;
  9234. case 'arrow': this.draw = this._drawArrow; break;
  9235. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  9236. case 'dash-line': this.draw = this._drawDashLine; break;
  9237. default: this.draw = this._drawLine; break;
  9238. }
  9239. };
  9240. /**
  9241. * Connect an edge to its nodes
  9242. */
  9243. Edge.prototype.connect = function () {
  9244. this.disconnect();
  9245. this.from = this.graph.nodes[this.fromId] || null;
  9246. this.to = this.graph.nodes[this.toId] || null;
  9247. this.connected = (this.from && this.to);
  9248. if (this.connected) {
  9249. this.from.attachEdge(this);
  9250. this.to.attachEdge(this);
  9251. }
  9252. else {
  9253. if (this.from) {
  9254. this.from.detachEdge(this);
  9255. }
  9256. if (this.to) {
  9257. this.to.detachEdge(this);
  9258. }
  9259. }
  9260. };
  9261. /**
  9262. * Disconnect an edge from its nodes
  9263. */
  9264. Edge.prototype.disconnect = function () {
  9265. if (this.from) {
  9266. this.from.detachEdge(this);
  9267. this.from = null;
  9268. }
  9269. if (this.to) {
  9270. this.to.detachEdge(this);
  9271. this.to = null;
  9272. }
  9273. this.connected = false;
  9274. };
  9275. /**
  9276. * get the title of this edge.
  9277. * @return {string} title The title of the edge, or undefined when no title
  9278. * has been set.
  9279. */
  9280. Edge.prototype.getTitle = function() {
  9281. return this.title;
  9282. };
  9283. /**
  9284. * Retrieve the value of the edge. Can be undefined
  9285. * @return {Number} value
  9286. */
  9287. Edge.prototype.getValue = function() {
  9288. return this.value;
  9289. };
  9290. /**
  9291. * Adjust the value range of the edge. The edge will adjust it's width
  9292. * based on its value.
  9293. * @param {Number} min
  9294. * @param {Number} max
  9295. */
  9296. Edge.prototype.setValueRange = function(min, max) {
  9297. if (!this.widthFixed && this.value !== undefined) {
  9298. var scale = (this.widthMax - this.widthMin) / (max - min);
  9299. this.width = (this.value - min) * scale + this.widthMin;
  9300. }
  9301. };
  9302. /**
  9303. * Redraw a edge
  9304. * Draw this edge in the given canvas
  9305. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9306. * @param {CanvasRenderingContext2D} ctx
  9307. */
  9308. Edge.prototype.draw = function(ctx) {
  9309. throw "Method draw not initialized in edge";
  9310. };
  9311. /**
  9312. * Check if this object is overlapping with the provided object
  9313. * @param {Object} obj an object with parameters left, top
  9314. * @return {boolean} True if location is located on the edge
  9315. */
  9316. Edge.prototype.isOverlappingWith = function(obj) {
  9317. if (this.connected) {
  9318. var distMax = 10;
  9319. var xFrom = this.from.x;
  9320. var yFrom = this.from.y;
  9321. var xTo = this.to.x;
  9322. var yTo = this.to.y;
  9323. var xObj = obj.left;
  9324. var yObj = obj.top;
  9325. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  9326. return (dist < distMax);
  9327. }
  9328. else {
  9329. return false
  9330. }
  9331. };
  9332. /**
  9333. * Redraw a edge as a line
  9334. * Draw this edge in the given canvas
  9335. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9336. * @param {CanvasRenderingContext2D} ctx
  9337. * @private
  9338. */
  9339. Edge.prototype._drawLine = function(ctx) {
  9340. // set style
  9341. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9342. else {ctx.strokeStyle = this.color.color;}
  9343. ctx.lineWidth = this._getLineWidth();
  9344. if (this.from != this.to) {
  9345. // draw line
  9346. this._line(ctx);
  9347. // draw label
  9348. var point;
  9349. if (this.label) {
  9350. if (this.smooth == true) {
  9351. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9352. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9353. point = {x:midpointX, y:midpointY};
  9354. }
  9355. else {
  9356. point = this._pointOnLine(0.5);
  9357. }
  9358. this._label(ctx, this.label, point.x, point.y);
  9359. }
  9360. }
  9361. else {
  9362. var x, y;
  9363. var radius = this.length / 4;
  9364. var node = this.from;
  9365. if (!node.width) {
  9366. node.resize(ctx);
  9367. }
  9368. if (node.width > node.height) {
  9369. x = node.x + node.width / 2;
  9370. y = node.y - radius;
  9371. }
  9372. else {
  9373. x = node.x + radius;
  9374. y = node.y - node.height / 2;
  9375. }
  9376. this._circle(ctx, x, y, radius);
  9377. point = this._pointOnCircle(x, y, radius, 0.5);
  9378. this._label(ctx, this.label, point.x, point.y);
  9379. }
  9380. };
  9381. /**
  9382. * Get the line width of the edge. Depends on width and whether one of the
  9383. * connected nodes is selected.
  9384. * @return {Number} width
  9385. * @private
  9386. */
  9387. Edge.prototype._getLineWidth = function() {
  9388. if (this.selected == true) {
  9389. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  9390. }
  9391. else {
  9392. return this.width*this.graphScaleInv;
  9393. }
  9394. };
  9395. /**
  9396. * Draw a line between two nodes
  9397. * @param {CanvasRenderingContext2D} ctx
  9398. * @private
  9399. */
  9400. Edge.prototype._line = function (ctx) {
  9401. // draw a straight line
  9402. ctx.beginPath();
  9403. ctx.moveTo(this.from.x, this.from.y);
  9404. if (this.smooth == true) {
  9405. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9406. }
  9407. else {
  9408. ctx.lineTo(this.to.x, this.to.y);
  9409. }
  9410. ctx.stroke();
  9411. };
  9412. /**
  9413. * Draw a line from a node to itself, a circle
  9414. * @param {CanvasRenderingContext2D} ctx
  9415. * @param {Number} x
  9416. * @param {Number} y
  9417. * @param {Number} radius
  9418. * @private
  9419. */
  9420. Edge.prototype._circle = function (ctx, x, y, radius) {
  9421. // draw a circle
  9422. ctx.beginPath();
  9423. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9424. ctx.stroke();
  9425. };
  9426. /**
  9427. * Draw label with white background and with the middle at (x, y)
  9428. * @param {CanvasRenderingContext2D} ctx
  9429. * @param {String} text
  9430. * @param {Number} x
  9431. * @param {Number} y
  9432. * @private
  9433. */
  9434. Edge.prototype._label = function (ctx, text, x, y) {
  9435. if (text) {
  9436. // TODO: cache the calculated size
  9437. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  9438. this.fontSize + "px " + this.fontFace;
  9439. ctx.fillStyle = 'white';
  9440. var width = ctx.measureText(text).width;
  9441. var height = this.fontSize;
  9442. var left = x - width / 2;
  9443. var top = y - height / 2;
  9444. ctx.fillRect(left, top, width, height);
  9445. // draw text
  9446. ctx.fillStyle = this.fontColor || "black";
  9447. ctx.textAlign = "left";
  9448. ctx.textBaseline = "top";
  9449. ctx.fillText(text, left, top);
  9450. }
  9451. };
  9452. /**
  9453. * Redraw a edge as a dashed line
  9454. * Draw this edge in the given canvas
  9455. * @author David Jordan
  9456. * @date 2012-08-08
  9457. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9458. * @param {CanvasRenderingContext2D} ctx
  9459. * @private
  9460. */
  9461. Edge.prototype._drawDashLine = function(ctx) {
  9462. // set style
  9463. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9464. else {ctx.strokeStyle = this.color.color;}
  9465. ctx.lineWidth = this._getLineWidth();
  9466. // only firefox and chrome support this method, else we use the legacy one.
  9467. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  9468. ctx.beginPath();
  9469. ctx.moveTo(this.from.x, this.from.y);
  9470. // configure the dash pattern
  9471. var pattern = [0];
  9472. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  9473. pattern = [this.dash.length,this.dash.gap];
  9474. }
  9475. else {
  9476. pattern = [5,5];
  9477. }
  9478. // set dash settings for chrome or firefox
  9479. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9480. ctx.setLineDash(pattern);
  9481. ctx.lineDashOffset = 0;
  9482. } else { //Firefox
  9483. ctx.mozDash = pattern;
  9484. ctx.mozDashOffset = 0;
  9485. }
  9486. // draw the line
  9487. if (this.smooth == true) {
  9488. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9489. }
  9490. else {
  9491. ctx.lineTo(this.to.x, this.to.y);
  9492. }
  9493. ctx.stroke();
  9494. // restore the dash settings.
  9495. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9496. ctx.setLineDash([0]);
  9497. ctx.lineDashOffset = 0;
  9498. } else { //Firefox
  9499. ctx.mozDash = [0];
  9500. ctx.mozDashOffset = 0;
  9501. }
  9502. }
  9503. else { // unsupporting smooth lines
  9504. // draw dashed line
  9505. ctx.beginPath();
  9506. ctx.lineCap = 'round';
  9507. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9508. {
  9509. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9510. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9511. }
  9512. 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
  9513. {
  9514. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9515. [this.dash.length,this.dash.gap]);
  9516. }
  9517. else //If all else fails draw a line
  9518. {
  9519. ctx.moveTo(this.from.x, this.from.y);
  9520. ctx.lineTo(this.to.x, this.to.y);
  9521. }
  9522. ctx.stroke();
  9523. }
  9524. // draw label
  9525. if (this.label) {
  9526. var point;
  9527. if (this.smooth == true) {
  9528. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9529. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9530. point = {x:midpointX, y:midpointY};
  9531. }
  9532. else {
  9533. point = this._pointOnLine(0.5);
  9534. }
  9535. this._label(ctx, this.label, point.x, point.y);
  9536. }
  9537. };
  9538. /**
  9539. * Get a point on a line
  9540. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9541. * @return {Object} point
  9542. * @private
  9543. */
  9544. Edge.prototype._pointOnLine = function (percentage) {
  9545. return {
  9546. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9547. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9548. }
  9549. };
  9550. /**
  9551. * Get a point on a circle
  9552. * @param {Number} x
  9553. * @param {Number} y
  9554. * @param {Number} radius
  9555. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9556. * @return {Object} point
  9557. * @private
  9558. */
  9559. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9560. var angle = (percentage - 3/8) * 2 * Math.PI;
  9561. return {
  9562. x: x + radius * Math.cos(angle),
  9563. y: y - radius * Math.sin(angle)
  9564. }
  9565. };
  9566. /**
  9567. * Redraw a edge as a line with an arrow halfway the line
  9568. * Draw this edge in the given canvas
  9569. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9570. * @param {CanvasRenderingContext2D} ctx
  9571. * @private
  9572. */
  9573. Edge.prototype._drawArrowCenter = function(ctx) {
  9574. var point;
  9575. // set style
  9576. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9577. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9578. ctx.lineWidth = this._getLineWidth();
  9579. if (this.from != this.to) {
  9580. // draw line
  9581. this._line(ctx);
  9582. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9583. var length = 10 + 5 * this.width; // TODO: make customizable?
  9584. // draw an arrow halfway the line
  9585. if (this.smooth == true) {
  9586. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9587. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9588. point = {x:midpointX, y:midpointY};
  9589. }
  9590. else {
  9591. point = this._pointOnLine(0.5);
  9592. }
  9593. ctx.arrow(point.x, point.y, angle, length);
  9594. ctx.fill();
  9595. ctx.stroke();
  9596. // draw label
  9597. if (this.label) {
  9598. this._label(ctx, this.label, point.x, point.y);
  9599. }
  9600. }
  9601. else {
  9602. // draw circle
  9603. var x, y;
  9604. var radius = 0.25 * Math.max(100,this.length);
  9605. var node = this.from;
  9606. if (!node.width) {
  9607. node.resize(ctx);
  9608. }
  9609. if (node.width > node.height) {
  9610. x = node.x + node.width * 0.5;
  9611. y = node.y - radius;
  9612. }
  9613. else {
  9614. x = node.x + radius;
  9615. y = node.y - node.height * 0.5;
  9616. }
  9617. this._circle(ctx, x, y, radius);
  9618. // draw all arrows
  9619. var angle = 0.2 * Math.PI;
  9620. var length = 10 + 5 * this.width; // TODO: make customizable?
  9621. point = this._pointOnCircle(x, y, radius, 0.5);
  9622. ctx.arrow(point.x, point.y, angle, length);
  9623. ctx.fill();
  9624. ctx.stroke();
  9625. // draw label
  9626. if (this.label) {
  9627. point = this._pointOnCircle(x, y, radius, 0.5);
  9628. this._label(ctx, this.label, point.x, point.y);
  9629. }
  9630. }
  9631. };
  9632. /**
  9633. * Redraw a edge as a line with an arrow
  9634. * Draw this edge in the given canvas
  9635. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9636. * @param {CanvasRenderingContext2D} ctx
  9637. * @private
  9638. */
  9639. Edge.prototype._drawArrow = function(ctx) {
  9640. // set style
  9641. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9642. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9643. ctx.lineWidth = this._getLineWidth();
  9644. var angle, length;
  9645. //draw a line
  9646. if (this.from != this.to) {
  9647. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9648. var dx = (this.to.x - this.from.x);
  9649. var dy = (this.to.y - this.from.y);
  9650. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9651. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9652. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9653. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9654. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9655. if (this.smooth == true) {
  9656. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9657. dx = (this.to.x - this.via.x);
  9658. dy = (this.to.y - this.via.y);
  9659. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9660. }
  9661. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9662. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9663. var xTo,yTo;
  9664. if (this.smooth == true) {
  9665. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9666. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9667. }
  9668. else {
  9669. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9670. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9671. }
  9672. ctx.beginPath();
  9673. ctx.moveTo(xFrom,yFrom);
  9674. if (this.smooth == true) {
  9675. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9676. }
  9677. else {
  9678. ctx.lineTo(xTo, yTo);
  9679. }
  9680. ctx.stroke();
  9681. // draw arrow at the end of the line
  9682. length = 10 + 5 * this.width;
  9683. ctx.arrow(xTo, yTo, angle, length);
  9684. ctx.fill();
  9685. ctx.stroke();
  9686. // draw label
  9687. if (this.label) {
  9688. var point;
  9689. if (this.smooth == true) {
  9690. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9691. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9692. point = {x:midpointX, y:midpointY};
  9693. }
  9694. else {
  9695. point = this._pointOnLine(0.5);
  9696. }
  9697. this._label(ctx, this.label, point.x, point.y);
  9698. }
  9699. }
  9700. else {
  9701. // draw circle
  9702. var node = this.from;
  9703. var x, y, arrow;
  9704. var radius = 0.25 * Math.max(100,this.length);
  9705. if (!node.width) {
  9706. node.resize(ctx);
  9707. }
  9708. if (node.width > node.height) {
  9709. x = node.x + node.width * 0.5;
  9710. y = node.y - radius;
  9711. arrow = {
  9712. x: x,
  9713. y: node.y,
  9714. angle: 0.9 * Math.PI
  9715. };
  9716. }
  9717. else {
  9718. x = node.x + radius;
  9719. y = node.y - node.height * 0.5;
  9720. arrow = {
  9721. x: node.x,
  9722. y: y,
  9723. angle: 0.6 * Math.PI
  9724. };
  9725. }
  9726. ctx.beginPath();
  9727. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9728. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9729. ctx.stroke();
  9730. // draw all arrows
  9731. length = 10 + 5 * this.width; // TODO: make customizable?
  9732. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9733. ctx.fill();
  9734. ctx.stroke();
  9735. // draw label
  9736. if (this.label) {
  9737. point = this._pointOnCircle(x, y, radius, 0.5);
  9738. this._label(ctx, this.label, point.x, point.y);
  9739. }
  9740. }
  9741. };
  9742. /**
  9743. * Calculate the distance between a point (x3,y3) and a line segment from
  9744. * (x1,y1) to (x2,y2).
  9745. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9746. * @param {number} x1
  9747. * @param {number} y1
  9748. * @param {number} x2
  9749. * @param {number} y2
  9750. * @param {number} x3
  9751. * @param {number} y3
  9752. * @private
  9753. */
  9754. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9755. if (this.smooth == true) {
  9756. var minDistance = 1e9;
  9757. var i,t,x,y,dx,dy;
  9758. for (i = 0; i < 10; i++) {
  9759. t = 0.1*i;
  9760. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9761. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9762. dx = Math.abs(x3-x);
  9763. dy = Math.abs(y3-y);
  9764. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9765. }
  9766. return minDistance
  9767. }
  9768. else {
  9769. var px = x2-x1,
  9770. py = y2-y1,
  9771. something = px*px + py*py,
  9772. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9773. if (u > 1) {
  9774. u = 1;
  9775. }
  9776. else if (u < 0) {
  9777. u = 0;
  9778. }
  9779. var x = x1 + u * px,
  9780. y = y1 + u * py,
  9781. dx = x - x3,
  9782. dy = y - y3;
  9783. //# Note: If the actual distance does not matter,
  9784. //# if you only want to compare what this function
  9785. //# returns to other results of this function, you
  9786. //# can just return the squared distance instead
  9787. //# (i.e. remove the sqrt) to gain a little performance
  9788. return Math.sqrt(dx*dx + dy*dy);
  9789. }
  9790. };
  9791. /**
  9792. * This allows the zoom level of the graph to influence the rendering
  9793. *
  9794. * @param scale
  9795. */
  9796. Edge.prototype.setScale = function(scale) {
  9797. this.graphScaleInv = 1.0/scale;
  9798. };
  9799. Edge.prototype.select = function() {
  9800. this.selected = true;
  9801. };
  9802. Edge.prototype.unselect = function() {
  9803. this.selected = false;
  9804. };
  9805. Edge.prototype.positionBezierNode = function() {
  9806. if (this.via !== null) {
  9807. this.via.x = 0.5 * (this.from.x + this.to.x);
  9808. this.via.y = 0.5 * (this.from.y + this.to.y);
  9809. }
  9810. };
  9811. /**
  9812. * Popup is a class to create a popup window with some text
  9813. * @param {Element} container The container object.
  9814. * @param {Number} [x]
  9815. * @param {Number} [y]
  9816. * @param {String} [text]
  9817. */
  9818. function Popup(container, x, y, text) {
  9819. if (container) {
  9820. this.container = container;
  9821. }
  9822. else {
  9823. this.container = document.body;
  9824. }
  9825. this.x = 0;
  9826. this.y = 0;
  9827. this.padding = 5;
  9828. if (x !== undefined && y !== undefined ) {
  9829. this.setPosition(x, y);
  9830. }
  9831. if (text !== undefined) {
  9832. this.setText(text);
  9833. }
  9834. // create the frame
  9835. this.frame = document.createElement("div");
  9836. var style = this.frame.style;
  9837. style.position = "absolute";
  9838. style.visibility = "hidden";
  9839. style.border = "1px solid #666";
  9840. style.color = "black";
  9841. style.padding = this.padding + "px";
  9842. style.backgroundColor = "#FFFFC6";
  9843. style.borderRadius = "3px";
  9844. style.MozBorderRadius = "3px";
  9845. style.WebkitBorderRadius = "3px";
  9846. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9847. style.whiteSpace = "nowrap";
  9848. this.container.appendChild(this.frame);
  9849. }
  9850. /**
  9851. * @param {number} x Horizontal position of the popup window
  9852. * @param {number} y Vertical position of the popup window
  9853. */
  9854. Popup.prototype.setPosition = function(x, y) {
  9855. this.x = parseInt(x);
  9856. this.y = parseInt(y);
  9857. };
  9858. /**
  9859. * Set the text for the popup window. This can be HTML code
  9860. * @param {string} text
  9861. */
  9862. Popup.prototype.setText = function(text) {
  9863. this.frame.innerHTML = text;
  9864. };
  9865. /**
  9866. * Show the popup window
  9867. * @param {boolean} show Optional. Show or hide the window
  9868. */
  9869. Popup.prototype.show = function (show) {
  9870. if (show === undefined) {
  9871. show = true;
  9872. }
  9873. if (show) {
  9874. var height = this.frame.clientHeight;
  9875. var width = this.frame.clientWidth;
  9876. var maxHeight = this.frame.parentNode.clientHeight;
  9877. var maxWidth = this.frame.parentNode.clientWidth;
  9878. var top = (this.y - height);
  9879. if (top + height + this.padding > maxHeight) {
  9880. top = maxHeight - height - this.padding;
  9881. }
  9882. if (top < this.padding) {
  9883. top = this.padding;
  9884. }
  9885. var left = this.x;
  9886. if (left + width + this.padding > maxWidth) {
  9887. left = maxWidth - width - this.padding;
  9888. }
  9889. if (left < this.padding) {
  9890. left = this.padding;
  9891. }
  9892. this.frame.style.left = left + "px";
  9893. this.frame.style.top = top + "px";
  9894. this.frame.style.visibility = "visible";
  9895. }
  9896. else {
  9897. this.hide();
  9898. }
  9899. };
  9900. /**
  9901. * Hide the popup window
  9902. */
  9903. Popup.prototype.hide = function () {
  9904. this.frame.style.visibility = "hidden";
  9905. };
  9906. /**
  9907. * @class Groups
  9908. * This class can store groups and properties specific for groups.
  9909. */
  9910. Groups = function () {
  9911. this.clear();
  9912. this.defaultIndex = 0;
  9913. };
  9914. /**
  9915. * default constants for group colors
  9916. */
  9917. Groups.DEFAULT = [
  9918. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9919. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9920. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9921. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9922. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9923. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9924. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9925. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9926. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9927. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9928. ];
  9929. /**
  9930. * Clear all groups
  9931. */
  9932. Groups.prototype.clear = function () {
  9933. this.groups = {};
  9934. this.groups.length = function()
  9935. {
  9936. var i = 0;
  9937. for ( var p in this ) {
  9938. if (this.hasOwnProperty(p)) {
  9939. i++;
  9940. }
  9941. }
  9942. return i;
  9943. }
  9944. };
  9945. /**
  9946. * get group properties of a groupname. If groupname is not found, a new group
  9947. * is added.
  9948. * @param {*} groupname Can be a number, string, Date, etc.
  9949. * @return {Object} group The created group, containing all group properties
  9950. */
  9951. Groups.prototype.get = function (groupname) {
  9952. var group = this.groups[groupname];
  9953. if (group == undefined) {
  9954. // create new group
  9955. var index = this.defaultIndex % Groups.DEFAULT.length;
  9956. this.defaultIndex++;
  9957. group = {};
  9958. group.color = Groups.DEFAULT[index];
  9959. this.groups[groupname] = group;
  9960. }
  9961. return group;
  9962. };
  9963. /**
  9964. * Add a custom group style
  9965. * @param {String} groupname
  9966. * @param {Object} style An object containing borderColor,
  9967. * backgroundColor, etc.
  9968. * @return {Object} group The created group object
  9969. */
  9970. Groups.prototype.add = function (groupname, style) {
  9971. this.groups[groupname] = style;
  9972. if (style.color) {
  9973. style.color = Node.parseColor(style.color);
  9974. }
  9975. return style;
  9976. };
  9977. /**
  9978. * @class Images
  9979. * This class loads images and keeps them stored.
  9980. */
  9981. Images = function () {
  9982. this.images = {};
  9983. this.callback = undefined;
  9984. };
  9985. /**
  9986. * Set an onload callback function. This will be called each time an image
  9987. * is loaded
  9988. * @param {function} callback
  9989. */
  9990. Images.prototype.setOnloadCallback = function(callback) {
  9991. this.callback = callback;
  9992. };
  9993. /**
  9994. *
  9995. * @param {string} url Url of the image
  9996. * @return {Image} img The image object
  9997. */
  9998. Images.prototype.load = function(url) {
  9999. var img = this.images[url];
  10000. if (img == undefined) {
  10001. // create the image
  10002. var images = this;
  10003. img = new Image();
  10004. this.images[url] = img;
  10005. img.onload = function() {
  10006. if (images.callback) {
  10007. images.callback(this);
  10008. }
  10009. };
  10010. img.src = url;
  10011. }
  10012. return img;
  10013. };
  10014. /**
  10015. * Created by Alex on 2/6/14.
  10016. */
  10017. var physicsMixin = {
  10018. /**
  10019. * Toggling barnes Hut calculation on and off.
  10020. *
  10021. * @private
  10022. */
  10023. _toggleBarnesHut : function() {
  10024. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  10025. this._loadSelectedForceSolver();
  10026. this.moving = true;
  10027. this.start();
  10028. },
  10029. /**
  10030. * This loads the node force solver based on the barnes hut or repulsion algorithm
  10031. *
  10032. * @private
  10033. */
  10034. _loadSelectedForceSolver : function() {
  10035. // this overloads the this._calculateNodeForces
  10036. if (this.constants.physics.barnesHut.enabled == true) {
  10037. this._clearMixin(repulsionMixin);
  10038. this._clearMixin(hierarchalRepulsionMixin);
  10039. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  10040. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  10041. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  10042. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  10043. this._loadMixin(barnesHutMixin);
  10044. }
  10045. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  10046. this._clearMixin(barnesHutMixin);
  10047. this._clearMixin(repulsionMixin);
  10048. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  10049. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  10050. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  10051. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  10052. this._loadMixin(hierarchalRepulsionMixin);
  10053. }
  10054. else {
  10055. this._clearMixin(barnesHutMixin);
  10056. this._clearMixin(hierarchalRepulsionMixin);
  10057. this.barnesHutTree = undefined;
  10058. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  10059. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  10060. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  10061. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  10062. this._loadMixin(repulsionMixin);
  10063. }
  10064. },
  10065. /**
  10066. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  10067. * if there is more than one node. If it is just one node, we dont calculate anything.
  10068. *
  10069. * @private
  10070. */
  10071. _initializeForceCalculation : function() {
  10072. // stop calculation if there is only one node
  10073. if (this.nodeIndices.length == 1) {
  10074. this.nodes[this.nodeIndices[0]]._setForce(0,0);
  10075. }
  10076. else {
  10077. // if there are too many nodes on screen, we cluster without repositioning
  10078. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  10079. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  10080. }
  10081. // we now start the force calculation
  10082. this._calculateForces();
  10083. }
  10084. },
  10085. /**
  10086. * Calculate the external forces acting on the nodes
  10087. * Forces are caused by: edges, repulsing forces between nodes, gravity
  10088. * @private
  10089. */
  10090. _calculateForces : function() {
  10091. // Gravity is required to keep separated groups from floating off
  10092. // the forces are reset to zero in this loop by using _setForce instead
  10093. // of _addForce
  10094. this._calculateGravitationalForces();
  10095. this._calculateNodeForces();
  10096. if (this.constants.smoothCurves == true) {
  10097. this._calculateSpringForcesWithSupport();
  10098. }
  10099. else {
  10100. this._calculateSpringForces();
  10101. }
  10102. },
  10103. /**
  10104. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  10105. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  10106. * This function joins the datanodes and invisible (called support) nodes into one object.
  10107. * We do this so we do not contaminate this.nodes with the support nodes.
  10108. *
  10109. * @private
  10110. */
  10111. _updateCalculationNodes : function() {
  10112. if (this.constants.smoothCurves == true) {
  10113. this.calculationNodes = {};
  10114. this.calculationNodeIndices = [];
  10115. for (var nodeId in this.nodes) {
  10116. if (this.nodes.hasOwnProperty(nodeId)) {
  10117. this.calculationNodes[nodeId] = this.nodes[nodeId];
  10118. }
  10119. }
  10120. var supportNodes = this.sectors['support']['nodes'];
  10121. for (var supportNodeId in supportNodes) {
  10122. if (supportNodes.hasOwnProperty(supportNodeId)) {
  10123. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  10124. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  10125. }
  10126. else {
  10127. supportNodes[supportNodeId]._setForce(0,0);
  10128. }
  10129. }
  10130. }
  10131. for (var idx in this.calculationNodes) {
  10132. if (this.calculationNodes.hasOwnProperty(idx)) {
  10133. this.calculationNodeIndices.push(idx);
  10134. }
  10135. }
  10136. }
  10137. else {
  10138. this.calculationNodes = this.nodes;
  10139. this.calculationNodeIndices = this.nodeIndices;
  10140. }
  10141. },
  10142. /**
  10143. * this function applies the central gravity effect to keep groups from floating off
  10144. *
  10145. * @private
  10146. */
  10147. _calculateGravitationalForces : function() {
  10148. var dx, dy, distance, node, i;
  10149. var nodes = this.calculationNodes;
  10150. var gravity = this.constants.physics.centralGravity;
  10151. var gravityForce = 0;
  10152. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  10153. node = nodes[this.calculationNodeIndices[i]];
  10154. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  10155. // gravity does not apply when we are in a pocket sector
  10156. if (this._sector() == "default" && gravity != 0) {
  10157. dx = -node.x;
  10158. dy = -node.y;
  10159. distance = Math.sqrt(dx*dx + dy*dy);
  10160. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  10161. node.fx = dx * gravityForce;
  10162. node.fy = dy * gravityForce;
  10163. }
  10164. else {
  10165. node.fx = 0;
  10166. node.fy = 0;
  10167. }
  10168. }
  10169. },
  10170. /**
  10171. * this function calculates the effects of the springs in the case of unsmooth curves.
  10172. *
  10173. * @private
  10174. */
  10175. _calculateSpringForces : function() {
  10176. var edgeLength, edge, edgeId;
  10177. var dx, dy, fx, fy, springForce, length;
  10178. var edges = this.edges;
  10179. // forces caused by the edges, modelled as springs
  10180. for (edgeId in edges) {
  10181. if (edges.hasOwnProperty(edgeId)) {
  10182. edge = edges[edgeId];
  10183. if (edge.connected) {
  10184. // only calculate forces if nodes are in the same sector
  10185. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10186. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  10187. // this implies that the edges between big clusters are longer
  10188. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  10189. dx = (edge.from.x - edge.to.x);
  10190. dy = (edge.from.y - edge.to.y);
  10191. length = Math.sqrt(dx * dx + dy * dy);
  10192. if (length == 0) {
  10193. length = 0.01;
  10194. }
  10195. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10196. fx = dx * springForce;
  10197. fy = dy * springForce;
  10198. edge.from.fx += fx;
  10199. edge.from.fy += fy;
  10200. edge.to.fx -= fx;
  10201. edge.to.fy -= fy;
  10202. }
  10203. }
  10204. }
  10205. }
  10206. },
  10207. /**
  10208. * This function calculates the springforces on the nodes, accounting for the support nodes.
  10209. *
  10210. * @private
  10211. */
  10212. _calculateSpringForcesWithSupport : function() {
  10213. var edgeLength, edge, edgeId, combinedClusterSize;
  10214. var edges = this.edges;
  10215. // forces caused by the edges, modelled as springs
  10216. for (edgeId in edges) {
  10217. if (edges.hasOwnProperty(edgeId)) {
  10218. edge = edges[edgeId];
  10219. if (edge.connected) {
  10220. // only calculate forces if nodes are in the same sector
  10221. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10222. if (edge.via != null) {
  10223. var node1 = edge.to;
  10224. var node2 = edge.via;
  10225. var node3 = edge.from;
  10226. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  10227. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  10228. // this implies that the edges between big clusters are longer
  10229. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  10230. this._calculateSpringForce(node1,node2,0.5*edgeLength);
  10231. this._calculateSpringForce(node2,node3,0.5*edgeLength);
  10232. }
  10233. }
  10234. }
  10235. }
  10236. }
  10237. },
  10238. /**
  10239. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  10240. *
  10241. * @param node1
  10242. * @param node2
  10243. * @param edgeLength
  10244. * @private
  10245. */
  10246. _calculateSpringForce : function(node1,node2,edgeLength) {
  10247. var dx, dy, fx, fy, springForce, length;
  10248. dx = (node1.x - node2.x);
  10249. dy = (node1.y - node2.y);
  10250. length = Math.sqrt(dx * dx + dy * dy);
  10251. if (length == 0) {
  10252. length = 0.01;
  10253. }
  10254. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10255. fx = dx * springForce;
  10256. fy = dy * springForce;
  10257. node1.fx += fx;
  10258. node1.fy += fy;
  10259. node2.fx -= fx;
  10260. node2.fy -= fy;
  10261. },
  10262. /**
  10263. * Load the HTML for the physics config and bind it
  10264. * @private
  10265. */
  10266. _loadPhysicsConfiguration : function() {
  10267. if (this.physicsConfiguration === undefined) {
  10268. this.backupConstants = {};
  10269. util.copyObject(this.constants,this.backupConstants);
  10270. var hierarchicalLayoutDirections = ["LR","RL","UD","DU"];
  10271. this.physicsConfiguration = document.createElement('div');
  10272. this.physicsConfiguration.className = "PhysicsConfiguration";
  10273. this.physicsConfiguration.innerHTML = '' +
  10274. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  10275. '<tr>' +
  10276. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  10277. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>'+
  10278. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  10279. '</tr>'+
  10280. '</table>' +
  10281. '<table id="graph_BH_table" style="display:none">'+
  10282. '<tr><td><b>Barnes Hut</b></td></tr>'+
  10283. '<tr>'+
  10284. '<td width="150px">gravitationalConstant</td><td>0</td><td><input type="range" min="500" 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>'+
  10285. '</tr>'+
  10286. '<tr>'+
  10287. '<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>'+
  10288. '</tr>'+
  10289. '<tr>'+
  10290. '<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>'+
  10291. '</tr>'+
  10292. '<tr>'+
  10293. '<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>'+
  10294. '</tr>'+
  10295. '<tr>'+
  10296. '<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>'+
  10297. '</tr>'+
  10298. '</table>'+
  10299. '<table id="graph_R_table" style="display:none">'+
  10300. '<tr><td><b>Repulsion</b></td></tr>'+
  10301. '<tr>'+
  10302. '<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>'+
  10303. '</tr>'+
  10304. '<tr>'+
  10305. '<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>'+
  10306. '</tr>'+
  10307. '<tr>'+
  10308. '<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>'+
  10309. '</tr>'+
  10310. '<tr>'+
  10311. '<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>'+
  10312. '</tr>'+
  10313. '<tr>'+
  10314. '<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>'+
  10315. '</tr>'+
  10316. '</table>'+
  10317. '<table id="graph_H_table" style="display:none">'+
  10318. '<tr><td width="150"><b>Hierarchical</b></td></tr>'+
  10319. '<tr>'+
  10320. '<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>'+
  10321. '</tr>'+
  10322. '<tr>'+
  10323. '<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>'+
  10324. '</tr>'+
  10325. '<tr>'+
  10326. '<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>'+
  10327. '</tr>'+
  10328. '<tr>'+
  10329. '<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>'+
  10330. '</tr>'+
  10331. '<tr>'+
  10332. '<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>'+
  10333. '</tr>'+
  10334. '<tr>'+
  10335. '<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>'+
  10336. '</tr>'+
  10337. '<tr>'+
  10338. '<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>'+
  10339. '</tr>'+
  10340. '<tr>'+
  10341. '<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>'+
  10342. '</tr>'+
  10343. '</table>' +
  10344. '<table><tr><td><b>Options:</b></td></tr>' +
  10345. '<tr>' +
  10346. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  10347. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  10348. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  10349. '</tr>'+
  10350. '</table>'
  10351. this.containerElement.parentElement.insertBefore(this.physicsConfiguration,this.containerElement);
  10352. this.optionsDiv = document.createElement("div");
  10353. this.optionsDiv.style.fontSize = "14px";
  10354. this.optionsDiv.style.fontFamily = "verdana";
  10355. this.containerElement.parentElement.insertBefore(this.optionsDiv,this.containerElement);
  10356. var rangeElement;
  10357. rangeElement = document.getElementById('graph_BH_gc');
  10358. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_gc',-1,"physics_barnesHut_gravitationalConstant");
  10359. rangeElement = document.getElementById('graph_BH_cg');
  10360. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_cg',1,"physics_centralGravity");
  10361. rangeElement = document.getElementById('graph_BH_sc');
  10362. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_sc',1,"physics_springConstant");
  10363. rangeElement = document.getElementById('graph_BH_sl');
  10364. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_sl',1,"physics_springLength");
  10365. rangeElement = document.getElementById('graph_BH_damp');
  10366. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_damp',1,"physics_damping");
  10367. rangeElement = document.getElementById('graph_R_nd');
  10368. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_nd',1,"physics_repulsion_nodeDistance");
  10369. rangeElement = document.getElementById('graph_R_cg');
  10370. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_cg',1,"physics_centralGravity");
  10371. rangeElement = document.getElementById('graph_R_sc');
  10372. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_sc',1,"physics_springConstant");
  10373. rangeElement = document.getElementById('graph_R_sl');
  10374. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_sl',1,"physics_springLength");
  10375. rangeElement = document.getElementById('graph_R_damp');
  10376. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_damp',1,"physics_damping");
  10377. rangeElement = document.getElementById('graph_H_nd');
  10378. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_nd',1,"physics_hierarchicalRepulsion_nodeDistance");
  10379. rangeElement = document.getElementById('graph_H_cg');
  10380. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_cg',1,"physics_centralGravity");
  10381. rangeElement = document.getElementById('graph_H_sc');
  10382. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_sc',1,"physics_springConstant");
  10383. rangeElement = document.getElementById('graph_H_sl');
  10384. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_sl',1,"physics_springLength");
  10385. rangeElement = document.getElementById('graph_H_damp');
  10386. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_damp',1,"physics_damping");
  10387. rangeElement = document.getElementById('graph_H_direction');
  10388. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_direction',hierarchicalLayoutDirections,"hierarchicalLayout_direction");
  10389. rangeElement = document.getElementById('graph_H_levsep');
  10390. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_levsep',1,"hierarchicalLayout_levelSeparation");
  10391. rangeElement = document.getElementById('graph_H_nspac');
  10392. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_nspac',1,"hierarchicalLayout_nodeSpacing");
  10393. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10394. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10395. var radioButton3 = document.getElementById("graph_physicsMethod3");
  10396. radioButton2.checked = true;
  10397. if (this.constants.physics.barnesHut.enabled) {
  10398. radioButton1.checked = true;
  10399. }
  10400. if (this.constants.hierarchicalLayout.enabled) {
  10401. radioButton3.checked = true;
  10402. }
  10403. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10404. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  10405. var graph_generateOptions = document.getElementById("graph_generateOptions");
  10406. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  10407. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  10408. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  10409. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10410. else {graph_toggleSmooth.style.background = "#FF8532";}
  10411. switchConfigurations.apply(this);
  10412. radioButton1.onchange = switchConfigurations.bind(this);
  10413. radioButton2.onchange = switchConfigurations.bind(this);
  10414. radioButton3.onchange = switchConfigurations.bind(this);
  10415. }
  10416. },
  10417. _overWriteGraphConstants : function(constantsVariableName, value) {
  10418. var nameArray = constantsVariableName.split("_");
  10419. if (nameArray.length == 1) {
  10420. this.constants[nameArray[0]] = value;
  10421. }
  10422. else if (nameArray.length == 2) {
  10423. this.constants[nameArray[0]][nameArray[1]] = value;
  10424. }
  10425. else if (nameArray.length == 3) {
  10426. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  10427. }
  10428. }
  10429. }
  10430. function graphToggleSmoothCurves () {
  10431. this.constants.smoothCurves = !this.constants.smoothCurves;
  10432. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10433. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10434. else {graph_toggleSmooth.style.background = "#FF8532";}
  10435. this._configureSmoothCurves(false);
  10436. };
  10437. function graphRepositionNodes () {
  10438. for (var nodeId in this.calculationNodes) {
  10439. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  10440. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  10441. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  10442. }
  10443. }
  10444. if (this.constants.hierarchicalLayout.enabled == true) {
  10445. this._setupHierarchicalLayout();
  10446. }
  10447. else {
  10448. this.repositionNodes();
  10449. }
  10450. this.moving = true;
  10451. this.start();
  10452. };
  10453. function graphGenerateOptions () {
  10454. var options = "No options are required, default values used."
  10455. var optionsSpecific = [];
  10456. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10457. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10458. if (radioButton1.checked == true) {
  10459. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  10460. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10461. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10462. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10463. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10464. if (optionsSpecific.length != 0) {
  10465. options = "var options = {"
  10466. options += "physics: {barnesHut: {"
  10467. for (var i = 0; i < optionsSpecific.length; i++) {
  10468. options += optionsSpecific[i];
  10469. if (i < optionsSpecific.length - 1) {
  10470. options += ", "
  10471. }
  10472. }
  10473. options += '}}'
  10474. }
  10475. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10476. if (optionsSpecific.length == 0) {options = "var options = {";}
  10477. else {options += ", "}
  10478. options += "smoothCurves: " + this.constants.smoothCurves;
  10479. }
  10480. if (options != "No options are required, default values used.") {
  10481. options += '};'
  10482. }
  10483. }
  10484. else if (radioButton2.checked == true) {
  10485. options = "var options = {"
  10486. options += "physics: {barnesHut: {enabled: false}";
  10487. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  10488. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10489. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10490. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10491. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10492. if (optionsSpecific.length != 0) {
  10493. options += ", repulsion: {"
  10494. for (var i = 0; i < optionsSpecific.length; i++) {
  10495. options += optionsSpecific[i];
  10496. if (i < optionsSpecific.length - 1) {
  10497. options += ", "
  10498. }
  10499. }
  10500. options += '}}'
  10501. }
  10502. if (optionsSpecific.length == 0) {options += "}"}
  10503. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10504. options += ", smoothCurves: " + this.constants.smoothCurves;
  10505. }
  10506. options += '};'
  10507. }
  10508. else {
  10509. options = "var options = {"
  10510. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  10511. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10512. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10513. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10514. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10515. if (optionsSpecific.length != 0) {
  10516. options += "physics: {hierarchicalRepulsion: {"
  10517. for (var i = 0; i < optionsSpecific.length; i++) {
  10518. options += optionsSpecific[i];
  10519. if (i < optionsSpecific.length - 1) {
  10520. options += ", ";
  10521. }
  10522. }
  10523. options += '}},';
  10524. }
  10525. options += 'hierarchicalLayout: {';
  10526. optionsSpecific = [];
  10527. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  10528. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  10529. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  10530. if (optionsSpecific.length != 0) {
  10531. for (var i = 0; i < optionsSpecific.length; i++) {
  10532. options += optionsSpecific[i];
  10533. if (i < optionsSpecific.length - 1) {
  10534. options += ", "
  10535. }
  10536. }
  10537. options += '}'
  10538. }
  10539. else {
  10540. options += "enabled:true}";
  10541. }
  10542. options += '};'
  10543. }
  10544. this.optionsDiv.innerHTML = options;
  10545. };
  10546. function switchConfigurations () {
  10547. var ids = ["graph_BH_table","graph_R_table","graph_H_table"]
  10548. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  10549. var tableId = "graph_" + radioButton + "_table";
  10550. var table = document.getElementById(tableId);
  10551. table.style.display = "block";
  10552. for (var i = 0; i < ids.length; i++) {
  10553. if (ids[i] != tableId) {
  10554. table = document.getElementById(ids[i]);
  10555. table.style.display = "none";
  10556. }
  10557. }
  10558. this._restoreNodes();
  10559. if (radioButton == "R") {
  10560. this.constants.hierarchicalLayout.enabled = false;
  10561. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10562. this.constants.physics.barnesHut.enabled = false;
  10563. }
  10564. else if (radioButton == "H") {
  10565. this.constants.hierarchicalLayout.enabled = true;
  10566. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10567. this.constants.physics.barnesHut.enabled = false;
  10568. this._setupHierarchicalLayout();
  10569. }
  10570. else {
  10571. this.constants.hierarchicalLayout.enabled = false;
  10572. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10573. this.constants.physics.barnesHut.enabled = true;
  10574. }
  10575. this._loadSelectedForceSolver();
  10576. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10577. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10578. else {graph_toggleSmooth.style.background = "#FF8532";}
  10579. this.moving = true;
  10580. this.start();
  10581. }
  10582. function showValueOfRange (id,map,constantsVariableName) {
  10583. var valueId = id + "_value";
  10584. var rangeValue = document.getElementById(id).value;
  10585. if (map instanceof Array) {
  10586. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  10587. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  10588. }
  10589. else {
  10590. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  10591. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  10592. }
  10593. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10594. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10595. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10596. this._setupHierarchicalLayout();
  10597. }
  10598. this.moving = true;
  10599. this.start();
  10600. };
  10601. /**
  10602. * Created by Alex on 2/10/14.
  10603. */
  10604. var hierarchalRepulsionMixin = {
  10605. /**
  10606. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10607. * This field is linearly approximated.
  10608. *
  10609. * @private
  10610. */
  10611. _calculateNodeForces : function() {
  10612. var dx, dy, distance, fx, fy, combinedClusterSize,
  10613. repulsingForce, node1, node2, i, j;
  10614. var nodes = this.calculationNodes;
  10615. var nodeIndices = this.calculationNodeIndices;
  10616. // approximation constants
  10617. var b = 5;
  10618. var a_base = 0.5*-b;
  10619. // repulsing forces between nodes
  10620. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  10621. var minimumDistance = nodeDistance;
  10622. // we loop from i over all but the last entree in the array
  10623. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10624. for (i = 0; i < nodeIndices.length-1; i++) {
  10625. node1 = nodes[nodeIndices[i]];
  10626. for (j = i+1; j < nodeIndices.length; j++) {
  10627. node2 = nodes[nodeIndices[j]];
  10628. dx = node2.x - node1.x;
  10629. dy = node2.y - node1.y;
  10630. distance = Math.sqrt(dx * dx + dy * dy);
  10631. var a = a_base / minimumDistance;
  10632. if (distance < 2*minimumDistance) {
  10633. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10634. // normalize force with
  10635. if (distance == 0) {
  10636. distance = 0.01;
  10637. }
  10638. else {
  10639. repulsingForce = repulsingForce/distance;
  10640. }
  10641. fx = dx * repulsingForce;
  10642. fy = dy * repulsingForce;
  10643. node1.fx -= fx;
  10644. node1.fy -= fy;
  10645. node2.fx += fx;
  10646. node2.fy += fy;
  10647. }
  10648. }
  10649. }
  10650. }
  10651. }
  10652. /**
  10653. * Created by Alex on 2/10/14.
  10654. */
  10655. var barnesHutMixin = {
  10656. /**
  10657. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10658. * The Barnes Hut method is used to speed up this N-body simulation.
  10659. *
  10660. * @private
  10661. */
  10662. _calculateNodeForces : function() {
  10663. var node;
  10664. var nodes = this.calculationNodes;
  10665. var nodeIndices = this.calculationNodeIndices;
  10666. var nodeCount = nodeIndices.length;
  10667. this._formBarnesHutTree(nodes,nodeIndices);
  10668. var barnesHutTree = this.barnesHutTree;
  10669. // place the nodes one by one recursively
  10670. for (var i = 0; i < nodeCount; i++) {
  10671. node = nodes[nodeIndices[i]];
  10672. // starting with root is irrelevant, it never passes the BarnesHut condition
  10673. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10674. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10675. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10676. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10677. }
  10678. },
  10679. /**
  10680. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10681. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10682. *
  10683. * @param parentBranch
  10684. * @param node
  10685. * @private
  10686. */
  10687. _getForceContribution : function(parentBranch,node) {
  10688. // we get no force contribution from an empty region
  10689. if (parentBranch.childrenCount > 0) {
  10690. var dx,dy,distance;
  10691. // get the distance from the center of mass to the node.
  10692. dx = parentBranch.centerOfMass.x - node.x;
  10693. dy = parentBranch.centerOfMass.y - node.y;
  10694. distance = Math.sqrt(dx * dx + dy * dy);
  10695. // BarnesHut condition
  10696. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10697. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10698. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10699. // duplicate code to reduce function calls to speed up program
  10700. if (distance == 0) {
  10701. distance = 0.1*Math.random();
  10702. dx = distance;
  10703. }
  10704. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10705. var fx = dx * gravityForce;
  10706. var fy = dy * gravityForce;
  10707. node.fx += fx;
  10708. node.fy += fy;
  10709. }
  10710. else {
  10711. // Did not pass the condition, go into children if available
  10712. if (parentBranch.childrenCount == 4) {
  10713. this._getForceContribution(parentBranch.children.NW,node);
  10714. this._getForceContribution(parentBranch.children.NE,node);
  10715. this._getForceContribution(parentBranch.children.SW,node);
  10716. this._getForceContribution(parentBranch.children.SE,node);
  10717. }
  10718. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10719. if (parentBranch.children.data.id != node.id) { // if it is not self
  10720. // duplicate code to reduce function calls to speed up program
  10721. if (distance == 0) {
  10722. distance = 0.5*Math.random();
  10723. dx = distance;
  10724. }
  10725. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10726. var fx = dx * gravityForce;
  10727. var fy = dy * gravityForce;
  10728. node.fx += fx;
  10729. node.fy += fy;
  10730. }
  10731. }
  10732. }
  10733. }
  10734. },
  10735. /**
  10736. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10737. *
  10738. * @param nodes
  10739. * @param nodeIndices
  10740. * @private
  10741. */
  10742. _formBarnesHutTree : function(nodes,nodeIndices) {
  10743. var node;
  10744. var nodeCount = nodeIndices.length;
  10745. var minX = Number.MAX_VALUE,
  10746. minY = Number.MAX_VALUE,
  10747. maxX =-Number.MAX_VALUE,
  10748. maxY =-Number.MAX_VALUE;
  10749. // get the range of the nodes
  10750. for (var i = 0; i < nodeCount; i++) {
  10751. var x = nodes[nodeIndices[i]].x;
  10752. var y = nodes[nodeIndices[i]].y;
  10753. if (x < minX) { minX = x; }
  10754. if (x > maxX) { maxX = x; }
  10755. if (y < minY) { minY = y; }
  10756. if (y > maxY) { maxY = y; }
  10757. }
  10758. // make the range a square
  10759. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10760. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10761. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10762. var minimumTreeSize = 1e-5;
  10763. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10764. var halfRootSize = 0.5 * rootSize;
  10765. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10766. // construct the barnesHutTree
  10767. var barnesHutTree = {root:{
  10768. centerOfMass:{x:0,y:0}, // Center of Mass
  10769. mass:0,
  10770. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10771. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10772. size: rootSize,
  10773. calcSize: 1 / rootSize,
  10774. children: {data:null},
  10775. maxWidth: 0,
  10776. level: 0,
  10777. childrenCount: 4
  10778. }};
  10779. this._splitBranch(barnesHutTree.root);
  10780. // place the nodes one by one recursively
  10781. for (i = 0; i < nodeCount; i++) {
  10782. node = nodes[nodeIndices[i]];
  10783. this._placeInTree(barnesHutTree.root,node);
  10784. }
  10785. // make global
  10786. this.barnesHutTree = barnesHutTree
  10787. },
  10788. _updateBranchMass : function(parentBranch, node) {
  10789. var totalMass = parentBranch.mass + node.mass;
  10790. var totalMassInv = 1/totalMass;
  10791. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10792. parentBranch.centerOfMass.x *= totalMassInv;
  10793. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10794. parentBranch.centerOfMass.y *= totalMassInv;
  10795. parentBranch.mass = totalMass;
  10796. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10797. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10798. },
  10799. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10800. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10801. // update the mass of the branch.
  10802. this._updateBranchMass(parentBranch,node);
  10803. }
  10804. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10805. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10806. this._placeInRegion(parentBranch,node,"NW");
  10807. }
  10808. else { // in SW
  10809. this._placeInRegion(parentBranch,node,"SW");
  10810. }
  10811. }
  10812. else { // in NE or SE
  10813. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10814. this._placeInRegion(parentBranch,node,"NE");
  10815. }
  10816. else { // in SE
  10817. this._placeInRegion(parentBranch,node,"SE");
  10818. }
  10819. }
  10820. },
  10821. _placeInRegion : function(parentBranch,node,region) {
  10822. switch (parentBranch.children[region].childrenCount) {
  10823. case 0: // place node here
  10824. parentBranch.children[region].children.data = node;
  10825. parentBranch.children[region].childrenCount = 1;
  10826. this._updateBranchMass(parentBranch.children[region],node);
  10827. break;
  10828. case 1: // convert into children
  10829. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10830. // we move one node a pixel and we do not put it in the tree.
  10831. if (parentBranch.children[region].children.data.x == node.x &&
  10832. parentBranch.children[region].children.data.y == node.y) {
  10833. node.x += Math.random();
  10834. node.y += Math.random();
  10835. }
  10836. else {
  10837. this._splitBranch(parentBranch.children[region]);
  10838. this._placeInTree(parentBranch.children[region],node);
  10839. }
  10840. break;
  10841. case 4: // place in branch
  10842. this._placeInTree(parentBranch.children[region],node);
  10843. break;
  10844. }
  10845. },
  10846. /**
  10847. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10848. * after the split is complete.
  10849. *
  10850. * @param parentBranch
  10851. * @private
  10852. */
  10853. _splitBranch : function(parentBranch) {
  10854. // if the branch is filled with a node, replace the node in the new subset.
  10855. var containedNode = null;
  10856. if (parentBranch.childrenCount == 1) {
  10857. containedNode = parentBranch.children.data;
  10858. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10859. }
  10860. parentBranch.childrenCount = 4;
  10861. parentBranch.children.data = null;
  10862. this._insertRegion(parentBranch,"NW");
  10863. this._insertRegion(parentBranch,"NE");
  10864. this._insertRegion(parentBranch,"SW");
  10865. this._insertRegion(parentBranch,"SE");
  10866. if (containedNode != null) {
  10867. this._placeInTree(parentBranch,containedNode);
  10868. }
  10869. },
  10870. /**
  10871. * This function subdivides the region into four new segments.
  10872. * Specifically, this inserts a single new segment.
  10873. * It fills the children section of the parentBranch
  10874. *
  10875. * @param parentBranch
  10876. * @param region
  10877. * @param parentRange
  10878. * @private
  10879. */
  10880. _insertRegion : function(parentBranch, region) {
  10881. var minX,maxX,minY,maxY;
  10882. var childSize = 0.5 * parentBranch.size;
  10883. switch (region) {
  10884. case "NW":
  10885. minX = parentBranch.range.minX;
  10886. maxX = parentBranch.range.minX + childSize;
  10887. minY = parentBranch.range.minY;
  10888. maxY = parentBranch.range.minY + childSize;
  10889. break;
  10890. case "NE":
  10891. minX = parentBranch.range.minX + childSize;
  10892. maxX = parentBranch.range.maxX;
  10893. minY = parentBranch.range.minY;
  10894. maxY = parentBranch.range.minY + childSize;
  10895. break;
  10896. case "SW":
  10897. minX = parentBranch.range.minX;
  10898. maxX = parentBranch.range.minX + childSize;
  10899. minY = parentBranch.range.minY + childSize;
  10900. maxY = parentBranch.range.maxY;
  10901. break;
  10902. case "SE":
  10903. minX = parentBranch.range.minX + childSize;
  10904. maxX = parentBranch.range.maxX;
  10905. minY = parentBranch.range.minY + childSize;
  10906. maxY = parentBranch.range.maxY;
  10907. break;
  10908. }
  10909. parentBranch.children[region] = {
  10910. centerOfMass:{x:0,y:0},
  10911. mass:0,
  10912. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10913. size: 0.5 * parentBranch.size,
  10914. calcSize: 2 * parentBranch.calcSize,
  10915. children: {data:null},
  10916. maxWidth: 0,
  10917. level: parentBranch.level+1,
  10918. childrenCount: 0
  10919. };
  10920. },
  10921. /**
  10922. * This function is for debugging purposed, it draws the tree.
  10923. *
  10924. * @param ctx
  10925. * @param color
  10926. * @private
  10927. */
  10928. _drawTree : function(ctx,color) {
  10929. if (this.barnesHutTree !== undefined) {
  10930. ctx.lineWidth = 1;
  10931. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10932. }
  10933. },
  10934. /**
  10935. * This function is for debugging purposes. It draws the branches recursively.
  10936. *
  10937. * @param branch
  10938. * @param ctx
  10939. * @param color
  10940. * @private
  10941. */
  10942. _drawBranch : function(branch,ctx,color) {
  10943. if (color === undefined) {
  10944. color = "#FF0000";
  10945. }
  10946. if (branch.childrenCount == 4) {
  10947. this._drawBranch(branch.children.NW,ctx);
  10948. this._drawBranch(branch.children.NE,ctx);
  10949. this._drawBranch(branch.children.SE,ctx);
  10950. this._drawBranch(branch.children.SW,ctx);
  10951. }
  10952. ctx.strokeStyle = color;
  10953. ctx.beginPath();
  10954. ctx.moveTo(branch.range.minX,branch.range.minY);
  10955. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10956. ctx.stroke();
  10957. ctx.beginPath();
  10958. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10959. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10960. ctx.stroke();
  10961. ctx.beginPath();
  10962. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10963. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10964. ctx.stroke();
  10965. ctx.beginPath();
  10966. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10967. ctx.lineTo(branch.range.minX,branch.range.minY);
  10968. ctx.stroke();
  10969. /*
  10970. if (branch.mass > 0) {
  10971. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  10972. ctx.stroke();
  10973. }
  10974. */
  10975. }
  10976. };
  10977. /**
  10978. * Created by Alex on 2/10/14.
  10979. */
  10980. var repulsionMixin = {
  10981. /**
  10982. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10983. * This field is linearly approximated.
  10984. *
  10985. * @private
  10986. */
  10987. _calculateNodeForces : function() {
  10988. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  10989. repulsingForce, node1, node2, i, j;
  10990. var nodes = this.calculationNodes;
  10991. var nodeIndices = this.calculationNodeIndices;
  10992. // approximation constants
  10993. var a_base = -2/3;
  10994. var b = 4/3;
  10995. // repulsing forces between nodes
  10996. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10997. var minimumDistance = nodeDistance;
  10998. // we loop from i over all but the last entree in the array
  10999. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  11000. for (i = 0; i < nodeIndices.length-1; i++) {
  11001. node1 = nodes[nodeIndices[i]];
  11002. for (j = i+1; j < nodeIndices.length; j++) {
  11003. node2 = nodes[nodeIndices[j]];
  11004. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  11005. dx = node2.x - node1.x;
  11006. dy = node2.y - node1.y;
  11007. distance = Math.sqrt(dx * dx + dy * dy);
  11008. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  11009. var a = a_base / minimumDistance;
  11010. if (distance < 2*minimumDistance) {
  11011. if (distance < 0.5*minimumDistance) {
  11012. repulsingForce = 1.0;
  11013. }
  11014. else {
  11015. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  11016. }
  11017. // amplify the repulsion for clusters.
  11018. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  11019. repulsingForce = repulsingForce/distance;
  11020. fx = dx * repulsingForce;
  11021. fy = dy * repulsingForce;
  11022. node1.fx -= fx;
  11023. node1.fy -= fy;
  11024. node2.fx += fx;
  11025. node2.fy += fy;
  11026. }
  11027. }
  11028. }
  11029. }
  11030. }
  11031. var HierarchicalLayoutMixin = {
  11032. /**
  11033. * This is the main function to layout the nodes in a hierarchical way.
  11034. * It checks if the node details are supplied correctly
  11035. *
  11036. * @private
  11037. */
  11038. _setupHierarchicalLayout : function() {
  11039. if (this.constants.hierarchicalLayout.enabled == true) {
  11040. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  11041. this.constants.hierarchicalLayout.levelSeparation *= -1;
  11042. }
  11043. else {
  11044. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  11045. }
  11046. // get the size of the largest hubs and check if the user has defined a level for a node.
  11047. var hubsize = 0;
  11048. var node, nodeId;
  11049. var definedLevel = false;
  11050. var undefinedLevel = false;
  11051. for (nodeId in this.nodes) {
  11052. if (this.nodes.hasOwnProperty(nodeId)) {
  11053. node = this.nodes[nodeId];
  11054. if (node.level != -1) {
  11055. definedLevel = true;
  11056. }
  11057. else {
  11058. undefinedLevel = true;
  11059. }
  11060. if (hubsize < node.edges.length) {
  11061. hubsize = node.edges.length;
  11062. }
  11063. }
  11064. }
  11065. // if the user defined some levels but not all, alert and run without hierarchical layout
  11066. if (undefinedLevel == true && definedLevel == true) {
  11067. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.")
  11068. this.zoomExtent(true,this.constants.clustering.enabled);
  11069. if (!this.constants.clustering.enabled) {
  11070. this.start();
  11071. }
  11072. }
  11073. else {
  11074. // setup the system to use hierarchical method.
  11075. this._changeConstants();
  11076. // define levels if undefined by the users. Based on hubsize
  11077. if (undefinedLevel == true) {
  11078. this._determineLevels(hubsize);
  11079. }
  11080. // check the distribution of the nodes per level.
  11081. var distribution = this._getDistribution();
  11082. // place the nodes on the canvas. This also stablilizes the system.
  11083. this._placeNodesByHierarchy(distribution);
  11084. // start the simulation.
  11085. this.start();
  11086. }
  11087. }
  11088. },
  11089. /**
  11090. * This function places the nodes on the canvas based on the hierarchial distribution.
  11091. *
  11092. * @param {Object} distribution | obtained by the function this._getDistribution()
  11093. * @private
  11094. */
  11095. _placeNodesByHierarchy : function(distribution) {
  11096. var nodeId, node;
  11097. // start placing all the level 0 nodes first. Then recursively position their branches.
  11098. for (nodeId in distribution[0].nodes) {
  11099. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  11100. node = distribution[0].nodes[nodeId];
  11101. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11102. if (node.xFixed) {
  11103. node.x = distribution[0].minPos;
  11104. node.xFixed = false;
  11105. distribution[0].minPos += distribution[0].nodeSpacing;
  11106. }
  11107. }
  11108. else {
  11109. if (node.yFixed) {
  11110. node.y = distribution[0].minPos;
  11111. node.yFixed = false;
  11112. distribution[0].minPos += distribution[0].nodeSpacing;
  11113. }
  11114. }
  11115. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  11116. }
  11117. }
  11118. // stabilize the system after positioning. This function calls zoomExtent.
  11119. this._stabilize();
  11120. },
  11121. /**
  11122. * This function get the distribution of levels based on hubsize
  11123. *
  11124. * @returns {Object}
  11125. * @private
  11126. */
  11127. _getDistribution : function() {
  11128. var distribution = {};
  11129. var nodeId, node;
  11130. // 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.
  11131. // the fix of X is removed after the x value has been set.
  11132. for (nodeId in this.nodes) {
  11133. if (this.nodes.hasOwnProperty(nodeId)) {
  11134. node = this.nodes[nodeId];
  11135. node.xFixed = true;
  11136. node.yFixed = true;
  11137. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11138. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  11139. }
  11140. else {
  11141. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  11142. }
  11143. if (!distribution.hasOwnProperty(node.level)) {
  11144. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  11145. }
  11146. distribution[node.level].amount += 1;
  11147. distribution[node.level].nodes[node.id] = node;
  11148. }
  11149. }
  11150. // determine the largest amount of nodes of all levels
  11151. var maxCount = 0;
  11152. for (var level in distribution) {
  11153. if (distribution.hasOwnProperty(level)) {
  11154. if (maxCount < distribution[level].amount) {
  11155. maxCount = distribution[level].amount;
  11156. }
  11157. }
  11158. }
  11159. // set the initial position and spacing of each nodes accordingly
  11160. for (var level in distribution) {
  11161. if (distribution.hasOwnProperty(level)) {
  11162. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  11163. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  11164. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  11165. }
  11166. }
  11167. return distribution;
  11168. },
  11169. /**
  11170. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  11171. *
  11172. * @param hubsize
  11173. * @private
  11174. */
  11175. _determineLevels : function(hubsize) {
  11176. var nodeId, node;
  11177. // determine hubs
  11178. for (nodeId in this.nodes) {
  11179. if (this.nodes.hasOwnProperty(nodeId)) {
  11180. node = this.nodes[nodeId];
  11181. if (node.edges.length == hubsize) {
  11182. node.level = 0;
  11183. }
  11184. }
  11185. }
  11186. // branch from hubs
  11187. for (nodeId in this.nodes) {
  11188. if (this.nodes.hasOwnProperty(nodeId)) {
  11189. node = this.nodes[nodeId];
  11190. if (node.level == 0) {
  11191. this._setLevel(1,node.edges,node.id);
  11192. }
  11193. }
  11194. }
  11195. },
  11196. /**
  11197. * Since hierarchical layout does not support:
  11198. * - smooth curves (based on the physics),
  11199. * - clustering (based on dynamic node counts)
  11200. *
  11201. * We disable both features so there will be no problems.
  11202. *
  11203. * @private
  11204. */
  11205. _changeConstants : function() {
  11206. this.constants.clustering.enabled = false;
  11207. this.constants.physics.barnesHut.enabled = false;
  11208. this.constants.physics.hierarchicalRepulsion.enabled = true;
  11209. this._loadSelectedForceSolver();
  11210. this.constants.smoothCurves = false;
  11211. this._configureSmoothCurves();
  11212. },
  11213. /**
  11214. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  11215. * on a X position that ensures there will be no overlap.
  11216. *
  11217. * @param edges
  11218. * @param parentId
  11219. * @param distribution
  11220. * @param parentLevel
  11221. * @private
  11222. */
  11223. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  11224. for (var i = 0; i < edges.length; i++) {
  11225. var childNode = null;
  11226. if (edges[i].toId == parentId) {
  11227. childNode = edges[i].from;
  11228. }
  11229. else {
  11230. childNode = edges[i].to;
  11231. }
  11232. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  11233. var nodeMoved = false;
  11234. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11235. if (childNode.xFixed && childNode.level > parentLevel) {
  11236. childNode.xFixed = false;
  11237. childNode.x = distribution[childNode.level].minPos;
  11238. nodeMoved = true;
  11239. }
  11240. }
  11241. else {
  11242. if (childNode.yFixed && childNode.level > parentLevel) {
  11243. childNode.yFixed = false;
  11244. childNode.y = distribution[childNode.level].minPos;
  11245. nodeMoved = true;
  11246. }
  11247. }
  11248. if (nodeMoved == true) {
  11249. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  11250. if (childNode.edges.length > 1) {
  11251. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  11252. }
  11253. }
  11254. }
  11255. },
  11256. /**
  11257. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  11258. *
  11259. * @param level
  11260. * @param edges
  11261. * @param parentId
  11262. * @private
  11263. */
  11264. _setLevel : function(level, edges, parentId) {
  11265. for (var i = 0; i < edges.length; i++) {
  11266. var childNode = null;
  11267. if (edges[i].toId == parentId) {
  11268. childNode = edges[i].from;
  11269. }
  11270. else {
  11271. childNode = edges[i].to;
  11272. }
  11273. if (childNode.level == -1 || childNode.level > level) {
  11274. childNode.level = level;
  11275. if (edges.length > 1) {
  11276. this._setLevel(level+1, childNode.edges, childNode.id);
  11277. }
  11278. }
  11279. }
  11280. },
  11281. /**
  11282. * Unfix nodes
  11283. *
  11284. * @private
  11285. */
  11286. _restoreNodes : function() {
  11287. for (nodeId in this.nodes) {
  11288. if (this.nodes.hasOwnProperty(nodeId)) {
  11289. this.nodes[nodeId].xFixed = false;
  11290. this.nodes[nodeId].yFixed = false;
  11291. }
  11292. }
  11293. }
  11294. };
  11295. /**
  11296. * Created by Alex on 2/4/14.
  11297. */
  11298. var manipulationMixin = {
  11299. /**
  11300. * clears the toolbar div element of children
  11301. *
  11302. * @private
  11303. */
  11304. _clearManipulatorBar : function() {
  11305. while (this.manipulationDiv.hasChildNodes()) {
  11306. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11307. }
  11308. },
  11309. /**
  11310. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  11311. * these functions to their original functionality, we saved them in this.cachedFunctions.
  11312. * This function restores these functions to their original function.
  11313. *
  11314. * @private
  11315. */
  11316. _restoreOverloadedFunctions : function() {
  11317. for (var functionName in this.cachedFunctions) {
  11318. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  11319. this[functionName] = this.cachedFunctions[functionName];
  11320. }
  11321. }
  11322. },
  11323. /**
  11324. * Enable or disable edit-mode.
  11325. *
  11326. * @private
  11327. */
  11328. _toggleEditMode : function() {
  11329. this.editMode = !this.editMode;
  11330. var toolbar = document.getElementById("graph-manipulationDiv");
  11331. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11332. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  11333. if (this.editMode == true) {
  11334. toolbar.style.display="block";
  11335. closeDiv.style.display="block";
  11336. editModeDiv.style.display="none";
  11337. closeDiv.onclick = this._toggleEditMode.bind(this);
  11338. }
  11339. else {
  11340. toolbar.style.display="none";
  11341. closeDiv.style.display="none";
  11342. editModeDiv.style.display="block";
  11343. closeDiv.onclick = null;
  11344. }
  11345. this._createManipulatorBar()
  11346. },
  11347. /**
  11348. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  11349. *
  11350. * @private
  11351. */
  11352. _createManipulatorBar : function() {
  11353. // remove bound functions
  11354. if (this.boundFunction) {
  11355. this.off('select', this.boundFunction);
  11356. }
  11357. // restore overloaded functions
  11358. this._restoreOverloadedFunctions();
  11359. // resume calculation
  11360. this.freezeSimulation = false;
  11361. // reset global variables
  11362. this.blockConnectingEdgeSelection = false;
  11363. this.forceAppendSelection = false
  11364. if (this.editMode == true) {
  11365. while (this.manipulationDiv.hasChildNodes()) {
  11366. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11367. }
  11368. // add the icons to the manipulator div
  11369. this.manipulationDiv.innerHTML = "" +
  11370. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  11371. "<span class='graph-manipulationLabel'>Add Node</span></span>" +
  11372. "<div class='graph-seperatorLine'></div>" +
  11373. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  11374. "<span class='graph-manipulationLabel'>Add Link</span></span>";
  11375. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11376. this.manipulationDiv.innerHTML += "" +
  11377. "<div class='graph-seperatorLine'></div>" +
  11378. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  11379. "<span class='graph-manipulationLabel'>Edit Node</span></span>";
  11380. }
  11381. if (this._selectionIsEmpty() == false) {
  11382. this.manipulationDiv.innerHTML += "" +
  11383. "<div class='graph-seperatorLine'></div>" +
  11384. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  11385. "<span class='graph-manipulationLabel'>Delete selected</span></span>";
  11386. }
  11387. // bind the icons
  11388. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  11389. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  11390. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  11391. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  11392. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11393. var editButton = document.getElementById("graph-manipulate-editNode");
  11394. editButton.onclick = this._editNode.bind(this);
  11395. }
  11396. if (this._selectionIsEmpty() == false) {
  11397. var deleteButton = document.getElementById("graph-manipulate-delete");
  11398. deleteButton.onclick = this._deleteSelected.bind(this);
  11399. }
  11400. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11401. closeDiv.onclick = this._toggleEditMode.bind(this);
  11402. this.boundFunction = this._createManipulatorBar.bind(this);
  11403. this.on('select', this.boundFunction);
  11404. }
  11405. else {
  11406. this.editModeDiv.innerHTML = "" +
  11407. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  11408. "<span class='graph-manipulationLabel'>Edit</span></span>"
  11409. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  11410. editModeButton.onclick = this._toggleEditMode.bind(this);
  11411. }
  11412. },
  11413. /**
  11414. * Create the toolbar for adding Nodes
  11415. *
  11416. * @private
  11417. */
  11418. _createAddNodeToolbar : function() {
  11419. // clear the toolbar
  11420. this._clearManipulatorBar();
  11421. if (this.boundFunction) {
  11422. this.off('select', this.boundFunction);
  11423. }
  11424. // create the toolbar contents
  11425. this.manipulationDiv.innerHTML = "" +
  11426. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11427. "<span class='graph-manipulationLabel'>Back</span></span>" +
  11428. "<div class='graph-seperatorLine'></div>" +
  11429. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11430. "<span class='graph-manipulationLabel'>Click in an empty space to place a new node</span></span>";
  11431. // bind the icon
  11432. var backButton = document.getElementById("graph-manipulate-back");
  11433. backButton.onclick = this._createManipulatorBar.bind(this);
  11434. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11435. this.boundFunction = this._addNode.bind(this);
  11436. this.on('select', this.boundFunction);
  11437. },
  11438. /**
  11439. * create the toolbar to connect nodes
  11440. *
  11441. * @private
  11442. */
  11443. _createAddEdgeToolbar : function() {
  11444. // clear the toolbar
  11445. this._clearManipulatorBar();
  11446. this._unselectAll(true);
  11447. this.freezeSimulation = true;
  11448. if (this.boundFunction) {
  11449. this.off('select', this.boundFunction);
  11450. }
  11451. this._unselectAll();
  11452. this.forceAppendSelection = false;
  11453. this.blockConnectingEdgeSelection = true;
  11454. this.manipulationDiv.innerHTML = "" +
  11455. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11456. "<span class='graph-manipulationLabel'>Back</span></span>" +
  11457. "<div class='graph-seperatorLine'></div>" +
  11458. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11459. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>Click on a node and drag the edge to another node to connect them.</span></span>";
  11460. // bind the icon
  11461. var backButton = document.getElementById("graph-manipulate-back");
  11462. backButton.onclick = this._createManipulatorBar.bind(this);
  11463. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11464. this.boundFunction = this._handleConnect.bind(this);
  11465. this.on('select', this.boundFunction);
  11466. // temporarily overload functions
  11467. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  11468. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  11469. this._handleTouch = this._handleConnect;
  11470. this._handleOnRelease = this._finishConnect;
  11471. // redraw to show the unselect
  11472. this._redraw();
  11473. },
  11474. /**
  11475. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11476. * to walk the user through the process.
  11477. *
  11478. * @private
  11479. */
  11480. _handleConnect : function(pointer) {
  11481. if (this._getSelectedNodeCount() == 0) {
  11482. var node = this._getNodeAt(pointer);
  11483. if (node != null) {
  11484. if (node.clusterSize > 1) {
  11485. alert("Cannot create edges to a cluster.")
  11486. }
  11487. else {
  11488. this._selectObject(node,false);
  11489. // create a node the temporary line can look at
  11490. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11491. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11492. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11493. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11494. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11495. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11496. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11497. // create a temporary edge
  11498. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11499. this.edges['connectionEdge'].from = node;
  11500. this.edges['connectionEdge'].connected = true;
  11501. this.edges['connectionEdge'].smooth = true;
  11502. this.edges['connectionEdge'].selected = true;
  11503. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11504. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11505. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11506. this._handleOnDrag = function(event) {
  11507. var pointer = this._getPointer(event.gesture.center);
  11508. this.sectors['support']['nodes']['targetNode'].x = this._canvasToX(pointer.x);
  11509. this.sectors['support']['nodes']['targetNode'].y = this._canvasToY(pointer.y);
  11510. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._canvasToX(pointer.x) + this.edges['connectionEdge'].from.x);
  11511. this.sectors['support']['nodes']['targetViaNode'].y = this._canvasToY(pointer.y);
  11512. };
  11513. this.moving = true;
  11514. this.start();
  11515. }
  11516. }
  11517. }
  11518. },
  11519. _finishConnect : function(pointer) {
  11520. if (this._getSelectedNodeCount() == 1) {
  11521. // restore the drag function
  11522. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11523. delete this.cachedFunctions["_handleOnDrag"];
  11524. // remember the edge id
  11525. var connectFromId = this.edges['connectionEdge'].fromId;
  11526. // remove the temporary nodes and edge
  11527. delete this.edges['connectionEdge']
  11528. delete this.sectors['support']['nodes']['targetNode'];
  11529. delete this.sectors['support']['nodes']['targetViaNode'];
  11530. var node = this._getNodeAt(pointer);
  11531. if (node != null) {
  11532. if (node.clusterSize > 1) {
  11533. alert("Cannot create edges to a cluster.")
  11534. }
  11535. else {
  11536. this._createEdge(connectFromId,node.id);
  11537. this._createManipulatorBar();
  11538. }
  11539. }
  11540. this._unselectAll();
  11541. }
  11542. },
  11543. /**
  11544. * Adds a node on the specified location
  11545. *
  11546. * @param {Object} pointer
  11547. */
  11548. _addNode : function() {
  11549. if (this._selectionIsEmpty() && this.editMode == true) {
  11550. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11551. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  11552. if (this.triggerFunctions.add) {
  11553. if (this.triggerFunctions.add.length == 2) {
  11554. var me = this;
  11555. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11556. me.nodesData.add(finalizedData);
  11557. me._createManipulatorBar();
  11558. me.moving = true;
  11559. me.start();
  11560. });
  11561. }
  11562. else {
  11563. alert("The function for add does not support two arguments (data,callback).");
  11564. this._createManipulatorBar();
  11565. this.moving = true;
  11566. this.start();
  11567. }
  11568. }
  11569. else {
  11570. this.nodesData.add(defaultData);
  11571. this._createManipulatorBar();
  11572. this.moving = true;
  11573. this.start();
  11574. }
  11575. }
  11576. },
  11577. /**
  11578. * connect two nodes with a new edge.
  11579. *
  11580. * @private
  11581. */
  11582. _createEdge : function(sourceNodeId,targetNodeId) {
  11583. if (this.editMode == true) {
  11584. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11585. if (this.triggerFunctions.connect) {
  11586. if (this.triggerFunctions.connect.length == 2) {
  11587. var me = this;
  11588. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11589. me.edgesData.add(finalizedData)
  11590. me.moving = true;
  11591. me.start();
  11592. });
  11593. }
  11594. else {
  11595. alert("The function for connect does not support two arguments (data,callback).");
  11596. this.moving = true;
  11597. this.start();
  11598. }
  11599. }
  11600. else {
  11601. this.edgesData.add(defaultData)
  11602. this.moving = true;
  11603. this.start();
  11604. }
  11605. }
  11606. },
  11607. /**
  11608. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11609. *
  11610. * @private
  11611. */
  11612. _editNode : function() {
  11613. if (this.triggerFunctions.edit && this.editMode == true) {
  11614. var node = this._getSelectedNode();
  11615. var data = {id:node.id,
  11616. label: node.label,
  11617. group: node.group,
  11618. shape: node.shape,
  11619. color: {
  11620. background:node.color.background,
  11621. border:node.color.border,
  11622. highlight: {
  11623. background:node.color.highlight.background,
  11624. border:node.color.highlight.border
  11625. }
  11626. }};
  11627. if (this.triggerFunctions.edit.length == 2) {
  11628. var me = this;
  11629. this.triggerFunctions.edit(data, function (finalizedData) {
  11630. me.nodesData.update(finalizedData);
  11631. me._createManipulatorBar();
  11632. me.moving = true;
  11633. me.start();
  11634. });
  11635. }
  11636. else {
  11637. alert("The function for edit does not support two arguments (data, callback).")
  11638. }
  11639. }
  11640. else {
  11641. alert("No edit function has been bound to this button.")
  11642. }
  11643. },
  11644. /**
  11645. * delete everything in the selection
  11646. *
  11647. * @private
  11648. */
  11649. _deleteSelected : function() {
  11650. if (!this._selectionIsEmpty() && this.editMode == true) {
  11651. if (!this._clusterInSelection()) {
  11652. var selectedNodes = this.getSelectedNodes();
  11653. var selectedEdges = this.getSelectedEdges();
  11654. if (this.triggerFunctions.delete) {
  11655. var me = this;
  11656. var data = {nodes: selectedNodes, edges: selectedEdges};
  11657. if (this.triggerFunctions.delete.length = 2) {
  11658. this.triggerFunctions.delete(data, function (finalizedData) {
  11659. me.edgesData.remove(finalizedData.edges);
  11660. me.nodesData.remove(finalizedData.nodes);
  11661. this._unselectAll();
  11662. me.moving = true;
  11663. me.start();
  11664. });
  11665. }
  11666. else {
  11667. alert("The function for edit does not support two arguments (data, callback).")
  11668. }
  11669. }
  11670. else {
  11671. this.edgesData.remove(selectedEdges);
  11672. this.nodesData.remove(selectedNodes);
  11673. this._unselectAll();
  11674. this.moving = true;
  11675. this.start();
  11676. }
  11677. }
  11678. else {
  11679. alert("Clusters cannot be deleted.");
  11680. }
  11681. }
  11682. }
  11683. };
  11684. /**
  11685. * Creation of the SectorMixin var.
  11686. *
  11687. * This contains all the functions the Graph object can use to employ the sector system.
  11688. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11689. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11690. *
  11691. * Alex de Mulder
  11692. * 21-01-2013
  11693. */
  11694. var SectorMixin = {
  11695. /**
  11696. * This function is only called by the setData function of the Graph object.
  11697. * This loads the global references into the active sector. This initializes the sector.
  11698. *
  11699. * @private
  11700. */
  11701. _putDataInSector : function() {
  11702. this.sectors["active"][this._sector()].nodes = this.nodes;
  11703. this.sectors["active"][this._sector()].edges = this.edges;
  11704. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11705. },
  11706. /**
  11707. * /**
  11708. * This function sets the global references to nodes, edges and nodeIndices back to
  11709. * those of the supplied (active) sector. If a type is defined, do the specific type
  11710. *
  11711. * @param {String} sectorId
  11712. * @param {String} [sectorType] | "active" or "frozen"
  11713. * @private
  11714. */
  11715. _switchToSector : function(sectorId, sectorType) {
  11716. if (sectorType === undefined || sectorType == "active") {
  11717. this._switchToActiveSector(sectorId);
  11718. }
  11719. else {
  11720. this._switchToFrozenSector(sectorId);
  11721. }
  11722. },
  11723. /**
  11724. * This function sets the global references to nodes, edges and nodeIndices back to
  11725. * those of the supplied active sector.
  11726. *
  11727. * @param sectorId
  11728. * @private
  11729. */
  11730. _switchToActiveSector : function(sectorId) {
  11731. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11732. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11733. this.edges = this.sectors["active"][sectorId]["edges"];
  11734. },
  11735. /**
  11736. * This function sets the global references to nodes, edges and nodeIndices back to
  11737. * those of the supplied active sector.
  11738. *
  11739. * @param sectorId
  11740. * @private
  11741. */
  11742. _switchToSupportSector : function() {
  11743. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11744. this.nodes = this.sectors["support"]["nodes"];
  11745. this.edges = this.sectors["support"]["edges"];
  11746. },
  11747. /**
  11748. * This function sets the global references to nodes, edges and nodeIndices back to
  11749. * those of the supplied frozen sector.
  11750. *
  11751. * @param sectorId
  11752. * @private
  11753. */
  11754. _switchToFrozenSector : function(sectorId) {
  11755. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11756. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11757. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11758. },
  11759. /**
  11760. * This function sets the global references to nodes, edges and nodeIndices back to
  11761. * those of the currently active sector.
  11762. *
  11763. * @private
  11764. */
  11765. _loadLatestSector : function() {
  11766. this._switchToSector(this._sector());
  11767. },
  11768. /**
  11769. * This function returns the currently active sector Id
  11770. *
  11771. * @returns {String}
  11772. * @private
  11773. */
  11774. _sector : function() {
  11775. return this.activeSector[this.activeSector.length-1];
  11776. },
  11777. /**
  11778. * This function returns the previously active sector Id
  11779. *
  11780. * @returns {String}
  11781. * @private
  11782. */
  11783. _previousSector : function() {
  11784. if (this.activeSector.length > 1) {
  11785. return this.activeSector[this.activeSector.length-2];
  11786. }
  11787. else {
  11788. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11789. }
  11790. },
  11791. /**
  11792. * We add the active sector at the end of the this.activeSector array
  11793. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11794. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11795. *
  11796. * @param newId
  11797. * @private
  11798. */
  11799. _setActiveSector : function(newId) {
  11800. this.activeSector.push(newId);
  11801. },
  11802. /**
  11803. * We remove the currently active sector id from the active sector stack. This happens when
  11804. * we reactivate the previously active sector
  11805. *
  11806. * @private
  11807. */
  11808. _forgetLastSector : function() {
  11809. this.activeSector.pop();
  11810. },
  11811. /**
  11812. * This function creates a new active sector with the supplied newId. This newId
  11813. * is the expanding node id.
  11814. *
  11815. * @param {String} newId | Id of the new active sector
  11816. * @private
  11817. */
  11818. _createNewSector : function(newId) {
  11819. // create the new sector
  11820. this.sectors["active"][newId] = {"nodes":{},
  11821. "edges":{},
  11822. "nodeIndices":[],
  11823. "formationScale": this.scale,
  11824. "drawingNode": undefined};
  11825. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11826. this.sectors["active"][newId]['drawingNode'] = new Node(
  11827. {id:newId,
  11828. color: {
  11829. background: "#eaefef",
  11830. border: "495c5e"
  11831. }
  11832. },{},{},this.constants);
  11833. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11834. },
  11835. /**
  11836. * This function removes the currently active sector. This is called when we create a new
  11837. * active sector.
  11838. *
  11839. * @param {String} sectorId | Id of the active sector that will be removed
  11840. * @private
  11841. */
  11842. _deleteActiveSector : function(sectorId) {
  11843. delete this.sectors["active"][sectorId];
  11844. },
  11845. /**
  11846. * This function removes the currently active sector. This is called when we reactivate
  11847. * the previously active sector.
  11848. *
  11849. * @param {String} sectorId | Id of the active sector that will be removed
  11850. * @private
  11851. */
  11852. _deleteFrozenSector : function(sectorId) {
  11853. delete this.sectors["frozen"][sectorId];
  11854. },
  11855. /**
  11856. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11857. * We copy the references, then delete the active entree.
  11858. *
  11859. * @param sectorId
  11860. * @private
  11861. */
  11862. _freezeSector : function(sectorId) {
  11863. // we move the set references from the active to the frozen stack.
  11864. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11865. // we have moved the sector data into the frozen set, we now remove it from the active set
  11866. this._deleteActiveSector(sectorId);
  11867. },
  11868. /**
  11869. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11870. * object to the "active" object.
  11871. *
  11872. * @param sectorId
  11873. * @private
  11874. */
  11875. _activateSector : function(sectorId) {
  11876. // we move the set references from the frozen to the active stack.
  11877. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11878. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11879. this._deleteFrozenSector(sectorId);
  11880. },
  11881. /**
  11882. * This function merges the data from the currently active sector with a frozen sector. This is used
  11883. * in the process of reverting back to the previously active sector.
  11884. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11885. * upon the creation of a new active sector.
  11886. *
  11887. * @param sectorId
  11888. * @private
  11889. */
  11890. _mergeThisWithFrozen : function(sectorId) {
  11891. // copy all nodes
  11892. for (var nodeId in this.nodes) {
  11893. if (this.nodes.hasOwnProperty(nodeId)) {
  11894. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11895. }
  11896. }
  11897. // copy all edges (if not fully clustered, else there are no edges)
  11898. for (var edgeId in this.edges) {
  11899. if (this.edges.hasOwnProperty(edgeId)) {
  11900. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11901. }
  11902. }
  11903. // merge the nodeIndices
  11904. for (var i = 0; i < this.nodeIndices.length; i++) {
  11905. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11906. }
  11907. },
  11908. /**
  11909. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11910. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11911. *
  11912. * @private
  11913. */
  11914. _collapseThisToSingleCluster : function() {
  11915. this.clusterToFit(1,false);
  11916. },
  11917. /**
  11918. * We create a new active sector from the node that we want to open.
  11919. *
  11920. * @param node
  11921. * @private
  11922. */
  11923. _addSector : function(node) {
  11924. // this is the currently active sector
  11925. var sector = this._sector();
  11926. // // this should allow me to select nodes from a frozen set.
  11927. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11928. // console.log("the node is part of the active sector");
  11929. // }
  11930. // else {
  11931. // console.log("I dont know what the fuck happened!!");
  11932. // }
  11933. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11934. delete this.nodes[node.id];
  11935. var unqiueIdentifier = util.randomUUID();
  11936. // we fully freeze the currently active sector
  11937. this._freezeSector(sector);
  11938. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11939. this._createNewSector(unqiueIdentifier);
  11940. // we add the active sector to the sectors array to be able to revert these steps later on
  11941. this._setActiveSector(unqiueIdentifier);
  11942. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11943. this._switchToSector(this._sector());
  11944. // finally we add the node we removed from our previous active sector to the new active sector
  11945. this.nodes[node.id] = node;
  11946. },
  11947. /**
  11948. * We close the sector that is currently open and revert back to the one before.
  11949. * If the active sector is the "default" sector, nothing happens.
  11950. *
  11951. * @private
  11952. */
  11953. _collapseSector : function() {
  11954. // the currently active sector
  11955. var sector = this._sector();
  11956. // we cannot collapse the default sector
  11957. if (sector != "default") {
  11958. if ((this.nodeIndices.length == 1) ||
  11959. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11960. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11961. var previousSector = this._previousSector();
  11962. // we collapse the sector back to a single cluster
  11963. this._collapseThisToSingleCluster();
  11964. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  11965. // This previous sector is the one we will reactivate
  11966. this._mergeThisWithFrozen(previousSector);
  11967. // the previously active (frozen) sector now has all the data from the currently active sector.
  11968. // we can now delete the active sector.
  11969. this._deleteActiveSector(sector);
  11970. // we activate the previously active (and currently frozen) sector.
  11971. this._activateSector(previousSector);
  11972. // we load the references from the newly active sector into the global references
  11973. this._switchToSector(previousSector);
  11974. // we forget the previously active sector because we reverted to the one before
  11975. this._forgetLastSector();
  11976. // finally, we update the node index list.
  11977. this._updateNodeIndexList();
  11978. // we refresh the list with calulation nodes and calculation node indices.
  11979. this._updateCalculationNodes();
  11980. }
  11981. }
  11982. },
  11983. /**
  11984. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11985. *
  11986. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11987. * | we dont pass the function itself because then the "this" is the window object
  11988. * | instead of the Graph object
  11989. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11990. * @private
  11991. */
  11992. _doInAllActiveSectors : function(runFunction,argument) {
  11993. if (argument === undefined) {
  11994. for (var sector in this.sectors["active"]) {
  11995. if (this.sectors["active"].hasOwnProperty(sector)) {
  11996. // switch the global references to those of this sector
  11997. this._switchToActiveSector(sector);
  11998. this[runFunction]();
  11999. }
  12000. }
  12001. }
  12002. else {
  12003. for (var sector in this.sectors["active"]) {
  12004. if (this.sectors["active"].hasOwnProperty(sector)) {
  12005. // switch the global references to those of this sector
  12006. this._switchToActiveSector(sector);
  12007. var args = Array.prototype.splice.call(arguments, 1);
  12008. if (args.length > 1) {
  12009. this[runFunction](args[0],args[1]);
  12010. }
  12011. else {
  12012. this[runFunction](argument);
  12013. }
  12014. }
  12015. }
  12016. }
  12017. // we revert the global references back to our active sector
  12018. this._loadLatestSector();
  12019. },
  12020. /**
  12021. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  12022. *
  12023. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  12024. * | we dont pass the function itself because then the "this" is the window object
  12025. * | instead of the Graph object
  12026. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12027. * @private
  12028. */
  12029. _doInSupportSector : function(runFunction,argument) {
  12030. if (argument === undefined) {
  12031. this._switchToSupportSector();
  12032. this[runFunction]();
  12033. }
  12034. else {
  12035. this._switchToSupportSector();
  12036. var args = Array.prototype.splice.call(arguments, 1);
  12037. if (args.length > 1) {
  12038. this[runFunction](args[0],args[1]);
  12039. }
  12040. else {
  12041. this[runFunction](argument);
  12042. }
  12043. }
  12044. // we revert the global references back to our active sector
  12045. this._loadLatestSector();
  12046. },
  12047. /**
  12048. * This runs a function in all frozen sectors. This is used in the _redraw().
  12049. *
  12050. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  12051. * | we don't pass the function itself because then the "this" is the window object
  12052. * | instead of the Graph object
  12053. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12054. * @private
  12055. */
  12056. _doInAllFrozenSectors : function(runFunction,argument) {
  12057. if (argument === undefined) {
  12058. for (var sector in this.sectors["frozen"]) {
  12059. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  12060. // switch the global references to those of this sector
  12061. this._switchToFrozenSector(sector);
  12062. this[runFunction]();
  12063. }
  12064. }
  12065. }
  12066. else {
  12067. for (var sector in this.sectors["frozen"]) {
  12068. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  12069. // switch the global references to those of this sector
  12070. this._switchToFrozenSector(sector);
  12071. var args = Array.prototype.splice.call(arguments, 1);
  12072. if (args.length > 1) {
  12073. this[runFunction](args[0],args[1]);
  12074. }
  12075. else {
  12076. this[runFunction](argument);
  12077. }
  12078. }
  12079. }
  12080. }
  12081. this._loadLatestSector();
  12082. },
  12083. /**
  12084. * This runs a function in all sectors. This is used in the _redraw().
  12085. *
  12086. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  12087. * | we don't pass the function itself because then the "this" is the window object
  12088. * | instead of the Graph object
  12089. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12090. * @private
  12091. */
  12092. _doInAllSectors : function(runFunction,argument) {
  12093. var args = Array.prototype.splice.call(arguments, 1);
  12094. if (argument === undefined) {
  12095. this._doInAllActiveSectors(runFunction);
  12096. this._doInAllFrozenSectors(runFunction);
  12097. }
  12098. else {
  12099. if (args.length > 1) {
  12100. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  12101. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  12102. }
  12103. else {
  12104. this._doInAllActiveSectors(runFunction,argument);
  12105. this._doInAllFrozenSectors(runFunction,argument);
  12106. }
  12107. }
  12108. },
  12109. /**
  12110. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  12111. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  12112. *
  12113. * @private
  12114. */
  12115. _clearNodeIndexList : function() {
  12116. var sector = this._sector();
  12117. this.sectors["active"][sector]["nodeIndices"] = [];
  12118. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  12119. },
  12120. /**
  12121. * Draw the encompassing sector node
  12122. *
  12123. * @param ctx
  12124. * @param sectorType
  12125. * @private
  12126. */
  12127. _drawSectorNodes : function(ctx,sectorType) {
  12128. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  12129. for (var sector in this.sectors[sectorType]) {
  12130. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  12131. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  12132. this._switchToSector(sector,sectorType);
  12133. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  12134. for (var nodeId in this.nodes) {
  12135. if (this.nodes.hasOwnProperty(nodeId)) {
  12136. node = this.nodes[nodeId];
  12137. node.resize(ctx);
  12138. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  12139. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  12140. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  12141. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  12142. }
  12143. }
  12144. node = this.sectors[sectorType][sector]["drawingNode"];
  12145. node.x = 0.5 * (maxX + minX);
  12146. node.y = 0.5 * (maxY + minY);
  12147. node.width = 2 * (node.x - minX);
  12148. node.height = 2 * (node.y - minY);
  12149. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  12150. node.setScale(this.scale);
  12151. node._drawCircle(ctx);
  12152. }
  12153. }
  12154. }
  12155. },
  12156. _drawAllSectorNodes : function(ctx) {
  12157. this._drawSectorNodes(ctx,"frozen");
  12158. this._drawSectorNodes(ctx,"active");
  12159. this._loadLatestSector();
  12160. }
  12161. };
  12162. /**
  12163. * Creation of the ClusterMixin var.
  12164. *
  12165. * This contains all the functions the Graph object can use to employ clustering
  12166. *
  12167. * Alex de Mulder
  12168. * 21-01-2013
  12169. */
  12170. var ClusterMixin = {
  12171. /**
  12172. * This is only called in the constructor of the graph object
  12173. *
  12174. */
  12175. startWithClustering : function() {
  12176. // cluster if the data set is big
  12177. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  12178. // updates the lables after clustering
  12179. this.updateLabels();
  12180. // this is called here because if clusterin is disabled, the start and stabilize are called in
  12181. // the setData function.
  12182. if (this.stabilize) {
  12183. this._stabilize();
  12184. }
  12185. this.start();
  12186. },
  12187. /**
  12188. * This function clusters until the initialMaxNodes has been reached
  12189. *
  12190. * @param {Number} maxNumberOfNodes
  12191. * @param {Boolean} reposition
  12192. */
  12193. clusterToFit : function(maxNumberOfNodes, reposition) {
  12194. var numberOfNodes = this.nodeIndices.length;
  12195. var maxLevels = 50;
  12196. var level = 0;
  12197. // we first cluster the hubs, then we pull in the outliers, repeat
  12198. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  12199. if (level % 3 == 0) {
  12200. this.forceAggregateHubs(true);
  12201. this.normalizeClusterLevels();
  12202. }
  12203. else {
  12204. this.increaseClusterLevel(); // this also includes a cluster normalization
  12205. }
  12206. numberOfNodes = this.nodeIndices.length;
  12207. level += 1;
  12208. }
  12209. // after the clustering we reposition the nodes to reduce the initial chaos
  12210. if (level > 0 && reposition == true) {
  12211. this.repositionNodes();
  12212. }
  12213. this._updateCalculationNodes();
  12214. },
  12215. /**
  12216. * This function can be called to open up a specific cluster. It is only called by
  12217. * It will unpack the cluster back one level.
  12218. *
  12219. * @param node | Node object: cluster to open.
  12220. */
  12221. openCluster : function(node) {
  12222. var isMovingBeforeClustering = this.moving;
  12223. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  12224. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  12225. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  12226. this._addSector(node);
  12227. var level = 0;
  12228. // we decluster until we reach a decent number of nodes
  12229. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  12230. this.decreaseClusterLevel();
  12231. level += 1;
  12232. }
  12233. }
  12234. else {
  12235. this._expandClusterNode(node,false,true);
  12236. // update the index list, dynamic edges and labels
  12237. this._updateNodeIndexList();
  12238. this._updateDynamicEdges();
  12239. this._updateCalculationNodes();
  12240. this.updateLabels();
  12241. }
  12242. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12243. if (this.moving != isMovingBeforeClustering) {
  12244. this.start();
  12245. }
  12246. },
  12247. /**
  12248. * This calls the updateClustes with default arguments
  12249. */
  12250. updateClustersDefault : function() {
  12251. if (this.constants.clustering.enabled == true) {
  12252. this.updateClusters(0,false,false);
  12253. }
  12254. },
  12255. /**
  12256. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  12257. * be clustered with their connected node. This can be repeated as many times as needed.
  12258. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  12259. */
  12260. increaseClusterLevel : function() {
  12261. this.updateClusters(-1,false,true);
  12262. },
  12263. /**
  12264. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  12265. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  12266. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  12267. */
  12268. decreaseClusterLevel : function() {
  12269. this.updateClusters(1,false,true);
  12270. },
  12271. /**
  12272. * This is the main clustering function. It clusters and declusters on zoom or forced
  12273. * This function clusters on zoom, it can be called with a predefined zoom direction
  12274. * If out, check if we can form clusters, if in, check if we can open clusters.
  12275. * This function is only called from _zoom()
  12276. *
  12277. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  12278. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  12279. * @param {Boolean} force | enabled or disable forcing
  12280. *
  12281. */
  12282. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  12283. var isMovingBeforeClustering = this.moving;
  12284. var amountOfNodes = this.nodeIndices.length;
  12285. // on zoom out collapse the sector if the scale is at the level the sector was made
  12286. if (this.previousScale > this.scale && zoomDirection == 0) {
  12287. this._collapseSector();
  12288. }
  12289. // check if we zoom in or out
  12290. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12291. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  12292. // outer nodes determines if it is being clustered
  12293. this._formClusters(force);
  12294. }
  12295. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  12296. if (force == true) {
  12297. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  12298. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  12299. this._openClusters(recursive,force);
  12300. }
  12301. else {
  12302. // if a cluster takes up a set percentage of the active window
  12303. this._openClustersBySize();
  12304. }
  12305. }
  12306. this._updateNodeIndexList();
  12307. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  12308. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  12309. this._aggregateHubs(force);
  12310. this._updateNodeIndexList();
  12311. }
  12312. // we now reduce chains.
  12313. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12314. this.handleChains();
  12315. this._updateNodeIndexList();
  12316. }
  12317. this.previousScale = this.scale;
  12318. // rest of the update the index list, dynamic edges and labels
  12319. this._updateDynamicEdges();
  12320. this.updateLabels();
  12321. // if a cluster was formed, we increase the clusterSession
  12322. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  12323. this.clusterSession += 1;
  12324. // if clusters have been made, we normalize the cluster level
  12325. this.normalizeClusterLevels();
  12326. }
  12327. if (doNotStart == false || doNotStart === undefined) {
  12328. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12329. if (this.moving != isMovingBeforeClustering) {
  12330. this.start();
  12331. }
  12332. }
  12333. this._updateCalculationNodes();
  12334. },
  12335. /**
  12336. * This function handles the chains. It is called on every updateClusters().
  12337. */
  12338. handleChains : function() {
  12339. // after clustering we check how many chains there are
  12340. var chainPercentage = this._getChainFraction();
  12341. if (chainPercentage > this.constants.clustering.chainThreshold) {
  12342. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  12343. }
  12344. },
  12345. /**
  12346. * this functions starts clustering by hubs
  12347. * The minimum hub threshold is set globally
  12348. *
  12349. * @private
  12350. */
  12351. _aggregateHubs : function(force) {
  12352. this._getHubSize();
  12353. this._formClustersByHub(force,false);
  12354. },
  12355. /**
  12356. * This function is fired by keypress. It forces hubs to form.
  12357. *
  12358. */
  12359. forceAggregateHubs : function(doNotStart) {
  12360. var isMovingBeforeClustering = this.moving;
  12361. var amountOfNodes = this.nodeIndices.length;
  12362. this._aggregateHubs(true);
  12363. // update the index list, dynamic edges and labels
  12364. this._updateNodeIndexList();
  12365. this._updateDynamicEdges();
  12366. this.updateLabels();
  12367. // if a cluster was formed, we increase the clusterSession
  12368. if (this.nodeIndices.length != amountOfNodes) {
  12369. this.clusterSession += 1;
  12370. }
  12371. if (doNotStart == false || doNotStart === undefined) {
  12372. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12373. if (this.moving != isMovingBeforeClustering) {
  12374. this.start();
  12375. }
  12376. }
  12377. },
  12378. /**
  12379. * If a cluster takes up more than a set percentage of the screen, open the cluster
  12380. *
  12381. * @private
  12382. */
  12383. _openClustersBySize : function() {
  12384. for (var nodeId in this.nodes) {
  12385. if (this.nodes.hasOwnProperty(nodeId)) {
  12386. var node = this.nodes[nodeId];
  12387. if (node.inView() == true) {
  12388. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  12389. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  12390. this.openCluster(node);
  12391. }
  12392. }
  12393. }
  12394. }
  12395. },
  12396. /**
  12397. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  12398. * has to be opened based on the current zoom level.
  12399. *
  12400. * @private
  12401. */
  12402. _openClusters : function(recursive,force) {
  12403. for (var i = 0; i < this.nodeIndices.length; i++) {
  12404. var node = this.nodes[this.nodeIndices[i]];
  12405. this._expandClusterNode(node,recursive,force);
  12406. this._updateCalculationNodes();
  12407. }
  12408. },
  12409. /**
  12410. * This function checks if a node has to be opened. This is done by checking the zoom level.
  12411. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  12412. * This recursive behaviour is optional and can be set by the recursive argument.
  12413. *
  12414. * @param {Node} parentNode | to check for cluster and expand
  12415. * @param {Boolean} recursive | enabled or disable recursive calling
  12416. * @param {Boolean} force | enabled or disable forcing
  12417. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  12418. * @private
  12419. */
  12420. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  12421. // first check if node is a cluster
  12422. if (parentNode.clusterSize > 1) {
  12423. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  12424. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  12425. openAll = true;
  12426. }
  12427. recursive = openAll ? true : recursive;
  12428. // if the last child has been added on a smaller scale than current scale decluster
  12429. if (parentNode.formationScale < this.scale || force == true) {
  12430. // we will check if any of the contained child nodes should be removed from the cluster
  12431. for (var containedNodeId in parentNode.containedNodes) {
  12432. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  12433. var childNode = parentNode.containedNodes[containedNodeId];
  12434. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  12435. // the largest cluster is the one that comes from outside
  12436. if (force == true) {
  12437. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  12438. || openAll) {
  12439. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12440. }
  12441. }
  12442. else {
  12443. if (this._nodeInActiveArea(parentNode)) {
  12444. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12445. }
  12446. }
  12447. }
  12448. }
  12449. }
  12450. }
  12451. },
  12452. /**
  12453. * ONLY CALLED FROM _expandClusterNode
  12454. *
  12455. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  12456. * the child node from the parent contained_node object and put it back into the global nodes object.
  12457. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  12458. *
  12459. * @param {Node} parentNode | the parent node
  12460. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  12461. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  12462. * With force and recursive both true, the entire cluster is unpacked
  12463. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  12464. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  12465. * @private
  12466. */
  12467. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  12468. var childNode = parentNode.containedNodes[containedNodeId];
  12469. // if child node has been added on smaller scale than current, kick out
  12470. if (childNode.formationScale < this.scale || force == true) {
  12471. // unselect all selected items
  12472. this._unselectAll();
  12473. // put the child node back in the global nodes object
  12474. this.nodes[containedNodeId] = childNode;
  12475. // release the contained edges from this childNode back into the global edges
  12476. this._releaseContainedEdges(parentNode,childNode);
  12477. // reconnect rerouted edges to the childNode
  12478. this._connectEdgeBackToChild(parentNode,childNode);
  12479. // validate all edges in dynamicEdges
  12480. this._validateEdges(parentNode);
  12481. // undo the changes from the clustering operation on the parent node
  12482. parentNode.mass -= childNode.mass;
  12483. parentNode.clusterSize -= childNode.clusterSize;
  12484. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12485. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12486. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12487. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12488. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12489. // remove node from the list
  12490. delete parentNode.containedNodes[containedNodeId];
  12491. // check if there are other childs with this clusterSession in the parent.
  12492. var othersPresent = false;
  12493. for (var childNodeId in parentNode.containedNodes) {
  12494. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12495. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12496. othersPresent = true;
  12497. break;
  12498. }
  12499. }
  12500. }
  12501. // if there are no others, remove the cluster session from the list
  12502. if (othersPresent == false) {
  12503. parentNode.clusterSessions.pop();
  12504. }
  12505. this._repositionBezierNodes(childNode);
  12506. // this._repositionBezierNodes(parentNode);
  12507. // remove the clusterSession from the child node
  12508. childNode.clusterSession = 0;
  12509. // recalculate the size of the node on the next time the node is rendered
  12510. parentNode.clearSizeCache();
  12511. // restart the simulation to reorganise all nodes
  12512. this.moving = true;
  12513. }
  12514. // check if a further expansion step is possible if recursivity is enabled
  12515. if (recursive == true) {
  12516. this._expandClusterNode(childNode,recursive,force,openAll);
  12517. }
  12518. },
  12519. /**
  12520. * position the bezier nodes at the center of the edges
  12521. *
  12522. * @param node
  12523. * @private
  12524. */
  12525. _repositionBezierNodes : function(node) {
  12526. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12527. node.dynamicEdges[i].positionBezierNode();
  12528. }
  12529. },
  12530. /**
  12531. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12532. * This function is called only from updateClusters()
  12533. * forceLevelCollapse ignores the length of the edge and collapses one level
  12534. * This means that a node with only one edge will be clustered with its connected node
  12535. *
  12536. * @private
  12537. * @param {Boolean} force
  12538. */
  12539. _formClusters : function(force) {
  12540. if (force == false) {
  12541. this._formClustersByZoom();
  12542. }
  12543. else {
  12544. this._forceClustersByZoom();
  12545. }
  12546. },
  12547. /**
  12548. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12549. *
  12550. * @private
  12551. */
  12552. _formClustersByZoom : function() {
  12553. var dx,dy,length,
  12554. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12555. // check if any edges are shorter than minLength and start the clustering
  12556. // the clustering favours the node with the larger mass
  12557. for (var edgeId in this.edges) {
  12558. if (this.edges.hasOwnProperty(edgeId)) {
  12559. var edge = this.edges[edgeId];
  12560. if (edge.connected) {
  12561. if (edge.toId != edge.fromId) {
  12562. dx = (edge.to.x - edge.from.x);
  12563. dy = (edge.to.y - edge.from.y);
  12564. length = Math.sqrt(dx * dx + dy * dy);
  12565. if (length < minLength) {
  12566. // first check which node is larger
  12567. var parentNode = edge.from;
  12568. var childNode = edge.to;
  12569. if (edge.to.mass > edge.from.mass) {
  12570. parentNode = edge.to;
  12571. childNode = edge.from;
  12572. }
  12573. if (childNode.dynamicEdgesLength == 1) {
  12574. this._addToCluster(parentNode,childNode,false);
  12575. }
  12576. else if (parentNode.dynamicEdgesLength == 1) {
  12577. this._addToCluster(childNode,parentNode,false);
  12578. }
  12579. }
  12580. }
  12581. }
  12582. }
  12583. }
  12584. },
  12585. /**
  12586. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12587. * connected node.
  12588. *
  12589. * @private
  12590. */
  12591. _forceClustersByZoom : function() {
  12592. for (var nodeId in this.nodes) {
  12593. // another node could have absorbed this child.
  12594. if (this.nodes.hasOwnProperty(nodeId)) {
  12595. var childNode = this.nodes[nodeId];
  12596. // the edges can be swallowed by another decrease
  12597. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12598. var edge = childNode.dynamicEdges[0];
  12599. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12600. // group to the largest node
  12601. if (childNode.id != parentNode.id) {
  12602. if (parentNode.mass > childNode.mass) {
  12603. this._addToCluster(parentNode,childNode,true);
  12604. }
  12605. else {
  12606. this._addToCluster(childNode,parentNode,true);
  12607. }
  12608. }
  12609. }
  12610. }
  12611. }
  12612. },
  12613. /**
  12614. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12615. * This function clusters a node to its smallest connected neighbour.
  12616. *
  12617. * @param node
  12618. * @private
  12619. */
  12620. _clusterToSmallestNeighbour : function(node) {
  12621. var smallestNeighbour = -1;
  12622. var smallestNeighbourNode = null;
  12623. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12624. if (node.dynamicEdges[i] !== undefined) {
  12625. var neighbour = null;
  12626. if (node.dynamicEdges[i].fromId != node.id) {
  12627. neighbour = node.dynamicEdges[i].from;
  12628. }
  12629. else if (node.dynamicEdges[i].toId != node.id) {
  12630. neighbour = node.dynamicEdges[i].to;
  12631. }
  12632. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12633. smallestNeighbour = neighbour.clusterSessions.length;
  12634. smallestNeighbourNode = neighbour;
  12635. }
  12636. }
  12637. }
  12638. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12639. this._addToCluster(neighbour, node, true);
  12640. }
  12641. },
  12642. /**
  12643. * This function forms clusters from hubs, it loops over all nodes
  12644. *
  12645. * @param {Boolean} force | Disregard zoom level
  12646. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12647. * @private
  12648. */
  12649. _formClustersByHub : function(force, onlyEqual) {
  12650. // we loop over all nodes in the list
  12651. for (var nodeId in this.nodes) {
  12652. // we check if it is still available since it can be used by the clustering in this loop
  12653. if (this.nodes.hasOwnProperty(nodeId)) {
  12654. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12655. }
  12656. }
  12657. },
  12658. /**
  12659. * This function forms a cluster from a specific preselected hub node
  12660. *
  12661. * @param {Node} hubNode | the node we will cluster as a hub
  12662. * @param {Boolean} force | Disregard zoom level
  12663. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12664. * @param {Number} [absorptionSizeOffset] |
  12665. * @private
  12666. */
  12667. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12668. if (absorptionSizeOffset === undefined) {
  12669. absorptionSizeOffset = 0;
  12670. }
  12671. // we decide if the node is a hub
  12672. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12673. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12674. // initialize variables
  12675. var dx,dy,length;
  12676. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12677. var allowCluster = false;
  12678. // we create a list of edges because the dynamicEdges change over the course of this loop
  12679. var edgesIdarray = [];
  12680. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12681. for (var j = 0; j < amountOfInitialEdges; j++) {
  12682. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12683. }
  12684. // if the hub clustering is not forces, we check if one of the edges connected
  12685. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12686. if (force == false) {
  12687. allowCluster = false;
  12688. for (j = 0; j < amountOfInitialEdges; j++) {
  12689. var edge = this.edges[edgesIdarray[j]];
  12690. if (edge !== undefined) {
  12691. if (edge.connected) {
  12692. if (edge.toId != edge.fromId) {
  12693. dx = (edge.to.x - edge.from.x);
  12694. dy = (edge.to.y - edge.from.y);
  12695. length = Math.sqrt(dx * dx + dy * dy);
  12696. if (length < minLength) {
  12697. allowCluster = true;
  12698. break;
  12699. }
  12700. }
  12701. }
  12702. }
  12703. }
  12704. }
  12705. // start the clustering if allowed
  12706. if ((!force && allowCluster) || force) {
  12707. // we loop over all edges INITIALLY connected to this hub
  12708. for (j = 0; j < amountOfInitialEdges; j++) {
  12709. edge = this.edges[edgesIdarray[j]];
  12710. // the edge can be clustered by this function in a previous loop
  12711. if (edge !== undefined) {
  12712. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12713. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12714. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12715. (childNode.id != hubNode.id)) {
  12716. this._addToCluster(hubNode,childNode,force);
  12717. }
  12718. }
  12719. }
  12720. }
  12721. }
  12722. },
  12723. /**
  12724. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12725. *
  12726. * @param {Node} parentNode | this is the node that will house the child node
  12727. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12728. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12729. * @private
  12730. */
  12731. _addToCluster : function(parentNode, childNode, force) {
  12732. // join child node in the parent node
  12733. parentNode.containedNodes[childNode.id] = childNode;
  12734. // manage all the edges connected to the child and parent nodes
  12735. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12736. var edge = childNode.dynamicEdges[i];
  12737. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12738. this._addToContainedEdges(parentNode,childNode,edge);
  12739. }
  12740. else {
  12741. this._connectEdgeToCluster(parentNode,childNode,edge);
  12742. }
  12743. }
  12744. // a contained node has no dynamic edges.
  12745. childNode.dynamicEdges = [];
  12746. // remove circular edges from clusters
  12747. this._containCircularEdgesFromNode(parentNode,childNode);
  12748. // remove the childNode from the global nodes object
  12749. delete this.nodes[childNode.id];
  12750. // update the properties of the child and parent
  12751. var massBefore = parentNode.mass;
  12752. childNode.clusterSession = this.clusterSession;
  12753. parentNode.mass += childNode.mass;
  12754. parentNode.clusterSize += childNode.clusterSize;
  12755. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12756. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12757. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12758. parentNode.clusterSessions.push(this.clusterSession);
  12759. }
  12760. // forced clusters only open from screen size and double tap
  12761. if (force == true) {
  12762. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12763. parentNode.formationScale = 0;
  12764. }
  12765. else {
  12766. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12767. }
  12768. // recalculate the size of the node on the next time the node is rendered
  12769. parentNode.clearSizeCache();
  12770. // set the pop-out scale for the childnode
  12771. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12772. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12773. childNode.clearVelocity();
  12774. // the mass has altered, preservation of energy dictates the velocity to be updated
  12775. parentNode.updateVelocity(massBefore);
  12776. // restart the simulation to reorganise all nodes
  12777. this.moving = true;
  12778. },
  12779. /**
  12780. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12781. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12782. * It has to be called if a level is collapsed. It is called by _formClusters().
  12783. * @private
  12784. */
  12785. _updateDynamicEdges : function() {
  12786. for (var i = 0; i < this.nodeIndices.length; i++) {
  12787. var node = this.nodes[this.nodeIndices[i]];
  12788. node.dynamicEdgesLength = node.dynamicEdges.length;
  12789. // this corrects for multiple edges pointing at the same other node
  12790. var correction = 0;
  12791. if (node.dynamicEdgesLength > 1) {
  12792. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12793. var edgeToId = node.dynamicEdges[j].toId;
  12794. var edgeFromId = node.dynamicEdges[j].fromId;
  12795. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12796. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12797. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12798. correction += 1;
  12799. }
  12800. }
  12801. }
  12802. }
  12803. node.dynamicEdgesLength -= correction;
  12804. }
  12805. },
  12806. /**
  12807. * This adds an edge from the childNode to the contained edges of the parent node
  12808. *
  12809. * @param parentNode | Node object
  12810. * @param childNode | Node object
  12811. * @param edge | Edge object
  12812. * @private
  12813. */
  12814. _addToContainedEdges : function(parentNode, childNode, edge) {
  12815. // create an array object if it does not yet exist for this childNode
  12816. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12817. parentNode.containedEdges[childNode.id] = []
  12818. }
  12819. // add this edge to the list
  12820. parentNode.containedEdges[childNode.id].push(edge);
  12821. // remove the edge from the global edges object
  12822. delete this.edges[edge.id];
  12823. // remove the edge from the parent object
  12824. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12825. if (parentNode.dynamicEdges[i].id == edge.id) {
  12826. parentNode.dynamicEdges.splice(i,1);
  12827. break;
  12828. }
  12829. }
  12830. },
  12831. /**
  12832. * This function connects an edge that was connected to a child node to the parent node.
  12833. * It keeps track of which nodes it has been connected to with the originalId array.
  12834. *
  12835. * @param {Node} parentNode | Node object
  12836. * @param {Node} childNode | Node object
  12837. * @param {Edge} edge | Edge object
  12838. * @private
  12839. */
  12840. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12841. // handle circular edges
  12842. if (edge.toId == edge.fromId) {
  12843. this._addToContainedEdges(parentNode, childNode, edge);
  12844. }
  12845. else {
  12846. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12847. edge.originalToId.push(childNode.id);
  12848. edge.to = parentNode;
  12849. edge.toId = parentNode.id;
  12850. }
  12851. else { // edge connected to other node with the "from" side
  12852. edge.originalFromId.push(childNode.id);
  12853. edge.from = parentNode;
  12854. edge.fromId = parentNode.id;
  12855. }
  12856. this._addToReroutedEdges(parentNode,childNode,edge);
  12857. }
  12858. },
  12859. /**
  12860. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12861. * these edges inside of the cluster.
  12862. *
  12863. * @param parentNode
  12864. * @param childNode
  12865. * @private
  12866. */
  12867. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12868. // manage all the edges connected to the child and parent nodes
  12869. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12870. var edge = parentNode.dynamicEdges[i];
  12871. // handle circular edges
  12872. if (edge.toId == edge.fromId) {
  12873. this._addToContainedEdges(parentNode, childNode, edge);
  12874. }
  12875. }
  12876. },
  12877. /**
  12878. * This adds an edge from the childNode to the rerouted edges of the parent node
  12879. *
  12880. * @param parentNode | Node object
  12881. * @param childNode | Node object
  12882. * @param edge | Edge object
  12883. * @private
  12884. */
  12885. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12886. // create an array object if it does not yet exist for this childNode
  12887. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12888. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12889. parentNode.reroutedEdges[childNode.id] = [];
  12890. }
  12891. parentNode.reroutedEdges[childNode.id].push(edge);
  12892. // this edge becomes part of the dynamicEdges of the cluster node
  12893. parentNode.dynamicEdges.push(edge);
  12894. },
  12895. /**
  12896. * This function connects an edge that was connected to a cluster node back to the child node.
  12897. *
  12898. * @param parentNode | Node object
  12899. * @param childNode | Node object
  12900. * @private
  12901. */
  12902. _connectEdgeBackToChild : function(parentNode, childNode) {
  12903. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12904. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12905. var edge = parentNode.reroutedEdges[childNode.id][i];
  12906. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12907. edge.originalFromId.pop();
  12908. edge.fromId = childNode.id;
  12909. edge.from = childNode;
  12910. }
  12911. else {
  12912. edge.originalToId.pop();
  12913. edge.toId = childNode.id;
  12914. edge.to = childNode;
  12915. }
  12916. // append this edge to the list of edges connecting to the childnode
  12917. childNode.dynamicEdges.push(edge);
  12918. // remove the edge from the parent object
  12919. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12920. if (parentNode.dynamicEdges[j].id == edge.id) {
  12921. parentNode.dynamicEdges.splice(j,1);
  12922. break;
  12923. }
  12924. }
  12925. }
  12926. // remove the entry from the rerouted edges
  12927. delete parentNode.reroutedEdges[childNode.id];
  12928. }
  12929. },
  12930. /**
  12931. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12932. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12933. * parentNode
  12934. *
  12935. * @param parentNode | Node object
  12936. * @private
  12937. */
  12938. _validateEdges : function(parentNode) {
  12939. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12940. var edge = parentNode.dynamicEdges[i];
  12941. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12942. parentNode.dynamicEdges.splice(i,1);
  12943. }
  12944. }
  12945. },
  12946. /**
  12947. * This function released the contained edges back into the global domain and puts them back into the
  12948. * dynamic edges of both parent and child.
  12949. *
  12950. * @param {Node} parentNode |
  12951. * @param {Node} childNode |
  12952. * @private
  12953. */
  12954. _releaseContainedEdges : function(parentNode, childNode) {
  12955. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12956. var edge = parentNode.containedEdges[childNode.id][i];
  12957. // put the edge back in the global edges object
  12958. this.edges[edge.id] = edge;
  12959. // put the edge back in the dynamic edges of the child and parent
  12960. childNode.dynamicEdges.push(edge);
  12961. parentNode.dynamicEdges.push(edge);
  12962. }
  12963. // remove the entry from the contained edges
  12964. delete parentNode.containedEdges[childNode.id];
  12965. },
  12966. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  12967. /**
  12968. * This updates the node labels for all nodes (for debugging purposes)
  12969. */
  12970. updateLabels : function() {
  12971. var nodeId;
  12972. // update node labels
  12973. for (nodeId in this.nodes) {
  12974. if (this.nodes.hasOwnProperty(nodeId)) {
  12975. var node = this.nodes[nodeId];
  12976. if (node.clusterSize > 1) {
  12977. node.label = "[".concat(String(node.clusterSize),"]");
  12978. }
  12979. }
  12980. }
  12981. // update node labels
  12982. for (nodeId in this.nodes) {
  12983. if (this.nodes.hasOwnProperty(nodeId)) {
  12984. node = this.nodes[nodeId];
  12985. if (node.clusterSize == 1) {
  12986. if (node.originalLabel !== undefined) {
  12987. node.label = node.originalLabel;
  12988. }
  12989. else {
  12990. node.label = String(node.id);
  12991. }
  12992. }
  12993. }
  12994. }
  12995. // /* Debug Override */
  12996. // for (nodeId in this.nodes) {
  12997. // if (this.nodes.hasOwnProperty(nodeId)) {
  12998. // node = this.nodes[nodeId];
  12999. // node.label = String(node.level);
  13000. // }
  13001. // }
  13002. },
  13003. /**
  13004. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  13005. * if the rest of the nodes are already a few cluster levels in.
  13006. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  13007. * clustered enough to the clusterToSmallestNeighbours function.
  13008. */
  13009. normalizeClusterLevels : function() {
  13010. var maxLevel = 0;
  13011. var minLevel = 1e9;
  13012. var clusterLevel = 0;
  13013. // we loop over all nodes in the list
  13014. for (var nodeId in this.nodes) {
  13015. if (this.nodes.hasOwnProperty(nodeId)) {
  13016. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  13017. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  13018. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  13019. }
  13020. }
  13021. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  13022. var amountOfNodes = this.nodeIndices.length;
  13023. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  13024. // we loop over all nodes in the list
  13025. for (var nodeId in this.nodes) {
  13026. if (this.nodes.hasOwnProperty(nodeId)) {
  13027. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  13028. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  13029. }
  13030. }
  13031. }
  13032. this._updateNodeIndexList();
  13033. this._updateDynamicEdges();
  13034. // if a cluster was formed, we increase the clusterSession
  13035. if (this.nodeIndices.length != amountOfNodes) {
  13036. this.clusterSession += 1;
  13037. }
  13038. }
  13039. },
  13040. /**
  13041. * This function determines if the cluster we want to decluster is in the active area
  13042. * this means around the zoom center
  13043. *
  13044. * @param {Node} node
  13045. * @returns {boolean}
  13046. * @private
  13047. */
  13048. _nodeInActiveArea : function(node) {
  13049. return (
  13050. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  13051. &&
  13052. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  13053. )
  13054. },
  13055. /**
  13056. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  13057. * It puts large clusters away from the center and randomizes the order.
  13058. *
  13059. */
  13060. repositionNodes : function() {
  13061. for (var i = 0; i < this.nodeIndices.length; i++) {
  13062. var node = this.nodes[this.nodeIndices[i]];
  13063. if ((node.xFixed == false || node.yFixed == false)) {
  13064. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.mass);
  13065. var angle = 2 * Math.PI * Math.random();
  13066. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  13067. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  13068. this._repositionBezierNodes(node);
  13069. }
  13070. }
  13071. },
  13072. /**
  13073. * We determine how many connections denote an important hub.
  13074. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  13075. *
  13076. * @private
  13077. */
  13078. _getHubSize : function() {
  13079. var average = 0;
  13080. var averageSquared = 0;
  13081. var hubCounter = 0;
  13082. var largestHub = 0;
  13083. for (var i = 0; i < this.nodeIndices.length; i++) {
  13084. var node = this.nodes[this.nodeIndices[i]];
  13085. if (node.dynamicEdgesLength > largestHub) {
  13086. largestHub = node.dynamicEdgesLength;
  13087. }
  13088. average += node.dynamicEdgesLength;
  13089. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  13090. hubCounter += 1;
  13091. }
  13092. average = average / hubCounter;
  13093. averageSquared = averageSquared / hubCounter;
  13094. var variance = averageSquared - Math.pow(average,2);
  13095. var standardDeviation = Math.sqrt(variance);
  13096. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  13097. // always have at least one to cluster
  13098. if (this.hubThreshold > largestHub) {
  13099. this.hubThreshold = largestHub;
  13100. }
  13101. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  13102. // console.log("hubThreshold:",this.hubThreshold);
  13103. },
  13104. /**
  13105. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  13106. * with this amount we can cluster specifically on these chains.
  13107. *
  13108. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  13109. * @private
  13110. */
  13111. _reduceAmountOfChains : function(fraction) {
  13112. this.hubThreshold = 2;
  13113. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  13114. for (var nodeId in this.nodes) {
  13115. if (this.nodes.hasOwnProperty(nodeId)) {
  13116. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  13117. if (reduceAmount > 0) {
  13118. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  13119. reduceAmount -= 1;
  13120. }
  13121. }
  13122. }
  13123. }
  13124. },
  13125. /**
  13126. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  13127. * with this amount we can cluster specifically on these chains.
  13128. *
  13129. * @private
  13130. */
  13131. _getChainFraction : function() {
  13132. var chains = 0;
  13133. var total = 0;
  13134. for (var nodeId in this.nodes) {
  13135. if (this.nodes.hasOwnProperty(nodeId)) {
  13136. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  13137. chains += 1;
  13138. }
  13139. total += 1;
  13140. }
  13141. }
  13142. return chains/total;
  13143. }
  13144. };
  13145. var SelectionMixin = {
  13146. /**
  13147. * This function can be called from the _doInAllSectors function
  13148. *
  13149. * @param object
  13150. * @param overlappingNodes
  13151. * @private
  13152. */
  13153. _getNodesOverlappingWith : function(object, overlappingNodes) {
  13154. var nodes = this.nodes;
  13155. for (var nodeId in nodes) {
  13156. if (nodes.hasOwnProperty(nodeId)) {
  13157. if (nodes[nodeId].isOverlappingWith(object)) {
  13158. overlappingNodes.push(nodeId);
  13159. }
  13160. }
  13161. }
  13162. },
  13163. /**
  13164. * retrieve all nodes overlapping with given object
  13165. * @param {Object} object An object with parameters left, top, right, bottom
  13166. * @return {Number[]} An array with id's of the overlapping nodes
  13167. * @private
  13168. */
  13169. _getAllNodesOverlappingWith : function (object) {
  13170. var overlappingNodes = [];
  13171. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  13172. return overlappingNodes;
  13173. },
  13174. /**
  13175. * Return a position object in canvasspace from a single point in screenspace
  13176. *
  13177. * @param pointer
  13178. * @returns {{left: number, top: number, right: number, bottom: number}}
  13179. * @private
  13180. */
  13181. _pointerToPositionObject : function(pointer) {
  13182. var x = this._canvasToX(pointer.x);
  13183. var y = this._canvasToY(pointer.y);
  13184. return {left: x,
  13185. top: y,
  13186. right: x,
  13187. bottom: y};
  13188. },
  13189. /**
  13190. * Get the top node at the a specific point (like a click)
  13191. *
  13192. * @param {{x: Number, y: Number}} pointer
  13193. * @return {Node | null} node
  13194. * @private
  13195. */
  13196. _getNodeAt : function (pointer) {
  13197. // we first check if this is an navigation controls element
  13198. var positionObject = this._pointerToPositionObject(pointer);
  13199. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  13200. // if there are overlapping nodes, select the last one, this is the
  13201. // one which is drawn on top of the others
  13202. if (overlappingNodes.length > 0) {
  13203. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  13204. }
  13205. else {
  13206. return null;
  13207. }
  13208. },
  13209. /**
  13210. * retrieve all edges overlapping with given object, selector is around center
  13211. * @param {Object} object An object with parameters left, top, right, bottom
  13212. * @return {Number[]} An array with id's of the overlapping nodes
  13213. * @private
  13214. */
  13215. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  13216. var edges = this.edges;
  13217. for (var edgeId in edges) {
  13218. if (edges.hasOwnProperty(edgeId)) {
  13219. if (edges[edgeId].isOverlappingWith(object)) {
  13220. overlappingEdges.push(edgeId);
  13221. }
  13222. }
  13223. }
  13224. },
  13225. /**
  13226. * retrieve all nodes overlapping with given object
  13227. * @param {Object} object An object with parameters left, top, right, bottom
  13228. * @return {Number[]} An array with id's of the overlapping nodes
  13229. * @private
  13230. */
  13231. _getAllEdgesOverlappingWith : function (object) {
  13232. var overlappingEdges = [];
  13233. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  13234. return overlappingEdges;
  13235. },
  13236. /**
  13237. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  13238. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  13239. *
  13240. * @param pointer
  13241. * @returns {null}
  13242. * @private
  13243. */
  13244. _getEdgeAt : function(pointer) {
  13245. var positionObject = this._pointerToPositionObject(pointer);
  13246. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  13247. if (overlappingEdges.length > 0) {
  13248. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  13249. }
  13250. else {
  13251. return null;
  13252. }
  13253. },
  13254. /**
  13255. * Add object to the selection array.
  13256. *
  13257. * @param obj
  13258. * @private
  13259. */
  13260. _addToSelection : function(obj) {
  13261. if (obj instanceof Node) {
  13262. this.selectionObj.nodes[obj.id] = obj;
  13263. }
  13264. else {
  13265. this.selectionObj.edges[obj.id] = obj;
  13266. }
  13267. },
  13268. /**
  13269. * Remove a single option from selection.
  13270. *
  13271. * @param {Object} obj
  13272. * @private
  13273. */
  13274. _removeFromSelection : function(obj) {
  13275. if (obj instanceof Node) {
  13276. delete this.selectionObj.nodes[obj.id];
  13277. }
  13278. else {
  13279. delete this.selectionObj.edges[obj.id];
  13280. }
  13281. },
  13282. /**
  13283. * Unselect all. The selectionObj is useful for this.
  13284. *
  13285. * @param {Boolean} [doNotTrigger] | ignore trigger
  13286. * @private
  13287. */
  13288. _unselectAll : function(doNotTrigger) {
  13289. if (doNotTrigger === undefined) {
  13290. doNotTrigger = false;
  13291. }
  13292. for(var nodeId in this.selectionObj.nodes) {
  13293. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13294. this.selectionObj.nodes[nodeId].unselect();
  13295. }
  13296. }
  13297. for(var edgeId in this.selectionObj.edges) {
  13298. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13299. this.selectionObj.edges[edgeId].unselect();;
  13300. }
  13301. }
  13302. this.selectionObj = {nodes:{},edges:{}};
  13303. if (doNotTrigger == false) {
  13304. this.emit('select', this.getSelection());
  13305. }
  13306. },
  13307. /**
  13308. * Unselect all clusters. The selectionObj is useful for this.
  13309. *
  13310. * @param {Boolean} [doNotTrigger] | ignore trigger
  13311. * @private
  13312. */
  13313. _unselectClusters : function(doNotTrigger) {
  13314. if (doNotTrigger === undefined) {
  13315. doNotTrigger = false;
  13316. }
  13317. for (var nodeId in this.selectionObj.nodes) {
  13318. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13319. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13320. this.selectionObj.nodes[nodeId].unselect();
  13321. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  13322. }
  13323. }
  13324. }
  13325. if (doNotTrigger == false) {
  13326. this.emit('select', this.getSelection());
  13327. }
  13328. },
  13329. /**
  13330. * return the number of selected nodes
  13331. *
  13332. * @returns {number}
  13333. * @private
  13334. */
  13335. _getSelectedNodeCount : function() {
  13336. var count = 0;
  13337. for (var nodeId in this.selectionObj.nodes) {
  13338. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13339. count += 1;
  13340. }
  13341. }
  13342. return count;
  13343. },
  13344. /**
  13345. * return the number of selected nodes
  13346. *
  13347. * @returns {number}
  13348. * @private
  13349. */
  13350. _getSelectedNode : function() {
  13351. for (var nodeId in this.selectionObj.nodes) {
  13352. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13353. return this.selectionObj.nodes[nodeId];
  13354. }
  13355. }
  13356. return null;
  13357. },
  13358. /**
  13359. * return the number of selected edges
  13360. *
  13361. * @returns {number}
  13362. * @private
  13363. */
  13364. _getSelectedEdgeCount : function() {
  13365. var count = 0;
  13366. for (var edgeId in this.selectionObj.edges) {
  13367. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13368. count += 1;
  13369. }
  13370. }
  13371. return count;
  13372. },
  13373. /**
  13374. * return the number of selected objects.
  13375. *
  13376. * @returns {number}
  13377. * @private
  13378. */
  13379. _getSelectedObjectCount : function() {
  13380. var count = 0;
  13381. for(var nodeId in this.selectionObj.nodes) {
  13382. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13383. count += 1;
  13384. }
  13385. }
  13386. for(var edgeId in this.selectionObj.edges) {
  13387. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13388. count += 1;
  13389. }
  13390. }
  13391. return count;
  13392. },
  13393. /**
  13394. * Check if anything is selected
  13395. *
  13396. * @returns {boolean}
  13397. * @private
  13398. */
  13399. _selectionIsEmpty : function() {
  13400. for(var nodeId in this.selectionObj.nodes) {
  13401. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13402. return false;
  13403. }
  13404. }
  13405. for(var edgeId in this.selectionObj.edges) {
  13406. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13407. return false;
  13408. }
  13409. }
  13410. return true;
  13411. },
  13412. /**
  13413. * check if one of the selected nodes is a cluster.
  13414. *
  13415. * @returns {boolean}
  13416. * @private
  13417. */
  13418. _clusterInSelection : function() {
  13419. for(var nodeId in this.selectionObj.nodes) {
  13420. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13421. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13422. return true;
  13423. }
  13424. }
  13425. }
  13426. return false;
  13427. },
  13428. /**
  13429. * select the edges connected to the node that is being selected
  13430. *
  13431. * @param {Node} node
  13432. * @private
  13433. */
  13434. _selectConnectedEdges : function(node) {
  13435. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13436. var edge = node.dynamicEdges[i];
  13437. edge.select();
  13438. this._addToSelection(edge);
  13439. }
  13440. },
  13441. /**
  13442. * unselect the edges connected to the node that is being selected
  13443. *
  13444. * @param {Node} node
  13445. * @private
  13446. */
  13447. _unselectConnectedEdges : function(node) {
  13448. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13449. var edge = node.dynamicEdges[i];
  13450. edge.unselect();
  13451. this._removeFromSelection(edge);
  13452. }
  13453. },
  13454. /**
  13455. * This is called when someone clicks on a node. either select or deselect it.
  13456. * If there is an existing selection and we don't want to append to it, clear the existing selection
  13457. *
  13458. * @param {Node || Edge} object
  13459. * @param {Boolean} append
  13460. * @param {Boolean} [doNotTrigger] | ignore trigger
  13461. * @private
  13462. */
  13463. _selectObject : function(object, append, doNotTrigger) {
  13464. if (doNotTrigger === undefined) {
  13465. doNotTrigger = false;
  13466. }
  13467. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  13468. this._unselectAll(true);
  13469. }
  13470. if (object.selected == false) {
  13471. object.select();
  13472. this._addToSelection(object);
  13473. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  13474. this._selectConnectedEdges(object);
  13475. }
  13476. }
  13477. else {
  13478. object.unselect();
  13479. this._removeFromSelection(object);
  13480. }
  13481. if (doNotTrigger == false) {
  13482. this.emit('select', this.getSelection());
  13483. }
  13484. },
  13485. /**
  13486. * handles the selection part of the touch, only for navigation controls elements;
  13487. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13488. * This is the most responsive solution
  13489. *
  13490. * @param {Object} pointer
  13491. * @private
  13492. */
  13493. _handleTouch : function(pointer) {
  13494. },
  13495. /**
  13496. * handles the selection part of the tap;
  13497. *
  13498. * @param {Object} pointer
  13499. * @private
  13500. */
  13501. _handleTap : function(pointer) {
  13502. var node = this._getNodeAt(pointer);
  13503. if (node != null) {
  13504. this._selectObject(node,false);
  13505. }
  13506. else {
  13507. var edge = this._getEdgeAt(pointer);
  13508. if (edge != null) {
  13509. this._selectObject(edge,false);
  13510. }
  13511. else {
  13512. this._unselectAll();
  13513. }
  13514. }
  13515. this.emit("click", this.getSelection());
  13516. this._redraw();
  13517. },
  13518. /**
  13519. * handles the selection part of the double tap and opens a cluster if needed
  13520. *
  13521. * @param {Object} pointer
  13522. * @private
  13523. */
  13524. _handleDoubleTap : function(pointer) {
  13525. var node = this._getNodeAt(pointer);
  13526. if (node != null && node !== undefined) {
  13527. // we reset the areaCenter here so the opening of the node will occur
  13528. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  13529. "y" : this._canvasToY(pointer.y)};
  13530. this.openCluster(node);
  13531. }
  13532. this.emit("doubleClick", this.getSelection());
  13533. },
  13534. /**
  13535. * Handle the onHold selection part
  13536. *
  13537. * @param pointer
  13538. * @private
  13539. */
  13540. _handleOnHold : function(pointer) {
  13541. var node = this._getNodeAt(pointer);
  13542. if (node != null) {
  13543. this._selectObject(node,true);
  13544. }
  13545. else {
  13546. var edge = this._getEdgeAt(pointer);
  13547. if (edge != null) {
  13548. this._selectObject(edge,true);
  13549. }
  13550. }
  13551. this._redraw();
  13552. },
  13553. /**
  13554. * handle the onRelease event. These functions are here for the navigation controls module.
  13555. *
  13556. * @private
  13557. */
  13558. _handleOnRelease : function(pointer) {
  13559. },
  13560. /**
  13561. *
  13562. * retrieve the currently selected objects
  13563. * @return {Number[] | String[]} selection An array with the ids of the
  13564. * selected nodes.
  13565. */
  13566. getSelection : function() {
  13567. var nodeIds = this.getSelectedNodes();
  13568. var edgeIds = this.getSelectedEdges();
  13569. return {nodes:nodeIds, edges:edgeIds};
  13570. },
  13571. /**
  13572. *
  13573. * retrieve the currently selected nodes
  13574. * @return {String} selection An array with the ids of the
  13575. * selected nodes.
  13576. */
  13577. getSelectedNodes : function() {
  13578. var idArray = [];
  13579. for(var nodeId in this.selectionObj.nodes) {
  13580. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13581. idArray.push(nodeId);
  13582. }
  13583. }
  13584. return idArray
  13585. },
  13586. /**
  13587. *
  13588. * retrieve the currently selected edges
  13589. * @return {Array} selection An array with the ids of the
  13590. * selected nodes.
  13591. */
  13592. getSelectedEdges : function() {
  13593. var idArray = [];
  13594. for(var edgeId in this.selectionObj.edges) {
  13595. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13596. idArray.push(edgeId);
  13597. }
  13598. }
  13599. return idArray;
  13600. },
  13601. /**
  13602. * select zero or more nodes
  13603. * @param {Number[] | String[]} selection An array with the ids of the
  13604. * selected nodes.
  13605. */
  13606. setSelection : function(selection) {
  13607. var i, iMax, id;
  13608. if (!selection || (selection.length == undefined))
  13609. throw 'Selection must be an array with ids';
  13610. // first unselect any selected node
  13611. this._unselectAll(true);
  13612. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13613. id = selection[i];
  13614. var node = this.nodes[id];
  13615. if (!node) {
  13616. throw new RangeError('Node with id "' + id + '" not found');
  13617. }
  13618. this._selectObject(node,true,true);
  13619. }
  13620. this.redraw();
  13621. },
  13622. /**
  13623. * Validate the selection: remove ids of nodes which no longer exist
  13624. * @private
  13625. */
  13626. _updateSelection : function () {
  13627. for(var nodeId in this.selectionObj.nodes) {
  13628. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13629. if (!this.nodes.hasOwnProperty(nodeId)) {
  13630. delete this.selectionObj.nodes[nodeId];
  13631. }
  13632. }
  13633. }
  13634. for(var edgeId in this.selectionObj.edges) {
  13635. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13636. if (!this.edges.hasOwnProperty(edgeId)) {
  13637. delete this.selectionObj.edges[edgeId];
  13638. }
  13639. }
  13640. }
  13641. }
  13642. };
  13643. /**
  13644. * Created by Alex on 1/22/14.
  13645. */
  13646. var NavigationMixin = {
  13647. _cleanNavigation : function() {
  13648. // clean up previosu navigation items
  13649. var wrapper = document.getElementById('graph-navigation_wrapper');
  13650. if (wrapper != null) {
  13651. this.containerElement.removeChild(wrapper);
  13652. }
  13653. document.onmouseup = null;
  13654. },
  13655. /**
  13656. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13657. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13658. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13659. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13660. *
  13661. * @private
  13662. */
  13663. _loadNavigationElements : function() {
  13664. this._cleanNavigation();
  13665. this.navigationDivs = {};
  13666. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13667. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  13668. this.navigationDivs['wrapper'] = document.createElement('div');
  13669. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13670. this.navigationDivs['wrapper'].style.position = "absolute";
  13671. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  13672. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  13673. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13674. for (var i = 0; i < navigationDivs.length; i++) {
  13675. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13676. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13677. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13678. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13679. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13680. }
  13681. document.onmouseup = this._stopMovement.bind(this);
  13682. },
  13683. /**
  13684. * this stops all movement induced by the navigation buttons
  13685. *
  13686. * @private
  13687. */
  13688. _stopMovement : function() {
  13689. this._xStopMoving();
  13690. this._yStopMoving();
  13691. this._stopZoom();
  13692. },
  13693. /**
  13694. * stops the actions performed by page up and down etc.
  13695. *
  13696. * @param event
  13697. * @private
  13698. */
  13699. _preventDefault : function(event) {
  13700. if (event !== undefined) {
  13701. if (event.preventDefault) {
  13702. event.preventDefault();
  13703. } else {
  13704. event.returnValue = false;
  13705. }
  13706. }
  13707. },
  13708. /**
  13709. * move the screen up
  13710. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13711. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13712. * To avoid this behaviour, we do the translation in the start loop.
  13713. *
  13714. * @private
  13715. */
  13716. _moveUp : function(event) {
  13717. this.yIncrement = this.constants.keyboard.speed.y;
  13718. this.start(); // if there is no node movement, the calculation wont be done
  13719. this._preventDefault(event);
  13720. if (this.navigationDivs) {
  13721. this.navigationDivs['up'].className += " active";
  13722. }
  13723. },
  13724. /**
  13725. * move the screen down
  13726. * @private
  13727. */
  13728. _moveDown : function(event) {
  13729. this.yIncrement = -this.constants.keyboard.speed.y;
  13730. this.start(); // if there is no node movement, the calculation wont be done
  13731. this._preventDefault(event);
  13732. if (this.navigationDivs) {
  13733. this.navigationDivs['down'].className += " active";
  13734. }
  13735. },
  13736. /**
  13737. * move the screen left
  13738. * @private
  13739. */
  13740. _moveLeft : function(event) {
  13741. this.xIncrement = this.constants.keyboard.speed.x;
  13742. this.start(); // if there is no node movement, the calculation wont be done
  13743. this._preventDefault(event);
  13744. if (this.navigationDivs) {
  13745. this.navigationDivs['left'].className += " active";
  13746. }
  13747. },
  13748. /**
  13749. * move the screen right
  13750. * @private
  13751. */
  13752. _moveRight : function(event) {
  13753. this.xIncrement = -this.constants.keyboard.speed.y;
  13754. this.start(); // if there is no node movement, the calculation wont be done
  13755. this._preventDefault(event);
  13756. if (this.navigationDivs) {
  13757. this.navigationDivs['right'].className += " active";
  13758. }
  13759. },
  13760. /**
  13761. * Zoom in, using the same method as the movement.
  13762. * @private
  13763. */
  13764. _zoomIn : function(event) {
  13765. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13766. this.start(); // if there is no node movement, the calculation wont be done
  13767. this._preventDefault(event);
  13768. if (this.navigationDivs) {
  13769. this.navigationDivs['zoomIn'].className += " active";
  13770. }
  13771. },
  13772. /**
  13773. * Zoom out
  13774. * @private
  13775. */
  13776. _zoomOut : function() {
  13777. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13778. this.start(); // if there is no node movement, the calculation wont be done
  13779. this._preventDefault(event);
  13780. if (this.navigationDivs) {
  13781. this.navigationDivs['zoomOut'].className += " active";
  13782. }
  13783. },
  13784. /**
  13785. * Stop zooming and unhighlight the zoom controls
  13786. * @private
  13787. */
  13788. _stopZoom : function() {
  13789. this.zoomIncrement = 0;
  13790. if (this.navigationDivs) {
  13791. this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active","");
  13792. this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active","");
  13793. }
  13794. },
  13795. /**
  13796. * Stop moving in the Y direction and unHighlight the up and down
  13797. * @private
  13798. */
  13799. _yStopMoving : function() {
  13800. this.yIncrement = 0;
  13801. if (this.navigationDivs) {
  13802. this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active","");
  13803. this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active","");
  13804. }
  13805. },
  13806. /**
  13807. * Stop moving in the X direction and unHighlight left and right.
  13808. * @private
  13809. */
  13810. _xStopMoving : function() {
  13811. this.xIncrement = 0;
  13812. if (this.navigationDivs) {
  13813. this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active","");
  13814. this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active","");
  13815. }
  13816. }
  13817. };
  13818. /**
  13819. * Created by Alex on 2/10/14.
  13820. */
  13821. var graphMixinLoaders = {
  13822. /**
  13823. * Load a mixin into the graph object
  13824. *
  13825. * @param {Object} sourceVariable | this object has to contain functions.
  13826. * @private
  13827. */
  13828. _loadMixin : function(sourceVariable) {
  13829. for (var mixinFunction in sourceVariable) {
  13830. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13831. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13832. }
  13833. }
  13834. },
  13835. /**
  13836. * removes a mixin from the graph object.
  13837. *
  13838. * @param {Object} sourceVariable | this object has to contain functions.
  13839. * @private
  13840. */
  13841. _clearMixin : function(sourceVariable) {
  13842. for (var mixinFunction in sourceVariable) {
  13843. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13844. Graph.prototype[mixinFunction] = undefined;
  13845. }
  13846. }
  13847. },
  13848. /**
  13849. * Mixin the physics system and initialize the parameters required.
  13850. *
  13851. * @private
  13852. */
  13853. _loadPhysicsSystem : function() {
  13854. this._loadMixin(physicsMixin);
  13855. this._loadSelectedForceSolver();
  13856. if (this.constants.configurePhysics == true) {
  13857. this._loadPhysicsConfiguration();
  13858. }
  13859. },
  13860. /**
  13861. * Mixin the cluster system and initialize the parameters required.
  13862. *
  13863. * @private
  13864. */
  13865. _loadClusterSystem : function() {
  13866. this.clusterSession = 0;
  13867. this.hubThreshold = 5;
  13868. this._loadMixin(ClusterMixin);
  13869. },
  13870. /**
  13871. * Mixin the sector system and initialize the parameters required
  13872. *
  13873. * @private
  13874. */
  13875. _loadSectorSystem : function() {
  13876. this.sectors = { },
  13877. this.activeSector = ["default"];
  13878. this.sectors["active"] = { },
  13879. this.sectors["active"]["default"] = {"nodes":{},
  13880. "edges":{},
  13881. "nodeIndices":[],
  13882. "formationScale": 1.0,
  13883. "drawingNode": undefined };
  13884. this.sectors["frozen"] = {},
  13885. this.sectors["support"] = {"nodes":{},
  13886. "edges":{},
  13887. "nodeIndices":[],
  13888. "formationScale": 1.0,
  13889. "drawingNode": undefined };
  13890. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13891. this._loadMixin(SectorMixin);
  13892. },
  13893. /**
  13894. * Mixin the selection system and initialize the parameters required
  13895. *
  13896. * @private
  13897. */
  13898. _loadSelectionSystem : function() {
  13899. this.selectionObj = {nodes:{},edges:{}};
  13900. this._loadMixin(SelectionMixin);
  13901. },
  13902. /**
  13903. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13904. *
  13905. * @private
  13906. */
  13907. _loadManipulationSystem : function() {
  13908. // reset global variables -- these are used by the selection of nodes and edges.
  13909. this.blockConnectingEdgeSelection = false;
  13910. this.forceAppendSelection = false
  13911. if (this.constants.dataManipulation.enabled == true) {
  13912. // load the manipulator HTML elements. All styling done in css.
  13913. if (this.manipulationDiv === undefined) {
  13914. this.manipulationDiv = document.createElement('div');
  13915. this.manipulationDiv.className = 'graph-manipulationDiv';
  13916. this.manipulationDiv.id = 'graph-manipulationDiv';
  13917. if (this.editMode == true) {
  13918. this.manipulationDiv.style.display = "block";
  13919. }
  13920. else {
  13921. this.manipulationDiv.style.display = "none";
  13922. }
  13923. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13924. }
  13925. if (this.editModeDiv === undefined) {
  13926. this.editModeDiv = document.createElement('div');
  13927. this.editModeDiv.className = 'graph-manipulation-editMode';
  13928. this.editModeDiv.id = 'graph-manipulation-editMode';
  13929. if (this.editMode == true) {
  13930. this.editModeDiv.style.display = "none";
  13931. }
  13932. else {
  13933. this.editModeDiv.style.display = "block";
  13934. }
  13935. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13936. }
  13937. if (this.closeDiv === undefined) {
  13938. this.closeDiv = document.createElement('div');
  13939. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13940. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13941. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13942. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13943. }
  13944. // load the manipulation functions
  13945. this._loadMixin(manipulationMixin);
  13946. // create the manipulator toolbar
  13947. this._createManipulatorBar();
  13948. }
  13949. else {
  13950. if (this.manipulationDiv !== undefined) {
  13951. // removes all the bindings and overloads
  13952. this._createManipulatorBar();
  13953. // remove the manipulation divs
  13954. this.containerElement.removeChild(this.manipulationDiv);
  13955. this.containerElement.removeChild(this.editModeDiv);
  13956. this.containerElement.removeChild(this.closeDiv);
  13957. this.manipulationDiv = undefined;
  13958. this.editModeDiv = undefined;
  13959. this.closeDiv = undefined;
  13960. // remove the mixin functions
  13961. this._clearMixin(manipulationMixin);
  13962. }
  13963. }
  13964. },
  13965. /**
  13966. * Mixin the navigation (User Interface) system and initialize the parameters required
  13967. *
  13968. * @private
  13969. */
  13970. _loadNavigationControls : function() {
  13971. this._loadMixin(NavigationMixin);
  13972. // the clean function removes the button divs, this is done to remove the bindings.
  13973. this._cleanNavigation();
  13974. if (this.constants.navigation.enabled == true) {
  13975. this._loadNavigationElements();
  13976. }
  13977. },
  13978. /**
  13979. * Mixin the hierarchical layout system.
  13980. *
  13981. * @private
  13982. */
  13983. _loadHierarchySystem : function() {
  13984. this._loadMixin(HierarchicalLayoutMixin);
  13985. }
  13986. }
  13987. /**
  13988. * @constructor Graph
  13989. * Create a graph visualization, displaying nodes and edges.
  13990. *
  13991. * @param {Element} container The DOM element in which the Graph will
  13992. * be created. Normally a div element.
  13993. * @param {Object} data An object containing parameters
  13994. * {Array} nodes
  13995. * {Array} edges
  13996. * @param {Object} options Options
  13997. */
  13998. function Graph (container, data, options) {
  13999. this._initializeMixinLoaders();
  14000. // create variables and set default values
  14001. this.containerElement = container;
  14002. this.width = '100%';
  14003. this.height = '100%';
  14004. // render and calculation settings
  14005. this.renderRefreshRate = 60; // hz (fps)
  14006. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  14007. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  14008. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  14009. this.physicsDiscreteStepsize = 0.65; // discrete stepsize of the simulation
  14010. this.stabilize = true; // stabilize before displaying the graph
  14011. this.selectable = true;
  14012. // these functions are triggered when the dataset is edited
  14013. this.triggerFunctions = {add:null,edit:null,connect:null,delete:null};
  14014. // set constant values
  14015. this.constants = {
  14016. nodes: {
  14017. radiusMin: 5,
  14018. radiusMax: 20,
  14019. radius: 5,
  14020. shape: 'ellipse',
  14021. image: undefined,
  14022. widthMin: 16, // px
  14023. widthMax: 64, // px
  14024. fixed: false,
  14025. fontColor: 'black',
  14026. fontSize: 14, // px
  14027. fontFace: 'verdana',
  14028. level: -1,
  14029. color: {
  14030. border: '#2B7CE9',
  14031. background: '#97C2FC',
  14032. highlight: {
  14033. border: '#2B7CE9',
  14034. background: '#D2E5FF'
  14035. }
  14036. },
  14037. borderColor: '#2B7CE9',
  14038. backgroundColor: '#97C2FC',
  14039. highlightColor: '#D2E5FF',
  14040. group: undefined
  14041. },
  14042. edges: {
  14043. widthMin: 1,
  14044. widthMax: 15,
  14045. width: 1,
  14046. style: 'line',
  14047. color: {
  14048. color:'#848484',
  14049. highlight:'#848484'
  14050. },
  14051. fontColor: '#343434',
  14052. fontSize: 14, // px
  14053. fontFace: 'arial',
  14054. dash: {
  14055. length: 10,
  14056. gap: 5,
  14057. altLength: undefined
  14058. }
  14059. },
  14060. configurePhysics:false,
  14061. physics: {
  14062. barnesHut: {
  14063. enabled: true,
  14064. theta: 1 / 0.6, // inverted to save time during calculation
  14065. gravitationalConstant: -2000,
  14066. centralGravity: 0.3,
  14067. springLength: 95,
  14068. springConstant: 0.04,
  14069. damping: 0.09
  14070. },
  14071. repulsion: {
  14072. centralGravity: 0.1,
  14073. springLength: 200,
  14074. springConstant: 0.05,
  14075. nodeDistance: 100,
  14076. damping: 0.09
  14077. },
  14078. hierarchicalRepulsion: {
  14079. enabled: false,
  14080. centralGravity: 0.0,
  14081. springLength: 100,
  14082. springConstant: 0.01,
  14083. nodeDistance: 60,
  14084. damping: 0.09
  14085. },
  14086. damping: null,
  14087. centralGravity: null,
  14088. springLength: null,
  14089. springConstant: null
  14090. },
  14091. clustering: { // Per Node in Cluster = PNiC
  14092. enabled: false, // (Boolean) | global on/off switch for clustering.
  14093. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  14094. 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
  14095. 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
  14096. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  14097. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  14098. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  14099. 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.
  14100. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  14101. maxFontSize: 1000,
  14102. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  14103. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  14104. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  14105. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  14106. height: 1, // (px PNiC) | growth of the height per node in cluster.
  14107. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  14108. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  14109. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  14110. clusterLevelDifference: 2
  14111. },
  14112. navigation: {
  14113. enabled: false
  14114. },
  14115. keyboard: {
  14116. enabled: false,
  14117. speed: {x: 10, y: 10, zoom: 0.02}
  14118. },
  14119. dataManipulation: {
  14120. enabled: false,
  14121. initiallyVisible: false
  14122. },
  14123. hierarchicalLayout: {
  14124. enabled:false,
  14125. levelSeparation: 150,
  14126. nodeSpacing: 100,
  14127. direction: "UD" // UD, DU, LR, RL
  14128. },
  14129. freezeForStabilization: false,
  14130. smoothCurves: true,
  14131. maxVelocity: 10,
  14132. minVelocity: 0.1, // px/s
  14133. stabilizationIterations: 1000 // maximum number of iteration to stabilize
  14134. };
  14135. this.editMode = this.constants.dataManipulation.initiallyVisible;
  14136. // Node variables
  14137. var graph = this;
  14138. this.groups = new Groups(); // object with groups
  14139. this.images = new Images(); // object with images
  14140. this.images.setOnloadCallback(function () {
  14141. graph._redraw();
  14142. });
  14143. // keyboard navigation variables
  14144. this.xIncrement = 0;
  14145. this.yIncrement = 0;
  14146. this.zoomIncrement = 0;
  14147. // loading all the mixins:
  14148. // load the force calculation functions, grouped under the physics system.
  14149. this._loadPhysicsSystem();
  14150. // create a frame and canvas
  14151. this._create();
  14152. // load the sector system. (mandatory, fully integrated with Graph)
  14153. this._loadSectorSystem();
  14154. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  14155. this._loadClusterSystem();
  14156. // load the selection system. (mandatory, required by Graph)
  14157. this._loadSelectionSystem();
  14158. // load the selection system. (mandatory, required by Graph)
  14159. this._loadHierarchySystem();
  14160. // apply options
  14161. this.setOptions(options);
  14162. // other vars
  14163. this.freezeSimulation = false;// freeze the simulation
  14164. this.cachedFunctions = {};
  14165. // containers for nodes and edges
  14166. this.calculationNodes = {};
  14167. this.calculationNodeIndices = [];
  14168. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  14169. this.nodes = {}; // object with Node objects
  14170. this.edges = {}; // object with Edge objects
  14171. // position and scale variables and objects
  14172. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  14173. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  14174. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  14175. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  14176. this.scale = 1; // defining the global scale variable in the constructor
  14177. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  14178. // datasets or dataviews
  14179. this.nodesData = null; // A DataSet or DataView
  14180. this.edgesData = null; // A DataSet or DataView
  14181. // create event listeners used to subscribe on the DataSets of the nodes and edges
  14182. this.nodesListeners = {
  14183. 'add': function (event, params) {
  14184. graph._addNodes(params.items);
  14185. graph.start();
  14186. },
  14187. 'update': function (event, params) {
  14188. graph._updateNodes(params.items);
  14189. graph.start();
  14190. },
  14191. 'remove': function (event, params) {
  14192. graph._removeNodes(params.items);
  14193. graph.start();
  14194. }
  14195. };
  14196. this.edgesListeners = {
  14197. 'add': function (event, params) {
  14198. graph._addEdges(params.items);
  14199. graph.start();
  14200. },
  14201. 'update': function (event, params) {
  14202. graph._updateEdges(params.items);
  14203. graph.start();
  14204. },
  14205. 'remove': function (event, params) {
  14206. graph._removeEdges(params.items);
  14207. graph.start();
  14208. }
  14209. };
  14210. // properties for the animation
  14211. this.moving = true;
  14212. this.timer = undefined; // Scheduling function. Is definded in this.start();
  14213. // load data (the disable start variable will be the same as the enabled clustering)
  14214. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  14215. // hierarchical layout
  14216. if (this.constants.hierarchicalLayout.enabled == true) {
  14217. this._setupHierarchicalLayout();
  14218. }
  14219. else {
  14220. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  14221. if (this.stabilize == false) {
  14222. this.zoomExtent(true,this.constants.clustering.enabled);
  14223. }
  14224. }
  14225. // if clustering is disabled, the simulation will have started in the setData function
  14226. if (this.constants.clustering.enabled) {
  14227. this.startWithClustering();
  14228. }
  14229. }
  14230. // Extend Graph with an Emitter mixin
  14231. Emitter(Graph.prototype);
  14232. /**
  14233. * Get the script path where the vis.js library is located
  14234. *
  14235. * @returns {string | null} path Path or null when not found. Path does not
  14236. * end with a slash.
  14237. * @private
  14238. */
  14239. Graph.prototype._getScriptPath = function() {
  14240. var scripts = document.getElementsByTagName( 'script' );
  14241. // find script named vis.js or vis.min.js
  14242. for (var i = 0; i < scripts.length; i++) {
  14243. var src = scripts[i].src;
  14244. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  14245. if (match) {
  14246. // return path without the script name
  14247. return src.substring(0, src.length - match[0].length);
  14248. }
  14249. }
  14250. return null;
  14251. };
  14252. /**
  14253. * Find the center position of the graph
  14254. * @private
  14255. */
  14256. Graph.prototype._getRange = function() {
  14257. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  14258. for (var nodeId in this.nodes) {
  14259. if (this.nodes.hasOwnProperty(nodeId)) {
  14260. node = this.nodes[nodeId];
  14261. if (minX > (node.x)) {minX = node.x;}
  14262. if (maxX < (node.x)) {maxX = node.x;}
  14263. if (minY > (node.y)) {minY = node.y;}
  14264. if (maxY < (node.y)) {maxY = node.y;}
  14265. }
  14266. }
  14267. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  14268. minY = 0, maxY = 0, minX = 0, maxX = 0;
  14269. }
  14270. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14271. };
  14272. /**
  14273. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14274. * @returns {{x: number, y: number}}
  14275. * @private
  14276. */
  14277. Graph.prototype._findCenter = function(range) {
  14278. return {x: (0.5 * (range.maxX + range.minX)),
  14279. y: (0.5 * (range.maxY + range.minY))};
  14280. };
  14281. /**
  14282. * center the graph
  14283. *
  14284. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14285. */
  14286. Graph.prototype._centerGraph = function(range) {
  14287. var center = this._findCenter(range);
  14288. center.x *= this.scale;
  14289. center.y *= this.scale;
  14290. center.x -= 0.5 * this.frame.canvas.clientWidth;
  14291. center.y -= 0.5 * this.frame.canvas.clientHeight;
  14292. this._setTranslation(-center.x,-center.y); // set at 0,0
  14293. };
  14294. /**
  14295. * This function zooms out to fit all data on screen based on amount of nodes
  14296. *
  14297. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  14298. */
  14299. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  14300. if (initialZoom === undefined) {
  14301. initialZoom = false;
  14302. }
  14303. if (disableStart === undefined) {
  14304. disableStart = false;
  14305. }
  14306. var range = this._getRange();
  14307. var zoomLevel;
  14308. if (initialZoom == true) {
  14309. var numberOfNodes = this.nodeIndices.length;
  14310. if (this.constants.smoothCurves == true) {
  14311. if (this.constants.clustering.enabled == true &&
  14312. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14313. 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.
  14314. }
  14315. else {
  14316. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14317. }
  14318. }
  14319. else {
  14320. if (this.constants.clustering.enabled == true &&
  14321. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14322. 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.
  14323. }
  14324. else {
  14325. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14326. }
  14327. }
  14328. // correct for larger canvasses.
  14329. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  14330. zoomLevel *= factor;
  14331. }
  14332. else {
  14333. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  14334. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  14335. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  14336. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  14337. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  14338. }
  14339. if (zoomLevel > 1.0) {
  14340. zoomLevel = 1.0;
  14341. }
  14342. this._setScale(zoomLevel);
  14343. this._centerGraph(range);
  14344. if (disableStart == false) {
  14345. this.moving = true;
  14346. this.start();
  14347. }
  14348. };
  14349. /**
  14350. * Update the this.nodeIndices with the most recent node index list
  14351. * @private
  14352. */
  14353. Graph.prototype._updateNodeIndexList = function() {
  14354. this._clearNodeIndexList();
  14355. for (var idx in this.nodes) {
  14356. if (this.nodes.hasOwnProperty(idx)) {
  14357. this.nodeIndices.push(idx);
  14358. }
  14359. }
  14360. };
  14361. /**
  14362. * Set nodes and edges, and optionally options as well.
  14363. *
  14364. * @param {Object} data Object containing parameters:
  14365. * {Array | DataSet | DataView} [nodes] Array with nodes
  14366. * {Array | DataSet | DataView} [edges] Array with edges
  14367. * {String} [dot] String containing data in DOT format
  14368. * {Options} [options] Object with options
  14369. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  14370. */
  14371. Graph.prototype.setData = function(data, disableStart) {
  14372. if (disableStart === undefined) {
  14373. disableStart = false;
  14374. }
  14375. if (data && data.dot && (data.nodes || data.edges)) {
  14376. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  14377. ' parameter pair "nodes" and "edges", but not both.');
  14378. }
  14379. // set options
  14380. this.setOptions(data && data.options);
  14381. // set all data
  14382. if (data && data.dot) {
  14383. // parse DOT file
  14384. if(data && data.dot) {
  14385. var dotData = vis.util.DOTToGraph(data.dot);
  14386. this.setData(dotData);
  14387. return;
  14388. }
  14389. }
  14390. else {
  14391. this._setNodes(data && data.nodes);
  14392. this._setEdges(data && data.edges);
  14393. }
  14394. this._putDataInSector();
  14395. if (!disableStart) {
  14396. // find a stable position or start animating to a stable position
  14397. if (this.stabilize) {
  14398. this._stabilize();
  14399. }
  14400. this.start();
  14401. }
  14402. };
  14403. /**
  14404. * Set options
  14405. * @param {Object} options
  14406. */
  14407. Graph.prototype.setOptions = function (options) {
  14408. if (options) {
  14409. var prop;
  14410. // retrieve parameter values
  14411. if (options.width !== undefined) {this.width = options.width;}
  14412. if (options.height !== undefined) {this.height = options.height;}
  14413. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14414. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14415. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14416. if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;}
  14417. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14418. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  14419. if (options.onAdd) {
  14420. this.triggerFunctions.add = options.onAdd;
  14421. }
  14422. if (options.onEdit) {
  14423. this.triggerFunctions.edit = options.onEdit;
  14424. }
  14425. if (options.onConnect) {
  14426. this.triggerFunctions.connect = options.onConnect;
  14427. }
  14428. if (options.onDelete) {
  14429. this.triggerFunctions.delete = options.onDelete;
  14430. }
  14431. if (options.physics) {
  14432. if (options.physics.barnesHut) {
  14433. this.constants.physics.barnesHut.enabled = true;
  14434. for (prop in options.physics.barnesHut) {
  14435. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14436. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14437. }
  14438. }
  14439. }
  14440. if (options.physics.repulsion) {
  14441. this.constants.physics.barnesHut.enabled = false;
  14442. for (prop in options.physics.repulsion) {
  14443. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14444. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14445. }
  14446. }
  14447. }
  14448. }
  14449. if (options.hierarchicalLayout) {
  14450. this.constants.hierarchicalLayout.enabled = true;
  14451. for (prop in options.hierarchicalLayout) {
  14452. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14453. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14454. }
  14455. }
  14456. }
  14457. else if (options.hierarchicalLayout !== undefined) {
  14458. this.constants.hierarchicalLayout.enabled = false;
  14459. }
  14460. if (options.clustering) {
  14461. this.constants.clustering.enabled = true;
  14462. for (prop in options.clustering) {
  14463. if (options.clustering.hasOwnProperty(prop)) {
  14464. this.constants.clustering[prop] = options.clustering[prop];
  14465. }
  14466. }
  14467. }
  14468. else if (options.clustering !== undefined) {
  14469. this.constants.clustering.enabled = false;
  14470. }
  14471. if (options.navigation) {
  14472. this.constants.navigation.enabled = true;
  14473. for (prop in options.navigation) {
  14474. if (options.navigation.hasOwnProperty(prop)) {
  14475. this.constants.navigation[prop] = options.navigation[prop];
  14476. }
  14477. }
  14478. }
  14479. else if (options.navigation !== undefined) {
  14480. this.constants.navigation.enabled = false;
  14481. }
  14482. if (options.keyboard) {
  14483. this.constants.keyboard.enabled = true;
  14484. for (prop in options.keyboard) {
  14485. if (options.keyboard.hasOwnProperty(prop)) {
  14486. this.constants.keyboard[prop] = options.keyboard[prop];
  14487. }
  14488. }
  14489. }
  14490. else if (options.keyboard !== undefined) {
  14491. this.constants.keyboard.enabled = false;
  14492. }
  14493. if (options.dataManipulation) {
  14494. this.constants.dataManipulation.enabled = true;
  14495. for (prop in options.dataManipulation) {
  14496. if (options.dataManipulation.hasOwnProperty(prop)) {
  14497. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14498. }
  14499. }
  14500. }
  14501. else if (options.dataManipulation !== undefined) {
  14502. this.constants.dataManipulation.enabled = false;
  14503. }
  14504. // TODO: work out these options and document them
  14505. if (options.edges) {
  14506. for (prop in options.edges) {
  14507. if (options.edges.hasOwnProperty(prop)) {
  14508. if (typeof options.edges[prop] != "object") {
  14509. this.constants.edges[prop] = options.edges[prop];
  14510. }
  14511. }
  14512. }
  14513. if (options.edges.color !== undefined) {
  14514. if (util.isString(options.edges.color)) {
  14515. this.constants.edges.color.color = options.edges.color;
  14516. this.constants.edges.color.highlight = options.edges.color;
  14517. }
  14518. else {
  14519. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  14520. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  14521. }
  14522. }
  14523. if (!options.edges.fontColor) {
  14524. if (options.edges.color !== undefined) {
  14525. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  14526. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  14527. }
  14528. }
  14529. // Added to support dashed lines
  14530. // David Jordan
  14531. // 2012-08-08
  14532. if (options.edges.dash) {
  14533. if (options.edges.dash.length !== undefined) {
  14534. this.constants.edges.dash.length = options.edges.dash.length;
  14535. }
  14536. if (options.edges.dash.gap !== undefined) {
  14537. this.constants.edges.dash.gap = options.edges.dash.gap;
  14538. }
  14539. if (options.edges.dash.altLength !== undefined) {
  14540. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14541. }
  14542. }
  14543. }
  14544. if (options.nodes) {
  14545. for (prop in options.nodes) {
  14546. if (options.nodes.hasOwnProperty(prop)) {
  14547. this.constants.nodes[prop] = options.nodes[prop];
  14548. }
  14549. }
  14550. if (options.nodes.color) {
  14551. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  14552. }
  14553. /*
  14554. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14555. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14556. */
  14557. }
  14558. if (options.groups) {
  14559. for (var groupname in options.groups) {
  14560. if (options.groups.hasOwnProperty(groupname)) {
  14561. var group = options.groups[groupname];
  14562. this.groups.add(groupname, group);
  14563. }
  14564. }
  14565. }
  14566. }
  14567. // (Re)loading the mixins that can be enabled or disabled in the options.
  14568. // load the force calculation functions, grouped under the physics system.
  14569. this._loadPhysicsSystem();
  14570. // load the navigation system.
  14571. this._loadNavigationControls();
  14572. // load the data manipulation system
  14573. this._loadManipulationSystem();
  14574. // configure the smooth curves
  14575. this._configureSmoothCurves();
  14576. // bind keys. If disabled, this will not do anything;
  14577. this._createKeyBinds();
  14578. this.setSize(this.width, this.height);
  14579. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14580. this._setScale(1);
  14581. this._redraw();
  14582. };
  14583. /**
  14584. * Create the main frame for the Graph.
  14585. * This function is executed once when a Graph object is created. The frame
  14586. * contains a canvas, and this canvas contains all objects like the axis and
  14587. * nodes.
  14588. * @private
  14589. */
  14590. Graph.prototype._create = function () {
  14591. // remove all elements from the container element.
  14592. while (this.containerElement.hasChildNodes()) {
  14593. this.containerElement.removeChild(this.containerElement.firstChild);
  14594. }
  14595. this.frame = document.createElement('div');
  14596. this.frame.className = 'graph-frame';
  14597. this.frame.style.position = 'relative';
  14598. this.frame.style.overflow = 'hidden';
  14599. this.frame.style.zIndex = "1";
  14600. // create the graph canvas (HTML canvas element)
  14601. this.frame.canvas = document.createElement( 'canvas' );
  14602. this.frame.canvas.style.position = 'relative';
  14603. this.frame.appendChild(this.frame.canvas);
  14604. if (!this.frame.canvas.getContext) {
  14605. var noCanvas = document.createElement( 'DIV' );
  14606. noCanvas.style.color = 'red';
  14607. noCanvas.style.fontWeight = 'bold' ;
  14608. noCanvas.style.padding = '10px';
  14609. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14610. this.frame.canvas.appendChild(noCanvas);
  14611. }
  14612. var me = this;
  14613. this.drag = {};
  14614. this.pinch = {};
  14615. this.hammer = Hammer(this.frame.canvas, {
  14616. prevent_default: true
  14617. });
  14618. this.hammer.on('tap', me._onTap.bind(me) );
  14619. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14620. this.hammer.on('hold', me._onHold.bind(me) );
  14621. this.hammer.on('pinch', me._onPinch.bind(me) );
  14622. this.hammer.on('touch', me._onTouch.bind(me) );
  14623. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14624. this.hammer.on('drag', me._onDrag.bind(me) );
  14625. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14626. this.hammer.on('release', me._onRelease.bind(me) );
  14627. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14628. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14629. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14630. // add the frame to the container element
  14631. this.containerElement.appendChild(this.frame);
  14632. };
  14633. /**
  14634. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14635. * @private
  14636. */
  14637. Graph.prototype._createKeyBinds = function() {
  14638. var me = this;
  14639. this.mousetrap = mousetrap;
  14640. this.mousetrap.reset();
  14641. if (this.constants.keyboard.enabled == true) {
  14642. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14643. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14644. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14645. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14646. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14647. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14648. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14649. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14650. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14651. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14652. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14653. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14654. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14655. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14656. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14657. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14658. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14659. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14660. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14661. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14662. }
  14663. if (this.constants.dataManipulation.enabled == true) {
  14664. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14665. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14666. }
  14667. };
  14668. /**
  14669. * Get the pointer location from a touch location
  14670. * @param {{pageX: Number, pageY: Number}} touch
  14671. * @return {{x: Number, y: Number}} pointer
  14672. * @private
  14673. */
  14674. Graph.prototype._getPointer = function (touch) {
  14675. return {
  14676. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14677. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14678. };
  14679. };
  14680. /**
  14681. * On start of a touch gesture, store the pointer
  14682. * @param event
  14683. * @private
  14684. */
  14685. Graph.prototype._onTouch = function (event) {
  14686. this.drag.pointer = this._getPointer(event.gesture.center);
  14687. this.drag.pinched = false;
  14688. this.pinch.scale = this._getScale();
  14689. this._handleTouch(this.drag.pointer);
  14690. };
  14691. /**
  14692. * handle drag start event
  14693. * @private
  14694. */
  14695. Graph.prototype._onDragStart = function () {
  14696. this._handleDragStart();
  14697. };
  14698. /**
  14699. * This function is called by _onDragStart.
  14700. * It is separated out because we can then overload it for the datamanipulation system.
  14701. *
  14702. * @private
  14703. */
  14704. Graph.prototype._handleDragStart = function() {
  14705. var drag = this.drag;
  14706. var node = this._getNodeAt(drag.pointer);
  14707. // note: drag.pointer is set in _onTouch to get the initial touch location
  14708. drag.dragging = true;
  14709. drag.selection = [];
  14710. drag.translation = this._getTranslation();
  14711. drag.nodeId = null;
  14712. if (node != null) {
  14713. drag.nodeId = node.id;
  14714. // select the clicked node if not yet selected
  14715. if (!node.isSelected()) {
  14716. this._selectObject(node,false);
  14717. }
  14718. // create an array with the selected nodes and their original location and status
  14719. for (var objectId in this.selectionObj.nodes) {
  14720. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  14721. var object = this.selectionObj.nodes[objectId];
  14722. var s = {
  14723. id: object.id,
  14724. node: object,
  14725. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14726. x: object.x,
  14727. y: object.y,
  14728. xFixed: object.xFixed,
  14729. yFixed: object.yFixed
  14730. };
  14731. object.xFixed = true;
  14732. object.yFixed = true;
  14733. drag.selection.push(s);
  14734. }
  14735. }
  14736. }
  14737. };
  14738. /**
  14739. * handle drag event
  14740. * @private
  14741. */
  14742. Graph.prototype._onDrag = function (event) {
  14743. this._handleOnDrag(event)
  14744. };
  14745. /**
  14746. * This function is called by _onDrag.
  14747. * It is separated out because we can then overload it for the datamanipulation system.
  14748. *
  14749. * @private
  14750. */
  14751. Graph.prototype._handleOnDrag = function(event) {
  14752. if (this.drag.pinched) {
  14753. return;
  14754. }
  14755. var pointer = this._getPointer(event.gesture.center);
  14756. var me = this,
  14757. drag = this.drag,
  14758. selection = drag.selection;
  14759. if (selection && selection.length) {
  14760. // calculate delta's and new location
  14761. var deltaX = pointer.x - drag.pointer.x,
  14762. deltaY = pointer.y - drag.pointer.y;
  14763. // update position of all selected nodes
  14764. selection.forEach(function (s) {
  14765. var node = s.node;
  14766. if (!s.xFixed) {
  14767. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14768. }
  14769. if (!s.yFixed) {
  14770. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14771. }
  14772. });
  14773. // start _animationStep if not yet running
  14774. if (!this.moving) {
  14775. this.moving = true;
  14776. this.start();
  14777. }
  14778. }
  14779. else {
  14780. // move the graph
  14781. var diffX = pointer.x - this.drag.pointer.x;
  14782. var diffY = pointer.y - this.drag.pointer.y;
  14783. this._setTranslation(
  14784. this.drag.translation.x + diffX,
  14785. this.drag.translation.y + diffY);
  14786. this._redraw();
  14787. this.moved = true;
  14788. }
  14789. };
  14790. /**
  14791. * handle drag start event
  14792. * @private
  14793. */
  14794. Graph.prototype._onDragEnd = function () {
  14795. this.drag.dragging = false;
  14796. var selection = this.drag.selection;
  14797. if (selection) {
  14798. selection.forEach(function (s) {
  14799. // restore original xFixed and yFixed
  14800. s.node.xFixed = s.xFixed;
  14801. s.node.yFixed = s.yFixed;
  14802. });
  14803. }
  14804. };
  14805. /**
  14806. * handle tap/click event: select/unselect a node
  14807. * @private
  14808. */
  14809. Graph.prototype._onTap = function (event) {
  14810. var pointer = this._getPointer(event.gesture.center);
  14811. this.pointerPosition = pointer;
  14812. this._handleTap(pointer);
  14813. };
  14814. /**
  14815. * handle doubletap event
  14816. * @private
  14817. */
  14818. Graph.prototype._onDoubleTap = function (event) {
  14819. var pointer = this._getPointer(event.gesture.center);
  14820. this._handleDoubleTap(pointer);
  14821. };
  14822. /**
  14823. * handle long tap event: multi select nodes
  14824. * @private
  14825. */
  14826. Graph.prototype._onHold = function (event) {
  14827. var pointer = this._getPointer(event.gesture.center);
  14828. this.pointerPosition = pointer;
  14829. this._handleOnHold(pointer);
  14830. };
  14831. /**
  14832. * handle the release of the screen
  14833. *
  14834. * @private
  14835. */
  14836. Graph.prototype._onRelease = function (event) {
  14837. var pointer = this._getPointer(event.gesture.center);
  14838. this._handleOnRelease(pointer);
  14839. };
  14840. /**
  14841. * Handle pinch event
  14842. * @param event
  14843. * @private
  14844. */
  14845. Graph.prototype._onPinch = function (event) {
  14846. var pointer = this._getPointer(event.gesture.center);
  14847. this.drag.pinched = true;
  14848. if (!('scale' in this.pinch)) {
  14849. this.pinch.scale = 1;
  14850. }
  14851. // TODO: enabled moving while pinching?
  14852. var scale = this.pinch.scale * event.gesture.scale;
  14853. this._zoom(scale, pointer)
  14854. };
  14855. /**
  14856. * Zoom the graph in or out
  14857. * @param {Number} scale a number around 1, and between 0.01 and 10
  14858. * @param {{x: Number, y: Number}} pointer Position on screen
  14859. * @return {Number} appliedScale scale is limited within the boundaries
  14860. * @private
  14861. */
  14862. Graph.prototype._zoom = function(scale, pointer) {
  14863. var scaleOld = this._getScale();
  14864. if (scale < 0.00001) {
  14865. scale = 0.00001;
  14866. }
  14867. if (scale > 10) {
  14868. scale = 10;
  14869. }
  14870. // + this.frame.canvas.clientHeight / 2
  14871. var translation = this._getTranslation();
  14872. var scaleFrac = scale / scaleOld;
  14873. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14874. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14875. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  14876. "y" : this._canvasToY(pointer.y)};
  14877. this._setScale(scale);
  14878. this._setTranslation(tx, ty);
  14879. this.updateClustersDefault();
  14880. this._redraw();
  14881. return scale;
  14882. };
  14883. /**
  14884. * Event handler for mouse wheel event, used to zoom the timeline
  14885. * See http://adomas.org/javascript-mouse-wheel/
  14886. * https://github.com/EightMedia/hammer.js/issues/256
  14887. * @param {MouseEvent} event
  14888. * @private
  14889. */
  14890. Graph.prototype._onMouseWheel = function(event) {
  14891. // retrieve delta
  14892. var delta = 0;
  14893. if (event.wheelDelta) { /* IE/Opera. */
  14894. delta = event.wheelDelta/120;
  14895. } else if (event.detail) { /* Mozilla case. */
  14896. // In Mozilla, sign of delta is different than in IE.
  14897. // Also, delta is multiple of 3.
  14898. delta = -event.detail/3;
  14899. }
  14900. // If delta is nonzero, handle it.
  14901. // Basically, delta is now positive if wheel was scrolled up,
  14902. // and negative, if wheel was scrolled down.
  14903. if (delta) {
  14904. // calculate the new scale
  14905. var scale = this._getScale();
  14906. var zoom = delta / 10;
  14907. if (delta < 0) {
  14908. zoom = zoom / (1 - zoom);
  14909. }
  14910. scale *= (1 + zoom);
  14911. // calculate the pointer location
  14912. var gesture = util.fakeGesture(this, event);
  14913. var pointer = this._getPointer(gesture.center);
  14914. // apply the new scale
  14915. this._zoom(scale, pointer);
  14916. }
  14917. // Prevent default actions caused by mouse wheel.
  14918. event.preventDefault();
  14919. };
  14920. /**
  14921. * Mouse move handler for checking whether the title moves over a node with a title.
  14922. * @param {Event} event
  14923. * @private
  14924. */
  14925. Graph.prototype._onMouseMoveTitle = function (event) {
  14926. var gesture = util.fakeGesture(this, event);
  14927. var pointer = this._getPointer(gesture.center);
  14928. // check if the previously selected node is still selected
  14929. if (this.popupNode) {
  14930. this._checkHidePopup(pointer);
  14931. }
  14932. // start a timeout that will check if the mouse is positioned above
  14933. // an element
  14934. var me = this;
  14935. var checkShow = function() {
  14936. me._checkShowPopup(pointer);
  14937. };
  14938. if (this.popupTimer) {
  14939. clearInterval(this.popupTimer); // stop any running calculationTimer
  14940. }
  14941. if (!this.drag.dragging) {
  14942. this.popupTimer = setTimeout(checkShow, 300);
  14943. }
  14944. };
  14945. /**
  14946. * Check if there is an element on the given position in the graph
  14947. * (a node or edge). If so, and if this element has a title,
  14948. * show a popup window with its title.
  14949. *
  14950. * @param {{x:Number, y:Number}} pointer
  14951. * @private
  14952. */
  14953. Graph.prototype._checkShowPopup = function (pointer) {
  14954. var obj = {
  14955. left: this._canvasToX(pointer.x),
  14956. top: this._canvasToY(pointer.y),
  14957. right: this._canvasToX(pointer.x),
  14958. bottom: this._canvasToY(pointer.y)
  14959. };
  14960. var id;
  14961. var lastPopupNode = this.popupNode;
  14962. if (this.popupNode == undefined) {
  14963. // search the nodes for overlap, select the top one in case of multiple nodes
  14964. var nodes = this.nodes;
  14965. for (id in nodes) {
  14966. if (nodes.hasOwnProperty(id)) {
  14967. var node = nodes[id];
  14968. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14969. this.popupNode = node;
  14970. break;
  14971. }
  14972. }
  14973. }
  14974. }
  14975. if (this.popupNode === undefined) {
  14976. // search the edges for overlap
  14977. var edges = this.edges;
  14978. for (id in edges) {
  14979. if (edges.hasOwnProperty(id)) {
  14980. var edge = edges[id];
  14981. if (edge.connected && (edge.getTitle() !== undefined) &&
  14982. edge.isOverlappingWith(obj)) {
  14983. this.popupNode = edge;
  14984. break;
  14985. }
  14986. }
  14987. }
  14988. }
  14989. if (this.popupNode) {
  14990. // show popup message window
  14991. if (this.popupNode != lastPopupNode) {
  14992. var me = this;
  14993. if (!me.popup) {
  14994. me.popup = new Popup(me.frame);
  14995. }
  14996. // adjust a small offset such that the mouse cursor is located in the
  14997. // bottom left location of the popup, and you can easily move over the
  14998. // popup area
  14999. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  15000. me.popup.setText(me.popupNode.getTitle());
  15001. me.popup.show();
  15002. }
  15003. }
  15004. else {
  15005. if (this.popup) {
  15006. this.popup.hide();
  15007. }
  15008. }
  15009. };
  15010. /**
  15011. * Check if the popup must be hided, which is the case when the mouse is no
  15012. * longer hovering on the object
  15013. * @param {{x:Number, y:Number}} pointer
  15014. * @private
  15015. */
  15016. Graph.prototype._checkHidePopup = function (pointer) {
  15017. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  15018. this.popupNode = undefined;
  15019. if (this.popup) {
  15020. this.popup.hide();
  15021. }
  15022. }
  15023. };
  15024. /**
  15025. * Set a new size for the graph
  15026. * @param {string} width Width in pixels or percentage (for example '800px'
  15027. * or '50%')
  15028. * @param {string} height Height in pixels or percentage (for example '400px'
  15029. * or '30%')
  15030. */
  15031. Graph.prototype.setSize = function(width, height) {
  15032. this.frame.style.width = width;
  15033. this.frame.style.height = height;
  15034. this.frame.canvas.style.width = '100%';
  15035. this.frame.canvas.style.height = '100%';
  15036. this.frame.canvas.width = this.frame.canvas.clientWidth;
  15037. this.frame.canvas.height = this.frame.canvas.clientHeight;
  15038. if (this.manipulationDiv !== undefined) {
  15039. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  15040. }
  15041. if (this.navigationDivs !== undefined) {
  15042. if (this.navigationDivs['wrapper'] !== undefined) {
  15043. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  15044. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  15045. }
  15046. }
  15047. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  15048. };
  15049. /**
  15050. * Set a data set with nodes for the graph
  15051. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  15052. * @private
  15053. */
  15054. Graph.prototype._setNodes = function(nodes) {
  15055. var oldNodesData = this.nodesData;
  15056. if (nodes instanceof DataSet || nodes instanceof DataView) {
  15057. this.nodesData = nodes;
  15058. }
  15059. else if (nodes instanceof Array) {
  15060. this.nodesData = new DataSet();
  15061. this.nodesData.add(nodes);
  15062. }
  15063. else if (!nodes) {
  15064. this.nodesData = new DataSet();
  15065. }
  15066. else {
  15067. throw new TypeError('Array or DataSet expected');
  15068. }
  15069. if (oldNodesData) {
  15070. // unsubscribe from old dataset
  15071. util.forEach(this.nodesListeners, function (callback, event) {
  15072. oldNodesData.off(event, callback);
  15073. });
  15074. }
  15075. // remove drawn nodes
  15076. this.nodes = {};
  15077. if (this.nodesData) {
  15078. // subscribe to new dataset
  15079. var me = this;
  15080. util.forEach(this.nodesListeners, function (callback, event) {
  15081. me.nodesData.on(event, callback);
  15082. });
  15083. // draw all new nodes
  15084. var ids = this.nodesData.getIds();
  15085. this._addNodes(ids);
  15086. }
  15087. this._updateSelection();
  15088. };
  15089. /**
  15090. * Add nodes
  15091. * @param {Number[] | String[]} ids
  15092. * @private
  15093. */
  15094. Graph.prototype._addNodes = function(ids) {
  15095. var id;
  15096. for (var i = 0, len = ids.length; i < len; i++) {
  15097. id = ids[i];
  15098. var data = this.nodesData.get(id);
  15099. var node = new Node(data, this.images, this.groups, this.constants);
  15100. this.nodes[id] = node; // note: this may replace an existing node
  15101. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  15102. var radius = 10 * 0.1*ids.length;
  15103. var angle = 2 * Math.PI * Math.random();
  15104. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  15105. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  15106. }
  15107. this.moving = true;
  15108. }
  15109. this._updateNodeIndexList();
  15110. this._updateCalculationNodes();
  15111. this._reconnectEdges();
  15112. this._updateValueRange(this.nodes);
  15113. this.updateLabels();
  15114. };
  15115. /**
  15116. * Update existing nodes, or create them when not yet existing
  15117. * @param {Number[] | String[]} ids
  15118. * @private
  15119. */
  15120. Graph.prototype._updateNodes = function(ids) {
  15121. var nodes = this.nodes,
  15122. nodesData = this.nodesData;
  15123. for (var i = 0, len = ids.length; i < len; i++) {
  15124. var id = ids[i];
  15125. var node = nodes[id];
  15126. var data = nodesData.get(id);
  15127. if (node) {
  15128. // update node
  15129. node.setProperties(data, this.constants);
  15130. }
  15131. else {
  15132. // create node
  15133. node = new Node(properties, this.images, this.groups, this.constants);
  15134. nodes[id] = node;
  15135. if (!node.isFixed()) {
  15136. this.moving = true;
  15137. }
  15138. }
  15139. }
  15140. this._updateNodeIndexList();
  15141. this._reconnectEdges();
  15142. this._updateValueRange(nodes);
  15143. };
  15144. /**
  15145. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  15146. * @param {Number[] | String[]} ids
  15147. * @private
  15148. */
  15149. Graph.prototype._removeNodes = function(ids) {
  15150. var nodes = this.nodes;
  15151. for (var i = 0, len = ids.length; i < len; i++) {
  15152. var id = ids[i];
  15153. delete nodes[id];
  15154. }
  15155. this._updateNodeIndexList();
  15156. this._updateCalculationNodes();
  15157. this._reconnectEdges();
  15158. this._updateSelection();
  15159. this._updateValueRange(nodes);
  15160. };
  15161. /**
  15162. * Load edges by reading the data table
  15163. * @param {Array | DataSet | DataView} edges The data containing the edges.
  15164. * @private
  15165. * @private
  15166. */
  15167. Graph.prototype._setEdges = function(edges) {
  15168. var oldEdgesData = this.edgesData;
  15169. if (edges instanceof DataSet || edges instanceof DataView) {
  15170. this.edgesData = edges;
  15171. }
  15172. else if (edges instanceof Array) {
  15173. this.edgesData = new DataSet();
  15174. this.edgesData.add(edges);
  15175. }
  15176. else if (!edges) {
  15177. this.edgesData = new DataSet();
  15178. }
  15179. else {
  15180. throw new TypeError('Array or DataSet expected');
  15181. }
  15182. if (oldEdgesData) {
  15183. // unsubscribe from old dataset
  15184. util.forEach(this.edgesListeners, function (callback, event) {
  15185. oldEdgesData.off(event, callback);
  15186. });
  15187. }
  15188. // remove drawn edges
  15189. this.edges = {};
  15190. if (this.edgesData) {
  15191. // subscribe to new dataset
  15192. var me = this;
  15193. util.forEach(this.edgesListeners, function (callback, event) {
  15194. me.edgesData.on(event, callback);
  15195. });
  15196. // draw all new nodes
  15197. var ids = this.edgesData.getIds();
  15198. this._addEdges(ids);
  15199. }
  15200. this._reconnectEdges();
  15201. };
  15202. /**
  15203. * Add edges
  15204. * @param {Number[] | String[]} ids
  15205. * @private
  15206. */
  15207. Graph.prototype._addEdges = function (ids) {
  15208. var edges = this.edges,
  15209. edgesData = this.edgesData;
  15210. for (var i = 0, len = ids.length; i < len; i++) {
  15211. var id = ids[i];
  15212. var oldEdge = edges[id];
  15213. if (oldEdge) {
  15214. oldEdge.disconnect();
  15215. }
  15216. var data = edgesData.get(id, {"showInternalIds" : true});
  15217. edges[id] = new Edge(data, this, this.constants);
  15218. }
  15219. this.moving = true;
  15220. this._updateValueRange(edges);
  15221. this._createBezierNodes();
  15222. this._updateCalculationNodes();
  15223. };
  15224. /**
  15225. * Update existing edges, or create them when not yet existing
  15226. * @param {Number[] | String[]} ids
  15227. * @private
  15228. */
  15229. Graph.prototype._updateEdges = function (ids) {
  15230. var edges = this.edges,
  15231. edgesData = this.edgesData;
  15232. for (var i = 0, len = ids.length; i < len; i++) {
  15233. var id = ids[i];
  15234. var data = edgesData.get(id);
  15235. var edge = edges[id];
  15236. if (edge) {
  15237. // update edge
  15238. edge.disconnect();
  15239. edge.setProperties(data, this.constants);
  15240. edge.connect();
  15241. }
  15242. else {
  15243. // create edge
  15244. edge = new Edge(data, this, this.constants);
  15245. this.edges[id] = edge;
  15246. }
  15247. }
  15248. this._createBezierNodes();
  15249. this.moving = true;
  15250. this._updateValueRange(edges);
  15251. };
  15252. /**
  15253. * Remove existing edges. Non existing ids will be ignored
  15254. * @param {Number[] | String[]} ids
  15255. * @private
  15256. */
  15257. Graph.prototype._removeEdges = function (ids) {
  15258. var edges = this.edges;
  15259. for (var i = 0, len = ids.length; i < len; i++) {
  15260. var id = ids[i];
  15261. var edge = edges[id];
  15262. if (edge) {
  15263. if (edge.via != null) {
  15264. delete this.sectors['support']['nodes'][edge.via.id];
  15265. }
  15266. edge.disconnect();
  15267. delete edges[id];
  15268. }
  15269. }
  15270. this.moving = true;
  15271. this._updateValueRange(edges);
  15272. this._updateCalculationNodes();
  15273. };
  15274. /**
  15275. * Reconnect all edges
  15276. * @private
  15277. */
  15278. Graph.prototype._reconnectEdges = function() {
  15279. var id,
  15280. nodes = this.nodes,
  15281. edges = this.edges;
  15282. for (id in nodes) {
  15283. if (nodes.hasOwnProperty(id)) {
  15284. nodes[id].edges = [];
  15285. }
  15286. }
  15287. for (id in edges) {
  15288. if (edges.hasOwnProperty(id)) {
  15289. var edge = edges[id];
  15290. edge.from = null;
  15291. edge.to = null;
  15292. edge.connect();
  15293. }
  15294. }
  15295. };
  15296. /**
  15297. * Update the values of all object in the given array according to the current
  15298. * value range of the objects in the array.
  15299. * @param {Object} obj An object containing a set of Edges or Nodes
  15300. * The objects must have a method getValue() and
  15301. * setValueRange(min, max).
  15302. * @private
  15303. */
  15304. Graph.prototype._updateValueRange = function(obj) {
  15305. var id;
  15306. // determine the range of the objects
  15307. var valueMin = undefined;
  15308. var valueMax = undefined;
  15309. for (id in obj) {
  15310. if (obj.hasOwnProperty(id)) {
  15311. var value = obj[id].getValue();
  15312. if (value !== undefined) {
  15313. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  15314. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  15315. }
  15316. }
  15317. }
  15318. // adjust the range of all objects
  15319. if (valueMin !== undefined && valueMax !== undefined) {
  15320. for (id in obj) {
  15321. if (obj.hasOwnProperty(id)) {
  15322. obj[id].setValueRange(valueMin, valueMax);
  15323. }
  15324. }
  15325. }
  15326. };
  15327. /**
  15328. * Redraw the graph with the current data
  15329. * chart will be resized too.
  15330. */
  15331. Graph.prototype.redraw = function() {
  15332. this.setSize(this.width, this.height);
  15333. this._redraw();
  15334. };
  15335. /**
  15336. * Redraw the graph with the current data
  15337. * @private
  15338. */
  15339. Graph.prototype._redraw = function() {
  15340. var ctx = this.frame.canvas.getContext('2d');
  15341. // clear the canvas
  15342. var w = this.frame.canvas.width;
  15343. var h = this.frame.canvas.height;
  15344. ctx.clearRect(0, 0, w, h);
  15345. // set scaling and translation
  15346. ctx.save();
  15347. ctx.translate(this.translation.x, this.translation.y);
  15348. ctx.scale(this.scale, this.scale);
  15349. this.canvasTopLeft = {
  15350. "x": this._canvasToX(0),
  15351. "y": this._canvasToY(0)
  15352. };
  15353. this.canvasBottomRight = {
  15354. "x": this._canvasToX(this.frame.canvas.clientWidth),
  15355. "y": this._canvasToY(this.frame.canvas.clientHeight)
  15356. };
  15357. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15358. this._doInAllSectors("_drawEdges",ctx);
  15359. this._doInAllSectors("_drawNodes",ctx,false);
  15360. // this._doInSupportSector("_drawNodes",ctx,true);
  15361. // this._drawTree(ctx,"#F00F0F");
  15362. // restore original scaling and translation
  15363. ctx.restore();
  15364. };
  15365. /**
  15366. * Set the translation of the graph
  15367. * @param {Number} offsetX Horizontal offset
  15368. * @param {Number} offsetY Vertical offset
  15369. * @private
  15370. */
  15371. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15372. if (this.translation === undefined) {
  15373. this.translation = {
  15374. x: 0,
  15375. y: 0
  15376. };
  15377. }
  15378. if (offsetX !== undefined) {
  15379. this.translation.x = offsetX;
  15380. }
  15381. if (offsetY !== undefined) {
  15382. this.translation.y = offsetY;
  15383. }
  15384. };
  15385. /**
  15386. * Get the translation of the graph
  15387. * @return {Object} translation An object with parameters x and y, both a number
  15388. * @private
  15389. */
  15390. Graph.prototype._getTranslation = function() {
  15391. return {
  15392. x: this.translation.x,
  15393. y: this.translation.y
  15394. };
  15395. };
  15396. /**
  15397. * Scale the graph
  15398. * @param {Number} scale Scaling factor 1.0 is unscaled
  15399. * @private
  15400. */
  15401. Graph.prototype._setScale = function(scale) {
  15402. this.scale = scale;
  15403. };
  15404. /**
  15405. * Get the current scale of the graph
  15406. * @return {Number} scale Scaling factor 1.0 is unscaled
  15407. * @private
  15408. */
  15409. Graph.prototype._getScale = function() {
  15410. return this.scale;
  15411. };
  15412. /**
  15413. * Convert a horizontal point on the HTML canvas to the x-value of the model
  15414. * @param {number} x
  15415. * @returns {number}
  15416. * @private
  15417. */
  15418. Graph.prototype._canvasToX = function(x) {
  15419. return (x - this.translation.x) / this.scale;
  15420. };
  15421. /**
  15422. * Convert an x-value in the model to a horizontal point on the HTML canvas
  15423. * @param {number} x
  15424. * @returns {number}
  15425. * @private
  15426. */
  15427. Graph.prototype._xToCanvas = function(x) {
  15428. return x * this.scale + this.translation.x;
  15429. };
  15430. /**
  15431. * Convert a vertical point on the HTML canvas to the y-value of the model
  15432. * @param {number} y
  15433. * @returns {number}
  15434. * @private
  15435. */
  15436. Graph.prototype._canvasToY = function(y) {
  15437. return (y - this.translation.y) / this.scale;
  15438. };
  15439. /**
  15440. * Convert an y-value in the model to a vertical point on the HTML canvas
  15441. * @param {number} y
  15442. * @returns {number}
  15443. * @private
  15444. */
  15445. Graph.prototype._yToCanvas = function(y) {
  15446. return y * this.scale + this.translation.y ;
  15447. };
  15448. /**
  15449. * Redraw all nodes
  15450. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15451. * @param {CanvasRenderingContext2D} ctx
  15452. * @param {Boolean} [alwaysShow]
  15453. * @private
  15454. */
  15455. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  15456. if (alwaysShow === undefined) {
  15457. alwaysShow = false;
  15458. }
  15459. // first draw the unselected nodes
  15460. var nodes = this.nodes;
  15461. var selected = [];
  15462. for (var id in nodes) {
  15463. if (nodes.hasOwnProperty(id)) {
  15464. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15465. if (nodes[id].isSelected()) {
  15466. selected.push(id);
  15467. }
  15468. else {
  15469. if (nodes[id].inArea() || alwaysShow) {
  15470. nodes[id].draw(ctx);
  15471. }
  15472. }
  15473. }
  15474. }
  15475. // draw the selected nodes on top
  15476. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15477. if (nodes[selected[s]].inArea() || alwaysShow) {
  15478. nodes[selected[s]].draw(ctx);
  15479. }
  15480. }
  15481. };
  15482. /**
  15483. * Redraw all edges
  15484. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15485. * @param {CanvasRenderingContext2D} ctx
  15486. * @private
  15487. */
  15488. Graph.prototype._drawEdges = function(ctx) {
  15489. var edges = this.edges;
  15490. for (var id in edges) {
  15491. if (edges.hasOwnProperty(id)) {
  15492. var edge = edges[id];
  15493. edge.setScale(this.scale);
  15494. if (edge.connected) {
  15495. edges[id].draw(ctx);
  15496. }
  15497. }
  15498. }
  15499. };
  15500. /**
  15501. * Find a stable position for all nodes
  15502. * @private
  15503. */
  15504. Graph.prototype._stabilize = function() {
  15505. if (this.constants.freezeForStabilization == true) {
  15506. this._freezeDefinedNodes();
  15507. }
  15508. // find stable position
  15509. var count = 0;
  15510. while (this.moving && count < this.constants.stabilizationIterations) {
  15511. this._physicsTick();
  15512. count++;
  15513. }
  15514. this.zoomExtent(false,true);
  15515. if (this.constants.freezeForStabilization == true) {
  15516. this._restoreFrozenNodes();
  15517. }
  15518. this.emit("stabilized",{iterations:count});
  15519. };
  15520. Graph.prototype._freezeDefinedNodes = function() {
  15521. var nodes = this.nodes;
  15522. for (var id in nodes) {
  15523. if (nodes.hasOwnProperty(id)) {
  15524. if (nodes[id].x != null && nodes[id].y != null) {
  15525. nodes[id].fixedData.x = nodes[id].xFixed;
  15526. nodes[id].fixedData.y = nodes[id].yFixed;
  15527. nodes[id].xFixed = true;
  15528. nodes[id].yFixed = true;
  15529. }
  15530. }
  15531. }
  15532. };
  15533. Graph.prototype._restoreFrozenNodes = function() {
  15534. var nodes = this.nodes;
  15535. for (var id in nodes) {
  15536. if (nodes.hasOwnProperty(id)) {
  15537. if (nodes[id].fixedData.x != null) {
  15538. nodes[id].xFixed = nodes[id].fixedData.x;
  15539. nodes[id].yFixed = nodes[id].fixedData.y;
  15540. }
  15541. }
  15542. }
  15543. };
  15544. /**
  15545. * Check if any of the nodes is still moving
  15546. * @param {number} vmin the minimum velocity considered as 'moving'
  15547. * @return {boolean} true if moving, false if non of the nodes is moving
  15548. * @private
  15549. */
  15550. Graph.prototype._isMoving = function(vmin) {
  15551. var nodes = this.nodes;
  15552. for (var id in nodes) {
  15553. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15554. return true;
  15555. }
  15556. }
  15557. return false;
  15558. };
  15559. /**
  15560. * /**
  15561. * Perform one discrete step for all nodes
  15562. *
  15563. * @private
  15564. */
  15565. Graph.prototype._discreteStepNodes = function() {
  15566. var interval = this.physicsDiscreteStepsize;
  15567. var nodes = this.nodes;
  15568. var nodeId;
  15569. var nodesPresent = false;
  15570. if (this.constants.maxVelocity > 0) {
  15571. for (nodeId in nodes) {
  15572. if (nodes.hasOwnProperty(nodeId)) {
  15573. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15574. nodesPresent = true;
  15575. }
  15576. }
  15577. }
  15578. else {
  15579. for (nodeId in nodes) {
  15580. if (nodes.hasOwnProperty(nodeId)) {
  15581. nodes[nodeId].discreteStep(interval);
  15582. nodesPresent = true;
  15583. }
  15584. }
  15585. }
  15586. if (nodesPresent == true) {
  15587. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15588. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15589. this.moving = true;
  15590. }
  15591. else {
  15592. this.moving = this._isMoving(vminCorrected);
  15593. }
  15594. }
  15595. };
  15596. Graph.prototype._physicsTick = function() {
  15597. if (!this.freezeSimulation) {
  15598. if (this.moving) {
  15599. this._doInAllActiveSectors("_initializeForceCalculation");
  15600. this._doInAllActiveSectors("_discreteStepNodes");
  15601. if (this.constants.smoothCurves) {
  15602. this._doInSupportSector("_discreteStepNodes");
  15603. }
  15604. this._findCenter(this._getRange())
  15605. }
  15606. }
  15607. };
  15608. /**
  15609. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15610. * It reschedules itself at the beginning of the function
  15611. *
  15612. * @private
  15613. */
  15614. Graph.prototype._animationStep = function() {
  15615. // reset the timer so a new scheduled animation step can be set
  15616. this.timer = undefined;
  15617. // handle the keyboad movement
  15618. this._handleNavigation();
  15619. // this schedules a new animation step
  15620. this.start();
  15621. // start the physics simulation
  15622. var calculationTime = Date.now();
  15623. var maxSteps = 1;
  15624. this._physicsTick();
  15625. var timeRequired = Date.now() - calculationTime;
  15626. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  15627. this._physicsTick();
  15628. timeRequired = Date.now() - calculationTime;
  15629. maxSteps++;
  15630. }
  15631. // start the rendering process
  15632. var renderTime = Date.now();
  15633. this._redraw();
  15634. this.renderTime = Date.now() - renderTime;
  15635. };
  15636. if (typeof window !== 'undefined') {
  15637. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15638. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15639. }
  15640. /**
  15641. * Schedule a animation step with the refreshrate interval.
  15642. *
  15643. * @poram {Boolean} runCalculationStep
  15644. */
  15645. Graph.prototype.start = function() {
  15646. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15647. if (!this.timer) {
  15648. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15649. }
  15650. }
  15651. else {
  15652. this._redraw();
  15653. }
  15654. };
  15655. /**
  15656. * Move the graph according to the keyboard presses.
  15657. *
  15658. * @private
  15659. */
  15660. Graph.prototype._handleNavigation = function() {
  15661. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15662. var translation = this._getTranslation();
  15663. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15664. }
  15665. if (this.zoomIncrement != 0) {
  15666. var center = {
  15667. x: this.frame.canvas.clientWidth / 2,
  15668. y: this.frame.canvas.clientHeight / 2
  15669. };
  15670. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15671. }
  15672. };
  15673. /**
  15674. * Freeze the _animationStep
  15675. */
  15676. Graph.prototype.toggleFreeze = function() {
  15677. if (this.freezeSimulation == false) {
  15678. this.freezeSimulation = true;
  15679. }
  15680. else {
  15681. this.freezeSimulation = false;
  15682. this.start();
  15683. }
  15684. };
  15685. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15686. if (disableStart === undefined) {
  15687. disableStart = true;
  15688. }
  15689. if (this.constants.smoothCurves == true) {
  15690. this._createBezierNodes();
  15691. }
  15692. else {
  15693. // delete the support nodes
  15694. this.sectors['support']['nodes'] = {};
  15695. for (var edgeId in this.edges) {
  15696. if (this.edges.hasOwnProperty(edgeId)) {
  15697. this.edges[edgeId].smooth = false;
  15698. this.edges[edgeId].via = null;
  15699. }
  15700. }
  15701. }
  15702. this._updateCalculationNodes();
  15703. if (!disableStart) {
  15704. this.moving = true;
  15705. this.start();
  15706. }
  15707. };
  15708. Graph.prototype._createBezierNodes = function() {
  15709. if (this.constants.smoothCurves == true) {
  15710. for (var edgeId in this.edges) {
  15711. if (this.edges.hasOwnProperty(edgeId)) {
  15712. var edge = this.edges[edgeId];
  15713. if (edge.via == null) {
  15714. edge.smooth = true;
  15715. var nodeId = "edgeId:".concat(edge.id);
  15716. this.sectors['support']['nodes'][nodeId] = new Node(
  15717. {id:nodeId,
  15718. mass:1,
  15719. shape:'circle',
  15720. image:"",
  15721. internalMultiplier:1
  15722. },{},{},this.constants);
  15723. edge.via = this.sectors['support']['nodes'][nodeId];
  15724. edge.via.parentEdgeId = edge.id;
  15725. edge.positionBezierNode();
  15726. }
  15727. }
  15728. }
  15729. }
  15730. };
  15731. Graph.prototype._initializeMixinLoaders = function () {
  15732. for (var mixinFunction in graphMixinLoaders) {
  15733. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15734. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15735. }
  15736. }
  15737. };
  15738. /**
  15739. * Load the XY positions of the nodes into the dataset.
  15740. */
  15741. Graph.prototype.storePosition = function() {
  15742. var dataArray = [];
  15743. for (var nodeId in this.nodes) {
  15744. if (this.nodes.hasOwnProperty(nodeId)) {
  15745. var node = this.nodes[nodeId];
  15746. var allowedToMoveX = !this.nodes.xFixed;
  15747. var allowedToMoveY = !this.nodes.yFixed;
  15748. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  15749. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15750. }
  15751. }
  15752. }
  15753. this.nodesData.update(dataArray);
  15754. };
  15755. /**
  15756. * vis.js module exports
  15757. */
  15758. var vis = {
  15759. util: util,
  15760. Controller: Controller,
  15761. DataSet: DataSet,
  15762. DataView: DataView,
  15763. Range: Range,
  15764. Stack: Stack,
  15765. TimeStep: TimeStep,
  15766. components: {
  15767. items: {
  15768. Item: Item,
  15769. ItemBox: ItemBox,
  15770. ItemPoint: ItemPoint,
  15771. ItemRange: ItemRange
  15772. },
  15773. Component: Component,
  15774. Panel: Panel,
  15775. RootPanel: RootPanel,
  15776. ItemSet: ItemSet,
  15777. TimeAxis: TimeAxis
  15778. },
  15779. graph: {
  15780. Node: Node,
  15781. Edge: Edge,
  15782. Popup: Popup,
  15783. Groups: Groups,
  15784. Images: Images
  15785. },
  15786. Timeline: Timeline,
  15787. Graph: Graph
  15788. };
  15789. /**
  15790. * CommonJS module exports
  15791. */
  15792. if (typeof exports !== 'undefined') {
  15793. exports = vis;
  15794. }
  15795. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15796. module.exports = vis;
  15797. }
  15798. /**
  15799. * AMD module exports
  15800. */
  15801. if (typeof(define) === 'function') {
  15802. define(function () {
  15803. return vis;
  15804. });
  15805. }
  15806. /**
  15807. * Window exports
  15808. */
  15809. if (typeof window !== 'undefined') {
  15810. // attach the module to the window, load as a regular javascript file
  15811. window['vis'] = vis;
  15812. }
  15813. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15814. /**
  15815. * Expose `Emitter`.
  15816. */
  15817. module.exports = Emitter;
  15818. /**
  15819. * Initialize a new `Emitter`.
  15820. *
  15821. * @api public
  15822. */
  15823. function Emitter(obj) {
  15824. if (obj) return mixin(obj);
  15825. };
  15826. /**
  15827. * Mixin the emitter properties.
  15828. *
  15829. * @param {Object} obj
  15830. * @return {Object}
  15831. * @api private
  15832. */
  15833. function mixin(obj) {
  15834. for (var key in Emitter.prototype) {
  15835. obj[key] = Emitter.prototype[key];
  15836. }
  15837. return obj;
  15838. }
  15839. /**
  15840. * Listen on the given `event` with `fn`.
  15841. *
  15842. * @param {String} event
  15843. * @param {Function} fn
  15844. * @return {Emitter}
  15845. * @api public
  15846. */
  15847. Emitter.prototype.on =
  15848. Emitter.prototype.addEventListener = function(event, fn){
  15849. this._callbacks = this._callbacks || {};
  15850. (this._callbacks[event] = this._callbacks[event] || [])
  15851. .push(fn);
  15852. return this;
  15853. };
  15854. /**
  15855. * Adds an `event` listener that will be invoked a single
  15856. * time then automatically removed.
  15857. *
  15858. * @param {String} event
  15859. * @param {Function} fn
  15860. * @return {Emitter}
  15861. * @api public
  15862. */
  15863. Emitter.prototype.once = function(event, fn){
  15864. var self = this;
  15865. this._callbacks = this._callbacks || {};
  15866. function on() {
  15867. self.off(event, on);
  15868. fn.apply(this, arguments);
  15869. }
  15870. on.fn = fn;
  15871. this.on(event, on);
  15872. return this;
  15873. };
  15874. /**
  15875. * Remove the given callback for `event` or all
  15876. * registered callbacks.
  15877. *
  15878. * @param {String} event
  15879. * @param {Function} fn
  15880. * @return {Emitter}
  15881. * @api public
  15882. */
  15883. Emitter.prototype.off =
  15884. Emitter.prototype.removeListener =
  15885. Emitter.prototype.removeAllListeners =
  15886. Emitter.prototype.removeEventListener = function(event, fn){
  15887. this._callbacks = this._callbacks || {};
  15888. // all
  15889. if (0 == arguments.length) {
  15890. this._callbacks = {};
  15891. return this;
  15892. }
  15893. // specific event
  15894. var callbacks = this._callbacks[event];
  15895. if (!callbacks) return this;
  15896. // remove all handlers
  15897. if (1 == arguments.length) {
  15898. delete this._callbacks[event];
  15899. return this;
  15900. }
  15901. // remove specific handler
  15902. var cb;
  15903. for (var i = 0; i < callbacks.length; i++) {
  15904. cb = callbacks[i];
  15905. if (cb === fn || cb.fn === fn) {
  15906. callbacks.splice(i, 1);
  15907. break;
  15908. }
  15909. }
  15910. return this;
  15911. };
  15912. /**
  15913. * Emit `event` with the given args.
  15914. *
  15915. * @param {String} event
  15916. * @param {Mixed} ...
  15917. * @return {Emitter}
  15918. */
  15919. Emitter.prototype.emit = function(event){
  15920. this._callbacks = this._callbacks || {};
  15921. var args = [].slice.call(arguments, 1)
  15922. , callbacks = this._callbacks[event];
  15923. if (callbacks) {
  15924. callbacks = callbacks.slice(0);
  15925. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15926. callbacks[i].apply(this, args);
  15927. }
  15928. }
  15929. return this;
  15930. };
  15931. /**
  15932. * Return array of callbacks for `event`.
  15933. *
  15934. * @param {String} event
  15935. * @return {Array}
  15936. * @api public
  15937. */
  15938. Emitter.prototype.listeners = function(event){
  15939. this._callbacks = this._callbacks || {};
  15940. return this._callbacks[event] || [];
  15941. };
  15942. /**
  15943. * Check if this emitter has `event` handlers.
  15944. *
  15945. * @param {String} event
  15946. * @return {Boolean}
  15947. * @api public
  15948. */
  15949. Emitter.prototype.hasListeners = function(event){
  15950. return !! this.listeners(event).length;
  15951. };
  15952. },{}],3:[function(require,module,exports){
  15953. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15954. * http://eightmedia.github.com/hammer.js
  15955. *
  15956. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  15957. * Licensed under the MIT license */
  15958. (function(window, undefined) {
  15959. 'use strict';
  15960. /**
  15961. * Hammer
  15962. * use this to create instances
  15963. * @param {HTMLElement} element
  15964. * @param {Object} options
  15965. * @returns {Hammer.Instance}
  15966. * @constructor
  15967. */
  15968. var Hammer = function(element, options) {
  15969. return new Hammer.Instance(element, options || {});
  15970. };
  15971. // default settings
  15972. Hammer.defaults = {
  15973. // add styles and attributes to the element to prevent the browser from doing
  15974. // its native behavior. this doesnt prevent the scrolling, but cancels
  15975. // the contextmenu, tap highlighting etc
  15976. // set to false to disable this
  15977. stop_browser_behavior: {
  15978. // this also triggers onselectstart=false for IE
  15979. userSelect: 'none',
  15980. // this makes the element blocking in IE10 >, you could experiment with the value
  15981. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  15982. touchAction: 'none',
  15983. touchCallout: 'none',
  15984. contentZooming: 'none',
  15985. userDrag: 'none',
  15986. tapHighlightColor: 'rgba(0,0,0,0)'
  15987. }
  15988. // more settings are defined per gesture at gestures.js
  15989. };
  15990. // detect touchevents
  15991. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  15992. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  15993. // dont use mouseevents on mobile devices
  15994. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  15995. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  15996. // eventtypes per touchevent (start, move, end)
  15997. // are filled by Hammer.event.determineEventTypes on setup
  15998. Hammer.EVENT_TYPES = {};
  15999. // direction defines
  16000. Hammer.DIRECTION_DOWN = 'down';
  16001. Hammer.DIRECTION_LEFT = 'left';
  16002. Hammer.DIRECTION_UP = 'up';
  16003. Hammer.DIRECTION_RIGHT = 'right';
  16004. // pointer type
  16005. Hammer.POINTER_MOUSE = 'mouse';
  16006. Hammer.POINTER_TOUCH = 'touch';
  16007. Hammer.POINTER_PEN = 'pen';
  16008. // touch event defines
  16009. Hammer.EVENT_START = 'start';
  16010. Hammer.EVENT_MOVE = 'move';
  16011. Hammer.EVENT_END = 'end';
  16012. // hammer document where the base events are added at
  16013. Hammer.DOCUMENT = document;
  16014. // plugins namespace
  16015. Hammer.plugins = {};
  16016. // if the window events are set...
  16017. Hammer.READY = false;
  16018. /**
  16019. * setup events to detect gestures on the document
  16020. */
  16021. function setup() {
  16022. if(Hammer.READY) {
  16023. return;
  16024. }
  16025. // find what eventtypes we add listeners to
  16026. Hammer.event.determineEventTypes();
  16027. // Register all gestures inside Hammer.gestures
  16028. for(var name in Hammer.gestures) {
  16029. if(Hammer.gestures.hasOwnProperty(name)) {
  16030. Hammer.detection.register(Hammer.gestures[name]);
  16031. }
  16032. }
  16033. // Add touch events on the document
  16034. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  16035. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  16036. // Hammer is ready...!
  16037. Hammer.READY = true;
  16038. }
  16039. /**
  16040. * create new hammer instance
  16041. * all methods should return the instance itself, so it is chainable.
  16042. * @param {HTMLElement} element
  16043. * @param {Object} [options={}]
  16044. * @returns {Hammer.Instance}
  16045. * @constructor
  16046. */
  16047. Hammer.Instance = function(element, options) {
  16048. var self = this;
  16049. // setup HammerJS window events and register all gestures
  16050. // this also sets up the default options
  16051. setup();
  16052. this.element = element;
  16053. // start/stop detection option
  16054. this.enabled = true;
  16055. // merge options
  16056. this.options = Hammer.utils.extend(
  16057. Hammer.utils.extend({}, Hammer.defaults),
  16058. options || {});
  16059. // add some css to the element to prevent the browser from doing its native behavoir
  16060. if(this.options.stop_browser_behavior) {
  16061. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  16062. }
  16063. // start detection on touchstart
  16064. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  16065. if(self.enabled) {
  16066. Hammer.detection.startDetect(self, ev);
  16067. }
  16068. });
  16069. // return instance
  16070. return this;
  16071. };
  16072. Hammer.Instance.prototype = {
  16073. /**
  16074. * bind events to the instance
  16075. * @param {String} gesture
  16076. * @param {Function} handler
  16077. * @returns {Hammer.Instance}
  16078. */
  16079. on: function onEvent(gesture, handler){
  16080. var gestures = gesture.split(' ');
  16081. for(var t=0; t<gestures.length; t++) {
  16082. this.element.addEventListener(gestures[t], handler, false);
  16083. }
  16084. return this;
  16085. },
  16086. /**
  16087. * unbind events to the instance
  16088. * @param {String} gesture
  16089. * @param {Function} handler
  16090. * @returns {Hammer.Instance}
  16091. */
  16092. off: function offEvent(gesture, handler){
  16093. var gestures = gesture.split(' ');
  16094. for(var t=0; t<gestures.length; t++) {
  16095. this.element.removeEventListener(gestures[t], handler, false);
  16096. }
  16097. return this;
  16098. },
  16099. /**
  16100. * trigger gesture event
  16101. * @param {String} gesture
  16102. * @param {Object} eventData
  16103. * @returns {Hammer.Instance}
  16104. */
  16105. trigger: function triggerEvent(gesture, eventData){
  16106. // create DOM event
  16107. var event = Hammer.DOCUMENT.createEvent('Event');
  16108. event.initEvent(gesture, true, true);
  16109. event.gesture = eventData;
  16110. // trigger on the target if it is in the instance element,
  16111. // this is for event delegation tricks
  16112. var element = this.element;
  16113. if(Hammer.utils.hasParent(eventData.target, element)) {
  16114. element = eventData.target;
  16115. }
  16116. element.dispatchEvent(event);
  16117. return this;
  16118. },
  16119. /**
  16120. * enable of disable hammer.js detection
  16121. * @param {Boolean} state
  16122. * @returns {Hammer.Instance}
  16123. */
  16124. enable: function enable(state) {
  16125. this.enabled = state;
  16126. return this;
  16127. }
  16128. };
  16129. /**
  16130. * this holds the last move event,
  16131. * used to fix empty touchend issue
  16132. * see the onTouch event for an explanation
  16133. * @type {Object}
  16134. */
  16135. var last_move_event = null;
  16136. /**
  16137. * when the mouse is hold down, this is true
  16138. * @type {Boolean}
  16139. */
  16140. var enable_detect = false;
  16141. /**
  16142. * when touch events have been fired, this is true
  16143. * @type {Boolean}
  16144. */
  16145. var touch_triggered = false;
  16146. Hammer.event = {
  16147. /**
  16148. * simple addEventListener
  16149. * @param {HTMLElement} element
  16150. * @param {String} type
  16151. * @param {Function} handler
  16152. */
  16153. bindDom: function(element, type, handler) {
  16154. var types = type.split(' ');
  16155. for(var t=0; t<types.length; t++) {
  16156. element.addEventListener(types[t], handler, false);
  16157. }
  16158. },
  16159. /**
  16160. * touch events with mouse fallback
  16161. * @param {HTMLElement} element
  16162. * @param {String} eventType like Hammer.EVENT_MOVE
  16163. * @param {Function} handler
  16164. */
  16165. onTouch: function onTouch(element, eventType, handler) {
  16166. var self = this;
  16167. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  16168. var sourceEventType = ev.type.toLowerCase();
  16169. // onmouseup, but when touchend has been fired we do nothing.
  16170. // this is for touchdevices which also fire a mouseup on touchend
  16171. if(sourceEventType.match(/mouse/) && touch_triggered) {
  16172. return;
  16173. }
  16174. // mousebutton must be down or a touch event
  16175. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  16176. sourceEventType.match(/pointerdown/) || // pointerevents touch
  16177. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  16178. ){
  16179. enable_detect = true;
  16180. }
  16181. // we are in a touch event, set the touch triggered bool to true,
  16182. // this for the conflicts that may occur on ios and android
  16183. if(sourceEventType.match(/touch|pointer/)) {
  16184. touch_triggered = true;
  16185. }
  16186. // count the total touches on the screen
  16187. var count_touches = 0;
  16188. // when touch has been triggered in this detection session
  16189. // and we are now handling a mouse event, we stop that to prevent conflicts
  16190. if(enable_detect) {
  16191. // update pointerevent
  16192. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  16193. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16194. }
  16195. // touch
  16196. else if(sourceEventType.match(/touch/)) {
  16197. count_touches = ev.touches.length;
  16198. }
  16199. // mouse
  16200. else if(!touch_triggered) {
  16201. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  16202. }
  16203. // if we are in a end event, but when we remove one touch and
  16204. // we still have enough, set eventType to move
  16205. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  16206. eventType = Hammer.EVENT_MOVE;
  16207. }
  16208. // no touches, force the end event
  16209. else if(!count_touches) {
  16210. eventType = Hammer.EVENT_END;
  16211. }
  16212. // because touchend has no touches, and we often want to use these in our gestures,
  16213. // we send the last move event as our eventData in touchend
  16214. if(!count_touches && last_move_event !== null) {
  16215. ev = last_move_event;
  16216. }
  16217. // store the last move event
  16218. else {
  16219. last_move_event = ev;
  16220. }
  16221. // trigger the handler
  16222. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  16223. // remove pointerevent from list
  16224. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  16225. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16226. }
  16227. }
  16228. //debug(sourceEventType +" "+ eventType);
  16229. // on the end we reset everything
  16230. if(!count_touches) {
  16231. last_move_event = null;
  16232. enable_detect = false;
  16233. touch_triggered = false;
  16234. Hammer.PointerEvent.reset();
  16235. }
  16236. });
  16237. },
  16238. /**
  16239. * we have different events for each device/browser
  16240. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  16241. */
  16242. determineEventTypes: function determineEventTypes() {
  16243. // determine the eventtype we want to set
  16244. var types;
  16245. // pointerEvents magic
  16246. if(Hammer.HAS_POINTEREVENTS) {
  16247. types = Hammer.PointerEvent.getEvents();
  16248. }
  16249. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  16250. else if(Hammer.NO_MOUSEEVENTS) {
  16251. types = [
  16252. 'touchstart',
  16253. 'touchmove',
  16254. 'touchend touchcancel'];
  16255. }
  16256. // for non pointer events browsers and mixed browsers,
  16257. // like chrome on windows8 touch laptop
  16258. else {
  16259. types = [
  16260. 'touchstart mousedown',
  16261. 'touchmove mousemove',
  16262. 'touchend touchcancel mouseup'];
  16263. }
  16264. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  16265. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  16266. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  16267. },
  16268. /**
  16269. * create touchlist depending on the event
  16270. * @param {Object} ev
  16271. * @param {String} eventType used by the fakemultitouch plugin
  16272. */
  16273. getTouchList: function getTouchList(ev/*, eventType*/) {
  16274. // get the fake pointerEvent touchlist
  16275. if(Hammer.HAS_POINTEREVENTS) {
  16276. return Hammer.PointerEvent.getTouchList();
  16277. }
  16278. // get the touchlist
  16279. else if(ev.touches) {
  16280. return ev.touches;
  16281. }
  16282. // make fake touchlist from mouse position
  16283. else {
  16284. return [{
  16285. identifier: 1,
  16286. pageX: ev.pageX,
  16287. pageY: ev.pageY,
  16288. target: ev.target
  16289. }];
  16290. }
  16291. },
  16292. /**
  16293. * collect event data for Hammer js
  16294. * @param {HTMLElement} element
  16295. * @param {String} eventType like Hammer.EVENT_MOVE
  16296. * @param {Object} eventData
  16297. */
  16298. collectEventData: function collectEventData(element, eventType, ev) {
  16299. var touches = this.getTouchList(ev, eventType);
  16300. // find out pointerType
  16301. var pointerType = Hammer.POINTER_TOUCH;
  16302. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  16303. pointerType = Hammer.POINTER_MOUSE;
  16304. }
  16305. return {
  16306. center : Hammer.utils.getCenter(touches),
  16307. timeStamp : new Date().getTime(),
  16308. target : ev.target,
  16309. touches : touches,
  16310. eventType : eventType,
  16311. pointerType : pointerType,
  16312. srcEvent : ev,
  16313. /**
  16314. * prevent the browser default actions
  16315. * mostly used to disable scrolling of the browser
  16316. */
  16317. preventDefault: function() {
  16318. if(this.srcEvent.preventManipulation) {
  16319. this.srcEvent.preventManipulation();
  16320. }
  16321. if(this.srcEvent.preventDefault) {
  16322. this.srcEvent.preventDefault();
  16323. }
  16324. },
  16325. /**
  16326. * stop bubbling the event up to its parents
  16327. */
  16328. stopPropagation: function() {
  16329. this.srcEvent.stopPropagation();
  16330. },
  16331. /**
  16332. * immediately stop gesture detection
  16333. * might be useful after a swipe was detected
  16334. * @return {*}
  16335. */
  16336. stopDetect: function() {
  16337. return Hammer.detection.stopDetect();
  16338. }
  16339. };
  16340. }
  16341. };
  16342. Hammer.PointerEvent = {
  16343. /**
  16344. * holds all pointers
  16345. * @type {Object}
  16346. */
  16347. pointers: {},
  16348. /**
  16349. * get a list of pointers
  16350. * @returns {Array} touchlist
  16351. */
  16352. getTouchList: function() {
  16353. var self = this;
  16354. var touchlist = [];
  16355. // we can use forEach since pointerEvents only is in IE10
  16356. Object.keys(self.pointers).sort().forEach(function(id) {
  16357. touchlist.push(self.pointers[id]);
  16358. });
  16359. return touchlist;
  16360. },
  16361. /**
  16362. * update the position of a pointer
  16363. * @param {String} type Hammer.EVENT_END
  16364. * @param {Object} pointerEvent
  16365. */
  16366. updatePointer: function(type, pointerEvent) {
  16367. if(type == Hammer.EVENT_END) {
  16368. this.pointers = {};
  16369. }
  16370. else {
  16371. pointerEvent.identifier = pointerEvent.pointerId;
  16372. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16373. }
  16374. return Object.keys(this.pointers).length;
  16375. },
  16376. /**
  16377. * check if ev matches pointertype
  16378. * @param {String} pointerType Hammer.POINTER_MOUSE
  16379. * @param {PointerEvent} ev
  16380. */
  16381. matchType: function(pointerType, ev) {
  16382. if(!ev.pointerType) {
  16383. return false;
  16384. }
  16385. var types = {};
  16386. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16387. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16388. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16389. return types[pointerType];
  16390. },
  16391. /**
  16392. * get events
  16393. */
  16394. getEvents: function() {
  16395. return [
  16396. 'pointerdown MSPointerDown',
  16397. 'pointermove MSPointerMove',
  16398. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16399. ];
  16400. },
  16401. /**
  16402. * reset the list
  16403. */
  16404. reset: function() {
  16405. this.pointers = {};
  16406. }
  16407. };
  16408. Hammer.utils = {
  16409. /**
  16410. * extend method,
  16411. * also used for cloning when dest is an empty object
  16412. * @param {Object} dest
  16413. * @param {Object} src
  16414. * @parm {Boolean} merge do a merge
  16415. * @returns {Object} dest
  16416. */
  16417. extend: function extend(dest, src, merge) {
  16418. for (var key in src) {
  16419. if(dest[key] !== undefined && merge) {
  16420. continue;
  16421. }
  16422. dest[key] = src[key];
  16423. }
  16424. return dest;
  16425. },
  16426. /**
  16427. * find if a node is in the given parent
  16428. * used for event delegation tricks
  16429. * @param {HTMLElement} node
  16430. * @param {HTMLElement} parent
  16431. * @returns {boolean} has_parent
  16432. */
  16433. hasParent: function(node, parent) {
  16434. while(node){
  16435. if(node == parent) {
  16436. return true;
  16437. }
  16438. node = node.parentNode;
  16439. }
  16440. return false;
  16441. },
  16442. /**
  16443. * get the center of all the touches
  16444. * @param {Array} touches
  16445. * @returns {Object} center
  16446. */
  16447. getCenter: function getCenter(touches) {
  16448. var valuesX = [], valuesY = [];
  16449. for(var t= 0,len=touches.length; t<len; t++) {
  16450. valuesX.push(touches[t].pageX);
  16451. valuesY.push(touches[t].pageY);
  16452. }
  16453. return {
  16454. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  16455. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  16456. };
  16457. },
  16458. /**
  16459. * calculate the velocity between two points
  16460. * @param {Number} delta_time
  16461. * @param {Number} delta_x
  16462. * @param {Number} delta_y
  16463. * @returns {Object} velocity
  16464. */
  16465. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  16466. return {
  16467. x: Math.abs(delta_x / delta_time) || 0,
  16468. y: Math.abs(delta_y / delta_time) || 0
  16469. };
  16470. },
  16471. /**
  16472. * calculate the angle between two coordinates
  16473. * @param {Touch} touch1
  16474. * @param {Touch} touch2
  16475. * @returns {Number} angle
  16476. */
  16477. getAngle: function getAngle(touch1, touch2) {
  16478. var y = touch2.pageY - touch1.pageY,
  16479. x = touch2.pageX - touch1.pageX;
  16480. return Math.atan2(y, x) * 180 / Math.PI;
  16481. },
  16482. /**
  16483. * angle to direction define
  16484. * @param {Touch} touch1
  16485. * @param {Touch} touch2
  16486. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  16487. */
  16488. getDirection: function getDirection(touch1, touch2) {
  16489. var x = Math.abs(touch1.pageX - touch2.pageX),
  16490. y = Math.abs(touch1.pageY - touch2.pageY);
  16491. if(x >= y) {
  16492. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16493. }
  16494. else {
  16495. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16496. }
  16497. },
  16498. /**
  16499. * calculate the distance between two touches
  16500. * @param {Touch} touch1
  16501. * @param {Touch} touch2
  16502. * @returns {Number} distance
  16503. */
  16504. getDistance: function getDistance(touch1, touch2) {
  16505. var x = touch2.pageX - touch1.pageX,
  16506. y = touch2.pageY - touch1.pageY;
  16507. return Math.sqrt((x*x) + (y*y));
  16508. },
  16509. /**
  16510. * calculate the scale factor between two touchLists (fingers)
  16511. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16512. * @param {Array} start
  16513. * @param {Array} end
  16514. * @returns {Number} scale
  16515. */
  16516. getScale: function getScale(start, end) {
  16517. // need two fingers...
  16518. if(start.length >= 2 && end.length >= 2) {
  16519. return this.getDistance(end[0], end[1]) /
  16520. this.getDistance(start[0], start[1]);
  16521. }
  16522. return 1;
  16523. },
  16524. /**
  16525. * calculate the rotation degrees between two touchLists (fingers)
  16526. * @param {Array} start
  16527. * @param {Array} end
  16528. * @returns {Number} rotation
  16529. */
  16530. getRotation: function getRotation(start, end) {
  16531. // need two fingers
  16532. if(start.length >= 2 && end.length >= 2) {
  16533. return this.getAngle(end[1], end[0]) -
  16534. this.getAngle(start[1], start[0]);
  16535. }
  16536. return 0;
  16537. },
  16538. /**
  16539. * boolean if the direction is vertical
  16540. * @param {String} direction
  16541. * @returns {Boolean} is_vertical
  16542. */
  16543. isVertical: function isVertical(direction) {
  16544. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16545. },
  16546. /**
  16547. * stop browser default behavior with css props
  16548. * @param {HtmlElement} element
  16549. * @param {Object} css_props
  16550. */
  16551. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16552. var prop,
  16553. vendors = ['webkit','khtml','moz','ms','o',''];
  16554. if(!css_props || !element.style) {
  16555. return;
  16556. }
  16557. // with css properties for modern browsers
  16558. for(var i = 0; i < vendors.length; i++) {
  16559. for(var p in css_props) {
  16560. if(css_props.hasOwnProperty(p)) {
  16561. prop = p;
  16562. // vender prefix at the property
  16563. if(vendors[i]) {
  16564. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16565. }
  16566. // set the style
  16567. element.style[prop] = css_props[p];
  16568. }
  16569. }
  16570. }
  16571. // also the disable onselectstart
  16572. if(css_props.userSelect == 'none') {
  16573. element.onselectstart = function() {
  16574. return false;
  16575. };
  16576. }
  16577. }
  16578. };
  16579. Hammer.detection = {
  16580. // contains all registred Hammer.gestures in the correct order
  16581. gestures: [],
  16582. // data of the current Hammer.gesture detection session
  16583. current: null,
  16584. // the previous Hammer.gesture session data
  16585. // is a full clone of the previous gesture.current object
  16586. previous: null,
  16587. // when this becomes true, no gestures are fired
  16588. stopped: false,
  16589. /**
  16590. * start Hammer.gesture detection
  16591. * @param {Hammer.Instance} inst
  16592. * @param {Object} eventData
  16593. */
  16594. startDetect: function startDetect(inst, eventData) {
  16595. // already busy with a Hammer.gesture detection on an element
  16596. if(this.current) {
  16597. return;
  16598. }
  16599. this.stopped = false;
  16600. this.current = {
  16601. inst : inst, // reference to HammerInstance we're working for
  16602. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16603. lastEvent : false, // last eventData
  16604. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16605. };
  16606. this.detect(eventData);
  16607. },
  16608. /**
  16609. * Hammer.gesture detection
  16610. * @param {Object} eventData
  16611. * @param {Object} eventData
  16612. */
  16613. detect: function detect(eventData) {
  16614. if(!this.current || this.stopped) {
  16615. return;
  16616. }
  16617. // extend event data with calculations about scale, distance etc
  16618. eventData = this.extendEventData(eventData);
  16619. // instance options
  16620. var inst_options = this.current.inst.options;
  16621. // call Hammer.gesture handlers
  16622. for(var g=0,len=this.gestures.length; g<len; g++) {
  16623. var gesture = this.gestures[g];
  16624. // only when the instance options have enabled this gesture
  16625. if(!this.stopped && inst_options[gesture.name] !== false) {
  16626. // if a handler returns false, we stop with the detection
  16627. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16628. this.stopDetect();
  16629. break;
  16630. }
  16631. }
  16632. }
  16633. // store as previous event event
  16634. if(this.current) {
  16635. this.current.lastEvent = eventData;
  16636. }
  16637. // endevent, but not the last touch, so dont stop
  16638. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16639. this.stopDetect();
  16640. }
  16641. return eventData;
  16642. },
  16643. /**
  16644. * clear the Hammer.gesture vars
  16645. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16646. * to stop other Hammer.gestures from being fired
  16647. */
  16648. stopDetect: function stopDetect() {
  16649. // clone current data to the store as the previous gesture
  16650. // used for the double tap gesture, since this is an other gesture detect session
  16651. this.previous = Hammer.utils.extend({}, this.current);
  16652. // reset the current
  16653. this.current = null;
  16654. // stopped!
  16655. this.stopped = true;
  16656. },
  16657. /**
  16658. * extend eventData for Hammer.gestures
  16659. * @param {Object} ev
  16660. * @returns {Object} ev
  16661. */
  16662. extendEventData: function extendEventData(ev) {
  16663. var startEv = this.current.startEvent;
  16664. // if the touches change, set the new touches over the startEvent touches
  16665. // this because touchevents don't have all the touches on touchstart, or the
  16666. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16667. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16668. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16669. // extend 1 level deep to get the touchlist with the touch objects
  16670. startEv.touches = [];
  16671. for(var i=0,len=ev.touches.length; i<len; i++) {
  16672. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16673. }
  16674. }
  16675. var delta_time = ev.timeStamp - startEv.timeStamp,
  16676. delta_x = ev.center.pageX - startEv.center.pageX,
  16677. delta_y = ev.center.pageY - startEv.center.pageY,
  16678. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16679. Hammer.utils.extend(ev, {
  16680. deltaTime : delta_time,
  16681. deltaX : delta_x,
  16682. deltaY : delta_y,
  16683. velocityX : velocity.x,
  16684. velocityY : velocity.y,
  16685. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16686. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16687. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16688. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16689. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16690. startEvent : startEv
  16691. });
  16692. return ev;
  16693. },
  16694. /**
  16695. * register new gesture
  16696. * @param {Object} gesture object, see gestures.js for documentation
  16697. * @returns {Array} gestures
  16698. */
  16699. register: function register(gesture) {
  16700. // add an enable gesture options if there is no given
  16701. var options = gesture.defaults || {};
  16702. if(options[gesture.name] === undefined) {
  16703. options[gesture.name] = true;
  16704. }
  16705. // extend Hammer default options with the Hammer.gesture options
  16706. Hammer.utils.extend(Hammer.defaults, options, true);
  16707. // set its index
  16708. gesture.index = gesture.index || 1000;
  16709. // add Hammer.gesture to the list
  16710. this.gestures.push(gesture);
  16711. // sort the list by index
  16712. this.gestures.sort(function(a, b) {
  16713. if (a.index < b.index) {
  16714. return -1;
  16715. }
  16716. if (a.index > b.index) {
  16717. return 1;
  16718. }
  16719. return 0;
  16720. });
  16721. return this.gestures;
  16722. }
  16723. };
  16724. Hammer.gestures = Hammer.gestures || {};
  16725. /**
  16726. * Custom gestures
  16727. * ==============================
  16728. *
  16729. * Gesture object
  16730. * --------------------
  16731. * The object structure of a gesture:
  16732. *
  16733. * { name: 'mygesture',
  16734. * index: 1337,
  16735. * defaults: {
  16736. * mygesture_option: true
  16737. * }
  16738. * handler: function(type, ev, inst) {
  16739. * // trigger gesture event
  16740. * inst.trigger(this.name, ev);
  16741. * }
  16742. * }
  16743. * @param {String} name
  16744. * this should be the name of the gesture, lowercase
  16745. * it is also being used to disable/enable the gesture per instance config.
  16746. *
  16747. * @param {Number} [index=1000]
  16748. * the index of the gesture, where it is going to be in the stack of gestures detection
  16749. * like when you build an gesture that depends on the drag gesture, it is a good
  16750. * idea to place it after the index of the drag gesture.
  16751. *
  16752. * @param {Object} [defaults={}]
  16753. * the default settings of the gesture. these are added to the instance settings,
  16754. * and can be overruled per instance. you can also add the name of the gesture,
  16755. * but this is also added by default (and set to true).
  16756. *
  16757. * @param {Function} handler
  16758. * this handles the gesture detection of your custom gesture and receives the
  16759. * following arguments:
  16760. *
  16761. * @param {Object} eventData
  16762. * event data containing the following properties:
  16763. * timeStamp {Number} time the event occurred
  16764. * target {HTMLElement} target element
  16765. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16766. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16767. * center {Object} center position of the touches. contains pageX and pageY
  16768. * deltaTime {Number} the total time of the touches in the screen
  16769. * deltaX {Number} the delta on x axis we haved moved
  16770. * deltaY {Number} the delta on y axis we haved moved
  16771. * velocityX {Number} the velocity on the x
  16772. * velocityY {Number} the velocity on y
  16773. * angle {Number} the angle we are moving
  16774. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16775. * distance {Number} the distance we haved moved
  16776. * scale {Number} scaling of the touches, needs 2 touches
  16777. * rotation {Number} rotation of the touches, needs 2 touches *
  16778. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16779. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16780. * startEvent {Object} contains the same properties as above,
  16781. * but from the first touch. this is used to calculate
  16782. * distances, deltaTime, scaling etc
  16783. *
  16784. * @param {Hammer.Instance} inst
  16785. * the instance we are doing the detection for. you can get the options from
  16786. * the inst.options object and trigger the gesture event by calling inst.trigger
  16787. *
  16788. *
  16789. * Handle gestures
  16790. * --------------------
  16791. * inside the handler you can get/set Hammer.detection.current. This is the current
  16792. * detection session. It has the following properties
  16793. * @param {String} name
  16794. * contains the name of the gesture we have detected. it has not a real function,
  16795. * only to check in other gestures if something is detected.
  16796. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16797. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16798. *
  16799. * @readonly
  16800. * @param {Hammer.Instance} inst
  16801. * the instance we do the detection for
  16802. *
  16803. * @readonly
  16804. * @param {Object} startEvent
  16805. * contains the properties of the first gesture detection in this session.
  16806. * Used for calculations about timing, distance, etc.
  16807. *
  16808. * @readonly
  16809. * @param {Object} lastEvent
  16810. * contains all the properties of the last gesture detect in this session.
  16811. *
  16812. * after the gesture detection session has been completed (user has released the screen)
  16813. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16814. * this is usefull for gestures like doubletap, where you need to know if the
  16815. * previous gesture was a tap
  16816. *
  16817. * options that have been set by the instance can be received by calling inst.options
  16818. *
  16819. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16820. * The first param is the name of your gesture, the second the event argument
  16821. *
  16822. *
  16823. * Register gestures
  16824. * --------------------
  16825. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16826. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16827. * manually and pass your gesture object as a param
  16828. *
  16829. */
  16830. /**
  16831. * Hold
  16832. * Touch stays at the same place for x time
  16833. * @events hold
  16834. */
  16835. Hammer.gestures.Hold = {
  16836. name: 'hold',
  16837. index: 10,
  16838. defaults: {
  16839. hold_timeout : 500,
  16840. hold_threshold : 1
  16841. },
  16842. timer: null,
  16843. handler: function holdGesture(ev, inst) {
  16844. switch(ev.eventType) {
  16845. case Hammer.EVENT_START:
  16846. // clear any running timers
  16847. clearTimeout(this.timer);
  16848. // set the gesture so we can check in the timeout if it still is
  16849. Hammer.detection.current.name = this.name;
  16850. // set timer and if after the timeout it still is hold,
  16851. // we trigger the hold event
  16852. this.timer = setTimeout(function() {
  16853. if(Hammer.detection.current.name == 'hold') {
  16854. inst.trigger('hold', ev);
  16855. }
  16856. }, inst.options.hold_timeout);
  16857. break;
  16858. // when you move or end we clear the timer
  16859. case Hammer.EVENT_MOVE:
  16860. if(ev.distance > inst.options.hold_threshold) {
  16861. clearTimeout(this.timer);
  16862. }
  16863. break;
  16864. case Hammer.EVENT_END:
  16865. clearTimeout(this.timer);
  16866. break;
  16867. }
  16868. }
  16869. };
  16870. /**
  16871. * Tap/DoubleTap
  16872. * Quick touch at a place or double at the same place
  16873. * @events tap, doubletap
  16874. */
  16875. Hammer.gestures.Tap = {
  16876. name: 'tap',
  16877. index: 100,
  16878. defaults: {
  16879. tap_max_touchtime : 250,
  16880. tap_max_distance : 10,
  16881. tap_always : true,
  16882. doubletap_distance : 20,
  16883. doubletap_interval : 300
  16884. },
  16885. handler: function tapGesture(ev, inst) {
  16886. if(ev.eventType == Hammer.EVENT_END) {
  16887. // previous gesture, for the double tap since these are two different gesture detections
  16888. var prev = Hammer.detection.previous,
  16889. did_doubletap = false;
  16890. // when the touchtime is higher then the max touch time
  16891. // or when the moving distance is too much
  16892. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16893. ev.distance > inst.options.tap_max_distance) {
  16894. return;
  16895. }
  16896. // check if double tap
  16897. if(prev && prev.name == 'tap' &&
  16898. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16899. ev.distance < inst.options.doubletap_distance) {
  16900. inst.trigger('doubletap', ev);
  16901. did_doubletap = true;
  16902. }
  16903. // do a single tap
  16904. if(!did_doubletap || inst.options.tap_always) {
  16905. Hammer.detection.current.name = 'tap';
  16906. inst.trigger(Hammer.detection.current.name, ev);
  16907. }
  16908. }
  16909. }
  16910. };
  16911. /**
  16912. * Swipe
  16913. * triggers swipe events when the end velocity is above the threshold
  16914. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16915. */
  16916. Hammer.gestures.Swipe = {
  16917. name: 'swipe',
  16918. index: 40,
  16919. defaults: {
  16920. // set 0 for unlimited, but this can conflict with transform
  16921. swipe_max_touches : 1,
  16922. swipe_velocity : 0.7
  16923. },
  16924. handler: function swipeGesture(ev, inst) {
  16925. if(ev.eventType == Hammer.EVENT_END) {
  16926. // max touches
  16927. if(inst.options.swipe_max_touches > 0 &&
  16928. ev.touches.length > inst.options.swipe_max_touches) {
  16929. return;
  16930. }
  16931. // when the distance we moved is too small we skip this gesture
  16932. // or we can be already in dragging
  16933. if(ev.velocityX > inst.options.swipe_velocity ||
  16934. ev.velocityY > inst.options.swipe_velocity) {
  16935. // trigger swipe events
  16936. inst.trigger(this.name, ev);
  16937. inst.trigger(this.name + ev.direction, ev);
  16938. }
  16939. }
  16940. }
  16941. };
  16942. /**
  16943. * Drag
  16944. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16945. * moving left and right is a good practice. When all the drag events are blocking
  16946. * you disable scrolling on that area.
  16947. * @events drag, drapleft, dragright, dragup, dragdown
  16948. */
  16949. Hammer.gestures.Drag = {
  16950. name: 'drag',
  16951. index: 50,
  16952. defaults: {
  16953. drag_min_distance : 10,
  16954. // set 0 for unlimited, but this can conflict with transform
  16955. drag_max_touches : 1,
  16956. // prevent default browser behavior when dragging occurs
  16957. // be careful with it, it makes the element a blocking element
  16958. // when you are using the drag gesture, it is a good practice to set this true
  16959. drag_block_horizontal : false,
  16960. drag_block_vertical : false,
  16961. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  16962. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  16963. drag_lock_to_axis : false,
  16964. // drag lock only kicks in when distance > drag_lock_min_distance
  16965. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  16966. drag_lock_min_distance : 25
  16967. },
  16968. triggered: false,
  16969. handler: function dragGesture(ev, inst) {
  16970. // current gesture isnt drag, but dragged is true
  16971. // this means an other gesture is busy. now call dragend
  16972. if(Hammer.detection.current.name != this.name && this.triggered) {
  16973. inst.trigger(this.name +'end', ev);
  16974. this.triggered = false;
  16975. return;
  16976. }
  16977. // max touches
  16978. if(inst.options.drag_max_touches > 0 &&
  16979. ev.touches.length > inst.options.drag_max_touches) {
  16980. return;
  16981. }
  16982. switch(ev.eventType) {
  16983. case Hammer.EVENT_START:
  16984. this.triggered = false;
  16985. break;
  16986. case Hammer.EVENT_MOVE:
  16987. // when the distance we moved is too small we skip this gesture
  16988. // or we can be already in dragging
  16989. if(ev.distance < inst.options.drag_min_distance &&
  16990. Hammer.detection.current.name != this.name) {
  16991. return;
  16992. }
  16993. // we are dragging!
  16994. Hammer.detection.current.name = this.name;
  16995. // lock drag to axis?
  16996. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  16997. ev.drag_locked_to_axis = true;
  16998. }
  16999. var last_direction = Hammer.detection.current.lastEvent.direction;
  17000. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  17001. // keep direction on the axis that the drag gesture started on
  17002. if(Hammer.utils.isVertical(last_direction)) {
  17003. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  17004. }
  17005. else {
  17006. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  17007. }
  17008. }
  17009. // first time, trigger dragstart event
  17010. if(!this.triggered) {
  17011. inst.trigger(this.name +'start', ev);
  17012. this.triggered = true;
  17013. }
  17014. // trigger normal event
  17015. inst.trigger(this.name, ev);
  17016. // direction event, like dragdown
  17017. inst.trigger(this.name + ev.direction, ev);
  17018. // block the browser events
  17019. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  17020. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  17021. ev.preventDefault();
  17022. }
  17023. break;
  17024. case Hammer.EVENT_END:
  17025. // trigger dragend
  17026. if(this.triggered) {
  17027. inst.trigger(this.name +'end', ev);
  17028. }
  17029. this.triggered = false;
  17030. break;
  17031. }
  17032. }
  17033. };
  17034. /**
  17035. * Transform
  17036. * User want to scale or rotate with 2 fingers
  17037. * @events transform, pinch, pinchin, pinchout, rotate
  17038. */
  17039. Hammer.gestures.Transform = {
  17040. name: 'transform',
  17041. index: 45,
  17042. defaults: {
  17043. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  17044. transform_min_scale : 0.01,
  17045. // rotation in degrees
  17046. transform_min_rotation : 1,
  17047. // prevent default browser behavior when two touches are on the screen
  17048. // but it makes the element a blocking element
  17049. // when you are using the transform gesture, it is a good practice to set this true
  17050. transform_always_block : false
  17051. },
  17052. triggered: false,
  17053. handler: function transformGesture(ev, inst) {
  17054. // current gesture isnt drag, but dragged is true
  17055. // this means an other gesture is busy. now call dragend
  17056. if(Hammer.detection.current.name != this.name && this.triggered) {
  17057. inst.trigger(this.name +'end', ev);
  17058. this.triggered = false;
  17059. return;
  17060. }
  17061. // atleast multitouch
  17062. if(ev.touches.length < 2) {
  17063. return;
  17064. }
  17065. // prevent default when two fingers are on the screen
  17066. if(inst.options.transform_always_block) {
  17067. ev.preventDefault();
  17068. }
  17069. switch(ev.eventType) {
  17070. case Hammer.EVENT_START:
  17071. this.triggered = false;
  17072. break;
  17073. case Hammer.EVENT_MOVE:
  17074. var scale_threshold = Math.abs(1-ev.scale);
  17075. var rotation_threshold = Math.abs(ev.rotation);
  17076. // when the distance we moved is too small we skip this gesture
  17077. // or we can be already in dragging
  17078. if(scale_threshold < inst.options.transform_min_scale &&
  17079. rotation_threshold < inst.options.transform_min_rotation) {
  17080. return;
  17081. }
  17082. // we are transforming!
  17083. Hammer.detection.current.name = this.name;
  17084. // first time, trigger dragstart event
  17085. if(!this.triggered) {
  17086. inst.trigger(this.name +'start', ev);
  17087. this.triggered = true;
  17088. }
  17089. inst.trigger(this.name, ev); // basic transform event
  17090. // trigger rotate event
  17091. if(rotation_threshold > inst.options.transform_min_rotation) {
  17092. inst.trigger('rotate', ev);
  17093. }
  17094. // trigger pinch event
  17095. if(scale_threshold > inst.options.transform_min_scale) {
  17096. inst.trigger('pinch', ev);
  17097. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  17098. }
  17099. break;
  17100. case Hammer.EVENT_END:
  17101. // trigger dragend
  17102. if(this.triggered) {
  17103. inst.trigger(this.name +'end', ev);
  17104. }
  17105. this.triggered = false;
  17106. break;
  17107. }
  17108. }
  17109. };
  17110. /**
  17111. * Touch
  17112. * Called as first, tells the user has touched the screen
  17113. * @events touch
  17114. */
  17115. Hammer.gestures.Touch = {
  17116. name: 'touch',
  17117. index: -Infinity,
  17118. defaults: {
  17119. // call preventDefault at touchstart, and makes the element blocking by
  17120. // disabling the scrolling of the page, but it improves gestures like
  17121. // transforming and dragging.
  17122. // be careful with using this, it can be very annoying for users to be stuck
  17123. // on the page
  17124. prevent_default: false,
  17125. // disable mouse events, so only touch (or pen!) input triggers events
  17126. prevent_mouseevents: false
  17127. },
  17128. handler: function touchGesture(ev, inst) {
  17129. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  17130. ev.stopDetect();
  17131. return;
  17132. }
  17133. if(inst.options.prevent_default) {
  17134. ev.preventDefault();
  17135. }
  17136. if(ev.eventType == Hammer.EVENT_START) {
  17137. inst.trigger(this.name, ev);
  17138. }
  17139. }
  17140. };
  17141. /**
  17142. * Release
  17143. * Called as last, tells the user has released the screen
  17144. * @events release
  17145. */
  17146. Hammer.gestures.Release = {
  17147. name: 'release',
  17148. index: Infinity,
  17149. handler: function releaseGesture(ev, inst) {
  17150. if(ev.eventType == Hammer.EVENT_END) {
  17151. inst.trigger(this.name, ev);
  17152. }
  17153. }
  17154. };
  17155. // node export
  17156. if(typeof module === 'object' && typeof module.exports === 'object'){
  17157. module.exports = Hammer;
  17158. }
  17159. // just window export
  17160. else {
  17161. window.Hammer = Hammer;
  17162. // requireJS module definition
  17163. if(typeof window.define === 'function' && window.define.amd) {
  17164. window.define('hammer', [], function() {
  17165. return Hammer;
  17166. });
  17167. }
  17168. }
  17169. })(this);
  17170. },{}],4:[function(require,module,exports){
  17171. //! moment.js
  17172. //! version : 2.5.1
  17173. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  17174. //! license : MIT
  17175. //! momentjs.com
  17176. (function (undefined) {
  17177. /************************************
  17178. Constants
  17179. ************************************/
  17180. var moment,
  17181. VERSION = "2.5.1",
  17182. global = this,
  17183. round = Math.round,
  17184. i,
  17185. YEAR = 0,
  17186. MONTH = 1,
  17187. DATE = 2,
  17188. HOUR = 3,
  17189. MINUTE = 4,
  17190. SECOND = 5,
  17191. MILLISECOND = 6,
  17192. // internal storage for language config files
  17193. languages = {},
  17194. // moment internal properties
  17195. momentProperties = {
  17196. _isAMomentObject: null,
  17197. _i : null,
  17198. _f : null,
  17199. _l : null,
  17200. _strict : null,
  17201. _isUTC : null,
  17202. _offset : null, // optional. Combine with _isUTC
  17203. _pf : null,
  17204. _lang : null // optional
  17205. },
  17206. // check for nodeJS
  17207. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  17208. // ASP.NET json date format regex
  17209. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  17210. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  17211. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  17212. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  17213. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  17214. // format tokens
  17215. formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,
  17216. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  17217. // parsing token regexes
  17218. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  17219. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  17220. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  17221. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  17222. parseTokenDigits = /\d+/, // nonzero number of digits
  17223. 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.
  17224. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  17225. parseTokenT = /T/i, // T (ISO separator)
  17226. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  17227. //strict parsing regexes
  17228. parseTokenOneDigit = /\d/, // 0 - 9
  17229. parseTokenTwoDigits = /\d\d/, // 00 - 99
  17230. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  17231. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  17232. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  17233. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  17234. // iso 8601 regex
  17235. // 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)
  17236. 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)?)?$/,
  17237. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  17238. isoDates = [
  17239. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  17240. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  17241. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  17242. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  17243. ['YYYY-DDD', /\d{4}-\d{3}/]
  17244. ],
  17245. // iso time formats and regexes
  17246. isoTimes = [
  17247. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  17248. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  17249. ['HH:mm', /(T| )\d\d:\d\d/],
  17250. ['HH', /(T| )\d\d/]
  17251. ],
  17252. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  17253. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  17254. // getter and setter names
  17255. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  17256. unitMillisecondFactors = {
  17257. 'Milliseconds' : 1,
  17258. 'Seconds' : 1e3,
  17259. 'Minutes' : 6e4,
  17260. 'Hours' : 36e5,
  17261. 'Days' : 864e5,
  17262. 'Months' : 2592e6,
  17263. 'Years' : 31536e6
  17264. },
  17265. unitAliases = {
  17266. ms : 'millisecond',
  17267. s : 'second',
  17268. m : 'minute',
  17269. h : 'hour',
  17270. d : 'day',
  17271. D : 'date',
  17272. w : 'week',
  17273. W : 'isoWeek',
  17274. M : 'month',
  17275. y : 'year',
  17276. DDD : 'dayOfYear',
  17277. e : 'weekday',
  17278. E : 'isoWeekday',
  17279. gg: 'weekYear',
  17280. GG: 'isoWeekYear'
  17281. },
  17282. camelFunctions = {
  17283. dayofyear : 'dayOfYear',
  17284. isoweekday : 'isoWeekday',
  17285. isoweek : 'isoWeek',
  17286. weekyear : 'weekYear',
  17287. isoweekyear : 'isoWeekYear'
  17288. },
  17289. // format function strings
  17290. formatFunctions = {},
  17291. // tokens to ordinalize and pad
  17292. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  17293. paddedTokens = 'M D H h m s w W'.split(' '),
  17294. formatTokenFunctions = {
  17295. M : function () {
  17296. return this.month() + 1;
  17297. },
  17298. MMM : function (format) {
  17299. return this.lang().monthsShort(this, format);
  17300. },
  17301. MMMM : function (format) {
  17302. return this.lang().months(this, format);
  17303. },
  17304. D : function () {
  17305. return this.date();
  17306. },
  17307. DDD : function () {
  17308. return this.dayOfYear();
  17309. },
  17310. d : function () {
  17311. return this.day();
  17312. },
  17313. dd : function (format) {
  17314. return this.lang().weekdaysMin(this, format);
  17315. },
  17316. ddd : function (format) {
  17317. return this.lang().weekdaysShort(this, format);
  17318. },
  17319. dddd : function (format) {
  17320. return this.lang().weekdays(this, format);
  17321. },
  17322. w : function () {
  17323. return this.week();
  17324. },
  17325. W : function () {
  17326. return this.isoWeek();
  17327. },
  17328. YY : function () {
  17329. return leftZeroFill(this.year() % 100, 2);
  17330. },
  17331. YYYY : function () {
  17332. return leftZeroFill(this.year(), 4);
  17333. },
  17334. YYYYY : function () {
  17335. return leftZeroFill(this.year(), 5);
  17336. },
  17337. YYYYYY : function () {
  17338. var y = this.year(), sign = y >= 0 ? '+' : '-';
  17339. return sign + leftZeroFill(Math.abs(y), 6);
  17340. },
  17341. gg : function () {
  17342. return leftZeroFill(this.weekYear() % 100, 2);
  17343. },
  17344. gggg : function () {
  17345. return leftZeroFill(this.weekYear(), 4);
  17346. },
  17347. ggggg : function () {
  17348. return leftZeroFill(this.weekYear(), 5);
  17349. },
  17350. GG : function () {
  17351. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17352. },
  17353. GGGG : function () {
  17354. return leftZeroFill(this.isoWeekYear(), 4);
  17355. },
  17356. GGGGG : function () {
  17357. return leftZeroFill(this.isoWeekYear(), 5);
  17358. },
  17359. e : function () {
  17360. return this.weekday();
  17361. },
  17362. E : function () {
  17363. return this.isoWeekday();
  17364. },
  17365. a : function () {
  17366. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17367. },
  17368. A : function () {
  17369. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17370. },
  17371. H : function () {
  17372. return this.hours();
  17373. },
  17374. h : function () {
  17375. return this.hours() % 12 || 12;
  17376. },
  17377. m : function () {
  17378. return this.minutes();
  17379. },
  17380. s : function () {
  17381. return this.seconds();
  17382. },
  17383. S : function () {
  17384. return toInt(this.milliseconds() / 100);
  17385. },
  17386. SS : function () {
  17387. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17388. },
  17389. SSS : function () {
  17390. return leftZeroFill(this.milliseconds(), 3);
  17391. },
  17392. SSSS : function () {
  17393. return leftZeroFill(this.milliseconds(), 3);
  17394. },
  17395. Z : function () {
  17396. var a = -this.zone(),
  17397. b = "+";
  17398. if (a < 0) {
  17399. a = -a;
  17400. b = "-";
  17401. }
  17402. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  17403. },
  17404. ZZ : function () {
  17405. var a = -this.zone(),
  17406. b = "+";
  17407. if (a < 0) {
  17408. a = -a;
  17409. b = "-";
  17410. }
  17411. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  17412. },
  17413. z : function () {
  17414. return this.zoneAbbr();
  17415. },
  17416. zz : function () {
  17417. return this.zoneName();
  17418. },
  17419. X : function () {
  17420. return this.unix();
  17421. },
  17422. Q : function () {
  17423. return this.quarter();
  17424. }
  17425. },
  17426. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  17427. function defaultParsingFlags() {
  17428. // We need to deep clone this object, and es5 standard is not very
  17429. // helpful.
  17430. return {
  17431. empty : false,
  17432. unusedTokens : [],
  17433. unusedInput : [],
  17434. overflow : -2,
  17435. charsLeftOver : 0,
  17436. nullInput : false,
  17437. invalidMonth : null,
  17438. invalidFormat : false,
  17439. userInvalidated : false,
  17440. iso: false
  17441. };
  17442. }
  17443. function padToken(func, count) {
  17444. return function (a) {
  17445. return leftZeroFill(func.call(this, a), count);
  17446. };
  17447. }
  17448. function ordinalizeToken(func, period) {
  17449. return function (a) {
  17450. return this.lang().ordinal(func.call(this, a), period);
  17451. };
  17452. }
  17453. while (ordinalizeTokens.length) {
  17454. i = ordinalizeTokens.pop();
  17455. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  17456. }
  17457. while (paddedTokens.length) {
  17458. i = paddedTokens.pop();
  17459. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  17460. }
  17461. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  17462. /************************************
  17463. Constructors
  17464. ************************************/
  17465. function Language() {
  17466. }
  17467. // Moment prototype object
  17468. function Moment(config) {
  17469. checkOverflow(config);
  17470. extend(this, config);
  17471. }
  17472. // Duration Constructor
  17473. function Duration(duration) {
  17474. var normalizedInput = normalizeObjectUnits(duration),
  17475. years = normalizedInput.year || 0,
  17476. months = normalizedInput.month || 0,
  17477. weeks = normalizedInput.week || 0,
  17478. days = normalizedInput.day || 0,
  17479. hours = normalizedInput.hour || 0,
  17480. minutes = normalizedInput.minute || 0,
  17481. seconds = normalizedInput.second || 0,
  17482. milliseconds = normalizedInput.millisecond || 0;
  17483. // representation for dateAddRemove
  17484. this._milliseconds = +milliseconds +
  17485. seconds * 1e3 + // 1000
  17486. minutes * 6e4 + // 1000 * 60
  17487. hours * 36e5; // 1000 * 60 * 60
  17488. // Because of dateAddRemove treats 24 hours as different from a
  17489. // day when working around DST, we need to store them separately
  17490. this._days = +days +
  17491. weeks * 7;
  17492. // It is impossible translate months into days without knowing
  17493. // which months you are are talking about, so we have to store
  17494. // it separately.
  17495. this._months = +months +
  17496. years * 12;
  17497. this._data = {};
  17498. this._bubble();
  17499. }
  17500. /************************************
  17501. Helpers
  17502. ************************************/
  17503. function extend(a, b) {
  17504. for (var i in b) {
  17505. if (b.hasOwnProperty(i)) {
  17506. a[i] = b[i];
  17507. }
  17508. }
  17509. if (b.hasOwnProperty("toString")) {
  17510. a.toString = b.toString;
  17511. }
  17512. if (b.hasOwnProperty("valueOf")) {
  17513. a.valueOf = b.valueOf;
  17514. }
  17515. return a;
  17516. }
  17517. function cloneMoment(m) {
  17518. var result = {}, i;
  17519. for (i in m) {
  17520. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17521. result[i] = m[i];
  17522. }
  17523. }
  17524. return result;
  17525. }
  17526. function absRound(number) {
  17527. if (number < 0) {
  17528. return Math.ceil(number);
  17529. } else {
  17530. return Math.floor(number);
  17531. }
  17532. }
  17533. // left zero fill a number
  17534. // see http://jsperf.com/left-zero-filling for performance comparison
  17535. function leftZeroFill(number, targetLength, forceSign) {
  17536. var output = '' + Math.abs(number),
  17537. sign = number >= 0;
  17538. while (output.length < targetLength) {
  17539. output = '0' + output;
  17540. }
  17541. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17542. }
  17543. // helper function for _.addTime and _.subtractTime
  17544. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  17545. var milliseconds = duration._milliseconds,
  17546. days = duration._days,
  17547. months = duration._months,
  17548. minutes,
  17549. hours;
  17550. if (milliseconds) {
  17551. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17552. }
  17553. // store the minutes and hours so we can restore them
  17554. if (days || months) {
  17555. minutes = mom.minute();
  17556. hours = mom.hour();
  17557. }
  17558. if (days) {
  17559. mom.date(mom.date() + days * isAdding);
  17560. }
  17561. if (months) {
  17562. mom.month(mom.month() + months * isAdding);
  17563. }
  17564. if (milliseconds && !ignoreUpdateOffset) {
  17565. moment.updateOffset(mom);
  17566. }
  17567. // restore the minutes and hours after possibly changing dst
  17568. if (days || months) {
  17569. mom.minute(minutes);
  17570. mom.hour(hours);
  17571. }
  17572. }
  17573. // check if is an array
  17574. function isArray(input) {
  17575. return Object.prototype.toString.call(input) === '[object Array]';
  17576. }
  17577. function isDate(input) {
  17578. return Object.prototype.toString.call(input) === '[object Date]' ||
  17579. input instanceof Date;
  17580. }
  17581. // compare two arrays, return the number of differences
  17582. function compareArrays(array1, array2, dontConvert) {
  17583. var len = Math.min(array1.length, array2.length),
  17584. lengthDiff = Math.abs(array1.length - array2.length),
  17585. diffs = 0,
  17586. i;
  17587. for (i = 0; i < len; i++) {
  17588. if ((dontConvert && array1[i] !== array2[i]) ||
  17589. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17590. diffs++;
  17591. }
  17592. }
  17593. return diffs + lengthDiff;
  17594. }
  17595. function normalizeUnits(units) {
  17596. if (units) {
  17597. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17598. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17599. }
  17600. return units;
  17601. }
  17602. function normalizeObjectUnits(inputObject) {
  17603. var normalizedInput = {},
  17604. normalizedProp,
  17605. prop;
  17606. for (prop in inputObject) {
  17607. if (inputObject.hasOwnProperty(prop)) {
  17608. normalizedProp = normalizeUnits(prop);
  17609. if (normalizedProp) {
  17610. normalizedInput[normalizedProp] = inputObject[prop];
  17611. }
  17612. }
  17613. }
  17614. return normalizedInput;
  17615. }
  17616. function makeList(field) {
  17617. var count, setter;
  17618. if (field.indexOf('week') === 0) {
  17619. count = 7;
  17620. setter = 'day';
  17621. }
  17622. else if (field.indexOf('month') === 0) {
  17623. count = 12;
  17624. setter = 'month';
  17625. }
  17626. else {
  17627. return;
  17628. }
  17629. moment[field] = function (format, index) {
  17630. var i, getter,
  17631. method = moment.fn._lang[field],
  17632. results = [];
  17633. if (typeof format === 'number') {
  17634. index = format;
  17635. format = undefined;
  17636. }
  17637. getter = function (i) {
  17638. var m = moment().utc().set(setter, i);
  17639. return method.call(moment.fn._lang, m, format || '');
  17640. };
  17641. if (index != null) {
  17642. return getter(index);
  17643. }
  17644. else {
  17645. for (i = 0; i < count; i++) {
  17646. results.push(getter(i));
  17647. }
  17648. return results;
  17649. }
  17650. };
  17651. }
  17652. function toInt(argumentForCoercion) {
  17653. var coercedNumber = +argumentForCoercion,
  17654. value = 0;
  17655. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17656. if (coercedNumber >= 0) {
  17657. value = Math.floor(coercedNumber);
  17658. } else {
  17659. value = Math.ceil(coercedNumber);
  17660. }
  17661. }
  17662. return value;
  17663. }
  17664. function daysInMonth(year, month) {
  17665. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17666. }
  17667. function daysInYear(year) {
  17668. return isLeapYear(year) ? 366 : 365;
  17669. }
  17670. function isLeapYear(year) {
  17671. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17672. }
  17673. function checkOverflow(m) {
  17674. var overflow;
  17675. if (m._a && m._pf.overflow === -2) {
  17676. overflow =
  17677. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17678. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17679. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17680. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17681. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17682. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17683. -1;
  17684. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17685. overflow = DATE;
  17686. }
  17687. m._pf.overflow = overflow;
  17688. }
  17689. }
  17690. function isValid(m) {
  17691. if (m._isValid == null) {
  17692. m._isValid = !isNaN(m._d.getTime()) &&
  17693. m._pf.overflow < 0 &&
  17694. !m._pf.empty &&
  17695. !m._pf.invalidMonth &&
  17696. !m._pf.nullInput &&
  17697. !m._pf.invalidFormat &&
  17698. !m._pf.userInvalidated;
  17699. if (m._strict) {
  17700. m._isValid = m._isValid &&
  17701. m._pf.charsLeftOver === 0 &&
  17702. m._pf.unusedTokens.length === 0;
  17703. }
  17704. }
  17705. return m._isValid;
  17706. }
  17707. function normalizeLanguage(key) {
  17708. return key ? key.toLowerCase().replace('_', '-') : key;
  17709. }
  17710. // Return a moment from input, that is local/utc/zone equivalent to model.
  17711. function makeAs(input, model) {
  17712. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17713. moment(input).local();
  17714. }
  17715. /************************************
  17716. Languages
  17717. ************************************/
  17718. extend(Language.prototype, {
  17719. set : function (config) {
  17720. var prop, i;
  17721. for (i in config) {
  17722. prop = config[i];
  17723. if (typeof prop === 'function') {
  17724. this[i] = prop;
  17725. } else {
  17726. this['_' + i] = prop;
  17727. }
  17728. }
  17729. },
  17730. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17731. months : function (m) {
  17732. return this._months[m.month()];
  17733. },
  17734. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17735. monthsShort : function (m) {
  17736. return this._monthsShort[m.month()];
  17737. },
  17738. monthsParse : function (monthName) {
  17739. var i, mom, regex;
  17740. if (!this._monthsParse) {
  17741. this._monthsParse = [];
  17742. }
  17743. for (i = 0; i < 12; i++) {
  17744. // make the regex if we don't have it already
  17745. if (!this._monthsParse[i]) {
  17746. mom = moment.utc([2000, i]);
  17747. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17748. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17749. }
  17750. // test the regex
  17751. if (this._monthsParse[i].test(monthName)) {
  17752. return i;
  17753. }
  17754. }
  17755. },
  17756. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17757. weekdays : function (m) {
  17758. return this._weekdays[m.day()];
  17759. },
  17760. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17761. weekdaysShort : function (m) {
  17762. return this._weekdaysShort[m.day()];
  17763. },
  17764. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17765. weekdaysMin : function (m) {
  17766. return this._weekdaysMin[m.day()];
  17767. },
  17768. weekdaysParse : function (weekdayName) {
  17769. var i, mom, regex;
  17770. if (!this._weekdaysParse) {
  17771. this._weekdaysParse = [];
  17772. }
  17773. for (i = 0; i < 7; i++) {
  17774. // make the regex if we don't have it already
  17775. if (!this._weekdaysParse[i]) {
  17776. mom = moment([2000, 1]).day(i);
  17777. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17778. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17779. }
  17780. // test the regex
  17781. if (this._weekdaysParse[i].test(weekdayName)) {
  17782. return i;
  17783. }
  17784. }
  17785. },
  17786. _longDateFormat : {
  17787. LT : "h:mm A",
  17788. L : "MM/DD/YYYY",
  17789. LL : "MMMM D YYYY",
  17790. LLL : "MMMM D YYYY LT",
  17791. LLLL : "dddd, MMMM D YYYY LT"
  17792. },
  17793. longDateFormat : function (key) {
  17794. var output = this._longDateFormat[key];
  17795. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17796. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17797. return val.slice(1);
  17798. });
  17799. this._longDateFormat[key] = output;
  17800. }
  17801. return output;
  17802. },
  17803. isPM : function (input) {
  17804. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17805. // Using charAt should be more compatible.
  17806. return ((input + '').toLowerCase().charAt(0) === 'p');
  17807. },
  17808. _meridiemParse : /[ap]\.?m?\.?/i,
  17809. meridiem : function (hours, minutes, isLower) {
  17810. if (hours > 11) {
  17811. return isLower ? 'pm' : 'PM';
  17812. } else {
  17813. return isLower ? 'am' : 'AM';
  17814. }
  17815. },
  17816. _calendar : {
  17817. sameDay : '[Today at] LT',
  17818. nextDay : '[Tomorrow at] LT',
  17819. nextWeek : 'dddd [at] LT',
  17820. lastDay : '[Yesterday at] LT',
  17821. lastWeek : '[Last] dddd [at] LT',
  17822. sameElse : 'L'
  17823. },
  17824. calendar : function (key, mom) {
  17825. var output = this._calendar[key];
  17826. return typeof output === 'function' ? output.apply(mom) : output;
  17827. },
  17828. _relativeTime : {
  17829. future : "in %s",
  17830. past : "%s ago",
  17831. s : "a few seconds",
  17832. m : "a minute",
  17833. mm : "%d minutes",
  17834. h : "an hour",
  17835. hh : "%d hours",
  17836. d : "a day",
  17837. dd : "%d days",
  17838. M : "a month",
  17839. MM : "%d months",
  17840. y : "a year",
  17841. yy : "%d years"
  17842. },
  17843. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17844. var output = this._relativeTime[string];
  17845. return (typeof output === 'function') ?
  17846. output(number, withoutSuffix, string, isFuture) :
  17847. output.replace(/%d/i, number);
  17848. },
  17849. pastFuture : function (diff, output) {
  17850. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17851. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17852. },
  17853. ordinal : function (number) {
  17854. return this._ordinal.replace("%d", number);
  17855. },
  17856. _ordinal : "%d",
  17857. preparse : function (string) {
  17858. return string;
  17859. },
  17860. postformat : function (string) {
  17861. return string;
  17862. },
  17863. week : function (mom) {
  17864. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17865. },
  17866. _week : {
  17867. dow : 0, // Sunday is the first day of the week.
  17868. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17869. },
  17870. _invalidDate: 'Invalid date',
  17871. invalidDate: function () {
  17872. return this._invalidDate;
  17873. }
  17874. });
  17875. // Loads a language definition into the `languages` cache. The function
  17876. // takes a key and optionally values. If not in the browser and no values
  17877. // are provided, it will load the language file module. As a convenience,
  17878. // this function also returns the language values.
  17879. function loadLang(key, values) {
  17880. values.abbr = key;
  17881. if (!languages[key]) {
  17882. languages[key] = new Language();
  17883. }
  17884. languages[key].set(values);
  17885. return languages[key];
  17886. }
  17887. // Remove a language from the `languages` cache. Mostly useful in tests.
  17888. function unloadLang(key) {
  17889. delete languages[key];
  17890. }
  17891. // Determines which language definition to use and returns it.
  17892. //
  17893. // With no parameters, it will return the global language. If you
  17894. // pass in a language key, such as 'en', it will return the
  17895. // definition for 'en', so long as 'en' has already been loaded using
  17896. // moment.lang.
  17897. function getLangDefinition(key) {
  17898. var i = 0, j, lang, next, split,
  17899. get = function (k) {
  17900. if (!languages[k] && hasModule) {
  17901. try {
  17902. require('./lang/' + k);
  17903. } catch (e) { }
  17904. }
  17905. return languages[k];
  17906. };
  17907. if (!key) {
  17908. return moment.fn._lang;
  17909. }
  17910. if (!isArray(key)) {
  17911. //short-circuit everything else
  17912. lang = get(key);
  17913. if (lang) {
  17914. return lang;
  17915. }
  17916. key = [key];
  17917. }
  17918. //pick the language from the array
  17919. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17920. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17921. while (i < key.length) {
  17922. split = normalizeLanguage(key[i]).split('-');
  17923. j = split.length;
  17924. next = normalizeLanguage(key[i + 1]);
  17925. next = next ? next.split('-') : null;
  17926. while (j > 0) {
  17927. lang = get(split.slice(0, j).join('-'));
  17928. if (lang) {
  17929. return lang;
  17930. }
  17931. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17932. //the next array item is better than a shallower substring of this one
  17933. break;
  17934. }
  17935. j--;
  17936. }
  17937. i++;
  17938. }
  17939. return moment.fn._lang;
  17940. }
  17941. /************************************
  17942. Formatting
  17943. ************************************/
  17944. function removeFormattingTokens(input) {
  17945. if (input.match(/\[[\s\S]/)) {
  17946. return input.replace(/^\[|\]$/g, "");
  17947. }
  17948. return input.replace(/\\/g, "");
  17949. }
  17950. function makeFormatFunction(format) {
  17951. var array = format.match(formattingTokens), i, length;
  17952. for (i = 0, length = array.length; i < length; i++) {
  17953. if (formatTokenFunctions[array[i]]) {
  17954. array[i] = formatTokenFunctions[array[i]];
  17955. } else {
  17956. array[i] = removeFormattingTokens(array[i]);
  17957. }
  17958. }
  17959. return function (mom) {
  17960. var output = "";
  17961. for (i = 0; i < length; i++) {
  17962. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  17963. }
  17964. return output;
  17965. };
  17966. }
  17967. // format date using native date object
  17968. function formatMoment(m, format) {
  17969. if (!m.isValid()) {
  17970. return m.lang().invalidDate();
  17971. }
  17972. format = expandFormat(format, m.lang());
  17973. if (!formatFunctions[format]) {
  17974. formatFunctions[format] = makeFormatFunction(format);
  17975. }
  17976. return formatFunctions[format](m);
  17977. }
  17978. function expandFormat(format, lang) {
  17979. var i = 5;
  17980. function replaceLongDateFormatTokens(input) {
  17981. return lang.longDateFormat(input) || input;
  17982. }
  17983. localFormattingTokens.lastIndex = 0;
  17984. while (i >= 0 && localFormattingTokens.test(format)) {
  17985. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  17986. localFormattingTokens.lastIndex = 0;
  17987. i -= 1;
  17988. }
  17989. return format;
  17990. }
  17991. /************************************
  17992. Parsing
  17993. ************************************/
  17994. // get the regex to find the next token
  17995. function getParseRegexForToken(token, config) {
  17996. var a, strict = config._strict;
  17997. switch (token) {
  17998. case 'DDDD':
  17999. return parseTokenThreeDigits;
  18000. case 'YYYY':
  18001. case 'GGGG':
  18002. case 'gggg':
  18003. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  18004. case 'Y':
  18005. case 'G':
  18006. case 'g':
  18007. return parseTokenSignedNumber;
  18008. case 'YYYYYY':
  18009. case 'YYYYY':
  18010. case 'GGGGG':
  18011. case 'ggggg':
  18012. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  18013. case 'S':
  18014. if (strict) { return parseTokenOneDigit; }
  18015. /* falls through */
  18016. case 'SS':
  18017. if (strict) { return parseTokenTwoDigits; }
  18018. /* falls through */
  18019. case 'SSS':
  18020. if (strict) { return parseTokenThreeDigits; }
  18021. /* falls through */
  18022. case 'DDD':
  18023. return parseTokenOneToThreeDigits;
  18024. case 'MMM':
  18025. case 'MMMM':
  18026. case 'dd':
  18027. case 'ddd':
  18028. case 'dddd':
  18029. return parseTokenWord;
  18030. case 'a':
  18031. case 'A':
  18032. return getLangDefinition(config._l)._meridiemParse;
  18033. case 'X':
  18034. return parseTokenTimestampMs;
  18035. case 'Z':
  18036. case 'ZZ':
  18037. return parseTokenTimezone;
  18038. case 'T':
  18039. return parseTokenT;
  18040. case 'SSSS':
  18041. return parseTokenDigits;
  18042. case 'MM':
  18043. case 'DD':
  18044. case 'YY':
  18045. case 'GG':
  18046. case 'gg':
  18047. case 'HH':
  18048. case 'hh':
  18049. case 'mm':
  18050. case 'ss':
  18051. case 'ww':
  18052. case 'WW':
  18053. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  18054. case 'M':
  18055. case 'D':
  18056. case 'd':
  18057. case 'H':
  18058. case 'h':
  18059. case 'm':
  18060. case 's':
  18061. case 'w':
  18062. case 'W':
  18063. case 'e':
  18064. case 'E':
  18065. return parseTokenOneOrTwoDigits;
  18066. default :
  18067. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  18068. return a;
  18069. }
  18070. }
  18071. function timezoneMinutesFromString(string) {
  18072. string = string || "";
  18073. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  18074. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  18075. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  18076. minutes = +(parts[1] * 60) + toInt(parts[2]);
  18077. return parts[0] === '+' ? -minutes : minutes;
  18078. }
  18079. // function to convert string input to date
  18080. function addTimeToArrayFromToken(token, input, config) {
  18081. var a, datePartArray = config._a;
  18082. switch (token) {
  18083. // MONTH
  18084. case 'M' : // fall through to MM
  18085. case 'MM' :
  18086. if (input != null) {
  18087. datePartArray[MONTH] = toInt(input) - 1;
  18088. }
  18089. break;
  18090. case 'MMM' : // fall through to MMMM
  18091. case 'MMMM' :
  18092. a = getLangDefinition(config._l).monthsParse(input);
  18093. // if we didn't find a month name, mark the date as invalid.
  18094. if (a != null) {
  18095. datePartArray[MONTH] = a;
  18096. } else {
  18097. config._pf.invalidMonth = input;
  18098. }
  18099. break;
  18100. // DAY OF MONTH
  18101. case 'D' : // fall through to DD
  18102. case 'DD' :
  18103. if (input != null) {
  18104. datePartArray[DATE] = toInt(input);
  18105. }
  18106. break;
  18107. // DAY OF YEAR
  18108. case 'DDD' : // fall through to DDDD
  18109. case 'DDDD' :
  18110. if (input != null) {
  18111. config._dayOfYear = toInt(input);
  18112. }
  18113. break;
  18114. // YEAR
  18115. case 'YY' :
  18116. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  18117. break;
  18118. case 'YYYY' :
  18119. case 'YYYYY' :
  18120. case 'YYYYYY' :
  18121. datePartArray[YEAR] = toInt(input);
  18122. break;
  18123. // AM / PM
  18124. case 'a' : // fall through to A
  18125. case 'A' :
  18126. config._isPm = getLangDefinition(config._l).isPM(input);
  18127. break;
  18128. // 24 HOUR
  18129. case 'H' : // fall through to hh
  18130. case 'HH' : // fall through to hh
  18131. case 'h' : // fall through to hh
  18132. case 'hh' :
  18133. datePartArray[HOUR] = toInt(input);
  18134. break;
  18135. // MINUTE
  18136. case 'm' : // fall through to mm
  18137. case 'mm' :
  18138. datePartArray[MINUTE] = toInt(input);
  18139. break;
  18140. // SECOND
  18141. case 's' : // fall through to ss
  18142. case 'ss' :
  18143. datePartArray[SECOND] = toInt(input);
  18144. break;
  18145. // MILLISECOND
  18146. case 'S' :
  18147. case 'SS' :
  18148. case 'SSS' :
  18149. case 'SSSS' :
  18150. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  18151. break;
  18152. // UNIX TIMESTAMP WITH MS
  18153. case 'X':
  18154. config._d = new Date(parseFloat(input) * 1000);
  18155. break;
  18156. // TIMEZONE
  18157. case 'Z' : // fall through to ZZ
  18158. case 'ZZ' :
  18159. config._useUTC = true;
  18160. config._tzm = timezoneMinutesFromString(input);
  18161. break;
  18162. case 'w':
  18163. case 'ww':
  18164. case 'W':
  18165. case 'WW':
  18166. case 'd':
  18167. case 'dd':
  18168. case 'ddd':
  18169. case 'dddd':
  18170. case 'e':
  18171. case 'E':
  18172. token = token.substr(0, 1);
  18173. /* falls through */
  18174. case 'gg':
  18175. case 'gggg':
  18176. case 'GG':
  18177. case 'GGGG':
  18178. case 'GGGGG':
  18179. token = token.substr(0, 2);
  18180. if (input) {
  18181. config._w = config._w || {};
  18182. config._w[token] = input;
  18183. }
  18184. break;
  18185. }
  18186. }
  18187. // convert an array to a date.
  18188. // the array should mirror the parameters below
  18189. // note: all values past the year are optional and will default to the lowest possible value.
  18190. // [year, month, day , hour, minute, second, millisecond]
  18191. function dateFromConfig(config) {
  18192. var i, date, input = [], currentDate,
  18193. yearToUse, fixYear, w, temp, lang, weekday, week;
  18194. if (config._d) {
  18195. return;
  18196. }
  18197. currentDate = currentDateArray(config);
  18198. //compute day of the year from weeks and weekdays
  18199. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  18200. fixYear = function (val) {
  18201. var int_val = parseInt(val, 10);
  18202. return val ?
  18203. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  18204. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  18205. };
  18206. w = config._w;
  18207. if (w.GG != null || w.W != null || w.E != null) {
  18208. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  18209. }
  18210. else {
  18211. lang = getLangDefinition(config._l);
  18212. weekday = w.d != null ? parseWeekday(w.d, lang) :
  18213. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  18214. week = parseInt(w.w, 10) || 1;
  18215. //if we're parsing 'd', then the low day numbers may be next week
  18216. if (w.d != null && weekday < lang._week.dow) {
  18217. week++;
  18218. }
  18219. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  18220. }
  18221. config._a[YEAR] = temp.year;
  18222. config._dayOfYear = temp.dayOfYear;
  18223. }
  18224. //if the day of the year is set, figure out what it is
  18225. if (config._dayOfYear) {
  18226. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  18227. if (config._dayOfYear > daysInYear(yearToUse)) {
  18228. config._pf._overflowDayOfYear = true;
  18229. }
  18230. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  18231. config._a[MONTH] = date.getUTCMonth();
  18232. config._a[DATE] = date.getUTCDate();
  18233. }
  18234. // Default to current date.
  18235. // * if no year, month, day of month are given, default to today
  18236. // * if day of month is given, default month and year
  18237. // * if month is given, default only year
  18238. // * if year is given, don't default anything
  18239. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  18240. config._a[i] = input[i] = currentDate[i];
  18241. }
  18242. // Zero out whatever was not defaulted, including time
  18243. for (; i < 7; i++) {
  18244. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  18245. }
  18246. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  18247. input[HOUR] += toInt((config._tzm || 0) / 60);
  18248. input[MINUTE] += toInt((config._tzm || 0) % 60);
  18249. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  18250. }
  18251. function dateFromObject(config) {
  18252. var normalizedInput;
  18253. if (config._d) {
  18254. return;
  18255. }
  18256. normalizedInput = normalizeObjectUnits(config._i);
  18257. config._a = [
  18258. normalizedInput.year,
  18259. normalizedInput.month,
  18260. normalizedInput.day,
  18261. normalizedInput.hour,
  18262. normalizedInput.minute,
  18263. normalizedInput.second,
  18264. normalizedInput.millisecond
  18265. ];
  18266. dateFromConfig(config);
  18267. }
  18268. function currentDateArray(config) {
  18269. var now = new Date();
  18270. if (config._useUTC) {
  18271. return [
  18272. now.getUTCFullYear(),
  18273. now.getUTCMonth(),
  18274. now.getUTCDate()
  18275. ];
  18276. } else {
  18277. return [now.getFullYear(), now.getMonth(), now.getDate()];
  18278. }
  18279. }
  18280. // date from string and format string
  18281. function makeDateFromStringAndFormat(config) {
  18282. config._a = [];
  18283. config._pf.empty = true;
  18284. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  18285. var lang = getLangDefinition(config._l),
  18286. string = '' + config._i,
  18287. i, parsedInput, tokens, token, skipped,
  18288. stringLength = string.length,
  18289. totalParsedInputLength = 0;
  18290. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  18291. for (i = 0; i < tokens.length; i++) {
  18292. token = tokens[i];
  18293. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  18294. if (parsedInput) {
  18295. skipped = string.substr(0, string.indexOf(parsedInput));
  18296. if (skipped.length > 0) {
  18297. config._pf.unusedInput.push(skipped);
  18298. }
  18299. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  18300. totalParsedInputLength += parsedInput.length;
  18301. }
  18302. // don't parse if it's not a known token
  18303. if (formatTokenFunctions[token]) {
  18304. if (parsedInput) {
  18305. config._pf.empty = false;
  18306. }
  18307. else {
  18308. config._pf.unusedTokens.push(token);
  18309. }
  18310. addTimeToArrayFromToken(token, parsedInput, config);
  18311. }
  18312. else if (config._strict && !parsedInput) {
  18313. config._pf.unusedTokens.push(token);
  18314. }
  18315. }
  18316. // add remaining unparsed input length to the string
  18317. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  18318. if (string.length > 0) {
  18319. config._pf.unusedInput.push(string);
  18320. }
  18321. // handle am pm
  18322. if (config._isPm && config._a[HOUR] < 12) {
  18323. config._a[HOUR] += 12;
  18324. }
  18325. // if is 12 am, change hours to 0
  18326. if (config._isPm === false && config._a[HOUR] === 12) {
  18327. config._a[HOUR] = 0;
  18328. }
  18329. dateFromConfig(config);
  18330. checkOverflow(config);
  18331. }
  18332. function unescapeFormat(s) {
  18333. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  18334. return p1 || p2 || p3 || p4;
  18335. });
  18336. }
  18337. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  18338. function regexpEscape(s) {
  18339. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18340. }
  18341. // date from string and array of format strings
  18342. function makeDateFromStringAndArray(config) {
  18343. var tempConfig,
  18344. bestMoment,
  18345. scoreToBeat,
  18346. i,
  18347. currentScore;
  18348. if (config._f.length === 0) {
  18349. config._pf.invalidFormat = true;
  18350. config._d = new Date(NaN);
  18351. return;
  18352. }
  18353. for (i = 0; i < config._f.length; i++) {
  18354. currentScore = 0;
  18355. tempConfig = extend({}, config);
  18356. tempConfig._pf = defaultParsingFlags();
  18357. tempConfig._f = config._f[i];
  18358. makeDateFromStringAndFormat(tempConfig);
  18359. if (!isValid(tempConfig)) {
  18360. continue;
  18361. }
  18362. // if there is any input that was not parsed add a penalty for that format
  18363. currentScore += tempConfig._pf.charsLeftOver;
  18364. //or tokens
  18365. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18366. tempConfig._pf.score = currentScore;
  18367. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18368. scoreToBeat = currentScore;
  18369. bestMoment = tempConfig;
  18370. }
  18371. }
  18372. extend(config, bestMoment || tempConfig);
  18373. }
  18374. // date from iso format
  18375. function makeDateFromString(config) {
  18376. var i, l,
  18377. string = config._i,
  18378. match = isoRegex.exec(string);
  18379. if (match) {
  18380. config._pf.iso = true;
  18381. for (i = 0, l = isoDates.length; i < l; i++) {
  18382. if (isoDates[i][1].exec(string)) {
  18383. // match[5] should be "T" or undefined
  18384. config._f = isoDates[i][0] + (match[6] || " ");
  18385. break;
  18386. }
  18387. }
  18388. for (i = 0, l = isoTimes.length; i < l; i++) {
  18389. if (isoTimes[i][1].exec(string)) {
  18390. config._f += isoTimes[i][0];
  18391. break;
  18392. }
  18393. }
  18394. if (string.match(parseTokenTimezone)) {
  18395. config._f += "Z";
  18396. }
  18397. makeDateFromStringAndFormat(config);
  18398. }
  18399. else {
  18400. config._d = new Date(string);
  18401. }
  18402. }
  18403. function makeDateFromInput(config) {
  18404. var input = config._i,
  18405. matched = aspNetJsonRegex.exec(input);
  18406. if (input === undefined) {
  18407. config._d = new Date();
  18408. } else if (matched) {
  18409. config._d = new Date(+matched[1]);
  18410. } else if (typeof input === 'string') {
  18411. makeDateFromString(config);
  18412. } else if (isArray(input)) {
  18413. config._a = input.slice(0);
  18414. dateFromConfig(config);
  18415. } else if (isDate(input)) {
  18416. config._d = new Date(+input);
  18417. } else if (typeof(input) === 'object') {
  18418. dateFromObject(config);
  18419. } else {
  18420. config._d = new Date(input);
  18421. }
  18422. }
  18423. function makeDate(y, m, d, h, M, s, ms) {
  18424. //can't just apply() to create a date:
  18425. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  18426. var date = new Date(y, m, d, h, M, s, ms);
  18427. //the date constructor doesn't accept years < 1970
  18428. if (y < 1970) {
  18429. date.setFullYear(y);
  18430. }
  18431. return date;
  18432. }
  18433. function makeUTCDate(y) {
  18434. var date = new Date(Date.UTC.apply(null, arguments));
  18435. if (y < 1970) {
  18436. date.setUTCFullYear(y);
  18437. }
  18438. return date;
  18439. }
  18440. function parseWeekday(input, language) {
  18441. if (typeof input === 'string') {
  18442. if (!isNaN(input)) {
  18443. input = parseInt(input, 10);
  18444. }
  18445. else {
  18446. input = language.weekdaysParse(input);
  18447. if (typeof input !== 'number') {
  18448. return null;
  18449. }
  18450. }
  18451. }
  18452. return input;
  18453. }
  18454. /************************************
  18455. Relative Time
  18456. ************************************/
  18457. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  18458. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  18459. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  18460. }
  18461. function relativeTime(milliseconds, withoutSuffix, lang) {
  18462. var seconds = round(Math.abs(milliseconds) / 1000),
  18463. minutes = round(seconds / 60),
  18464. hours = round(minutes / 60),
  18465. days = round(hours / 24),
  18466. years = round(days / 365),
  18467. args = seconds < 45 && ['s', seconds] ||
  18468. minutes === 1 && ['m'] ||
  18469. minutes < 45 && ['mm', minutes] ||
  18470. hours === 1 && ['h'] ||
  18471. hours < 22 && ['hh', hours] ||
  18472. days === 1 && ['d'] ||
  18473. days <= 25 && ['dd', days] ||
  18474. days <= 45 && ['M'] ||
  18475. days < 345 && ['MM', round(days / 30)] ||
  18476. years === 1 && ['y'] || ['yy', years];
  18477. args[2] = withoutSuffix;
  18478. args[3] = milliseconds > 0;
  18479. args[4] = lang;
  18480. return substituteTimeAgo.apply({}, args);
  18481. }
  18482. /************************************
  18483. Week of Year
  18484. ************************************/
  18485. // firstDayOfWeek 0 = sun, 6 = sat
  18486. // the day of the week that starts the week
  18487. // (usually sunday or monday)
  18488. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18489. // the first week is the week that contains the first
  18490. // of this day of the week
  18491. // (eg. ISO weeks use thursday (4))
  18492. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18493. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18494. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18495. adjustedMoment;
  18496. if (daysToDayOfWeek > end) {
  18497. daysToDayOfWeek -= 7;
  18498. }
  18499. if (daysToDayOfWeek < end - 7) {
  18500. daysToDayOfWeek += 7;
  18501. }
  18502. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18503. return {
  18504. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18505. year: adjustedMoment.year()
  18506. };
  18507. }
  18508. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18509. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18510. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18511. weekday = weekday != null ? weekday : firstDayOfWeek;
  18512. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18513. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18514. return {
  18515. year: dayOfYear > 0 ? year : year - 1,
  18516. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18517. };
  18518. }
  18519. /************************************
  18520. Top Level Functions
  18521. ************************************/
  18522. function makeMoment(config) {
  18523. var input = config._i,
  18524. format = config._f;
  18525. if (input === null) {
  18526. return moment.invalid({nullInput: true});
  18527. }
  18528. if (typeof input === 'string') {
  18529. config._i = input = getLangDefinition().preparse(input);
  18530. }
  18531. if (moment.isMoment(input)) {
  18532. config = cloneMoment(input);
  18533. config._d = new Date(+input._d);
  18534. } else if (format) {
  18535. if (isArray(format)) {
  18536. makeDateFromStringAndArray(config);
  18537. } else {
  18538. makeDateFromStringAndFormat(config);
  18539. }
  18540. } else {
  18541. makeDateFromInput(config);
  18542. }
  18543. return new Moment(config);
  18544. }
  18545. moment = function (input, format, lang, strict) {
  18546. var c;
  18547. if (typeof(lang) === "boolean") {
  18548. strict = lang;
  18549. lang = undefined;
  18550. }
  18551. // object construction must be done this way.
  18552. // https://github.com/moment/moment/issues/1423
  18553. c = {};
  18554. c._isAMomentObject = true;
  18555. c._i = input;
  18556. c._f = format;
  18557. c._l = lang;
  18558. c._strict = strict;
  18559. c._isUTC = false;
  18560. c._pf = defaultParsingFlags();
  18561. return makeMoment(c);
  18562. };
  18563. // creating with utc
  18564. moment.utc = function (input, format, lang, strict) {
  18565. var c;
  18566. if (typeof(lang) === "boolean") {
  18567. strict = lang;
  18568. lang = undefined;
  18569. }
  18570. // object construction must be done this way.
  18571. // https://github.com/moment/moment/issues/1423
  18572. c = {};
  18573. c._isAMomentObject = true;
  18574. c._useUTC = true;
  18575. c._isUTC = true;
  18576. c._l = lang;
  18577. c._i = input;
  18578. c._f = format;
  18579. c._strict = strict;
  18580. c._pf = defaultParsingFlags();
  18581. return makeMoment(c).utc();
  18582. };
  18583. // creating with unix timestamp (in seconds)
  18584. moment.unix = function (input) {
  18585. return moment(input * 1000);
  18586. };
  18587. // duration
  18588. moment.duration = function (input, key) {
  18589. var duration = input,
  18590. // matching against regexp is expensive, do it on demand
  18591. match = null,
  18592. sign,
  18593. ret,
  18594. parseIso;
  18595. if (moment.isDuration(input)) {
  18596. duration = {
  18597. ms: input._milliseconds,
  18598. d: input._days,
  18599. M: input._months
  18600. };
  18601. } else if (typeof input === 'number') {
  18602. duration = {};
  18603. if (key) {
  18604. duration[key] = input;
  18605. } else {
  18606. duration.milliseconds = input;
  18607. }
  18608. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18609. sign = (match[1] === "-") ? -1 : 1;
  18610. duration = {
  18611. y: 0,
  18612. d: toInt(match[DATE]) * sign,
  18613. h: toInt(match[HOUR]) * sign,
  18614. m: toInt(match[MINUTE]) * sign,
  18615. s: toInt(match[SECOND]) * sign,
  18616. ms: toInt(match[MILLISECOND]) * sign
  18617. };
  18618. } else if (!!(match = isoDurationRegex.exec(input))) {
  18619. sign = (match[1] === "-") ? -1 : 1;
  18620. parseIso = function (inp) {
  18621. // We'd normally use ~~inp for this, but unfortunately it also
  18622. // converts floats to ints.
  18623. // inp may be undefined, so careful calling replace on it.
  18624. var res = inp && parseFloat(inp.replace(',', '.'));
  18625. // apply sign while we're at it
  18626. return (isNaN(res) ? 0 : res) * sign;
  18627. };
  18628. duration = {
  18629. y: parseIso(match[2]),
  18630. M: parseIso(match[3]),
  18631. d: parseIso(match[4]),
  18632. h: parseIso(match[5]),
  18633. m: parseIso(match[6]),
  18634. s: parseIso(match[7]),
  18635. w: parseIso(match[8])
  18636. };
  18637. }
  18638. ret = new Duration(duration);
  18639. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18640. ret._lang = input._lang;
  18641. }
  18642. return ret;
  18643. };
  18644. // version number
  18645. moment.version = VERSION;
  18646. // default format
  18647. moment.defaultFormat = isoFormat;
  18648. // This function will be called whenever a moment is mutated.
  18649. // It is intended to keep the offset in sync with the timezone.
  18650. moment.updateOffset = function () {};
  18651. // This function will load languages and then set the global language. If
  18652. // no arguments are passed in, it will simply return the current global
  18653. // language key.
  18654. moment.lang = function (key, values) {
  18655. var r;
  18656. if (!key) {
  18657. return moment.fn._lang._abbr;
  18658. }
  18659. if (values) {
  18660. loadLang(normalizeLanguage(key), values);
  18661. } else if (values === null) {
  18662. unloadLang(key);
  18663. key = 'en';
  18664. } else if (!languages[key]) {
  18665. getLangDefinition(key);
  18666. }
  18667. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18668. return r._abbr;
  18669. };
  18670. // returns language data
  18671. moment.langData = function (key) {
  18672. if (key && key._lang && key._lang._abbr) {
  18673. key = key._lang._abbr;
  18674. }
  18675. return getLangDefinition(key);
  18676. };
  18677. // compare moment object
  18678. moment.isMoment = function (obj) {
  18679. return obj instanceof Moment ||
  18680. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18681. };
  18682. // for typechecking Duration objects
  18683. moment.isDuration = function (obj) {
  18684. return obj instanceof Duration;
  18685. };
  18686. for (i = lists.length - 1; i >= 0; --i) {
  18687. makeList(lists[i]);
  18688. }
  18689. moment.normalizeUnits = function (units) {
  18690. return normalizeUnits(units);
  18691. };
  18692. moment.invalid = function (flags) {
  18693. var m = moment.utc(NaN);
  18694. if (flags != null) {
  18695. extend(m._pf, flags);
  18696. }
  18697. else {
  18698. m._pf.userInvalidated = true;
  18699. }
  18700. return m;
  18701. };
  18702. moment.parseZone = function (input) {
  18703. return moment(input).parseZone();
  18704. };
  18705. /************************************
  18706. Moment Prototype
  18707. ************************************/
  18708. extend(moment.fn = Moment.prototype, {
  18709. clone : function () {
  18710. return moment(this);
  18711. },
  18712. valueOf : function () {
  18713. return +this._d + ((this._offset || 0) * 60000);
  18714. },
  18715. unix : function () {
  18716. return Math.floor(+this / 1000);
  18717. },
  18718. toString : function () {
  18719. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18720. },
  18721. toDate : function () {
  18722. return this._offset ? new Date(+this) : this._d;
  18723. },
  18724. toISOString : function () {
  18725. var m = moment(this).utc();
  18726. if (0 < m.year() && m.year() <= 9999) {
  18727. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18728. } else {
  18729. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18730. }
  18731. },
  18732. toArray : function () {
  18733. var m = this;
  18734. return [
  18735. m.year(),
  18736. m.month(),
  18737. m.date(),
  18738. m.hours(),
  18739. m.minutes(),
  18740. m.seconds(),
  18741. m.milliseconds()
  18742. ];
  18743. },
  18744. isValid : function () {
  18745. return isValid(this);
  18746. },
  18747. isDSTShifted : function () {
  18748. if (this._a) {
  18749. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18750. }
  18751. return false;
  18752. },
  18753. parsingFlags : function () {
  18754. return extend({}, this._pf);
  18755. },
  18756. invalidAt: function () {
  18757. return this._pf.overflow;
  18758. },
  18759. utc : function () {
  18760. return this.zone(0);
  18761. },
  18762. local : function () {
  18763. this.zone(0);
  18764. this._isUTC = false;
  18765. return this;
  18766. },
  18767. format : function (inputString) {
  18768. var output = formatMoment(this, inputString || moment.defaultFormat);
  18769. return this.lang().postformat(output);
  18770. },
  18771. add : function (input, val) {
  18772. var dur;
  18773. // switch args to support add('s', 1) and add(1, 's')
  18774. if (typeof input === 'string') {
  18775. dur = moment.duration(+val, input);
  18776. } else {
  18777. dur = moment.duration(input, val);
  18778. }
  18779. addOrSubtractDurationFromMoment(this, dur, 1);
  18780. return this;
  18781. },
  18782. subtract : function (input, val) {
  18783. var dur;
  18784. // switch args to support subtract('s', 1) and subtract(1, 's')
  18785. if (typeof input === 'string') {
  18786. dur = moment.duration(+val, input);
  18787. } else {
  18788. dur = moment.duration(input, val);
  18789. }
  18790. addOrSubtractDurationFromMoment(this, dur, -1);
  18791. return this;
  18792. },
  18793. diff : function (input, units, asFloat) {
  18794. var that = makeAs(input, this),
  18795. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18796. diff, output;
  18797. units = normalizeUnits(units);
  18798. if (units === 'year' || units === 'month') {
  18799. // average number of days in the months in the given dates
  18800. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18801. // difference in months
  18802. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18803. // adjust by taking difference in days, average number of days
  18804. // and dst in the given months.
  18805. output += ((this - moment(this).startOf('month')) -
  18806. (that - moment(that).startOf('month'))) / diff;
  18807. // same as above but with zones, to negate all dst
  18808. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18809. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18810. if (units === 'year') {
  18811. output = output / 12;
  18812. }
  18813. } else {
  18814. diff = (this - that);
  18815. output = units === 'second' ? diff / 1e3 : // 1000
  18816. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18817. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18818. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18819. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18820. diff;
  18821. }
  18822. return asFloat ? output : absRound(output);
  18823. },
  18824. from : function (time, withoutSuffix) {
  18825. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18826. },
  18827. fromNow : function (withoutSuffix) {
  18828. return this.from(moment(), withoutSuffix);
  18829. },
  18830. calendar : function () {
  18831. // We want to compare the start of today, vs this.
  18832. // Getting start-of-today depends on whether we're zone'd or not.
  18833. var sod = makeAs(moment(), this).startOf('day'),
  18834. diff = this.diff(sod, 'days', true),
  18835. format = diff < -6 ? 'sameElse' :
  18836. diff < -1 ? 'lastWeek' :
  18837. diff < 0 ? 'lastDay' :
  18838. diff < 1 ? 'sameDay' :
  18839. diff < 2 ? 'nextDay' :
  18840. diff < 7 ? 'nextWeek' : 'sameElse';
  18841. return this.format(this.lang().calendar(format, this));
  18842. },
  18843. isLeapYear : function () {
  18844. return isLeapYear(this.year());
  18845. },
  18846. isDST : function () {
  18847. return (this.zone() < this.clone().month(0).zone() ||
  18848. this.zone() < this.clone().month(5).zone());
  18849. },
  18850. day : function (input) {
  18851. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18852. if (input != null) {
  18853. input = parseWeekday(input, this.lang());
  18854. return this.add({ d : input - day });
  18855. } else {
  18856. return day;
  18857. }
  18858. },
  18859. month : function (input) {
  18860. var utc = this._isUTC ? 'UTC' : '',
  18861. dayOfMonth;
  18862. if (input != null) {
  18863. if (typeof input === 'string') {
  18864. input = this.lang().monthsParse(input);
  18865. if (typeof input !== 'number') {
  18866. return this;
  18867. }
  18868. }
  18869. dayOfMonth = this.date();
  18870. this.date(1);
  18871. this._d['set' + utc + 'Month'](input);
  18872. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  18873. moment.updateOffset(this);
  18874. return this;
  18875. } else {
  18876. return this._d['get' + utc + 'Month']();
  18877. }
  18878. },
  18879. startOf: function (units) {
  18880. units = normalizeUnits(units);
  18881. // the following switch intentionally omits break keywords
  18882. // to utilize falling through the cases.
  18883. switch (units) {
  18884. case 'year':
  18885. this.month(0);
  18886. /* falls through */
  18887. case 'month':
  18888. this.date(1);
  18889. /* falls through */
  18890. case 'week':
  18891. case 'isoWeek':
  18892. case 'day':
  18893. this.hours(0);
  18894. /* falls through */
  18895. case 'hour':
  18896. this.minutes(0);
  18897. /* falls through */
  18898. case 'minute':
  18899. this.seconds(0);
  18900. /* falls through */
  18901. case 'second':
  18902. this.milliseconds(0);
  18903. /* falls through */
  18904. }
  18905. // weeks are a special case
  18906. if (units === 'week') {
  18907. this.weekday(0);
  18908. } else if (units === 'isoWeek') {
  18909. this.isoWeekday(1);
  18910. }
  18911. return this;
  18912. },
  18913. endOf: function (units) {
  18914. units = normalizeUnits(units);
  18915. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18916. },
  18917. isAfter: function (input, units) {
  18918. units = typeof units !== 'undefined' ? units : 'millisecond';
  18919. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18920. },
  18921. isBefore: function (input, units) {
  18922. units = typeof units !== 'undefined' ? units : 'millisecond';
  18923. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18924. },
  18925. isSame: function (input, units) {
  18926. units = units || 'ms';
  18927. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18928. },
  18929. min: function (other) {
  18930. other = moment.apply(null, arguments);
  18931. return other < this ? this : other;
  18932. },
  18933. max: function (other) {
  18934. other = moment.apply(null, arguments);
  18935. return other > this ? this : other;
  18936. },
  18937. zone : function (input) {
  18938. var offset = this._offset || 0;
  18939. if (input != null) {
  18940. if (typeof input === "string") {
  18941. input = timezoneMinutesFromString(input);
  18942. }
  18943. if (Math.abs(input) < 16) {
  18944. input = input * 60;
  18945. }
  18946. this._offset = input;
  18947. this._isUTC = true;
  18948. if (offset !== input) {
  18949. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  18950. }
  18951. } else {
  18952. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18953. }
  18954. return this;
  18955. },
  18956. zoneAbbr : function () {
  18957. return this._isUTC ? "UTC" : "";
  18958. },
  18959. zoneName : function () {
  18960. return this._isUTC ? "Coordinated Universal Time" : "";
  18961. },
  18962. parseZone : function () {
  18963. if (this._tzm) {
  18964. this.zone(this._tzm);
  18965. } else if (typeof this._i === 'string') {
  18966. this.zone(this._i);
  18967. }
  18968. return this;
  18969. },
  18970. hasAlignedHourOffset : function (input) {
  18971. if (!input) {
  18972. input = 0;
  18973. }
  18974. else {
  18975. input = moment(input).zone();
  18976. }
  18977. return (this.zone() - input) % 60 === 0;
  18978. },
  18979. daysInMonth : function () {
  18980. return daysInMonth(this.year(), this.month());
  18981. },
  18982. dayOfYear : function (input) {
  18983. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  18984. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  18985. },
  18986. quarter : function () {
  18987. return Math.ceil((this.month() + 1.0) / 3.0);
  18988. },
  18989. weekYear : function (input) {
  18990. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  18991. return input == null ? year : this.add("y", (input - year));
  18992. },
  18993. isoWeekYear : function (input) {
  18994. var year = weekOfYear(this, 1, 4).year;
  18995. return input == null ? year : this.add("y", (input - year));
  18996. },
  18997. week : function (input) {
  18998. var week = this.lang().week(this);
  18999. return input == null ? week : this.add("d", (input - week) * 7);
  19000. },
  19001. isoWeek : function (input) {
  19002. var week = weekOfYear(this, 1, 4).week;
  19003. return input == null ? week : this.add("d", (input - week) * 7);
  19004. },
  19005. weekday : function (input) {
  19006. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  19007. return input == null ? weekday : this.add("d", input - weekday);
  19008. },
  19009. isoWeekday : function (input) {
  19010. // behaves the same as moment#day except
  19011. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  19012. // as a setter, sunday should belong to the previous week.
  19013. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  19014. },
  19015. get : function (units) {
  19016. units = normalizeUnits(units);
  19017. return this[units]();
  19018. },
  19019. set : function (units, value) {
  19020. units = normalizeUnits(units);
  19021. if (typeof this[units] === 'function') {
  19022. this[units](value);
  19023. }
  19024. return this;
  19025. },
  19026. // If passed a language key, it will set the language for this
  19027. // instance. Otherwise, it will return the language configuration
  19028. // variables for this instance.
  19029. lang : function (key) {
  19030. if (key === undefined) {
  19031. return this._lang;
  19032. } else {
  19033. this._lang = getLangDefinition(key);
  19034. return this;
  19035. }
  19036. }
  19037. });
  19038. // helper for adding shortcuts
  19039. function makeGetterAndSetter(name, key) {
  19040. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  19041. var utc = this._isUTC ? 'UTC' : '';
  19042. if (input != null) {
  19043. this._d['set' + utc + key](input);
  19044. moment.updateOffset(this);
  19045. return this;
  19046. } else {
  19047. return this._d['get' + utc + key]();
  19048. }
  19049. };
  19050. }
  19051. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  19052. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  19053. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  19054. }
  19055. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  19056. makeGetterAndSetter('year', 'FullYear');
  19057. // add plural methods
  19058. moment.fn.days = moment.fn.day;
  19059. moment.fn.months = moment.fn.month;
  19060. moment.fn.weeks = moment.fn.week;
  19061. moment.fn.isoWeeks = moment.fn.isoWeek;
  19062. // add aliased format methods
  19063. moment.fn.toJSON = moment.fn.toISOString;
  19064. /************************************
  19065. Duration Prototype
  19066. ************************************/
  19067. extend(moment.duration.fn = Duration.prototype, {
  19068. _bubble : function () {
  19069. var milliseconds = this._milliseconds,
  19070. days = this._days,
  19071. months = this._months,
  19072. data = this._data,
  19073. seconds, minutes, hours, years;
  19074. // The following code bubbles up values, see the tests for
  19075. // examples of what that means.
  19076. data.milliseconds = milliseconds % 1000;
  19077. seconds = absRound(milliseconds / 1000);
  19078. data.seconds = seconds % 60;
  19079. minutes = absRound(seconds / 60);
  19080. data.minutes = minutes % 60;
  19081. hours = absRound(minutes / 60);
  19082. data.hours = hours % 24;
  19083. days += absRound(hours / 24);
  19084. data.days = days % 30;
  19085. months += absRound(days / 30);
  19086. data.months = months % 12;
  19087. years = absRound(months / 12);
  19088. data.years = years;
  19089. },
  19090. weeks : function () {
  19091. return absRound(this.days() / 7);
  19092. },
  19093. valueOf : function () {
  19094. return this._milliseconds +
  19095. this._days * 864e5 +
  19096. (this._months % 12) * 2592e6 +
  19097. toInt(this._months / 12) * 31536e6;
  19098. },
  19099. humanize : function (withSuffix) {
  19100. var difference = +this,
  19101. output = relativeTime(difference, !withSuffix, this.lang());
  19102. if (withSuffix) {
  19103. output = this.lang().pastFuture(difference, output);
  19104. }
  19105. return this.lang().postformat(output);
  19106. },
  19107. add : function (input, val) {
  19108. // supports only 2.0-style add(1, 's') or add(moment)
  19109. var dur = moment.duration(input, val);
  19110. this._milliseconds += dur._milliseconds;
  19111. this._days += dur._days;
  19112. this._months += dur._months;
  19113. this._bubble();
  19114. return this;
  19115. },
  19116. subtract : function (input, val) {
  19117. var dur = moment.duration(input, val);
  19118. this._milliseconds -= dur._milliseconds;
  19119. this._days -= dur._days;
  19120. this._months -= dur._months;
  19121. this._bubble();
  19122. return this;
  19123. },
  19124. get : function (units) {
  19125. units = normalizeUnits(units);
  19126. return this[units.toLowerCase() + 's']();
  19127. },
  19128. as : function (units) {
  19129. units = normalizeUnits(units);
  19130. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  19131. },
  19132. lang : moment.fn.lang,
  19133. toIsoString : function () {
  19134. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  19135. var years = Math.abs(this.years()),
  19136. months = Math.abs(this.months()),
  19137. days = Math.abs(this.days()),
  19138. hours = Math.abs(this.hours()),
  19139. minutes = Math.abs(this.minutes()),
  19140. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  19141. if (!this.asSeconds()) {
  19142. // this is the same as C#'s (Noda) and python (isodate)...
  19143. // but not other JS (goog.date)
  19144. return 'P0D';
  19145. }
  19146. return (this.asSeconds() < 0 ? '-' : '') +
  19147. 'P' +
  19148. (years ? years + 'Y' : '') +
  19149. (months ? months + 'M' : '') +
  19150. (days ? days + 'D' : '') +
  19151. ((hours || minutes || seconds) ? 'T' : '') +
  19152. (hours ? hours + 'H' : '') +
  19153. (minutes ? minutes + 'M' : '') +
  19154. (seconds ? seconds + 'S' : '');
  19155. }
  19156. });
  19157. function makeDurationGetter(name) {
  19158. moment.duration.fn[name] = function () {
  19159. return this._data[name];
  19160. };
  19161. }
  19162. function makeDurationAsGetter(name, factor) {
  19163. moment.duration.fn['as' + name] = function () {
  19164. return +this / factor;
  19165. };
  19166. }
  19167. for (i in unitMillisecondFactors) {
  19168. if (unitMillisecondFactors.hasOwnProperty(i)) {
  19169. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  19170. makeDurationGetter(i.toLowerCase());
  19171. }
  19172. }
  19173. makeDurationAsGetter('Weeks', 6048e5);
  19174. moment.duration.fn.asMonths = function () {
  19175. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  19176. };
  19177. /************************************
  19178. Default Lang
  19179. ************************************/
  19180. // Set default language, other languages will inherit from English.
  19181. moment.lang('en', {
  19182. ordinal : function (number) {
  19183. var b = number % 10,
  19184. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  19185. (b === 1) ? 'st' :
  19186. (b === 2) ? 'nd' :
  19187. (b === 3) ? 'rd' : 'th';
  19188. return number + output;
  19189. }
  19190. });
  19191. /* EMBED_LANGUAGES */
  19192. /************************************
  19193. Exposing Moment
  19194. ************************************/
  19195. function makeGlobal(deprecate) {
  19196. var warned = false, local_moment = moment;
  19197. /*global ender:false */
  19198. if (typeof ender !== 'undefined') {
  19199. return;
  19200. }
  19201. // here, `this` means `window` in the browser, or `global` on the server
  19202. // add `moment` as a global object via a string identifier,
  19203. // for Closure Compiler "advanced" mode
  19204. if (deprecate) {
  19205. global.moment = function () {
  19206. if (!warned && console && console.warn) {
  19207. warned = true;
  19208. console.warn(
  19209. "Accessing Moment through the global scope is " +
  19210. "deprecated, and will be removed in an upcoming " +
  19211. "release.");
  19212. }
  19213. return local_moment.apply(null, arguments);
  19214. };
  19215. extend(global.moment, local_moment);
  19216. } else {
  19217. global['moment'] = moment;
  19218. }
  19219. }
  19220. // CommonJS module is defined
  19221. if (hasModule) {
  19222. module.exports = moment;
  19223. makeGlobal(true);
  19224. } else if (typeof define === "function" && define.amd) {
  19225. define("moment", function (require, exports, module) {
  19226. if (module.config && module.config() && module.config().noGlobal !== true) {
  19227. // If user provided noGlobal, he is aware of global
  19228. makeGlobal(module.config().noGlobal === undefined);
  19229. }
  19230. return moment;
  19231. });
  19232. } else {
  19233. makeGlobal();
  19234. }
  19235. }).call(this);
  19236. },{}],5:[function(require,module,exports){
  19237. /**
  19238. * Copyright 2012 Craig Campbell
  19239. *
  19240. * Licensed under the Apache License, Version 2.0 (the "License");
  19241. * you may not use this file except in compliance with the License.
  19242. * You may obtain a copy of the License at
  19243. *
  19244. * http://www.apache.org/licenses/LICENSE-2.0
  19245. *
  19246. * Unless required by applicable law or agreed to in writing, software
  19247. * distributed under the License is distributed on an "AS IS" BASIS,
  19248. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19249. * See the License for the specific language governing permissions and
  19250. * limitations under the License.
  19251. *
  19252. * Mousetrap is a simple keyboard shortcut library for Javascript with
  19253. * no external dependencies
  19254. *
  19255. * @version 1.1.2
  19256. * @url craig.is/killing/mice
  19257. */
  19258. /**
  19259. * mapping of special keycodes to their corresponding keys
  19260. *
  19261. * everything in this dictionary cannot use keypress events
  19262. * so it has to be here to map to the correct keycodes for
  19263. * keyup/keydown events
  19264. *
  19265. * @type {Object}
  19266. */
  19267. var _MAP = {
  19268. 8: 'backspace',
  19269. 9: 'tab',
  19270. 13: 'enter',
  19271. 16: 'shift',
  19272. 17: 'ctrl',
  19273. 18: 'alt',
  19274. 20: 'capslock',
  19275. 27: 'esc',
  19276. 32: 'space',
  19277. 33: 'pageup',
  19278. 34: 'pagedown',
  19279. 35: 'end',
  19280. 36: 'home',
  19281. 37: 'left',
  19282. 38: 'up',
  19283. 39: 'right',
  19284. 40: 'down',
  19285. 45: 'ins',
  19286. 46: 'del',
  19287. 91: 'meta',
  19288. 93: 'meta',
  19289. 224: 'meta'
  19290. },
  19291. /**
  19292. * mapping for special characters so they can support
  19293. *
  19294. * this dictionary is only used incase you want to bind a
  19295. * keyup or keydown event to one of these keys
  19296. *
  19297. * @type {Object}
  19298. */
  19299. _KEYCODE_MAP = {
  19300. 106: '*',
  19301. 107: '+',
  19302. 109: '-',
  19303. 110: '.',
  19304. 111 : '/',
  19305. 186: ';',
  19306. 187: '=',
  19307. 188: ',',
  19308. 189: '-',
  19309. 190: '.',
  19310. 191: '/',
  19311. 192: '`',
  19312. 219: '[',
  19313. 220: '\\',
  19314. 221: ']',
  19315. 222: '\''
  19316. },
  19317. /**
  19318. * this is a mapping of keys that require shift on a US keypad
  19319. * back to the non shift equivelents
  19320. *
  19321. * this is so you can use keyup events with these keys
  19322. *
  19323. * note that this will only work reliably on US keyboards
  19324. *
  19325. * @type {Object}
  19326. */
  19327. _SHIFT_MAP = {
  19328. '~': '`',
  19329. '!': '1',
  19330. '@': '2',
  19331. '#': '3',
  19332. '$': '4',
  19333. '%': '5',
  19334. '^': '6',
  19335. '&': '7',
  19336. '*': '8',
  19337. '(': '9',
  19338. ')': '0',
  19339. '_': '-',
  19340. '+': '=',
  19341. ':': ';',
  19342. '\"': '\'',
  19343. '<': ',',
  19344. '>': '.',
  19345. '?': '/',
  19346. '|': '\\'
  19347. },
  19348. /**
  19349. * this is a list of special strings you can use to map
  19350. * to modifier keys when you specify your keyboard shortcuts
  19351. *
  19352. * @type {Object}
  19353. */
  19354. _SPECIAL_ALIASES = {
  19355. 'option': 'alt',
  19356. 'command': 'meta',
  19357. 'return': 'enter',
  19358. 'escape': 'esc'
  19359. },
  19360. /**
  19361. * variable to store the flipped version of _MAP from above
  19362. * needed to check if we should use keypress or not when no action
  19363. * is specified
  19364. *
  19365. * @type {Object|undefined}
  19366. */
  19367. _REVERSE_MAP,
  19368. /**
  19369. * a list of all the callbacks setup via Mousetrap.bind()
  19370. *
  19371. * @type {Object}
  19372. */
  19373. _callbacks = {},
  19374. /**
  19375. * direct map of string combinations to callbacks used for trigger()
  19376. *
  19377. * @type {Object}
  19378. */
  19379. _direct_map = {},
  19380. /**
  19381. * keeps track of what level each sequence is at since multiple
  19382. * sequences can start out with the same sequence
  19383. *
  19384. * @type {Object}
  19385. */
  19386. _sequence_levels = {},
  19387. /**
  19388. * variable to store the setTimeout call
  19389. *
  19390. * @type {null|number}
  19391. */
  19392. _reset_timer,
  19393. /**
  19394. * temporary state where we will ignore the next keyup
  19395. *
  19396. * @type {boolean|string}
  19397. */
  19398. _ignore_next_keyup = false,
  19399. /**
  19400. * are we currently inside of a sequence?
  19401. * type of action ("keyup" or "keydown" or "keypress") or false
  19402. *
  19403. * @type {boolean|string}
  19404. */
  19405. _inside_sequence = false;
  19406. /**
  19407. * loop through the f keys, f1 to f19 and add them to the map
  19408. * programatically
  19409. */
  19410. for (var i = 1; i < 20; ++i) {
  19411. _MAP[111 + i] = 'f' + i;
  19412. }
  19413. /**
  19414. * loop through to map numbers on the numeric keypad
  19415. */
  19416. for (i = 0; i <= 9; ++i) {
  19417. _MAP[i + 96] = i;
  19418. }
  19419. /**
  19420. * cross browser add event method
  19421. *
  19422. * @param {Element|HTMLDocument} object
  19423. * @param {string} type
  19424. * @param {Function} callback
  19425. * @returns void
  19426. */
  19427. function _addEvent(object, type, callback) {
  19428. if (object.addEventListener) {
  19429. return object.addEventListener(type, callback, false);
  19430. }
  19431. object.attachEvent('on' + type, callback);
  19432. }
  19433. /**
  19434. * takes the event and returns the key character
  19435. *
  19436. * @param {Event} e
  19437. * @return {string}
  19438. */
  19439. function _characterFromEvent(e) {
  19440. // for keypress events we should return the character as is
  19441. if (e.type == 'keypress') {
  19442. return String.fromCharCode(e.which);
  19443. }
  19444. // for non keypress events the special maps are needed
  19445. if (_MAP[e.which]) {
  19446. return _MAP[e.which];
  19447. }
  19448. if (_KEYCODE_MAP[e.which]) {
  19449. return _KEYCODE_MAP[e.which];
  19450. }
  19451. // if it is not in the special map
  19452. return String.fromCharCode(e.which).toLowerCase();
  19453. }
  19454. /**
  19455. * should we stop this event before firing off callbacks
  19456. *
  19457. * @param {Event} e
  19458. * @return {boolean}
  19459. */
  19460. function _stop(e) {
  19461. var element = e.target || e.srcElement,
  19462. tag_name = element.tagName;
  19463. // if the element has the class "mousetrap" then no need to stop
  19464. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19465. return false;
  19466. }
  19467. // stop for input, select, and textarea
  19468. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19469. }
  19470. /**
  19471. * checks if two arrays are equal
  19472. *
  19473. * @param {Array} modifiers1
  19474. * @param {Array} modifiers2
  19475. * @returns {boolean}
  19476. */
  19477. function _modifiersMatch(modifiers1, modifiers2) {
  19478. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19479. }
  19480. /**
  19481. * resets all sequence counters except for the ones passed in
  19482. *
  19483. * @param {Object} do_not_reset
  19484. * @returns void
  19485. */
  19486. function _resetSequences(do_not_reset) {
  19487. do_not_reset = do_not_reset || {};
  19488. var active_sequences = false,
  19489. key;
  19490. for (key in _sequence_levels) {
  19491. if (do_not_reset[key]) {
  19492. active_sequences = true;
  19493. continue;
  19494. }
  19495. _sequence_levels[key] = 0;
  19496. }
  19497. if (!active_sequences) {
  19498. _inside_sequence = false;
  19499. }
  19500. }
  19501. /**
  19502. * finds all callbacks that match based on the keycode, modifiers,
  19503. * and action
  19504. *
  19505. * @param {string} character
  19506. * @param {Array} modifiers
  19507. * @param {string} action
  19508. * @param {boolean=} remove - should we remove any matches
  19509. * @param {string=} combination
  19510. * @returns {Array}
  19511. */
  19512. function _getMatches(character, modifiers, action, remove, combination) {
  19513. var i,
  19514. callback,
  19515. matches = [];
  19516. // if there are no events related to this keycode
  19517. if (!_callbacks[character]) {
  19518. return [];
  19519. }
  19520. // if a modifier key is coming up on its own we should allow it
  19521. if (action == 'keyup' && _isModifier(character)) {
  19522. modifiers = [character];
  19523. }
  19524. // loop through all callbacks for the key that was pressed
  19525. // and see if any of them match
  19526. for (i = 0; i < _callbacks[character].length; ++i) {
  19527. callback = _callbacks[character][i];
  19528. // if this is a sequence but it is not at the right level
  19529. // then move onto the next match
  19530. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19531. continue;
  19532. }
  19533. // if the action we are looking for doesn't match the action we got
  19534. // then we should keep going
  19535. if (action != callback.action) {
  19536. continue;
  19537. }
  19538. // if this is a keypress event that means that we need to only
  19539. // look at the character, otherwise check the modifiers as
  19540. // well
  19541. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19542. // remove is used so if you change your mind and call bind a
  19543. // second time with a new function the first one is overwritten
  19544. if (remove && callback.combo == combination) {
  19545. _callbacks[character].splice(i, 1);
  19546. }
  19547. matches.push(callback);
  19548. }
  19549. }
  19550. return matches;
  19551. }
  19552. /**
  19553. * takes a key event and figures out what the modifiers are
  19554. *
  19555. * @param {Event} e
  19556. * @returns {Array}
  19557. */
  19558. function _eventModifiers(e) {
  19559. var modifiers = [];
  19560. if (e.shiftKey) {
  19561. modifiers.push('shift');
  19562. }
  19563. if (e.altKey) {
  19564. modifiers.push('alt');
  19565. }
  19566. if (e.ctrlKey) {
  19567. modifiers.push('ctrl');
  19568. }
  19569. if (e.metaKey) {
  19570. modifiers.push('meta');
  19571. }
  19572. return modifiers;
  19573. }
  19574. /**
  19575. * actually calls the callback function
  19576. *
  19577. * if your callback function returns false this will use the jquery
  19578. * convention - prevent default and stop propogation on the event
  19579. *
  19580. * @param {Function} callback
  19581. * @param {Event} e
  19582. * @returns void
  19583. */
  19584. function _fireCallback(callback, e) {
  19585. if (callback(e) === false) {
  19586. if (e.preventDefault) {
  19587. e.preventDefault();
  19588. }
  19589. if (e.stopPropagation) {
  19590. e.stopPropagation();
  19591. }
  19592. e.returnValue = false;
  19593. e.cancelBubble = true;
  19594. }
  19595. }
  19596. /**
  19597. * handles a character key event
  19598. *
  19599. * @param {string} character
  19600. * @param {Event} e
  19601. * @returns void
  19602. */
  19603. function _handleCharacter(character, e) {
  19604. // if this event should not happen stop here
  19605. if (_stop(e)) {
  19606. return;
  19607. }
  19608. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19609. i,
  19610. do_not_reset = {},
  19611. processed_sequence_callback = false;
  19612. // loop through matching callbacks for this key event
  19613. for (i = 0; i < callbacks.length; ++i) {
  19614. // fire for all sequence callbacks
  19615. // this is because if for example you have multiple sequences
  19616. // bound such as "g i" and "g t" they both need to fire the
  19617. // callback for matching g cause otherwise you can only ever
  19618. // match the first one
  19619. if (callbacks[i].seq) {
  19620. processed_sequence_callback = true;
  19621. // keep a list of which sequences were matches for later
  19622. do_not_reset[callbacks[i].seq] = 1;
  19623. _fireCallback(callbacks[i].callback, e);
  19624. continue;
  19625. }
  19626. // if there were no sequence matches but we are still here
  19627. // that means this is a regular match so we should fire that
  19628. if (!processed_sequence_callback && !_inside_sequence) {
  19629. _fireCallback(callbacks[i].callback, e);
  19630. }
  19631. }
  19632. // if you are inside of a sequence and the key you are pressing
  19633. // is not a modifier key then we should reset all sequences
  19634. // that were not matched by this key event
  19635. if (e.type == _inside_sequence && !_isModifier(character)) {
  19636. _resetSequences(do_not_reset);
  19637. }
  19638. }
  19639. /**
  19640. * handles a keydown event
  19641. *
  19642. * @param {Event} e
  19643. * @returns void
  19644. */
  19645. function _handleKey(e) {
  19646. // normalize e.which for key events
  19647. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19648. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19649. var character = _characterFromEvent(e);
  19650. // no character found then stop
  19651. if (!character) {
  19652. return;
  19653. }
  19654. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19655. _ignore_next_keyup = false;
  19656. return;
  19657. }
  19658. _handleCharacter(character, e);
  19659. }
  19660. /**
  19661. * determines if the keycode specified is a modifier key or not
  19662. *
  19663. * @param {string} key
  19664. * @returns {boolean}
  19665. */
  19666. function _isModifier(key) {
  19667. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19668. }
  19669. /**
  19670. * called to set a 1 second timeout on the specified sequence
  19671. *
  19672. * this is so after each key press in the sequence you have 1 second
  19673. * to press the next key before you have to start over
  19674. *
  19675. * @returns void
  19676. */
  19677. function _resetSequenceTimer() {
  19678. clearTimeout(_reset_timer);
  19679. _reset_timer = setTimeout(_resetSequences, 1000);
  19680. }
  19681. /**
  19682. * reverses the map lookup so that we can look for specific keys
  19683. * to see what can and can't use keypress
  19684. *
  19685. * @return {Object}
  19686. */
  19687. function _getReverseMap() {
  19688. if (!_REVERSE_MAP) {
  19689. _REVERSE_MAP = {};
  19690. for (var key in _MAP) {
  19691. // pull out the numeric keypad from here cause keypress should
  19692. // be able to detect the keys from the character
  19693. if (key > 95 && key < 112) {
  19694. continue;
  19695. }
  19696. if (_MAP.hasOwnProperty(key)) {
  19697. _REVERSE_MAP[_MAP[key]] = key;
  19698. }
  19699. }
  19700. }
  19701. return _REVERSE_MAP;
  19702. }
  19703. /**
  19704. * picks the best action based on the key combination
  19705. *
  19706. * @param {string} key - character for key
  19707. * @param {Array} modifiers
  19708. * @param {string=} action passed in
  19709. */
  19710. function _pickBestAction(key, modifiers, action) {
  19711. // if no action was picked in we should try to pick the one
  19712. // that we think would work best for this key
  19713. if (!action) {
  19714. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19715. }
  19716. // modifier keys don't work as expected with keypress,
  19717. // switch to keydown
  19718. if (action == 'keypress' && modifiers.length) {
  19719. action = 'keydown';
  19720. }
  19721. return action;
  19722. }
  19723. /**
  19724. * binds a key sequence to an event
  19725. *
  19726. * @param {string} combo - combo specified in bind call
  19727. * @param {Array} keys
  19728. * @param {Function} callback
  19729. * @param {string=} action
  19730. * @returns void
  19731. */
  19732. function _bindSequence(combo, keys, callback, action) {
  19733. // start off by adding a sequence level record for this combination
  19734. // and setting the level to 0
  19735. _sequence_levels[combo] = 0;
  19736. // if there is no action pick the best one for the first key
  19737. // in the sequence
  19738. if (!action) {
  19739. action = _pickBestAction(keys[0], []);
  19740. }
  19741. /**
  19742. * callback to increase the sequence level for this sequence and reset
  19743. * all other sequences that were active
  19744. *
  19745. * @param {Event} e
  19746. * @returns void
  19747. */
  19748. var _increaseSequence = function(e) {
  19749. _inside_sequence = action;
  19750. ++_sequence_levels[combo];
  19751. _resetSequenceTimer();
  19752. },
  19753. /**
  19754. * wraps the specified callback inside of another function in order
  19755. * to reset all sequence counters as soon as this sequence is done
  19756. *
  19757. * @param {Event} e
  19758. * @returns void
  19759. */
  19760. _callbackAndReset = function(e) {
  19761. _fireCallback(callback, e);
  19762. // we should ignore the next key up if the action is key down
  19763. // or keypress. this is so if you finish a sequence and
  19764. // release the key the final key will not trigger a keyup
  19765. if (action !== 'keyup') {
  19766. _ignore_next_keyup = _characterFromEvent(e);
  19767. }
  19768. // weird race condition if a sequence ends with the key
  19769. // another sequence begins with
  19770. setTimeout(_resetSequences, 10);
  19771. },
  19772. i;
  19773. // loop through keys one at a time and bind the appropriate callback
  19774. // function. for any key leading up to the final one it should
  19775. // increase the sequence. after the final, it should reset all sequences
  19776. for (i = 0; i < keys.length; ++i) {
  19777. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19778. }
  19779. }
  19780. /**
  19781. * binds a single keyboard combination
  19782. *
  19783. * @param {string} combination
  19784. * @param {Function} callback
  19785. * @param {string=} action
  19786. * @param {string=} sequence_name - name of sequence if part of sequence
  19787. * @param {number=} level - what part of the sequence the command is
  19788. * @returns void
  19789. */
  19790. function _bindSingle(combination, callback, action, sequence_name, level) {
  19791. // make sure multiple spaces in a row become a single space
  19792. combination = combination.replace(/\s+/g, ' ');
  19793. var sequence = combination.split(' '),
  19794. i,
  19795. key,
  19796. keys,
  19797. modifiers = [];
  19798. // if this pattern is a sequence of keys then run through this method
  19799. // to reprocess each pattern one key at a time
  19800. if (sequence.length > 1) {
  19801. return _bindSequence(combination, sequence, callback, action);
  19802. }
  19803. // take the keys from this pattern and figure out what the actual
  19804. // pattern is all about
  19805. keys = combination === '+' ? ['+'] : combination.split('+');
  19806. for (i = 0; i < keys.length; ++i) {
  19807. key = keys[i];
  19808. // normalize key names
  19809. if (_SPECIAL_ALIASES[key]) {
  19810. key = _SPECIAL_ALIASES[key];
  19811. }
  19812. // if this is not a keypress event then we should
  19813. // be smart about using shift keys
  19814. // this will only work for US keyboards however
  19815. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19816. key = _SHIFT_MAP[key];
  19817. modifiers.push('shift');
  19818. }
  19819. // if this key is a modifier then add it to the list of modifiers
  19820. if (_isModifier(key)) {
  19821. modifiers.push(key);
  19822. }
  19823. }
  19824. // depending on what the key combination is
  19825. // we will try to pick the best event for it
  19826. action = _pickBestAction(key, modifiers, action);
  19827. // make sure to initialize array if this is the first time
  19828. // a callback is added for this key
  19829. if (!_callbacks[key]) {
  19830. _callbacks[key] = [];
  19831. }
  19832. // remove an existing match if there is one
  19833. _getMatches(key, modifiers, action, !sequence_name, combination);
  19834. // add this call back to the array
  19835. // if it is a sequence put it at the beginning
  19836. // if not put it at the end
  19837. //
  19838. // this is important because the way these are processed expects
  19839. // the sequence ones to come first
  19840. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19841. callback: callback,
  19842. modifiers: modifiers,
  19843. action: action,
  19844. seq: sequence_name,
  19845. level: level,
  19846. combo: combination
  19847. });
  19848. }
  19849. /**
  19850. * binds multiple combinations to the same callback
  19851. *
  19852. * @param {Array} combinations
  19853. * @param {Function} callback
  19854. * @param {string|undefined} action
  19855. * @returns void
  19856. */
  19857. function _bindMultiple(combinations, callback, action) {
  19858. for (var i = 0; i < combinations.length; ++i) {
  19859. _bindSingle(combinations[i], callback, action);
  19860. }
  19861. }
  19862. // start!
  19863. _addEvent(document, 'keypress', _handleKey);
  19864. _addEvent(document, 'keydown', _handleKey);
  19865. _addEvent(document, 'keyup', _handleKey);
  19866. var mousetrap = {
  19867. /**
  19868. * binds an event to mousetrap
  19869. *
  19870. * can be a single key, a combination of keys separated with +,
  19871. * a comma separated list of keys, an array of keys, or
  19872. * a sequence of keys separated by spaces
  19873. *
  19874. * be sure to list the modifier keys first to make sure that the
  19875. * correct key ends up getting bound (the last key in the pattern)
  19876. *
  19877. * @param {string|Array} keys
  19878. * @param {Function} callback
  19879. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19880. * @returns void
  19881. */
  19882. bind: function(keys, callback, action) {
  19883. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19884. _direct_map[keys + ':' + action] = callback;
  19885. return this;
  19886. },
  19887. /**
  19888. * unbinds an event to mousetrap
  19889. *
  19890. * the unbinding sets the callback function of the specified key combo
  19891. * to an empty function and deletes the corresponding key in the
  19892. * _direct_map dict.
  19893. *
  19894. * the keycombo+action has to be exactly the same as
  19895. * it was defined in the bind method
  19896. *
  19897. * TODO: actually remove this from the _callbacks dictionary instead
  19898. * of binding an empty function
  19899. *
  19900. * @param {string|Array} keys
  19901. * @param {string} action
  19902. * @returns void
  19903. */
  19904. unbind: function(keys, action) {
  19905. if (_direct_map[keys + ':' + action]) {
  19906. delete _direct_map[keys + ':' + action];
  19907. this.bind(keys, function() {}, action);
  19908. }
  19909. return this;
  19910. },
  19911. /**
  19912. * triggers an event that has already been bound
  19913. *
  19914. * @param {string} keys
  19915. * @param {string=} action
  19916. * @returns void
  19917. */
  19918. trigger: function(keys, action) {
  19919. _direct_map[keys + ':' + action]();
  19920. return this;
  19921. },
  19922. /**
  19923. * resets the library back to its initial state. this is useful
  19924. * if you want to clear out the current keyboard shortcuts and bind
  19925. * new ones - for example if you switch to another page
  19926. *
  19927. * @returns void
  19928. */
  19929. reset: function() {
  19930. _callbacks = {};
  19931. _direct_map = {};
  19932. return this;
  19933. }
  19934. };
  19935. module.exports = mousetrap;
  19936. },{}]},{},[1])
  19937. (1)
  19938. });