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.

22626 lines
668 KiB

  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 1.0.0
  8. * @date 2014-05-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. * Test whether all elements in two arrays are equal.
  354. * @param {Array} a
  355. * @param {Array} b
  356. * @return {boolean} Returns true if both arrays have the same length and same
  357. * elements.
  358. */
  359. util.equalArray = function (a, b) {
  360. if (a.length != b.length) return false;
  361. for (var i = 1, len = a.length; i < len; i++) {
  362. if (a[i] != b[i]) return false;
  363. }
  364. return true;
  365. };
  366. /**
  367. * Convert an object to another type
  368. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  369. * @param {String | undefined} type Name of the type. Available types:
  370. * 'Boolean', 'Number', 'String',
  371. * 'Date', 'Moment', ISODate', 'ASPDate'.
  372. * @return {*} object
  373. * @throws Error
  374. */
  375. util.convert = function convert(object, type) {
  376. var match;
  377. if (object === undefined) {
  378. return undefined;
  379. }
  380. if (object === null) {
  381. return null;
  382. }
  383. if (!type) {
  384. return object;
  385. }
  386. if (!(typeof type === 'string') && !(type instanceof String)) {
  387. throw new Error('Type must be a string');
  388. }
  389. //noinspection FallthroughInSwitchStatementJS
  390. switch (type) {
  391. case 'boolean':
  392. case 'Boolean':
  393. return Boolean(object);
  394. case 'number':
  395. case 'Number':
  396. return Number(object.valueOf());
  397. case 'string':
  398. case 'String':
  399. return String(object);
  400. case 'Date':
  401. if (util.isNumber(object)) {
  402. return new Date(object);
  403. }
  404. if (object instanceof Date) {
  405. return new Date(object.valueOf());
  406. }
  407. else if (moment.isMoment(object)) {
  408. return new Date(object.valueOf());
  409. }
  410. if (util.isString(object)) {
  411. match = ASPDateRegex.exec(object);
  412. if (match) {
  413. // object is an ASP date
  414. return new Date(Number(match[1])); // parse number
  415. }
  416. else {
  417. return moment(object).toDate(); // parse string
  418. }
  419. }
  420. else {
  421. throw new Error(
  422. 'Cannot convert object of type ' + util.getType(object) +
  423. ' to type Date');
  424. }
  425. case 'Moment':
  426. if (util.isNumber(object)) {
  427. return moment(object);
  428. }
  429. if (object instanceof Date) {
  430. return moment(object.valueOf());
  431. }
  432. else if (moment.isMoment(object)) {
  433. return moment(object);
  434. }
  435. if (util.isString(object)) {
  436. match = ASPDateRegex.exec(object);
  437. if (match) {
  438. // object is an ASP date
  439. return moment(Number(match[1])); // parse number
  440. }
  441. else {
  442. return moment(object); // parse string
  443. }
  444. }
  445. else {
  446. throw new Error(
  447. 'Cannot convert object of type ' + util.getType(object) +
  448. ' to type Date');
  449. }
  450. case 'ISODate':
  451. if (util.isNumber(object)) {
  452. return new Date(object);
  453. }
  454. else if (object instanceof Date) {
  455. return object.toISOString();
  456. }
  457. else if (moment.isMoment(object)) {
  458. return object.toDate().toISOString();
  459. }
  460. else if (util.isString(object)) {
  461. match = ASPDateRegex.exec(object);
  462. if (match) {
  463. // object is an ASP date
  464. return new Date(Number(match[1])).toISOString(); // parse number
  465. }
  466. else {
  467. return new Date(object).toISOString(); // parse string
  468. }
  469. }
  470. else {
  471. throw new Error(
  472. 'Cannot convert object of type ' + util.getType(object) +
  473. ' to type ISODate');
  474. }
  475. case 'ASPDate':
  476. if (util.isNumber(object)) {
  477. return '/Date(' + object + ')/';
  478. }
  479. else if (object instanceof Date) {
  480. return '/Date(' + object.valueOf() + ')/';
  481. }
  482. else if (util.isString(object)) {
  483. match = ASPDateRegex.exec(object);
  484. var value;
  485. if (match) {
  486. // object is an ASP date
  487. value = new Date(Number(match[1])).valueOf(); // parse number
  488. }
  489. else {
  490. value = new Date(object).valueOf(); // parse string
  491. }
  492. return '/Date(' + value + ')/';
  493. }
  494. else {
  495. throw new Error(
  496. 'Cannot convert object of type ' + util.getType(object) +
  497. ' to type ASPDate');
  498. }
  499. default:
  500. throw new Error('Cannot convert object of type ' + util.getType(object) +
  501. ' to type "' + type + '"');
  502. }
  503. };
  504. // parse ASP.Net Date pattern,
  505. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  506. // code from http://momentjs.com/
  507. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  508. /**
  509. * Get the type of an object, for example util.getType([]) returns 'Array'
  510. * @param {*} object
  511. * @return {String} type
  512. */
  513. util.getType = function getType(object) {
  514. var type = typeof object;
  515. if (type == 'object') {
  516. if (object == null) {
  517. return 'null';
  518. }
  519. if (object instanceof Boolean) {
  520. return 'Boolean';
  521. }
  522. if (object instanceof Number) {
  523. return 'Number';
  524. }
  525. if (object instanceof String) {
  526. return 'String';
  527. }
  528. if (object instanceof Array) {
  529. return 'Array';
  530. }
  531. if (object instanceof Date) {
  532. return 'Date';
  533. }
  534. return 'Object';
  535. }
  536. else if (type == 'number') {
  537. return 'Number';
  538. }
  539. else if (type == 'boolean') {
  540. return 'Boolean';
  541. }
  542. else if (type == 'string') {
  543. return 'String';
  544. }
  545. return type;
  546. };
  547. /**
  548. * Retrieve the absolute left value of a DOM element
  549. * @param {Element} elem A dom element, for example a div
  550. * @return {number} left The absolute left position of this element
  551. * in the browser page.
  552. */
  553. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  554. var doc = document.documentElement;
  555. var body = document.body;
  556. var left = elem.offsetLeft;
  557. var e = elem.offsetParent;
  558. while (e != null && e != body && e != doc) {
  559. left += e.offsetLeft;
  560. left -= e.scrollLeft;
  561. e = e.offsetParent;
  562. }
  563. return left;
  564. };
  565. /**
  566. * Retrieve the absolute top value of a DOM element
  567. * @param {Element} elem A dom element, for example a div
  568. * @return {number} top The absolute top position of this element
  569. * in the browser page.
  570. */
  571. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  572. var doc = document.documentElement;
  573. var body = document.body;
  574. var top = elem.offsetTop;
  575. var e = elem.offsetParent;
  576. while (e != null && e != body && e != doc) {
  577. top += e.offsetTop;
  578. top -= e.scrollTop;
  579. e = e.offsetParent;
  580. }
  581. return top;
  582. };
  583. /**
  584. * Get the absolute, vertical mouse position from an event.
  585. * @param {Event} event
  586. * @return {Number} pageY
  587. */
  588. util.getPageY = function getPageY (event) {
  589. if ('pageY' in event) {
  590. return event.pageY;
  591. }
  592. else {
  593. var clientY;
  594. if (('targetTouches' in event) && event.targetTouches.length) {
  595. clientY = event.targetTouches[0].clientY;
  596. }
  597. else {
  598. clientY = event.clientY;
  599. }
  600. var doc = document.documentElement;
  601. var body = document.body;
  602. return clientY +
  603. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  604. ( doc && doc.clientTop || body && body.clientTop || 0 );
  605. }
  606. };
  607. /**
  608. * Get the absolute, horizontal mouse position from an event.
  609. * @param {Event} event
  610. * @return {Number} pageX
  611. */
  612. util.getPageX = function getPageX (event) {
  613. if ('pageY' in event) {
  614. return event.pageX;
  615. }
  616. else {
  617. var clientX;
  618. if (('targetTouches' in event) && event.targetTouches.length) {
  619. clientX = event.targetTouches[0].clientX;
  620. }
  621. else {
  622. clientX = event.clientX;
  623. }
  624. var doc = document.documentElement;
  625. var body = document.body;
  626. return clientX +
  627. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  628. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  629. }
  630. };
  631. /**
  632. * add a className to the given elements style
  633. * @param {Element} elem
  634. * @param {String} className
  635. */
  636. util.addClassName = function addClassName(elem, className) {
  637. var classes = elem.className.split(' ');
  638. if (classes.indexOf(className) == -1) {
  639. classes.push(className); // add the class to the array
  640. elem.className = classes.join(' ');
  641. }
  642. };
  643. /**
  644. * add a className to the given elements style
  645. * @param {Element} elem
  646. * @param {String} className
  647. */
  648. util.removeClassName = function removeClassname(elem, className) {
  649. var classes = elem.className.split(' ');
  650. var index = classes.indexOf(className);
  651. if (index != -1) {
  652. classes.splice(index, 1); // remove the class from the array
  653. elem.className = classes.join(' ');
  654. }
  655. };
  656. /**
  657. * For each method for both arrays and objects.
  658. * In case of an array, the built-in Array.forEach() is applied.
  659. * In case of an Object, the method loops over all properties of the object.
  660. * @param {Object | Array} object An Object or Array
  661. * @param {function} callback Callback method, called for each item in
  662. * the object or array with three parameters:
  663. * callback(value, index, object)
  664. */
  665. util.forEach = function forEach (object, callback) {
  666. var i,
  667. len;
  668. if (object instanceof Array) {
  669. // array
  670. for (i = 0, len = object.length; i < len; i++) {
  671. callback(object[i], i, object);
  672. }
  673. }
  674. else {
  675. // object
  676. for (i in object) {
  677. if (object.hasOwnProperty(i)) {
  678. callback(object[i], i, object);
  679. }
  680. }
  681. }
  682. };
  683. /**
  684. * Convert an object into an array: all objects properties are put into the
  685. * array. The resulting array is unordered.
  686. * @param {Object} object
  687. * @param {Array} array
  688. */
  689. util.toArray = function toArray(object) {
  690. var array = [];
  691. for (var prop in object) {
  692. if (object.hasOwnProperty(prop)) array.push(object[prop]);
  693. }
  694. return array;
  695. }
  696. /**
  697. * Update a property in an object
  698. * @param {Object} object
  699. * @param {String} key
  700. * @param {*} value
  701. * @return {Boolean} changed
  702. */
  703. util.updateProperty = function updateProperty (object, key, value) {
  704. if (object[key] !== value) {
  705. object[key] = value;
  706. return true;
  707. }
  708. else {
  709. return false;
  710. }
  711. };
  712. /**
  713. * Add and event listener. Works for all browsers
  714. * @param {Element} element An html element
  715. * @param {string} action The action, for example "click",
  716. * without the prefix "on"
  717. * @param {function} listener The callback function to be executed
  718. * @param {boolean} [useCapture]
  719. */
  720. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  721. if (element.addEventListener) {
  722. if (useCapture === undefined)
  723. useCapture = false;
  724. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  725. action = "DOMMouseScroll"; // For Firefox
  726. }
  727. element.addEventListener(action, listener, useCapture);
  728. } else {
  729. element.attachEvent("on" + action, listener); // IE browsers
  730. }
  731. };
  732. /**
  733. * Remove an event listener from an element
  734. * @param {Element} element An html dom element
  735. * @param {string} action The name of the event, for example "mousedown"
  736. * @param {function} listener The listener function
  737. * @param {boolean} [useCapture]
  738. */
  739. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  740. if (element.removeEventListener) {
  741. // non-IE browsers
  742. if (useCapture === undefined)
  743. useCapture = false;
  744. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  745. action = "DOMMouseScroll"; // For Firefox
  746. }
  747. element.removeEventListener(action, listener, useCapture);
  748. } else {
  749. // IE browsers
  750. element.detachEvent("on" + action, listener);
  751. }
  752. };
  753. /**
  754. * Get HTML element which is the target of the event
  755. * @param {Event} event
  756. * @return {Element} target element
  757. */
  758. util.getTarget = function getTarget(event) {
  759. // code from http://www.quirksmode.org/js/events_properties.html
  760. if (!event) {
  761. event = window.event;
  762. }
  763. var target;
  764. if (event.target) {
  765. target = event.target;
  766. }
  767. else if (event.srcElement) {
  768. target = event.srcElement;
  769. }
  770. if (target.nodeType != undefined && target.nodeType == 3) {
  771. // defeat Safari bug
  772. target = target.parentNode;
  773. }
  774. return target;
  775. };
  776. /**
  777. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  778. * @param {Element} element
  779. * @param {Event} event
  780. */
  781. util.fakeGesture = function fakeGesture (element, event) {
  782. var eventType = null;
  783. // for hammer.js 1.0.5
  784. var gesture = Hammer.event.collectEventData(this, eventType, event);
  785. // for hammer.js 1.0.6
  786. //var touches = Hammer.event.getTouchList(event, eventType);
  787. // var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  788. // on IE in standards mode, no touches are recognized by hammer.js,
  789. // resulting in NaN values for center.pageX and center.pageY
  790. if (isNaN(gesture.center.pageX)) {
  791. gesture.center.pageX = event.pageX;
  792. }
  793. if (isNaN(gesture.center.pageY)) {
  794. gesture.center.pageY = event.pageY;
  795. }
  796. return gesture;
  797. };
  798. util.option = {};
  799. /**
  800. * Convert a value into a boolean
  801. * @param {Boolean | function | undefined} value
  802. * @param {Boolean} [defaultValue]
  803. * @returns {Boolean} bool
  804. */
  805. util.option.asBoolean = function (value, defaultValue) {
  806. if (typeof value == 'function') {
  807. value = value();
  808. }
  809. if (value != null) {
  810. return (value != false);
  811. }
  812. return defaultValue || null;
  813. };
  814. /**
  815. * Convert a value into a number
  816. * @param {Boolean | function | undefined} value
  817. * @param {Number} [defaultValue]
  818. * @returns {Number} number
  819. */
  820. util.option.asNumber = function (value, defaultValue) {
  821. if (typeof value == 'function') {
  822. value = value();
  823. }
  824. if (value != null) {
  825. return Number(value) || defaultValue || null;
  826. }
  827. return defaultValue || null;
  828. };
  829. /**
  830. * Convert a value into a string
  831. * @param {String | function | undefined} value
  832. * @param {String} [defaultValue]
  833. * @returns {String} str
  834. */
  835. util.option.asString = function (value, defaultValue) {
  836. if (typeof value == 'function') {
  837. value = value();
  838. }
  839. if (value != null) {
  840. return String(value);
  841. }
  842. return defaultValue || null;
  843. };
  844. /**
  845. * Convert a size or location into a string with pixels or a percentage
  846. * @param {String | Number | function | undefined} value
  847. * @param {String} [defaultValue]
  848. * @returns {String} size
  849. */
  850. util.option.asSize = function (value, defaultValue) {
  851. if (typeof value == 'function') {
  852. value = value();
  853. }
  854. if (util.isString(value)) {
  855. return value;
  856. }
  857. else if (util.isNumber(value)) {
  858. return value + 'px';
  859. }
  860. else {
  861. return defaultValue || null;
  862. }
  863. };
  864. /**
  865. * Convert a value into a DOM element
  866. * @param {HTMLElement | function | undefined} value
  867. * @param {HTMLElement} [defaultValue]
  868. * @returns {HTMLElement | null} dom
  869. */
  870. util.option.asElement = function (value, defaultValue) {
  871. if (typeof value == 'function') {
  872. value = value();
  873. }
  874. return value || defaultValue || null;
  875. };
  876. util.GiveDec = function GiveDec(Hex) {
  877. var Value;
  878. if (Hex == "A")
  879. Value = 10;
  880. else if (Hex == "B")
  881. Value = 11;
  882. else if (Hex == "C")
  883. Value = 12;
  884. else if (Hex == "D")
  885. Value = 13;
  886. else if (Hex == "E")
  887. Value = 14;
  888. else if (Hex == "F")
  889. Value = 15;
  890. else
  891. Value = eval(Hex);
  892. return Value;
  893. };
  894. util.GiveHex = function GiveHex(Dec) {
  895. var Value;
  896. if(Dec == 10)
  897. Value = "A";
  898. else if (Dec == 11)
  899. Value = "B";
  900. else if (Dec == 12)
  901. Value = "C";
  902. else if (Dec == 13)
  903. Value = "D";
  904. else if (Dec == 14)
  905. Value = "E";
  906. else if (Dec == 15)
  907. Value = "F";
  908. else
  909. Value = "" + Dec;
  910. return Value;
  911. };
  912. /**
  913. * Parse a color property into an object with border, background, and
  914. * highlight colors
  915. * @param {Object | String} color
  916. * @return {Object} colorObject
  917. */
  918. util.parseColor = function(color) {
  919. var c;
  920. if (util.isString(color)) {
  921. if (util.isValidHex(color)) {
  922. var hsv = util.hexToHSV(color);
  923. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  924. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  925. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  926. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  927. c = {
  928. background: color,
  929. border:darkerColorHex,
  930. highlight: {
  931. background:lighterColorHex,
  932. border:darkerColorHex
  933. }
  934. };
  935. }
  936. else {
  937. c = {
  938. background:color,
  939. border:color,
  940. highlight: {
  941. background:color,
  942. border:color
  943. }
  944. };
  945. }
  946. }
  947. else {
  948. c = {};
  949. c.background = color.background || 'white';
  950. c.border = color.border || c.background;
  951. if (util.isString(color.highlight)) {
  952. c.highlight = {
  953. border: color.highlight,
  954. background: color.highlight
  955. }
  956. }
  957. else {
  958. c.highlight = {};
  959. c.highlight.background = color.highlight && color.highlight.background || c.background;
  960. c.highlight.border = color.highlight && color.highlight.border || c.border;
  961. }
  962. }
  963. return c;
  964. };
  965. /**
  966. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  967. *
  968. * @param {String} hex
  969. * @returns {{r: *, g: *, b: *}}
  970. */
  971. util.hexToRGB = function hexToRGB(hex) {
  972. hex = hex.replace("#","").toUpperCase();
  973. var a = util.GiveDec(hex.substring(0, 1));
  974. var b = util.GiveDec(hex.substring(1, 2));
  975. var c = util.GiveDec(hex.substring(2, 3));
  976. var d = util.GiveDec(hex.substring(3, 4));
  977. var e = util.GiveDec(hex.substring(4, 5));
  978. var f = util.GiveDec(hex.substring(5, 6));
  979. var r = (a * 16) + b;
  980. var g = (c * 16) + d;
  981. var b = (e * 16) + f;
  982. return {r:r,g:g,b:b};
  983. };
  984. util.RGBToHex = function RGBToHex(red,green,blue) {
  985. var a = util.GiveHex(Math.floor(red / 16));
  986. var b = util.GiveHex(red % 16);
  987. var c = util.GiveHex(Math.floor(green / 16));
  988. var d = util.GiveHex(green % 16);
  989. var e = util.GiveHex(Math.floor(blue / 16));
  990. var f = util.GiveHex(blue % 16);
  991. var hex = a + b + c + d + e + f;
  992. return "#" + hex;
  993. };
  994. /**
  995. * http://www.javascripter.net/faq/rgb2hsv.htm
  996. *
  997. * @param red
  998. * @param green
  999. * @param blue
  1000. * @returns {*}
  1001. * @constructor
  1002. */
  1003. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  1004. red=red/255; green=green/255; blue=blue/255;
  1005. var minRGB = Math.min(red,Math.min(green,blue));
  1006. var maxRGB = Math.max(red,Math.max(green,blue));
  1007. // Black-gray-white
  1008. if (minRGB == maxRGB) {
  1009. return {h:0,s:0,v:minRGB};
  1010. }
  1011. // Colors other than black-gray-white:
  1012. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  1013. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  1014. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  1015. var saturation = (maxRGB - minRGB)/maxRGB;
  1016. var value = maxRGB;
  1017. return {h:hue,s:saturation,v:value};
  1018. };
  1019. /**
  1020. * https://gist.github.com/mjijackson/5311256
  1021. * @param hue
  1022. * @param saturation
  1023. * @param value
  1024. * @returns {{r: number, g: number, b: number}}
  1025. * @constructor
  1026. */
  1027. util.HSVToRGB = function HSVToRGB(h, s, v) {
  1028. var r, g, b;
  1029. var i = Math.floor(h * 6);
  1030. var f = h * 6 - i;
  1031. var p = v * (1 - s);
  1032. var q = v * (1 - f * s);
  1033. var t = v * (1 - (1 - f) * s);
  1034. switch (i % 6) {
  1035. case 0: r = v, g = t, b = p; break;
  1036. case 1: r = q, g = v, b = p; break;
  1037. case 2: r = p, g = v, b = t; break;
  1038. case 3: r = p, g = q, b = v; break;
  1039. case 4: r = t, g = p, b = v; break;
  1040. case 5: r = v, g = p, b = q; break;
  1041. }
  1042. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  1043. };
  1044. util.HSVToHex = function HSVToHex(h, s, v) {
  1045. var rgb = util.HSVToRGB(h, s, v);
  1046. return util.RGBToHex(rgb.r, rgb.g, rgb.b);
  1047. };
  1048. util.hexToHSV = function hexToHSV(hex) {
  1049. var rgb = util.hexToRGB(hex);
  1050. return util.RGBToHSV(rgb.r, rgb.g, rgb.b);
  1051. };
  1052. util.isValidHex = function isValidHex(hex) {
  1053. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1054. return isOk;
  1055. };
  1056. util.copyObject = function copyObject(objectFrom, objectTo) {
  1057. for (var i in objectFrom) {
  1058. if (objectFrom.hasOwnProperty(i)) {
  1059. if (typeof objectFrom[i] == "object") {
  1060. objectTo[i] = {};
  1061. util.copyObject(objectFrom[i], objectTo[i]);
  1062. }
  1063. else {
  1064. objectTo[i] = objectFrom[i];
  1065. }
  1066. }
  1067. }
  1068. };
  1069. /**
  1070. * DataSet
  1071. *
  1072. * Usage:
  1073. * var dataSet = new DataSet({
  1074. * fieldId: '_id',
  1075. * convert: {
  1076. * // ...
  1077. * }
  1078. * });
  1079. *
  1080. * dataSet.add(item);
  1081. * dataSet.add(data);
  1082. * dataSet.update(item);
  1083. * dataSet.update(data);
  1084. * dataSet.remove(id);
  1085. * dataSet.remove(ids);
  1086. * var data = dataSet.get();
  1087. * var data = dataSet.get(id);
  1088. * var data = dataSet.get(ids);
  1089. * var data = dataSet.get(ids, options, data);
  1090. * dataSet.clear();
  1091. *
  1092. * A data set can:
  1093. * - add/remove/update data
  1094. * - gives triggers upon changes in the data
  1095. * - can import/export data in various data formats
  1096. *
  1097. * @param {Array | DataTable} [data] Optional array with initial data
  1098. * @param {Object} [options] Available options:
  1099. * {String} fieldId Field name of the id in the
  1100. * items, 'id' by default.
  1101. * {Object.<String, String} convert
  1102. * A map with field names as key,
  1103. * and the field type as value.
  1104. * @constructor DataSet
  1105. */
  1106. // TODO: add a DataSet constructor DataSet(data, options)
  1107. function DataSet (data, options) {
  1108. this.id = util.randomUUID();
  1109. // correctly read optional arguments
  1110. if (data && !Array.isArray(data) && !util.isDataTable(data)) {
  1111. options = data;
  1112. data = null;
  1113. }
  1114. this.options = options || {};
  1115. this.data = {}; // map with data indexed by id
  1116. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1117. this.convert = {}; // field types by field name
  1118. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1119. if (this.options.convert) {
  1120. for (var field in this.options.convert) {
  1121. if (this.options.convert.hasOwnProperty(field)) {
  1122. var value = this.options.convert[field];
  1123. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1124. this.convert[field] = 'Date';
  1125. }
  1126. else {
  1127. this.convert[field] = value;
  1128. }
  1129. }
  1130. }
  1131. }
  1132. this.subscribers = {}; // event subscribers
  1133. this.internalIds = {}; // internally generated id's
  1134. // add initial data when provided
  1135. if (data) {
  1136. this.add(data);
  1137. }
  1138. }
  1139. /**
  1140. * Subscribe to an event, add an event listener
  1141. * @param {String} event Event name. Available events: 'put', 'update',
  1142. * 'remove'
  1143. * @param {function} callback Callback method. Called with three parameters:
  1144. * {String} event
  1145. * {Object | null} params
  1146. * {String | Number} senderId
  1147. */
  1148. DataSet.prototype.on = function on (event, callback) {
  1149. var subscribers = this.subscribers[event];
  1150. if (!subscribers) {
  1151. subscribers = [];
  1152. this.subscribers[event] = subscribers;
  1153. }
  1154. subscribers.push({
  1155. callback: callback
  1156. });
  1157. };
  1158. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1159. DataSet.prototype.subscribe = DataSet.prototype.on;
  1160. /**
  1161. * Unsubscribe from an event, remove an event listener
  1162. * @param {String} event
  1163. * @param {function} callback
  1164. */
  1165. DataSet.prototype.off = function off(event, callback) {
  1166. var subscribers = this.subscribers[event];
  1167. if (subscribers) {
  1168. this.subscribers[event] = subscribers.filter(function (listener) {
  1169. return (listener.callback != callback);
  1170. });
  1171. }
  1172. };
  1173. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1174. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1175. /**
  1176. * Trigger an event
  1177. * @param {String} event
  1178. * @param {Object | null} params
  1179. * @param {String} [senderId] Optional id of the sender.
  1180. * @private
  1181. */
  1182. DataSet.prototype._trigger = function (event, params, senderId) {
  1183. if (event == '*') {
  1184. throw new Error('Cannot trigger event *');
  1185. }
  1186. var subscribers = [];
  1187. if (event in this.subscribers) {
  1188. subscribers = subscribers.concat(this.subscribers[event]);
  1189. }
  1190. if ('*' in this.subscribers) {
  1191. subscribers = subscribers.concat(this.subscribers['*']);
  1192. }
  1193. for (var i = 0; i < subscribers.length; i++) {
  1194. var subscriber = subscribers[i];
  1195. if (subscriber.callback) {
  1196. subscriber.callback(event, params, senderId || null);
  1197. }
  1198. }
  1199. };
  1200. /**
  1201. * Add data.
  1202. * Adding an item will fail when there already is an item with the same id.
  1203. * @param {Object | Array | DataTable} data
  1204. * @param {String} [senderId] Optional sender id
  1205. * @return {Array} addedIds Array with the ids of the added items
  1206. */
  1207. DataSet.prototype.add = function (data, senderId) {
  1208. var addedIds = [],
  1209. id,
  1210. me = this;
  1211. if (data instanceof Array) {
  1212. // Array
  1213. for (var i = 0, len = data.length; i < len; i++) {
  1214. id = me._addItem(data[i]);
  1215. addedIds.push(id);
  1216. }
  1217. }
  1218. else if (util.isDataTable(data)) {
  1219. // Google DataTable
  1220. var columns = this._getColumnNames(data);
  1221. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1222. var item = {};
  1223. for (var col = 0, cols = columns.length; col < cols; col++) {
  1224. var field = columns[col];
  1225. item[field] = data.getValue(row, col);
  1226. }
  1227. id = me._addItem(item);
  1228. addedIds.push(id);
  1229. }
  1230. }
  1231. else if (data instanceof Object) {
  1232. // Single item
  1233. id = me._addItem(data);
  1234. addedIds.push(id);
  1235. }
  1236. else {
  1237. throw new Error('Unknown dataType');
  1238. }
  1239. if (addedIds.length) {
  1240. this._trigger('add', {items: addedIds}, senderId);
  1241. }
  1242. return addedIds;
  1243. };
  1244. /**
  1245. * Update existing items. When an item does not exist, it will be created
  1246. * @param {Object | Array | DataTable} data
  1247. * @param {String} [senderId] Optional sender id
  1248. * @return {Array} updatedIds The ids of the added or updated items
  1249. */
  1250. DataSet.prototype.update = function (data, senderId) {
  1251. var addedIds = [],
  1252. updatedIds = [],
  1253. me = this,
  1254. fieldId = me.fieldId;
  1255. var addOrUpdate = function (item) {
  1256. var id = item[fieldId];
  1257. if (me.data[id]) {
  1258. // update item
  1259. id = me._updateItem(item);
  1260. updatedIds.push(id);
  1261. }
  1262. else {
  1263. // add new item
  1264. id = me._addItem(item);
  1265. addedIds.push(id);
  1266. }
  1267. };
  1268. if (data instanceof Array) {
  1269. // Array
  1270. for (var i = 0, len = data.length; i < len; i++) {
  1271. addOrUpdate(data[i]);
  1272. }
  1273. }
  1274. else if (util.isDataTable(data)) {
  1275. // Google DataTable
  1276. var columns = this._getColumnNames(data);
  1277. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1278. var item = {};
  1279. for (var col = 0, cols = columns.length; col < cols; col++) {
  1280. var field = columns[col];
  1281. item[field] = data.getValue(row, col);
  1282. }
  1283. addOrUpdate(item);
  1284. }
  1285. }
  1286. else if (data instanceof Object) {
  1287. // Single item
  1288. addOrUpdate(data);
  1289. }
  1290. else {
  1291. throw new Error('Unknown dataType');
  1292. }
  1293. if (addedIds.length) {
  1294. this._trigger('add', {items: addedIds}, senderId);
  1295. }
  1296. if (updatedIds.length) {
  1297. this._trigger('update', {items: updatedIds}, senderId);
  1298. }
  1299. return addedIds.concat(updatedIds);
  1300. };
  1301. /**
  1302. * Get a data item or multiple items.
  1303. *
  1304. * Usage:
  1305. *
  1306. * get()
  1307. * get(options: Object)
  1308. * get(options: Object, data: Array | DataTable)
  1309. *
  1310. * get(id: Number | String)
  1311. * get(id: Number | String, options: Object)
  1312. * get(id: Number | String, options: Object, data: Array | DataTable)
  1313. *
  1314. * get(ids: Number[] | String[])
  1315. * get(ids: Number[] | String[], options: Object)
  1316. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1317. *
  1318. * Where:
  1319. *
  1320. * {Number | String} id The id of an item
  1321. * {Number[] | String{}} ids An array with ids of items
  1322. * {Object} options An Object with options. Available options:
  1323. * {String} [type] Type of data to be returned. Can
  1324. * be 'DataTable' or 'Array' (default)
  1325. * {Object.<String, String>} [convert]
  1326. * {String[]} [fields] field names to be returned
  1327. * {function} [filter] filter items
  1328. * {String | function} [order] Order the items by
  1329. * a field name or custom sort function.
  1330. * {Array | DataTable} [data] If provided, items will be appended to this
  1331. * array or table. Required in case of Google
  1332. * DataTable.
  1333. *
  1334. * @throws Error
  1335. */
  1336. DataSet.prototype.get = function (args) {
  1337. var me = this;
  1338. var globalShowInternalIds = this.showInternalIds;
  1339. // parse the arguments
  1340. var id, ids, options, data;
  1341. var firstType = util.getType(arguments[0]);
  1342. if (firstType == 'String' || firstType == 'Number') {
  1343. // get(id [, options] [, data])
  1344. id = arguments[0];
  1345. options = arguments[1];
  1346. data = arguments[2];
  1347. }
  1348. else if (firstType == 'Array') {
  1349. // get(ids [, options] [, data])
  1350. ids = arguments[0];
  1351. options = arguments[1];
  1352. data = arguments[2];
  1353. }
  1354. else {
  1355. // get([, options] [, data])
  1356. options = arguments[0];
  1357. data = arguments[1];
  1358. }
  1359. // determine the return type
  1360. var type;
  1361. if (options && options.type) {
  1362. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1363. if (data && (type != util.getType(data))) {
  1364. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1365. 'does not correspond with specified options.type (' + options.type + ')');
  1366. }
  1367. if (type == 'DataTable' && !util.isDataTable(data)) {
  1368. throw new Error('Parameter "data" must be a DataTable ' +
  1369. 'when options.type is "DataTable"');
  1370. }
  1371. }
  1372. else if (data) {
  1373. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1374. }
  1375. else {
  1376. type = 'Array';
  1377. }
  1378. // we allow the setting of this value for a single get request.
  1379. if (options != undefined) {
  1380. if (options.showInternalIds != undefined) {
  1381. this.showInternalIds = options.showInternalIds;
  1382. }
  1383. }
  1384. // build options
  1385. var convert = options && options.convert || this.options.convert;
  1386. var filter = options && options.filter;
  1387. var items = [], item, itemId, i, len;
  1388. // convert items
  1389. if (id != undefined) {
  1390. // return a single item
  1391. item = me._getItem(id, convert);
  1392. if (filter && !filter(item)) {
  1393. item = null;
  1394. }
  1395. }
  1396. else if (ids != undefined) {
  1397. // return a subset of items
  1398. for (i = 0, len = ids.length; i < len; i++) {
  1399. item = me._getItem(ids[i], convert);
  1400. if (!filter || filter(item)) {
  1401. items.push(item);
  1402. }
  1403. }
  1404. }
  1405. else {
  1406. // return all items
  1407. for (itemId in this.data) {
  1408. if (this.data.hasOwnProperty(itemId)) {
  1409. item = me._getItem(itemId, convert);
  1410. if (!filter || filter(item)) {
  1411. items.push(item);
  1412. }
  1413. }
  1414. }
  1415. }
  1416. // restore the global value of showInternalIds
  1417. this.showInternalIds = globalShowInternalIds;
  1418. // order the results
  1419. if (options && options.order && id == undefined) {
  1420. this._sort(items, options.order);
  1421. }
  1422. // filter fields of the items
  1423. if (options && options.fields) {
  1424. var fields = options.fields;
  1425. if (id != undefined) {
  1426. item = this._filterFields(item, fields);
  1427. }
  1428. else {
  1429. for (i = 0, len = items.length; i < len; i++) {
  1430. items[i] = this._filterFields(items[i], fields);
  1431. }
  1432. }
  1433. }
  1434. // return the results
  1435. if (type == 'DataTable') {
  1436. var columns = this._getColumnNames(data);
  1437. if (id != undefined) {
  1438. // append a single item to the data table
  1439. me._appendRow(data, columns, item);
  1440. }
  1441. else {
  1442. // copy the items to the provided data table
  1443. for (i = 0, len = items.length; i < len; i++) {
  1444. me._appendRow(data, columns, items[i]);
  1445. }
  1446. }
  1447. return data;
  1448. }
  1449. else {
  1450. // return an array
  1451. if (id != undefined) {
  1452. // a single item
  1453. return item;
  1454. }
  1455. else {
  1456. // multiple items
  1457. if (data) {
  1458. // copy the items to the provided array
  1459. for (i = 0, len = items.length; i < len; i++) {
  1460. data.push(items[i]);
  1461. }
  1462. return data;
  1463. }
  1464. else {
  1465. // just return our array
  1466. return items;
  1467. }
  1468. }
  1469. }
  1470. };
  1471. /**
  1472. * Get ids of all items or from a filtered set of items.
  1473. * @param {Object} [options] An Object with options. Available options:
  1474. * {function} [filter] filter items
  1475. * {String | function} [order] Order the items by
  1476. * a field name or custom sort function.
  1477. * @return {Array} ids
  1478. */
  1479. DataSet.prototype.getIds = function (options) {
  1480. var data = this.data,
  1481. filter = options && options.filter,
  1482. order = options && options.order,
  1483. convert = options && options.convert || this.options.convert,
  1484. i,
  1485. len,
  1486. id,
  1487. item,
  1488. items,
  1489. ids = [];
  1490. if (filter) {
  1491. // get filtered items
  1492. if (order) {
  1493. // create ordered list
  1494. items = [];
  1495. for (id in data) {
  1496. if (data.hasOwnProperty(id)) {
  1497. item = this._getItem(id, convert);
  1498. if (filter(item)) {
  1499. items.push(item);
  1500. }
  1501. }
  1502. }
  1503. this._sort(items, order);
  1504. for (i = 0, len = items.length; i < len; i++) {
  1505. ids[i] = items[i][this.fieldId];
  1506. }
  1507. }
  1508. else {
  1509. // create unordered list
  1510. for (id in data) {
  1511. if (data.hasOwnProperty(id)) {
  1512. item = this._getItem(id, convert);
  1513. if (filter(item)) {
  1514. ids.push(item[this.fieldId]);
  1515. }
  1516. }
  1517. }
  1518. }
  1519. }
  1520. else {
  1521. // get all items
  1522. if (order) {
  1523. // create an ordered list
  1524. items = [];
  1525. for (id in data) {
  1526. if (data.hasOwnProperty(id)) {
  1527. items.push(data[id]);
  1528. }
  1529. }
  1530. this._sort(items, order);
  1531. for (i = 0, len = items.length; i < len; i++) {
  1532. ids[i] = items[i][this.fieldId];
  1533. }
  1534. }
  1535. else {
  1536. // create unordered list
  1537. for (id in data) {
  1538. if (data.hasOwnProperty(id)) {
  1539. item = data[id];
  1540. ids.push(item[this.fieldId]);
  1541. }
  1542. }
  1543. }
  1544. }
  1545. return ids;
  1546. };
  1547. /**
  1548. * Execute a callback function for every item in the dataset.
  1549. * @param {function} callback
  1550. * @param {Object} [options] Available options:
  1551. * {Object.<String, String>} [convert]
  1552. * {String[]} [fields] filter fields
  1553. * {function} [filter] filter items
  1554. * {String | function} [order] Order the items by
  1555. * a field name or custom sort function.
  1556. */
  1557. DataSet.prototype.forEach = function (callback, options) {
  1558. var filter = options && options.filter,
  1559. convert = options && options.convert || this.options.convert,
  1560. data = this.data,
  1561. item,
  1562. id;
  1563. if (options && options.order) {
  1564. // execute forEach on ordered list
  1565. var items = this.get(options);
  1566. for (var i = 0, len = items.length; i < len; i++) {
  1567. item = items[i];
  1568. id = item[this.fieldId];
  1569. callback(item, id);
  1570. }
  1571. }
  1572. else {
  1573. // unordered
  1574. for (id in data) {
  1575. if (data.hasOwnProperty(id)) {
  1576. item = this._getItem(id, convert);
  1577. if (!filter || filter(item)) {
  1578. callback(item, id);
  1579. }
  1580. }
  1581. }
  1582. }
  1583. };
  1584. /**
  1585. * Map every item in the dataset.
  1586. * @param {function} callback
  1587. * @param {Object} [options] Available options:
  1588. * {Object.<String, String>} [convert]
  1589. * {String[]} [fields] filter fields
  1590. * {function} [filter] filter items
  1591. * {String | function} [order] Order the items by
  1592. * a field name or custom sort function.
  1593. * @return {Object[]} mappedItems
  1594. */
  1595. DataSet.prototype.map = function (callback, options) {
  1596. var filter = options && options.filter,
  1597. convert = options && options.convert || this.options.convert,
  1598. mappedItems = [],
  1599. data = this.data,
  1600. item;
  1601. // convert and filter items
  1602. for (var id in data) {
  1603. if (data.hasOwnProperty(id)) {
  1604. item = this._getItem(id, convert);
  1605. if (!filter || filter(item)) {
  1606. mappedItems.push(callback(item, id));
  1607. }
  1608. }
  1609. }
  1610. // order items
  1611. if (options && options.order) {
  1612. this._sort(mappedItems, options.order);
  1613. }
  1614. return mappedItems;
  1615. };
  1616. /**
  1617. * Filter the fields of an item
  1618. * @param {Object} item
  1619. * @param {String[]} fields Field names
  1620. * @return {Object} filteredItem
  1621. * @private
  1622. */
  1623. DataSet.prototype._filterFields = function (item, fields) {
  1624. var filteredItem = {};
  1625. for (var field in item) {
  1626. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1627. filteredItem[field] = item[field];
  1628. }
  1629. }
  1630. return filteredItem;
  1631. };
  1632. /**
  1633. * Sort the provided array with items
  1634. * @param {Object[]} items
  1635. * @param {String | function} order A field name or custom sort function.
  1636. * @private
  1637. */
  1638. DataSet.prototype._sort = function (items, order) {
  1639. if (util.isString(order)) {
  1640. // order by provided field name
  1641. var name = order; // field name
  1642. items.sort(function (a, b) {
  1643. var av = a[name];
  1644. var bv = b[name];
  1645. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1646. });
  1647. }
  1648. else if (typeof order === 'function') {
  1649. // order by sort function
  1650. items.sort(order);
  1651. }
  1652. // TODO: extend order by an Object {field:String, direction:String}
  1653. // where direction can be 'asc' or 'desc'
  1654. else {
  1655. throw new TypeError('Order must be a function or a string');
  1656. }
  1657. };
  1658. /**
  1659. * Remove an object by pointer or by id
  1660. * @param {String | Number | Object | Array} id Object or id, or an array with
  1661. * objects or ids to be removed
  1662. * @param {String} [senderId] Optional sender id
  1663. * @return {Array} removedIds
  1664. */
  1665. DataSet.prototype.remove = function (id, senderId) {
  1666. var removedIds = [],
  1667. i, len, removedId;
  1668. if (id instanceof Array) {
  1669. for (i = 0, len = id.length; i < len; i++) {
  1670. removedId = this._remove(id[i]);
  1671. if (removedId != null) {
  1672. removedIds.push(removedId);
  1673. }
  1674. }
  1675. }
  1676. else {
  1677. removedId = this._remove(id);
  1678. if (removedId != null) {
  1679. removedIds.push(removedId);
  1680. }
  1681. }
  1682. if (removedIds.length) {
  1683. this._trigger('remove', {items: removedIds}, senderId);
  1684. }
  1685. return removedIds;
  1686. };
  1687. /**
  1688. * Remove an item by its id
  1689. * @param {Number | String | Object} id id or item
  1690. * @returns {Number | String | null} id
  1691. * @private
  1692. */
  1693. DataSet.prototype._remove = function (id) {
  1694. if (util.isNumber(id) || util.isString(id)) {
  1695. if (this.data[id]) {
  1696. delete this.data[id];
  1697. delete this.internalIds[id];
  1698. return id;
  1699. }
  1700. }
  1701. else if (id instanceof Object) {
  1702. var itemId = id[this.fieldId];
  1703. if (itemId && this.data[itemId]) {
  1704. delete this.data[itemId];
  1705. delete this.internalIds[itemId];
  1706. return itemId;
  1707. }
  1708. }
  1709. return null;
  1710. };
  1711. /**
  1712. * Clear the data
  1713. * @param {String} [senderId] Optional sender id
  1714. * @return {Array} removedIds The ids of all removed items
  1715. */
  1716. DataSet.prototype.clear = function (senderId) {
  1717. var ids = Object.keys(this.data);
  1718. this.data = {};
  1719. this.internalIds = {};
  1720. this._trigger('remove', {items: ids}, senderId);
  1721. return ids;
  1722. };
  1723. /**
  1724. * Find the item with maximum value of a specified field
  1725. * @param {String} field
  1726. * @return {Object | null} item Item containing max value, or null if no items
  1727. */
  1728. DataSet.prototype.max = function (field) {
  1729. var data = this.data,
  1730. max = null,
  1731. maxField = null;
  1732. for (var id in data) {
  1733. if (data.hasOwnProperty(id)) {
  1734. var item = data[id];
  1735. var itemField = item[field];
  1736. if (itemField != null && (!max || itemField > maxField)) {
  1737. max = item;
  1738. maxField = itemField;
  1739. }
  1740. }
  1741. }
  1742. return max;
  1743. };
  1744. /**
  1745. * Find the item with minimum value of a specified field
  1746. * @param {String} field
  1747. * @return {Object | null} item Item containing max value, or null if no items
  1748. */
  1749. DataSet.prototype.min = function (field) {
  1750. var data = this.data,
  1751. min = null,
  1752. minField = null;
  1753. for (var id in data) {
  1754. if (data.hasOwnProperty(id)) {
  1755. var item = data[id];
  1756. var itemField = item[field];
  1757. if (itemField != null && (!min || itemField < minField)) {
  1758. min = item;
  1759. minField = itemField;
  1760. }
  1761. }
  1762. }
  1763. return min;
  1764. };
  1765. /**
  1766. * Find all distinct values of a specified field
  1767. * @param {String} field
  1768. * @return {Array} values Array containing all distinct values. If data items
  1769. * do not contain the specified field are ignored.
  1770. * The returned array is unordered.
  1771. */
  1772. DataSet.prototype.distinct = function (field) {
  1773. var data = this.data,
  1774. values = [],
  1775. fieldType = this.options.convert[field],
  1776. count = 0;
  1777. for (var prop in data) {
  1778. if (data.hasOwnProperty(prop)) {
  1779. var item = data[prop];
  1780. var value = util.convert(item[field], fieldType);
  1781. var exists = false;
  1782. for (var i = 0; i < count; i++) {
  1783. if (values[i] == value) {
  1784. exists = true;
  1785. break;
  1786. }
  1787. }
  1788. if (!exists && (value !== undefined)) {
  1789. values[count] = value;
  1790. count++;
  1791. }
  1792. }
  1793. }
  1794. return values;
  1795. };
  1796. /**
  1797. * Add a single item. Will fail when an item with the same id already exists.
  1798. * @param {Object} item
  1799. * @return {String} id
  1800. * @private
  1801. */
  1802. DataSet.prototype._addItem = function (item) {
  1803. var id = item[this.fieldId];
  1804. if (id != undefined) {
  1805. // check whether this id is already taken
  1806. if (this.data[id]) {
  1807. // item already exists
  1808. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1809. }
  1810. }
  1811. else {
  1812. // generate an id
  1813. id = util.randomUUID();
  1814. item[this.fieldId] = id;
  1815. this.internalIds[id] = item;
  1816. }
  1817. var d = {};
  1818. for (var field in item) {
  1819. if (item.hasOwnProperty(field)) {
  1820. var fieldType = this.convert[field]; // type may be undefined
  1821. d[field] = util.convert(item[field], fieldType);
  1822. }
  1823. }
  1824. this.data[id] = d;
  1825. return id;
  1826. };
  1827. /**
  1828. * Get an item. Fields can be converted to a specific type
  1829. * @param {String} id
  1830. * @param {Object.<String, String>} [convert] field types to convert
  1831. * @return {Object | null} item
  1832. * @private
  1833. */
  1834. DataSet.prototype._getItem = function (id, convert) {
  1835. var field, value;
  1836. // get the item from the dataset
  1837. var raw = this.data[id];
  1838. if (!raw) {
  1839. return null;
  1840. }
  1841. // convert the items field types
  1842. var converted = {},
  1843. fieldId = this.fieldId,
  1844. internalIds = this.internalIds;
  1845. if (convert) {
  1846. for (field in raw) {
  1847. if (raw.hasOwnProperty(field)) {
  1848. value = raw[field];
  1849. // output all fields, except internal ids
  1850. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1851. converted[field] = util.convert(value, convert[field]);
  1852. }
  1853. }
  1854. }
  1855. }
  1856. else {
  1857. // no field types specified, no converting needed
  1858. for (field in raw) {
  1859. if (raw.hasOwnProperty(field)) {
  1860. value = raw[field];
  1861. // output all fields, except internal ids
  1862. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1863. converted[field] = value;
  1864. }
  1865. }
  1866. }
  1867. }
  1868. return converted;
  1869. };
  1870. /**
  1871. * Update a single item: merge with existing item.
  1872. * Will fail when the item has no id, or when there does not exist an item
  1873. * with the same id.
  1874. * @param {Object} item
  1875. * @return {String} id
  1876. * @private
  1877. */
  1878. DataSet.prototype._updateItem = function (item) {
  1879. var id = item[this.fieldId];
  1880. if (id == undefined) {
  1881. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1882. }
  1883. var d = this.data[id];
  1884. if (!d) {
  1885. // item doesn't exist
  1886. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1887. }
  1888. // merge with current item
  1889. for (var field in item) {
  1890. if (item.hasOwnProperty(field)) {
  1891. var fieldType = this.convert[field]; // type may be undefined
  1892. d[field] = util.convert(item[field], fieldType);
  1893. }
  1894. }
  1895. return id;
  1896. };
  1897. /**
  1898. * check if an id is an internal or external id
  1899. * @param id
  1900. * @returns {boolean}
  1901. * @private
  1902. */
  1903. DataSet.prototype.isInternalId = function(id) {
  1904. return (id in this.internalIds);
  1905. };
  1906. /**
  1907. * Get an array with the column names of a Google DataTable
  1908. * @param {DataTable} dataTable
  1909. * @return {String[]} columnNames
  1910. * @private
  1911. */
  1912. DataSet.prototype._getColumnNames = function (dataTable) {
  1913. var columns = [];
  1914. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1915. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1916. }
  1917. return columns;
  1918. };
  1919. /**
  1920. * Append an item as a row to the dataTable
  1921. * @param dataTable
  1922. * @param columns
  1923. * @param item
  1924. * @private
  1925. */
  1926. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1927. var row = dataTable.addRow();
  1928. for (var col = 0, cols = columns.length; col < cols; col++) {
  1929. var field = columns[col];
  1930. dataTable.setValue(row, col, item[field]);
  1931. }
  1932. };
  1933. /**
  1934. * DataView
  1935. *
  1936. * a dataview offers a filtered view on a dataset or an other dataview.
  1937. *
  1938. * @param {DataSet | DataView} data
  1939. * @param {Object} [options] Available options: see method get
  1940. *
  1941. * @constructor DataView
  1942. */
  1943. function DataView (data, options) {
  1944. this.id = util.randomUUID();
  1945. this.data = null;
  1946. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1947. this.options = options || {};
  1948. this.fieldId = 'id'; // name of the field containing id
  1949. this.subscribers = {}; // event subscribers
  1950. var me = this;
  1951. this.listener = function () {
  1952. me._onEvent.apply(me, arguments);
  1953. };
  1954. this.setData(data);
  1955. }
  1956. // TODO: implement a function .config() to dynamically update things like configured filter
  1957. // and trigger changes accordingly
  1958. /**
  1959. * Set a data source for the view
  1960. * @param {DataSet | DataView} data
  1961. */
  1962. DataView.prototype.setData = function (data) {
  1963. var ids, dataItems, i, len;
  1964. if (this.data) {
  1965. // unsubscribe from current dataset
  1966. if (this.data.unsubscribe) {
  1967. this.data.unsubscribe('*', this.listener);
  1968. }
  1969. // trigger a remove of all items in memory
  1970. ids = [];
  1971. for (var id in this.ids) {
  1972. if (this.ids.hasOwnProperty(id)) {
  1973. ids.push(id);
  1974. }
  1975. }
  1976. this.ids = {};
  1977. this._trigger('remove', {items: ids});
  1978. }
  1979. this.data = data;
  1980. if (this.data) {
  1981. // update fieldId
  1982. this.fieldId = this.options.fieldId ||
  1983. (this.data && this.data.options && this.data.options.fieldId) ||
  1984. 'id';
  1985. // trigger an add of all added items
  1986. ids = this.data.getIds({filter: this.options && this.options.filter});
  1987. for (i = 0, len = ids.length; i < len; i++) {
  1988. id = ids[i];
  1989. this.ids[id] = true;
  1990. }
  1991. this._trigger('add', {items: ids});
  1992. // subscribe to new dataset
  1993. if (this.data.on) {
  1994. this.data.on('*', this.listener);
  1995. }
  1996. }
  1997. };
  1998. /**
  1999. * Get data from the data view
  2000. *
  2001. * Usage:
  2002. *
  2003. * get()
  2004. * get(options: Object)
  2005. * get(options: Object, data: Array | DataTable)
  2006. *
  2007. * get(id: Number)
  2008. * get(id: Number, options: Object)
  2009. * get(id: Number, options: Object, data: Array | DataTable)
  2010. *
  2011. * get(ids: Number[])
  2012. * get(ids: Number[], options: Object)
  2013. * get(ids: Number[], options: Object, data: Array | DataTable)
  2014. *
  2015. * Where:
  2016. *
  2017. * {Number | String} id The id of an item
  2018. * {Number[] | String{}} ids An array with ids of items
  2019. * {Object} options An Object with options. Available options:
  2020. * {String} [type] Type of data to be returned. Can
  2021. * be 'DataTable' or 'Array' (default)
  2022. * {Object.<String, String>} [convert]
  2023. * {String[]} [fields] field names to be returned
  2024. * {function} [filter] filter items
  2025. * {String | function} [order] Order the items by
  2026. * a field name or custom sort function.
  2027. * {Array | DataTable} [data] If provided, items will be appended to this
  2028. * array or table. Required in case of Google
  2029. * DataTable.
  2030. * @param args
  2031. */
  2032. DataView.prototype.get = function (args) {
  2033. var me = this;
  2034. // parse the arguments
  2035. var ids, options, data;
  2036. var firstType = util.getType(arguments[0]);
  2037. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2038. // get(id(s) [, options] [, data])
  2039. ids = arguments[0]; // can be a single id or an array with ids
  2040. options = arguments[1];
  2041. data = arguments[2];
  2042. }
  2043. else {
  2044. // get([, options] [, data])
  2045. options = arguments[0];
  2046. data = arguments[1];
  2047. }
  2048. // extend the options with the default options and provided options
  2049. var viewOptions = util.extend({}, this.options, options);
  2050. // create a combined filter method when needed
  2051. if (this.options.filter && options && options.filter) {
  2052. viewOptions.filter = function (item) {
  2053. return me.options.filter(item) && options.filter(item);
  2054. }
  2055. }
  2056. // build up the call to the linked data set
  2057. var getArguments = [];
  2058. if (ids != undefined) {
  2059. getArguments.push(ids);
  2060. }
  2061. getArguments.push(viewOptions);
  2062. getArguments.push(data);
  2063. return this.data && this.data.get.apply(this.data, getArguments);
  2064. };
  2065. /**
  2066. * Get ids of all items or from a filtered set of items.
  2067. * @param {Object} [options] An Object with options. Available options:
  2068. * {function} [filter] filter items
  2069. * {String | function} [order] Order the items by
  2070. * a field name or custom sort function.
  2071. * @return {Array} ids
  2072. */
  2073. DataView.prototype.getIds = function (options) {
  2074. var ids;
  2075. if (this.data) {
  2076. var defaultFilter = this.options.filter;
  2077. var filter;
  2078. if (options && options.filter) {
  2079. if (defaultFilter) {
  2080. filter = function (item) {
  2081. return defaultFilter(item) && options.filter(item);
  2082. }
  2083. }
  2084. else {
  2085. filter = options.filter;
  2086. }
  2087. }
  2088. else {
  2089. filter = defaultFilter;
  2090. }
  2091. ids = this.data.getIds({
  2092. filter: filter,
  2093. order: options && options.order
  2094. });
  2095. }
  2096. else {
  2097. ids = [];
  2098. }
  2099. return ids;
  2100. };
  2101. /**
  2102. * Event listener. Will propagate all events from the connected data set to
  2103. * the subscribers of the DataView, but will filter the items and only trigger
  2104. * when there are changes in the filtered data set.
  2105. * @param {String} event
  2106. * @param {Object | null} params
  2107. * @param {String} senderId
  2108. * @private
  2109. */
  2110. DataView.prototype._onEvent = function (event, params, senderId) {
  2111. var i, len, id, item,
  2112. ids = params && params.items,
  2113. data = this.data,
  2114. added = [],
  2115. updated = [],
  2116. removed = [];
  2117. if (ids && data) {
  2118. switch (event) {
  2119. case 'add':
  2120. // filter the ids of the added items
  2121. for (i = 0, len = ids.length; i < len; i++) {
  2122. id = ids[i];
  2123. item = this.get(id);
  2124. if (item) {
  2125. this.ids[id] = true;
  2126. added.push(id);
  2127. }
  2128. }
  2129. break;
  2130. case 'update':
  2131. // determine the event from the views viewpoint: an updated
  2132. // item can be added, updated, or removed from this view.
  2133. for (i = 0, len = ids.length; i < len; i++) {
  2134. id = ids[i];
  2135. item = this.get(id);
  2136. if (item) {
  2137. if (this.ids[id]) {
  2138. updated.push(id);
  2139. }
  2140. else {
  2141. this.ids[id] = true;
  2142. added.push(id);
  2143. }
  2144. }
  2145. else {
  2146. if (this.ids[id]) {
  2147. delete this.ids[id];
  2148. removed.push(id);
  2149. }
  2150. else {
  2151. // nothing interesting for me :-(
  2152. }
  2153. }
  2154. }
  2155. break;
  2156. case 'remove':
  2157. // filter the ids of the removed items
  2158. for (i = 0, len = ids.length; i < len; i++) {
  2159. id = ids[i];
  2160. if (this.ids[id]) {
  2161. delete this.ids[id];
  2162. removed.push(id);
  2163. }
  2164. }
  2165. break;
  2166. }
  2167. if (added.length) {
  2168. this._trigger('add', {items: added}, senderId);
  2169. }
  2170. if (updated.length) {
  2171. this._trigger('update', {items: updated}, senderId);
  2172. }
  2173. if (removed.length) {
  2174. this._trigger('remove', {items: removed}, senderId);
  2175. }
  2176. }
  2177. };
  2178. // copy subscription functionality from DataSet
  2179. DataView.prototype.on = DataSet.prototype.on;
  2180. DataView.prototype.off = DataSet.prototype.off;
  2181. DataView.prototype._trigger = DataSet.prototype._trigger;
  2182. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2183. DataView.prototype.subscribe = DataView.prototype.on;
  2184. DataView.prototype.unsubscribe = DataView.prototype.off;
  2185. /**
  2186. * Utility functions for ordering and stacking of items
  2187. */
  2188. var stack = {};
  2189. /**
  2190. * Order items by their start data
  2191. * @param {Item[]} items
  2192. */
  2193. stack.orderByStart = function orderByStart(items) {
  2194. items.sort(function (a, b) {
  2195. return a.data.start - b.data.start;
  2196. });
  2197. };
  2198. /**
  2199. * Order items by their end date. If they have no end date, their start date
  2200. * is used.
  2201. * @param {Item[]} items
  2202. */
  2203. stack.orderByEnd = function orderByEnd(items) {
  2204. items.sort(function (a, b) {
  2205. var aTime = ('end' in a.data) ? a.data.end : a.data.start,
  2206. bTime = ('end' in b.data) ? b.data.end : b.data.start;
  2207. return aTime - bTime;
  2208. });
  2209. };
  2210. /**
  2211. * Adjust vertical positions of the items such that they don't overlap each
  2212. * other.
  2213. * @param {Item[]} items
  2214. * All visible items
  2215. * @param {{item: number, axis: number}} margin
  2216. * Margins between items and between items and the axis.
  2217. * @param {boolean} [force=false]
  2218. * If true, all items will be repositioned. If false (default), only
  2219. * items having a top===null will be re-stacked
  2220. */
  2221. stack.stack = function _stack (items, margin, force) {
  2222. var i, iMax;
  2223. if (force) {
  2224. // reset top position of all items
  2225. for (i = 0, iMax = items.length; i < iMax; i++) {
  2226. items[i].top = null;
  2227. }
  2228. }
  2229. // calculate new, non-overlapping positions
  2230. for (i = 0, iMax = items.length; i < iMax; i++) {
  2231. var item = items[i];
  2232. if (item.top === null) {
  2233. // initialize top position
  2234. item.top = margin.axis;
  2235. do {
  2236. // TODO: optimize checking for overlap. when there is a gap without items,
  2237. // you only need to check for items from the next item on, not from zero
  2238. var collidingItem = null;
  2239. for (var j = 0, jj = items.length; j < jj; j++) {
  2240. var other = items[j];
  2241. if (other.top !== null && other !== item && stack.collision(item, other, margin.item)) {
  2242. collidingItem = other;
  2243. break;
  2244. }
  2245. }
  2246. if (collidingItem != null) {
  2247. // There is a collision. Reposition the items above the colliding element
  2248. item.top = collidingItem.top + collidingItem.height + margin.item;
  2249. }
  2250. } while (collidingItem);
  2251. }
  2252. }
  2253. };
  2254. /**
  2255. * Adjust vertical positions of the items without stacking them
  2256. * @param {Item[]} items
  2257. * All visible items
  2258. * @param {{item: number, axis: number}} margin
  2259. * Margins between items and between items and the axis.
  2260. */
  2261. stack.nostack = function nostack (items, margin) {
  2262. var i, iMax;
  2263. // reset top position of all items
  2264. for (i = 0, iMax = items.length; i < iMax; i++) {
  2265. items[i].top = margin.axis;
  2266. }
  2267. };
  2268. /**
  2269. * Test if the two provided items collide
  2270. * The items must have parameters left, width, top, and height.
  2271. * @param {Item} a The first item
  2272. * @param {Item} b The second item
  2273. * @param {Number} margin A minimum required margin.
  2274. * If margin is provided, the two items will be
  2275. * marked colliding when they overlap or
  2276. * when the margin between the two is smaller than
  2277. * the requested margin.
  2278. * @return {boolean} true if a and b collide, else false
  2279. */
  2280. stack.collision = function collision (a, b, margin) {
  2281. return ((a.left - margin) < (b.left + b.width) &&
  2282. (a.left + a.width + margin) > b.left &&
  2283. (a.top - margin) < (b.top + b.height) &&
  2284. (a.top + a.height + margin) > b.top);
  2285. };
  2286. /**
  2287. * @constructor TimeStep
  2288. * The class TimeStep is an iterator for dates. You provide a start date and an
  2289. * end date. The class itself determines the best scale (step size) based on the
  2290. * provided start Date, end Date, and minimumStep.
  2291. *
  2292. * If minimumStep is provided, the step size is chosen as close as possible
  2293. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2294. * provided, the scale is set to 1 DAY.
  2295. * The minimumStep should correspond with the onscreen size of about 6 characters
  2296. *
  2297. * Alternatively, you can set a scale by hand.
  2298. * After creation, you can initialize the class by executing first(). Then you
  2299. * can iterate from the start date to the end date via next(). You can check if
  2300. * the end date is reached with the function hasNext(). After each step, you can
  2301. * retrieve the current date via getCurrent().
  2302. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2303. * days, to years.
  2304. *
  2305. * Version: 1.2
  2306. *
  2307. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2308. * or new Date(2010, 9, 21, 23, 45, 00)
  2309. * @param {Date} [end] The end date
  2310. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2311. */
  2312. TimeStep = function(start, end, minimumStep) {
  2313. // variables
  2314. this.current = new Date();
  2315. this._start = new Date();
  2316. this._end = new Date();
  2317. this.autoScale = true;
  2318. this.scale = TimeStep.SCALE.DAY;
  2319. this.step = 1;
  2320. // initialize the range
  2321. this.setRange(start, end, minimumStep);
  2322. };
  2323. /// enum scale
  2324. TimeStep.SCALE = {
  2325. MILLISECOND: 1,
  2326. SECOND: 2,
  2327. MINUTE: 3,
  2328. HOUR: 4,
  2329. DAY: 5,
  2330. WEEKDAY: 6,
  2331. MONTH: 7,
  2332. YEAR: 8
  2333. };
  2334. /**
  2335. * Set a new range
  2336. * If minimumStep is provided, the step size is chosen as close as possible
  2337. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2338. * provided, the scale is set to 1 DAY.
  2339. * The minimumStep should correspond with the onscreen size of about 6 characters
  2340. * @param {Date} [start] The start date and time.
  2341. * @param {Date} [end] The end date and time.
  2342. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2343. */
  2344. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2345. if (!(start instanceof Date) || !(end instanceof Date)) {
  2346. throw "No legal start or end date in method setRange";
  2347. }
  2348. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2349. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2350. if (this.autoScale) {
  2351. this.setMinimumStep(minimumStep);
  2352. }
  2353. };
  2354. /**
  2355. * Set the range iterator to the start date.
  2356. */
  2357. TimeStep.prototype.first = function() {
  2358. this.current = new Date(this._start.valueOf());
  2359. this.roundToMinor();
  2360. };
  2361. /**
  2362. * Round the current date to the first minor date value
  2363. * This must be executed once when the current date is set to start Date
  2364. */
  2365. TimeStep.prototype.roundToMinor = function() {
  2366. // round to floor
  2367. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2368. //noinspection FallthroughInSwitchStatementJS
  2369. switch (this.scale) {
  2370. case TimeStep.SCALE.YEAR:
  2371. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2372. this.current.setMonth(0);
  2373. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2374. case TimeStep.SCALE.DAY: // intentional fall through
  2375. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2376. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2377. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2378. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2379. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2380. }
  2381. if (this.step != 1) {
  2382. // round down to the first minor value that is a multiple of the current step size
  2383. switch (this.scale) {
  2384. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2385. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2386. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2387. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2388. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2389. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2390. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2391. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2392. default: break;
  2393. }
  2394. }
  2395. };
  2396. /**
  2397. * Check if the there is a next step
  2398. * @return {boolean} true if the current date has not passed the end date
  2399. */
  2400. TimeStep.prototype.hasNext = function () {
  2401. return (this.current.valueOf() <= this._end.valueOf());
  2402. };
  2403. /**
  2404. * Do the next step
  2405. */
  2406. TimeStep.prototype.next = function() {
  2407. var prev = this.current.valueOf();
  2408. // Two cases, needed to prevent issues with switching daylight savings
  2409. // (end of March and end of October)
  2410. if (this.current.getMonth() < 6) {
  2411. switch (this.scale) {
  2412. case TimeStep.SCALE.MILLISECOND:
  2413. this.current = new Date(this.current.valueOf() + this.step); break;
  2414. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2415. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2416. case TimeStep.SCALE.HOUR:
  2417. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2418. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2419. var h = this.current.getHours();
  2420. this.current.setHours(h - (h % this.step));
  2421. break;
  2422. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2423. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2424. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2425. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2426. default: break;
  2427. }
  2428. }
  2429. else {
  2430. switch (this.scale) {
  2431. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2432. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2433. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2434. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2435. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2436. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2437. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2438. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2439. default: break;
  2440. }
  2441. }
  2442. if (this.step != 1) {
  2443. // round down to the correct major value
  2444. switch (this.scale) {
  2445. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2446. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2447. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2448. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2449. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2450. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2451. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2452. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2453. default: break;
  2454. }
  2455. }
  2456. // safety mechanism: if current time is still unchanged, move to the end
  2457. if (this.current.valueOf() == prev) {
  2458. this.current = new Date(this._end.valueOf());
  2459. }
  2460. };
  2461. /**
  2462. * Get the current datetime
  2463. * @return {Date} current The current date
  2464. */
  2465. TimeStep.prototype.getCurrent = function() {
  2466. return this.current;
  2467. };
  2468. /**
  2469. * Set a custom scale. Autoscaling will be disabled.
  2470. * For example setScale(SCALE.MINUTES, 5) will result
  2471. * in minor steps of 5 minutes, and major steps of an hour.
  2472. *
  2473. * @param {TimeStep.SCALE} newScale
  2474. * A scale. Choose from SCALE.MILLISECOND,
  2475. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2476. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2477. * SCALE.YEAR.
  2478. * @param {Number} newStep A step size, by default 1. Choose for
  2479. * example 1, 2, 5, or 10.
  2480. */
  2481. TimeStep.prototype.setScale = function(newScale, newStep) {
  2482. this.scale = newScale;
  2483. if (newStep > 0) {
  2484. this.step = newStep;
  2485. }
  2486. this.autoScale = false;
  2487. };
  2488. /**
  2489. * Enable or disable autoscaling
  2490. * @param {boolean} enable If true, autoascaling is set true
  2491. */
  2492. TimeStep.prototype.setAutoScale = function (enable) {
  2493. this.autoScale = enable;
  2494. };
  2495. /**
  2496. * Automatically determine the scale that bests fits the provided minimum step
  2497. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2498. */
  2499. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2500. if (minimumStep == undefined) {
  2501. return;
  2502. }
  2503. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2504. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2505. var stepDay = (1000 * 60 * 60 * 24);
  2506. var stepHour = (1000 * 60 * 60);
  2507. var stepMinute = (1000 * 60);
  2508. var stepSecond = (1000);
  2509. var stepMillisecond= (1);
  2510. // find the smallest step that is larger than the provided minimumStep
  2511. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2512. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2513. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2514. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2515. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2516. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2517. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2518. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2519. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2520. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2521. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2522. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2523. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2524. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2525. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2526. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2527. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2528. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2529. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2530. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2531. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2532. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2533. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2534. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2535. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2536. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2537. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2538. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2539. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2540. };
  2541. /**
  2542. * Snap a date to a rounded value.
  2543. * The snap intervals are dependent on the current scale and step.
  2544. * @param {Date} date the date to be snapped.
  2545. * @return {Date} snappedDate
  2546. */
  2547. TimeStep.prototype.snap = function(date) {
  2548. var clone = new Date(date.valueOf());
  2549. if (this.scale == TimeStep.SCALE.YEAR) {
  2550. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2551. clone.setFullYear(Math.round(year / this.step) * this.step);
  2552. clone.setMonth(0);
  2553. clone.setDate(0);
  2554. clone.setHours(0);
  2555. clone.setMinutes(0);
  2556. clone.setSeconds(0);
  2557. clone.setMilliseconds(0);
  2558. }
  2559. else if (this.scale == TimeStep.SCALE.MONTH) {
  2560. if (clone.getDate() > 15) {
  2561. clone.setDate(1);
  2562. clone.setMonth(clone.getMonth() + 1);
  2563. // important: first set Date to 1, after that change the month.
  2564. }
  2565. else {
  2566. clone.setDate(1);
  2567. }
  2568. clone.setHours(0);
  2569. clone.setMinutes(0);
  2570. clone.setSeconds(0);
  2571. clone.setMilliseconds(0);
  2572. }
  2573. else if (this.scale == TimeStep.SCALE.DAY ||
  2574. this.scale == TimeStep.SCALE.WEEKDAY) {
  2575. //noinspection FallthroughInSwitchStatementJS
  2576. switch (this.step) {
  2577. case 5:
  2578. case 2:
  2579. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2580. default:
  2581. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2582. }
  2583. clone.setMinutes(0);
  2584. clone.setSeconds(0);
  2585. clone.setMilliseconds(0);
  2586. }
  2587. else if (this.scale == TimeStep.SCALE.HOUR) {
  2588. switch (this.step) {
  2589. case 4:
  2590. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2591. default:
  2592. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2593. }
  2594. clone.setSeconds(0);
  2595. clone.setMilliseconds(0);
  2596. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2597. //noinspection FallthroughInSwitchStatementJS
  2598. switch (this.step) {
  2599. case 15:
  2600. case 10:
  2601. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2602. clone.setSeconds(0);
  2603. break;
  2604. case 5:
  2605. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2606. default:
  2607. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2608. }
  2609. clone.setMilliseconds(0);
  2610. }
  2611. else if (this.scale == TimeStep.SCALE.SECOND) {
  2612. //noinspection FallthroughInSwitchStatementJS
  2613. switch (this.step) {
  2614. case 15:
  2615. case 10:
  2616. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2617. clone.setMilliseconds(0);
  2618. break;
  2619. case 5:
  2620. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2621. default:
  2622. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2623. }
  2624. }
  2625. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2626. var step = this.step > 5 ? this.step / 2 : 1;
  2627. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2628. }
  2629. return clone;
  2630. };
  2631. /**
  2632. * Check if the current value is a major value (for example when the step
  2633. * is DAY, a major value is each first day of the MONTH)
  2634. * @return {boolean} true if current date is major, else false.
  2635. */
  2636. TimeStep.prototype.isMajor = function() {
  2637. switch (this.scale) {
  2638. case TimeStep.SCALE.MILLISECOND:
  2639. return (this.current.getMilliseconds() == 0);
  2640. case TimeStep.SCALE.SECOND:
  2641. return (this.current.getSeconds() == 0);
  2642. case TimeStep.SCALE.MINUTE:
  2643. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2644. // Note: this is no bug. Major label is equal for both minute and hour scale
  2645. case TimeStep.SCALE.HOUR:
  2646. return (this.current.getHours() == 0);
  2647. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2648. case TimeStep.SCALE.DAY:
  2649. return (this.current.getDate() == 1);
  2650. case TimeStep.SCALE.MONTH:
  2651. return (this.current.getMonth() == 0);
  2652. case TimeStep.SCALE.YEAR:
  2653. return false;
  2654. default:
  2655. return false;
  2656. }
  2657. };
  2658. /**
  2659. * Returns formatted text for the minor axislabel, depending on the current
  2660. * date and the scale. For example when scale is MINUTE, the current time is
  2661. * formatted as "hh:mm".
  2662. * @param {Date} [date] custom date. if not provided, current date is taken
  2663. */
  2664. TimeStep.prototype.getLabelMinor = function(date) {
  2665. if (date == undefined) {
  2666. date = this.current;
  2667. }
  2668. switch (this.scale) {
  2669. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2670. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2671. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2672. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2673. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2674. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2675. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2676. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2677. default: return '';
  2678. }
  2679. };
  2680. /**
  2681. * Returns formatted text for the major axis label, depending on the current
  2682. * date and the scale. For example when scale is MINUTE, the major scale is
  2683. * hours, and the hour will be formatted as "hh".
  2684. * @param {Date} [date] custom date. if not provided, current date is taken
  2685. */
  2686. TimeStep.prototype.getLabelMajor = function(date) {
  2687. if (date == undefined) {
  2688. date = this.current;
  2689. }
  2690. //noinspection FallthroughInSwitchStatementJS
  2691. switch (this.scale) {
  2692. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2693. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2694. case TimeStep.SCALE.MINUTE:
  2695. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2696. case TimeStep.SCALE.WEEKDAY:
  2697. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2698. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2699. case TimeStep.SCALE.YEAR: return '';
  2700. default: return '';
  2701. }
  2702. };
  2703. /**
  2704. * @constructor Range
  2705. * A Range controls a numeric range with a start and end value.
  2706. * The Range adjusts the range based on mouse events or programmatic changes,
  2707. * and triggers events when the range is changing or has been changed.
  2708. * @param {RootPanel} root Root panel, used to subscribe to events
  2709. * @param {Panel} parent Parent panel, used to attach to the DOM
  2710. * @param {Object} [options] See description at Range.setOptions
  2711. */
  2712. function Range(root, parent, options) {
  2713. this.id = util.randomUUID();
  2714. this.start = null; // Number
  2715. this.end = null; // Number
  2716. this.root = root;
  2717. this.parent = parent;
  2718. this.options = options || {};
  2719. // drag listeners for dragging
  2720. this.root.on('dragstart', this._onDragStart.bind(this));
  2721. this.root.on('drag', this._onDrag.bind(this));
  2722. this.root.on('dragend', this._onDragEnd.bind(this));
  2723. // ignore dragging when holding
  2724. this.root.on('hold', this._onHold.bind(this));
  2725. // mouse wheel for zooming
  2726. this.root.on('mousewheel', this._onMouseWheel.bind(this));
  2727. this.root.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF
  2728. // pinch to zoom
  2729. this.root.on('touch', this._onTouch.bind(this));
  2730. this.root.on('pinch', this._onPinch.bind(this));
  2731. this.setOptions(options);
  2732. }
  2733. // turn Range into an event emitter
  2734. Emitter(Range.prototype);
  2735. /**
  2736. * Set options for the range controller
  2737. * @param {Object} options Available options:
  2738. * {Number} min Minimum value for start
  2739. * {Number} max Maximum value for end
  2740. * {Number} zoomMin Set a minimum value for
  2741. * (end - start).
  2742. * {Number} zoomMax Set a maximum value for
  2743. * (end - start).
  2744. */
  2745. Range.prototype.setOptions = function (options) {
  2746. util.extend(this.options, options);
  2747. // re-apply range with new limitations
  2748. if (this.start !== null && this.end !== null) {
  2749. this.setRange(this.start, this.end);
  2750. }
  2751. };
  2752. /**
  2753. * Test whether direction has a valid value
  2754. * @param {String} direction 'horizontal' or 'vertical'
  2755. */
  2756. function validateDirection (direction) {
  2757. if (direction != 'horizontal' && direction != 'vertical') {
  2758. throw new TypeError('Unknown direction "' + direction + '". ' +
  2759. 'Choose "horizontal" or "vertical".');
  2760. }
  2761. }
  2762. /**
  2763. * Set a new start and end range
  2764. * @param {Number} [start]
  2765. * @param {Number} [end]
  2766. */
  2767. Range.prototype.setRange = function(start, end) {
  2768. var changed = this._applyRange(start, end);
  2769. if (changed) {
  2770. var params = {
  2771. start: new Date(this.start),
  2772. end: new Date(this.end)
  2773. };
  2774. this.emit('rangechange', params);
  2775. this.emit('rangechanged', params);
  2776. }
  2777. };
  2778. /**
  2779. * Set a new start and end range. This method is the same as setRange, but
  2780. * does not trigger a range change and range changed event, and it returns
  2781. * true when the range is changed
  2782. * @param {Number} [start]
  2783. * @param {Number} [end]
  2784. * @return {Boolean} changed
  2785. * @private
  2786. */
  2787. Range.prototype._applyRange = function(start, end) {
  2788. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2789. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2790. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2791. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2792. diff;
  2793. // check for valid number
  2794. if (isNaN(newStart) || newStart === null) {
  2795. throw new Error('Invalid start "' + start + '"');
  2796. }
  2797. if (isNaN(newEnd) || newEnd === null) {
  2798. throw new Error('Invalid end "' + end + '"');
  2799. }
  2800. // prevent start < end
  2801. if (newEnd < newStart) {
  2802. newEnd = newStart;
  2803. }
  2804. // prevent start < min
  2805. if (min !== null) {
  2806. if (newStart < min) {
  2807. diff = (min - newStart);
  2808. newStart += diff;
  2809. newEnd += diff;
  2810. // prevent end > max
  2811. if (max != null) {
  2812. if (newEnd > max) {
  2813. newEnd = max;
  2814. }
  2815. }
  2816. }
  2817. }
  2818. // prevent end > max
  2819. if (max !== null) {
  2820. if (newEnd > max) {
  2821. diff = (newEnd - max);
  2822. newStart -= diff;
  2823. newEnd -= diff;
  2824. // prevent start < min
  2825. if (min != null) {
  2826. if (newStart < min) {
  2827. newStart = min;
  2828. }
  2829. }
  2830. }
  2831. }
  2832. // prevent (end-start) < zoomMin
  2833. if (this.options.zoomMin !== null) {
  2834. var zoomMin = parseFloat(this.options.zoomMin);
  2835. if (zoomMin < 0) {
  2836. zoomMin = 0;
  2837. }
  2838. if ((newEnd - newStart) < zoomMin) {
  2839. if ((this.end - this.start) === zoomMin) {
  2840. // ignore this action, we are already zoomed to the minimum
  2841. newStart = this.start;
  2842. newEnd = this.end;
  2843. }
  2844. else {
  2845. // zoom to the minimum
  2846. diff = (zoomMin - (newEnd - newStart));
  2847. newStart -= diff / 2;
  2848. newEnd += diff / 2;
  2849. }
  2850. }
  2851. }
  2852. // prevent (end-start) > zoomMax
  2853. if (this.options.zoomMax !== null) {
  2854. var zoomMax = parseFloat(this.options.zoomMax);
  2855. if (zoomMax < 0) {
  2856. zoomMax = 0;
  2857. }
  2858. if ((newEnd - newStart) > zoomMax) {
  2859. if ((this.end - this.start) === zoomMax) {
  2860. // ignore this action, we are already zoomed to the maximum
  2861. newStart = this.start;
  2862. newEnd = this.end;
  2863. }
  2864. else {
  2865. // zoom to the maximum
  2866. diff = ((newEnd - newStart) - zoomMax);
  2867. newStart += diff / 2;
  2868. newEnd -= diff / 2;
  2869. }
  2870. }
  2871. }
  2872. var changed = (this.start != newStart || this.end != newEnd);
  2873. this.start = newStart;
  2874. this.end = newEnd;
  2875. return changed;
  2876. };
  2877. /**
  2878. * Retrieve the current range.
  2879. * @return {Object} An object with start and end properties
  2880. */
  2881. Range.prototype.getRange = function() {
  2882. return {
  2883. start: this.start,
  2884. end: this.end
  2885. };
  2886. };
  2887. /**
  2888. * Calculate the conversion offset and scale for current range, based on
  2889. * the provided width
  2890. * @param {Number} width
  2891. * @returns {{offset: number, scale: number}} conversion
  2892. */
  2893. Range.prototype.conversion = function (width) {
  2894. return Range.conversion(this.start, this.end, width);
  2895. };
  2896. /**
  2897. * Static method to calculate the conversion offset and scale for a range,
  2898. * based on the provided start, end, and width
  2899. * @param {Number} start
  2900. * @param {Number} end
  2901. * @param {Number} width
  2902. * @returns {{offset: number, scale: number}} conversion
  2903. */
  2904. Range.conversion = function (start, end, width) {
  2905. if (width != 0 && (end - start != 0)) {
  2906. return {
  2907. offset: start,
  2908. scale: width / (end - start)
  2909. }
  2910. }
  2911. else {
  2912. return {
  2913. offset: 0,
  2914. scale: 1
  2915. };
  2916. }
  2917. };
  2918. // global (private) object to store drag params
  2919. var touchParams = {};
  2920. /**
  2921. * Start dragging horizontally or vertically
  2922. * @param {Event} event
  2923. * @private
  2924. */
  2925. Range.prototype._onDragStart = function(event) {
  2926. // refuse to drag when we where pinching to prevent the timeline make a jump
  2927. // when releasing the fingers in opposite order from the touch screen
  2928. if (touchParams.ignore) return;
  2929. // TODO: reckon with option movable
  2930. touchParams.start = this.start;
  2931. touchParams.end = this.end;
  2932. var frame = this.parent.frame;
  2933. if (frame) {
  2934. frame.style.cursor = 'move';
  2935. }
  2936. };
  2937. /**
  2938. * Perform dragging operating.
  2939. * @param {Event} event
  2940. * @private
  2941. */
  2942. Range.prototype._onDrag = function (event) {
  2943. var direction = this.options.direction;
  2944. validateDirection(direction);
  2945. // TODO: reckon with option movable
  2946. // refuse to drag when we where pinching to prevent the timeline make a jump
  2947. // when releasing the fingers in opposite order from the touch screen
  2948. if (touchParams.ignore) return;
  2949. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  2950. interval = (touchParams.end - touchParams.start),
  2951. width = (direction == 'horizontal') ? this.parent.width : this.parent.height,
  2952. diffRange = -delta / width * interval;
  2953. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  2954. this.emit('rangechange', {
  2955. start: new Date(this.start),
  2956. end: new Date(this.end)
  2957. });
  2958. };
  2959. /**
  2960. * Stop dragging operating.
  2961. * @param {event} event
  2962. * @private
  2963. */
  2964. Range.prototype._onDragEnd = function (event) {
  2965. // refuse to drag when we where pinching to prevent the timeline make a jump
  2966. // when releasing the fingers in opposite order from the touch screen
  2967. if (touchParams.ignore) return;
  2968. // TODO: reckon with option movable
  2969. if (this.parent.frame) {
  2970. this.parent.frame.style.cursor = 'auto';
  2971. }
  2972. // fire a rangechanged event
  2973. this.emit('rangechanged', {
  2974. start: new Date(this.start),
  2975. end: new Date(this.end)
  2976. });
  2977. };
  2978. /**
  2979. * Event handler for mouse wheel event, used to zoom
  2980. * Code from http://adomas.org/javascript-mouse-wheel/
  2981. * @param {Event} event
  2982. * @private
  2983. */
  2984. Range.prototype._onMouseWheel = function(event) {
  2985. // TODO: reckon with option zoomable
  2986. // retrieve delta
  2987. var delta = 0;
  2988. if (event.wheelDelta) { /* IE/Opera. */
  2989. delta = event.wheelDelta / 120;
  2990. } else if (event.detail) { /* Mozilla case. */
  2991. // In Mozilla, sign of delta is different than in IE.
  2992. // Also, delta is multiple of 3.
  2993. delta = -event.detail / 3;
  2994. }
  2995. // If delta is nonzero, handle it.
  2996. // Basically, delta is now positive if wheel was scrolled up,
  2997. // and negative, if wheel was scrolled down.
  2998. if (delta) {
  2999. // perform the zoom action. Delta is normally 1 or -1
  3000. // adjust a negative delta such that zooming in with delta 0.1
  3001. // equals zooming out with a delta -0.1
  3002. var scale;
  3003. if (delta < 0) {
  3004. scale = 1 - (delta / 5);
  3005. }
  3006. else {
  3007. scale = 1 / (1 + (delta / 5)) ;
  3008. }
  3009. // calculate center, the date to zoom around
  3010. var gesture = util.fakeGesture(this, event),
  3011. pointer = getPointer(gesture.center, this.parent.frame),
  3012. pointerDate = this._pointerToDate(pointer);
  3013. this.zoom(scale, pointerDate);
  3014. }
  3015. // Prevent default actions caused by mouse wheel
  3016. // (else the page and timeline both zoom and scroll)
  3017. event.preventDefault();
  3018. };
  3019. /**
  3020. * Start of a touch gesture
  3021. * @private
  3022. */
  3023. Range.prototype._onTouch = function (event) {
  3024. touchParams.start = this.start;
  3025. touchParams.end = this.end;
  3026. touchParams.ignore = false;
  3027. touchParams.center = null;
  3028. // don't move the range when dragging a selected event
  3029. // TODO: it's not so neat to have to know about the state of the ItemSet
  3030. var item = ItemSet.itemFromTarget(event);
  3031. if (item && item.selected && this.options.editable) {
  3032. touchParams.ignore = true;
  3033. }
  3034. };
  3035. /**
  3036. * On start of a hold gesture
  3037. * @private
  3038. */
  3039. Range.prototype._onHold = function () {
  3040. touchParams.ignore = true;
  3041. };
  3042. /**
  3043. * Handle pinch event
  3044. * @param {Event} event
  3045. * @private
  3046. */
  3047. Range.prototype._onPinch = function (event) {
  3048. var direction = this.options.direction;
  3049. touchParams.ignore = true;
  3050. // TODO: reckon with option zoomable
  3051. if (event.gesture.touches.length > 1) {
  3052. if (!touchParams.center) {
  3053. touchParams.center = getPointer(event.gesture.center, this.parent.frame);
  3054. }
  3055. var scale = 1 / event.gesture.scale,
  3056. initDate = this._pointerToDate(touchParams.center),
  3057. center = getPointer(event.gesture.center, this.parent.frame),
  3058. date = this._pointerToDate(this.parent, center),
  3059. delta = date - initDate; // TODO: utilize delta
  3060. // calculate new start and end
  3061. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3062. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3063. // apply new range
  3064. this.setRange(newStart, newEnd);
  3065. }
  3066. };
  3067. /**
  3068. * Helper function to calculate the center date for zooming
  3069. * @param {{x: Number, y: Number}} pointer
  3070. * @return {number} date
  3071. * @private
  3072. */
  3073. Range.prototype._pointerToDate = function (pointer) {
  3074. var conversion;
  3075. var direction = this.options.direction;
  3076. validateDirection(direction);
  3077. if (direction == 'horizontal') {
  3078. var width = this.parent.width;
  3079. conversion = this.conversion(width);
  3080. return pointer.x / conversion.scale + conversion.offset;
  3081. }
  3082. else {
  3083. var height = this.parent.height;
  3084. conversion = this.conversion(height);
  3085. return pointer.y / conversion.scale + conversion.offset;
  3086. }
  3087. };
  3088. /**
  3089. * Get the pointer location relative to the location of the dom element
  3090. * @param {{pageX: Number, pageY: Number}} touch
  3091. * @param {Element} element HTML DOM element
  3092. * @return {{x: Number, y: Number}} pointer
  3093. * @private
  3094. */
  3095. function getPointer (touch, element) {
  3096. return {
  3097. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3098. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3099. };
  3100. }
  3101. /**
  3102. * Zoom the range the given scale in or out. Start and end date will
  3103. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3104. * date around which to zoom.
  3105. * For example, try scale = 0.9 or 1.1
  3106. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3107. * values below 1 will zoom in.
  3108. * @param {Number} [center] Value representing a date around which will
  3109. * be zoomed.
  3110. */
  3111. Range.prototype.zoom = function(scale, center) {
  3112. // if centerDate is not provided, take it half between start Date and end Date
  3113. if (center == null) {
  3114. center = (this.start + this.end) / 2;
  3115. }
  3116. // calculate new start and end
  3117. var newStart = center + (this.start - center) * scale;
  3118. var newEnd = center + (this.end - center) * scale;
  3119. this.setRange(newStart, newEnd);
  3120. };
  3121. /**
  3122. * Move the range with a given delta to the left or right. Start and end
  3123. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3124. * @param {Number} delta Moving amount. Positive value will move right,
  3125. * negative value will move left
  3126. */
  3127. Range.prototype.move = function(delta) {
  3128. // zoom start Date and end Date relative to the centerDate
  3129. var diff = (this.end - this.start);
  3130. // apply new values
  3131. var newStart = this.start + diff * delta;
  3132. var newEnd = this.end + diff * delta;
  3133. // TODO: reckon with min and max range
  3134. this.start = newStart;
  3135. this.end = newEnd;
  3136. };
  3137. /**
  3138. * Move the range to a new center point
  3139. * @param {Number} moveTo New center point of the range
  3140. */
  3141. Range.prototype.moveTo = function(moveTo) {
  3142. var center = (this.start + this.end) / 2;
  3143. var diff = center - moveTo;
  3144. // calculate new start and end
  3145. var newStart = this.start - diff;
  3146. var newEnd = this.end - diff;
  3147. this.setRange(newStart, newEnd);
  3148. };
  3149. /**
  3150. * Prototype for visual components
  3151. */
  3152. function Component () {
  3153. this.id = null;
  3154. this.parent = null;
  3155. this.childs = null;
  3156. this.options = null;
  3157. this.top = 0;
  3158. this.left = 0;
  3159. this.width = 0;
  3160. this.height = 0;
  3161. }
  3162. // Turn the Component into an event emitter
  3163. Emitter(Component.prototype);
  3164. /**
  3165. * Set parameters for the frame. Parameters will be merged in current parameter
  3166. * set.
  3167. * @param {Object} options Available parameters:
  3168. * {String | function} [className]
  3169. * {String | Number | function} [left]
  3170. * {String | Number | function} [top]
  3171. * {String | Number | function} [width]
  3172. * {String | Number | function} [height]
  3173. */
  3174. Component.prototype.setOptions = function setOptions(options) {
  3175. if (options) {
  3176. util.extend(this.options, options);
  3177. this.repaint();
  3178. }
  3179. };
  3180. /**
  3181. * Get an option value by name
  3182. * The function will first check this.options object, and else will check
  3183. * this.defaultOptions.
  3184. * @param {String} name
  3185. * @return {*} value
  3186. */
  3187. Component.prototype.getOption = function getOption(name) {
  3188. var value;
  3189. if (this.options) {
  3190. value = this.options[name];
  3191. }
  3192. if (value === undefined && this.defaultOptions) {
  3193. value = this.defaultOptions[name];
  3194. }
  3195. return value;
  3196. };
  3197. /**
  3198. * Get the frame element of the component, the outer HTML DOM element.
  3199. * @returns {HTMLElement | null} frame
  3200. */
  3201. Component.prototype.getFrame = function getFrame() {
  3202. // should be implemented by the component
  3203. return null;
  3204. };
  3205. /**
  3206. * Repaint the component
  3207. * @return {boolean} Returns true if the component is resized
  3208. */
  3209. Component.prototype.repaint = function repaint() {
  3210. // should be implemented by the component
  3211. return false;
  3212. };
  3213. /**
  3214. * Test whether the component is resized since the last time _isResized() was
  3215. * called.
  3216. * @return {Boolean} Returns true if the component is resized
  3217. * @protected
  3218. */
  3219. Component.prototype._isResized = function _isResized() {
  3220. var resized = (this._previousWidth !== this.width || this._previousHeight !== this.height);
  3221. this._previousWidth = this.width;
  3222. this._previousHeight = this.height;
  3223. return resized;
  3224. };
  3225. /**
  3226. * A panel can contain components
  3227. * @param {Object} [options] Available parameters:
  3228. * {String | Number | function} [left]
  3229. * {String | Number | function} [top]
  3230. * {String | Number | function} [width]
  3231. * {String | Number | function} [height]
  3232. * {String | function} [className]
  3233. * @constructor Panel
  3234. * @extends Component
  3235. */
  3236. function Panel(options) {
  3237. this.id = util.randomUUID();
  3238. this.parent = null;
  3239. this.childs = [];
  3240. this.options = options || {};
  3241. // create frame
  3242. this.frame = (typeof document !== 'undefined') ? document.createElement('div') : null;
  3243. }
  3244. Panel.prototype = new Component();
  3245. /**
  3246. * Set options. Will extend the current options.
  3247. * @param {Object} [options] Available parameters:
  3248. * {String | function} [className]
  3249. * {String | Number | function} [left]
  3250. * {String | Number | function} [top]
  3251. * {String | Number | function} [width]
  3252. * {String | Number | function} [height]
  3253. */
  3254. Panel.prototype.setOptions = Component.prototype.setOptions;
  3255. /**
  3256. * Get the outer frame of the panel
  3257. * @returns {HTMLElement} frame
  3258. */
  3259. Panel.prototype.getFrame = function () {
  3260. return this.frame;
  3261. };
  3262. /**
  3263. * Append a child to the panel
  3264. * @param {Component} child
  3265. */
  3266. Panel.prototype.appendChild = function (child) {
  3267. this.childs.push(child);
  3268. child.parent = this;
  3269. // attach to the DOM
  3270. var frame = child.getFrame();
  3271. if (frame) {
  3272. if (frame.parentNode) {
  3273. frame.parentNode.removeChild(frame);
  3274. }
  3275. this.frame.appendChild(frame);
  3276. }
  3277. };
  3278. /**
  3279. * Insert a child to the panel
  3280. * @param {Component} child
  3281. * @param {Component} beforeChild
  3282. */
  3283. Panel.prototype.insertBefore = function (child, beforeChild) {
  3284. var index = this.childs.indexOf(beforeChild);
  3285. if (index != -1) {
  3286. this.childs.splice(index, 0, child);
  3287. child.parent = this;
  3288. // attach to the DOM
  3289. var frame = child.getFrame();
  3290. if (frame) {
  3291. if (frame.parentNode) {
  3292. frame.parentNode.removeChild(frame);
  3293. }
  3294. var beforeFrame = beforeChild.getFrame();
  3295. if (beforeFrame) {
  3296. this.frame.insertBefore(frame, beforeFrame);
  3297. }
  3298. else {
  3299. this.frame.appendChild(frame);
  3300. }
  3301. }
  3302. }
  3303. };
  3304. /**
  3305. * Remove a child from the panel
  3306. * @param {Component} child
  3307. */
  3308. Panel.prototype.removeChild = function (child) {
  3309. var index = this.childs.indexOf(child);
  3310. if (index != -1) {
  3311. this.childs.splice(index, 1);
  3312. child.parent = null;
  3313. // remove from the DOM
  3314. var frame = child.getFrame();
  3315. if (frame && frame.parentNode) {
  3316. this.frame.removeChild(frame);
  3317. }
  3318. }
  3319. };
  3320. /**
  3321. * Test whether the panel contains given child
  3322. * @param {Component} child
  3323. */
  3324. Panel.prototype.hasChild = function (child) {
  3325. var index = this.childs.indexOf(child);
  3326. return (index != -1);
  3327. };
  3328. /**
  3329. * Repaint the component
  3330. * @return {boolean} Returns true if the component was resized since previous repaint
  3331. */
  3332. Panel.prototype.repaint = function () {
  3333. var asString = util.option.asString,
  3334. options = this.options,
  3335. frame = this.getFrame();
  3336. // update className
  3337. frame.className = 'vpanel' + (options.className ? (' ' + asString(options.className)) : '');
  3338. // repaint the child components
  3339. var childsResized = this._repaintChilds();
  3340. // update frame size
  3341. this._updateSize();
  3342. return this._isResized() || childsResized;
  3343. };
  3344. /**
  3345. * Repaint all childs of the panel
  3346. * @return {boolean} Returns true if the component is resized
  3347. * @private
  3348. */
  3349. Panel.prototype._repaintChilds = function () {
  3350. var resized = false;
  3351. for (var i = 0, ii = this.childs.length; i < ii; i++) {
  3352. resized = this.childs[i].repaint() || resized;
  3353. }
  3354. return resized;
  3355. };
  3356. /**
  3357. * Apply the size from options to the panel, and recalculate it's actual size.
  3358. * @private
  3359. */
  3360. Panel.prototype._updateSize = function () {
  3361. // apply size
  3362. this.frame.style.top = util.option.asSize(this.options.top);
  3363. this.frame.style.bottom = util.option.asSize(this.options.bottom);
  3364. this.frame.style.left = util.option.asSize(this.options.left);
  3365. this.frame.style.right = util.option.asSize(this.options.right);
  3366. this.frame.style.width = util.option.asSize(this.options.width, '100%');
  3367. this.frame.style.height = util.option.asSize(this.options.height, '');
  3368. // get actual size
  3369. this.top = this.frame.offsetTop;
  3370. this.left = this.frame.offsetLeft;
  3371. this.width = this.frame.offsetWidth;
  3372. this.height = this.frame.offsetHeight;
  3373. };
  3374. /**
  3375. * A root panel can hold components. The root panel must be initialized with
  3376. * a DOM element as container.
  3377. * @param {HTMLElement} container
  3378. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3379. * @constructor RootPanel
  3380. * @extends Panel
  3381. */
  3382. function RootPanel(container, options) {
  3383. this.id = util.randomUUID();
  3384. this.container = container;
  3385. this.options = options || {};
  3386. this.defaultOptions = {
  3387. autoResize: true
  3388. };
  3389. // create the HTML DOM
  3390. this._create();
  3391. // attach the root panel to the provided container
  3392. if (!this.container) throw new Error('Cannot repaint root panel: no container attached');
  3393. this.container.appendChild(this.getFrame());
  3394. this._initWatch();
  3395. }
  3396. RootPanel.prototype = new Panel();
  3397. /**
  3398. * Create the HTML DOM for the root panel
  3399. */
  3400. RootPanel.prototype._create = function _create() {
  3401. // create frame
  3402. this.frame = document.createElement('div');
  3403. // create event listeners for all interesting events, these events will be
  3404. // emitted via emitter
  3405. this.hammer = Hammer(this.frame, {
  3406. prevent_default: true
  3407. });
  3408. this.listeners = {};
  3409. var me = this;
  3410. var events = [
  3411. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3412. 'dragstart', 'drag', 'dragend',
  3413. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3414. ];
  3415. events.forEach(function (event) {
  3416. var listener = function () {
  3417. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3418. me.emit.apply(me, args);
  3419. };
  3420. me.hammer.on(event, listener);
  3421. me.listeners[event] = listener;
  3422. });
  3423. };
  3424. /**
  3425. * Set options. Will extend the current options.
  3426. * @param {Object} [options] Available parameters:
  3427. * {String | function} [className]
  3428. * {String | Number | function} [left]
  3429. * {String | Number | function} [top]
  3430. * {String | Number | function} [width]
  3431. * {String | Number | function} [height]
  3432. * {Boolean | function} [autoResize]
  3433. */
  3434. RootPanel.prototype.setOptions = function setOptions(options) {
  3435. if (options) {
  3436. util.extend(this.options, options);
  3437. this.repaint();
  3438. this._initWatch();
  3439. }
  3440. };
  3441. /**
  3442. * Get the frame of the root panel
  3443. */
  3444. RootPanel.prototype.getFrame = function getFrame() {
  3445. return this.frame;
  3446. };
  3447. /**
  3448. * Repaint the root panel
  3449. */
  3450. RootPanel.prototype.repaint = function repaint() {
  3451. // update class name
  3452. var options = this.options;
  3453. var editable = options.editable.updateTime || options.editable.updateGroup;
  3454. var className = 'vis timeline rootpanel ' + options.orientation + (editable ? ' editable' : '');
  3455. if (options.className) className += ' ' + util.option.asString(className);
  3456. this.frame.className = className;
  3457. // repaint the child components
  3458. var childsResized = this._repaintChilds();
  3459. // update frame size
  3460. this.frame.style.maxHeight = util.option.asSize(this.options.maxHeight, '');
  3461. this._updateSize();
  3462. // if the root panel or any of its childs is resized, repaint again,
  3463. // as other components may need to be resized accordingly
  3464. var resized = this._isResized() || childsResized;
  3465. if (resized) {
  3466. setTimeout(this.repaint.bind(this), 0);
  3467. }
  3468. };
  3469. /**
  3470. * Initialize watching when option autoResize is true
  3471. * @private
  3472. */
  3473. RootPanel.prototype._initWatch = function _initWatch() {
  3474. var autoResize = this.getOption('autoResize');
  3475. if (autoResize) {
  3476. this._watch();
  3477. }
  3478. else {
  3479. this._unwatch();
  3480. }
  3481. };
  3482. /**
  3483. * Watch for changes in the size of the frame. On resize, the Panel will
  3484. * automatically redraw itself.
  3485. * @private
  3486. */
  3487. RootPanel.prototype._watch = function _watch() {
  3488. var me = this;
  3489. this._unwatch();
  3490. var checkSize = function checkSize() {
  3491. var autoResize = me.getOption('autoResize');
  3492. if (!autoResize) {
  3493. // stop watching when the option autoResize is changed to false
  3494. me._unwatch();
  3495. return;
  3496. }
  3497. if (me.frame) {
  3498. // check whether the frame is resized
  3499. if ((me.frame.clientWidth != me.lastWidth) ||
  3500. (me.frame.clientHeight != me.lastHeight)) {
  3501. me.lastWidth = me.frame.clientWidth;
  3502. me.lastHeight = me.frame.clientHeight;
  3503. me.repaint();
  3504. // TODO: emit a resize event instead?
  3505. }
  3506. }
  3507. };
  3508. // TODO: automatically cleanup the event listener when the frame is deleted
  3509. util.addEventListener(window, 'resize', checkSize);
  3510. this.watchTimer = setInterval(checkSize, 1000);
  3511. };
  3512. /**
  3513. * Stop watching for a resize of the frame.
  3514. * @private
  3515. */
  3516. RootPanel.prototype._unwatch = function _unwatch() {
  3517. if (this.watchTimer) {
  3518. clearInterval(this.watchTimer);
  3519. this.watchTimer = undefined;
  3520. }
  3521. // TODO: remove event listener on window.resize
  3522. };
  3523. /**
  3524. * A horizontal time axis
  3525. * @param {Object} [options] See TimeAxis.setOptions for the available
  3526. * options.
  3527. * @constructor TimeAxis
  3528. * @extends Component
  3529. */
  3530. function TimeAxis (options) {
  3531. this.id = util.randomUUID();
  3532. this.dom = {
  3533. majorLines: [],
  3534. majorTexts: [],
  3535. minorLines: [],
  3536. minorTexts: [],
  3537. redundant: {
  3538. majorLines: [],
  3539. majorTexts: [],
  3540. minorLines: [],
  3541. minorTexts: []
  3542. }
  3543. };
  3544. this.props = {
  3545. range: {
  3546. start: 0,
  3547. end: 0,
  3548. minimumStep: 0
  3549. },
  3550. lineTop: 0
  3551. };
  3552. this.options = options || {};
  3553. this.defaultOptions = {
  3554. orientation: 'bottom', // supported: 'top', 'bottom'
  3555. // TODO: implement timeaxis orientations 'left' and 'right'
  3556. showMinorLabels: true,
  3557. showMajorLabels: true
  3558. };
  3559. this.range = null;
  3560. // create the HTML DOM
  3561. this._create();
  3562. }
  3563. TimeAxis.prototype = new Component();
  3564. // TODO: comment options
  3565. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3566. /**
  3567. * Create the HTML DOM for the TimeAxis
  3568. */
  3569. TimeAxis.prototype._create = function _create() {
  3570. this.frame = document.createElement('div');
  3571. };
  3572. /**
  3573. * Set a range (start and end)
  3574. * @param {Range | Object} range A Range or an object containing start and end.
  3575. */
  3576. TimeAxis.prototype.setRange = function (range) {
  3577. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3578. throw new TypeError('Range must be an instance of Range, ' +
  3579. 'or an object containing start and end.');
  3580. }
  3581. this.range = range;
  3582. };
  3583. /**
  3584. * Get the outer frame of the time axis
  3585. * @return {HTMLElement} frame
  3586. */
  3587. TimeAxis.prototype.getFrame = function getFrame() {
  3588. return this.frame;
  3589. };
  3590. /**
  3591. * Repaint the component
  3592. * @return {boolean} Returns true if the component is resized
  3593. */
  3594. TimeAxis.prototype.repaint = function () {
  3595. var asSize = util.option.asSize,
  3596. options = this.options,
  3597. props = this.props,
  3598. frame = this.frame;
  3599. // update classname
  3600. frame.className = 'timeaxis'; // TODO: add className from options if defined
  3601. var parent = frame.parentNode;
  3602. if (parent) {
  3603. // calculate character width and height
  3604. this._calculateCharSize();
  3605. // TODO: recalculate sizes only needed when parent is resized or options is changed
  3606. var orientation = this.getOption('orientation'),
  3607. showMinorLabels = this.getOption('showMinorLabels'),
  3608. showMajorLabels = this.getOption('showMajorLabels');
  3609. // determine the width and height of the elemens for the axis
  3610. var parentHeight = this.parent.height;
  3611. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  3612. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  3613. this.height = props.minorLabelHeight + props.majorLabelHeight;
  3614. this.width = frame.offsetWidth; // TODO: only update the width when the frame is resized?
  3615. props.minorLineHeight = parentHeight + props.minorLabelHeight;
  3616. props.minorLineWidth = 1; // TODO: really calculate width
  3617. props.majorLineHeight = parentHeight + this.height;
  3618. props.majorLineWidth = 1; // TODO: really calculate width
  3619. // take frame offline while updating (is almost twice as fast)
  3620. var beforeChild = frame.nextSibling;
  3621. parent.removeChild(frame);
  3622. // TODO: top/bottom positioning should be determined by options set in the Timeline, not here
  3623. if (orientation == 'top') {
  3624. frame.style.top = '0';
  3625. frame.style.left = '0';
  3626. frame.style.bottom = '';
  3627. frame.style.width = asSize(options.width, '100%');
  3628. frame.style.height = this.height + 'px';
  3629. }
  3630. else { // bottom
  3631. frame.style.top = '';
  3632. frame.style.bottom = '0';
  3633. frame.style.left = '0';
  3634. frame.style.width = asSize(options.width, '100%');
  3635. frame.style.height = this.height + 'px';
  3636. }
  3637. this._repaintLabels();
  3638. this._repaintLine();
  3639. // put frame online again
  3640. if (beforeChild) {
  3641. parent.insertBefore(frame, beforeChild);
  3642. }
  3643. else {
  3644. parent.appendChild(frame)
  3645. }
  3646. }
  3647. return this._isResized();
  3648. };
  3649. /**
  3650. * Repaint major and minor text labels and vertical grid lines
  3651. * @private
  3652. */
  3653. TimeAxis.prototype._repaintLabels = function () {
  3654. var orientation = this.getOption('orientation');
  3655. // calculate range and step (step such that we have space for 7 characters per label)
  3656. var start = util.convert(this.range.start, 'Number'),
  3657. end = util.convert(this.range.end, 'Number'),
  3658. minimumStep = this.options.toTime((this.props.minorCharWidth || 10) * 7).valueOf()
  3659. -this.options.toTime(0).valueOf();
  3660. var step = new TimeStep(new Date(start), new Date(end), minimumStep);
  3661. this.step = step;
  3662. // Move all DOM elements to a "redundant" list, where they
  3663. // can be picked for re-use, and clear the lists with lines and texts.
  3664. // At the end of the function _repaintLabels, left over elements will be cleaned up
  3665. var dom = this.dom;
  3666. dom.redundant.majorLines = dom.majorLines;
  3667. dom.redundant.majorTexts = dom.majorTexts;
  3668. dom.redundant.minorLines = dom.minorLines;
  3669. dom.redundant.minorTexts = dom.minorTexts;
  3670. dom.majorLines = [];
  3671. dom.majorTexts = [];
  3672. dom.minorLines = [];
  3673. dom.minorTexts = [];
  3674. step.first();
  3675. var xFirstMajorLabel = undefined;
  3676. var max = 0;
  3677. while (step.hasNext() && max < 1000) {
  3678. max++;
  3679. var cur = step.getCurrent(),
  3680. x = this.options.toScreen(cur),
  3681. isMajor = step.isMajor();
  3682. // TODO: lines must have a width, such that we can create css backgrounds
  3683. if (this.getOption('showMinorLabels')) {
  3684. this._repaintMinorText(x, step.getLabelMinor(), orientation);
  3685. }
  3686. if (isMajor && this.getOption('showMajorLabels')) {
  3687. if (x > 0) {
  3688. if (xFirstMajorLabel == undefined) {
  3689. xFirstMajorLabel = x;
  3690. }
  3691. this._repaintMajorText(x, step.getLabelMajor(), orientation);
  3692. }
  3693. this._repaintMajorLine(x, orientation);
  3694. }
  3695. else {
  3696. this._repaintMinorLine(x, orientation);
  3697. }
  3698. step.next();
  3699. }
  3700. // create a major label on the left when needed
  3701. if (this.getOption('showMajorLabels')) {
  3702. var leftTime = this.options.toTime(0),
  3703. leftText = step.getLabelMajor(leftTime),
  3704. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  3705. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3706. this._repaintMajorText(0, leftText, orientation);
  3707. }
  3708. }
  3709. // Cleanup leftover DOM elements from the redundant list
  3710. util.forEach(this.dom.redundant, function (arr) {
  3711. while (arr.length) {
  3712. var elem = arr.pop();
  3713. if (elem && elem.parentNode) {
  3714. elem.parentNode.removeChild(elem);
  3715. }
  3716. }
  3717. });
  3718. };
  3719. /**
  3720. * Create a minor label for the axis at position x
  3721. * @param {Number} x
  3722. * @param {String} text
  3723. * @param {String} orientation "top" or "bottom" (default)
  3724. * @private
  3725. */
  3726. TimeAxis.prototype._repaintMinorText = function (x, text, orientation) {
  3727. // reuse redundant label
  3728. var label = this.dom.redundant.minorTexts.shift();
  3729. if (!label) {
  3730. // create new label
  3731. var content = document.createTextNode('');
  3732. label = document.createElement('div');
  3733. label.appendChild(content);
  3734. label.className = 'text minor';
  3735. this.frame.appendChild(label);
  3736. }
  3737. this.dom.minorTexts.push(label);
  3738. label.childNodes[0].nodeValue = text;
  3739. if (orientation == 'top') {
  3740. label.style.top = this.props.majorLabelHeight + 'px';
  3741. label.style.bottom = '';
  3742. }
  3743. else {
  3744. label.style.top = '';
  3745. label.style.bottom = this.props.majorLabelHeight + 'px';
  3746. }
  3747. label.style.left = x + 'px';
  3748. //label.title = title; // TODO: this is a heavy operation
  3749. };
  3750. /**
  3751. * Create a Major label for the axis at position x
  3752. * @param {Number} x
  3753. * @param {String} text
  3754. * @param {String} orientation "top" or "bottom" (default)
  3755. * @private
  3756. */
  3757. TimeAxis.prototype._repaintMajorText = function (x, text, orientation) {
  3758. // reuse redundant label
  3759. var label = this.dom.redundant.majorTexts.shift();
  3760. if (!label) {
  3761. // create label
  3762. var content = document.createTextNode(text);
  3763. label = document.createElement('div');
  3764. label.className = 'text major';
  3765. label.appendChild(content);
  3766. this.frame.appendChild(label);
  3767. }
  3768. this.dom.majorTexts.push(label);
  3769. label.childNodes[0].nodeValue = text;
  3770. //label.title = title; // TODO: this is a heavy operation
  3771. if (orientation == 'top') {
  3772. label.style.top = '0px';
  3773. label.style.bottom = '';
  3774. }
  3775. else {
  3776. label.style.top = '';
  3777. label.style.bottom = '0px';
  3778. }
  3779. label.style.left = x + 'px';
  3780. };
  3781. /**
  3782. * Create a minor line for the axis at position x
  3783. * @param {Number} x
  3784. * @param {String} orientation "top" or "bottom" (default)
  3785. * @private
  3786. */
  3787. TimeAxis.prototype._repaintMinorLine = function (x, orientation) {
  3788. // reuse redundant line
  3789. var line = this.dom.redundant.minorLines.shift();
  3790. if (!line) {
  3791. // create vertical line
  3792. line = document.createElement('div');
  3793. line.className = 'grid vertical minor';
  3794. this.frame.appendChild(line);
  3795. }
  3796. this.dom.minorLines.push(line);
  3797. var props = this.props;
  3798. if (orientation == 'top') {
  3799. line.style.top = this.props.majorLabelHeight + 'px';
  3800. line.style.bottom = '';
  3801. }
  3802. else {
  3803. line.style.top = '';
  3804. line.style.bottom = this.props.majorLabelHeight + 'px';
  3805. }
  3806. line.style.height = props.minorLineHeight + 'px';
  3807. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  3808. };
  3809. /**
  3810. * Create a Major line for the axis at position x
  3811. * @param {Number} x
  3812. * @param {String} orientation "top" or "bottom" (default)
  3813. * @private
  3814. */
  3815. TimeAxis.prototype._repaintMajorLine = function (x, orientation) {
  3816. // reuse redundant line
  3817. var line = this.dom.redundant.majorLines.shift();
  3818. if (!line) {
  3819. // create vertical line
  3820. line = document.createElement('DIV');
  3821. line.className = 'grid vertical major';
  3822. this.frame.appendChild(line);
  3823. }
  3824. this.dom.majorLines.push(line);
  3825. var props = this.props;
  3826. if (orientation == 'top') {
  3827. line.style.top = '0px';
  3828. line.style.bottom = '';
  3829. }
  3830. else {
  3831. line.style.top = '';
  3832. line.style.bottom = '0px';
  3833. }
  3834. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  3835. line.style.height = props.majorLineHeight + 'px';
  3836. };
  3837. /**
  3838. * Repaint the horizontal line for the axis
  3839. * @private
  3840. */
  3841. TimeAxis.prototype._repaintLine = function() {
  3842. var line = this.dom.line,
  3843. frame = this.frame,
  3844. orientation = this.getOption('orientation');
  3845. // line before all axis elements
  3846. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  3847. if (line) {
  3848. // put this line at the end of all childs
  3849. frame.removeChild(line);
  3850. frame.appendChild(line);
  3851. }
  3852. else {
  3853. // create the axis line
  3854. line = document.createElement('div');
  3855. line.className = 'grid horizontal major';
  3856. frame.appendChild(line);
  3857. this.dom.line = line;
  3858. }
  3859. if (orientation == 'top') {
  3860. line.style.top = this.height + 'px';
  3861. line.style.bottom = '';
  3862. }
  3863. else {
  3864. line.style.top = '';
  3865. line.style.bottom = this.height + 'px';
  3866. }
  3867. }
  3868. else {
  3869. if (line && line.parentNode) {
  3870. line.parentNode.removeChild(line);
  3871. delete this.dom.line;
  3872. }
  3873. }
  3874. };
  3875. /**
  3876. * Determine the size of text on the axis (both major and minor axis).
  3877. * The size is calculated only once and then cached in this.props.
  3878. * @private
  3879. */
  3880. TimeAxis.prototype._calculateCharSize = function () {
  3881. // determine the char width and height on the minor axis
  3882. if (!('minorCharHeight' in this.props)) {
  3883. var textMinor = document.createTextNode('0');
  3884. var measureCharMinor = document.createElement('DIV');
  3885. measureCharMinor.className = 'text minor measure';
  3886. measureCharMinor.appendChild(textMinor);
  3887. this.frame.appendChild(measureCharMinor);
  3888. this.props.minorCharHeight = measureCharMinor.clientHeight;
  3889. this.props.minorCharWidth = measureCharMinor.clientWidth;
  3890. this.frame.removeChild(measureCharMinor);
  3891. }
  3892. if (!('majorCharHeight' in this.props)) {
  3893. var textMajor = document.createTextNode('0');
  3894. var measureCharMajor = document.createElement('DIV');
  3895. measureCharMajor.className = 'text major measure';
  3896. measureCharMajor.appendChild(textMajor);
  3897. this.frame.appendChild(measureCharMajor);
  3898. this.props.majorCharHeight = measureCharMajor.clientHeight;
  3899. this.props.majorCharWidth = measureCharMajor.clientWidth;
  3900. this.frame.removeChild(measureCharMajor);
  3901. }
  3902. };
  3903. /**
  3904. * Snap a date to a rounded value.
  3905. * The snap intervals are dependent on the current scale and step.
  3906. * @param {Date} date the date to be snapped.
  3907. * @return {Date} snappedDate
  3908. */
  3909. TimeAxis.prototype.snap = function snap (date) {
  3910. return this.step.snap(date);
  3911. };
  3912. /**
  3913. * A current time bar
  3914. * @param {Range} range
  3915. * @param {Object} [options] Available parameters:
  3916. * {Boolean} [showCurrentTime]
  3917. * @constructor CurrentTime
  3918. * @extends Component
  3919. */
  3920. function CurrentTime (range, options) {
  3921. this.id = util.randomUUID();
  3922. this.range = range;
  3923. this.options = options || {};
  3924. this.defaultOptions = {
  3925. showCurrentTime: false
  3926. };
  3927. this._create();
  3928. }
  3929. CurrentTime.prototype = new Component();
  3930. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  3931. /**
  3932. * Create the HTML DOM for the current time bar
  3933. * @private
  3934. */
  3935. CurrentTime.prototype._create = function _create () {
  3936. var bar = document.createElement('div');
  3937. bar.className = 'currenttime';
  3938. bar.style.position = 'absolute';
  3939. bar.style.top = '0px';
  3940. bar.style.height = '100%';
  3941. this.bar = bar;
  3942. };
  3943. /**
  3944. * Get the frame element of the current time bar
  3945. * @returns {HTMLElement} frame
  3946. */
  3947. CurrentTime.prototype.getFrame = function getFrame() {
  3948. return this.bar;
  3949. };
  3950. /**
  3951. * Repaint the component
  3952. * @return {boolean} Returns true if the component is resized
  3953. */
  3954. CurrentTime.prototype.repaint = function repaint() {
  3955. var parent = this.parent;
  3956. var now = new Date();
  3957. var x = this.options.toScreen(now);
  3958. this.bar.style.left = x + 'px';
  3959. this.bar.title = 'Current time: ' + now;
  3960. return false;
  3961. };
  3962. /**
  3963. * Start auto refreshing the current time bar
  3964. */
  3965. CurrentTime.prototype.start = function start() {
  3966. var me = this;
  3967. function update () {
  3968. me.stop();
  3969. // determine interval to refresh
  3970. var scale = me.range.conversion(me.parent.width).scale;
  3971. var interval = 1 / scale / 10;
  3972. if (interval < 30) interval = 30;
  3973. if (interval > 1000) interval = 1000;
  3974. me.repaint();
  3975. // start a timer to adjust for the new time
  3976. me.currentTimeTimer = setTimeout(update, interval);
  3977. }
  3978. update();
  3979. };
  3980. /**
  3981. * Stop auto refreshing the current time bar
  3982. */
  3983. CurrentTime.prototype.stop = function stop() {
  3984. if (this.currentTimeTimer !== undefined) {
  3985. clearTimeout(this.currentTimeTimer);
  3986. delete this.currentTimeTimer;
  3987. }
  3988. };
  3989. /**
  3990. * A custom time bar
  3991. * @param {Object} [options] Available parameters:
  3992. * {Boolean} [showCustomTime]
  3993. * @constructor CustomTime
  3994. * @extends Component
  3995. */
  3996. function CustomTime (options) {
  3997. this.id = util.randomUUID();
  3998. this.options = options || {};
  3999. this.defaultOptions = {
  4000. showCustomTime: false
  4001. };
  4002. this.customTime = new Date();
  4003. this.eventParams = {}; // stores state parameters while dragging the bar
  4004. // create the DOM
  4005. this._create();
  4006. }
  4007. CustomTime.prototype = new Component();
  4008. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4009. /**
  4010. * Create the DOM for the custom time
  4011. * @private
  4012. */
  4013. CustomTime.prototype._create = function _create () {
  4014. var bar = document.createElement('div');
  4015. bar.className = 'customtime';
  4016. bar.style.position = 'absolute';
  4017. bar.style.top = '0px';
  4018. bar.style.height = '100%';
  4019. this.bar = bar;
  4020. var drag = document.createElement('div');
  4021. drag.style.position = 'relative';
  4022. drag.style.top = '0px';
  4023. drag.style.left = '-10px';
  4024. drag.style.height = '100%';
  4025. drag.style.width = '20px';
  4026. bar.appendChild(drag);
  4027. // attach event listeners
  4028. this.hammer = Hammer(bar, {
  4029. prevent_default: true
  4030. });
  4031. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4032. this.hammer.on('drag', this._onDrag.bind(this));
  4033. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4034. };
  4035. /**
  4036. * Get the frame element of the custom time bar
  4037. * @returns {HTMLElement} frame
  4038. */
  4039. CustomTime.prototype.getFrame = function getFrame() {
  4040. return this.bar;
  4041. };
  4042. /**
  4043. * Repaint the component
  4044. * @return {boolean} Returns true if the component is resized
  4045. */
  4046. CustomTime.prototype.repaint = function () {
  4047. var x = this.options.toScreen(this.customTime);
  4048. this.bar.style.left = x + 'px';
  4049. this.bar.title = 'Time: ' + this.customTime;
  4050. return false;
  4051. };
  4052. /**
  4053. * Set custom time.
  4054. * @param {Date} time
  4055. */
  4056. CustomTime.prototype.setCustomTime = function(time) {
  4057. this.customTime = new Date(time.valueOf());
  4058. this.repaint();
  4059. };
  4060. /**
  4061. * Retrieve the current custom time.
  4062. * @return {Date} customTime
  4063. */
  4064. CustomTime.prototype.getCustomTime = function() {
  4065. return new Date(this.customTime.valueOf());
  4066. };
  4067. /**
  4068. * Start moving horizontally
  4069. * @param {Event} event
  4070. * @private
  4071. */
  4072. CustomTime.prototype._onDragStart = function(event) {
  4073. this.eventParams.dragging = true;
  4074. this.eventParams.customTime = this.customTime;
  4075. event.stopPropagation();
  4076. event.preventDefault();
  4077. };
  4078. /**
  4079. * Perform moving operating.
  4080. * @param {Event} event
  4081. * @private
  4082. */
  4083. CustomTime.prototype._onDrag = function (event) {
  4084. if (!this.eventParams.dragging) return;
  4085. var deltaX = event.gesture.deltaX,
  4086. x = this.options.toScreen(this.eventParams.customTime) + deltaX,
  4087. time = this.options.toTime(x);
  4088. this.setCustomTime(time);
  4089. // fire a timechange event
  4090. this.emit('timechange', {
  4091. time: new Date(this.customTime.valueOf())
  4092. });
  4093. event.stopPropagation();
  4094. event.preventDefault();
  4095. };
  4096. /**
  4097. * Stop moving operating.
  4098. * @param {event} event
  4099. * @private
  4100. */
  4101. CustomTime.prototype._onDragEnd = function (event) {
  4102. if (!this.eventParams.dragging) return;
  4103. // fire a timechanged event
  4104. this.emit('timechanged', {
  4105. time: new Date(this.customTime.valueOf())
  4106. });
  4107. event.stopPropagation();
  4108. event.preventDefault();
  4109. };
  4110. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  4111. /**
  4112. * An ItemSet holds a set of items and ranges which can be displayed in a
  4113. * range. The width is determined by the parent of the ItemSet, and the height
  4114. * is determined by the size of the items.
  4115. * @param {Panel} backgroundPanel Panel which can be used to display the
  4116. * vertical lines of box items.
  4117. * @param {Panel} axisPanel Panel on the axis where the dots of box-items
  4118. * can be displayed.
  4119. * @param {Panel} sidePanel Left side panel holding labels
  4120. * @param {Object} [options] See ItemSet.setOptions for the available options.
  4121. * @constructor ItemSet
  4122. * @extends Panel
  4123. */
  4124. function ItemSet(backgroundPanel, axisPanel, sidePanel, options) {
  4125. this.id = util.randomUUID();
  4126. // one options object is shared by this itemset and all its items
  4127. this.options = options || {};
  4128. this.backgroundPanel = backgroundPanel;
  4129. this.axisPanel = axisPanel;
  4130. this.sidePanel = sidePanel;
  4131. this.itemOptions = Object.create(this.options);
  4132. this.dom = {};
  4133. this.hammer = null;
  4134. var me = this;
  4135. this.itemsData = null; // DataSet
  4136. this.groupsData = null; // DataSet
  4137. this.range = null; // Range or Object {start: number, end: number}
  4138. // listeners for the DataSet of the items
  4139. this.itemListeners = {
  4140. 'add': function (event, params, senderId) {
  4141. if (senderId != me.id) me._onAdd(params.items);
  4142. },
  4143. 'update': function (event, params, senderId) {
  4144. if (senderId != me.id) me._onUpdate(params.items);
  4145. },
  4146. 'remove': function (event, params, senderId) {
  4147. if (senderId != me.id) me._onRemove(params.items);
  4148. }
  4149. };
  4150. // listeners for the DataSet of the groups
  4151. this.groupListeners = {
  4152. 'add': function (event, params, senderId) {
  4153. if (senderId != me.id) me._onAddGroups(params.items);
  4154. },
  4155. 'update': function (event, params, senderId) {
  4156. if (senderId != me.id) me._onUpdateGroups(params.items);
  4157. },
  4158. 'remove': function (event, params, senderId) {
  4159. if (senderId != me.id) me._onRemoveGroups(params.items);
  4160. }
  4161. };
  4162. this.items = {}; // object with an Item for every data item
  4163. this.groups = {}; // Group object for every group
  4164. this.groupIds = [];
  4165. this.selection = []; // list with the ids of all selected nodes
  4166. this.stackDirty = true; // if true, all items will be restacked on next repaint
  4167. this.touchParams = {}; // stores properties while dragging
  4168. // create the HTML DOM
  4169. this._create();
  4170. }
  4171. ItemSet.prototype = new Panel();
  4172. // available item types will be registered here
  4173. ItemSet.types = {
  4174. box: ItemBox,
  4175. range: ItemRange,
  4176. rangeoverflow: ItemRangeOverflow,
  4177. point: ItemPoint
  4178. };
  4179. /**
  4180. * Create the HTML DOM for the ItemSet
  4181. */
  4182. ItemSet.prototype._create = function _create(){
  4183. var frame = document.createElement('div');
  4184. frame['timeline-itemset'] = this;
  4185. this.frame = frame;
  4186. // create background panel
  4187. var background = document.createElement('div');
  4188. background.className = 'background';
  4189. this.backgroundPanel.frame.appendChild(background);
  4190. this.dom.background = background;
  4191. // create foreground panel
  4192. var foreground = document.createElement('div');
  4193. foreground.className = 'foreground';
  4194. frame.appendChild(foreground);
  4195. this.dom.foreground = foreground;
  4196. // create axis panel
  4197. var axis = document.createElement('div');
  4198. axis.className = 'axis';
  4199. this.dom.axis = axis;
  4200. this.axisPanel.frame.appendChild(axis);
  4201. // create labelset
  4202. var labelSet = document.createElement('div');
  4203. labelSet.className = 'labelset';
  4204. this.dom.labelSet = labelSet;
  4205. this.sidePanel.frame.appendChild(labelSet);
  4206. // create ungrouped Group
  4207. this._updateUngrouped();
  4208. // attach event listeners
  4209. // TODO: use event listeners from the rootpanel to improve performance?
  4210. this.hammer = Hammer(frame, {
  4211. prevent_default: true
  4212. });
  4213. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4214. this.hammer.on('drag', this._onDrag.bind(this));
  4215. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4216. };
  4217. /**
  4218. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4219. * @param {Object} [options] The following options are available:
  4220. * {String | function} [className]
  4221. * class name for the itemset
  4222. * {String} [type]
  4223. * Default type for the items. Choose from 'box'
  4224. * (default), 'point', or 'range'. The default
  4225. * Style can be overwritten by individual items.
  4226. * {String} align
  4227. * Alignment for the items, only applicable for
  4228. * ItemBox. Choose 'center' (default), 'left', or
  4229. * 'right'.
  4230. * {String} orientation
  4231. * Orientation of the item set. Choose 'top' or
  4232. * 'bottom' (default).
  4233. * {Number} margin.axis
  4234. * Margin between the axis and the items in pixels.
  4235. * Default is 20.
  4236. * {Number} margin.item
  4237. * Margin between items in pixels. Default is 10.
  4238. * {Number} padding
  4239. * Padding of the contents of an item in pixels.
  4240. * Must correspond with the items css. Default is 5.
  4241. * {Function} snap
  4242. * Function to let items snap to nice dates when
  4243. * dragging items.
  4244. */
  4245. ItemSet.prototype.setOptions = function setOptions(options) {
  4246. Component.prototype.setOptions.call(this, options);
  4247. };
  4248. /**
  4249. * Mark the ItemSet dirty so it will refresh everything with next repaint
  4250. */
  4251. ItemSet.prototype.markDirty = function markDirty() {
  4252. this.groupIds = [];
  4253. this.stackDirty = true;
  4254. };
  4255. /**
  4256. * Hide the component from the DOM
  4257. */
  4258. ItemSet.prototype.hide = function hide() {
  4259. // remove the axis with dots
  4260. if (this.dom.axis.parentNode) {
  4261. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4262. }
  4263. // remove the background with vertical lines
  4264. if (this.dom.background.parentNode) {
  4265. this.dom.background.parentNode.removeChild(this.dom.background);
  4266. }
  4267. // remove the labelset containing all group labels
  4268. if (this.dom.labelSet.parentNode) {
  4269. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  4270. }
  4271. };
  4272. /**
  4273. * Show the component in the DOM (when not already visible).
  4274. * @return {Boolean} changed
  4275. */
  4276. ItemSet.prototype.show = function show() {
  4277. // show axis with dots
  4278. if (!this.dom.axis.parentNode) {
  4279. this.axisPanel.frame.appendChild(this.dom.axis);
  4280. }
  4281. // show background with vertical lines
  4282. if (!this.dom.background.parentNode) {
  4283. this.backgroundPanel.frame.appendChild(this.dom.background);
  4284. }
  4285. // show labelset containing labels
  4286. if (!this.dom.labelSet.parentNode) {
  4287. this.sidePanel.frame.appendChild(this.dom.labelSet);
  4288. }
  4289. };
  4290. /**
  4291. * Set range (start and end).
  4292. * @param {Range | Object} range A Range or an object containing start and end.
  4293. */
  4294. ItemSet.prototype.setRange = function setRange(range) {
  4295. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4296. throw new TypeError('Range must be an instance of Range, ' +
  4297. 'or an object containing start and end.');
  4298. }
  4299. this.range = range;
  4300. };
  4301. /**
  4302. * Set selected items by their id. Replaces the current selection
  4303. * Unknown id's are silently ignored.
  4304. * @param {Array} [ids] An array with zero or more id's of the items to be
  4305. * selected. If ids is an empty array, all items will be
  4306. * unselected.
  4307. */
  4308. ItemSet.prototype.setSelection = function setSelection(ids) {
  4309. var i, ii, id, item;
  4310. if (ids) {
  4311. if (!Array.isArray(ids)) {
  4312. throw new TypeError('Array expected');
  4313. }
  4314. // unselect currently selected items
  4315. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4316. id = this.selection[i];
  4317. item = this.items[id];
  4318. if (item) item.unselect();
  4319. }
  4320. // select items
  4321. this.selection = [];
  4322. for (i = 0, ii = ids.length; i < ii; i++) {
  4323. id = ids[i];
  4324. item = this.items[id];
  4325. if (item) {
  4326. this.selection.push(id);
  4327. item.select();
  4328. }
  4329. }
  4330. }
  4331. };
  4332. /**
  4333. * Get the selected items by their id
  4334. * @return {Array} ids The ids of the selected items
  4335. */
  4336. ItemSet.prototype.getSelection = function getSelection() {
  4337. return this.selection.concat([]);
  4338. };
  4339. /**
  4340. * Deselect a selected item
  4341. * @param {String | Number} id
  4342. * @private
  4343. */
  4344. ItemSet.prototype._deselect = function _deselect(id) {
  4345. var selection = this.selection;
  4346. for (var i = 0, ii = selection.length; i < ii; i++) {
  4347. if (selection[i] == id) { // non-strict comparison!
  4348. selection.splice(i, 1);
  4349. break;
  4350. }
  4351. }
  4352. };
  4353. /**
  4354. * Return the item sets frame
  4355. * @returns {HTMLElement} frame
  4356. */
  4357. ItemSet.prototype.getFrame = function getFrame() {
  4358. return this.frame;
  4359. };
  4360. /**
  4361. * Repaint the component
  4362. * @return {boolean} Returns true if the component is resized
  4363. */
  4364. ItemSet.prototype.repaint = function repaint() {
  4365. var margin = this.options.margin,
  4366. range = this.range,
  4367. asSize = util.option.asSize,
  4368. asString = util.option.asString,
  4369. options = this.options,
  4370. orientation = this.getOption('orientation'),
  4371. resized = false,
  4372. frame = this.frame;
  4373. // TODO: document this feature to specify one margin for both item and axis distance
  4374. if (typeof margin === 'number') {
  4375. margin = {
  4376. item: margin,
  4377. axis: margin
  4378. };
  4379. }
  4380. // update className
  4381. frame.className = 'itemset' + (options.className ? (' ' + asString(options.className)) : '');
  4382. // reorder the groups (if needed)
  4383. resized = this._orderGroups() || resized;
  4384. // check whether zoomed (in that case we need to re-stack everything)
  4385. // TODO: would be nicer to get this as a trigger from Range
  4386. var visibleInterval = this.range.end - this.range.start;
  4387. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth);
  4388. if (zoomed) this.stackDirty = true;
  4389. this.lastVisibleInterval = visibleInterval;
  4390. this.lastWidth = this.width;
  4391. // repaint all groups
  4392. var restack = this.stackDirty,
  4393. firstGroup = this._firstGroup(),
  4394. firstMargin = {
  4395. item: margin.item,
  4396. axis: margin.axis
  4397. },
  4398. nonFirstMargin = {
  4399. item: margin.item,
  4400. axis: margin.item / 2
  4401. },
  4402. height = 0,
  4403. minHeight = margin.axis + margin.item;
  4404. util.forEach(this.groups, function (group) {
  4405. var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
  4406. resized = group.repaint(range, groupMargin, restack) || resized;
  4407. height += group.height;
  4408. });
  4409. height = Math.max(height, minHeight);
  4410. this.stackDirty = false;
  4411. // reposition frame
  4412. frame.style.left = asSize(options.left, '');
  4413. frame.style.right = asSize(options.right, '');
  4414. frame.style.top = asSize((orientation == 'top') ? '0' : '');
  4415. frame.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4416. frame.style.width = asSize(options.width, '100%');
  4417. frame.style.height = asSize(height);
  4418. //frame.style.height = asSize('height' in options ? options.height : height); // TODO: reckon with height
  4419. // calculate actual size and position
  4420. this.top = frame.offsetTop;
  4421. this.left = frame.offsetLeft;
  4422. this.width = frame.offsetWidth;
  4423. this.height = height;
  4424. // reposition axis
  4425. this.dom.axis.style.left = asSize(options.left, '0');
  4426. this.dom.axis.style.right = asSize(options.right, '');
  4427. this.dom.axis.style.width = asSize(options.width, '100%');
  4428. this.dom.axis.style.height = asSize(0);
  4429. this.dom.axis.style.top = asSize((orientation == 'top') ? '0' : '');
  4430. this.dom.axis.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4431. // check if this component is resized
  4432. resized = this._isResized() || resized;
  4433. return resized;
  4434. };
  4435. /**
  4436. * Get the first group, aligned with the axis
  4437. * @return {Group | null} firstGroup
  4438. * @private
  4439. */
  4440. ItemSet.prototype._firstGroup = function _firstGroup() {
  4441. var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1);
  4442. var firstGroupId = this.groupIds[firstGroupIndex];
  4443. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  4444. return firstGroup || null;
  4445. };
  4446. /**
  4447. * Create or delete the group holding all ungrouped items. This group is used when
  4448. * there are no groups specified.
  4449. * @protected
  4450. */
  4451. ItemSet.prototype._updateUngrouped = function _updateUngrouped() {
  4452. var ungrouped = this.groups[UNGROUPED];
  4453. if (this.groupsData) {
  4454. // remove the group holding all ungrouped items
  4455. if (ungrouped) {
  4456. ungrouped.hide();
  4457. delete this.groups[UNGROUPED];
  4458. }
  4459. }
  4460. else {
  4461. // create a group holding all (unfiltered) items
  4462. if (!ungrouped) {
  4463. var id = null;
  4464. var data = null;
  4465. ungrouped = new Group(id, data, this);
  4466. this.groups[UNGROUPED] = ungrouped;
  4467. for (var itemId in this.items) {
  4468. if (this.items.hasOwnProperty(itemId)) {
  4469. ungrouped.add(this.items[itemId]);
  4470. }
  4471. }
  4472. ungrouped.show();
  4473. }
  4474. }
  4475. };
  4476. /**
  4477. * Get the foreground container element
  4478. * @return {HTMLElement} foreground
  4479. */
  4480. ItemSet.prototype.getForeground = function getForeground() {
  4481. return this.dom.foreground;
  4482. };
  4483. /**
  4484. * Get the background container element
  4485. * @return {HTMLElement} background
  4486. */
  4487. ItemSet.prototype.getBackground = function getBackground() {
  4488. return this.dom.background;
  4489. };
  4490. /**
  4491. * Get the axis container element
  4492. * @return {HTMLElement} axis
  4493. */
  4494. ItemSet.prototype.getAxis = function getAxis() {
  4495. return this.dom.axis;
  4496. };
  4497. /**
  4498. * Get the element for the labelset
  4499. * @return {HTMLElement} labelSet
  4500. */
  4501. ItemSet.prototype.getLabelSet = function getLabelSet() {
  4502. return this.dom.labelSet;
  4503. };
  4504. /**
  4505. * Set items
  4506. * @param {vis.DataSet | null} items
  4507. */
  4508. ItemSet.prototype.setItems = function setItems(items) {
  4509. var me = this,
  4510. ids,
  4511. oldItemsData = this.itemsData;
  4512. // replace the dataset
  4513. if (!items) {
  4514. this.itemsData = null;
  4515. }
  4516. else if (items instanceof DataSet || items instanceof DataView) {
  4517. this.itemsData = items;
  4518. }
  4519. else {
  4520. throw new TypeError('Data must be an instance of DataSet or DataView');
  4521. }
  4522. if (oldItemsData) {
  4523. // unsubscribe from old dataset
  4524. util.forEach(this.itemListeners, function (callback, event) {
  4525. oldItemsData.unsubscribe(event, callback);
  4526. });
  4527. // remove all drawn items
  4528. ids = oldItemsData.getIds();
  4529. this._onRemove(ids);
  4530. }
  4531. if (this.itemsData) {
  4532. // subscribe to new dataset
  4533. var id = this.id;
  4534. util.forEach(this.itemListeners, function (callback, event) {
  4535. me.itemsData.on(event, callback, id);
  4536. });
  4537. // add all new items
  4538. ids = this.itemsData.getIds();
  4539. this._onAdd(ids);
  4540. // update the group holding all ungrouped items
  4541. this._updateUngrouped();
  4542. }
  4543. };
  4544. /**
  4545. * Get the current items
  4546. * @returns {vis.DataSet | null}
  4547. */
  4548. ItemSet.prototype.getItems = function getItems() {
  4549. return this.itemsData;
  4550. };
  4551. /**
  4552. * Set groups
  4553. * @param {vis.DataSet} groups
  4554. */
  4555. ItemSet.prototype.setGroups = function setGroups(groups) {
  4556. var me = this,
  4557. ids;
  4558. // unsubscribe from current dataset
  4559. if (this.groupsData) {
  4560. util.forEach(this.groupListeners, function (callback, event) {
  4561. me.groupsData.unsubscribe(event, callback);
  4562. });
  4563. // remove all drawn groups
  4564. ids = this.groupsData.getIds();
  4565. this._onRemoveGroups(ids);
  4566. }
  4567. // replace the dataset
  4568. if (!groups) {
  4569. this.groupsData = null;
  4570. }
  4571. else if (groups instanceof DataSet || groups instanceof DataView) {
  4572. this.groupsData = groups;
  4573. }
  4574. else {
  4575. throw new TypeError('Data must be an instance of DataSet or DataView');
  4576. }
  4577. if (this.groupsData) {
  4578. // subscribe to new dataset
  4579. var id = this.id;
  4580. util.forEach(this.groupListeners, function (callback, event) {
  4581. me.groupsData.on(event, callback, id);
  4582. });
  4583. // draw all ms
  4584. ids = this.groupsData.getIds();
  4585. this._onAddGroups(ids);
  4586. }
  4587. // update the group holding all ungrouped items
  4588. this._updateUngrouped();
  4589. // update the order of all items in each group
  4590. this._order();
  4591. this.emit('change');
  4592. };
  4593. /**
  4594. * Get the current groups
  4595. * @returns {vis.DataSet | null} groups
  4596. */
  4597. ItemSet.prototype.getGroups = function getGroups() {
  4598. return this.groupsData;
  4599. };
  4600. /**
  4601. * Remove an item by its id
  4602. * @param {String | Number} id
  4603. */
  4604. ItemSet.prototype.removeItem = function removeItem (id) {
  4605. var item = this.itemsData.get(id),
  4606. dataset = this._myDataSet();
  4607. if (item) {
  4608. // confirm deletion
  4609. this.options.onRemove(item, function (item) {
  4610. if (item) {
  4611. // remove by id here, it is possible that an item has no id defined
  4612. // itself, so better not delete by the item itself
  4613. dataset.remove(id);
  4614. }
  4615. });
  4616. }
  4617. };
  4618. /**
  4619. * Handle updated items
  4620. * @param {Number[]} ids
  4621. * @protected
  4622. */
  4623. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4624. var me = this,
  4625. items = this.items,
  4626. itemOptions = this.itemOptions;
  4627. ids.forEach(function (id) {
  4628. var itemData = me.itemsData.get(id),
  4629. item = items[id],
  4630. type = itemData.type ||
  4631. (itemData.start && itemData.end && 'range') ||
  4632. me.options.type ||
  4633. 'box';
  4634. var constructor = ItemSet.types[type];
  4635. if (item) {
  4636. // update item
  4637. if (!constructor || !(item instanceof constructor)) {
  4638. // item type has changed, delete the item and recreate it
  4639. me._removeItem(item);
  4640. item = null;
  4641. }
  4642. else {
  4643. me._updateItem(item, itemData);
  4644. }
  4645. }
  4646. if (!item) {
  4647. // create item
  4648. if (constructor) {
  4649. item = new constructor(itemData, me.options, itemOptions);
  4650. item.id = id; // TODO: not so nice setting id afterwards
  4651. me._addItem(item);
  4652. }
  4653. else {
  4654. throw new TypeError('Unknown item type "' + type + '"');
  4655. }
  4656. }
  4657. });
  4658. this._order();
  4659. this.stackDirty = true; // force re-stacking of all items next repaint
  4660. this.emit('change');
  4661. };
  4662. /**
  4663. * Handle added items
  4664. * @param {Number[]} ids
  4665. * @protected
  4666. */
  4667. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  4668. /**
  4669. * Handle removed items
  4670. * @param {Number[]} ids
  4671. * @protected
  4672. */
  4673. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4674. var count = 0;
  4675. var me = this;
  4676. ids.forEach(function (id) {
  4677. var item = me.items[id];
  4678. if (item) {
  4679. count++;
  4680. me._removeItem(item);
  4681. }
  4682. });
  4683. if (count) {
  4684. // update order
  4685. this._order();
  4686. this.stackDirty = true; // force re-stacking of all items next repaint
  4687. this.emit('change');
  4688. }
  4689. };
  4690. /**
  4691. * Update the order of item in all groups
  4692. * @private
  4693. */
  4694. ItemSet.prototype._order = function _order() {
  4695. // reorder the items in all groups
  4696. // TODO: optimization: only reorder groups affected by the changed items
  4697. util.forEach(this.groups, function (group) {
  4698. group.order();
  4699. });
  4700. };
  4701. /**
  4702. * Handle updated groups
  4703. * @param {Number[]} ids
  4704. * @private
  4705. */
  4706. ItemSet.prototype._onUpdateGroups = function _onUpdateGroups(ids) {
  4707. this._onAddGroups(ids);
  4708. };
  4709. /**
  4710. * Handle changed groups
  4711. * @param {Number[]} ids
  4712. * @private
  4713. */
  4714. ItemSet.prototype._onAddGroups = function _onAddGroups(ids) {
  4715. var me = this;
  4716. ids.forEach(function (id) {
  4717. var groupData = me.groupsData.get(id);
  4718. var group = me.groups[id];
  4719. if (!group) {
  4720. // check for reserved ids
  4721. if (id == UNGROUPED) {
  4722. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  4723. }
  4724. var groupOptions = Object.create(me.options);
  4725. util.extend(groupOptions, {
  4726. height: null
  4727. });
  4728. group = new Group(id, groupData, me);
  4729. me.groups[id] = group;
  4730. // add items with this groupId to the new group
  4731. for (var itemId in me.items) {
  4732. if (me.items.hasOwnProperty(itemId)) {
  4733. var item = me.items[itemId];
  4734. if (item.data.group == id) {
  4735. group.add(item);
  4736. }
  4737. }
  4738. }
  4739. group.order();
  4740. group.show();
  4741. }
  4742. else {
  4743. // update group
  4744. group.setData(groupData);
  4745. }
  4746. });
  4747. this.emit('change');
  4748. };
  4749. /**
  4750. * Handle removed groups
  4751. * @param {Number[]} ids
  4752. * @private
  4753. */
  4754. ItemSet.prototype._onRemoveGroups = function _onRemoveGroups(ids) {
  4755. var groups = this.groups;
  4756. ids.forEach(function (id) {
  4757. var group = groups[id];
  4758. if (group) {
  4759. group.hide();
  4760. delete groups[id];
  4761. }
  4762. });
  4763. this.markDirty();
  4764. this.emit('change');
  4765. };
  4766. /**
  4767. * Reorder the groups if needed
  4768. * @return {boolean} changed
  4769. * @private
  4770. */
  4771. ItemSet.prototype._orderGroups = function () {
  4772. if (this.groupsData) {
  4773. // reorder the groups
  4774. var groupIds = this.groupsData.getIds({
  4775. order: this.options.groupOrder
  4776. });
  4777. var changed = !util.equalArray(groupIds, this.groupIds);
  4778. if (changed) {
  4779. // hide all groups, removes them from the DOM
  4780. var groups = this.groups;
  4781. groupIds.forEach(function (groupId) {
  4782. var group = groups[groupId];
  4783. group.hide();
  4784. });
  4785. // show the groups again, attach them to the DOM in correct order
  4786. groupIds.forEach(function (groupId) {
  4787. groups[groupId].show();
  4788. });
  4789. this.groupIds = groupIds;
  4790. }
  4791. return changed;
  4792. }
  4793. else {
  4794. return false;
  4795. }
  4796. };
  4797. /**
  4798. * Add a new item
  4799. * @param {Item} item
  4800. * @private
  4801. */
  4802. ItemSet.prototype._addItem = function _addItem(item) {
  4803. this.items[item.id] = item;
  4804. // add to group
  4805. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  4806. var group = this.groups[groupId];
  4807. if (group) group.add(item);
  4808. };
  4809. /**
  4810. * Update an existing item
  4811. * @param {Item} item
  4812. * @param {Object} itemData
  4813. * @private
  4814. */
  4815. ItemSet.prototype._updateItem = function _updateItem(item, itemData) {
  4816. var oldGroupId = item.data.group;
  4817. item.data = itemData;
  4818. item.repaint();
  4819. // update group
  4820. if (oldGroupId != item.data.group) {
  4821. var oldGroup = this.groups[oldGroupId];
  4822. if (oldGroup) oldGroup.remove(item);
  4823. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  4824. var group = this.groups[groupId];
  4825. if (group) group.add(item);
  4826. }
  4827. };
  4828. /**
  4829. * Delete an item from the ItemSet: remove it from the DOM, from the map
  4830. * with items, and from the map with visible items, and from the selection
  4831. * @param {Item} item
  4832. * @private
  4833. */
  4834. ItemSet.prototype._removeItem = function _removeItem(item) {
  4835. // remove from DOM
  4836. item.hide();
  4837. // remove from items
  4838. delete this.items[item.id];
  4839. // remove from selection
  4840. var index = this.selection.indexOf(item.id);
  4841. if (index != -1) this.selection.splice(index, 1);
  4842. // remove from group
  4843. var groupId = this.groupsData ? item.data.group : UNGROUPED;
  4844. var group = this.groups[groupId];
  4845. if (group) group.remove(item);
  4846. };
  4847. /**
  4848. * Create an array containing all items being a range (having an end date)
  4849. * @param array
  4850. * @returns {Array}
  4851. * @private
  4852. */
  4853. ItemSet.prototype._constructByEndArray = function _constructByEndArray(array) {
  4854. var endArray = [];
  4855. for (var i = 0; i < array.length; i++) {
  4856. if (array[i] instanceof ItemRange) {
  4857. endArray.push(array[i]);
  4858. }
  4859. }
  4860. return endArray;
  4861. };
  4862. /**
  4863. * Get the width of the group labels
  4864. * @return {Number} width
  4865. */
  4866. ItemSet.prototype.getLabelsWidth = function getLabelsWidth() {
  4867. var width = 0;
  4868. util.forEach(this.groups, function (group) {
  4869. width = Math.max(width, group.getLabelWidth());
  4870. });
  4871. return width;
  4872. };
  4873. /**
  4874. * Get the height of the itemsets background
  4875. * @return {Number} height
  4876. */
  4877. ItemSet.prototype.getBackgroundHeight = function getBackgroundHeight() {
  4878. return this.height;
  4879. };
  4880. /**
  4881. * Start dragging the selected events
  4882. * @param {Event} event
  4883. * @private
  4884. */
  4885. ItemSet.prototype._onDragStart = function (event) {
  4886. if (!this.options.editable.updateTime && !this.options.editable.updateGroup) {
  4887. return;
  4888. }
  4889. var item = ItemSet.itemFromTarget(event),
  4890. me = this,
  4891. props;
  4892. if (item && item.selected) {
  4893. var dragLeftItem = event.target.dragLeftItem;
  4894. var dragRightItem = event.target.dragRightItem;
  4895. if (dragLeftItem) {
  4896. props = {
  4897. item: dragLeftItem
  4898. };
  4899. if (me.options.editable.updateTime) {
  4900. props.start = item.data.start.valueOf();
  4901. }
  4902. if (me.options.editable.updateGroup) {
  4903. if ('group' in item.data) props.group = item.data.group;
  4904. }
  4905. this.touchParams.itemProps = [props];
  4906. }
  4907. else if (dragRightItem) {
  4908. props = {
  4909. item: dragRightItem
  4910. };
  4911. if (me.options.editable.updateTime) {
  4912. props.end = item.data.end.valueOf();
  4913. }
  4914. if (me.options.editable.updateGroup) {
  4915. if ('group' in item.data) props.group = item.data.group;
  4916. }
  4917. this.touchParams.itemProps = [props];
  4918. }
  4919. else {
  4920. this.touchParams.itemProps = this.getSelection().map(function (id) {
  4921. var item = me.items[id];
  4922. var props = {
  4923. item: item
  4924. };
  4925. if (me.options.editable.updateTime) {
  4926. if ('start' in item.data) props.start = item.data.start.valueOf();
  4927. if ('end' in item.data) props.end = item.data.end.valueOf();
  4928. }
  4929. if (me.options.editable.updateGroup) {
  4930. if ('group' in item.data) props.group = item.data.group;
  4931. }
  4932. return props;
  4933. });
  4934. }
  4935. event.stopPropagation();
  4936. }
  4937. };
  4938. /**
  4939. * Drag selected items
  4940. * @param {Event} event
  4941. * @private
  4942. */
  4943. ItemSet.prototype._onDrag = function (event) {
  4944. if (this.touchParams.itemProps) {
  4945. var snap = this.options.snap || null,
  4946. deltaX = event.gesture.deltaX,
  4947. scale = (this.width / (this.range.end - this.range.start)),
  4948. offset = deltaX / scale;
  4949. // move
  4950. this.touchParams.itemProps.forEach(function (props) {
  4951. if ('start' in props) {
  4952. var start = new Date(props.start + offset);
  4953. props.item.data.start = snap ? snap(start) : start;
  4954. }
  4955. if ('end' in props) {
  4956. var end = new Date(props.end + offset);
  4957. props.item.data.end = snap ? snap(end) : end;
  4958. }
  4959. if ('group' in props) {
  4960. // drag from one group to another
  4961. var group = ItemSet.groupFromTarget(event);
  4962. if (group && group.groupId != props.item.data.group) {
  4963. var oldGroup = props.item.parent;
  4964. oldGroup.remove(props.item);
  4965. oldGroup.order();
  4966. group.add(props.item);
  4967. group.order();
  4968. props.item.data.group = group.groupId;
  4969. }
  4970. }
  4971. });
  4972. // TODO: implement onMoving handler
  4973. this.stackDirty = true; // force re-stacking of all items next repaint
  4974. this.emit('change');
  4975. event.stopPropagation();
  4976. }
  4977. };
  4978. /**
  4979. * End of dragging selected items
  4980. * @param {Event} event
  4981. * @private
  4982. */
  4983. ItemSet.prototype._onDragEnd = function (event) {
  4984. if (this.touchParams.itemProps) {
  4985. // prepare a change set for the changed items
  4986. var changes = [],
  4987. me = this,
  4988. dataset = this._myDataSet();
  4989. this.touchParams.itemProps.forEach(function (props) {
  4990. var id = props.item.id,
  4991. itemData = me.itemsData.get(id);
  4992. var changed = false;
  4993. if ('start' in props.item.data) {
  4994. changed = (props.start != props.item.data.start.valueOf());
  4995. itemData.start = util.convert(props.item.data.start, dataset.convert['start']);
  4996. }
  4997. if ('end' in props.item.data) {
  4998. changed = changed || (props.end != props.item.data.end.valueOf());
  4999. itemData.end = util.convert(props.item.data.end, dataset.convert['end']);
  5000. }
  5001. if ('group' in props.item.data) {
  5002. changed = changed || (props.group != props.item.data.group);
  5003. itemData.group = props.item.data.group;
  5004. }
  5005. // only apply changes when start or end is actually changed
  5006. if (changed) {
  5007. me.options.onMove(itemData, function (itemData) {
  5008. if (itemData) {
  5009. // apply changes
  5010. itemData[dataset.fieldId] = id; // ensure the item contains its id (can be undefined)
  5011. changes.push(itemData);
  5012. }
  5013. else {
  5014. // restore original values
  5015. if ('start' in props) props.item.data.start = props.start;
  5016. if ('end' in props) props.item.data.end = props.end;
  5017. me.stackDirty = true; // force re-stacking of all items next repaint
  5018. me.emit('change');
  5019. }
  5020. });
  5021. }
  5022. });
  5023. this.touchParams.itemProps = null;
  5024. // apply the changes to the data (if there are changes)
  5025. if (changes.length) {
  5026. dataset.update(changes);
  5027. }
  5028. event.stopPropagation();
  5029. }
  5030. };
  5031. /**
  5032. * Find an item from an event target:
  5033. * searches for the attribute 'timeline-item' in the event target's element tree
  5034. * @param {Event} event
  5035. * @return {Item | null} item
  5036. */
  5037. ItemSet.itemFromTarget = function itemFromTarget (event) {
  5038. var target = event.target;
  5039. while (target) {
  5040. if (target.hasOwnProperty('timeline-item')) {
  5041. return target['timeline-item'];
  5042. }
  5043. target = target.parentNode;
  5044. }
  5045. return null;
  5046. };
  5047. /**
  5048. * Find the Group from an event target:
  5049. * searches for the attribute 'timeline-group' in the event target's element tree
  5050. * @param {Event} event
  5051. * @return {Group | null} group
  5052. */
  5053. ItemSet.groupFromTarget = function groupFromTarget (event) {
  5054. var target = event.target;
  5055. while (target) {
  5056. if (target.hasOwnProperty('timeline-group')) {
  5057. return target['timeline-group'];
  5058. }
  5059. target = target.parentNode;
  5060. }
  5061. return null;
  5062. };
  5063. /**
  5064. * Find the ItemSet from an event target:
  5065. * searches for the attribute 'timeline-itemset' in the event target's element tree
  5066. * @param {Event} event
  5067. * @return {ItemSet | null} item
  5068. */
  5069. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  5070. var target = event.target;
  5071. while (target) {
  5072. if (target.hasOwnProperty('timeline-itemset')) {
  5073. return target['timeline-itemset'];
  5074. }
  5075. target = target.parentNode;
  5076. }
  5077. return null;
  5078. };
  5079. /**
  5080. * Find the DataSet to which this ItemSet is connected
  5081. * @returns {null | DataSet} dataset
  5082. * @private
  5083. */
  5084. ItemSet.prototype._myDataSet = function _myDataSet() {
  5085. // find the root DataSet
  5086. var dataset = this.itemsData;
  5087. while (dataset instanceof DataView) {
  5088. dataset = dataset.data;
  5089. }
  5090. return dataset;
  5091. };
  5092. /**
  5093. * @constructor Item
  5094. * @param {Object} data Object containing (optional) parameters type,
  5095. * start, end, content, group, className.
  5096. * @param {Object} [options] Options to set initial property values
  5097. * @param {Object} [defaultOptions] default options
  5098. * // TODO: describe available options
  5099. */
  5100. function Item (data, options, defaultOptions) {
  5101. this.id = null;
  5102. this.parent = null;
  5103. this.data = data;
  5104. this.dom = null;
  5105. this.options = options || {};
  5106. this.defaultOptions = defaultOptions || {};
  5107. this.selected = false;
  5108. this.displayed = false;
  5109. this.dirty = true;
  5110. this.top = null;
  5111. this.left = null;
  5112. this.width = null;
  5113. this.height = null;
  5114. }
  5115. /**
  5116. * Select current item
  5117. */
  5118. Item.prototype.select = function select() {
  5119. this.selected = true;
  5120. if (this.displayed) this.repaint();
  5121. };
  5122. /**
  5123. * Unselect current item
  5124. */
  5125. Item.prototype.unselect = function unselect() {
  5126. this.selected = false;
  5127. if (this.displayed) this.repaint();
  5128. };
  5129. /**
  5130. * Set a parent for the item
  5131. * @param {ItemSet | Group} parent
  5132. */
  5133. Item.prototype.setParent = function setParent(parent) {
  5134. if (this.displayed) {
  5135. this.hide();
  5136. this.parent = parent;
  5137. if (this.parent) {
  5138. this.show();
  5139. }
  5140. }
  5141. else {
  5142. this.parent = parent;
  5143. }
  5144. };
  5145. /**
  5146. * Check whether this item is visible inside given range
  5147. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5148. * @returns {boolean} True if visible
  5149. */
  5150. Item.prototype.isVisible = function isVisible (range) {
  5151. // Should be implemented by Item implementations
  5152. return false;
  5153. };
  5154. /**
  5155. * Show the Item in the DOM (when not already visible)
  5156. * @return {Boolean} changed
  5157. */
  5158. Item.prototype.show = function show() {
  5159. return false;
  5160. };
  5161. /**
  5162. * Hide the Item from the DOM (when visible)
  5163. * @return {Boolean} changed
  5164. */
  5165. Item.prototype.hide = function hide() {
  5166. return false;
  5167. };
  5168. /**
  5169. * Repaint the item
  5170. */
  5171. Item.prototype.repaint = function repaint() {
  5172. // should be implemented by the item
  5173. };
  5174. /**
  5175. * Reposition the Item horizontally
  5176. */
  5177. Item.prototype.repositionX = function repositionX() {
  5178. // should be implemented by the item
  5179. };
  5180. /**
  5181. * Reposition the Item vertically
  5182. */
  5183. Item.prototype.repositionY = function repositionY() {
  5184. // should be implemented by the item
  5185. };
  5186. /**
  5187. * Repaint a delete button on the top right of the item when the item is selected
  5188. * @param {HTMLElement} anchor
  5189. * @protected
  5190. */
  5191. Item.prototype._repaintDeleteButton = function (anchor) {
  5192. if (this.selected && this.options.editable.remove && !this.dom.deleteButton) {
  5193. // create and show button
  5194. var me = this;
  5195. var deleteButton = document.createElement('div');
  5196. deleteButton.className = 'delete';
  5197. deleteButton.title = 'Delete this item';
  5198. Hammer(deleteButton, {
  5199. preventDefault: true
  5200. }).on('tap', function (event) {
  5201. me.parent.removeFromDataSet(me);
  5202. event.stopPropagation();
  5203. });
  5204. anchor.appendChild(deleteButton);
  5205. this.dom.deleteButton = deleteButton;
  5206. }
  5207. else if (!this.selected && this.dom.deleteButton) {
  5208. // remove button
  5209. if (this.dom.deleteButton.parentNode) {
  5210. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5211. }
  5212. this.dom.deleteButton = null;
  5213. }
  5214. };
  5215. /**
  5216. * @constructor ItemBox
  5217. * @extends Item
  5218. * @param {Object} data Object containing parameters start
  5219. * content, className.
  5220. * @param {Object} [options] Options to set initial property values
  5221. * @param {Object} [defaultOptions] default options
  5222. * // TODO: describe available options
  5223. */
  5224. function ItemBox (data, options, defaultOptions) {
  5225. this.props = {
  5226. dot: {
  5227. width: 0,
  5228. height: 0
  5229. },
  5230. line: {
  5231. width: 0,
  5232. height: 0
  5233. }
  5234. };
  5235. // validate data
  5236. if (data) {
  5237. if (data.start == undefined) {
  5238. throw new Error('Property "start" missing in item ' + data);
  5239. }
  5240. }
  5241. Item.call(this, data, options, defaultOptions);
  5242. }
  5243. ItemBox.prototype = new Item (null);
  5244. /**
  5245. * Check whether this item is visible inside given range
  5246. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5247. * @returns {boolean} True if visible
  5248. */
  5249. ItemBox.prototype.isVisible = function isVisible (range) {
  5250. // determine visibility
  5251. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  5252. var interval = (range.end - range.start) / 4;
  5253. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  5254. };
  5255. /**
  5256. * Repaint the item
  5257. */
  5258. ItemBox.prototype.repaint = function repaint() {
  5259. var dom = this.dom;
  5260. if (!dom) {
  5261. // create DOM
  5262. this.dom = {};
  5263. dom = this.dom;
  5264. // create main box
  5265. dom.box = document.createElement('DIV');
  5266. // contents box (inside the background box). used for making margins
  5267. dom.content = document.createElement('DIV');
  5268. dom.content.className = 'content';
  5269. dom.box.appendChild(dom.content);
  5270. // line to axis
  5271. dom.line = document.createElement('DIV');
  5272. dom.line.className = 'line';
  5273. // dot on axis
  5274. dom.dot = document.createElement('DIV');
  5275. dom.dot.className = 'dot';
  5276. // attach this item as attribute
  5277. dom.box['timeline-item'] = this;
  5278. }
  5279. // append DOM to parent DOM
  5280. if (!this.parent) {
  5281. throw new Error('Cannot repaint item: no parent attached');
  5282. }
  5283. if (!dom.box.parentNode) {
  5284. var foreground = this.parent.getForeground();
  5285. if (!foreground) throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5286. foreground.appendChild(dom.box);
  5287. }
  5288. if (!dom.line.parentNode) {
  5289. var background = this.parent.getBackground();
  5290. if (!background) throw new Error('Cannot repaint time axis: parent has no background container element');
  5291. background.appendChild(dom.line);
  5292. }
  5293. if (!dom.dot.parentNode) {
  5294. var axis = this.parent.getAxis();
  5295. if (!background) throw new Error('Cannot repaint time axis: parent has no axis container element');
  5296. axis.appendChild(dom.dot);
  5297. }
  5298. this.displayed = true;
  5299. // update contents
  5300. if (this.data.content != this.content) {
  5301. this.content = this.data.content;
  5302. if (this.content instanceof Element) {
  5303. dom.content.innerHTML = '';
  5304. dom.content.appendChild(this.content);
  5305. }
  5306. else if (this.data.content != undefined) {
  5307. dom.content.innerHTML = this.content;
  5308. }
  5309. else {
  5310. throw new Error('Property "content" missing in item ' + this.data.id);
  5311. }
  5312. this.dirty = true;
  5313. }
  5314. // update class
  5315. var className = (this.data.className? ' ' + this.data.className : '') +
  5316. (this.selected ? ' selected' : '');
  5317. if (this.className != className) {
  5318. this.className = className;
  5319. dom.box.className = 'item box' + className;
  5320. dom.line.className = 'item line' + className;
  5321. dom.dot.className = 'item dot' + className;
  5322. this.dirty = true;
  5323. }
  5324. // recalculate size
  5325. if (this.dirty) {
  5326. this.props.dot.height = dom.dot.offsetHeight;
  5327. this.props.dot.width = dom.dot.offsetWidth;
  5328. this.props.line.width = dom.line.offsetWidth;
  5329. this.width = dom.box.offsetWidth;
  5330. this.height = dom.box.offsetHeight;
  5331. this.dirty = false;
  5332. }
  5333. this._repaintDeleteButton(dom.box);
  5334. };
  5335. /**
  5336. * Show the item in the DOM (when not already displayed). The items DOM will
  5337. * be created when needed.
  5338. */
  5339. ItemBox.prototype.show = function show() {
  5340. if (!this.displayed) {
  5341. this.repaint();
  5342. }
  5343. };
  5344. /**
  5345. * Hide the item from the DOM (when visible)
  5346. */
  5347. ItemBox.prototype.hide = function hide() {
  5348. if (this.displayed) {
  5349. var dom = this.dom;
  5350. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  5351. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  5352. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  5353. this.top = null;
  5354. this.left = null;
  5355. this.displayed = false;
  5356. }
  5357. };
  5358. /**
  5359. * Reposition the item horizontally
  5360. * @Override
  5361. */
  5362. ItemBox.prototype.repositionX = function repositionX() {
  5363. var start = this.defaultOptions.toScreen(this.data.start),
  5364. align = this.options.align || this.defaultOptions.align,
  5365. left,
  5366. box = this.dom.box,
  5367. line = this.dom.line,
  5368. dot = this.dom.dot;
  5369. // calculate left position of the box
  5370. if (align == 'right') {
  5371. this.left = start - this.width;
  5372. }
  5373. else if (align == 'left') {
  5374. this.left = start;
  5375. }
  5376. else {
  5377. // default or 'center'
  5378. this.left = start - this.width / 2;
  5379. }
  5380. // reposition box
  5381. box.style.left = this.left + 'px';
  5382. // reposition line
  5383. line.style.left = (start - this.props.line.width / 2) + 'px';
  5384. // reposition dot
  5385. dot.style.left = (start - this.props.dot.width / 2) + 'px';
  5386. };
  5387. /**
  5388. * Reposition the item vertically
  5389. * @Override
  5390. */
  5391. ItemBox.prototype.repositionY = function repositionY () {
  5392. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5393. box = this.dom.box,
  5394. line = this.dom.line,
  5395. dot = this.dom.dot;
  5396. if (orientation == 'top') {
  5397. box.style.top = (this.top || 0) + 'px';
  5398. box.style.bottom = '';
  5399. line.style.top = '0';
  5400. line.style.bottom = '';
  5401. line.style.height = (this.parent.top + this.top + 1) + 'px';
  5402. }
  5403. else { // orientation 'bottom'
  5404. box.style.top = '';
  5405. box.style.bottom = (this.top || 0) + 'px';
  5406. line.style.top = (this.parent.top + this.parent.height - this.top - 1) + 'px';
  5407. line.style.bottom = '0';
  5408. line.style.height = '';
  5409. }
  5410. dot.style.top = (-this.props.dot.height / 2) + 'px';
  5411. };
  5412. /**
  5413. * @constructor ItemPoint
  5414. * @extends Item
  5415. * @param {Object} data Object containing parameters start
  5416. * content, className.
  5417. * @param {Object} [options] Options to set initial property values
  5418. * @param {Object} [defaultOptions] default options
  5419. * // TODO: describe available options
  5420. */
  5421. function ItemPoint (data, options, defaultOptions) {
  5422. this.props = {
  5423. dot: {
  5424. top: 0,
  5425. width: 0,
  5426. height: 0
  5427. },
  5428. content: {
  5429. height: 0,
  5430. marginLeft: 0
  5431. }
  5432. };
  5433. // validate data
  5434. if (data) {
  5435. if (data.start == undefined) {
  5436. throw new Error('Property "start" missing in item ' + data);
  5437. }
  5438. }
  5439. Item.call(this, data, options, defaultOptions);
  5440. }
  5441. ItemPoint.prototype = new Item (null);
  5442. /**
  5443. * Check whether this item is visible inside given range
  5444. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5445. * @returns {boolean} True if visible
  5446. */
  5447. ItemPoint.prototype.isVisible = function isVisible (range) {
  5448. // determine visibility
  5449. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  5450. var interval = (range.end - range.start) / 4;
  5451. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  5452. };
  5453. /**
  5454. * Repaint the item
  5455. */
  5456. ItemPoint.prototype.repaint = function repaint() {
  5457. var dom = this.dom;
  5458. if (!dom) {
  5459. // create DOM
  5460. this.dom = {};
  5461. dom = this.dom;
  5462. // background box
  5463. dom.point = document.createElement('div');
  5464. // className is updated in repaint()
  5465. // contents box, right from the dot
  5466. dom.content = document.createElement('div');
  5467. dom.content.className = 'content';
  5468. dom.point.appendChild(dom.content);
  5469. // dot at start
  5470. dom.dot = document.createElement('div');
  5471. dom.point.appendChild(dom.dot);
  5472. // attach this item as attribute
  5473. dom.point['timeline-item'] = this;
  5474. }
  5475. // append DOM to parent DOM
  5476. if (!this.parent) {
  5477. throw new Error('Cannot repaint item: no parent attached');
  5478. }
  5479. if (!dom.point.parentNode) {
  5480. var foreground = this.parent.getForeground();
  5481. if (!foreground) {
  5482. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5483. }
  5484. foreground.appendChild(dom.point);
  5485. }
  5486. this.displayed = true;
  5487. // update contents
  5488. if (this.data.content != this.content) {
  5489. this.content = this.data.content;
  5490. if (this.content instanceof Element) {
  5491. dom.content.innerHTML = '';
  5492. dom.content.appendChild(this.content);
  5493. }
  5494. else if (this.data.content != undefined) {
  5495. dom.content.innerHTML = this.content;
  5496. }
  5497. else {
  5498. throw new Error('Property "content" missing in item ' + this.data.id);
  5499. }
  5500. this.dirty = true;
  5501. }
  5502. // update class
  5503. var className = (this.data.className? ' ' + this.data.className : '') +
  5504. (this.selected ? ' selected' : '');
  5505. if (this.className != className) {
  5506. this.className = className;
  5507. dom.point.className = 'item point' + className;
  5508. dom.dot.className = 'item dot' + className;
  5509. this.dirty = true;
  5510. }
  5511. // recalculate size
  5512. if (this.dirty) {
  5513. this.width = dom.point.offsetWidth;
  5514. this.height = dom.point.offsetHeight;
  5515. this.props.dot.width = dom.dot.offsetWidth;
  5516. this.props.dot.height = dom.dot.offsetHeight;
  5517. this.props.content.height = dom.content.offsetHeight;
  5518. // resize contents
  5519. dom.content.style.marginLeft = 2 * this.props.dot.width + 'px';
  5520. //dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  5521. dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px';
  5522. dom.dot.style.left = (this.props.dot.width / 2) + 'px';
  5523. this.dirty = false;
  5524. }
  5525. this._repaintDeleteButton(dom.point);
  5526. };
  5527. /**
  5528. * Show the item in the DOM (when not already visible). The items DOM will
  5529. * be created when needed.
  5530. */
  5531. ItemPoint.prototype.show = function show() {
  5532. if (!this.displayed) {
  5533. this.repaint();
  5534. }
  5535. };
  5536. /**
  5537. * Hide the item from the DOM (when visible)
  5538. */
  5539. ItemPoint.prototype.hide = function hide() {
  5540. if (this.displayed) {
  5541. if (this.dom.point.parentNode) {
  5542. this.dom.point.parentNode.removeChild(this.dom.point);
  5543. }
  5544. this.top = null;
  5545. this.left = null;
  5546. this.displayed = false;
  5547. }
  5548. };
  5549. /**
  5550. * Reposition the item horizontally
  5551. * @Override
  5552. */
  5553. ItemPoint.prototype.repositionX = function repositionX() {
  5554. var start = this.defaultOptions.toScreen(this.data.start);
  5555. this.left = start - this.props.dot.width;
  5556. // reposition point
  5557. this.dom.point.style.left = this.left + 'px';
  5558. };
  5559. /**
  5560. * Reposition the item vertically
  5561. * @Override
  5562. */
  5563. ItemPoint.prototype.repositionY = function repositionY () {
  5564. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5565. point = this.dom.point;
  5566. if (orientation == 'top') {
  5567. point.style.top = this.top + 'px';
  5568. point.style.bottom = '';
  5569. }
  5570. else {
  5571. point.style.top = '';
  5572. point.style.bottom = this.top + 'px';
  5573. }
  5574. };
  5575. /**
  5576. * @constructor ItemRange
  5577. * @extends Item
  5578. * @param {Object} data Object containing parameters start, end
  5579. * content, className.
  5580. * @param {Object} [options] Options to set initial property values
  5581. * @param {Object} [defaultOptions] default options
  5582. * // TODO: describe available options
  5583. */
  5584. function ItemRange (data, options, defaultOptions) {
  5585. this.props = {
  5586. content: {
  5587. width: 0
  5588. }
  5589. };
  5590. // validate data
  5591. if (data) {
  5592. if (data.start == undefined) {
  5593. throw new Error('Property "start" missing in item ' + data.id);
  5594. }
  5595. if (data.end == undefined) {
  5596. throw new Error('Property "end" missing in item ' + data.id);
  5597. }
  5598. }
  5599. Item.call(this, data, options, defaultOptions);
  5600. }
  5601. ItemRange.prototype = new Item (null);
  5602. ItemRange.prototype.baseClassName = 'item range';
  5603. /**
  5604. * Check whether this item is visible inside given range
  5605. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5606. * @returns {boolean} True if visible
  5607. */
  5608. ItemRange.prototype.isVisible = function isVisible (range) {
  5609. // determine visibility
  5610. return (this.data.start < range.end) && (this.data.end > range.start);
  5611. };
  5612. /**
  5613. * Repaint the item
  5614. */
  5615. ItemRange.prototype.repaint = function repaint() {
  5616. var dom = this.dom;
  5617. if (!dom) {
  5618. // create DOM
  5619. this.dom = {};
  5620. dom = this.dom;
  5621. // background box
  5622. dom.box = document.createElement('div');
  5623. // className is updated in repaint()
  5624. // contents box
  5625. dom.content = document.createElement('div');
  5626. dom.content.className = 'content';
  5627. dom.box.appendChild(dom.content);
  5628. // attach this item as attribute
  5629. dom.box['timeline-item'] = this;
  5630. }
  5631. // append DOM to parent DOM
  5632. if (!this.parent) {
  5633. throw new Error('Cannot repaint item: no parent attached');
  5634. }
  5635. if (!dom.box.parentNode) {
  5636. var foreground = this.parent.getForeground();
  5637. if (!foreground) {
  5638. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5639. }
  5640. foreground.appendChild(dom.box);
  5641. }
  5642. this.displayed = true;
  5643. // update contents
  5644. if (this.data.content != this.content) {
  5645. this.content = this.data.content;
  5646. if (this.content instanceof Element) {
  5647. dom.content.innerHTML = '';
  5648. dom.content.appendChild(this.content);
  5649. }
  5650. else if (this.data.content != undefined) {
  5651. dom.content.innerHTML = this.content;
  5652. }
  5653. else {
  5654. throw new Error('Property "content" missing in item ' + this.data.id);
  5655. }
  5656. this.dirty = true;
  5657. }
  5658. // update class
  5659. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5660. (this.selected ? ' selected' : '');
  5661. if (this.className != className) {
  5662. this.className = className;
  5663. dom.box.className = this.baseClassName + className;
  5664. this.dirty = true;
  5665. }
  5666. // recalculate size
  5667. if (this.dirty) {
  5668. this.props.content.width = this.dom.content.offsetWidth;
  5669. this.height = this.dom.box.offsetHeight;
  5670. this.dirty = false;
  5671. }
  5672. this._repaintDeleteButton(dom.box);
  5673. this._repaintDragLeft();
  5674. this._repaintDragRight();
  5675. };
  5676. /**
  5677. * Show the item in the DOM (when not already visible). The items DOM will
  5678. * be created when needed.
  5679. */
  5680. ItemRange.prototype.show = function show() {
  5681. if (!this.displayed) {
  5682. this.repaint();
  5683. }
  5684. };
  5685. /**
  5686. * Hide the item from the DOM (when visible)
  5687. * @return {Boolean} changed
  5688. */
  5689. ItemRange.prototype.hide = function hide() {
  5690. if (this.displayed) {
  5691. var box = this.dom.box;
  5692. if (box.parentNode) {
  5693. box.parentNode.removeChild(box);
  5694. }
  5695. this.top = null;
  5696. this.left = null;
  5697. this.displayed = false;
  5698. }
  5699. };
  5700. /**
  5701. * Reposition the item horizontally
  5702. * @Override
  5703. */
  5704. ItemRange.prototype.repositionX = function repositionX() {
  5705. var props = this.props,
  5706. parentWidth = this.parent.width,
  5707. start = this.defaultOptions.toScreen(this.data.start),
  5708. end = this.defaultOptions.toScreen(this.data.end),
  5709. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5710. contentLeft;
  5711. // limit the width of the this, as browsers cannot draw very wide divs
  5712. if (start < -parentWidth) {
  5713. start = -parentWidth;
  5714. }
  5715. if (end > 2 * parentWidth) {
  5716. end = 2 * parentWidth;
  5717. }
  5718. // when range exceeds left of the window, position the contents at the left of the visible area
  5719. if (start < 0) {
  5720. contentLeft = Math.min(-start,
  5721. (end - start - props.content.width - 2 * padding));
  5722. // TODO: remove the need for options.padding. it's terrible.
  5723. }
  5724. else {
  5725. contentLeft = 0;
  5726. }
  5727. this.left = start;
  5728. this.width = Math.max(end - start, 1);
  5729. this.dom.box.style.left = this.left + 'px';
  5730. this.dom.box.style.width = this.width + 'px';
  5731. this.dom.content.style.left = contentLeft + 'px';
  5732. };
  5733. /**
  5734. * Reposition the item vertically
  5735. * @Override
  5736. */
  5737. ItemRange.prototype.repositionY = function repositionY() {
  5738. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5739. box = this.dom.box;
  5740. if (orientation == 'top') {
  5741. box.style.top = this.top + 'px';
  5742. box.style.bottom = '';
  5743. }
  5744. else {
  5745. box.style.top = '';
  5746. box.style.bottom = this.top + 'px';
  5747. }
  5748. };
  5749. /**
  5750. * Repaint a drag area on the left side of the range when the range is selected
  5751. * @protected
  5752. */
  5753. ItemRange.prototype._repaintDragLeft = function () {
  5754. if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) {
  5755. // create and show drag area
  5756. var dragLeft = document.createElement('div');
  5757. dragLeft.className = 'drag-left';
  5758. dragLeft.dragLeftItem = this;
  5759. // TODO: this should be redundant?
  5760. Hammer(dragLeft, {
  5761. preventDefault: true
  5762. }).on('drag', function () {
  5763. //console.log('drag left')
  5764. });
  5765. this.dom.box.appendChild(dragLeft);
  5766. this.dom.dragLeft = dragLeft;
  5767. }
  5768. else if (!this.selected && this.dom.dragLeft) {
  5769. // delete drag area
  5770. if (this.dom.dragLeft.parentNode) {
  5771. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  5772. }
  5773. this.dom.dragLeft = null;
  5774. }
  5775. };
  5776. /**
  5777. * Repaint a drag area on the right side of the range when the range is selected
  5778. * @protected
  5779. */
  5780. ItemRange.prototype._repaintDragRight = function () {
  5781. if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) {
  5782. // create and show drag area
  5783. var dragRight = document.createElement('div');
  5784. dragRight.className = 'drag-right';
  5785. dragRight.dragRightItem = this;
  5786. // TODO: this should be redundant?
  5787. Hammer(dragRight, {
  5788. preventDefault: true
  5789. }).on('drag', function () {
  5790. //console.log('drag right')
  5791. });
  5792. this.dom.box.appendChild(dragRight);
  5793. this.dom.dragRight = dragRight;
  5794. }
  5795. else if (!this.selected && this.dom.dragRight) {
  5796. // delete drag area
  5797. if (this.dom.dragRight.parentNode) {
  5798. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  5799. }
  5800. this.dom.dragRight = null;
  5801. }
  5802. };
  5803. /**
  5804. * @constructor ItemRangeOverflow
  5805. * @extends ItemRange
  5806. * @param {Object} data Object containing parameters start, end
  5807. * content, className.
  5808. * @param {Object} [options] Options to set initial property values
  5809. * @param {Object} [defaultOptions] default options
  5810. * // TODO: describe available options
  5811. */
  5812. function ItemRangeOverflow (data, options, defaultOptions) {
  5813. this.props = {
  5814. content: {
  5815. left: 0,
  5816. width: 0
  5817. }
  5818. };
  5819. ItemRange.call(this, data, options, defaultOptions);
  5820. }
  5821. ItemRangeOverflow.prototype = new ItemRange (null);
  5822. ItemRangeOverflow.prototype.baseClassName = 'item rangeoverflow';
  5823. /**
  5824. * Reposition the item horizontally
  5825. * @Override
  5826. */
  5827. ItemRangeOverflow.prototype.repositionX = function repositionX() {
  5828. var parentWidth = this.parent.width,
  5829. start = this.defaultOptions.toScreen(this.data.start),
  5830. end = this.defaultOptions.toScreen(this.data.end),
  5831. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5832. contentLeft;
  5833. // limit the width of the this, as browsers cannot draw very wide divs
  5834. if (start < -parentWidth) {
  5835. start = -parentWidth;
  5836. }
  5837. if (end > 2 * parentWidth) {
  5838. end = 2 * parentWidth;
  5839. }
  5840. // when range exceeds left of the window, position the contents at the left of the visible area
  5841. contentLeft = Math.max(-start, 0);
  5842. this.left = start;
  5843. var boxWidth = Math.max(end - start, 1);
  5844. this.width = (this.props.content.width < boxWidth) ?
  5845. boxWidth :
  5846. start + contentLeft + this.props.content.width;
  5847. this.dom.box.style.left = this.left + 'px';
  5848. this.dom.box.style.width = boxWidth + 'px';
  5849. this.dom.content.style.left = contentLeft + 'px';
  5850. };
  5851. /**
  5852. * @constructor Group
  5853. * @param {Number | String} groupId
  5854. * @param {Object} data
  5855. * @param {ItemSet} itemSet
  5856. */
  5857. function Group (groupId, data, itemSet) {
  5858. this.groupId = groupId;
  5859. this.itemSet = itemSet;
  5860. this.dom = {};
  5861. this.props = {
  5862. label: {
  5863. width: 0,
  5864. height: 0
  5865. }
  5866. };
  5867. this.items = {}; // items filtered by groupId of this group
  5868. this.visibleItems = []; // items currently visible in window
  5869. this.orderedItems = { // items sorted by start and by end
  5870. byStart: [],
  5871. byEnd: []
  5872. };
  5873. this._create();
  5874. this.setData(data);
  5875. }
  5876. /**
  5877. * Create DOM elements for the group
  5878. * @private
  5879. */
  5880. Group.prototype._create = function() {
  5881. var label = document.createElement('div');
  5882. label.className = 'vlabel';
  5883. this.dom.label = label;
  5884. var inner = document.createElement('div');
  5885. inner.className = 'inner';
  5886. label.appendChild(inner);
  5887. this.dom.inner = inner;
  5888. var foreground = document.createElement('div');
  5889. foreground.className = 'group';
  5890. foreground['timeline-group'] = this;
  5891. this.dom.foreground = foreground;
  5892. this.dom.background = document.createElement('div');
  5893. this.dom.axis = document.createElement('div');
  5894. };
  5895. /**
  5896. * Set the group data for this group
  5897. * @param {Object} data Group data, can contain properties content and className
  5898. */
  5899. Group.prototype.setData = function setData(data) {
  5900. // update contents
  5901. var content = data && data.content;
  5902. if (content instanceof Element) {
  5903. this.dom.inner.appendChild(content);
  5904. }
  5905. else if (content != undefined) {
  5906. this.dom.inner.innerHTML = content;
  5907. }
  5908. else {
  5909. this.dom.inner.innerHTML = this.groupId;
  5910. }
  5911. // update className
  5912. var className = data && data.className;
  5913. if (className) {
  5914. util.addClassName(this.dom.label, className);
  5915. }
  5916. };
  5917. /**
  5918. * Get the foreground container element
  5919. * @return {HTMLElement} foreground
  5920. */
  5921. Group.prototype.getForeground = function getForeground() {
  5922. return this.dom.foreground;
  5923. };
  5924. /**
  5925. * Get the background container element
  5926. * @return {HTMLElement} background
  5927. */
  5928. Group.prototype.getBackground = function getBackground() {
  5929. return this.dom.background;
  5930. };
  5931. /**
  5932. * Get the axis container element
  5933. * @return {HTMLElement} axis
  5934. */
  5935. Group.prototype.getAxis = function getAxis() {
  5936. return this.dom.axis;
  5937. };
  5938. /**
  5939. * Get the width of the group label
  5940. * @return {number} width
  5941. */
  5942. Group.prototype.getLabelWidth = function getLabelWidth() {
  5943. return this.props.label.width;
  5944. };
  5945. /**
  5946. * Repaint this group
  5947. * @param {{start: number, end: number}} range
  5948. * @param {{item: number, axis: number}} margin
  5949. * @param {boolean} [restack=false] Force restacking of all items
  5950. * @return {boolean} Returns true if the group is resized
  5951. */
  5952. Group.prototype.repaint = function repaint(range, margin, restack) {
  5953. var resized = false;
  5954. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  5955. // reposition visible items vertically
  5956. if (this.itemSet.options.stack) { // TODO: ugly way to access options...
  5957. stack.stack(this.visibleItems, margin, restack);
  5958. }
  5959. else { // no stacking
  5960. stack.nostack(this.visibleItems, margin);
  5961. }
  5962. this.stackDirty = false;
  5963. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  5964. var item = this.visibleItems[i];
  5965. item.repositionY();
  5966. }
  5967. // recalculate the height of the group
  5968. var height;
  5969. var visibleItems = this.visibleItems;
  5970. if (visibleItems.length) {
  5971. var min = visibleItems[0].top;
  5972. var max = visibleItems[0].top + visibleItems[0].height;
  5973. util.forEach(visibleItems, function (item) {
  5974. min = Math.min(min, item.top);
  5975. max = Math.max(max, (item.top + item.height));
  5976. });
  5977. height = (max - min) + margin.axis + margin.item;
  5978. }
  5979. else {
  5980. height = margin.axis + margin.item;
  5981. }
  5982. height = Math.max(height, this.props.label.height);
  5983. // calculate actual size and position
  5984. var foreground = this.dom.foreground;
  5985. this.top = foreground.offsetTop;
  5986. this.left = foreground.offsetLeft;
  5987. this.width = foreground.offsetWidth;
  5988. resized = util.updateProperty(this, 'height', height) || resized;
  5989. // recalculate size of label
  5990. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  5991. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  5992. // apply new height
  5993. foreground.style.height = height + 'px';
  5994. this.dom.label.style.height = height + 'px';
  5995. return resized;
  5996. };
  5997. /**
  5998. * Show this group: attach to the DOM
  5999. */
  6000. Group.prototype.show = function show() {
  6001. if (!this.dom.label.parentNode) {
  6002. this.itemSet.getLabelSet().appendChild(this.dom.label);
  6003. }
  6004. if (!this.dom.foreground.parentNode) {
  6005. this.itemSet.getForeground().appendChild(this.dom.foreground);
  6006. }
  6007. if (!this.dom.background.parentNode) {
  6008. this.itemSet.getBackground().appendChild(this.dom.background);
  6009. }
  6010. if (!this.dom.axis.parentNode) {
  6011. this.itemSet.getAxis().appendChild(this.dom.axis);
  6012. }
  6013. };
  6014. /**
  6015. * Hide this group: remove from the DOM
  6016. */
  6017. Group.prototype.hide = function hide() {
  6018. var label = this.dom.label;
  6019. if (label.parentNode) {
  6020. label.parentNode.removeChild(label);
  6021. }
  6022. var foreground = this.dom.foreground;
  6023. if (foreground.parentNode) {
  6024. foreground.parentNode.removeChild(foreground);
  6025. }
  6026. var background = this.dom.background;
  6027. if (background.parentNode) {
  6028. background.parentNode.removeChild(background);
  6029. }
  6030. var axis = this.dom.axis;
  6031. if (axis.parentNode) {
  6032. axis.parentNode.removeChild(axis);
  6033. }
  6034. };
  6035. /**
  6036. * Add an item to the group
  6037. * @param {Item} item
  6038. */
  6039. Group.prototype.add = function add(item) {
  6040. this.items[item.id] = item;
  6041. item.setParent(this);
  6042. if (item instanceof ItemRange && this.visibleItems.indexOf(item) == -1) {
  6043. var range = this.itemSet.range; // TODO: not nice accessing the range like this
  6044. this._checkIfVisible(item, this.visibleItems, range);
  6045. }
  6046. };
  6047. /**
  6048. * Remove an item from the group
  6049. * @param {Item} item
  6050. */
  6051. Group.prototype.remove = function remove(item) {
  6052. delete this.items[item.id];
  6053. item.setParent(this.itemSet);
  6054. // remove from visible items
  6055. var index = this.visibleItems.indexOf(item);
  6056. if (index != -1) this.visibleItems.splice(index, 1);
  6057. // TODO: also remove from ordered items?
  6058. };
  6059. /**
  6060. * Remove an item from the corresponding DataSet
  6061. * @param {Item} item
  6062. */
  6063. Group.prototype.removeFromDataSet = function removeFromDataSet(item) {
  6064. this.itemSet.removeItem(item.id);
  6065. };
  6066. /**
  6067. * Reorder the items
  6068. */
  6069. Group.prototype.order = function order() {
  6070. var array = util.toArray(this.items);
  6071. this.orderedItems.byStart = array;
  6072. this.orderedItems.byEnd = this._constructByEndArray(array);
  6073. stack.orderByStart(this.orderedItems.byStart);
  6074. stack.orderByEnd(this.orderedItems.byEnd);
  6075. };
  6076. /**
  6077. * Create an array containing all items being a range (having an end date)
  6078. * @param {Item[]} array
  6079. * @returns {ItemRange[]}
  6080. * @private
  6081. */
  6082. Group.prototype._constructByEndArray = function _constructByEndArray(array) {
  6083. var endArray = [];
  6084. for (var i = 0; i < array.length; i++) {
  6085. if (array[i] instanceof ItemRange) {
  6086. endArray.push(array[i]);
  6087. }
  6088. }
  6089. return endArray;
  6090. };
  6091. /**
  6092. * Update the visible items
  6093. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  6094. * @param {Item[]} visibleItems The previously visible items.
  6095. * @param {{start: number, end: number}} range Visible range
  6096. * @return {Item[]} visibleItems The new visible items.
  6097. * @private
  6098. */
  6099. Group.prototype._updateVisibleItems = function _updateVisibleItems(orderedItems, visibleItems, range) {
  6100. var initialPosByStart,
  6101. newVisibleItems = [],
  6102. i;
  6103. // first check if the items that were in view previously are still in view.
  6104. // this handles the case for the ItemRange that is both before and after the current one.
  6105. if (visibleItems.length > 0) {
  6106. for (i = 0; i < visibleItems.length; i++) {
  6107. this._checkIfVisible(visibleItems[i], newVisibleItems, range);
  6108. }
  6109. }
  6110. // If there were no visible items previously, use binarySearch to find a visible ItemPoint or ItemRange (based on startTime)
  6111. if (newVisibleItems.length == 0) {
  6112. initialPosByStart = this._binarySearch(orderedItems, range, false);
  6113. }
  6114. else {
  6115. initialPosByStart = orderedItems.byStart.indexOf(newVisibleItems[0]);
  6116. }
  6117. // use visible search to find a visible ItemRange (only based on endTime)
  6118. var initialPosByEnd = this._binarySearch(orderedItems, range, true);
  6119. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  6120. if (initialPosByStart != -1) {
  6121. for (i = initialPosByStart; i >= 0; i--) {
  6122. if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;}
  6123. }
  6124. for (i = initialPosByStart + 1; i < orderedItems.byStart.length; i++) {
  6125. if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;}
  6126. }
  6127. }
  6128. // if we found a initial ID to use, trace it up and down until we meet an invisible item.
  6129. if (initialPosByEnd != -1) {
  6130. for (i = initialPosByEnd; i >= 0; i--) {
  6131. if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;}
  6132. }
  6133. for (i = initialPosByEnd + 1; i < orderedItems.byEnd.length; i++) {
  6134. if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;}
  6135. }
  6136. }
  6137. return newVisibleItems;
  6138. };
  6139. /**
  6140. * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd
  6141. * arrays. This is done by giving a boolean value true if you want to use the byEnd.
  6142. * This is done to be able to select the correct if statement (we do not want to check if an item is visible, we want to check
  6143. * if the time we selected (start or end) is within the current range).
  6144. *
  6145. * The trick is that every interval has to either enter the screen at the initial load or by dragging. The case of the ItemRange that is
  6146. * before and after the current range is handled by simply checking if it was in view before and if it is again. For all the rest,
  6147. * either the start OR end time has to be in the range.
  6148. *
  6149. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems
  6150. * @param {{start: number, end: number}} range
  6151. * @param {Boolean} byEnd
  6152. * @returns {number}
  6153. * @private
  6154. */
  6155. Group.prototype._binarySearch = function _binarySearch(orderedItems, range, byEnd) {
  6156. var array = [];
  6157. var byTime = byEnd ? 'end' : 'start';
  6158. if (byEnd == true) {array = orderedItems.byEnd; }
  6159. else {array = orderedItems.byStart;}
  6160. var interval = range.end - range.start;
  6161. var found = false;
  6162. var low = 0;
  6163. var high = array.length;
  6164. var guess = Math.floor(0.5*(high+low));
  6165. var newGuess;
  6166. if (high == 0) {guess = -1;}
  6167. else if (high == 1) {
  6168. if ((array[guess].data[byTime] > range.start - interval) && (array[guess].data[byTime] < range.end)) {
  6169. guess = 0;
  6170. }
  6171. else {
  6172. guess = -1;
  6173. }
  6174. }
  6175. else {
  6176. high -= 1;
  6177. while (found == false) {
  6178. if ((array[guess].data[byTime] > range.start - interval) && (array[guess].data[byTime] < range.end)) {
  6179. found = true;
  6180. }
  6181. else {
  6182. if (array[guess].data[byTime] < range.start - interval) { // it is too small --> increase low
  6183. low = Math.floor(0.5*(high+low));
  6184. }
  6185. else { // it is too big --> decrease high
  6186. high = Math.floor(0.5*(high+low));
  6187. }
  6188. newGuess = Math.floor(0.5*(high+low));
  6189. // not in list;
  6190. if (guess == newGuess) {
  6191. guess = -1;
  6192. found = true;
  6193. }
  6194. else {
  6195. guess = newGuess;
  6196. }
  6197. }
  6198. }
  6199. }
  6200. return guess;
  6201. };
  6202. /**
  6203. * this function checks if an item is invisible. If it is NOT we make it visible
  6204. * and add it to the global visible items. If it is, return true.
  6205. *
  6206. * @param {Item} item
  6207. * @param {Item[]} visibleItems
  6208. * @param {{start:number, end:number}} range
  6209. * @returns {boolean}
  6210. * @private
  6211. */
  6212. Group.prototype._checkIfInvisible = function _checkIfInvisible(item, visibleItems, range) {
  6213. if (item.isVisible(range)) {
  6214. if (!item.displayed) item.show();
  6215. item.repositionX();
  6216. if (visibleItems.indexOf(item) == -1) {
  6217. visibleItems.push(item);
  6218. }
  6219. return false;
  6220. }
  6221. else {
  6222. return true;
  6223. }
  6224. };
  6225. /**
  6226. * this function is very similar to the _checkIfInvisible() but it does not
  6227. * return booleans, hides the item if it should not be seen and always adds to
  6228. * the visibleItems.
  6229. * this one is for brute forcing and hiding.
  6230. *
  6231. * @param {Item} item
  6232. * @param {Array} visibleItems
  6233. * @param {{start:number, end:number}} range
  6234. * @private
  6235. */
  6236. Group.prototype._checkIfVisible = function _checkIfVisible(item, visibleItems, range) {
  6237. if (item.isVisible(range)) {
  6238. if (!item.displayed) item.show();
  6239. // reposition item horizontally
  6240. item.repositionX();
  6241. visibleItems.push(item);
  6242. }
  6243. else {
  6244. if (item.displayed) item.hide();
  6245. }
  6246. };
  6247. /**
  6248. * Create a timeline visualization
  6249. * @param {HTMLElement} container
  6250. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6251. * @param {Object} [options] See Timeline.setOptions for the available options.
  6252. * @constructor
  6253. */
  6254. function Timeline (container, items, options) {
  6255. // validate arguments
  6256. if (!container) throw new Error('No container element provided');
  6257. var me = this;
  6258. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6259. this.options = {
  6260. orientation: 'bottom',
  6261. direction: 'horizontal', // 'horizontal' or 'vertical'
  6262. autoResize: true,
  6263. stack: true,
  6264. editable: {
  6265. updateTime: false,
  6266. updateGroup: false,
  6267. add: false,
  6268. remove: false
  6269. },
  6270. selectable: true,
  6271. snap: null, // will be specified after timeaxis is created
  6272. min: null,
  6273. max: null,
  6274. zoomMin: 10, // milliseconds
  6275. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6276. // moveable: true, // TODO: option moveable
  6277. // zoomable: true, // TODO: option zoomable
  6278. showMinorLabels: true,
  6279. showMajorLabels: true,
  6280. showCurrentTime: false,
  6281. showCustomTime: false,
  6282. type: 'box',
  6283. align: 'center',
  6284. margin: {
  6285. axis: 20,
  6286. item: 10
  6287. },
  6288. padding: 5,
  6289. onAdd: function (item, callback) {
  6290. callback(item);
  6291. },
  6292. onUpdate: function (item, callback) {
  6293. callback(item);
  6294. },
  6295. onMove: function (item, callback) {
  6296. callback(item);
  6297. },
  6298. onRemove: function (item, callback) {
  6299. callback(item);
  6300. },
  6301. toScreen: me._toScreen.bind(me),
  6302. toTime: me._toTime.bind(me)
  6303. };
  6304. // root panel
  6305. var rootOptions = util.extend(Object.create(this.options), {
  6306. height: function () {
  6307. if (me.options.height) {
  6308. // fixed height
  6309. return me.options.height;
  6310. }
  6311. else {
  6312. // auto height
  6313. // TODO: implement a css based solution to automatically have the right hight
  6314. return (me.timeAxis.height + me.contentPanel.height) + 'px';
  6315. }
  6316. }
  6317. });
  6318. this.rootPanel = new RootPanel(container, rootOptions);
  6319. // single select (or unselect) when tapping an item
  6320. this.rootPanel.on('tap', this._onSelectItem.bind(this));
  6321. // multi select when holding mouse/touch, or on ctrl+click
  6322. this.rootPanel.on('hold', this._onMultiSelectItem.bind(this));
  6323. // add item on doubletap
  6324. this.rootPanel.on('doubletap', this._onAddItem.bind(this));
  6325. // side panel
  6326. var sideOptions = util.extend(Object.create(this.options), {
  6327. top: function () {
  6328. return (sideOptions.orientation == 'top') ? '0' : '';
  6329. },
  6330. bottom: function () {
  6331. return (sideOptions.orientation == 'top') ? '' : '0';
  6332. },
  6333. left: '0',
  6334. right: null,
  6335. height: '100%',
  6336. width: function () {
  6337. if (me.itemSet) {
  6338. return me.itemSet.getLabelsWidth();
  6339. }
  6340. else {
  6341. return 0;
  6342. }
  6343. },
  6344. className: function () {
  6345. return 'side' + (me.groupsData ? '' : ' hidden');
  6346. }
  6347. });
  6348. this.sidePanel = new Panel(sideOptions);
  6349. this.rootPanel.appendChild(this.sidePanel);
  6350. // main panel (contains time axis and itemsets)
  6351. var mainOptions = util.extend(Object.create(this.options), {
  6352. left: function () {
  6353. // we align left to enable a smooth resizing of the window
  6354. return me.sidePanel.width;
  6355. },
  6356. right: null,
  6357. height: '100%',
  6358. width: function () {
  6359. return me.rootPanel.width - me.sidePanel.width;
  6360. },
  6361. className: 'main'
  6362. });
  6363. this.mainPanel = new Panel(mainOptions);
  6364. this.rootPanel.appendChild(this.mainPanel);
  6365. // range
  6366. // TODO: move range inside rootPanel?
  6367. var rangeOptions = Object.create(this.options);
  6368. this.range = new Range(this.rootPanel, this.mainPanel, rangeOptions);
  6369. this.range.setRange(
  6370. now.clone().add('days', -3).valueOf(),
  6371. now.clone().add('days', 4).valueOf()
  6372. );
  6373. this.range.on('rangechange', function (properties) {
  6374. me.rootPanel.repaint();
  6375. me.emit('rangechange', properties);
  6376. });
  6377. this.range.on('rangechanged', function (properties) {
  6378. me.rootPanel.repaint();
  6379. me.emit('rangechanged', properties);
  6380. });
  6381. // panel with time axis
  6382. var timeAxisOptions = util.extend(Object.create(rootOptions), {
  6383. range: this.range,
  6384. left: null,
  6385. top: null,
  6386. width: null,
  6387. height: null
  6388. });
  6389. this.timeAxis = new TimeAxis(timeAxisOptions);
  6390. this.timeAxis.setRange(this.range);
  6391. this.options.snap = this.timeAxis.snap.bind(this.timeAxis);
  6392. this.mainPanel.appendChild(this.timeAxis);
  6393. // content panel (contains itemset(s))
  6394. var contentOptions = util.extend(Object.create(this.options), {
  6395. top: function () {
  6396. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6397. },
  6398. bottom: function () {
  6399. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6400. },
  6401. left: null,
  6402. right: null,
  6403. height: null,
  6404. width: null,
  6405. className: 'content'
  6406. });
  6407. this.contentPanel = new Panel(contentOptions);
  6408. this.mainPanel.appendChild(this.contentPanel);
  6409. // content panel (contains the vertical lines of box items)
  6410. var backgroundOptions = util.extend(Object.create(this.options), {
  6411. top: function () {
  6412. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6413. },
  6414. bottom: function () {
  6415. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6416. },
  6417. left: null,
  6418. right: null,
  6419. height: function () {
  6420. return me.contentPanel.height;
  6421. },
  6422. width: null,
  6423. className: 'background'
  6424. });
  6425. this.backgroundPanel = new Panel(backgroundOptions);
  6426. this.mainPanel.insertBefore(this.backgroundPanel, this.contentPanel);
  6427. // panel with axis holding the dots of item boxes
  6428. var axisPanelOptions = util.extend(Object.create(rootOptions), {
  6429. left: 0,
  6430. top: function () {
  6431. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6432. },
  6433. bottom: function () {
  6434. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6435. },
  6436. width: '100%',
  6437. height: 0,
  6438. className: 'axis'
  6439. });
  6440. this.axisPanel = new Panel(axisPanelOptions);
  6441. this.mainPanel.appendChild(this.axisPanel);
  6442. // content panel (contains itemset(s))
  6443. var sideContentOptions = util.extend(Object.create(this.options), {
  6444. top: function () {
  6445. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6446. },
  6447. bottom: function () {
  6448. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6449. },
  6450. left: null,
  6451. right: null,
  6452. height: null,
  6453. width: null,
  6454. className: 'side-content'
  6455. });
  6456. this.sideContentPanel = new Panel(sideContentOptions);
  6457. this.sidePanel.appendChild(this.sideContentPanel);
  6458. // current time bar
  6459. // Note: time bar will be attached in this.setOptions when selected
  6460. this.currentTime = new CurrentTime(this.range, rootOptions);
  6461. // custom time bar
  6462. // Note: time bar will be attached in this.setOptions when selected
  6463. this.customTime = new CustomTime(rootOptions);
  6464. this.customTime.on('timechange', function (time) {
  6465. me.emit('timechange', time);
  6466. });
  6467. this.customTime.on('timechanged', function (time) {
  6468. me.emit('timechanged', time);
  6469. });
  6470. // itemset containing items and groups
  6471. var itemOptions = util.extend(Object.create(this.options), {
  6472. left: null,
  6473. right: null,
  6474. top: null,
  6475. bottom: null,
  6476. width: null,
  6477. height: null
  6478. });
  6479. this.itemSet = new ItemSet(this.backgroundPanel, this.axisPanel, this.sideContentPanel, itemOptions);
  6480. this.itemSet.setRange(this.range);
  6481. this.itemSet.on('change', me.rootPanel.repaint.bind(me.rootPanel));
  6482. this.contentPanel.appendChild(this.itemSet);
  6483. this.itemsData = null; // DataSet
  6484. this.groupsData = null; // DataSet
  6485. // apply options
  6486. if (options) {
  6487. this.setOptions(options);
  6488. }
  6489. // create itemset
  6490. if (items) {
  6491. this.setItems(items);
  6492. }
  6493. }
  6494. // turn Timeline into an event emitter
  6495. Emitter(Timeline.prototype);
  6496. /**
  6497. * Set options
  6498. * @param {Object} options TODO: describe the available options
  6499. */
  6500. Timeline.prototype.setOptions = function (options) {
  6501. util.extend(this.options, options);
  6502. if ('editable' in options) {
  6503. var isBoolean = typeof options.editable === 'boolean';
  6504. this.options.editable = {
  6505. updateTime: isBoolean ? options.editable : (options.editable.updateTime || false),
  6506. updateGroup: isBoolean ? options.editable : (options.editable.updateGroup || false),
  6507. add: isBoolean ? options.editable : (options.editable.add || false),
  6508. remove: isBoolean ? options.editable : (options.editable.remove || false)
  6509. };
  6510. }
  6511. // force update of range (apply new min/max etc.)
  6512. // both start and end are optional
  6513. this.range.setRange(options.start, options.end);
  6514. if ('editable' in options || 'selectable' in options) {
  6515. if (this.options.selectable) {
  6516. // force update of selection
  6517. this.setSelection(this.getSelection());
  6518. }
  6519. else {
  6520. // remove selection
  6521. this.setSelection([]);
  6522. }
  6523. }
  6524. // force the itemSet to refresh: options like orientation and margins may be changed
  6525. this.itemSet.markDirty();
  6526. // validate the callback functions
  6527. var validateCallback = (function (fn) {
  6528. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  6529. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  6530. }
  6531. }).bind(this);
  6532. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  6533. // add/remove the current time bar
  6534. if (this.options.showCurrentTime) {
  6535. if (!this.mainPanel.hasChild(this.currentTime)) {
  6536. this.mainPanel.appendChild(this.currentTime);
  6537. this.currentTime.start();
  6538. }
  6539. }
  6540. else {
  6541. if (this.mainPanel.hasChild(this.currentTime)) {
  6542. this.currentTime.stop();
  6543. this.mainPanel.removeChild(this.currentTime);
  6544. }
  6545. }
  6546. // add/remove the custom time bar
  6547. if (this.options.showCustomTime) {
  6548. if (!this.mainPanel.hasChild(this.customTime)) {
  6549. this.mainPanel.appendChild(this.customTime);
  6550. }
  6551. }
  6552. else {
  6553. if (this.mainPanel.hasChild(this.customTime)) {
  6554. this.mainPanel.removeChild(this.customTime);
  6555. }
  6556. }
  6557. // TODO: remove deprecation error one day (deprecated since version 0.8.0)
  6558. if (options && options.order) {
  6559. throw new Error('Option order is deprecated. There is no replacement for this feature.');
  6560. }
  6561. // repaint everything
  6562. this.rootPanel.repaint();
  6563. };
  6564. /**
  6565. * Set a custom time bar
  6566. * @param {Date} time
  6567. */
  6568. Timeline.prototype.setCustomTime = function (time) {
  6569. if (!this.customTime) {
  6570. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6571. }
  6572. this.customTime.setCustomTime(time);
  6573. };
  6574. /**
  6575. * Retrieve the current custom time.
  6576. * @return {Date} customTime
  6577. */
  6578. Timeline.prototype.getCustomTime = function() {
  6579. if (!this.customTime) {
  6580. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6581. }
  6582. return this.customTime.getCustomTime();
  6583. };
  6584. /**
  6585. * Set items
  6586. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  6587. */
  6588. Timeline.prototype.setItems = function(items) {
  6589. var initialLoad = (this.itemsData == null);
  6590. // convert to type DataSet when needed
  6591. var newDataSet;
  6592. if (!items) {
  6593. newDataSet = null;
  6594. }
  6595. else if (items instanceof DataSet || items instanceof DataView) {
  6596. newDataSet = items;
  6597. }
  6598. else {
  6599. // turn an array into a dataset
  6600. newDataSet = new DataSet(items, {
  6601. convert: {
  6602. start: 'Date',
  6603. end: 'Date'
  6604. }
  6605. });
  6606. }
  6607. // set items
  6608. this.itemsData = newDataSet;
  6609. this.itemSet.setItems(newDataSet);
  6610. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6611. this.fit();
  6612. var start = (this.options.start != undefined) ? util.convert(this.options.start, 'Date') : null;
  6613. var end = (this.options.end != undefined) ? util.convert(this.options.end, 'Date') : null;
  6614. this.setWindow(start, end);
  6615. }
  6616. };
  6617. /**
  6618. * Set groups
  6619. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  6620. */
  6621. Timeline.prototype.setGroups = function setGroups(groups) {
  6622. // convert to type DataSet when needed
  6623. var newDataSet;
  6624. if (!groups) {
  6625. newDataSet = null;
  6626. }
  6627. else if (groups instanceof DataSet || groups instanceof DataView) {
  6628. newDataSet = groups;
  6629. }
  6630. else {
  6631. // turn an array into a dataset
  6632. newDataSet = new DataSet(groups);
  6633. }
  6634. this.groupsData = newDataSet;
  6635. this.itemSet.setGroups(newDataSet);
  6636. };
  6637. /**
  6638. * Set Timeline window such that it fits all items
  6639. */
  6640. Timeline.prototype.fit = function fit() {
  6641. // apply the data range as range
  6642. var dataRange = this.getItemRange();
  6643. // add 5% space on both sides
  6644. var start = dataRange.min;
  6645. var end = dataRange.max;
  6646. if (start != null && end != null) {
  6647. var interval = (end.valueOf() - start.valueOf());
  6648. if (interval <= 0) {
  6649. // prevent an empty interval
  6650. interval = 24 * 60 * 60 * 1000; // 1 day
  6651. }
  6652. start = new Date(start.valueOf() - interval * 0.05);
  6653. end = new Date(end.valueOf() + interval * 0.05);
  6654. }
  6655. // skip range set if there is no start and end date
  6656. if (start === null && end === null) {
  6657. return;
  6658. }
  6659. this.range.setRange(start, end);
  6660. };
  6661. /**
  6662. * Get the data range of the item set.
  6663. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6664. * When no minimum is found, min==null
  6665. * When no maximum is found, max==null
  6666. */
  6667. Timeline.prototype.getItemRange = function getItemRange() {
  6668. // calculate min from start filed
  6669. var itemsData = this.itemsData,
  6670. min = null,
  6671. max = null;
  6672. if (itemsData) {
  6673. // calculate the minimum value of the field 'start'
  6674. var minItem = itemsData.min('start');
  6675. min = minItem ? minItem.start.valueOf() : null;
  6676. // calculate maximum value of fields 'start' and 'end'
  6677. var maxStartItem = itemsData.max('start');
  6678. if (maxStartItem) {
  6679. max = maxStartItem.start.valueOf();
  6680. }
  6681. var maxEndItem = itemsData.max('end');
  6682. if (maxEndItem) {
  6683. if (max == null) {
  6684. max = maxEndItem.end.valueOf();
  6685. }
  6686. else {
  6687. max = Math.max(max, maxEndItem.end.valueOf());
  6688. }
  6689. }
  6690. }
  6691. return {
  6692. min: (min != null) ? new Date(min) : null,
  6693. max: (max != null) ? new Date(max) : null
  6694. };
  6695. };
  6696. /**
  6697. * Set selected items by their id. Replaces the current selection
  6698. * Unknown id's are silently ignored.
  6699. * @param {Array} [ids] An array with zero or more id's of the items to be
  6700. * selected. If ids is an empty array, all items will be
  6701. * unselected.
  6702. */
  6703. Timeline.prototype.setSelection = function setSelection (ids) {
  6704. this.itemSet.setSelection(ids);
  6705. };
  6706. /**
  6707. * Get the selected items by their id
  6708. * @return {Array} ids The ids of the selected items
  6709. */
  6710. Timeline.prototype.getSelection = function getSelection() {
  6711. return this.itemSet.getSelection();
  6712. };
  6713. /**
  6714. * Set the visible window. Both parameters are optional, you can change only
  6715. * start or only end. Syntax:
  6716. *
  6717. * TimeLine.setWindow(start, end)
  6718. * TimeLine.setWindow(range)
  6719. *
  6720. * Where start and end can be a Date, number, or string, and range is an
  6721. * object with properties start and end.
  6722. *
  6723. * @param {Date | Number | String} [start] Start date of visible window
  6724. * @param {Date | Number | String} [end] End date of visible window
  6725. */
  6726. Timeline.prototype.setWindow = function setWindow(start, end) {
  6727. if (arguments.length == 1) {
  6728. var range = arguments[0];
  6729. this.range.setRange(range.start, range.end);
  6730. }
  6731. else {
  6732. this.range.setRange(start, end);
  6733. }
  6734. };
  6735. /**
  6736. * Get the visible window
  6737. * @return {{start: Date, end: Date}} Visible range
  6738. */
  6739. Timeline.prototype.getWindow = function setWindow() {
  6740. var range = this.range.getRange();
  6741. return {
  6742. start: new Date(range.start),
  6743. end: new Date(range.end)
  6744. };
  6745. };
  6746. /**
  6747. * Handle selecting/deselecting an item when tapping it
  6748. * @param {Event} event
  6749. * @private
  6750. */
  6751. // TODO: move this function to ItemSet
  6752. Timeline.prototype._onSelectItem = function (event) {
  6753. if (!this.options.selectable) return;
  6754. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  6755. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  6756. if (ctrlKey || shiftKey) {
  6757. this._onMultiSelectItem(event);
  6758. return;
  6759. }
  6760. var oldSelection = this.getSelection();
  6761. var item = ItemSet.itemFromTarget(event);
  6762. var selection = item ? [item.id] : [];
  6763. this.setSelection(selection);
  6764. var newSelection = this.getSelection();
  6765. // if selection is changed, emit a select event
  6766. if (!util.equalArray(oldSelection, newSelection)) {
  6767. this.emit('select', {
  6768. items: this.getSelection()
  6769. });
  6770. }
  6771. event.stopPropagation();
  6772. };
  6773. /**
  6774. * Handle creation and updates of an item on double tap
  6775. * @param event
  6776. * @private
  6777. */
  6778. Timeline.prototype._onAddItem = function (event) {
  6779. if (!this.options.selectable) return;
  6780. if (!this.options.editable.add) return;
  6781. var me = this,
  6782. item = ItemSet.itemFromTarget(event);
  6783. if (item) {
  6784. // update item
  6785. // execute async handler to update the item (or cancel it)
  6786. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  6787. this.options.onUpdate(itemData, function (itemData) {
  6788. if (itemData) {
  6789. me.itemsData.update(itemData);
  6790. }
  6791. });
  6792. }
  6793. else {
  6794. // add item
  6795. var xAbs = vis.util.getAbsoluteLeft(this.contentPanel.frame);
  6796. var x = event.gesture.center.pageX - xAbs;
  6797. var newItem = {
  6798. start: this.timeAxis.snap(this._toTime(x)),
  6799. content: 'new item'
  6800. };
  6801. var id = util.randomUUID();
  6802. newItem[this.itemsData.fieldId] = id;
  6803. var group = ItemSet.groupFromTarget(event);
  6804. if (group) {
  6805. newItem.group = group.groupId;
  6806. }
  6807. // execute async handler to customize (or cancel) adding an item
  6808. this.options.onAdd(newItem, function (item) {
  6809. if (item) {
  6810. me.itemsData.add(newItem);
  6811. // TODO: need to trigger a repaint?
  6812. }
  6813. });
  6814. }
  6815. };
  6816. /**
  6817. * Handle selecting/deselecting multiple items when holding an item
  6818. * @param {Event} event
  6819. * @private
  6820. */
  6821. // TODO: move this function to ItemSet
  6822. Timeline.prototype._onMultiSelectItem = function (event) {
  6823. if (!this.options.selectable) return;
  6824. var selection,
  6825. item = ItemSet.itemFromTarget(event);
  6826. if (item) {
  6827. // multi select items
  6828. selection = this.getSelection(); // current selection
  6829. var index = selection.indexOf(item.id);
  6830. if (index == -1) {
  6831. // item is not yet selected -> select it
  6832. selection.push(item.id);
  6833. }
  6834. else {
  6835. // item is already selected -> deselect it
  6836. selection.splice(index, 1);
  6837. }
  6838. this.setSelection(selection);
  6839. this.emit('select', {
  6840. items: this.getSelection()
  6841. });
  6842. event.stopPropagation();
  6843. }
  6844. };
  6845. /**
  6846. * Convert a position on screen (pixels) to a datetime
  6847. * @param {int} x Position on the screen in pixels
  6848. * @return {Date} time The datetime the corresponds with given position x
  6849. * @private
  6850. */
  6851. Timeline.prototype._toTime = function _toTime(x) {
  6852. var conversion = this.range.conversion(this.mainPanel.width);
  6853. return new Date(x / conversion.scale + conversion.offset);
  6854. };
  6855. /**
  6856. * Convert a datetime (Date object) into a position on the screen
  6857. * @param {Date} time A date
  6858. * @return {int} x The position on the screen in pixels which corresponds
  6859. * with the given date.
  6860. * @private
  6861. */
  6862. Timeline.prototype._toScreen = function _toScreen(time) {
  6863. var conversion = this.range.conversion(this.mainPanel.width);
  6864. return (time.valueOf() - conversion.offset) * conversion.scale;
  6865. };
  6866. (function(exports) {
  6867. /**
  6868. * Parse a text source containing data in DOT language into a JSON object.
  6869. * The object contains two lists: one with nodes and one with edges.
  6870. *
  6871. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6872. *
  6873. * @param {String} data Text containing a graph in DOT-notation
  6874. * @return {Object} graph An object containing two parameters:
  6875. * {Object[]} nodes
  6876. * {Object[]} edges
  6877. */
  6878. function parseDOT (data) {
  6879. dot = data;
  6880. return parseGraph();
  6881. }
  6882. // token types enumeration
  6883. var TOKENTYPE = {
  6884. NULL : 0,
  6885. DELIMITER : 1,
  6886. IDENTIFIER: 2,
  6887. UNKNOWN : 3
  6888. };
  6889. // map with all delimiters
  6890. var DELIMITERS = {
  6891. '{': true,
  6892. '}': true,
  6893. '[': true,
  6894. ']': true,
  6895. ';': true,
  6896. '=': true,
  6897. ',': true,
  6898. '->': true,
  6899. '--': true
  6900. };
  6901. var dot = ''; // current dot file
  6902. var index = 0; // current index in dot file
  6903. var c = ''; // current token character in expr
  6904. var token = ''; // current token
  6905. var tokenType = TOKENTYPE.NULL; // type of the token
  6906. /**
  6907. * Get the first character from the dot file.
  6908. * The character is stored into the char c. If the end of the dot file is
  6909. * reached, the function puts an empty string in c.
  6910. */
  6911. function first() {
  6912. index = 0;
  6913. c = dot.charAt(0);
  6914. }
  6915. /**
  6916. * Get the next character from the dot file.
  6917. * The character is stored into the char c. If the end of the dot file is
  6918. * reached, the function puts an empty string in c.
  6919. */
  6920. function next() {
  6921. index++;
  6922. c = dot.charAt(index);
  6923. }
  6924. /**
  6925. * Preview the next character from the dot file.
  6926. * @return {String} cNext
  6927. */
  6928. function nextPreview() {
  6929. return dot.charAt(index + 1);
  6930. }
  6931. /**
  6932. * Test whether given character is alphabetic or numeric
  6933. * @param {String} c
  6934. * @return {Boolean} isAlphaNumeric
  6935. */
  6936. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  6937. function isAlphaNumeric(c) {
  6938. return regexAlphaNumeric.test(c);
  6939. }
  6940. /**
  6941. * Merge all properties of object b into object b
  6942. * @param {Object} a
  6943. * @param {Object} b
  6944. * @return {Object} a
  6945. */
  6946. function merge (a, b) {
  6947. if (!a) {
  6948. a = {};
  6949. }
  6950. if (b) {
  6951. for (var name in b) {
  6952. if (b.hasOwnProperty(name)) {
  6953. a[name] = b[name];
  6954. }
  6955. }
  6956. }
  6957. return a;
  6958. }
  6959. /**
  6960. * Set a value in an object, where the provided parameter name can be a
  6961. * path with nested parameters. For example:
  6962. *
  6963. * var obj = {a: 2};
  6964. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  6965. *
  6966. * @param {Object} obj
  6967. * @param {String} path A parameter name or dot-separated parameter path,
  6968. * like "color.highlight.border".
  6969. * @param {*} value
  6970. */
  6971. function setValue(obj, path, value) {
  6972. var keys = path.split('.');
  6973. var o = obj;
  6974. while (keys.length) {
  6975. var key = keys.shift();
  6976. if (keys.length) {
  6977. // this isn't the end point
  6978. if (!o[key]) {
  6979. o[key] = {};
  6980. }
  6981. o = o[key];
  6982. }
  6983. else {
  6984. // this is the end point
  6985. o[key] = value;
  6986. }
  6987. }
  6988. }
  6989. /**
  6990. * Add a node to a graph object. If there is already a node with
  6991. * the same id, their attributes will be merged.
  6992. * @param {Object} graph
  6993. * @param {Object} node
  6994. */
  6995. function addNode(graph, node) {
  6996. var i, len;
  6997. var current = null;
  6998. // find root graph (in case of subgraph)
  6999. var graphs = [graph]; // list with all graphs from current graph to root graph
  7000. var root = graph;
  7001. while (root.parent) {
  7002. graphs.push(root.parent);
  7003. root = root.parent;
  7004. }
  7005. // find existing node (at root level) by its id
  7006. if (root.nodes) {
  7007. for (i = 0, len = root.nodes.length; i < len; i++) {
  7008. if (node.id === root.nodes[i].id) {
  7009. current = root.nodes[i];
  7010. break;
  7011. }
  7012. }
  7013. }
  7014. if (!current) {
  7015. // this is a new node
  7016. current = {
  7017. id: node.id
  7018. };
  7019. if (graph.node) {
  7020. // clone default attributes
  7021. current.attr = merge(current.attr, graph.node);
  7022. }
  7023. }
  7024. // add node to this (sub)graph and all its parent graphs
  7025. for (i = graphs.length - 1; i >= 0; i--) {
  7026. var g = graphs[i];
  7027. if (!g.nodes) {
  7028. g.nodes = [];
  7029. }
  7030. if (g.nodes.indexOf(current) == -1) {
  7031. g.nodes.push(current);
  7032. }
  7033. }
  7034. // merge attributes
  7035. if (node.attr) {
  7036. current.attr = merge(current.attr, node.attr);
  7037. }
  7038. }
  7039. /**
  7040. * Add an edge to a graph object
  7041. * @param {Object} graph
  7042. * @param {Object} edge
  7043. */
  7044. function addEdge(graph, edge) {
  7045. if (!graph.edges) {
  7046. graph.edges = [];
  7047. }
  7048. graph.edges.push(edge);
  7049. if (graph.edge) {
  7050. var attr = merge({}, graph.edge); // clone default attributes
  7051. edge.attr = merge(attr, edge.attr); // merge attributes
  7052. }
  7053. }
  7054. /**
  7055. * Create an edge to a graph object
  7056. * @param {Object} graph
  7057. * @param {String | Number | Object} from
  7058. * @param {String | Number | Object} to
  7059. * @param {String} type
  7060. * @param {Object | null} attr
  7061. * @return {Object} edge
  7062. */
  7063. function createEdge(graph, from, to, type, attr) {
  7064. var edge = {
  7065. from: from,
  7066. to: to,
  7067. type: type
  7068. };
  7069. if (graph.edge) {
  7070. edge.attr = merge({}, graph.edge); // clone default attributes
  7071. }
  7072. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7073. return edge;
  7074. }
  7075. /**
  7076. * Get next token in the current dot file.
  7077. * The token and token type are available as token and tokenType
  7078. */
  7079. function getToken() {
  7080. tokenType = TOKENTYPE.NULL;
  7081. token = '';
  7082. // skip over whitespaces
  7083. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7084. next();
  7085. }
  7086. do {
  7087. var isComment = false;
  7088. // skip comment
  7089. if (c == '#') {
  7090. // find the previous non-space character
  7091. var i = index - 1;
  7092. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7093. i--;
  7094. }
  7095. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7096. // the # is at the start of a line, this is indeed a line comment
  7097. while (c != '' && c != '\n') {
  7098. next();
  7099. }
  7100. isComment = true;
  7101. }
  7102. }
  7103. if (c == '/' && nextPreview() == '/') {
  7104. // skip line comment
  7105. while (c != '' && c != '\n') {
  7106. next();
  7107. }
  7108. isComment = true;
  7109. }
  7110. if (c == '/' && nextPreview() == '*') {
  7111. // skip block comment
  7112. while (c != '') {
  7113. if (c == '*' && nextPreview() == '/') {
  7114. // end of block comment found. skip these last two characters
  7115. next();
  7116. next();
  7117. break;
  7118. }
  7119. else {
  7120. next();
  7121. }
  7122. }
  7123. isComment = true;
  7124. }
  7125. // skip over whitespaces
  7126. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7127. next();
  7128. }
  7129. }
  7130. while (isComment);
  7131. // check for end of dot file
  7132. if (c == '') {
  7133. // token is still empty
  7134. tokenType = TOKENTYPE.DELIMITER;
  7135. return;
  7136. }
  7137. // check for delimiters consisting of 2 characters
  7138. var c2 = c + nextPreview();
  7139. if (DELIMITERS[c2]) {
  7140. tokenType = TOKENTYPE.DELIMITER;
  7141. token = c2;
  7142. next();
  7143. next();
  7144. return;
  7145. }
  7146. // check for delimiters consisting of 1 character
  7147. if (DELIMITERS[c]) {
  7148. tokenType = TOKENTYPE.DELIMITER;
  7149. token = c;
  7150. next();
  7151. return;
  7152. }
  7153. // check for an identifier (number or string)
  7154. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7155. if (isAlphaNumeric(c) || c == '-') {
  7156. token += c;
  7157. next();
  7158. while (isAlphaNumeric(c)) {
  7159. token += c;
  7160. next();
  7161. }
  7162. if (token == 'false') {
  7163. token = false; // convert to boolean
  7164. }
  7165. else if (token == 'true') {
  7166. token = true; // convert to boolean
  7167. }
  7168. else if (!isNaN(Number(token))) {
  7169. token = Number(token); // convert to number
  7170. }
  7171. tokenType = TOKENTYPE.IDENTIFIER;
  7172. return;
  7173. }
  7174. // check for a string enclosed by double quotes
  7175. if (c == '"') {
  7176. next();
  7177. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7178. token += c;
  7179. if (c == '"') { // skip the escape character
  7180. next();
  7181. }
  7182. next();
  7183. }
  7184. if (c != '"') {
  7185. throw newSyntaxError('End of string " expected');
  7186. }
  7187. next();
  7188. tokenType = TOKENTYPE.IDENTIFIER;
  7189. return;
  7190. }
  7191. // something unknown is found, wrong characters, a syntax error
  7192. tokenType = TOKENTYPE.UNKNOWN;
  7193. while (c != '') {
  7194. token += c;
  7195. next();
  7196. }
  7197. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7198. }
  7199. /**
  7200. * Parse a graph.
  7201. * @returns {Object} graph
  7202. */
  7203. function parseGraph() {
  7204. var graph = {};
  7205. first();
  7206. getToken();
  7207. // optional strict keyword
  7208. if (token == 'strict') {
  7209. graph.strict = true;
  7210. getToken();
  7211. }
  7212. // graph or digraph keyword
  7213. if (token == 'graph' || token == 'digraph') {
  7214. graph.type = token;
  7215. getToken();
  7216. }
  7217. // optional graph id
  7218. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7219. graph.id = token;
  7220. getToken();
  7221. }
  7222. // open angle bracket
  7223. if (token != '{') {
  7224. throw newSyntaxError('Angle bracket { expected');
  7225. }
  7226. getToken();
  7227. // statements
  7228. parseStatements(graph);
  7229. // close angle bracket
  7230. if (token != '}') {
  7231. throw newSyntaxError('Angle bracket } expected');
  7232. }
  7233. getToken();
  7234. // end of file
  7235. if (token !== '') {
  7236. throw newSyntaxError('End of file expected');
  7237. }
  7238. getToken();
  7239. // remove temporary default properties
  7240. delete graph.node;
  7241. delete graph.edge;
  7242. delete graph.graph;
  7243. return graph;
  7244. }
  7245. /**
  7246. * Parse a list with statements.
  7247. * @param {Object} graph
  7248. */
  7249. function parseStatements (graph) {
  7250. while (token !== '' && token != '}') {
  7251. parseStatement(graph);
  7252. if (token == ';') {
  7253. getToken();
  7254. }
  7255. }
  7256. }
  7257. /**
  7258. * Parse a single statement. Can be a an attribute statement, node
  7259. * statement, a series of node statements and edge statements, or a
  7260. * parameter.
  7261. * @param {Object} graph
  7262. */
  7263. function parseStatement(graph) {
  7264. // parse subgraph
  7265. var subgraph = parseSubgraph(graph);
  7266. if (subgraph) {
  7267. // edge statements
  7268. parseEdge(graph, subgraph);
  7269. return;
  7270. }
  7271. // parse an attribute statement
  7272. var attr = parseAttributeStatement(graph);
  7273. if (attr) {
  7274. return;
  7275. }
  7276. // parse node
  7277. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7278. throw newSyntaxError('Identifier expected');
  7279. }
  7280. var id = token; // id can be a string or a number
  7281. getToken();
  7282. if (token == '=') {
  7283. // id statement
  7284. getToken();
  7285. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7286. throw newSyntaxError('Identifier expected');
  7287. }
  7288. graph[id] = token;
  7289. getToken();
  7290. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7291. }
  7292. else {
  7293. parseNodeStatement(graph, id);
  7294. }
  7295. }
  7296. /**
  7297. * Parse a subgraph
  7298. * @param {Object} graph parent graph object
  7299. * @return {Object | null} subgraph
  7300. */
  7301. function parseSubgraph (graph) {
  7302. var subgraph = null;
  7303. // optional subgraph keyword
  7304. if (token == 'subgraph') {
  7305. subgraph = {};
  7306. subgraph.type = 'subgraph';
  7307. getToken();
  7308. // optional graph id
  7309. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7310. subgraph.id = token;
  7311. getToken();
  7312. }
  7313. }
  7314. // open angle bracket
  7315. if (token == '{') {
  7316. getToken();
  7317. if (!subgraph) {
  7318. subgraph = {};
  7319. }
  7320. subgraph.parent = graph;
  7321. subgraph.node = graph.node;
  7322. subgraph.edge = graph.edge;
  7323. subgraph.graph = graph.graph;
  7324. // statements
  7325. parseStatements(subgraph);
  7326. // close angle bracket
  7327. if (token != '}') {
  7328. throw newSyntaxError('Angle bracket } expected');
  7329. }
  7330. getToken();
  7331. // remove temporary default properties
  7332. delete subgraph.node;
  7333. delete subgraph.edge;
  7334. delete subgraph.graph;
  7335. delete subgraph.parent;
  7336. // register at the parent graph
  7337. if (!graph.subgraphs) {
  7338. graph.subgraphs = [];
  7339. }
  7340. graph.subgraphs.push(subgraph);
  7341. }
  7342. return subgraph;
  7343. }
  7344. /**
  7345. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7346. * Available keywords are 'node', 'edge', 'graph'.
  7347. * The previous list with default attributes will be replaced
  7348. * @param {Object} graph
  7349. * @returns {String | null} keyword Returns the name of the parsed attribute
  7350. * (node, edge, graph), or null if nothing
  7351. * is parsed.
  7352. */
  7353. function parseAttributeStatement (graph) {
  7354. // attribute statements
  7355. if (token == 'node') {
  7356. getToken();
  7357. // node attributes
  7358. graph.node = parseAttributeList();
  7359. return 'node';
  7360. }
  7361. else if (token == 'edge') {
  7362. getToken();
  7363. // edge attributes
  7364. graph.edge = parseAttributeList();
  7365. return 'edge';
  7366. }
  7367. else if (token == 'graph') {
  7368. getToken();
  7369. // graph attributes
  7370. graph.graph = parseAttributeList();
  7371. return 'graph';
  7372. }
  7373. return null;
  7374. }
  7375. /**
  7376. * parse a node statement
  7377. * @param {Object} graph
  7378. * @param {String | Number} id
  7379. */
  7380. function parseNodeStatement(graph, id) {
  7381. // node statement
  7382. var node = {
  7383. id: id
  7384. };
  7385. var attr = parseAttributeList();
  7386. if (attr) {
  7387. node.attr = attr;
  7388. }
  7389. addNode(graph, node);
  7390. // edge statements
  7391. parseEdge(graph, id);
  7392. }
  7393. /**
  7394. * Parse an edge or a series of edges
  7395. * @param {Object} graph
  7396. * @param {String | Number} from Id of the from node
  7397. */
  7398. function parseEdge(graph, from) {
  7399. while (token == '->' || token == '--') {
  7400. var to;
  7401. var type = token;
  7402. getToken();
  7403. var subgraph = parseSubgraph(graph);
  7404. if (subgraph) {
  7405. to = subgraph;
  7406. }
  7407. else {
  7408. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7409. throw newSyntaxError('Identifier or subgraph expected');
  7410. }
  7411. to = token;
  7412. addNode(graph, {
  7413. id: to
  7414. });
  7415. getToken();
  7416. }
  7417. // parse edge attributes
  7418. var attr = parseAttributeList();
  7419. // create edge
  7420. var edge = createEdge(graph, from, to, type, attr);
  7421. addEdge(graph, edge);
  7422. from = to;
  7423. }
  7424. }
  7425. /**
  7426. * Parse a set with attributes,
  7427. * for example [label="1.000", shape=solid]
  7428. * @return {Object | null} attr
  7429. */
  7430. function parseAttributeList() {
  7431. var attr = null;
  7432. while (token == '[') {
  7433. getToken();
  7434. attr = {};
  7435. while (token !== '' && token != ']') {
  7436. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7437. throw newSyntaxError('Attribute name expected');
  7438. }
  7439. var name = token;
  7440. getToken();
  7441. if (token != '=') {
  7442. throw newSyntaxError('Equal sign = expected');
  7443. }
  7444. getToken();
  7445. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7446. throw newSyntaxError('Attribute value expected');
  7447. }
  7448. var value = token;
  7449. setValue(attr, name, value); // name can be a path
  7450. getToken();
  7451. if (token ==',') {
  7452. getToken();
  7453. }
  7454. }
  7455. if (token != ']') {
  7456. throw newSyntaxError('Bracket ] expected');
  7457. }
  7458. getToken();
  7459. }
  7460. return attr;
  7461. }
  7462. /**
  7463. * Create a syntax error with extra information on current token and index.
  7464. * @param {String} message
  7465. * @returns {SyntaxError} err
  7466. */
  7467. function newSyntaxError(message) {
  7468. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7469. }
  7470. /**
  7471. * Chop off text after a maximum length
  7472. * @param {String} text
  7473. * @param {Number} maxLength
  7474. * @returns {String}
  7475. */
  7476. function chop (text, maxLength) {
  7477. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7478. }
  7479. /**
  7480. * Execute a function fn for each pair of elements in two arrays
  7481. * @param {Array | *} array1
  7482. * @param {Array | *} array2
  7483. * @param {function} fn
  7484. */
  7485. function forEach2(array1, array2, fn) {
  7486. if (array1 instanceof Array) {
  7487. array1.forEach(function (elem1) {
  7488. if (array2 instanceof Array) {
  7489. array2.forEach(function (elem2) {
  7490. fn(elem1, elem2);
  7491. });
  7492. }
  7493. else {
  7494. fn(elem1, array2);
  7495. }
  7496. });
  7497. }
  7498. else {
  7499. if (array2 instanceof Array) {
  7500. array2.forEach(function (elem2) {
  7501. fn(array1, elem2);
  7502. });
  7503. }
  7504. else {
  7505. fn(array1, array2);
  7506. }
  7507. }
  7508. }
  7509. /**
  7510. * Convert a string containing a graph in DOT language into a map containing
  7511. * with nodes and edges in the format of graph.
  7512. * @param {String} data Text containing a graph in DOT-notation
  7513. * @return {Object} graphData
  7514. */
  7515. function DOTToGraph (data) {
  7516. // parse the DOT file
  7517. var dotData = parseDOT(data);
  7518. var graphData = {
  7519. nodes: [],
  7520. edges: [],
  7521. options: {}
  7522. };
  7523. // copy the nodes
  7524. if (dotData.nodes) {
  7525. dotData.nodes.forEach(function (dotNode) {
  7526. var graphNode = {
  7527. id: dotNode.id,
  7528. label: String(dotNode.label || dotNode.id)
  7529. };
  7530. merge(graphNode, dotNode.attr);
  7531. if (graphNode.image) {
  7532. graphNode.shape = 'image';
  7533. }
  7534. graphData.nodes.push(graphNode);
  7535. });
  7536. }
  7537. // copy the edges
  7538. if (dotData.edges) {
  7539. /**
  7540. * Convert an edge in DOT format to an edge with VisGraph format
  7541. * @param {Object} dotEdge
  7542. * @returns {Object} graphEdge
  7543. */
  7544. function convertEdge(dotEdge) {
  7545. var graphEdge = {
  7546. from: dotEdge.from,
  7547. to: dotEdge.to
  7548. };
  7549. merge(graphEdge, dotEdge.attr);
  7550. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  7551. return graphEdge;
  7552. }
  7553. dotData.edges.forEach(function (dotEdge) {
  7554. var from, to;
  7555. if (dotEdge.from instanceof Object) {
  7556. from = dotEdge.from.nodes;
  7557. }
  7558. else {
  7559. from = {
  7560. id: dotEdge.from
  7561. }
  7562. }
  7563. if (dotEdge.to instanceof Object) {
  7564. to = dotEdge.to.nodes;
  7565. }
  7566. else {
  7567. to = {
  7568. id: dotEdge.to
  7569. }
  7570. }
  7571. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  7572. dotEdge.from.edges.forEach(function (subEdge) {
  7573. var graphEdge = convertEdge(subEdge);
  7574. graphData.edges.push(graphEdge);
  7575. });
  7576. }
  7577. forEach2(from, to, function (from, to) {
  7578. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  7579. var graphEdge = convertEdge(subEdge);
  7580. graphData.edges.push(graphEdge);
  7581. });
  7582. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  7583. dotEdge.to.edges.forEach(function (subEdge) {
  7584. var graphEdge = convertEdge(subEdge);
  7585. graphData.edges.push(graphEdge);
  7586. });
  7587. }
  7588. });
  7589. }
  7590. // copy the options
  7591. if (dotData.attr) {
  7592. graphData.options = dotData.attr;
  7593. }
  7594. return graphData;
  7595. }
  7596. // exports
  7597. exports.parseDOT = parseDOT;
  7598. exports.DOTToGraph = DOTToGraph;
  7599. })(typeof util !== 'undefined' ? util : exports);
  7600. /**
  7601. * Canvas shapes used by the Graph
  7602. */
  7603. if (typeof CanvasRenderingContext2D !== 'undefined') {
  7604. /**
  7605. * Draw a circle shape
  7606. */
  7607. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  7608. this.beginPath();
  7609. this.arc(x, y, r, 0, 2*Math.PI, false);
  7610. };
  7611. /**
  7612. * Draw a square shape
  7613. * @param {Number} x horizontal center
  7614. * @param {Number} y vertical center
  7615. * @param {Number} r size, width and height of the square
  7616. */
  7617. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  7618. this.beginPath();
  7619. this.rect(x - r, y - r, r * 2, r * 2);
  7620. };
  7621. /**
  7622. * Draw a triangle shape
  7623. * @param {Number} x horizontal center
  7624. * @param {Number} y vertical center
  7625. * @param {Number} r radius, half the length of the sides of the triangle
  7626. */
  7627. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  7628. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7629. this.beginPath();
  7630. var s = r * 2;
  7631. var s2 = s / 2;
  7632. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7633. var h = Math.sqrt(s * s - s2 * s2); // height
  7634. this.moveTo(x, y - (h - ir));
  7635. this.lineTo(x + s2, y + ir);
  7636. this.lineTo(x - s2, y + ir);
  7637. this.lineTo(x, y - (h - ir));
  7638. this.closePath();
  7639. };
  7640. /**
  7641. * Draw a triangle shape in downward orientation
  7642. * @param {Number} x horizontal center
  7643. * @param {Number} y vertical center
  7644. * @param {Number} r radius
  7645. */
  7646. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  7647. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7648. this.beginPath();
  7649. var s = r * 2;
  7650. var s2 = s / 2;
  7651. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7652. var h = Math.sqrt(s * s - s2 * s2); // height
  7653. this.moveTo(x, y + (h - ir));
  7654. this.lineTo(x + s2, y - ir);
  7655. this.lineTo(x - s2, y - ir);
  7656. this.lineTo(x, y + (h - ir));
  7657. this.closePath();
  7658. };
  7659. /**
  7660. * Draw a star shape, a star with 5 points
  7661. * @param {Number} x horizontal center
  7662. * @param {Number} y vertical center
  7663. * @param {Number} r radius, half the length of the sides of the triangle
  7664. */
  7665. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  7666. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  7667. this.beginPath();
  7668. for (var n = 0; n < 10; n++) {
  7669. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  7670. this.lineTo(
  7671. x + radius * Math.sin(n * 2 * Math.PI / 10),
  7672. y - radius * Math.cos(n * 2 * Math.PI / 10)
  7673. );
  7674. }
  7675. this.closePath();
  7676. };
  7677. /**
  7678. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7679. */
  7680. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7681. var r2d = Math.PI/180;
  7682. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7683. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7684. this.beginPath();
  7685. this.moveTo(x+r,y);
  7686. this.lineTo(x+w-r,y);
  7687. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7688. this.lineTo(x+w,y+h-r);
  7689. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7690. this.lineTo(x+r,y+h);
  7691. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7692. this.lineTo(x,y+r);
  7693. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7694. };
  7695. /**
  7696. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7697. */
  7698. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7699. var kappa = .5522848,
  7700. ox = (w / 2) * kappa, // control point offset horizontal
  7701. oy = (h / 2) * kappa, // control point offset vertical
  7702. xe = x + w, // x-end
  7703. ye = y + h, // y-end
  7704. xm = x + w / 2, // x-middle
  7705. ym = y + h / 2; // y-middle
  7706. this.beginPath();
  7707. this.moveTo(x, ym);
  7708. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7709. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7710. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7711. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7712. };
  7713. /**
  7714. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7715. */
  7716. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7717. var f = 1/3;
  7718. var wEllipse = w;
  7719. var hEllipse = h * f;
  7720. var kappa = .5522848,
  7721. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7722. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7723. xe = x + wEllipse, // x-end
  7724. ye = y + hEllipse, // y-end
  7725. xm = x + wEllipse / 2, // x-middle
  7726. ym = y + hEllipse / 2, // y-middle
  7727. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7728. yeb = y + h; // y-end, bottom ellipse
  7729. this.beginPath();
  7730. this.moveTo(xe, ym);
  7731. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7732. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7733. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7734. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7735. this.lineTo(xe, ymb);
  7736. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7737. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7738. this.lineTo(x, ym);
  7739. };
  7740. /**
  7741. * Draw an arrow point (no line)
  7742. */
  7743. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  7744. // tail
  7745. var xt = x - length * Math.cos(angle);
  7746. var yt = y - length * Math.sin(angle);
  7747. // inner tail
  7748. // TODO: allow to customize different shapes
  7749. var xi = x - length * 0.9 * Math.cos(angle);
  7750. var yi = y - length * 0.9 * Math.sin(angle);
  7751. // left
  7752. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  7753. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  7754. // right
  7755. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  7756. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  7757. this.beginPath();
  7758. this.moveTo(x, y);
  7759. this.lineTo(xl, yl);
  7760. this.lineTo(xi, yi);
  7761. this.lineTo(xr, yr);
  7762. this.closePath();
  7763. };
  7764. /**
  7765. * Sets up the dashedLine functionality for drawing
  7766. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  7767. * @author David Jordan
  7768. * @date 2012-08-08
  7769. */
  7770. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  7771. if (!dashArray) dashArray=[10,5];
  7772. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  7773. var dashCount = dashArray.length;
  7774. this.moveTo(x, y);
  7775. var dx = (x2-x), dy = (y2-y);
  7776. var slope = dy/dx;
  7777. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  7778. var dashIndex=0, draw=true;
  7779. while (distRemaining>=0.1){
  7780. var dashLength = dashArray[dashIndex++%dashCount];
  7781. if (dashLength > distRemaining) dashLength = distRemaining;
  7782. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  7783. if (dx<0) xStep = -xStep;
  7784. x += xStep;
  7785. y += slope*xStep;
  7786. this[draw ? 'lineTo' : 'moveTo'](x,y);
  7787. distRemaining -= dashLength;
  7788. draw = !draw;
  7789. }
  7790. };
  7791. // TODO: add diamond shape
  7792. }
  7793. /**
  7794. * @class Node
  7795. * A node. A node can be connected to other nodes via one or multiple edges.
  7796. * @param {object} properties An object containing properties for the node. All
  7797. * properties are optional, except for the id.
  7798. * {number} id Id of the node. Required
  7799. * {string} label Text label for the node
  7800. * {number} x Horizontal position of the node
  7801. * {number} y Vertical position of the node
  7802. * {string} shape Node shape, available:
  7803. * "database", "circle", "ellipse",
  7804. * "box", "image", "text", "dot",
  7805. * "star", "triangle", "triangleDown",
  7806. * "square"
  7807. * {string} image An image url
  7808. * {string} title An title text, can be HTML
  7809. * {anytype} group A group name or number
  7810. * @param {Graph.Images} imagelist A list with images. Only needed
  7811. * when the node has an image
  7812. * @param {Graph.Groups} grouplist A list with groups. Needed for
  7813. * retrieving group properties
  7814. * @param {Object} constants An object with default values for
  7815. * example for the color
  7816. *
  7817. */
  7818. function Node(properties, imagelist, grouplist, constants) {
  7819. this.selected = false;
  7820. this.edges = []; // all edges connected to this node
  7821. this.dynamicEdges = [];
  7822. this.reroutedEdges = {};
  7823. this.group = constants.nodes.group;
  7824. this.fontSize = constants.nodes.fontSize;
  7825. this.fontFace = constants.nodes.fontFace;
  7826. this.fontColor = constants.nodes.fontColor;
  7827. this.fontDrawThreshold = 3;
  7828. this.color = constants.nodes.color;
  7829. // set defaults for the properties
  7830. this.id = undefined;
  7831. this.shape = constants.nodes.shape;
  7832. this.image = constants.nodes.image;
  7833. this.x = null;
  7834. this.y = null;
  7835. this.xFixed = false;
  7836. this.yFixed = false;
  7837. this.horizontalAlignLeft = true; // these are for the navigation controls
  7838. this.verticalAlignTop = true; // these are for the navigation controls
  7839. this.radius = constants.nodes.radius;
  7840. this.baseRadiusValue = constants.nodes.radius;
  7841. this.radiusFixed = false;
  7842. this.radiusMin = constants.nodes.radiusMin;
  7843. this.radiusMax = constants.nodes.radiusMax;
  7844. this.level = -1;
  7845. this.preassignedLevel = false;
  7846. this.imagelist = imagelist;
  7847. this.grouplist = grouplist;
  7848. // physics properties
  7849. this.fx = 0.0; // external force x
  7850. this.fy = 0.0; // external force y
  7851. this.vx = 0.0; // velocity x
  7852. this.vy = 0.0; // velocity y
  7853. this.minForce = constants.minForce;
  7854. this.damping = constants.physics.damping;
  7855. this.mass = 1; // kg
  7856. this.fixedData = {x:null,y:null};
  7857. this.setProperties(properties, constants);
  7858. // creating the variables for clustering
  7859. this.resetCluster();
  7860. this.dynamicEdgesLength = 0;
  7861. this.clusterSession = 0;
  7862. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  7863. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  7864. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  7865. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  7866. this.growthIndicator = 0;
  7867. // variables to tell the node about the graph.
  7868. this.graphScaleInv = 1;
  7869. this.graphScale = 1;
  7870. this.canvasTopLeft = {"x": -300, "y": -300};
  7871. this.canvasBottomRight = {"x": 300, "y": 300};
  7872. this.parentEdgeId = null;
  7873. }
  7874. /**
  7875. * (re)setting the clustering variables and objects
  7876. */
  7877. Node.prototype.resetCluster = function() {
  7878. // clustering variables
  7879. this.formationScale = undefined; // this is used to determine when to open the cluster
  7880. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  7881. this.containedNodes = {};
  7882. this.containedEdges = {};
  7883. this.clusterSessions = [];
  7884. };
  7885. /**
  7886. * Attach a edge to the node
  7887. * @param {Edge} edge
  7888. */
  7889. Node.prototype.attachEdge = function(edge) {
  7890. if (this.edges.indexOf(edge) == -1) {
  7891. this.edges.push(edge);
  7892. }
  7893. if (this.dynamicEdges.indexOf(edge) == -1) {
  7894. this.dynamicEdges.push(edge);
  7895. }
  7896. this.dynamicEdgesLength = this.dynamicEdges.length;
  7897. };
  7898. /**
  7899. * Detach a edge from the node
  7900. * @param {Edge} edge
  7901. */
  7902. Node.prototype.detachEdge = function(edge) {
  7903. var index = this.edges.indexOf(edge);
  7904. if (index != -1) {
  7905. this.edges.splice(index, 1);
  7906. this.dynamicEdges.splice(index, 1);
  7907. }
  7908. this.dynamicEdgesLength = this.dynamicEdges.length;
  7909. };
  7910. /**
  7911. * Set or overwrite properties for the node
  7912. * @param {Object} properties an object with properties
  7913. * @param {Object} constants and object with default, global properties
  7914. */
  7915. Node.prototype.setProperties = function(properties, constants) {
  7916. if (!properties) {
  7917. return;
  7918. }
  7919. this.originalLabel = undefined;
  7920. // basic properties
  7921. if (properties.id !== undefined) {this.id = properties.id;}
  7922. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  7923. if (properties.title !== undefined) {this.title = properties.title;}
  7924. if (properties.group !== undefined) {this.group = properties.group;}
  7925. if (properties.x !== undefined) {this.x = properties.x;}
  7926. if (properties.y !== undefined) {this.y = properties.y;}
  7927. if (properties.value !== undefined) {this.value = properties.value;}
  7928. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  7929. // physics
  7930. if (properties.mass !== undefined) {this.mass = properties.mass;}
  7931. // navigation controls properties
  7932. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  7933. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  7934. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  7935. if (this.id === undefined) {
  7936. throw "Node must have an id";
  7937. }
  7938. // copy group properties
  7939. if (this.group) {
  7940. var groupObj = this.grouplist.get(this.group);
  7941. for (var prop in groupObj) {
  7942. if (groupObj.hasOwnProperty(prop)) {
  7943. this[prop] = groupObj[prop];
  7944. }
  7945. }
  7946. }
  7947. // individual shape properties
  7948. if (properties.shape !== undefined) {this.shape = properties.shape;}
  7949. if (properties.image !== undefined) {this.image = properties.image;}
  7950. if (properties.radius !== undefined) {this.radius = properties.radius;}
  7951. if (properties.color !== undefined) {this.color = util.parseColor(properties.color);}
  7952. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  7953. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  7954. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  7955. if (this.image !== undefined && this.image != "") {
  7956. if (this.imagelist) {
  7957. this.imageObj = this.imagelist.load(this.image);
  7958. }
  7959. else {
  7960. throw "No imagelist provided";
  7961. }
  7962. }
  7963. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX);
  7964. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  7965. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  7966. if (this.shape == 'image') {
  7967. this.radiusMin = constants.nodes.widthMin;
  7968. this.radiusMax = constants.nodes.widthMax;
  7969. }
  7970. // choose draw method depending on the shape
  7971. switch (this.shape) {
  7972. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  7973. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  7974. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  7975. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7976. // TODO: add diamond shape
  7977. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  7978. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  7979. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  7980. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  7981. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  7982. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  7983. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  7984. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7985. }
  7986. // reset the size of the node, this can be changed
  7987. this._reset();
  7988. };
  7989. /**
  7990. * select this node
  7991. */
  7992. Node.prototype.select = function() {
  7993. this.selected = true;
  7994. this._reset();
  7995. };
  7996. /**
  7997. * unselect this node
  7998. */
  7999. Node.prototype.unselect = function() {
  8000. this.selected = false;
  8001. this._reset();
  8002. };
  8003. /**
  8004. * Reset the calculated size of the node, forces it to recalculate its size
  8005. */
  8006. Node.prototype.clearSizeCache = function() {
  8007. this._reset();
  8008. };
  8009. /**
  8010. * Reset the calculated size of the node, forces it to recalculate its size
  8011. * @private
  8012. */
  8013. Node.prototype._reset = function() {
  8014. this.width = undefined;
  8015. this.height = undefined;
  8016. };
  8017. /**
  8018. * get the title of this node.
  8019. * @return {string} title The title of the node, or undefined when no title
  8020. * has been set.
  8021. */
  8022. Node.prototype.getTitle = function() {
  8023. return typeof this.title === "function" ? this.title() : this.title;
  8024. };
  8025. /**
  8026. * Calculate the distance to the border of the Node
  8027. * @param {CanvasRenderingContext2D} ctx
  8028. * @param {Number} angle Angle in radians
  8029. * @returns {number} distance Distance to the border in pixels
  8030. */
  8031. Node.prototype.distanceToBorder = function (ctx, angle) {
  8032. var borderWidth = 1;
  8033. if (!this.width) {
  8034. this.resize(ctx);
  8035. }
  8036. switch (this.shape) {
  8037. case 'circle':
  8038. case 'dot':
  8039. return this.radius + borderWidth;
  8040. case 'ellipse':
  8041. var a = this.width / 2;
  8042. var b = this.height / 2;
  8043. var w = (Math.sin(angle) * a);
  8044. var h = (Math.cos(angle) * b);
  8045. return a * b / Math.sqrt(w * w + h * h);
  8046. // TODO: implement distanceToBorder for database
  8047. // TODO: implement distanceToBorder for triangle
  8048. // TODO: implement distanceToBorder for triangleDown
  8049. case 'box':
  8050. case 'image':
  8051. case 'text':
  8052. default:
  8053. if (this.width) {
  8054. return Math.min(
  8055. Math.abs(this.width / 2 / Math.cos(angle)),
  8056. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8057. // TODO: reckon with border radius too in case of box
  8058. }
  8059. else {
  8060. return 0;
  8061. }
  8062. }
  8063. // TODO: implement calculation of distance to border for all shapes
  8064. };
  8065. /**
  8066. * Set forces acting on the node
  8067. * @param {number} fx Force in horizontal direction
  8068. * @param {number} fy Force in vertical direction
  8069. */
  8070. Node.prototype._setForce = function(fx, fy) {
  8071. this.fx = fx;
  8072. this.fy = fy;
  8073. };
  8074. /**
  8075. * Add forces acting on the node
  8076. * @param {number} fx Force in horizontal direction
  8077. * @param {number} fy Force in vertical direction
  8078. * @private
  8079. */
  8080. Node.prototype._addForce = function(fx, fy) {
  8081. this.fx += fx;
  8082. this.fy += fy;
  8083. };
  8084. /**
  8085. * Perform one discrete step for the node
  8086. * @param {number} interval Time interval in seconds
  8087. */
  8088. Node.prototype.discreteStep = function(interval) {
  8089. if (!this.xFixed) {
  8090. var dx = this.damping * this.vx; // damping force
  8091. var ax = (this.fx - dx) / this.mass; // acceleration
  8092. this.vx += ax * interval; // velocity
  8093. this.x += this.vx * interval; // position
  8094. }
  8095. if (!this.yFixed) {
  8096. var dy = this.damping * this.vy; // damping force
  8097. var ay = (this.fy - dy) / this.mass; // acceleration
  8098. this.vy += ay * interval; // velocity
  8099. this.y += this.vy * interval; // position
  8100. }
  8101. };
  8102. /**
  8103. * Perform one discrete step for the node
  8104. * @param {number} interval Time interval in seconds
  8105. * @param {number} maxVelocity The speed limit imposed on the velocity
  8106. */
  8107. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8108. if (!this.xFixed) {
  8109. var dx = this.damping * this.vx; // damping force
  8110. var ax = (this.fx - dx) / this.mass; // acceleration
  8111. this.vx += ax * interval; // velocity
  8112. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8113. this.x += this.vx * interval; // position
  8114. }
  8115. else {
  8116. this.fx = 0;
  8117. }
  8118. if (!this.yFixed) {
  8119. var dy = this.damping * this.vy; // damping force
  8120. var ay = (this.fy - dy) / this.mass; // acceleration
  8121. this.vy += ay * interval; // velocity
  8122. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8123. this.y += this.vy * interval; // position
  8124. }
  8125. else {
  8126. this.fy = 0;
  8127. }
  8128. };
  8129. /**
  8130. * Check if this node has a fixed x and y position
  8131. * @return {boolean} true if fixed, false if not
  8132. */
  8133. Node.prototype.isFixed = function() {
  8134. return (this.xFixed && this.yFixed);
  8135. };
  8136. /**
  8137. * Check if this node is moving
  8138. * @param {number} vmin the minimum velocity considered as "moving"
  8139. * @return {boolean} true if moving, false if it has no velocity
  8140. */
  8141. // TODO: replace this method with calculating the kinetic energy
  8142. Node.prototype.isMoving = function(vmin) {
  8143. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8144. };
  8145. /**
  8146. * check if this node is selecte
  8147. * @return {boolean} selected True if node is selected, else false
  8148. */
  8149. Node.prototype.isSelected = function() {
  8150. return this.selected;
  8151. };
  8152. /**
  8153. * Retrieve the value of the node. Can be undefined
  8154. * @return {Number} value
  8155. */
  8156. Node.prototype.getValue = function() {
  8157. return this.value;
  8158. };
  8159. /**
  8160. * Calculate the distance from the nodes location to the given location (x,y)
  8161. * @param {Number} x
  8162. * @param {Number} y
  8163. * @return {Number} value
  8164. */
  8165. Node.prototype.getDistance = function(x, y) {
  8166. var dx = this.x - x,
  8167. dy = this.y - y;
  8168. return Math.sqrt(dx * dx + dy * dy);
  8169. };
  8170. /**
  8171. * Adjust the value range of the node. The node will adjust it's radius
  8172. * based on its value.
  8173. * @param {Number} min
  8174. * @param {Number} max
  8175. */
  8176. Node.prototype.setValueRange = function(min, max) {
  8177. if (!this.radiusFixed && this.value !== undefined) {
  8178. if (max == min) {
  8179. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8180. }
  8181. else {
  8182. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8183. this.radius = (this.value - min) * scale + this.radiusMin;
  8184. }
  8185. }
  8186. this.baseRadiusValue = this.radius;
  8187. };
  8188. /**
  8189. * Draw this node in the given canvas
  8190. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8191. * @param {CanvasRenderingContext2D} ctx
  8192. */
  8193. Node.prototype.draw = function(ctx) {
  8194. throw "Draw method not initialized for node";
  8195. };
  8196. /**
  8197. * Recalculate the size of this node in the given canvas
  8198. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8199. * @param {CanvasRenderingContext2D} ctx
  8200. */
  8201. Node.prototype.resize = function(ctx) {
  8202. throw "Resize method not initialized for node";
  8203. };
  8204. /**
  8205. * Check if this object is overlapping with the provided object
  8206. * @param {Object} obj an object with parameters left, top, right, bottom
  8207. * @return {boolean} True if location is located on node
  8208. */
  8209. Node.prototype.isOverlappingWith = function(obj) {
  8210. return (this.left < obj.right &&
  8211. this.left + this.width > obj.left &&
  8212. this.top < obj.bottom &&
  8213. this.top + this.height > obj.top);
  8214. };
  8215. Node.prototype._resizeImage = function (ctx) {
  8216. // TODO: pre calculate the image size
  8217. if (!this.width || !this.height) { // undefined or 0
  8218. var width, height;
  8219. if (this.value) {
  8220. this.radius = this.baseRadiusValue;
  8221. var scale = this.imageObj.height / this.imageObj.width;
  8222. if (scale !== undefined) {
  8223. width = this.radius || this.imageObj.width;
  8224. height = this.radius * scale || this.imageObj.height;
  8225. }
  8226. else {
  8227. width = 0;
  8228. height = 0;
  8229. }
  8230. }
  8231. else {
  8232. width = this.imageObj.width;
  8233. height = this.imageObj.height;
  8234. }
  8235. this.width = width;
  8236. this.height = height;
  8237. this.growthIndicator = 0;
  8238. if (this.width > 0 && this.height > 0) {
  8239. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8240. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8241. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8242. this.growthIndicator = this.width - width;
  8243. }
  8244. }
  8245. };
  8246. Node.prototype._drawImage = function (ctx) {
  8247. this._resizeImage(ctx);
  8248. this.left = this.x - this.width / 2;
  8249. this.top = this.y - this.height / 2;
  8250. var yLabel;
  8251. if (this.imageObj.width != 0 ) {
  8252. // draw the shade
  8253. if (this.clusterSize > 1) {
  8254. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8255. lineWidth *= this.graphScaleInv;
  8256. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8257. ctx.globalAlpha = 0.5;
  8258. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8259. }
  8260. // draw the image
  8261. ctx.globalAlpha = 1.0;
  8262. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8263. yLabel = this.y + this.height / 2;
  8264. }
  8265. else {
  8266. // image still loading... just draw the label for now
  8267. yLabel = this.y;
  8268. }
  8269. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8270. };
  8271. Node.prototype._resizeBox = function (ctx) {
  8272. if (!this.width) {
  8273. var margin = 5;
  8274. var textSize = this.getTextSize(ctx);
  8275. this.width = textSize.width + 2 * margin;
  8276. this.height = textSize.height + 2 * margin;
  8277. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8278. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8279. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8280. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8281. }
  8282. };
  8283. Node.prototype._drawBox = function (ctx) {
  8284. this._resizeBox(ctx);
  8285. this.left = this.x - this.width / 2;
  8286. this.top = this.y - this.height / 2;
  8287. var clusterLineWidth = 2.5;
  8288. var selectionLineWidth = 2;
  8289. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8290. // draw the outer border
  8291. if (this.clusterSize > 1) {
  8292. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8293. ctx.lineWidth *= this.graphScaleInv;
  8294. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8295. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8296. ctx.stroke();
  8297. }
  8298. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8299. ctx.lineWidth *= this.graphScaleInv;
  8300. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8301. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8302. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8303. ctx.fill();
  8304. ctx.stroke();
  8305. this._label(ctx, this.label, this.x, this.y);
  8306. };
  8307. Node.prototype._resizeDatabase = function (ctx) {
  8308. if (!this.width) {
  8309. var margin = 5;
  8310. var textSize = this.getTextSize(ctx);
  8311. var size = textSize.width + 2 * margin;
  8312. this.width = size;
  8313. this.height = size;
  8314. // scaling used for clustering
  8315. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8316. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8317. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8318. this.growthIndicator = this.width - size;
  8319. }
  8320. };
  8321. Node.prototype._drawDatabase = function (ctx) {
  8322. this._resizeDatabase(ctx);
  8323. this.left = this.x - this.width / 2;
  8324. this.top = this.y - this.height / 2;
  8325. var clusterLineWidth = 2.5;
  8326. var selectionLineWidth = 2;
  8327. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8328. // draw the outer border
  8329. if (this.clusterSize > 1) {
  8330. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8331. ctx.lineWidth *= this.graphScaleInv;
  8332. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8333. 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);
  8334. ctx.stroke();
  8335. }
  8336. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8337. ctx.lineWidth *= this.graphScaleInv;
  8338. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8339. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8340. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8341. ctx.fill();
  8342. ctx.stroke();
  8343. this._label(ctx, this.label, this.x, this.y);
  8344. };
  8345. Node.prototype._resizeCircle = function (ctx) {
  8346. if (!this.width) {
  8347. var margin = 5;
  8348. var textSize = this.getTextSize(ctx);
  8349. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8350. this.radius = diameter / 2;
  8351. this.width = diameter;
  8352. this.height = diameter;
  8353. // scaling used for clustering
  8354. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8355. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8356. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8357. this.growthIndicator = this.radius - 0.5*diameter;
  8358. }
  8359. };
  8360. Node.prototype._drawCircle = function (ctx) {
  8361. this._resizeCircle(ctx);
  8362. this.left = this.x - this.width / 2;
  8363. this.top = this.y - this.height / 2;
  8364. var clusterLineWidth = 2.5;
  8365. var selectionLineWidth = 2;
  8366. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8367. // draw the outer border
  8368. if (this.clusterSize > 1) {
  8369. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8370. ctx.lineWidth *= this.graphScaleInv;
  8371. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8372. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8373. ctx.stroke();
  8374. }
  8375. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8376. ctx.lineWidth *= this.graphScaleInv;
  8377. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8378. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8379. ctx.circle(this.x, this.y, this.radius);
  8380. ctx.fill();
  8381. ctx.stroke();
  8382. this._label(ctx, this.label, this.x, this.y);
  8383. };
  8384. Node.prototype._resizeEllipse = function (ctx) {
  8385. if (!this.width) {
  8386. var textSize = this.getTextSize(ctx);
  8387. this.width = textSize.width * 1.5;
  8388. this.height = textSize.height * 2;
  8389. if (this.width < this.height) {
  8390. this.width = this.height;
  8391. }
  8392. var defaultSize = this.width;
  8393. // scaling used for clustering
  8394. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8395. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8396. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8397. this.growthIndicator = this.width - defaultSize;
  8398. }
  8399. };
  8400. Node.prototype._drawEllipse = function (ctx) {
  8401. this._resizeEllipse(ctx);
  8402. this.left = this.x - this.width / 2;
  8403. this.top = this.y - this.height / 2;
  8404. var clusterLineWidth = 2.5;
  8405. var selectionLineWidth = 2;
  8406. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8407. // draw the outer border
  8408. if (this.clusterSize > 1) {
  8409. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8410. ctx.lineWidth *= this.graphScaleInv;
  8411. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8412. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8413. ctx.stroke();
  8414. }
  8415. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8416. ctx.lineWidth *= this.graphScaleInv;
  8417. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8418. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8419. ctx.ellipse(this.left, this.top, this.width, this.height);
  8420. ctx.fill();
  8421. ctx.stroke();
  8422. this._label(ctx, this.label, this.x, this.y);
  8423. };
  8424. Node.prototype._drawDot = function (ctx) {
  8425. this._drawShape(ctx, 'circle');
  8426. };
  8427. Node.prototype._drawTriangle = function (ctx) {
  8428. this._drawShape(ctx, 'triangle');
  8429. };
  8430. Node.prototype._drawTriangleDown = function (ctx) {
  8431. this._drawShape(ctx, 'triangleDown');
  8432. };
  8433. Node.prototype._drawSquare = function (ctx) {
  8434. this._drawShape(ctx, 'square');
  8435. };
  8436. Node.prototype._drawStar = function (ctx) {
  8437. this._drawShape(ctx, 'star');
  8438. };
  8439. Node.prototype._resizeShape = function (ctx) {
  8440. if (!this.width) {
  8441. this.radius = this.baseRadiusValue;
  8442. var size = 2 * this.radius;
  8443. this.width = size;
  8444. this.height = size;
  8445. // scaling used for clustering
  8446. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8447. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8448. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8449. this.growthIndicator = this.width - size;
  8450. }
  8451. };
  8452. Node.prototype._drawShape = function (ctx, shape) {
  8453. this._resizeShape(ctx);
  8454. this.left = this.x - this.width / 2;
  8455. this.top = this.y - this.height / 2;
  8456. var clusterLineWidth = 2.5;
  8457. var selectionLineWidth = 2;
  8458. var radiusMultiplier = 2;
  8459. // choose draw method depending on the shape
  8460. switch (shape) {
  8461. case 'dot': radiusMultiplier = 2; break;
  8462. case 'square': radiusMultiplier = 2; break;
  8463. case 'triangle': radiusMultiplier = 3; break;
  8464. case 'triangleDown': radiusMultiplier = 3; break;
  8465. case 'star': radiusMultiplier = 4; break;
  8466. }
  8467. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8468. // draw the outer border
  8469. if (this.clusterSize > 1) {
  8470. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8471. ctx.lineWidth *= this.graphScaleInv;
  8472. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8473. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8474. ctx.stroke();
  8475. }
  8476. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8477. ctx.lineWidth *= this.graphScaleInv;
  8478. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8479. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8480. ctx[shape](this.x, this.y, this.radius);
  8481. ctx.fill();
  8482. ctx.stroke();
  8483. if (this.label) {
  8484. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8485. }
  8486. };
  8487. Node.prototype._resizeText = function (ctx) {
  8488. if (!this.width) {
  8489. var margin = 5;
  8490. var textSize = this.getTextSize(ctx);
  8491. this.width = textSize.width + 2 * margin;
  8492. this.height = textSize.height + 2 * margin;
  8493. // scaling used for clustering
  8494. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8495. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8496. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8497. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8498. }
  8499. };
  8500. Node.prototype._drawText = function (ctx) {
  8501. this._resizeText(ctx);
  8502. this.left = this.x - this.width / 2;
  8503. this.top = this.y - this.height / 2;
  8504. this._label(ctx, this.label, this.x, this.y);
  8505. };
  8506. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  8507. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  8508. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8509. ctx.fillStyle = this.fontColor || "black";
  8510. ctx.textAlign = align || "center";
  8511. ctx.textBaseline = baseline || "middle";
  8512. var lines = text.split('\n'),
  8513. lineCount = lines.length,
  8514. fontSize = (this.fontSize + 4),
  8515. yLine = y + (1 - lineCount) / 2 * fontSize;
  8516. for (var i = 0; i < lineCount; i++) {
  8517. ctx.fillText(lines[i], x, yLine);
  8518. yLine += fontSize;
  8519. }
  8520. }
  8521. };
  8522. Node.prototype.getTextSize = function(ctx) {
  8523. if (this.label !== undefined) {
  8524. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8525. var lines = this.label.split('\n'),
  8526. height = (this.fontSize + 4) * lines.length,
  8527. width = 0;
  8528. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  8529. width = Math.max(width, ctx.measureText(lines[i]).width);
  8530. }
  8531. return {"width": width, "height": height};
  8532. }
  8533. else {
  8534. return {"width": 0, "height": 0};
  8535. }
  8536. };
  8537. /**
  8538. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  8539. * there is a safety margin of 0.3 * width;
  8540. *
  8541. * @returns {boolean}
  8542. */
  8543. Node.prototype.inArea = function() {
  8544. if (this.width !== undefined) {
  8545. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  8546. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  8547. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  8548. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  8549. }
  8550. else {
  8551. return true;
  8552. }
  8553. };
  8554. /**
  8555. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  8556. * @returns {boolean}
  8557. */
  8558. Node.prototype.inView = function() {
  8559. return (this.x >= this.canvasTopLeft.x &&
  8560. this.x < this.canvasBottomRight.x &&
  8561. this.y >= this.canvasTopLeft.y &&
  8562. this.y < this.canvasBottomRight.y);
  8563. };
  8564. /**
  8565. * This allows the zoom level of the graph to influence the rendering
  8566. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  8567. *
  8568. * @param scale
  8569. * @param canvasTopLeft
  8570. * @param canvasBottomRight
  8571. */
  8572. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  8573. this.graphScaleInv = 1.0/scale;
  8574. this.graphScale = scale;
  8575. this.canvasTopLeft = canvasTopLeft;
  8576. this.canvasBottomRight = canvasBottomRight;
  8577. };
  8578. /**
  8579. * This allows the zoom level of the graph to influence the rendering
  8580. *
  8581. * @param scale
  8582. */
  8583. Node.prototype.setScale = function(scale) {
  8584. this.graphScaleInv = 1.0/scale;
  8585. this.graphScale = scale;
  8586. };
  8587. /**
  8588. * set the velocity at 0. Is called when this node is contained in another during clustering
  8589. */
  8590. Node.prototype.clearVelocity = function() {
  8591. this.vx = 0;
  8592. this.vy = 0;
  8593. };
  8594. /**
  8595. * Basic preservation of (kinectic) energy
  8596. *
  8597. * @param massBeforeClustering
  8598. */
  8599. Node.prototype.updateVelocity = function(massBeforeClustering) {
  8600. var energyBefore = this.vx * this.vx * massBeforeClustering;
  8601. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8602. this.vx = Math.sqrt(energyBefore/this.mass);
  8603. energyBefore = this.vy * this.vy * massBeforeClustering;
  8604. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8605. this.vy = Math.sqrt(energyBefore/this.mass);
  8606. };
  8607. /**
  8608. * @class Edge
  8609. *
  8610. * A edge connects two nodes
  8611. * @param {Object} properties Object with properties. Must contain
  8612. * At least properties from and to.
  8613. * Available properties: from (number),
  8614. * to (number), label (string, color (string),
  8615. * width (number), style (string),
  8616. * length (number), title (string)
  8617. * @param {Graph} graph A graph object, used to find and edge to
  8618. * nodes.
  8619. * @param {Object} constants An object with default values for
  8620. * example for the color
  8621. */
  8622. function Edge (properties, graph, constants) {
  8623. if (!graph) {
  8624. throw "No graph provided";
  8625. }
  8626. this.graph = graph;
  8627. // initialize constants
  8628. this.widthMin = constants.edges.widthMin;
  8629. this.widthMax = constants.edges.widthMax;
  8630. // initialize variables
  8631. this.id = undefined;
  8632. this.fromId = undefined;
  8633. this.toId = undefined;
  8634. this.style = constants.edges.style;
  8635. this.title = undefined;
  8636. this.width = constants.edges.width;
  8637. this.value = undefined;
  8638. this.length = constants.physics.springLength;
  8639. this.customLength = false;
  8640. this.selected = false;
  8641. this.smooth = constants.smoothCurves;
  8642. this.arrowScaleFactor = constants.edges.arrowScaleFactor;
  8643. this.from = null; // a node
  8644. this.to = null; // a node
  8645. this.via = null; // a temp node
  8646. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  8647. // by storing the original information we can revert to the original connection when the cluser is opened.
  8648. this.originalFromId = [];
  8649. this.originalToId = [];
  8650. this.connected = false;
  8651. // Added to support dashed lines
  8652. // David Jordan
  8653. // 2012-08-08
  8654. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  8655. this.color = {color:constants.edges.color.color,
  8656. highlight:constants.edges.color.highlight};
  8657. this.widthFixed = false;
  8658. this.lengthFixed = false;
  8659. this.setProperties(properties, constants);
  8660. }
  8661. /**
  8662. * Set or overwrite properties for the edge
  8663. * @param {Object} properties an object with properties
  8664. * @param {Object} constants and object with default, global properties
  8665. */
  8666. Edge.prototype.setProperties = function(properties, constants) {
  8667. if (!properties) {
  8668. return;
  8669. }
  8670. if (properties.from !== undefined) {this.fromId = properties.from;}
  8671. if (properties.to !== undefined) {this.toId = properties.to;}
  8672. if (properties.id !== undefined) {this.id = properties.id;}
  8673. if (properties.style !== undefined) {this.style = properties.style;}
  8674. if (properties.label !== undefined) {this.label = properties.label;}
  8675. if (this.label) {
  8676. this.fontSize = constants.edges.fontSize;
  8677. this.fontFace = constants.edges.fontFace;
  8678. this.fontColor = constants.edges.fontColor;
  8679. this.fontFill = constants.edges.fontFill;
  8680. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8681. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8682. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8683. if (properties.fontFill !== undefined) {this.fontFill = properties.fontFill;}
  8684. }
  8685. if (properties.title !== undefined) {this.title = properties.title;}
  8686. if (properties.width !== undefined) {this.width = properties.width;}
  8687. if (properties.value !== undefined) {this.value = properties.value;}
  8688. if (properties.length !== undefined) {this.length = properties.length;
  8689. this.customLength = true;}
  8690. // scale the arrow
  8691. if (properties.arrowScaleFactor !== undefined) {this.arrowScaleFactor = properties.arrowScaleFactor;}
  8692. // Added to support dashed lines
  8693. // David Jordan
  8694. // 2012-08-08
  8695. if (properties.dash) {
  8696. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  8697. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  8698. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  8699. }
  8700. if (properties.color !== undefined) {
  8701. if (util.isString(properties.color)) {
  8702. this.color.color = properties.color;
  8703. this.color.highlight = properties.color;
  8704. }
  8705. else {
  8706. if (properties.color.color !== undefined) {this.color.color = properties.color.color;}
  8707. if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;}
  8708. }
  8709. }
  8710. // A node is connected when it has a from and to node.
  8711. this.connect();
  8712. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  8713. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  8714. // set draw method based on style
  8715. switch (this.style) {
  8716. case 'line': this.draw = this._drawLine; break;
  8717. case 'arrow': this.draw = this._drawArrow; break;
  8718. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  8719. case 'dash-line': this.draw = this._drawDashLine; break;
  8720. default: this.draw = this._drawLine; break;
  8721. }
  8722. };
  8723. /**
  8724. * Connect an edge to its nodes
  8725. */
  8726. Edge.prototype.connect = function () {
  8727. this.disconnect();
  8728. this.from = this.graph.nodes[this.fromId] || null;
  8729. this.to = this.graph.nodes[this.toId] || null;
  8730. this.connected = (this.from && this.to);
  8731. if (this.connected) {
  8732. this.from.attachEdge(this);
  8733. this.to.attachEdge(this);
  8734. }
  8735. else {
  8736. if (this.from) {
  8737. this.from.detachEdge(this);
  8738. }
  8739. if (this.to) {
  8740. this.to.detachEdge(this);
  8741. }
  8742. }
  8743. };
  8744. /**
  8745. * Disconnect an edge from its nodes
  8746. */
  8747. Edge.prototype.disconnect = function () {
  8748. if (this.from) {
  8749. this.from.detachEdge(this);
  8750. this.from = null;
  8751. }
  8752. if (this.to) {
  8753. this.to.detachEdge(this);
  8754. this.to = null;
  8755. }
  8756. this.connected = false;
  8757. };
  8758. /**
  8759. * get the title of this edge.
  8760. * @return {string} title The title of the edge, or undefined when no title
  8761. * has been set.
  8762. */
  8763. Edge.prototype.getTitle = function() {
  8764. return typeof this.title === "function" ? this.title() : this.title;
  8765. };
  8766. /**
  8767. * Retrieve the value of the edge. Can be undefined
  8768. * @return {Number} value
  8769. */
  8770. Edge.prototype.getValue = function() {
  8771. return this.value;
  8772. };
  8773. /**
  8774. * Adjust the value range of the edge. The edge will adjust it's width
  8775. * based on its value.
  8776. * @param {Number} min
  8777. * @param {Number} max
  8778. */
  8779. Edge.prototype.setValueRange = function(min, max) {
  8780. if (!this.widthFixed && this.value !== undefined) {
  8781. var scale = (this.widthMax - this.widthMin) / (max - min);
  8782. this.width = (this.value - min) * scale + this.widthMin;
  8783. }
  8784. };
  8785. /**
  8786. * Redraw a edge
  8787. * Draw this edge in the given canvas
  8788. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8789. * @param {CanvasRenderingContext2D} ctx
  8790. */
  8791. Edge.prototype.draw = function(ctx) {
  8792. throw "Method draw not initialized in edge";
  8793. };
  8794. /**
  8795. * Check if this object is overlapping with the provided object
  8796. * @param {Object} obj an object with parameters left, top
  8797. * @return {boolean} True if location is located on the edge
  8798. */
  8799. Edge.prototype.isOverlappingWith = function(obj) {
  8800. if (this.connected) {
  8801. var distMax = 10;
  8802. var xFrom = this.from.x;
  8803. var yFrom = this.from.y;
  8804. var xTo = this.to.x;
  8805. var yTo = this.to.y;
  8806. var xObj = obj.left;
  8807. var yObj = obj.top;
  8808. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  8809. return (dist < distMax);
  8810. }
  8811. else {
  8812. return false
  8813. }
  8814. };
  8815. /**
  8816. * Redraw a edge as a line
  8817. * Draw this edge in the given canvas
  8818. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8819. * @param {CanvasRenderingContext2D} ctx
  8820. * @private
  8821. */
  8822. Edge.prototype._drawLine = function(ctx) {
  8823. // set style
  8824. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  8825. else {ctx.strokeStyle = this.color.color;}
  8826. ctx.lineWidth = this._getLineWidth();
  8827. if (this.from != this.to) {
  8828. // draw line
  8829. this._line(ctx);
  8830. // draw label
  8831. var point;
  8832. if (this.label) {
  8833. if (this.smooth == true) {
  8834. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  8835. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  8836. point = {x:midpointX, y:midpointY};
  8837. }
  8838. else {
  8839. point = this._pointOnLine(0.5);
  8840. }
  8841. this._label(ctx, this.label, point.x, point.y);
  8842. }
  8843. }
  8844. else {
  8845. var x, y;
  8846. var radius = this.length / 4;
  8847. var node = this.from;
  8848. if (!node.width) {
  8849. node.resize(ctx);
  8850. }
  8851. if (node.width > node.height) {
  8852. x = node.x + node.width / 2;
  8853. y = node.y - radius;
  8854. }
  8855. else {
  8856. x = node.x + radius;
  8857. y = node.y - node.height / 2;
  8858. }
  8859. this._circle(ctx, x, y, radius);
  8860. point = this._pointOnCircle(x, y, radius, 0.5);
  8861. this._label(ctx, this.label, point.x, point.y);
  8862. }
  8863. };
  8864. /**
  8865. * Get the line width of the edge. Depends on width and whether one of the
  8866. * connected nodes is selected.
  8867. * @return {Number} width
  8868. * @private
  8869. */
  8870. Edge.prototype._getLineWidth = function() {
  8871. if (this.selected == true) {
  8872. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  8873. }
  8874. else {
  8875. return this.width*this.graphScaleInv;
  8876. }
  8877. };
  8878. /**
  8879. * Draw a line between two nodes
  8880. * @param {CanvasRenderingContext2D} ctx
  8881. * @private
  8882. */
  8883. Edge.prototype._line = function (ctx) {
  8884. // draw a straight line
  8885. ctx.beginPath();
  8886. ctx.moveTo(this.from.x, this.from.y);
  8887. if (this.smooth == true) {
  8888. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  8889. }
  8890. else {
  8891. ctx.lineTo(this.to.x, this.to.y);
  8892. }
  8893. ctx.stroke();
  8894. };
  8895. /**
  8896. * Draw a line from a node to itself, a circle
  8897. * @param {CanvasRenderingContext2D} ctx
  8898. * @param {Number} x
  8899. * @param {Number} y
  8900. * @param {Number} radius
  8901. * @private
  8902. */
  8903. Edge.prototype._circle = function (ctx, x, y, radius) {
  8904. // draw a circle
  8905. ctx.beginPath();
  8906. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  8907. ctx.stroke();
  8908. };
  8909. /**
  8910. * Draw label with white background and with the middle at (x, y)
  8911. * @param {CanvasRenderingContext2D} ctx
  8912. * @param {String} text
  8913. * @param {Number} x
  8914. * @param {Number} y
  8915. * @private
  8916. */
  8917. Edge.prototype._label = function (ctx, text, x, y) {
  8918. if (text) {
  8919. // TODO: cache the calculated size
  8920. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  8921. this.fontSize + "px " + this.fontFace;
  8922. ctx.fillStyle = this.fontFill;
  8923. var width = ctx.measureText(text).width;
  8924. var height = this.fontSize;
  8925. var left = x - width / 2;
  8926. var top = y - height / 2;
  8927. ctx.fillRect(left, top, width, height);
  8928. // draw text
  8929. ctx.fillStyle = this.fontColor || "black";
  8930. ctx.textAlign = "left";
  8931. ctx.textBaseline = "top";
  8932. ctx.fillText(text, left, top);
  8933. }
  8934. };
  8935. /**
  8936. * Redraw a edge as a dashed line
  8937. * Draw this edge in the given canvas
  8938. * @author David Jordan
  8939. * @date 2012-08-08
  8940. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8941. * @param {CanvasRenderingContext2D} ctx
  8942. * @private
  8943. */
  8944. Edge.prototype._drawDashLine = function(ctx) {
  8945. // set style
  8946. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  8947. else {ctx.strokeStyle = this.color.color;}
  8948. ctx.lineWidth = this._getLineWidth();
  8949. // only firefox and chrome support this method, else we use the legacy one.
  8950. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  8951. ctx.beginPath();
  8952. ctx.moveTo(this.from.x, this.from.y);
  8953. // configure the dash pattern
  8954. var pattern = [0];
  8955. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  8956. pattern = [this.dash.length,this.dash.gap];
  8957. }
  8958. else {
  8959. pattern = [5,5];
  8960. }
  8961. // set dash settings for chrome or firefox
  8962. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  8963. ctx.setLineDash(pattern);
  8964. ctx.lineDashOffset = 0;
  8965. } else { //Firefox
  8966. ctx.mozDash = pattern;
  8967. ctx.mozDashOffset = 0;
  8968. }
  8969. // draw the line
  8970. if (this.smooth == true) {
  8971. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  8972. }
  8973. else {
  8974. ctx.lineTo(this.to.x, this.to.y);
  8975. }
  8976. ctx.stroke();
  8977. // restore the dash settings.
  8978. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  8979. ctx.setLineDash([0]);
  8980. ctx.lineDashOffset = 0;
  8981. } else { //Firefox
  8982. ctx.mozDash = [0];
  8983. ctx.mozDashOffset = 0;
  8984. }
  8985. }
  8986. else { // unsupporting smooth lines
  8987. // draw dashed line
  8988. ctx.beginPath();
  8989. ctx.lineCap = 'round';
  8990. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  8991. {
  8992. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8993. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  8994. }
  8995. 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
  8996. {
  8997. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8998. [this.dash.length,this.dash.gap]);
  8999. }
  9000. else //If all else fails draw a line
  9001. {
  9002. ctx.moveTo(this.from.x, this.from.y);
  9003. ctx.lineTo(this.to.x, this.to.y);
  9004. }
  9005. ctx.stroke();
  9006. }
  9007. // draw label
  9008. if (this.label) {
  9009. var point;
  9010. if (this.smooth == true) {
  9011. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9012. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9013. point = {x:midpointX, y:midpointY};
  9014. }
  9015. else {
  9016. point = this._pointOnLine(0.5);
  9017. }
  9018. this._label(ctx, this.label, point.x, point.y);
  9019. }
  9020. };
  9021. /**
  9022. * Get a point on a line
  9023. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9024. * @return {Object} point
  9025. * @private
  9026. */
  9027. Edge.prototype._pointOnLine = function (percentage) {
  9028. return {
  9029. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9030. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9031. }
  9032. };
  9033. /**
  9034. * Get a point on a circle
  9035. * @param {Number} x
  9036. * @param {Number} y
  9037. * @param {Number} radius
  9038. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9039. * @return {Object} point
  9040. * @private
  9041. */
  9042. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9043. var angle = (percentage - 3/8) * 2 * Math.PI;
  9044. return {
  9045. x: x + radius * Math.cos(angle),
  9046. y: y - radius * Math.sin(angle)
  9047. }
  9048. };
  9049. /**
  9050. * Redraw a edge as a line with an arrow halfway the line
  9051. * Draw this edge in the given canvas
  9052. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9053. * @param {CanvasRenderingContext2D} ctx
  9054. * @private
  9055. */
  9056. Edge.prototype._drawArrowCenter = function(ctx) {
  9057. var point;
  9058. // set style
  9059. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9060. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9061. ctx.lineWidth = this._getLineWidth();
  9062. if (this.from != this.to) {
  9063. // draw line
  9064. this._line(ctx);
  9065. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9066. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9067. // draw an arrow halfway the line
  9068. if (this.smooth == true) {
  9069. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9070. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9071. point = {x:midpointX, y:midpointY};
  9072. }
  9073. else {
  9074. point = this._pointOnLine(0.5);
  9075. }
  9076. ctx.arrow(point.x, point.y, angle, length);
  9077. ctx.fill();
  9078. ctx.stroke();
  9079. // draw label
  9080. if (this.label) {
  9081. this._label(ctx, this.label, point.x, point.y);
  9082. }
  9083. }
  9084. else {
  9085. // draw circle
  9086. var x, y;
  9087. var radius = 0.25 * Math.max(100,this.length);
  9088. var node = this.from;
  9089. if (!node.width) {
  9090. node.resize(ctx);
  9091. }
  9092. if (node.width > node.height) {
  9093. x = node.x + node.width * 0.5;
  9094. y = node.y - radius;
  9095. }
  9096. else {
  9097. x = node.x + radius;
  9098. y = node.y - node.height * 0.5;
  9099. }
  9100. this._circle(ctx, x, y, radius);
  9101. // draw all arrows
  9102. var angle = 0.2 * Math.PI;
  9103. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9104. point = this._pointOnCircle(x, y, radius, 0.5);
  9105. ctx.arrow(point.x, point.y, angle, length);
  9106. ctx.fill();
  9107. ctx.stroke();
  9108. // draw label
  9109. if (this.label) {
  9110. point = this._pointOnCircle(x, y, radius, 0.5);
  9111. this._label(ctx, this.label, point.x, point.y);
  9112. }
  9113. }
  9114. };
  9115. /**
  9116. * Redraw a edge as a line with an arrow
  9117. * Draw this edge in the given canvas
  9118. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9119. * @param {CanvasRenderingContext2D} ctx
  9120. * @private
  9121. */
  9122. Edge.prototype._drawArrow = function(ctx) {
  9123. // set style
  9124. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9125. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9126. ctx.lineWidth = this._getLineWidth();
  9127. var angle, length;
  9128. //draw a line
  9129. if (this.from != this.to) {
  9130. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9131. var dx = (this.to.x - this.from.x);
  9132. var dy = (this.to.y - this.from.y);
  9133. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9134. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9135. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9136. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9137. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9138. if (this.smooth == true) {
  9139. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9140. dx = (this.to.x - this.via.x);
  9141. dy = (this.to.y - this.via.y);
  9142. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9143. }
  9144. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9145. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9146. var xTo,yTo;
  9147. if (this.smooth == true) {
  9148. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9149. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9150. }
  9151. else {
  9152. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9153. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9154. }
  9155. ctx.beginPath();
  9156. ctx.moveTo(xFrom,yFrom);
  9157. if (this.smooth == true) {
  9158. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9159. }
  9160. else {
  9161. ctx.lineTo(xTo, yTo);
  9162. }
  9163. ctx.stroke();
  9164. // draw arrow at the end of the line
  9165. length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9166. ctx.arrow(xTo, yTo, angle, length);
  9167. ctx.fill();
  9168. ctx.stroke();
  9169. // draw label
  9170. if (this.label) {
  9171. var point;
  9172. if (this.smooth == true) {
  9173. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9174. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9175. point = {x:midpointX, y:midpointY};
  9176. }
  9177. else {
  9178. point = this._pointOnLine(0.5);
  9179. }
  9180. this._label(ctx, this.label, point.x, point.y);
  9181. }
  9182. }
  9183. else {
  9184. // draw circle
  9185. var node = this.from;
  9186. var x, y, arrow;
  9187. var radius = 0.25 * Math.max(100,this.length);
  9188. if (!node.width) {
  9189. node.resize(ctx);
  9190. }
  9191. if (node.width > node.height) {
  9192. x = node.x + node.width * 0.5;
  9193. y = node.y - radius;
  9194. arrow = {
  9195. x: x,
  9196. y: node.y,
  9197. angle: 0.9 * Math.PI
  9198. };
  9199. }
  9200. else {
  9201. x = node.x + radius;
  9202. y = node.y - node.height * 0.5;
  9203. arrow = {
  9204. x: node.x,
  9205. y: y,
  9206. angle: 0.6 * Math.PI
  9207. };
  9208. }
  9209. ctx.beginPath();
  9210. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9211. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9212. ctx.stroke();
  9213. // draw all arrows
  9214. var length = (10 + 5 * this.width) * this.arrowScaleFactor;
  9215. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9216. ctx.fill();
  9217. ctx.stroke();
  9218. // draw label
  9219. if (this.label) {
  9220. point = this._pointOnCircle(x, y, radius, 0.5);
  9221. this._label(ctx, this.label, point.x, point.y);
  9222. }
  9223. }
  9224. };
  9225. /**
  9226. * Calculate the distance between a point (x3,y3) and a line segment from
  9227. * (x1,y1) to (x2,y2).
  9228. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9229. * @param {number} x1
  9230. * @param {number} y1
  9231. * @param {number} x2
  9232. * @param {number} y2
  9233. * @param {number} x3
  9234. * @param {number} y3
  9235. * @private
  9236. */
  9237. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9238. if (this.smooth == true) {
  9239. var minDistance = 1e9;
  9240. var i,t,x,y,dx,dy;
  9241. for (i = 0; i < 10; i++) {
  9242. t = 0.1*i;
  9243. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9244. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9245. dx = Math.abs(x3-x);
  9246. dy = Math.abs(y3-y);
  9247. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9248. }
  9249. return minDistance
  9250. }
  9251. else {
  9252. var px = x2-x1,
  9253. py = y2-y1,
  9254. something = px*px + py*py,
  9255. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9256. if (u > 1) {
  9257. u = 1;
  9258. }
  9259. else if (u < 0) {
  9260. u = 0;
  9261. }
  9262. var x = x1 + u * px,
  9263. y = y1 + u * py,
  9264. dx = x - x3,
  9265. dy = y - y3;
  9266. //# Note: If the actual distance does not matter,
  9267. //# if you only want to compare what this function
  9268. //# returns to other results of this function, you
  9269. //# can just return the squared distance instead
  9270. //# (i.e. remove the sqrt) to gain a little performance
  9271. return Math.sqrt(dx*dx + dy*dy);
  9272. }
  9273. };
  9274. /**
  9275. * This allows the zoom level of the graph to influence the rendering
  9276. *
  9277. * @param scale
  9278. */
  9279. Edge.prototype.setScale = function(scale) {
  9280. this.graphScaleInv = 1.0/scale;
  9281. };
  9282. Edge.prototype.select = function() {
  9283. this.selected = true;
  9284. };
  9285. Edge.prototype.unselect = function() {
  9286. this.selected = false;
  9287. };
  9288. Edge.prototype.positionBezierNode = function() {
  9289. if (this.via !== null) {
  9290. this.via.x = 0.5 * (this.from.x + this.to.x);
  9291. this.via.y = 0.5 * (this.from.y + this.to.y);
  9292. }
  9293. };
  9294. /**
  9295. * Popup is a class to create a popup window with some text
  9296. * @param {Element} container The container object.
  9297. * @param {Number} [x]
  9298. * @param {Number} [y]
  9299. * @param {String} [text]
  9300. * @param {Object} [style] An object containing borderColor,
  9301. * backgroundColor, etc.
  9302. */
  9303. function Popup(container, x, y, text, style) {
  9304. if (container) {
  9305. this.container = container;
  9306. }
  9307. else {
  9308. this.container = document.body;
  9309. }
  9310. // x, y and text are optional, see if a style object was passed in their place
  9311. if (style === undefined) {
  9312. if (typeof x === "object") {
  9313. style = x;
  9314. x = undefined;
  9315. } else if (typeof text === "object") {
  9316. style = text;
  9317. text = undefined;
  9318. } else {
  9319. // for backwards compatibility, in case clients other than Graph are creating Popup directly
  9320. style = {
  9321. fontColor: 'black',
  9322. fontSize: 14, // px
  9323. fontFace: 'verdana',
  9324. color: {
  9325. border: '#666',
  9326. background: '#FFFFC6'
  9327. }
  9328. }
  9329. }
  9330. }
  9331. this.x = 0;
  9332. this.y = 0;
  9333. this.padding = 5;
  9334. if (x !== undefined && y !== undefined ) {
  9335. this.setPosition(x, y);
  9336. }
  9337. if (text !== undefined) {
  9338. this.setText(text);
  9339. }
  9340. // create the frame
  9341. this.frame = document.createElement("div");
  9342. var styleAttr = this.frame.style;
  9343. styleAttr.position = "absolute";
  9344. styleAttr.visibility = "hidden";
  9345. styleAttr.border = "1px solid " + style.color.border;
  9346. styleAttr.color = style.fontColor;
  9347. styleAttr.fontSize = style.fontSize + "px";
  9348. styleAttr.fontFamily = style.fontFace;
  9349. styleAttr.padding = this.padding + "px";
  9350. styleAttr.backgroundColor = style.color.background;
  9351. styleAttr.borderRadius = "3px";
  9352. styleAttr.MozBorderRadius = "3px";
  9353. styleAttr.WebkitBorderRadius = "3px";
  9354. styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9355. styleAttr.whiteSpace = "nowrap";
  9356. this.container.appendChild(this.frame);
  9357. }
  9358. /**
  9359. * @param {number} x Horizontal position of the popup window
  9360. * @param {number} y Vertical position of the popup window
  9361. */
  9362. Popup.prototype.setPosition = function(x, y) {
  9363. this.x = parseInt(x);
  9364. this.y = parseInt(y);
  9365. };
  9366. /**
  9367. * Set the text for the popup window. This can be HTML code
  9368. * @param {string} text
  9369. */
  9370. Popup.prototype.setText = function(text) {
  9371. this.frame.innerHTML = text;
  9372. };
  9373. /**
  9374. * Show the popup window
  9375. * @param {boolean} show Optional. Show or hide the window
  9376. */
  9377. Popup.prototype.show = function (show) {
  9378. if (show === undefined) {
  9379. show = true;
  9380. }
  9381. if (show) {
  9382. var height = this.frame.clientHeight;
  9383. var width = this.frame.clientWidth;
  9384. var maxHeight = this.frame.parentNode.clientHeight;
  9385. var maxWidth = this.frame.parentNode.clientWidth;
  9386. var top = (this.y - height);
  9387. if (top + height + this.padding > maxHeight) {
  9388. top = maxHeight - height - this.padding;
  9389. }
  9390. if (top < this.padding) {
  9391. top = this.padding;
  9392. }
  9393. var left = this.x;
  9394. if (left + width + this.padding > maxWidth) {
  9395. left = maxWidth - width - this.padding;
  9396. }
  9397. if (left < this.padding) {
  9398. left = this.padding;
  9399. }
  9400. this.frame.style.left = left + "px";
  9401. this.frame.style.top = top + "px";
  9402. this.frame.style.visibility = "visible";
  9403. }
  9404. else {
  9405. this.hide();
  9406. }
  9407. };
  9408. /**
  9409. * Hide the popup window
  9410. */
  9411. Popup.prototype.hide = function () {
  9412. this.frame.style.visibility = "hidden";
  9413. };
  9414. /**
  9415. * @class Groups
  9416. * This class can store groups and properties specific for groups.
  9417. */
  9418. Groups = function () {
  9419. this.clear();
  9420. this.defaultIndex = 0;
  9421. };
  9422. /**
  9423. * default constants for group colors
  9424. */
  9425. Groups.DEFAULT = [
  9426. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9427. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9428. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9429. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9430. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9431. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9432. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9433. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9434. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9435. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9436. ];
  9437. /**
  9438. * Clear all groups
  9439. */
  9440. Groups.prototype.clear = function () {
  9441. this.groups = {};
  9442. this.groups.length = function()
  9443. {
  9444. var i = 0;
  9445. for ( var p in this ) {
  9446. if (this.hasOwnProperty(p)) {
  9447. i++;
  9448. }
  9449. }
  9450. return i;
  9451. }
  9452. };
  9453. /**
  9454. * get group properties of a groupname. If groupname is not found, a new group
  9455. * is added.
  9456. * @param {*} groupname Can be a number, string, Date, etc.
  9457. * @return {Object} group The created group, containing all group properties
  9458. */
  9459. Groups.prototype.get = function (groupname) {
  9460. var group = this.groups[groupname];
  9461. if (group == undefined) {
  9462. // create new group
  9463. var index = this.defaultIndex % Groups.DEFAULT.length;
  9464. this.defaultIndex++;
  9465. group = {};
  9466. group.color = Groups.DEFAULT[index];
  9467. this.groups[groupname] = group;
  9468. }
  9469. return group;
  9470. };
  9471. /**
  9472. * Add a custom group style
  9473. * @param {String} groupname
  9474. * @param {Object} style An object containing borderColor,
  9475. * backgroundColor, etc.
  9476. * @return {Object} group The created group object
  9477. */
  9478. Groups.prototype.add = function (groupname, style) {
  9479. this.groups[groupname] = style;
  9480. if (style.color) {
  9481. style.color = util.parseColor(style.color);
  9482. }
  9483. return style;
  9484. };
  9485. /**
  9486. * @class Images
  9487. * This class loads images and keeps them stored.
  9488. */
  9489. Images = function () {
  9490. this.images = {};
  9491. this.callback = undefined;
  9492. };
  9493. /**
  9494. * Set an onload callback function. This will be called each time an image
  9495. * is loaded
  9496. * @param {function} callback
  9497. */
  9498. Images.prototype.setOnloadCallback = function(callback) {
  9499. this.callback = callback;
  9500. };
  9501. /**
  9502. *
  9503. * @param {string} url Url of the image
  9504. * @return {Image} img The image object
  9505. */
  9506. Images.prototype.load = function(url) {
  9507. var img = this.images[url];
  9508. if (img == undefined) {
  9509. // create the image
  9510. var images = this;
  9511. img = new Image();
  9512. this.images[url] = img;
  9513. img.onload = function() {
  9514. if (images.callback) {
  9515. images.callback(this);
  9516. }
  9517. };
  9518. img.src = url;
  9519. }
  9520. return img;
  9521. };
  9522. /**
  9523. * Created by Alex on 2/6/14.
  9524. */
  9525. var physicsMixin = {
  9526. /**
  9527. * Toggling barnes Hut calculation on and off.
  9528. *
  9529. * @private
  9530. */
  9531. _toggleBarnesHut: function () {
  9532. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  9533. this._loadSelectedForceSolver();
  9534. this.moving = true;
  9535. this.start();
  9536. },
  9537. /**
  9538. * This loads the node force solver based on the barnes hut or repulsion algorithm
  9539. *
  9540. * @private
  9541. */
  9542. _loadSelectedForceSolver: function () {
  9543. // this overloads the this._calculateNodeForces
  9544. if (this.constants.physics.barnesHut.enabled == true) {
  9545. this._clearMixin(repulsionMixin);
  9546. this._clearMixin(hierarchalRepulsionMixin);
  9547. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  9548. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  9549. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  9550. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  9551. this._loadMixin(barnesHutMixin);
  9552. }
  9553. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  9554. this._clearMixin(barnesHutMixin);
  9555. this._clearMixin(repulsionMixin);
  9556. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  9557. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  9558. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  9559. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  9560. this._loadMixin(hierarchalRepulsionMixin);
  9561. }
  9562. else {
  9563. this._clearMixin(barnesHutMixin);
  9564. this._clearMixin(hierarchalRepulsionMixin);
  9565. this.barnesHutTree = undefined;
  9566. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  9567. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  9568. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  9569. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  9570. this._loadMixin(repulsionMixin);
  9571. }
  9572. },
  9573. /**
  9574. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  9575. * if there is more than one node. If it is just one node, we dont calculate anything.
  9576. *
  9577. * @private
  9578. */
  9579. _initializeForceCalculation: function () {
  9580. // stop calculation if there is only one node
  9581. if (this.nodeIndices.length == 1) {
  9582. this.nodes[this.nodeIndices[0]]._setForce(0, 0);
  9583. }
  9584. else {
  9585. // if there are too many nodes on screen, we cluster without repositioning
  9586. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  9587. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  9588. }
  9589. // we now start the force calculation
  9590. this._calculateForces();
  9591. }
  9592. },
  9593. /**
  9594. * Calculate the external forces acting on the nodes
  9595. * Forces are caused by: edges, repulsing forces between nodes, gravity
  9596. * @private
  9597. */
  9598. _calculateForces: function () {
  9599. // Gravity is required to keep separated groups from floating off
  9600. // the forces are reset to zero in this loop by using _setForce instead
  9601. // of _addForce
  9602. this._calculateGravitationalForces();
  9603. this._calculateNodeForces();
  9604. if (this.constants.smoothCurves == true) {
  9605. this._calculateSpringForcesWithSupport();
  9606. }
  9607. else {
  9608. this._calculateSpringForces();
  9609. }
  9610. },
  9611. /**
  9612. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  9613. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  9614. * This function joins the datanodes and invisible (called support) nodes into one object.
  9615. * We do this so we do not contaminate this.nodes with the support nodes.
  9616. *
  9617. * @private
  9618. */
  9619. _updateCalculationNodes: function () {
  9620. if (this.constants.smoothCurves == true) {
  9621. this.calculationNodes = {};
  9622. this.calculationNodeIndices = [];
  9623. for (var nodeId in this.nodes) {
  9624. if (this.nodes.hasOwnProperty(nodeId)) {
  9625. this.calculationNodes[nodeId] = this.nodes[nodeId];
  9626. }
  9627. }
  9628. var supportNodes = this.sectors['support']['nodes'];
  9629. for (var supportNodeId in supportNodes) {
  9630. if (supportNodes.hasOwnProperty(supportNodeId)) {
  9631. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  9632. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  9633. }
  9634. else {
  9635. supportNodes[supportNodeId]._setForce(0, 0);
  9636. }
  9637. }
  9638. }
  9639. for (var idx in this.calculationNodes) {
  9640. if (this.calculationNodes.hasOwnProperty(idx)) {
  9641. this.calculationNodeIndices.push(idx);
  9642. }
  9643. }
  9644. }
  9645. else {
  9646. this.calculationNodes = this.nodes;
  9647. this.calculationNodeIndices = this.nodeIndices;
  9648. }
  9649. },
  9650. /**
  9651. * this function applies the central gravity effect to keep groups from floating off
  9652. *
  9653. * @private
  9654. */
  9655. _calculateGravitationalForces: function () {
  9656. var dx, dy, distance, node, i;
  9657. var nodes = this.calculationNodes;
  9658. var gravity = this.constants.physics.centralGravity;
  9659. var gravityForce = 0;
  9660. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  9661. node = nodes[this.calculationNodeIndices[i]];
  9662. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  9663. // gravity does not apply when we are in a pocket sector
  9664. if (this._sector() == "default" && gravity != 0) {
  9665. dx = -node.x;
  9666. dy = -node.y;
  9667. distance = Math.sqrt(dx * dx + dy * dy);
  9668. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  9669. node.fx = dx * gravityForce;
  9670. node.fy = dy * gravityForce;
  9671. }
  9672. else {
  9673. node.fx = 0;
  9674. node.fy = 0;
  9675. }
  9676. }
  9677. },
  9678. /**
  9679. * this function calculates the effects of the springs in the case of unsmooth curves.
  9680. *
  9681. * @private
  9682. */
  9683. _calculateSpringForces: function () {
  9684. var edgeLength, edge, edgeId;
  9685. var dx, dy, fx, fy, springForce, length;
  9686. var edges = this.edges;
  9687. // forces caused by the edges, modelled as springs
  9688. for (edgeId in edges) {
  9689. if (edges.hasOwnProperty(edgeId)) {
  9690. edge = edges[edgeId];
  9691. if (edge.connected) {
  9692. // only calculate forces if nodes are in the same sector
  9693. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9694. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9695. // this implies that the edges between big clusters are longer
  9696. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  9697. dx = (edge.from.x - edge.to.x);
  9698. dy = (edge.from.y - edge.to.y);
  9699. length = Math.sqrt(dx * dx + dy * dy);
  9700. if (length == 0) {
  9701. length = 0.01;
  9702. }
  9703. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  9704. fx = dx * springForce;
  9705. fy = dy * springForce;
  9706. edge.from.fx += fx;
  9707. edge.from.fy += fy;
  9708. edge.to.fx -= fx;
  9709. edge.to.fy -= fy;
  9710. }
  9711. }
  9712. }
  9713. }
  9714. },
  9715. /**
  9716. * This function calculates the springforces on the nodes, accounting for the support nodes.
  9717. *
  9718. * @private
  9719. */
  9720. _calculateSpringForcesWithSupport: function () {
  9721. var edgeLength, edge, edgeId, combinedClusterSize;
  9722. var edges = this.edges;
  9723. // forces caused by the edges, modelled as springs
  9724. for (edgeId in edges) {
  9725. if (edges.hasOwnProperty(edgeId)) {
  9726. edge = edges[edgeId];
  9727. if (edge.connected) {
  9728. // only calculate forces if nodes are in the same sector
  9729. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9730. if (edge.via != null) {
  9731. var node1 = edge.to;
  9732. var node2 = edge.via;
  9733. var node3 = edge.from;
  9734. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9735. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  9736. // this implies that the edges between big clusters are longer
  9737. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  9738. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  9739. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  9740. }
  9741. }
  9742. }
  9743. }
  9744. }
  9745. },
  9746. /**
  9747. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  9748. *
  9749. * @param node1
  9750. * @param node2
  9751. * @param edgeLength
  9752. * @private
  9753. */
  9754. _calculateSpringForce: function (node1, node2, edgeLength) {
  9755. var dx, dy, fx, fy, springForce, length;
  9756. dx = (node1.x - node2.x);
  9757. dy = (node1.y - node2.y);
  9758. length = Math.sqrt(dx * dx + dy * dy);
  9759. if (length == 0) {
  9760. length = 0.01;
  9761. }
  9762. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  9763. fx = dx * springForce;
  9764. fy = dy * springForce;
  9765. node1.fx += fx;
  9766. node1.fy += fy;
  9767. node2.fx -= fx;
  9768. node2.fy -= fy;
  9769. },
  9770. /**
  9771. * Load the HTML for the physics config and bind it
  9772. * @private
  9773. */
  9774. _loadPhysicsConfiguration: function () {
  9775. if (this.physicsConfiguration === undefined) {
  9776. this.backupConstants = {};
  9777. util.copyObject(this.constants, this.backupConstants);
  9778. var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"];
  9779. this.physicsConfiguration = document.createElement('div');
  9780. this.physicsConfiguration.className = "PhysicsConfiguration";
  9781. this.physicsConfiguration.innerHTML = '' +
  9782. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  9783. '<tr>' +
  9784. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  9785. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' +
  9786. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  9787. '</tr>' +
  9788. '</table>' +
  9789. '<table id="graph_BH_table" style="display:none">' +
  9790. '<tr><td><b>Barnes Hut</b></td></tr>' +
  9791. '<tr>' +
  9792. '<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>' +
  9793. '</tr>' +
  9794. '<tr>' +
  9795. '<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>' +
  9796. '</tr>' +
  9797. '<tr>' +
  9798. '<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>' +
  9799. '</tr>' +
  9800. '<tr>' +
  9801. '<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>' +
  9802. '</tr>' +
  9803. '<tr>' +
  9804. '<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>' +
  9805. '</tr>' +
  9806. '</table>' +
  9807. '<table id="graph_R_table" style="display:none">' +
  9808. '<tr><td><b>Repulsion</b></td></tr>' +
  9809. '<tr>' +
  9810. '<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>' +
  9811. '</tr>' +
  9812. '<tr>' +
  9813. '<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>' +
  9814. '</tr>' +
  9815. '<tr>' +
  9816. '<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>' +
  9817. '</tr>' +
  9818. '<tr>' +
  9819. '<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>' +
  9820. '</tr>' +
  9821. '<tr>' +
  9822. '<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>' +
  9823. '</tr>' +
  9824. '</table>' +
  9825. '<table id="graph_H_table" style="display:none">' +
  9826. '<tr><td width="150"><b>Hierarchical</b></td></tr>' +
  9827. '<tr>' +
  9828. '<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>' +
  9829. '</tr>' +
  9830. '<tr>' +
  9831. '<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>' +
  9832. '</tr>' +
  9833. '<tr>' +
  9834. '<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>' +
  9835. '</tr>' +
  9836. '<tr>' +
  9837. '<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>' +
  9838. '</tr>' +
  9839. '<tr>' +
  9840. '<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>' +
  9841. '</tr>' +
  9842. '<tr>' +
  9843. '<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>' +
  9844. '</tr>' +
  9845. '<tr>' +
  9846. '<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>' +
  9847. '</tr>' +
  9848. '<tr>' +
  9849. '<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>' +
  9850. '</tr>' +
  9851. '</table>' +
  9852. '<table><tr><td><b>Options:</b></td></tr>' +
  9853. '<tr>' +
  9854. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  9855. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  9856. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  9857. '</tr>' +
  9858. '</table>'
  9859. this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement);
  9860. this.optionsDiv = document.createElement("div");
  9861. this.optionsDiv.style.fontSize = "14px";
  9862. this.optionsDiv.style.fontFamily = "verdana";
  9863. this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement);
  9864. var rangeElement;
  9865. rangeElement = document.getElementById('graph_BH_gc');
  9866. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant");
  9867. rangeElement = document.getElementById('graph_BH_cg');
  9868. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity");
  9869. rangeElement = document.getElementById('graph_BH_sc');
  9870. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant");
  9871. rangeElement = document.getElementById('graph_BH_sl');
  9872. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength");
  9873. rangeElement = document.getElementById('graph_BH_damp');
  9874. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping");
  9875. rangeElement = document.getElementById('graph_R_nd');
  9876. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance");
  9877. rangeElement = document.getElementById('graph_R_cg');
  9878. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity");
  9879. rangeElement = document.getElementById('graph_R_sc');
  9880. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant");
  9881. rangeElement = document.getElementById('graph_R_sl');
  9882. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength");
  9883. rangeElement = document.getElementById('graph_R_damp');
  9884. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping");
  9885. rangeElement = document.getElementById('graph_H_nd');
  9886. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  9887. rangeElement = document.getElementById('graph_H_cg');
  9888. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity");
  9889. rangeElement = document.getElementById('graph_H_sc');
  9890. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant");
  9891. rangeElement = document.getElementById('graph_H_sl');
  9892. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength");
  9893. rangeElement = document.getElementById('graph_H_damp');
  9894. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping");
  9895. rangeElement = document.getElementById('graph_H_direction');
  9896. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction");
  9897. rangeElement = document.getElementById('graph_H_levsep');
  9898. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation");
  9899. rangeElement = document.getElementById('graph_H_nspac');
  9900. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing");
  9901. var radioButton1 = document.getElementById("graph_physicsMethod1");
  9902. var radioButton2 = document.getElementById("graph_physicsMethod2");
  9903. var radioButton3 = document.getElementById("graph_physicsMethod3");
  9904. radioButton2.checked = true;
  9905. if (this.constants.physics.barnesHut.enabled) {
  9906. radioButton1.checked = true;
  9907. }
  9908. if (this.constants.hierarchicalLayout.enabled) {
  9909. radioButton3.checked = true;
  9910. }
  9911. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  9912. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  9913. var graph_generateOptions = document.getElementById("graph_generateOptions");
  9914. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  9915. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  9916. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  9917. if (this.constants.smoothCurves == true) {
  9918. graph_toggleSmooth.style.background = "#A4FF56";
  9919. }
  9920. else {
  9921. graph_toggleSmooth.style.background = "#FF8532";
  9922. }
  9923. switchConfigurations.apply(this);
  9924. radioButton1.onchange = switchConfigurations.bind(this);
  9925. radioButton2.onchange = switchConfigurations.bind(this);
  9926. radioButton3.onchange = switchConfigurations.bind(this);
  9927. }
  9928. },
  9929. /**
  9930. * This overwrites the this.constants.
  9931. *
  9932. * @param constantsVariableName
  9933. * @param value
  9934. * @private
  9935. */
  9936. _overWriteGraphConstants: function (constantsVariableName, value) {
  9937. var nameArray = constantsVariableName.split("_");
  9938. if (nameArray.length == 1) {
  9939. this.constants[nameArray[0]] = value;
  9940. }
  9941. else if (nameArray.length == 2) {
  9942. this.constants[nameArray[0]][nameArray[1]] = value;
  9943. }
  9944. else if (nameArray.length == 3) {
  9945. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  9946. }
  9947. }
  9948. };
  9949. /**
  9950. * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype.
  9951. */
  9952. function graphToggleSmoothCurves () {
  9953. this.constants.smoothCurves = !this.constants.smoothCurves;
  9954. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  9955. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  9956. else {graph_toggleSmooth.style.background = "#FF8532";}
  9957. this._configureSmoothCurves(false);
  9958. };
  9959. /**
  9960. * this function is used to scramble the nodes
  9961. *
  9962. */
  9963. function graphRepositionNodes () {
  9964. for (var nodeId in this.calculationNodes) {
  9965. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  9966. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  9967. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  9968. }
  9969. }
  9970. if (this.constants.hierarchicalLayout.enabled == true) {
  9971. this._setupHierarchicalLayout();
  9972. }
  9973. else {
  9974. this.repositionNodes();
  9975. }
  9976. this.moving = true;
  9977. this.start();
  9978. };
  9979. /**
  9980. * this is used to generate an options file from the playing with physics system.
  9981. */
  9982. function graphGenerateOptions () {
  9983. var options = "No options are required, default values used.";
  9984. var optionsSpecific = [];
  9985. var radioButton1 = document.getElementById("graph_physicsMethod1");
  9986. var radioButton2 = document.getElementById("graph_physicsMethod2");
  9987. if (radioButton1.checked == true) {
  9988. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  9989. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  9990. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  9991. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  9992. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  9993. if (optionsSpecific.length != 0) {
  9994. options = "var options = {";
  9995. options += "physics: {barnesHut: {";
  9996. for (var i = 0; i < optionsSpecific.length; i++) {
  9997. options += optionsSpecific[i];
  9998. if (i < optionsSpecific.length - 1) {
  9999. options += ", "
  10000. }
  10001. }
  10002. options += '}}'
  10003. }
  10004. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10005. if (optionsSpecific.length == 0) {options = "var options = {";}
  10006. else {options += ", "}
  10007. options += "smoothCurves: " + this.constants.smoothCurves;
  10008. }
  10009. if (options != "No options are required, default values used.") {
  10010. options += '};'
  10011. }
  10012. }
  10013. else if (radioButton2.checked == true) {
  10014. options = "var options = {";
  10015. options += "physics: {barnesHut: {enabled: false}";
  10016. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  10017. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10018. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10019. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10020. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10021. if (optionsSpecific.length != 0) {
  10022. options += ", repulsion: {";
  10023. for (var i = 0; i < optionsSpecific.length; i++) {
  10024. options += optionsSpecific[i];
  10025. if (i < optionsSpecific.length - 1) {
  10026. options += ", "
  10027. }
  10028. }
  10029. options += '}}'
  10030. }
  10031. if (optionsSpecific.length == 0) {options += "}"}
  10032. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10033. options += ", smoothCurves: " + this.constants.smoothCurves;
  10034. }
  10035. options += '};'
  10036. }
  10037. else {
  10038. options = "var options = {";
  10039. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  10040. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10041. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10042. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10043. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10044. if (optionsSpecific.length != 0) {
  10045. options += "physics: {hierarchicalRepulsion: {";
  10046. for (var i = 0; i < optionsSpecific.length; i++) {
  10047. options += optionsSpecific[i];
  10048. if (i < optionsSpecific.length - 1) {
  10049. options += ", ";
  10050. }
  10051. }
  10052. options += '}},';
  10053. }
  10054. options += 'hierarchicalLayout: {';
  10055. optionsSpecific = [];
  10056. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  10057. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  10058. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  10059. if (optionsSpecific.length != 0) {
  10060. for (var i = 0; i < optionsSpecific.length; i++) {
  10061. options += optionsSpecific[i];
  10062. if (i < optionsSpecific.length - 1) {
  10063. options += ", "
  10064. }
  10065. }
  10066. options += '}'
  10067. }
  10068. else {
  10069. options += "enabled:true}";
  10070. }
  10071. options += '};'
  10072. }
  10073. this.optionsDiv.innerHTML = options;
  10074. };
  10075. /**
  10076. * this is used to switch between barnesHut, repulsion and hierarchical.
  10077. *
  10078. */
  10079. function switchConfigurations () {
  10080. var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"];
  10081. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  10082. var tableId = "graph_" + radioButton + "_table";
  10083. var table = document.getElementById(tableId);
  10084. table.style.display = "block";
  10085. for (var i = 0; i < ids.length; i++) {
  10086. if (ids[i] != tableId) {
  10087. table = document.getElementById(ids[i]);
  10088. table.style.display = "none";
  10089. }
  10090. }
  10091. this._restoreNodes();
  10092. if (radioButton == "R") {
  10093. this.constants.hierarchicalLayout.enabled = false;
  10094. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10095. this.constants.physics.barnesHut.enabled = false;
  10096. }
  10097. else if (radioButton == "H") {
  10098. this.constants.hierarchicalLayout.enabled = true;
  10099. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10100. this.constants.physics.barnesHut.enabled = false;
  10101. this._setupHierarchicalLayout();
  10102. }
  10103. else {
  10104. this.constants.hierarchicalLayout.enabled = false;
  10105. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10106. this.constants.physics.barnesHut.enabled = true;
  10107. }
  10108. this._loadSelectedForceSolver();
  10109. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10110. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10111. else {graph_toggleSmooth.style.background = "#FF8532";}
  10112. this.moving = true;
  10113. this.start();
  10114. }
  10115. /**
  10116. * this generates the ranges depending on the iniital values.
  10117. *
  10118. * @param id
  10119. * @param map
  10120. * @param constantsVariableName
  10121. */
  10122. function showValueOfRange (id,map,constantsVariableName) {
  10123. var valueId = id + "_value";
  10124. var rangeValue = document.getElementById(id).value;
  10125. if (map instanceof Array) {
  10126. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  10127. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  10128. }
  10129. else {
  10130. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  10131. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  10132. }
  10133. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10134. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10135. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10136. this._setupHierarchicalLayout();
  10137. }
  10138. this.moving = true;
  10139. this.start();
  10140. };
  10141. /**
  10142. * Created by Alex on 2/10/14.
  10143. */
  10144. var hierarchalRepulsionMixin = {
  10145. /**
  10146. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10147. * This field is linearly approximated.
  10148. *
  10149. * @private
  10150. */
  10151. _calculateNodeForces: function () {
  10152. var dx, dy, distance, fx, fy, combinedClusterSize,
  10153. repulsingForce, node1, node2, i, j;
  10154. var nodes = this.calculationNodes;
  10155. var nodeIndices = this.calculationNodeIndices;
  10156. // approximation constants
  10157. var b = 5;
  10158. var a_base = 0.5 * -b;
  10159. // repulsing forces between nodes
  10160. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  10161. var minimumDistance = nodeDistance;
  10162. // we loop from i over all but the last entree in the array
  10163. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10164. for (i = 0; i < nodeIndices.length - 1; i++) {
  10165. node1 = nodes[nodeIndices[i]];
  10166. for (j = i + 1; j < nodeIndices.length; j++) {
  10167. node2 = nodes[nodeIndices[j]];
  10168. dx = node2.x - node1.x;
  10169. dy = node2.y - node1.y;
  10170. distance = Math.sqrt(dx * dx + dy * dy);
  10171. var a = a_base / minimumDistance;
  10172. if (distance < 2 * minimumDistance) {
  10173. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10174. // normalize force with
  10175. if (distance == 0) {
  10176. distance = 0.01;
  10177. }
  10178. else {
  10179. repulsingForce = repulsingForce / distance;
  10180. }
  10181. fx = dx * repulsingForce;
  10182. fy = dy * repulsingForce;
  10183. node1.fx -= fx;
  10184. node1.fy -= fy;
  10185. node2.fx += fx;
  10186. node2.fy += fy;
  10187. }
  10188. }
  10189. }
  10190. }
  10191. };
  10192. /**
  10193. * Created by Alex on 2/10/14.
  10194. */
  10195. var barnesHutMixin = {
  10196. /**
  10197. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10198. * The Barnes Hut method is used to speed up this N-body simulation.
  10199. *
  10200. * @private
  10201. */
  10202. _calculateNodeForces : function() {
  10203. if (this.constants.physics.barnesHut.gravitationalConstant != 0) {
  10204. var node;
  10205. var nodes = this.calculationNodes;
  10206. var nodeIndices = this.calculationNodeIndices;
  10207. var nodeCount = nodeIndices.length;
  10208. this._formBarnesHutTree(nodes,nodeIndices);
  10209. var barnesHutTree = this.barnesHutTree;
  10210. // place the nodes one by one recursively
  10211. for (var i = 0; i < nodeCount; i++) {
  10212. node = nodes[nodeIndices[i]];
  10213. // starting with root is irrelevant, it never passes the BarnesHut condition
  10214. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10215. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10216. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10217. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10218. }
  10219. }
  10220. },
  10221. /**
  10222. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10223. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10224. *
  10225. * @param parentBranch
  10226. * @param node
  10227. * @private
  10228. */
  10229. _getForceContribution : function(parentBranch,node) {
  10230. // we get no force contribution from an empty region
  10231. if (parentBranch.childrenCount > 0) {
  10232. var dx,dy,distance;
  10233. // get the distance from the center of mass to the node.
  10234. dx = parentBranch.centerOfMass.x - node.x;
  10235. dy = parentBranch.centerOfMass.y - node.y;
  10236. distance = Math.sqrt(dx * dx + dy * dy);
  10237. // BarnesHut condition
  10238. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10239. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10240. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10241. // duplicate code to reduce function calls to speed up program
  10242. if (distance == 0) {
  10243. distance = 0.1*Math.random();
  10244. dx = distance;
  10245. }
  10246. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10247. var fx = dx * gravityForce;
  10248. var fy = dy * gravityForce;
  10249. node.fx += fx;
  10250. node.fy += fy;
  10251. }
  10252. else {
  10253. // Did not pass the condition, go into children if available
  10254. if (parentBranch.childrenCount == 4) {
  10255. this._getForceContribution(parentBranch.children.NW,node);
  10256. this._getForceContribution(parentBranch.children.NE,node);
  10257. this._getForceContribution(parentBranch.children.SW,node);
  10258. this._getForceContribution(parentBranch.children.SE,node);
  10259. }
  10260. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10261. if (parentBranch.children.data.id != node.id) { // if it is not self
  10262. // duplicate code to reduce function calls to speed up program
  10263. if (distance == 0) {
  10264. distance = 0.5*Math.random();
  10265. dx = distance;
  10266. }
  10267. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10268. var fx = dx * gravityForce;
  10269. var fy = dy * gravityForce;
  10270. node.fx += fx;
  10271. node.fy += fy;
  10272. }
  10273. }
  10274. }
  10275. }
  10276. },
  10277. /**
  10278. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10279. *
  10280. * @param nodes
  10281. * @param nodeIndices
  10282. * @private
  10283. */
  10284. _formBarnesHutTree : function(nodes,nodeIndices) {
  10285. var node;
  10286. var nodeCount = nodeIndices.length;
  10287. var minX = Number.MAX_VALUE,
  10288. minY = Number.MAX_VALUE,
  10289. maxX =-Number.MAX_VALUE,
  10290. maxY =-Number.MAX_VALUE;
  10291. // get the range of the nodes
  10292. for (var i = 0; i < nodeCount; i++) {
  10293. var x = nodes[nodeIndices[i]].x;
  10294. var y = nodes[nodeIndices[i]].y;
  10295. if (x < minX) { minX = x; }
  10296. if (x > maxX) { maxX = x; }
  10297. if (y < minY) { minY = y; }
  10298. if (y > maxY) { maxY = y; }
  10299. }
  10300. // make the range a square
  10301. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10302. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10303. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10304. var minimumTreeSize = 1e-5;
  10305. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10306. var halfRootSize = 0.5 * rootSize;
  10307. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10308. // construct the barnesHutTree
  10309. var barnesHutTree = {root:{
  10310. centerOfMass:{x:0,y:0}, // Center of Mass
  10311. mass:0,
  10312. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10313. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10314. size: rootSize,
  10315. calcSize: 1 / rootSize,
  10316. children: {data:null},
  10317. maxWidth: 0,
  10318. level: 0,
  10319. childrenCount: 4
  10320. }};
  10321. this._splitBranch(barnesHutTree.root);
  10322. // place the nodes one by one recursively
  10323. for (i = 0; i < nodeCount; i++) {
  10324. node = nodes[nodeIndices[i]];
  10325. this._placeInTree(barnesHutTree.root,node);
  10326. }
  10327. // make global
  10328. this.barnesHutTree = barnesHutTree
  10329. },
  10330. /**
  10331. * this updates the mass of a branch. this is increased by adding a node.
  10332. *
  10333. * @param parentBranch
  10334. * @param node
  10335. * @private
  10336. */
  10337. _updateBranchMass : function(parentBranch, node) {
  10338. var totalMass = parentBranch.mass + node.mass;
  10339. var totalMassInv = 1/totalMass;
  10340. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10341. parentBranch.centerOfMass.x *= totalMassInv;
  10342. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10343. parentBranch.centerOfMass.y *= totalMassInv;
  10344. parentBranch.mass = totalMass;
  10345. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10346. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10347. },
  10348. /**
  10349. * determine in which branch the node will be placed.
  10350. *
  10351. * @param parentBranch
  10352. * @param node
  10353. * @param skipMassUpdate
  10354. * @private
  10355. */
  10356. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10357. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10358. // update the mass of the branch.
  10359. this._updateBranchMass(parentBranch,node);
  10360. }
  10361. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10362. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10363. this._placeInRegion(parentBranch,node,"NW");
  10364. }
  10365. else { // in SW
  10366. this._placeInRegion(parentBranch,node,"SW");
  10367. }
  10368. }
  10369. else { // in NE or SE
  10370. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10371. this._placeInRegion(parentBranch,node,"NE");
  10372. }
  10373. else { // in SE
  10374. this._placeInRegion(parentBranch,node,"SE");
  10375. }
  10376. }
  10377. },
  10378. /**
  10379. * actually place the node in a region (or branch)
  10380. *
  10381. * @param parentBranch
  10382. * @param node
  10383. * @param region
  10384. * @private
  10385. */
  10386. _placeInRegion : function(parentBranch,node,region) {
  10387. switch (parentBranch.children[region].childrenCount) {
  10388. case 0: // place node here
  10389. parentBranch.children[region].children.data = node;
  10390. parentBranch.children[region].childrenCount = 1;
  10391. this._updateBranchMass(parentBranch.children[region],node);
  10392. break;
  10393. case 1: // convert into children
  10394. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10395. // we move one node a pixel and we do not put it in the tree.
  10396. if (parentBranch.children[region].children.data.x == node.x &&
  10397. parentBranch.children[region].children.data.y == node.y) {
  10398. node.x += Math.random();
  10399. node.y += Math.random();
  10400. }
  10401. else {
  10402. this._splitBranch(parentBranch.children[region]);
  10403. this._placeInTree(parentBranch.children[region],node);
  10404. }
  10405. break;
  10406. case 4: // place in branch
  10407. this._placeInTree(parentBranch.children[region],node);
  10408. break;
  10409. }
  10410. },
  10411. /**
  10412. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10413. * after the split is complete.
  10414. *
  10415. * @param parentBranch
  10416. * @private
  10417. */
  10418. _splitBranch : function(parentBranch) {
  10419. // if the branch is filled with a node, replace the node in the new subset.
  10420. var containedNode = null;
  10421. if (parentBranch.childrenCount == 1) {
  10422. containedNode = parentBranch.children.data;
  10423. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10424. }
  10425. parentBranch.childrenCount = 4;
  10426. parentBranch.children.data = null;
  10427. this._insertRegion(parentBranch,"NW");
  10428. this._insertRegion(parentBranch,"NE");
  10429. this._insertRegion(parentBranch,"SW");
  10430. this._insertRegion(parentBranch,"SE");
  10431. if (containedNode != null) {
  10432. this._placeInTree(parentBranch,containedNode);
  10433. }
  10434. },
  10435. /**
  10436. * This function subdivides the region into four new segments.
  10437. * Specifically, this inserts a single new segment.
  10438. * It fills the children section of the parentBranch
  10439. *
  10440. * @param parentBranch
  10441. * @param region
  10442. * @param parentRange
  10443. * @private
  10444. */
  10445. _insertRegion : function(parentBranch, region) {
  10446. var minX,maxX,minY,maxY;
  10447. var childSize = 0.5 * parentBranch.size;
  10448. switch (region) {
  10449. case "NW":
  10450. minX = parentBranch.range.minX;
  10451. maxX = parentBranch.range.minX + childSize;
  10452. minY = parentBranch.range.minY;
  10453. maxY = parentBranch.range.minY + childSize;
  10454. break;
  10455. case "NE":
  10456. minX = parentBranch.range.minX + childSize;
  10457. maxX = parentBranch.range.maxX;
  10458. minY = parentBranch.range.minY;
  10459. maxY = parentBranch.range.minY + childSize;
  10460. break;
  10461. case "SW":
  10462. minX = parentBranch.range.minX;
  10463. maxX = parentBranch.range.minX + childSize;
  10464. minY = parentBranch.range.minY + childSize;
  10465. maxY = parentBranch.range.maxY;
  10466. break;
  10467. case "SE":
  10468. minX = parentBranch.range.minX + childSize;
  10469. maxX = parentBranch.range.maxX;
  10470. minY = parentBranch.range.minY + childSize;
  10471. maxY = parentBranch.range.maxY;
  10472. break;
  10473. }
  10474. parentBranch.children[region] = {
  10475. centerOfMass:{x:0,y:0},
  10476. mass:0,
  10477. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10478. size: 0.5 * parentBranch.size,
  10479. calcSize: 2 * parentBranch.calcSize,
  10480. children: {data:null},
  10481. maxWidth: 0,
  10482. level: parentBranch.level+1,
  10483. childrenCount: 0
  10484. };
  10485. },
  10486. /**
  10487. * This function is for debugging purposed, it draws the tree.
  10488. *
  10489. * @param ctx
  10490. * @param color
  10491. * @private
  10492. */
  10493. _drawTree : function(ctx,color) {
  10494. if (this.barnesHutTree !== undefined) {
  10495. ctx.lineWidth = 1;
  10496. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10497. }
  10498. },
  10499. /**
  10500. * This function is for debugging purposes. It draws the branches recursively.
  10501. *
  10502. * @param branch
  10503. * @param ctx
  10504. * @param color
  10505. * @private
  10506. */
  10507. _drawBranch : function(branch,ctx,color) {
  10508. if (color === undefined) {
  10509. color = "#FF0000";
  10510. }
  10511. if (branch.childrenCount == 4) {
  10512. this._drawBranch(branch.children.NW,ctx);
  10513. this._drawBranch(branch.children.NE,ctx);
  10514. this._drawBranch(branch.children.SE,ctx);
  10515. this._drawBranch(branch.children.SW,ctx);
  10516. }
  10517. ctx.strokeStyle = color;
  10518. ctx.beginPath();
  10519. ctx.moveTo(branch.range.minX,branch.range.minY);
  10520. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10521. ctx.stroke();
  10522. ctx.beginPath();
  10523. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10524. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10525. ctx.stroke();
  10526. ctx.beginPath();
  10527. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10528. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10529. ctx.stroke();
  10530. ctx.beginPath();
  10531. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10532. ctx.lineTo(branch.range.minX,branch.range.minY);
  10533. ctx.stroke();
  10534. /*
  10535. if (branch.mass > 0) {
  10536. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  10537. ctx.stroke();
  10538. }
  10539. */
  10540. }
  10541. };
  10542. /**
  10543. * Created by Alex on 2/10/14.
  10544. */
  10545. var repulsionMixin = {
  10546. /**
  10547. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10548. * This field is linearly approximated.
  10549. *
  10550. * @private
  10551. */
  10552. _calculateNodeForces: function () {
  10553. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  10554. repulsingForce, node1, node2, i, j;
  10555. var nodes = this.calculationNodes;
  10556. var nodeIndices = this.calculationNodeIndices;
  10557. // approximation constants
  10558. var a_base = -2 / 3;
  10559. var b = 4 / 3;
  10560. // repulsing forces between nodes
  10561. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10562. var minimumDistance = nodeDistance;
  10563. // we loop from i over all but the last entree in the array
  10564. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10565. for (i = 0; i < nodeIndices.length - 1; i++) {
  10566. node1 = nodes[nodeIndices[i]];
  10567. for (j = i + 1; j < nodeIndices.length; j++) {
  10568. node2 = nodes[nodeIndices[j]];
  10569. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  10570. dx = node2.x - node1.x;
  10571. dy = node2.y - node1.y;
  10572. distance = Math.sqrt(dx * dx + dy * dy);
  10573. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  10574. var a = a_base / minimumDistance;
  10575. if (distance < 2 * minimumDistance) {
  10576. if (distance < 0.5 * minimumDistance) {
  10577. repulsingForce = 1.0;
  10578. }
  10579. else {
  10580. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10581. }
  10582. // amplify the repulsion for clusters.
  10583. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  10584. repulsingForce = repulsingForce / distance;
  10585. fx = dx * repulsingForce;
  10586. fy = dy * repulsingForce;
  10587. node1.fx -= fx;
  10588. node1.fy -= fy;
  10589. node2.fx += fx;
  10590. node2.fy += fy;
  10591. }
  10592. }
  10593. }
  10594. }
  10595. };
  10596. var HierarchicalLayoutMixin = {
  10597. _resetLevels : function() {
  10598. for (var nodeId in this.nodes) {
  10599. if (this.nodes.hasOwnProperty(nodeId)) {
  10600. var node = this.nodes[nodeId];
  10601. if (node.preassignedLevel == false) {
  10602. node.level = -1;
  10603. }
  10604. }
  10605. }
  10606. },
  10607. /**
  10608. * This is the main function to layout the nodes in a hierarchical way.
  10609. * It checks if the node details are supplied correctly
  10610. *
  10611. * @private
  10612. */
  10613. _setupHierarchicalLayout : function() {
  10614. if (this.constants.hierarchicalLayout.enabled == true) {
  10615. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  10616. this.constants.hierarchicalLayout.levelSeparation *= -1;
  10617. }
  10618. else {
  10619. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  10620. }
  10621. // get the size of the largest hubs and check if the user has defined a level for a node.
  10622. var hubsize = 0;
  10623. var node, nodeId;
  10624. var definedLevel = false;
  10625. var undefinedLevel = false;
  10626. for (nodeId in this.nodes) {
  10627. if (this.nodes.hasOwnProperty(nodeId)) {
  10628. node = this.nodes[nodeId];
  10629. if (node.level != -1) {
  10630. definedLevel = true;
  10631. }
  10632. else {
  10633. undefinedLevel = true;
  10634. }
  10635. if (hubsize < node.edges.length) {
  10636. hubsize = node.edges.length;
  10637. }
  10638. }
  10639. }
  10640. // if the user defined some levels but not all, alert and run without hierarchical layout
  10641. if (undefinedLevel == true && definedLevel == true) {
  10642. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");
  10643. this.zoomExtent(true,this.constants.clustering.enabled);
  10644. if (!this.constants.clustering.enabled) {
  10645. this.start();
  10646. }
  10647. }
  10648. else {
  10649. // setup the system to use hierarchical method.
  10650. this._changeConstants();
  10651. // define levels if undefined by the users. Based on hubsize
  10652. if (undefinedLevel == true) {
  10653. this._determineLevels(hubsize);
  10654. }
  10655. // check the distribution of the nodes per level.
  10656. var distribution = this._getDistribution();
  10657. // place the nodes on the canvas. This also stablilizes the system.
  10658. this._placeNodesByHierarchy(distribution);
  10659. // start the simulation.
  10660. this.start();
  10661. }
  10662. }
  10663. },
  10664. /**
  10665. * This function places the nodes on the canvas based on the hierarchial distribution.
  10666. *
  10667. * @param {Object} distribution | obtained by the function this._getDistribution()
  10668. * @private
  10669. */
  10670. _placeNodesByHierarchy : function(distribution) {
  10671. var nodeId, node;
  10672. // start placing all the level 0 nodes first. Then recursively position their branches.
  10673. for (nodeId in distribution[0].nodes) {
  10674. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  10675. node = distribution[0].nodes[nodeId];
  10676. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10677. if (node.xFixed) {
  10678. node.x = distribution[0].minPos;
  10679. node.xFixed = false;
  10680. distribution[0].minPos += distribution[0].nodeSpacing;
  10681. }
  10682. }
  10683. else {
  10684. if (node.yFixed) {
  10685. node.y = distribution[0].minPos;
  10686. node.yFixed = false;
  10687. distribution[0].minPos += distribution[0].nodeSpacing;
  10688. }
  10689. }
  10690. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  10691. }
  10692. }
  10693. // stabilize the system after positioning. This function calls zoomExtent.
  10694. this._stabilize();
  10695. },
  10696. /**
  10697. * This function get the distribution of levels based on hubsize
  10698. *
  10699. * @returns {Object}
  10700. * @private
  10701. */
  10702. _getDistribution : function() {
  10703. var distribution = {};
  10704. var nodeId, node, level;
  10705. // 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.
  10706. // the fix of X is removed after the x value has been set.
  10707. for (nodeId in this.nodes) {
  10708. if (this.nodes.hasOwnProperty(nodeId)) {
  10709. node = this.nodes[nodeId];
  10710. node.xFixed = true;
  10711. node.yFixed = true;
  10712. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10713. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10714. }
  10715. else {
  10716. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10717. }
  10718. if (!distribution.hasOwnProperty(node.level)) {
  10719. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  10720. }
  10721. distribution[node.level].amount += 1;
  10722. distribution[node.level].nodes[node.id] = node;
  10723. }
  10724. }
  10725. // determine the largest amount of nodes of all levels
  10726. var maxCount = 0;
  10727. for (level in distribution) {
  10728. if (distribution.hasOwnProperty(level)) {
  10729. if (maxCount < distribution[level].amount) {
  10730. maxCount = distribution[level].amount;
  10731. }
  10732. }
  10733. }
  10734. // set the initial position and spacing of each nodes accordingly
  10735. for (level in distribution) {
  10736. if (distribution.hasOwnProperty(level)) {
  10737. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  10738. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  10739. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  10740. }
  10741. }
  10742. return distribution;
  10743. },
  10744. /**
  10745. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  10746. *
  10747. * @param hubsize
  10748. * @private
  10749. */
  10750. _determineLevels : function(hubsize) {
  10751. var nodeId, node;
  10752. // determine hubs
  10753. for (nodeId in this.nodes) {
  10754. if (this.nodes.hasOwnProperty(nodeId)) {
  10755. node = this.nodes[nodeId];
  10756. if (node.edges.length == hubsize) {
  10757. node.level = 0;
  10758. }
  10759. }
  10760. }
  10761. // branch from hubs
  10762. for (nodeId in this.nodes) {
  10763. if (this.nodes.hasOwnProperty(nodeId)) {
  10764. node = this.nodes[nodeId];
  10765. if (node.level == 0) {
  10766. this._setLevel(1,node.edges,node.id);
  10767. }
  10768. }
  10769. }
  10770. },
  10771. /**
  10772. * Since hierarchical layout does not support:
  10773. * - smooth curves (based on the physics),
  10774. * - clustering (based on dynamic node counts)
  10775. *
  10776. * We disable both features so there will be no problems.
  10777. *
  10778. * @private
  10779. */
  10780. _changeConstants : function() {
  10781. this.constants.clustering.enabled = false;
  10782. this.constants.physics.barnesHut.enabled = false;
  10783. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10784. this._loadSelectedForceSolver();
  10785. this.constants.smoothCurves = false;
  10786. this._configureSmoothCurves();
  10787. },
  10788. /**
  10789. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  10790. * on a X position that ensures there will be no overlap.
  10791. *
  10792. * @param edges
  10793. * @param parentId
  10794. * @param distribution
  10795. * @param parentLevel
  10796. * @private
  10797. */
  10798. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  10799. for (var i = 0; i < edges.length; i++) {
  10800. var childNode = null;
  10801. if (edges[i].toId == parentId) {
  10802. childNode = edges[i].from;
  10803. }
  10804. else {
  10805. childNode = edges[i].to;
  10806. }
  10807. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  10808. var nodeMoved = false;
  10809. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10810. if (childNode.xFixed && childNode.level > parentLevel) {
  10811. childNode.xFixed = false;
  10812. childNode.x = distribution[childNode.level].minPos;
  10813. nodeMoved = true;
  10814. }
  10815. }
  10816. else {
  10817. if (childNode.yFixed && childNode.level > parentLevel) {
  10818. childNode.yFixed = false;
  10819. childNode.y = distribution[childNode.level].minPos;
  10820. nodeMoved = true;
  10821. }
  10822. }
  10823. if (nodeMoved == true) {
  10824. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  10825. if (childNode.edges.length > 1) {
  10826. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  10827. }
  10828. }
  10829. }
  10830. },
  10831. /**
  10832. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  10833. *
  10834. * @param level
  10835. * @param edges
  10836. * @param parentId
  10837. * @private
  10838. */
  10839. _setLevel : function(level, edges, parentId) {
  10840. for (var i = 0; i < edges.length; i++) {
  10841. var childNode = null;
  10842. if (edges[i].toId == parentId) {
  10843. childNode = edges[i].from;
  10844. }
  10845. else {
  10846. childNode = edges[i].to;
  10847. }
  10848. if (childNode.level == -1 || childNode.level > level) {
  10849. childNode.level = level;
  10850. if (edges.length > 1) {
  10851. this._setLevel(level+1, childNode.edges, childNode.id);
  10852. }
  10853. }
  10854. }
  10855. },
  10856. /**
  10857. * Unfix nodes
  10858. *
  10859. * @private
  10860. */
  10861. _restoreNodes : function() {
  10862. for (nodeId in this.nodes) {
  10863. if (this.nodes.hasOwnProperty(nodeId)) {
  10864. this.nodes[nodeId].xFixed = false;
  10865. this.nodes[nodeId].yFixed = false;
  10866. }
  10867. }
  10868. }
  10869. };
  10870. /**
  10871. * Created by Alex on 2/4/14.
  10872. */
  10873. var manipulationMixin = {
  10874. /**
  10875. * clears the toolbar div element of children
  10876. *
  10877. * @private
  10878. */
  10879. _clearManipulatorBar : function() {
  10880. while (this.manipulationDiv.hasChildNodes()) {
  10881. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  10882. }
  10883. },
  10884. /**
  10885. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  10886. * these functions to their original functionality, we saved them in this.cachedFunctions.
  10887. * This function restores these functions to their original function.
  10888. *
  10889. * @private
  10890. */
  10891. _restoreOverloadedFunctions : function() {
  10892. for (var functionName in this.cachedFunctions) {
  10893. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  10894. this[functionName] = this.cachedFunctions[functionName];
  10895. }
  10896. }
  10897. },
  10898. /**
  10899. * Enable or disable edit-mode.
  10900. *
  10901. * @private
  10902. */
  10903. _toggleEditMode : function() {
  10904. this.editMode = !this.editMode;
  10905. var toolbar = document.getElementById("graph-manipulationDiv");
  10906. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  10907. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  10908. if (this.editMode == true) {
  10909. toolbar.style.display="block";
  10910. closeDiv.style.display="block";
  10911. editModeDiv.style.display="none";
  10912. closeDiv.onclick = this._toggleEditMode.bind(this);
  10913. }
  10914. else {
  10915. toolbar.style.display="none";
  10916. closeDiv.style.display="none";
  10917. editModeDiv.style.display="block";
  10918. closeDiv.onclick = null;
  10919. }
  10920. this._createManipulatorBar()
  10921. },
  10922. /**
  10923. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  10924. *
  10925. * @private
  10926. */
  10927. _createManipulatorBar : function() {
  10928. // remove bound functions
  10929. if (this.boundFunction) {
  10930. this.off('select', this.boundFunction);
  10931. }
  10932. // restore overloaded functions
  10933. this._restoreOverloadedFunctions();
  10934. // resume calculation
  10935. this.freezeSimulation = false;
  10936. // reset global variables
  10937. this.blockConnectingEdgeSelection = false;
  10938. this.forceAppendSelection = false;
  10939. if (this.editMode == true) {
  10940. while (this.manipulationDiv.hasChildNodes()) {
  10941. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  10942. }
  10943. // add the icons to the manipulator div
  10944. this.manipulationDiv.innerHTML = "" +
  10945. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  10946. "<span class='graph-manipulationLabel'>"+this.constants.labels['add'] +"</span></span>" +
  10947. "<div class='graph-seperatorLine'></div>" +
  10948. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  10949. "<span class='graph-manipulationLabel'>"+this.constants.labels['link'] +"</span></span>";
  10950. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  10951. this.manipulationDiv.innerHTML += "" +
  10952. "<div class='graph-seperatorLine'></div>" +
  10953. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  10954. "<span class='graph-manipulationLabel'>"+this.constants.labels['editNode'] +"</span></span>";
  10955. }
  10956. if (this._selectionIsEmpty() == false) {
  10957. this.manipulationDiv.innerHTML += "" +
  10958. "<div class='graph-seperatorLine'></div>" +
  10959. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  10960. "<span class='graph-manipulationLabel'>"+this.constants.labels['del'] +"</span></span>";
  10961. }
  10962. // bind the icons
  10963. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  10964. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  10965. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  10966. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  10967. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  10968. var editButton = document.getElementById("graph-manipulate-editNode");
  10969. editButton.onclick = this._editNode.bind(this);
  10970. }
  10971. if (this._selectionIsEmpty() == false) {
  10972. var deleteButton = document.getElementById("graph-manipulate-delete");
  10973. deleteButton.onclick = this._deleteSelected.bind(this);
  10974. }
  10975. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  10976. closeDiv.onclick = this._toggleEditMode.bind(this);
  10977. this.boundFunction = this._createManipulatorBar.bind(this);
  10978. this.on('select', this.boundFunction);
  10979. }
  10980. else {
  10981. this.editModeDiv.innerHTML = "" +
  10982. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  10983. "<span class='graph-manipulationLabel'>" + this.constants.labels['edit'] + "</span></span>";
  10984. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  10985. editModeButton.onclick = this._toggleEditMode.bind(this);
  10986. }
  10987. },
  10988. /**
  10989. * Create the toolbar for adding Nodes
  10990. *
  10991. * @private
  10992. */
  10993. _createAddNodeToolbar : function() {
  10994. // clear the toolbar
  10995. this._clearManipulatorBar();
  10996. if (this.boundFunction) {
  10997. this.off('select', this.boundFunction);
  10998. }
  10999. // create the toolbar contents
  11000. this.manipulationDiv.innerHTML = "" +
  11001. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11002. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11003. "<div class='graph-seperatorLine'></div>" +
  11004. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11005. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['addDescription'] + "</span></span>";
  11006. // bind the icon
  11007. var backButton = document.getElementById("graph-manipulate-back");
  11008. backButton.onclick = this._createManipulatorBar.bind(this);
  11009. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11010. this.boundFunction = this._addNode.bind(this);
  11011. this.on('select', this.boundFunction);
  11012. },
  11013. /**
  11014. * create the toolbar to connect nodes
  11015. *
  11016. * @private
  11017. */
  11018. _createAddEdgeToolbar : function() {
  11019. // clear the toolbar
  11020. this._clearManipulatorBar();
  11021. this._unselectAll(true);
  11022. this.freezeSimulation = true;
  11023. if (this.boundFunction) {
  11024. this.off('select', this.boundFunction);
  11025. }
  11026. this._unselectAll();
  11027. this.forceAppendSelection = false;
  11028. this.blockConnectingEdgeSelection = true;
  11029. this.manipulationDiv.innerHTML = "" +
  11030. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11031. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11032. "<div class='graph-seperatorLine'></div>" +
  11033. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11034. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['linkDescription'] + "</span></span>";
  11035. // bind the icon
  11036. var backButton = document.getElementById("graph-manipulate-back");
  11037. backButton.onclick = this._createManipulatorBar.bind(this);
  11038. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11039. this.boundFunction = this._handleConnect.bind(this);
  11040. this.on('select', this.boundFunction);
  11041. // temporarily overload functions
  11042. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  11043. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  11044. this._handleTouch = this._handleConnect;
  11045. this._handleOnRelease = this._finishConnect;
  11046. // redraw to show the unselect
  11047. this._redraw();
  11048. },
  11049. /**
  11050. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11051. * to walk the user through the process.
  11052. *
  11053. * @private
  11054. */
  11055. _handleConnect : function(pointer) {
  11056. if (this._getSelectedNodeCount() == 0) {
  11057. var node = this._getNodeAt(pointer);
  11058. if (node != null) {
  11059. if (node.clusterSize > 1) {
  11060. alert("Cannot create edges to a cluster.")
  11061. }
  11062. else {
  11063. this._selectObject(node,false);
  11064. // create a node the temporary line can look at
  11065. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11066. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11067. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11068. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11069. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11070. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11071. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11072. // create a temporary edge
  11073. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11074. this.edges['connectionEdge'].from = node;
  11075. this.edges['connectionEdge'].connected = true;
  11076. this.edges['connectionEdge'].smooth = true;
  11077. this.edges['connectionEdge'].selected = true;
  11078. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11079. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11080. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11081. this._handleOnDrag = function(event) {
  11082. var pointer = this._getPointer(event.gesture.center);
  11083. this.sectors['support']['nodes']['targetNode'].x = this._canvasToX(pointer.x);
  11084. this.sectors['support']['nodes']['targetNode'].y = this._canvasToY(pointer.y);
  11085. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._canvasToX(pointer.x) + this.edges['connectionEdge'].from.x);
  11086. this.sectors['support']['nodes']['targetViaNode'].y = this._canvasToY(pointer.y);
  11087. };
  11088. this.moving = true;
  11089. this.start();
  11090. }
  11091. }
  11092. }
  11093. },
  11094. _finishConnect : function(pointer) {
  11095. if (this._getSelectedNodeCount() == 1) {
  11096. // restore the drag function
  11097. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11098. delete this.cachedFunctions["_handleOnDrag"];
  11099. // remember the edge id
  11100. var connectFromId = this.edges['connectionEdge'].fromId;
  11101. // remove the temporary nodes and edge
  11102. delete this.edges['connectionEdge'];
  11103. delete this.sectors['support']['nodes']['targetNode'];
  11104. delete this.sectors['support']['nodes']['targetViaNode'];
  11105. var node = this._getNodeAt(pointer);
  11106. if (node != null) {
  11107. if (node.clusterSize > 1) {
  11108. alert("Cannot create edges to a cluster.")
  11109. }
  11110. else {
  11111. this._createEdge(connectFromId,node.id);
  11112. this._createManipulatorBar();
  11113. }
  11114. }
  11115. this._unselectAll();
  11116. }
  11117. },
  11118. /**
  11119. * Adds a node on the specified location
  11120. */
  11121. _addNode : function() {
  11122. if (this._selectionIsEmpty() && this.editMode == true) {
  11123. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11124. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  11125. if (this.triggerFunctions.add) {
  11126. if (this.triggerFunctions.add.length == 2) {
  11127. var me = this;
  11128. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11129. me.nodesData.add(finalizedData);
  11130. me._createManipulatorBar();
  11131. me.moving = true;
  11132. me.start();
  11133. });
  11134. }
  11135. else {
  11136. alert(this.constants.labels['addError']);
  11137. this._createManipulatorBar();
  11138. this.moving = true;
  11139. this.start();
  11140. }
  11141. }
  11142. else {
  11143. this.nodesData.add(defaultData);
  11144. this._createManipulatorBar();
  11145. this.moving = true;
  11146. this.start();
  11147. }
  11148. }
  11149. },
  11150. /**
  11151. * connect two nodes with a new edge.
  11152. *
  11153. * @private
  11154. */
  11155. _createEdge : function(sourceNodeId,targetNodeId) {
  11156. if (this.editMode == true) {
  11157. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11158. if (this.triggerFunctions.connect) {
  11159. if (this.triggerFunctions.connect.length == 2) {
  11160. var me = this;
  11161. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11162. me.edgesData.add(finalizedData);
  11163. me.moving = true;
  11164. me.start();
  11165. });
  11166. }
  11167. else {
  11168. alert(this.constants.labels["linkError"]);
  11169. this.moving = true;
  11170. this.start();
  11171. }
  11172. }
  11173. else {
  11174. this.edgesData.add(defaultData);
  11175. this.moving = true;
  11176. this.start();
  11177. }
  11178. }
  11179. },
  11180. /**
  11181. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11182. *
  11183. * @private
  11184. */
  11185. _editNode : function() {
  11186. if (this.triggerFunctions.edit && this.editMode == true) {
  11187. var node = this._getSelectedNode();
  11188. var data = {id:node.id,
  11189. label: node.label,
  11190. group: node.group,
  11191. shape: node.shape,
  11192. color: {
  11193. background:node.color.background,
  11194. border:node.color.border,
  11195. highlight: {
  11196. background:node.color.highlight.background,
  11197. border:node.color.highlight.border
  11198. }
  11199. }};
  11200. if (this.triggerFunctions.edit.length == 2) {
  11201. var me = this;
  11202. this.triggerFunctions.edit(data, function (finalizedData) {
  11203. me.nodesData.update(finalizedData);
  11204. me._createManipulatorBar();
  11205. me.moving = true;
  11206. me.start();
  11207. });
  11208. }
  11209. else {
  11210. alert(this.constants.labels["editError"]);
  11211. }
  11212. }
  11213. else {
  11214. alert(this.constants.labels["editBoundError"]);
  11215. }
  11216. },
  11217. /**
  11218. * delete everything in the selection
  11219. *
  11220. * @private
  11221. */
  11222. _deleteSelected : function() {
  11223. if (!this._selectionIsEmpty() && this.editMode == true) {
  11224. if (!this._clusterInSelection()) {
  11225. var selectedNodes = this.getSelectedNodes();
  11226. var selectedEdges = this.getSelectedEdges();
  11227. if (this.triggerFunctions.del) {
  11228. var me = this;
  11229. var data = {nodes: selectedNodes, edges: selectedEdges};
  11230. if (this.triggerFunctions.del.length = 2) {
  11231. this.triggerFunctions.del(data, function (finalizedData) {
  11232. me.edgesData.remove(finalizedData.edges);
  11233. me.nodesData.remove(finalizedData.nodes);
  11234. me._unselectAll();
  11235. me.moving = true;
  11236. me.start();
  11237. });
  11238. }
  11239. else {
  11240. alert(this.constants.labels["deleteError"])
  11241. }
  11242. }
  11243. else {
  11244. this.edgesData.remove(selectedEdges);
  11245. this.nodesData.remove(selectedNodes);
  11246. this._unselectAll();
  11247. this.moving = true;
  11248. this.start();
  11249. }
  11250. }
  11251. else {
  11252. alert(this.constants.labels["deleteClusterError"]);
  11253. }
  11254. }
  11255. }
  11256. };
  11257. /**
  11258. * Creation of the SectorMixin var.
  11259. *
  11260. * This contains all the functions the Graph object can use to employ the sector system.
  11261. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11262. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11263. *
  11264. * Alex de Mulder
  11265. * 21-01-2013
  11266. */
  11267. var SectorMixin = {
  11268. /**
  11269. * This function is only called by the setData function of the Graph object.
  11270. * This loads the global references into the active sector. This initializes the sector.
  11271. *
  11272. * @private
  11273. */
  11274. _putDataInSector : function() {
  11275. this.sectors["active"][this._sector()].nodes = this.nodes;
  11276. this.sectors["active"][this._sector()].edges = this.edges;
  11277. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11278. },
  11279. /**
  11280. * /**
  11281. * This function sets the global references to nodes, edges and nodeIndices back to
  11282. * those of the supplied (active) sector. If a type is defined, do the specific type
  11283. *
  11284. * @param {String} sectorId
  11285. * @param {String} [sectorType] | "active" or "frozen"
  11286. * @private
  11287. */
  11288. _switchToSector : function(sectorId, sectorType) {
  11289. if (sectorType === undefined || sectorType == "active") {
  11290. this._switchToActiveSector(sectorId);
  11291. }
  11292. else {
  11293. this._switchToFrozenSector(sectorId);
  11294. }
  11295. },
  11296. /**
  11297. * This function sets the global references to nodes, edges and nodeIndices back to
  11298. * those of the supplied active sector.
  11299. *
  11300. * @param sectorId
  11301. * @private
  11302. */
  11303. _switchToActiveSector : function(sectorId) {
  11304. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11305. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11306. this.edges = this.sectors["active"][sectorId]["edges"];
  11307. },
  11308. /**
  11309. * This function sets the global references to nodes, edges and nodeIndices back to
  11310. * those of the supplied active sector.
  11311. *
  11312. * @param sectorId
  11313. * @private
  11314. */
  11315. _switchToSupportSector : function() {
  11316. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11317. this.nodes = this.sectors["support"]["nodes"];
  11318. this.edges = this.sectors["support"]["edges"];
  11319. },
  11320. /**
  11321. * This function sets the global references to nodes, edges and nodeIndices back to
  11322. * those of the supplied frozen sector.
  11323. *
  11324. * @param sectorId
  11325. * @private
  11326. */
  11327. _switchToFrozenSector : function(sectorId) {
  11328. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11329. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11330. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11331. },
  11332. /**
  11333. * This function sets the global references to nodes, edges and nodeIndices back to
  11334. * those of the currently active sector.
  11335. *
  11336. * @private
  11337. */
  11338. _loadLatestSector : function() {
  11339. this._switchToSector(this._sector());
  11340. },
  11341. /**
  11342. * This function returns the currently active sector Id
  11343. *
  11344. * @returns {String}
  11345. * @private
  11346. */
  11347. _sector : function() {
  11348. return this.activeSector[this.activeSector.length-1];
  11349. },
  11350. /**
  11351. * This function returns the previously active sector Id
  11352. *
  11353. * @returns {String}
  11354. * @private
  11355. */
  11356. _previousSector : function() {
  11357. if (this.activeSector.length > 1) {
  11358. return this.activeSector[this.activeSector.length-2];
  11359. }
  11360. else {
  11361. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11362. }
  11363. },
  11364. /**
  11365. * We add the active sector at the end of the this.activeSector array
  11366. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11367. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11368. *
  11369. * @param newId
  11370. * @private
  11371. */
  11372. _setActiveSector : function(newId) {
  11373. this.activeSector.push(newId);
  11374. },
  11375. /**
  11376. * We remove the currently active sector id from the active sector stack. This happens when
  11377. * we reactivate the previously active sector
  11378. *
  11379. * @private
  11380. */
  11381. _forgetLastSector : function() {
  11382. this.activeSector.pop();
  11383. },
  11384. /**
  11385. * This function creates a new active sector with the supplied newId. This newId
  11386. * is the expanding node id.
  11387. *
  11388. * @param {String} newId | Id of the new active sector
  11389. * @private
  11390. */
  11391. _createNewSector : function(newId) {
  11392. // create the new sector
  11393. this.sectors["active"][newId] = {"nodes":{},
  11394. "edges":{},
  11395. "nodeIndices":[],
  11396. "formationScale": this.scale,
  11397. "drawingNode": undefined};
  11398. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11399. this.sectors["active"][newId]['drawingNode'] = new Node(
  11400. {id:newId,
  11401. color: {
  11402. background: "#eaefef",
  11403. border: "495c5e"
  11404. }
  11405. },{},{},this.constants);
  11406. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11407. },
  11408. /**
  11409. * This function removes the currently active sector. This is called when we create a new
  11410. * active sector.
  11411. *
  11412. * @param {String} sectorId | Id of the active sector that will be removed
  11413. * @private
  11414. */
  11415. _deleteActiveSector : function(sectorId) {
  11416. delete this.sectors["active"][sectorId];
  11417. },
  11418. /**
  11419. * This function removes the currently active sector. This is called when we reactivate
  11420. * the previously active sector.
  11421. *
  11422. * @param {String} sectorId | Id of the active sector that will be removed
  11423. * @private
  11424. */
  11425. _deleteFrozenSector : function(sectorId) {
  11426. delete this.sectors["frozen"][sectorId];
  11427. },
  11428. /**
  11429. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11430. * We copy the references, then delete the active entree.
  11431. *
  11432. * @param sectorId
  11433. * @private
  11434. */
  11435. _freezeSector : function(sectorId) {
  11436. // we move the set references from the active to the frozen stack.
  11437. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11438. // we have moved the sector data into the frozen set, we now remove it from the active set
  11439. this._deleteActiveSector(sectorId);
  11440. },
  11441. /**
  11442. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11443. * object to the "active" object.
  11444. *
  11445. * @param sectorId
  11446. * @private
  11447. */
  11448. _activateSector : function(sectorId) {
  11449. // we move the set references from the frozen to the active stack.
  11450. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11451. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11452. this._deleteFrozenSector(sectorId);
  11453. },
  11454. /**
  11455. * This function merges the data from the currently active sector with a frozen sector. This is used
  11456. * in the process of reverting back to the previously active sector.
  11457. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11458. * upon the creation of a new active sector.
  11459. *
  11460. * @param sectorId
  11461. * @private
  11462. */
  11463. _mergeThisWithFrozen : function(sectorId) {
  11464. // copy all nodes
  11465. for (var nodeId in this.nodes) {
  11466. if (this.nodes.hasOwnProperty(nodeId)) {
  11467. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11468. }
  11469. }
  11470. // copy all edges (if not fully clustered, else there are no edges)
  11471. for (var edgeId in this.edges) {
  11472. if (this.edges.hasOwnProperty(edgeId)) {
  11473. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11474. }
  11475. }
  11476. // merge the nodeIndices
  11477. for (var i = 0; i < this.nodeIndices.length; i++) {
  11478. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11479. }
  11480. },
  11481. /**
  11482. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11483. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11484. *
  11485. * @private
  11486. */
  11487. _collapseThisToSingleCluster : function() {
  11488. this.clusterToFit(1,false);
  11489. },
  11490. /**
  11491. * We create a new active sector from the node that we want to open.
  11492. *
  11493. * @param node
  11494. * @private
  11495. */
  11496. _addSector : function(node) {
  11497. // this is the currently active sector
  11498. var sector = this._sector();
  11499. // // this should allow me to select nodes from a frozen set.
  11500. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11501. // console.log("the node is part of the active sector");
  11502. // }
  11503. // else {
  11504. // console.log("I dont know what the fuck happened!!");
  11505. // }
  11506. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11507. delete this.nodes[node.id];
  11508. var unqiueIdentifier = util.randomUUID();
  11509. // we fully freeze the currently active sector
  11510. this._freezeSector(sector);
  11511. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11512. this._createNewSector(unqiueIdentifier);
  11513. // we add the active sector to the sectors array to be able to revert these steps later on
  11514. this._setActiveSector(unqiueIdentifier);
  11515. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11516. this._switchToSector(this._sector());
  11517. // finally we add the node we removed from our previous active sector to the new active sector
  11518. this.nodes[node.id] = node;
  11519. },
  11520. /**
  11521. * We close the sector that is currently open and revert back to the one before.
  11522. * If the active sector is the "default" sector, nothing happens.
  11523. *
  11524. * @private
  11525. */
  11526. _collapseSector : function() {
  11527. // the currently active sector
  11528. var sector = this._sector();
  11529. // we cannot collapse the default sector
  11530. if (sector != "default") {
  11531. if ((this.nodeIndices.length == 1) ||
  11532. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11533. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11534. var previousSector = this._previousSector();
  11535. // we collapse the sector back to a single cluster
  11536. this._collapseThisToSingleCluster();
  11537. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  11538. // This previous sector is the one we will reactivate
  11539. this._mergeThisWithFrozen(previousSector);
  11540. // the previously active (frozen) sector now has all the data from the currently active sector.
  11541. // we can now delete the active sector.
  11542. this._deleteActiveSector(sector);
  11543. // we activate the previously active (and currently frozen) sector.
  11544. this._activateSector(previousSector);
  11545. // we load the references from the newly active sector into the global references
  11546. this._switchToSector(previousSector);
  11547. // we forget the previously active sector because we reverted to the one before
  11548. this._forgetLastSector();
  11549. // finally, we update the node index list.
  11550. this._updateNodeIndexList();
  11551. // we refresh the list with calulation nodes and calculation node indices.
  11552. this._updateCalculationNodes();
  11553. }
  11554. }
  11555. },
  11556. /**
  11557. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11558. *
  11559. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11560. * | we dont pass the function itself because then the "this" is the window object
  11561. * | instead of the Graph object
  11562. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11563. * @private
  11564. */
  11565. _doInAllActiveSectors : function(runFunction,argument) {
  11566. if (argument === undefined) {
  11567. for (var sector in this.sectors["active"]) {
  11568. if (this.sectors["active"].hasOwnProperty(sector)) {
  11569. // switch the global references to those of this sector
  11570. this._switchToActiveSector(sector);
  11571. this[runFunction]();
  11572. }
  11573. }
  11574. }
  11575. else {
  11576. for (var sector in this.sectors["active"]) {
  11577. if (this.sectors["active"].hasOwnProperty(sector)) {
  11578. // switch the global references to those of this sector
  11579. this._switchToActiveSector(sector);
  11580. var args = Array.prototype.splice.call(arguments, 1);
  11581. if (args.length > 1) {
  11582. this[runFunction](args[0],args[1]);
  11583. }
  11584. else {
  11585. this[runFunction](argument);
  11586. }
  11587. }
  11588. }
  11589. }
  11590. // we revert the global references back to our active sector
  11591. this._loadLatestSector();
  11592. },
  11593. /**
  11594. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11595. *
  11596. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11597. * | we dont pass the function itself because then the "this" is the window object
  11598. * | instead of the Graph object
  11599. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11600. * @private
  11601. */
  11602. _doInSupportSector : function(runFunction,argument) {
  11603. if (argument === undefined) {
  11604. this._switchToSupportSector();
  11605. this[runFunction]();
  11606. }
  11607. else {
  11608. this._switchToSupportSector();
  11609. var args = Array.prototype.splice.call(arguments, 1);
  11610. if (args.length > 1) {
  11611. this[runFunction](args[0],args[1]);
  11612. }
  11613. else {
  11614. this[runFunction](argument);
  11615. }
  11616. }
  11617. // we revert the global references back to our active sector
  11618. this._loadLatestSector();
  11619. },
  11620. /**
  11621. * This runs a function in all frozen sectors. This is used in the _redraw().
  11622. *
  11623. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11624. * | we don't pass the function itself because then the "this" is the window object
  11625. * | instead of the Graph object
  11626. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11627. * @private
  11628. */
  11629. _doInAllFrozenSectors : function(runFunction,argument) {
  11630. if (argument === undefined) {
  11631. for (var sector in this.sectors["frozen"]) {
  11632. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11633. // switch the global references to those of this sector
  11634. this._switchToFrozenSector(sector);
  11635. this[runFunction]();
  11636. }
  11637. }
  11638. }
  11639. else {
  11640. for (var sector in this.sectors["frozen"]) {
  11641. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11642. // switch the global references to those of this sector
  11643. this._switchToFrozenSector(sector);
  11644. var args = Array.prototype.splice.call(arguments, 1);
  11645. if (args.length > 1) {
  11646. this[runFunction](args[0],args[1]);
  11647. }
  11648. else {
  11649. this[runFunction](argument);
  11650. }
  11651. }
  11652. }
  11653. }
  11654. this._loadLatestSector();
  11655. },
  11656. /**
  11657. * This runs a function in all sectors. This is used in the _redraw().
  11658. *
  11659. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11660. * | we don't pass the function itself because then the "this" is the window object
  11661. * | instead of the Graph object
  11662. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11663. * @private
  11664. */
  11665. _doInAllSectors : function(runFunction,argument) {
  11666. var args = Array.prototype.splice.call(arguments, 1);
  11667. if (argument === undefined) {
  11668. this._doInAllActiveSectors(runFunction);
  11669. this._doInAllFrozenSectors(runFunction);
  11670. }
  11671. else {
  11672. if (args.length > 1) {
  11673. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  11674. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  11675. }
  11676. else {
  11677. this._doInAllActiveSectors(runFunction,argument);
  11678. this._doInAllFrozenSectors(runFunction,argument);
  11679. }
  11680. }
  11681. },
  11682. /**
  11683. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  11684. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  11685. *
  11686. * @private
  11687. */
  11688. _clearNodeIndexList : function() {
  11689. var sector = this._sector();
  11690. this.sectors["active"][sector]["nodeIndices"] = [];
  11691. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  11692. },
  11693. /**
  11694. * Draw the encompassing sector node
  11695. *
  11696. * @param ctx
  11697. * @param sectorType
  11698. * @private
  11699. */
  11700. _drawSectorNodes : function(ctx,sectorType) {
  11701. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11702. for (var sector in this.sectors[sectorType]) {
  11703. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  11704. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  11705. this._switchToSector(sector,sectorType);
  11706. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  11707. for (var nodeId in this.nodes) {
  11708. if (this.nodes.hasOwnProperty(nodeId)) {
  11709. node = this.nodes[nodeId];
  11710. node.resize(ctx);
  11711. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  11712. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  11713. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  11714. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  11715. }
  11716. }
  11717. node = this.sectors[sectorType][sector]["drawingNode"];
  11718. node.x = 0.5 * (maxX + minX);
  11719. node.y = 0.5 * (maxY + minY);
  11720. node.width = 2 * (node.x - minX);
  11721. node.height = 2 * (node.y - minY);
  11722. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  11723. node.setScale(this.scale);
  11724. node._drawCircle(ctx);
  11725. }
  11726. }
  11727. }
  11728. },
  11729. _drawAllSectorNodes : function(ctx) {
  11730. this._drawSectorNodes(ctx,"frozen");
  11731. this._drawSectorNodes(ctx,"active");
  11732. this._loadLatestSector();
  11733. }
  11734. };
  11735. /**
  11736. * Creation of the ClusterMixin var.
  11737. *
  11738. * This contains all the functions the Graph object can use to employ clustering
  11739. *
  11740. * Alex de Mulder
  11741. * 21-01-2013
  11742. */
  11743. var ClusterMixin = {
  11744. /**
  11745. * This is only called in the constructor of the graph object
  11746. *
  11747. */
  11748. startWithClustering : function() {
  11749. // cluster if the data set is big
  11750. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  11751. // updates the lables after clustering
  11752. this.updateLabels();
  11753. // this is called here because if clusterin is disabled, the start and stabilize are called in
  11754. // the setData function.
  11755. if (this.stabilize) {
  11756. this._stabilize();
  11757. }
  11758. this.start();
  11759. },
  11760. /**
  11761. * This function clusters until the initialMaxNodes has been reached
  11762. *
  11763. * @param {Number} maxNumberOfNodes
  11764. * @param {Boolean} reposition
  11765. */
  11766. clusterToFit : function(maxNumberOfNodes, reposition) {
  11767. var numberOfNodes = this.nodeIndices.length;
  11768. var maxLevels = 50;
  11769. var level = 0;
  11770. // we first cluster the hubs, then we pull in the outliers, repeat
  11771. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  11772. if (level % 3 == 0) {
  11773. this.forceAggregateHubs(true);
  11774. this.normalizeClusterLevels();
  11775. }
  11776. else {
  11777. this.increaseClusterLevel(); // this also includes a cluster normalization
  11778. }
  11779. numberOfNodes = this.nodeIndices.length;
  11780. level += 1;
  11781. }
  11782. // after the clustering we reposition the nodes to reduce the initial chaos
  11783. if (level > 0 && reposition == true) {
  11784. this.repositionNodes();
  11785. }
  11786. this._updateCalculationNodes();
  11787. },
  11788. /**
  11789. * This function can be called to open up a specific cluster. It is only called by
  11790. * It will unpack the cluster back one level.
  11791. *
  11792. * @param node | Node object: cluster to open.
  11793. */
  11794. openCluster : function(node) {
  11795. var isMovingBeforeClustering = this.moving;
  11796. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  11797. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  11798. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  11799. this._addSector(node);
  11800. var level = 0;
  11801. // we decluster until we reach a decent number of nodes
  11802. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  11803. this.decreaseClusterLevel();
  11804. level += 1;
  11805. }
  11806. }
  11807. else {
  11808. this._expandClusterNode(node,false,true);
  11809. // update the index list, dynamic edges and labels
  11810. this._updateNodeIndexList();
  11811. this._updateDynamicEdges();
  11812. this._updateCalculationNodes();
  11813. this.updateLabels();
  11814. }
  11815. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11816. if (this.moving != isMovingBeforeClustering) {
  11817. this.start();
  11818. }
  11819. },
  11820. /**
  11821. * This calls the updateClustes with default arguments
  11822. */
  11823. updateClustersDefault : function() {
  11824. if (this.constants.clustering.enabled == true) {
  11825. this.updateClusters(0,false,false);
  11826. }
  11827. },
  11828. /**
  11829. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  11830. * be clustered with their connected node. This can be repeated as many times as needed.
  11831. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  11832. */
  11833. increaseClusterLevel : function() {
  11834. this.updateClusters(-1,false,true);
  11835. },
  11836. /**
  11837. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  11838. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  11839. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  11840. */
  11841. decreaseClusterLevel : function() {
  11842. this.updateClusters(1,false,true);
  11843. },
  11844. /**
  11845. * This is the main clustering function. It clusters and declusters on zoom or forced
  11846. * This function clusters on zoom, it can be called with a predefined zoom direction
  11847. * If out, check if we can form clusters, if in, check if we can open clusters.
  11848. * This function is only called from _zoom()
  11849. *
  11850. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  11851. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  11852. * @param {Boolean} force | enabled or disable forcing
  11853. * @param {Boolean} doNotStart | if true do not call start
  11854. *
  11855. */
  11856. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  11857. var isMovingBeforeClustering = this.moving;
  11858. var amountOfNodes = this.nodeIndices.length;
  11859. // on zoom out collapse the sector if the scale is at the level the sector was made
  11860. if (this.previousScale > this.scale && zoomDirection == 0) {
  11861. this._collapseSector();
  11862. }
  11863. // check if we zoom in or out
  11864. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  11865. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  11866. // outer nodes determines if it is being clustered
  11867. this._formClusters(force);
  11868. }
  11869. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  11870. if (force == true) {
  11871. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  11872. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  11873. this._openClusters(recursive,force);
  11874. }
  11875. else {
  11876. // if a cluster takes up a set percentage of the active window
  11877. this._openClustersBySize();
  11878. }
  11879. }
  11880. this._updateNodeIndexList();
  11881. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  11882. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  11883. this._aggregateHubs(force);
  11884. this._updateNodeIndexList();
  11885. }
  11886. // we now reduce chains.
  11887. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  11888. this.handleChains();
  11889. this._updateNodeIndexList();
  11890. }
  11891. this.previousScale = this.scale;
  11892. // rest of the update the index list, dynamic edges and labels
  11893. this._updateDynamicEdges();
  11894. this.updateLabels();
  11895. // if a cluster was formed, we increase the clusterSession
  11896. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  11897. this.clusterSession += 1;
  11898. // if clusters have been made, we normalize the cluster level
  11899. this.normalizeClusterLevels();
  11900. }
  11901. if (doNotStart == false || doNotStart === undefined) {
  11902. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11903. if (this.moving != isMovingBeforeClustering) {
  11904. this.start();
  11905. }
  11906. }
  11907. this._updateCalculationNodes();
  11908. },
  11909. /**
  11910. * This function handles the chains. It is called on every updateClusters().
  11911. */
  11912. handleChains : function() {
  11913. // after clustering we check how many chains there are
  11914. var chainPercentage = this._getChainFraction();
  11915. if (chainPercentage > this.constants.clustering.chainThreshold) {
  11916. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  11917. }
  11918. },
  11919. /**
  11920. * this functions starts clustering by hubs
  11921. * The minimum hub threshold is set globally
  11922. *
  11923. * @private
  11924. */
  11925. _aggregateHubs : function(force) {
  11926. this._getHubSize();
  11927. this._formClustersByHub(force,false);
  11928. },
  11929. /**
  11930. * This function is fired by keypress. It forces hubs to form.
  11931. *
  11932. */
  11933. forceAggregateHubs : function(doNotStart) {
  11934. var isMovingBeforeClustering = this.moving;
  11935. var amountOfNodes = this.nodeIndices.length;
  11936. this._aggregateHubs(true);
  11937. // update the index list, dynamic edges and labels
  11938. this._updateNodeIndexList();
  11939. this._updateDynamicEdges();
  11940. this.updateLabels();
  11941. // if a cluster was formed, we increase the clusterSession
  11942. if (this.nodeIndices.length != amountOfNodes) {
  11943. this.clusterSession += 1;
  11944. }
  11945. if (doNotStart == false || doNotStart === undefined) {
  11946. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11947. if (this.moving != isMovingBeforeClustering) {
  11948. this.start();
  11949. }
  11950. }
  11951. },
  11952. /**
  11953. * If a cluster takes up more than a set percentage of the screen, open the cluster
  11954. *
  11955. * @private
  11956. */
  11957. _openClustersBySize : function() {
  11958. for (var nodeId in this.nodes) {
  11959. if (this.nodes.hasOwnProperty(nodeId)) {
  11960. var node = this.nodes[nodeId];
  11961. if (node.inView() == true) {
  11962. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11963. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11964. this.openCluster(node);
  11965. }
  11966. }
  11967. }
  11968. }
  11969. },
  11970. /**
  11971. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  11972. * has to be opened based on the current zoom level.
  11973. *
  11974. * @private
  11975. */
  11976. _openClusters : function(recursive,force) {
  11977. for (var i = 0; i < this.nodeIndices.length; i++) {
  11978. var node = this.nodes[this.nodeIndices[i]];
  11979. this._expandClusterNode(node,recursive,force);
  11980. this._updateCalculationNodes();
  11981. }
  11982. },
  11983. /**
  11984. * This function checks if a node has to be opened. This is done by checking the zoom level.
  11985. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  11986. * This recursive behaviour is optional and can be set by the recursive argument.
  11987. *
  11988. * @param {Node} parentNode | to check for cluster and expand
  11989. * @param {Boolean} recursive | enabled or disable recursive calling
  11990. * @param {Boolean} force | enabled or disable forcing
  11991. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  11992. * @private
  11993. */
  11994. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  11995. // first check if node is a cluster
  11996. if (parentNode.clusterSize > 1) {
  11997. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  11998. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  11999. openAll = true;
  12000. }
  12001. recursive = openAll ? true : recursive;
  12002. // if the last child has been added on a smaller scale than current scale decluster
  12003. if (parentNode.formationScale < this.scale || force == true) {
  12004. // we will check if any of the contained child nodes should be removed from the cluster
  12005. for (var containedNodeId in parentNode.containedNodes) {
  12006. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  12007. var childNode = parentNode.containedNodes[containedNodeId];
  12008. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  12009. // the largest cluster is the one that comes from outside
  12010. if (force == true) {
  12011. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  12012. || openAll) {
  12013. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12014. }
  12015. }
  12016. else {
  12017. if (this._nodeInActiveArea(parentNode)) {
  12018. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12019. }
  12020. }
  12021. }
  12022. }
  12023. }
  12024. }
  12025. },
  12026. /**
  12027. * ONLY CALLED FROM _expandClusterNode
  12028. *
  12029. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  12030. * the child node from the parent contained_node object and put it back into the global nodes object.
  12031. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  12032. *
  12033. * @param {Node} parentNode | the parent node
  12034. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  12035. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  12036. * With force and recursive both true, the entire cluster is unpacked
  12037. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  12038. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  12039. * @private
  12040. */
  12041. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  12042. var childNode = parentNode.containedNodes[containedNodeId];
  12043. // if child node has been added on smaller scale than current, kick out
  12044. if (childNode.formationScale < this.scale || force == true) {
  12045. // unselect all selected items
  12046. this._unselectAll();
  12047. // put the child node back in the global nodes object
  12048. this.nodes[containedNodeId] = childNode;
  12049. // release the contained edges from this childNode back into the global edges
  12050. this._releaseContainedEdges(parentNode,childNode);
  12051. // reconnect rerouted edges to the childNode
  12052. this._connectEdgeBackToChild(parentNode,childNode);
  12053. // validate all edges in dynamicEdges
  12054. this._validateEdges(parentNode);
  12055. // undo the changes from the clustering operation on the parent node
  12056. parentNode.mass -= childNode.mass;
  12057. parentNode.clusterSize -= childNode.clusterSize;
  12058. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12059. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12060. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12061. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12062. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12063. // remove node from the list
  12064. delete parentNode.containedNodes[containedNodeId];
  12065. // check if there are other childs with this clusterSession in the parent.
  12066. var othersPresent = false;
  12067. for (var childNodeId in parentNode.containedNodes) {
  12068. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12069. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12070. othersPresent = true;
  12071. break;
  12072. }
  12073. }
  12074. }
  12075. // if there are no others, remove the cluster session from the list
  12076. if (othersPresent == false) {
  12077. parentNode.clusterSessions.pop();
  12078. }
  12079. this._repositionBezierNodes(childNode);
  12080. // this._repositionBezierNodes(parentNode);
  12081. // remove the clusterSession from the child node
  12082. childNode.clusterSession = 0;
  12083. // recalculate the size of the node on the next time the node is rendered
  12084. parentNode.clearSizeCache();
  12085. // restart the simulation to reorganise all nodes
  12086. this.moving = true;
  12087. }
  12088. // check if a further expansion step is possible if recursivity is enabled
  12089. if (recursive == true) {
  12090. this._expandClusterNode(childNode,recursive,force,openAll);
  12091. }
  12092. },
  12093. /**
  12094. * position the bezier nodes at the center of the edges
  12095. *
  12096. * @param node
  12097. * @private
  12098. */
  12099. _repositionBezierNodes : function(node) {
  12100. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12101. node.dynamicEdges[i].positionBezierNode();
  12102. }
  12103. },
  12104. /**
  12105. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12106. * This function is called only from updateClusters()
  12107. * forceLevelCollapse ignores the length of the edge and collapses one level
  12108. * This means that a node with only one edge will be clustered with its connected node
  12109. *
  12110. * @private
  12111. * @param {Boolean} force
  12112. */
  12113. _formClusters : function(force) {
  12114. if (force == false) {
  12115. this._formClustersByZoom();
  12116. }
  12117. else {
  12118. this._forceClustersByZoom();
  12119. }
  12120. },
  12121. /**
  12122. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12123. *
  12124. * @private
  12125. */
  12126. _formClustersByZoom : function() {
  12127. var dx,dy,length,
  12128. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12129. // check if any edges are shorter than minLength and start the clustering
  12130. // the clustering favours the node with the larger mass
  12131. for (var edgeId in this.edges) {
  12132. if (this.edges.hasOwnProperty(edgeId)) {
  12133. var edge = this.edges[edgeId];
  12134. if (edge.connected) {
  12135. if (edge.toId != edge.fromId) {
  12136. dx = (edge.to.x - edge.from.x);
  12137. dy = (edge.to.y - edge.from.y);
  12138. length = Math.sqrt(dx * dx + dy * dy);
  12139. if (length < minLength) {
  12140. // first check which node is larger
  12141. var parentNode = edge.from;
  12142. var childNode = edge.to;
  12143. if (edge.to.mass > edge.from.mass) {
  12144. parentNode = edge.to;
  12145. childNode = edge.from;
  12146. }
  12147. if (childNode.dynamicEdgesLength == 1) {
  12148. this._addToCluster(parentNode,childNode,false);
  12149. }
  12150. else if (parentNode.dynamicEdgesLength == 1) {
  12151. this._addToCluster(childNode,parentNode,false);
  12152. }
  12153. }
  12154. }
  12155. }
  12156. }
  12157. }
  12158. },
  12159. /**
  12160. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12161. * connected node.
  12162. *
  12163. * @private
  12164. */
  12165. _forceClustersByZoom : function() {
  12166. for (var nodeId in this.nodes) {
  12167. // another node could have absorbed this child.
  12168. if (this.nodes.hasOwnProperty(nodeId)) {
  12169. var childNode = this.nodes[nodeId];
  12170. // the edges can be swallowed by another decrease
  12171. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12172. var edge = childNode.dynamicEdges[0];
  12173. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12174. // group to the largest node
  12175. if (childNode.id != parentNode.id) {
  12176. if (parentNode.mass > childNode.mass) {
  12177. this._addToCluster(parentNode,childNode,true);
  12178. }
  12179. else {
  12180. this._addToCluster(childNode,parentNode,true);
  12181. }
  12182. }
  12183. }
  12184. }
  12185. }
  12186. },
  12187. /**
  12188. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12189. * This function clusters a node to its smallest connected neighbour.
  12190. *
  12191. * @param node
  12192. * @private
  12193. */
  12194. _clusterToSmallestNeighbour : function(node) {
  12195. var smallestNeighbour = -1;
  12196. var smallestNeighbourNode = null;
  12197. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12198. if (node.dynamicEdges[i] !== undefined) {
  12199. var neighbour = null;
  12200. if (node.dynamicEdges[i].fromId != node.id) {
  12201. neighbour = node.dynamicEdges[i].from;
  12202. }
  12203. else if (node.dynamicEdges[i].toId != node.id) {
  12204. neighbour = node.dynamicEdges[i].to;
  12205. }
  12206. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12207. smallestNeighbour = neighbour.clusterSessions.length;
  12208. smallestNeighbourNode = neighbour;
  12209. }
  12210. }
  12211. }
  12212. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12213. this._addToCluster(neighbour, node, true);
  12214. }
  12215. },
  12216. /**
  12217. * This function forms clusters from hubs, it loops over all nodes
  12218. *
  12219. * @param {Boolean} force | Disregard zoom level
  12220. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12221. * @private
  12222. */
  12223. _formClustersByHub : function(force, onlyEqual) {
  12224. // we loop over all nodes in the list
  12225. for (var nodeId in this.nodes) {
  12226. // we check if it is still available since it can be used by the clustering in this loop
  12227. if (this.nodes.hasOwnProperty(nodeId)) {
  12228. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12229. }
  12230. }
  12231. },
  12232. /**
  12233. * This function forms a cluster from a specific preselected hub node
  12234. *
  12235. * @param {Node} hubNode | the node we will cluster as a hub
  12236. * @param {Boolean} force | Disregard zoom level
  12237. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12238. * @param {Number} [absorptionSizeOffset] |
  12239. * @private
  12240. */
  12241. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12242. if (absorptionSizeOffset === undefined) {
  12243. absorptionSizeOffset = 0;
  12244. }
  12245. // we decide if the node is a hub
  12246. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12247. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12248. // initialize variables
  12249. var dx,dy,length;
  12250. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12251. var allowCluster = false;
  12252. // we create a list of edges because the dynamicEdges change over the course of this loop
  12253. var edgesIdarray = [];
  12254. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12255. for (var j = 0; j < amountOfInitialEdges; j++) {
  12256. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12257. }
  12258. // if the hub clustering is not forces, we check if one of the edges connected
  12259. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12260. if (force == false) {
  12261. allowCluster = false;
  12262. for (j = 0; j < amountOfInitialEdges; j++) {
  12263. var edge = this.edges[edgesIdarray[j]];
  12264. if (edge !== undefined) {
  12265. if (edge.connected) {
  12266. if (edge.toId != edge.fromId) {
  12267. dx = (edge.to.x - edge.from.x);
  12268. dy = (edge.to.y - edge.from.y);
  12269. length = Math.sqrt(dx * dx + dy * dy);
  12270. if (length < minLength) {
  12271. allowCluster = true;
  12272. break;
  12273. }
  12274. }
  12275. }
  12276. }
  12277. }
  12278. }
  12279. // start the clustering if allowed
  12280. if ((!force && allowCluster) || force) {
  12281. // we loop over all edges INITIALLY connected to this hub
  12282. for (j = 0; j < amountOfInitialEdges; j++) {
  12283. edge = this.edges[edgesIdarray[j]];
  12284. // the edge can be clustered by this function in a previous loop
  12285. if (edge !== undefined) {
  12286. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12287. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12288. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12289. (childNode.id != hubNode.id)) {
  12290. this._addToCluster(hubNode,childNode,force);
  12291. }
  12292. }
  12293. }
  12294. }
  12295. }
  12296. },
  12297. /**
  12298. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12299. *
  12300. * @param {Node} parentNode | this is the node that will house the child node
  12301. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12302. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12303. * @private
  12304. */
  12305. _addToCluster : function(parentNode, childNode, force) {
  12306. // join child node in the parent node
  12307. parentNode.containedNodes[childNode.id] = childNode;
  12308. // manage all the edges connected to the child and parent nodes
  12309. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12310. var edge = childNode.dynamicEdges[i];
  12311. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12312. this._addToContainedEdges(parentNode,childNode,edge);
  12313. }
  12314. else {
  12315. this._connectEdgeToCluster(parentNode,childNode,edge);
  12316. }
  12317. }
  12318. // a contained node has no dynamic edges.
  12319. childNode.dynamicEdges = [];
  12320. // remove circular edges from clusters
  12321. this._containCircularEdgesFromNode(parentNode,childNode);
  12322. // remove the childNode from the global nodes object
  12323. delete this.nodes[childNode.id];
  12324. // update the properties of the child and parent
  12325. var massBefore = parentNode.mass;
  12326. childNode.clusterSession = this.clusterSession;
  12327. parentNode.mass += childNode.mass;
  12328. parentNode.clusterSize += childNode.clusterSize;
  12329. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12330. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12331. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12332. parentNode.clusterSessions.push(this.clusterSession);
  12333. }
  12334. // forced clusters only open from screen size and double tap
  12335. if (force == true) {
  12336. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12337. parentNode.formationScale = 0;
  12338. }
  12339. else {
  12340. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12341. }
  12342. // recalculate the size of the node on the next time the node is rendered
  12343. parentNode.clearSizeCache();
  12344. // set the pop-out scale for the childnode
  12345. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12346. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12347. childNode.clearVelocity();
  12348. // the mass has altered, preservation of energy dictates the velocity to be updated
  12349. parentNode.updateVelocity(massBefore);
  12350. // restart the simulation to reorganise all nodes
  12351. this.moving = true;
  12352. },
  12353. /**
  12354. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12355. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12356. * It has to be called if a level is collapsed. It is called by _formClusters().
  12357. * @private
  12358. */
  12359. _updateDynamicEdges : function() {
  12360. for (var i = 0; i < this.nodeIndices.length; i++) {
  12361. var node = this.nodes[this.nodeIndices[i]];
  12362. node.dynamicEdgesLength = node.dynamicEdges.length;
  12363. // this corrects for multiple edges pointing at the same other node
  12364. var correction = 0;
  12365. if (node.dynamicEdgesLength > 1) {
  12366. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12367. var edgeToId = node.dynamicEdges[j].toId;
  12368. var edgeFromId = node.dynamicEdges[j].fromId;
  12369. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12370. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12371. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12372. correction += 1;
  12373. }
  12374. }
  12375. }
  12376. }
  12377. node.dynamicEdgesLength -= correction;
  12378. }
  12379. },
  12380. /**
  12381. * This adds an edge from the childNode to the contained edges of the parent node
  12382. *
  12383. * @param parentNode | Node object
  12384. * @param childNode | Node object
  12385. * @param edge | Edge object
  12386. * @private
  12387. */
  12388. _addToContainedEdges : function(parentNode, childNode, edge) {
  12389. // create an array object if it does not yet exist for this childNode
  12390. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12391. parentNode.containedEdges[childNode.id] = []
  12392. }
  12393. // add this edge to the list
  12394. parentNode.containedEdges[childNode.id].push(edge);
  12395. // remove the edge from the global edges object
  12396. delete this.edges[edge.id];
  12397. // remove the edge from the parent object
  12398. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12399. if (parentNode.dynamicEdges[i].id == edge.id) {
  12400. parentNode.dynamicEdges.splice(i,1);
  12401. break;
  12402. }
  12403. }
  12404. },
  12405. /**
  12406. * This function connects an edge that was connected to a child node to the parent node.
  12407. * It keeps track of which nodes it has been connected to with the originalId array.
  12408. *
  12409. * @param {Node} parentNode | Node object
  12410. * @param {Node} childNode | Node object
  12411. * @param {Edge} edge | Edge object
  12412. * @private
  12413. */
  12414. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12415. // handle circular edges
  12416. if (edge.toId == edge.fromId) {
  12417. this._addToContainedEdges(parentNode, childNode, edge);
  12418. }
  12419. else {
  12420. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12421. edge.originalToId.push(childNode.id);
  12422. edge.to = parentNode;
  12423. edge.toId = parentNode.id;
  12424. }
  12425. else { // edge connected to other node with the "from" side
  12426. edge.originalFromId.push(childNode.id);
  12427. edge.from = parentNode;
  12428. edge.fromId = parentNode.id;
  12429. }
  12430. this._addToReroutedEdges(parentNode,childNode,edge);
  12431. }
  12432. },
  12433. /**
  12434. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12435. * these edges inside of the cluster.
  12436. *
  12437. * @param parentNode
  12438. * @param childNode
  12439. * @private
  12440. */
  12441. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12442. // manage all the edges connected to the child and parent nodes
  12443. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12444. var edge = parentNode.dynamicEdges[i];
  12445. // handle circular edges
  12446. if (edge.toId == edge.fromId) {
  12447. this._addToContainedEdges(parentNode, childNode, edge);
  12448. }
  12449. }
  12450. },
  12451. /**
  12452. * This adds an edge from the childNode to the rerouted edges of the parent node
  12453. *
  12454. * @param parentNode | Node object
  12455. * @param childNode | Node object
  12456. * @param edge | Edge object
  12457. * @private
  12458. */
  12459. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12460. // create an array object if it does not yet exist for this childNode
  12461. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12462. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12463. parentNode.reroutedEdges[childNode.id] = [];
  12464. }
  12465. parentNode.reroutedEdges[childNode.id].push(edge);
  12466. // this edge becomes part of the dynamicEdges of the cluster node
  12467. parentNode.dynamicEdges.push(edge);
  12468. },
  12469. /**
  12470. * This function connects an edge that was connected to a cluster node back to the child node.
  12471. *
  12472. * @param parentNode | Node object
  12473. * @param childNode | Node object
  12474. * @private
  12475. */
  12476. _connectEdgeBackToChild : function(parentNode, childNode) {
  12477. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12478. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12479. var edge = parentNode.reroutedEdges[childNode.id][i];
  12480. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12481. edge.originalFromId.pop();
  12482. edge.fromId = childNode.id;
  12483. edge.from = childNode;
  12484. }
  12485. else {
  12486. edge.originalToId.pop();
  12487. edge.toId = childNode.id;
  12488. edge.to = childNode;
  12489. }
  12490. // append this edge to the list of edges connecting to the childnode
  12491. childNode.dynamicEdges.push(edge);
  12492. // remove the edge from the parent object
  12493. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12494. if (parentNode.dynamicEdges[j].id == edge.id) {
  12495. parentNode.dynamicEdges.splice(j,1);
  12496. break;
  12497. }
  12498. }
  12499. }
  12500. // remove the entry from the rerouted edges
  12501. delete parentNode.reroutedEdges[childNode.id];
  12502. }
  12503. },
  12504. /**
  12505. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12506. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12507. * parentNode
  12508. *
  12509. * @param parentNode | Node object
  12510. * @private
  12511. */
  12512. _validateEdges : function(parentNode) {
  12513. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12514. var edge = parentNode.dynamicEdges[i];
  12515. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12516. parentNode.dynamicEdges.splice(i,1);
  12517. }
  12518. }
  12519. },
  12520. /**
  12521. * This function released the contained edges back into the global domain and puts them back into the
  12522. * dynamic edges of both parent and child.
  12523. *
  12524. * @param {Node} parentNode |
  12525. * @param {Node} childNode |
  12526. * @private
  12527. */
  12528. _releaseContainedEdges : function(parentNode, childNode) {
  12529. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12530. var edge = parentNode.containedEdges[childNode.id][i];
  12531. // put the edge back in the global edges object
  12532. this.edges[edge.id] = edge;
  12533. // put the edge back in the dynamic edges of the child and parent
  12534. childNode.dynamicEdges.push(edge);
  12535. parentNode.dynamicEdges.push(edge);
  12536. }
  12537. // remove the entry from the contained edges
  12538. delete parentNode.containedEdges[childNode.id];
  12539. },
  12540. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  12541. /**
  12542. * This updates the node labels for all nodes (for debugging purposes)
  12543. */
  12544. updateLabels : function() {
  12545. var nodeId;
  12546. // update node labels
  12547. for (nodeId in this.nodes) {
  12548. if (this.nodes.hasOwnProperty(nodeId)) {
  12549. var node = this.nodes[nodeId];
  12550. if (node.clusterSize > 1) {
  12551. node.label = "[".concat(String(node.clusterSize),"]");
  12552. }
  12553. }
  12554. }
  12555. // update node labels
  12556. for (nodeId in this.nodes) {
  12557. if (this.nodes.hasOwnProperty(nodeId)) {
  12558. node = this.nodes[nodeId];
  12559. if (node.clusterSize == 1) {
  12560. if (node.originalLabel !== undefined) {
  12561. node.label = node.originalLabel;
  12562. }
  12563. else {
  12564. node.label = String(node.id);
  12565. }
  12566. }
  12567. }
  12568. }
  12569. // /* Debug Override */
  12570. // for (nodeId in this.nodes) {
  12571. // if (this.nodes.hasOwnProperty(nodeId)) {
  12572. // node = this.nodes[nodeId];
  12573. // node.label = String(node.level);
  12574. // }
  12575. // }
  12576. },
  12577. /**
  12578. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  12579. * if the rest of the nodes are already a few cluster levels in.
  12580. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  12581. * clustered enough to the clusterToSmallestNeighbours function.
  12582. */
  12583. normalizeClusterLevels : function() {
  12584. var maxLevel = 0;
  12585. var minLevel = 1e9;
  12586. var clusterLevel = 0;
  12587. var nodeId;
  12588. // we loop over all nodes in the list
  12589. for (nodeId in this.nodes) {
  12590. if (this.nodes.hasOwnProperty(nodeId)) {
  12591. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  12592. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  12593. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  12594. }
  12595. }
  12596. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  12597. var amountOfNodes = this.nodeIndices.length;
  12598. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  12599. // we loop over all nodes in the list
  12600. for (nodeId in this.nodes) {
  12601. if (this.nodes.hasOwnProperty(nodeId)) {
  12602. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  12603. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  12604. }
  12605. }
  12606. }
  12607. this._updateNodeIndexList();
  12608. this._updateDynamicEdges();
  12609. // if a cluster was formed, we increase the clusterSession
  12610. if (this.nodeIndices.length != amountOfNodes) {
  12611. this.clusterSession += 1;
  12612. }
  12613. }
  12614. },
  12615. /**
  12616. * This function determines if the cluster we want to decluster is in the active area
  12617. * this means around the zoom center
  12618. *
  12619. * @param {Node} node
  12620. * @returns {boolean}
  12621. * @private
  12622. */
  12623. _nodeInActiveArea : function(node) {
  12624. return (
  12625. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12626. &&
  12627. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12628. )
  12629. },
  12630. /**
  12631. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  12632. * It puts large clusters away from the center and randomizes the order.
  12633. *
  12634. */
  12635. repositionNodes : function() {
  12636. for (var i = 0; i < this.nodeIndices.length; i++) {
  12637. var node = this.nodes[this.nodeIndices[i]];
  12638. if ((node.xFixed == false || node.yFixed == false)) {
  12639. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.mass);
  12640. var angle = 2 * Math.PI * Math.random();
  12641. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  12642. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  12643. this._repositionBezierNodes(node);
  12644. }
  12645. }
  12646. },
  12647. /**
  12648. * We determine how many connections denote an important hub.
  12649. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  12650. *
  12651. * @private
  12652. */
  12653. _getHubSize : function() {
  12654. var average = 0;
  12655. var averageSquared = 0;
  12656. var hubCounter = 0;
  12657. var largestHub = 0;
  12658. for (var i = 0; i < this.nodeIndices.length; i++) {
  12659. var node = this.nodes[this.nodeIndices[i]];
  12660. if (node.dynamicEdgesLength > largestHub) {
  12661. largestHub = node.dynamicEdgesLength;
  12662. }
  12663. average += node.dynamicEdgesLength;
  12664. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  12665. hubCounter += 1;
  12666. }
  12667. average = average / hubCounter;
  12668. averageSquared = averageSquared / hubCounter;
  12669. var variance = averageSquared - Math.pow(average,2);
  12670. var standardDeviation = Math.sqrt(variance);
  12671. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  12672. // always have at least one to cluster
  12673. if (this.hubThreshold > largestHub) {
  12674. this.hubThreshold = largestHub;
  12675. }
  12676. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  12677. // console.log("hubThreshold:",this.hubThreshold);
  12678. },
  12679. /**
  12680. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12681. * with this amount we can cluster specifically on these chains.
  12682. *
  12683. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  12684. * @private
  12685. */
  12686. _reduceAmountOfChains : function(fraction) {
  12687. this.hubThreshold = 2;
  12688. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  12689. for (var nodeId in this.nodes) {
  12690. if (this.nodes.hasOwnProperty(nodeId)) {
  12691. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12692. if (reduceAmount > 0) {
  12693. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  12694. reduceAmount -= 1;
  12695. }
  12696. }
  12697. }
  12698. }
  12699. },
  12700. /**
  12701. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12702. * with this amount we can cluster specifically on these chains.
  12703. *
  12704. * @private
  12705. */
  12706. _getChainFraction : function() {
  12707. var chains = 0;
  12708. var total = 0;
  12709. for (var nodeId in this.nodes) {
  12710. if (this.nodes.hasOwnProperty(nodeId)) {
  12711. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12712. chains += 1;
  12713. }
  12714. total += 1;
  12715. }
  12716. }
  12717. return chains/total;
  12718. }
  12719. };
  12720. var SelectionMixin = {
  12721. /**
  12722. * This function can be called from the _doInAllSectors function
  12723. *
  12724. * @param object
  12725. * @param overlappingNodes
  12726. * @private
  12727. */
  12728. _getNodesOverlappingWith : function(object, overlappingNodes) {
  12729. var nodes = this.nodes;
  12730. for (var nodeId in nodes) {
  12731. if (nodes.hasOwnProperty(nodeId)) {
  12732. if (nodes[nodeId].isOverlappingWith(object)) {
  12733. overlappingNodes.push(nodeId);
  12734. }
  12735. }
  12736. }
  12737. },
  12738. /**
  12739. * retrieve all nodes overlapping with given object
  12740. * @param {Object} object An object with parameters left, top, right, bottom
  12741. * @return {Number[]} An array with id's of the overlapping nodes
  12742. * @private
  12743. */
  12744. _getAllNodesOverlappingWith : function (object) {
  12745. var overlappingNodes = [];
  12746. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  12747. return overlappingNodes;
  12748. },
  12749. /**
  12750. * Return a position object in canvasspace from a single point in screenspace
  12751. *
  12752. * @param pointer
  12753. * @returns {{left: number, top: number, right: number, bottom: number}}
  12754. * @private
  12755. */
  12756. _pointerToPositionObject : function(pointer) {
  12757. var x = this._canvasToX(pointer.x);
  12758. var y = this._canvasToY(pointer.y);
  12759. return {left: x,
  12760. top: y,
  12761. right: x,
  12762. bottom: y};
  12763. },
  12764. /**
  12765. * Get the top node at the a specific point (like a click)
  12766. *
  12767. * @param {{x: Number, y: Number}} pointer
  12768. * @return {Node | null} node
  12769. * @private
  12770. */
  12771. _getNodeAt : function (pointer) {
  12772. // we first check if this is an navigation controls element
  12773. var positionObject = this._pointerToPositionObject(pointer);
  12774. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  12775. // if there are overlapping nodes, select the last one, this is the
  12776. // one which is drawn on top of the others
  12777. if (overlappingNodes.length > 0) {
  12778. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  12779. }
  12780. else {
  12781. return null;
  12782. }
  12783. },
  12784. /**
  12785. * retrieve all edges overlapping with given object, selector is around center
  12786. * @param {Object} object An object with parameters left, top, right, bottom
  12787. * @return {Number[]} An array with id's of the overlapping nodes
  12788. * @private
  12789. */
  12790. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  12791. var edges = this.edges;
  12792. for (var edgeId in edges) {
  12793. if (edges.hasOwnProperty(edgeId)) {
  12794. if (edges[edgeId].isOverlappingWith(object)) {
  12795. overlappingEdges.push(edgeId);
  12796. }
  12797. }
  12798. }
  12799. },
  12800. /**
  12801. * retrieve all nodes overlapping with given object
  12802. * @param {Object} object An object with parameters left, top, right, bottom
  12803. * @return {Number[]} An array with id's of the overlapping nodes
  12804. * @private
  12805. */
  12806. _getAllEdgesOverlappingWith : function (object) {
  12807. var overlappingEdges = [];
  12808. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  12809. return overlappingEdges;
  12810. },
  12811. /**
  12812. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  12813. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  12814. *
  12815. * @param pointer
  12816. * @returns {null}
  12817. * @private
  12818. */
  12819. _getEdgeAt : function(pointer) {
  12820. var positionObject = this._pointerToPositionObject(pointer);
  12821. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  12822. if (overlappingEdges.length > 0) {
  12823. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  12824. }
  12825. else {
  12826. return null;
  12827. }
  12828. },
  12829. /**
  12830. * Add object to the selection array.
  12831. *
  12832. * @param obj
  12833. * @private
  12834. */
  12835. _addToSelection : function(obj) {
  12836. if (obj instanceof Node) {
  12837. this.selectionObj.nodes[obj.id] = obj;
  12838. }
  12839. else {
  12840. this.selectionObj.edges[obj.id] = obj;
  12841. }
  12842. },
  12843. /**
  12844. * Remove a single option from selection.
  12845. *
  12846. * @param {Object} obj
  12847. * @private
  12848. */
  12849. _removeFromSelection : function(obj) {
  12850. if (obj instanceof Node) {
  12851. delete this.selectionObj.nodes[obj.id];
  12852. }
  12853. else {
  12854. delete this.selectionObj.edges[obj.id];
  12855. }
  12856. },
  12857. /**
  12858. * Unselect all. The selectionObj is useful for this.
  12859. *
  12860. * @param {Boolean} [doNotTrigger] | ignore trigger
  12861. * @private
  12862. */
  12863. _unselectAll : function(doNotTrigger) {
  12864. if (doNotTrigger === undefined) {
  12865. doNotTrigger = false;
  12866. }
  12867. for(var nodeId in this.selectionObj.nodes) {
  12868. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12869. this.selectionObj.nodes[nodeId].unselect();
  12870. }
  12871. }
  12872. for(var edgeId in this.selectionObj.edges) {
  12873. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12874. this.selectionObj.edges[edgeId].unselect();
  12875. }
  12876. }
  12877. this.selectionObj = {nodes:{},edges:{}};
  12878. if (doNotTrigger == false) {
  12879. this.emit('select', this.getSelection());
  12880. }
  12881. },
  12882. /**
  12883. * Unselect all clusters. The selectionObj is useful for this.
  12884. *
  12885. * @param {Boolean} [doNotTrigger] | ignore trigger
  12886. * @private
  12887. */
  12888. _unselectClusters : function(doNotTrigger) {
  12889. if (doNotTrigger === undefined) {
  12890. doNotTrigger = false;
  12891. }
  12892. for (var nodeId in this.selectionObj.nodes) {
  12893. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12894. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  12895. this.selectionObj.nodes[nodeId].unselect();
  12896. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  12897. }
  12898. }
  12899. }
  12900. if (doNotTrigger == false) {
  12901. this.emit('select', this.getSelection());
  12902. }
  12903. },
  12904. /**
  12905. * return the number of selected nodes
  12906. *
  12907. * @returns {number}
  12908. * @private
  12909. */
  12910. _getSelectedNodeCount : function() {
  12911. var count = 0;
  12912. for (var nodeId in this.selectionObj.nodes) {
  12913. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12914. count += 1;
  12915. }
  12916. }
  12917. return count;
  12918. },
  12919. /**
  12920. * return the number of selected nodes
  12921. *
  12922. * @returns {number}
  12923. * @private
  12924. */
  12925. _getSelectedNode : function() {
  12926. for (var nodeId in this.selectionObj.nodes) {
  12927. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12928. return this.selectionObj.nodes[nodeId];
  12929. }
  12930. }
  12931. return null;
  12932. },
  12933. /**
  12934. * return the number of selected edges
  12935. *
  12936. * @returns {number}
  12937. * @private
  12938. */
  12939. _getSelectedEdgeCount : function() {
  12940. var count = 0;
  12941. for (var edgeId in this.selectionObj.edges) {
  12942. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12943. count += 1;
  12944. }
  12945. }
  12946. return count;
  12947. },
  12948. /**
  12949. * return the number of selected objects.
  12950. *
  12951. * @returns {number}
  12952. * @private
  12953. */
  12954. _getSelectedObjectCount : function() {
  12955. var count = 0;
  12956. for(var nodeId in this.selectionObj.nodes) {
  12957. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12958. count += 1;
  12959. }
  12960. }
  12961. for(var edgeId in this.selectionObj.edges) {
  12962. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12963. count += 1;
  12964. }
  12965. }
  12966. return count;
  12967. },
  12968. /**
  12969. * Check if anything is selected
  12970. *
  12971. * @returns {boolean}
  12972. * @private
  12973. */
  12974. _selectionIsEmpty : function() {
  12975. for(var nodeId in this.selectionObj.nodes) {
  12976. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12977. return false;
  12978. }
  12979. }
  12980. for(var edgeId in this.selectionObj.edges) {
  12981. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12982. return false;
  12983. }
  12984. }
  12985. return true;
  12986. },
  12987. /**
  12988. * check if one of the selected nodes is a cluster.
  12989. *
  12990. * @returns {boolean}
  12991. * @private
  12992. */
  12993. _clusterInSelection : function() {
  12994. for(var nodeId in this.selectionObj.nodes) {
  12995. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12996. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  12997. return true;
  12998. }
  12999. }
  13000. }
  13001. return false;
  13002. },
  13003. /**
  13004. * select the edges connected to the node that is being selected
  13005. *
  13006. * @param {Node} node
  13007. * @private
  13008. */
  13009. _selectConnectedEdges : function(node) {
  13010. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13011. var edge = node.dynamicEdges[i];
  13012. edge.select();
  13013. this._addToSelection(edge);
  13014. }
  13015. },
  13016. /**
  13017. * unselect the edges connected to the node that is being selected
  13018. *
  13019. * @param {Node} node
  13020. * @private
  13021. */
  13022. _unselectConnectedEdges : function(node) {
  13023. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13024. var edge = node.dynamicEdges[i];
  13025. edge.unselect();
  13026. this._removeFromSelection(edge);
  13027. }
  13028. },
  13029. /**
  13030. * This is called when someone clicks on a node. either select or deselect it.
  13031. * If there is an existing selection and we don't want to append to it, clear the existing selection
  13032. *
  13033. * @param {Node || Edge} object
  13034. * @param {Boolean} append
  13035. * @param {Boolean} [doNotTrigger] | ignore trigger
  13036. * @private
  13037. */
  13038. _selectObject : function(object, append, doNotTrigger) {
  13039. if (doNotTrigger === undefined) {
  13040. doNotTrigger = false;
  13041. }
  13042. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  13043. this._unselectAll(true);
  13044. }
  13045. if (object.selected == false) {
  13046. object.select();
  13047. this._addToSelection(object);
  13048. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  13049. this._selectConnectedEdges(object);
  13050. }
  13051. }
  13052. else {
  13053. object.unselect();
  13054. this._removeFromSelection(object);
  13055. }
  13056. if (doNotTrigger == false) {
  13057. this.emit('select', this.getSelection());
  13058. }
  13059. },
  13060. /**
  13061. * handles the selection part of the touch, only for navigation controls elements;
  13062. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13063. * This is the most responsive solution
  13064. *
  13065. * @param {Object} pointer
  13066. * @private
  13067. */
  13068. _handleTouch : function(pointer) {
  13069. },
  13070. /**
  13071. * handles the selection part of the tap;
  13072. *
  13073. * @param {Object} pointer
  13074. * @private
  13075. */
  13076. _handleTap : function(pointer) {
  13077. var node = this._getNodeAt(pointer);
  13078. if (node != null) {
  13079. this._selectObject(node,false);
  13080. }
  13081. else {
  13082. var edge = this._getEdgeAt(pointer);
  13083. if (edge != null) {
  13084. this._selectObject(edge,false);
  13085. }
  13086. else {
  13087. this._unselectAll();
  13088. }
  13089. }
  13090. this.emit("click", this.getSelection());
  13091. this._redraw();
  13092. },
  13093. /**
  13094. * handles the selection part of the double tap and opens a cluster if needed
  13095. *
  13096. * @param {Object} pointer
  13097. * @private
  13098. */
  13099. _handleDoubleTap : function(pointer) {
  13100. var node = this._getNodeAt(pointer);
  13101. if (node != null && node !== undefined) {
  13102. // we reset the areaCenter here so the opening of the node will occur
  13103. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  13104. "y" : this._canvasToY(pointer.y)};
  13105. this.openCluster(node);
  13106. }
  13107. this.emit("doubleClick", this.getSelection());
  13108. },
  13109. /**
  13110. * Handle the onHold selection part
  13111. *
  13112. * @param pointer
  13113. * @private
  13114. */
  13115. _handleOnHold : function(pointer) {
  13116. var node = this._getNodeAt(pointer);
  13117. if (node != null) {
  13118. this._selectObject(node,true);
  13119. }
  13120. else {
  13121. var edge = this._getEdgeAt(pointer);
  13122. if (edge != null) {
  13123. this._selectObject(edge,true);
  13124. }
  13125. }
  13126. this._redraw();
  13127. },
  13128. /**
  13129. * handle the onRelease event. These functions are here for the navigation controls module.
  13130. *
  13131. * @private
  13132. */
  13133. _handleOnRelease : function(pointer) {
  13134. },
  13135. /**
  13136. *
  13137. * retrieve the currently selected objects
  13138. * @return {Number[] | String[]} selection An array with the ids of the
  13139. * selected nodes.
  13140. */
  13141. getSelection : function() {
  13142. var nodeIds = this.getSelectedNodes();
  13143. var edgeIds = this.getSelectedEdges();
  13144. return {nodes:nodeIds, edges:edgeIds};
  13145. },
  13146. /**
  13147. *
  13148. * retrieve the currently selected nodes
  13149. * @return {String} selection An array with the ids of the
  13150. * selected nodes.
  13151. */
  13152. getSelectedNodes : function() {
  13153. var idArray = [];
  13154. for(var nodeId in this.selectionObj.nodes) {
  13155. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13156. idArray.push(nodeId);
  13157. }
  13158. }
  13159. return idArray
  13160. },
  13161. /**
  13162. *
  13163. * retrieve the currently selected edges
  13164. * @return {Array} selection An array with the ids of the
  13165. * selected nodes.
  13166. */
  13167. getSelectedEdges : function() {
  13168. var idArray = [];
  13169. for(var edgeId in this.selectionObj.edges) {
  13170. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13171. idArray.push(edgeId);
  13172. }
  13173. }
  13174. return idArray;
  13175. },
  13176. /**
  13177. * select zero or more nodes
  13178. * @param {Number[] | String[]} selection An array with the ids of the
  13179. * selected nodes.
  13180. */
  13181. setSelection : function(selection) {
  13182. var i, iMax, id;
  13183. if (!selection || (selection.length == undefined))
  13184. throw 'Selection must be an array with ids';
  13185. // first unselect any selected node
  13186. this._unselectAll(true);
  13187. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13188. id = selection[i];
  13189. var node = this.nodes[id];
  13190. if (!node) {
  13191. throw new RangeError('Node with id "' + id + '" not found');
  13192. }
  13193. this._selectObject(node,true,true);
  13194. }
  13195. this.redraw();
  13196. },
  13197. /**
  13198. * Validate the selection: remove ids of nodes which no longer exist
  13199. * @private
  13200. */
  13201. _updateSelection : function () {
  13202. for(var nodeId in this.selectionObj.nodes) {
  13203. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13204. if (!this.nodes.hasOwnProperty(nodeId)) {
  13205. delete this.selectionObj.nodes[nodeId];
  13206. }
  13207. }
  13208. }
  13209. for(var edgeId in this.selectionObj.edges) {
  13210. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13211. if (!this.edges.hasOwnProperty(edgeId)) {
  13212. delete this.selectionObj.edges[edgeId];
  13213. }
  13214. }
  13215. }
  13216. }
  13217. };
  13218. /**
  13219. * Created by Alex on 1/22/14.
  13220. */
  13221. var NavigationMixin = {
  13222. _cleanNavigation : function() {
  13223. // clean up previosu navigation items
  13224. var wrapper = document.getElementById('graph-navigation_wrapper');
  13225. if (wrapper != null) {
  13226. this.containerElement.removeChild(wrapper);
  13227. }
  13228. document.onmouseup = null;
  13229. },
  13230. /**
  13231. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13232. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13233. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13234. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13235. *
  13236. * @private
  13237. */
  13238. _loadNavigationElements : function() {
  13239. this._cleanNavigation();
  13240. this.navigationDivs = {};
  13241. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13242. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  13243. this.navigationDivs['wrapper'] = document.createElement('div');
  13244. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13245. this.navigationDivs['wrapper'].style.position = "absolute";
  13246. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  13247. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  13248. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13249. for (var i = 0; i < navigationDivs.length; i++) {
  13250. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13251. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13252. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13253. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13254. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13255. }
  13256. document.onmouseup = this._stopMovement.bind(this);
  13257. },
  13258. /**
  13259. * this stops all movement induced by the navigation buttons
  13260. *
  13261. * @private
  13262. */
  13263. _stopMovement : function() {
  13264. this._xStopMoving();
  13265. this._yStopMoving();
  13266. this._stopZoom();
  13267. },
  13268. /**
  13269. * stops the actions performed by page up and down etc.
  13270. *
  13271. * @param event
  13272. * @private
  13273. */
  13274. _preventDefault : function(event) {
  13275. if (event !== undefined) {
  13276. if (event.preventDefault) {
  13277. event.preventDefault();
  13278. } else {
  13279. event.returnValue = false;
  13280. }
  13281. }
  13282. },
  13283. /**
  13284. * move the screen up
  13285. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13286. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13287. * To avoid this behaviour, we do the translation in the start loop.
  13288. *
  13289. * @private
  13290. */
  13291. _moveUp : function(event) {
  13292. this.yIncrement = this.constants.keyboard.speed.y;
  13293. this.start(); // if there is no node movement, the calculation wont be done
  13294. this._preventDefault(event);
  13295. if (this.navigationDivs) {
  13296. this.navigationDivs['up'].className += " active";
  13297. }
  13298. },
  13299. /**
  13300. * move the screen down
  13301. * @private
  13302. */
  13303. _moveDown : function(event) {
  13304. this.yIncrement = -this.constants.keyboard.speed.y;
  13305. this.start(); // if there is no node movement, the calculation wont be done
  13306. this._preventDefault(event);
  13307. if (this.navigationDivs) {
  13308. this.navigationDivs['down'].className += " active";
  13309. }
  13310. },
  13311. /**
  13312. * move the screen left
  13313. * @private
  13314. */
  13315. _moveLeft : function(event) {
  13316. this.xIncrement = this.constants.keyboard.speed.x;
  13317. this.start(); // if there is no node movement, the calculation wont be done
  13318. this._preventDefault(event);
  13319. if (this.navigationDivs) {
  13320. this.navigationDivs['left'].className += " active";
  13321. }
  13322. },
  13323. /**
  13324. * move the screen right
  13325. * @private
  13326. */
  13327. _moveRight : function(event) {
  13328. this.xIncrement = -this.constants.keyboard.speed.y;
  13329. this.start(); // if there is no node movement, the calculation wont be done
  13330. this._preventDefault(event);
  13331. if (this.navigationDivs) {
  13332. this.navigationDivs['right'].className += " active";
  13333. }
  13334. },
  13335. /**
  13336. * Zoom in, using the same method as the movement.
  13337. * @private
  13338. */
  13339. _zoomIn : function(event) {
  13340. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13341. this.start(); // if there is no node movement, the calculation wont be done
  13342. this._preventDefault(event);
  13343. if (this.navigationDivs) {
  13344. this.navigationDivs['zoomIn'].className += " active";
  13345. }
  13346. },
  13347. /**
  13348. * Zoom out
  13349. * @private
  13350. */
  13351. _zoomOut : function() {
  13352. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13353. this.start(); // if there is no node movement, the calculation wont be done
  13354. this._preventDefault(event);
  13355. if (this.navigationDivs) {
  13356. this.navigationDivs['zoomOut'].className += " active";
  13357. }
  13358. },
  13359. /**
  13360. * Stop zooming and unhighlight the zoom controls
  13361. * @private
  13362. */
  13363. _stopZoom : function() {
  13364. this.zoomIncrement = 0;
  13365. if (this.navigationDivs) {
  13366. this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active","");
  13367. this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active","");
  13368. }
  13369. },
  13370. /**
  13371. * Stop moving in the Y direction and unHighlight the up and down
  13372. * @private
  13373. */
  13374. _yStopMoving : function() {
  13375. this.yIncrement = 0;
  13376. if (this.navigationDivs) {
  13377. this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active","");
  13378. this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active","");
  13379. }
  13380. },
  13381. /**
  13382. * Stop moving in the X direction and unHighlight left and right.
  13383. * @private
  13384. */
  13385. _xStopMoving : function() {
  13386. this.xIncrement = 0;
  13387. if (this.navigationDivs) {
  13388. this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active","");
  13389. this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active","");
  13390. }
  13391. }
  13392. };
  13393. /**
  13394. * Created by Alex on 2/10/14.
  13395. */
  13396. var graphMixinLoaders = {
  13397. /**
  13398. * Load a mixin into the graph object
  13399. *
  13400. * @param {Object} sourceVariable | this object has to contain functions.
  13401. * @private
  13402. */
  13403. _loadMixin: function (sourceVariable) {
  13404. for (var mixinFunction in sourceVariable) {
  13405. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13406. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13407. }
  13408. }
  13409. },
  13410. /**
  13411. * removes a mixin from the graph object.
  13412. *
  13413. * @param {Object} sourceVariable | this object has to contain functions.
  13414. * @private
  13415. */
  13416. _clearMixin: function (sourceVariable) {
  13417. for (var mixinFunction in sourceVariable) {
  13418. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13419. Graph.prototype[mixinFunction] = undefined;
  13420. }
  13421. }
  13422. },
  13423. /**
  13424. * Mixin the physics system and initialize the parameters required.
  13425. *
  13426. * @private
  13427. */
  13428. _loadPhysicsSystem: function () {
  13429. this._loadMixin(physicsMixin);
  13430. this._loadSelectedForceSolver();
  13431. if (this.constants.configurePhysics == true) {
  13432. this._loadPhysicsConfiguration();
  13433. }
  13434. },
  13435. /**
  13436. * Mixin the cluster system and initialize the parameters required.
  13437. *
  13438. * @private
  13439. */
  13440. _loadClusterSystem: function () {
  13441. this.clusterSession = 0;
  13442. this.hubThreshold = 5;
  13443. this._loadMixin(ClusterMixin);
  13444. },
  13445. /**
  13446. * Mixin the sector system and initialize the parameters required
  13447. *
  13448. * @private
  13449. */
  13450. _loadSectorSystem: function () {
  13451. this.sectors = {};
  13452. this.activeSector = ["default"];
  13453. this.sectors["active"] = {};
  13454. this.sectors["active"]["default"] = {"nodes": {},
  13455. "edges": {},
  13456. "nodeIndices": [],
  13457. "formationScale": 1.0,
  13458. "drawingNode": undefined };
  13459. this.sectors["frozen"] = {};
  13460. this.sectors["support"] = {"nodes": {},
  13461. "edges": {},
  13462. "nodeIndices": [],
  13463. "formationScale": 1.0,
  13464. "drawingNode": undefined };
  13465. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13466. this._loadMixin(SectorMixin);
  13467. },
  13468. /**
  13469. * Mixin the selection system and initialize the parameters required
  13470. *
  13471. * @private
  13472. */
  13473. _loadSelectionSystem: function () {
  13474. this.selectionObj = {nodes: {}, edges: {}};
  13475. this._loadMixin(SelectionMixin);
  13476. },
  13477. /**
  13478. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13479. *
  13480. * @private
  13481. */
  13482. _loadManipulationSystem: function () {
  13483. // reset global variables -- these are used by the selection of nodes and edges.
  13484. this.blockConnectingEdgeSelection = false;
  13485. this.forceAppendSelection = false;
  13486. if (this.constants.dataManipulation.enabled == true) {
  13487. // load the manipulator HTML elements. All styling done in css.
  13488. if (this.manipulationDiv === undefined) {
  13489. this.manipulationDiv = document.createElement('div');
  13490. this.manipulationDiv.className = 'graph-manipulationDiv';
  13491. this.manipulationDiv.id = 'graph-manipulationDiv';
  13492. if (this.editMode == true) {
  13493. this.manipulationDiv.style.display = "block";
  13494. }
  13495. else {
  13496. this.manipulationDiv.style.display = "none";
  13497. }
  13498. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13499. }
  13500. if (this.editModeDiv === undefined) {
  13501. this.editModeDiv = document.createElement('div');
  13502. this.editModeDiv.className = 'graph-manipulation-editMode';
  13503. this.editModeDiv.id = 'graph-manipulation-editMode';
  13504. if (this.editMode == true) {
  13505. this.editModeDiv.style.display = "none";
  13506. }
  13507. else {
  13508. this.editModeDiv.style.display = "block";
  13509. }
  13510. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13511. }
  13512. if (this.closeDiv === undefined) {
  13513. this.closeDiv = document.createElement('div');
  13514. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13515. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13516. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13517. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13518. }
  13519. // load the manipulation functions
  13520. this._loadMixin(manipulationMixin);
  13521. // create the manipulator toolbar
  13522. this._createManipulatorBar();
  13523. }
  13524. else {
  13525. if (this.manipulationDiv !== undefined) {
  13526. // removes all the bindings and overloads
  13527. this._createManipulatorBar();
  13528. // remove the manipulation divs
  13529. this.containerElement.removeChild(this.manipulationDiv);
  13530. this.containerElement.removeChild(this.editModeDiv);
  13531. this.containerElement.removeChild(this.closeDiv);
  13532. this.manipulationDiv = undefined;
  13533. this.editModeDiv = undefined;
  13534. this.closeDiv = undefined;
  13535. // remove the mixin functions
  13536. this._clearMixin(manipulationMixin);
  13537. }
  13538. }
  13539. },
  13540. /**
  13541. * Mixin the navigation (User Interface) system and initialize the parameters required
  13542. *
  13543. * @private
  13544. */
  13545. _loadNavigationControls: function () {
  13546. this._loadMixin(NavigationMixin);
  13547. // the clean function removes the button divs, this is done to remove the bindings.
  13548. this._cleanNavigation();
  13549. if (this.constants.navigation.enabled == true) {
  13550. this._loadNavigationElements();
  13551. }
  13552. },
  13553. /**
  13554. * Mixin the hierarchical layout system.
  13555. *
  13556. * @private
  13557. */
  13558. _loadHierarchySystem: function () {
  13559. this._loadMixin(HierarchicalLayoutMixin);
  13560. }
  13561. };
  13562. /**
  13563. * @constructor Graph
  13564. * Create a graph visualization, displaying nodes and edges.
  13565. *
  13566. * @param {Element} container The DOM element in which the Graph will
  13567. * be created. Normally a div element.
  13568. * @param {Object} data An object containing parameters
  13569. * {Array} nodes
  13570. * {Array} edges
  13571. * @param {Object} options Options
  13572. */
  13573. function Graph (container, data, options) {
  13574. this._initializeMixinLoaders();
  13575. // create variables and set default values
  13576. this.containerElement = container;
  13577. this.width = '100%';
  13578. this.height = '100%';
  13579. // render and calculation settings
  13580. this.renderRefreshRate = 60; // hz (fps)
  13581. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  13582. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  13583. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  13584. this.physicsDiscreteStepsize = 0.65; // discrete stepsize of the simulation
  13585. this.stabilize = true; // stabilize before displaying the graph
  13586. this.selectable = true;
  13587. this.initializing = true;
  13588. // these functions are triggered when the dataset is edited
  13589. this.triggerFunctions = {add:null,edit:null,connect:null,del:null};
  13590. // set constant values
  13591. this.constants = {
  13592. nodes: {
  13593. radiusMin: 5,
  13594. radiusMax: 20,
  13595. radius: 5,
  13596. shape: 'ellipse',
  13597. image: undefined,
  13598. widthMin: 16, // px
  13599. widthMax: 64, // px
  13600. fixed: false,
  13601. fontColor: 'black',
  13602. fontSize: 14, // px
  13603. fontFace: 'verdana',
  13604. level: -1,
  13605. color: {
  13606. border: '#2B7CE9',
  13607. background: '#97C2FC',
  13608. highlight: {
  13609. border: '#2B7CE9',
  13610. background: '#D2E5FF'
  13611. }
  13612. },
  13613. borderColor: '#2B7CE9',
  13614. backgroundColor: '#97C2FC',
  13615. highlightColor: '#D2E5FF',
  13616. group: undefined
  13617. },
  13618. edges: {
  13619. widthMin: 1,
  13620. widthMax: 15,
  13621. width: 1,
  13622. style: 'line',
  13623. color: {
  13624. color:'#848484',
  13625. highlight:'#848484'
  13626. },
  13627. fontColor: '#343434',
  13628. fontSize: 14, // px
  13629. fontFace: 'arial',
  13630. fontFill: 'white',
  13631. arrowScaleFactor: 1,
  13632. dash: {
  13633. length: 10,
  13634. gap: 5,
  13635. altLength: undefined
  13636. }
  13637. },
  13638. configurePhysics:false,
  13639. physics: {
  13640. barnesHut: {
  13641. enabled: true,
  13642. theta: 1 / 0.6, // inverted to save time during calculation
  13643. gravitationalConstant: -2000,
  13644. centralGravity: 0.3,
  13645. springLength: 95,
  13646. springConstant: 0.04,
  13647. damping: 0.09
  13648. },
  13649. repulsion: {
  13650. centralGravity: 0.1,
  13651. springLength: 200,
  13652. springConstant: 0.05,
  13653. nodeDistance: 100,
  13654. damping: 0.09
  13655. },
  13656. hierarchicalRepulsion: {
  13657. enabled: false,
  13658. centralGravity: 0.0,
  13659. springLength: 100,
  13660. springConstant: 0.01,
  13661. nodeDistance: 60,
  13662. damping: 0.09
  13663. },
  13664. damping: null,
  13665. centralGravity: null,
  13666. springLength: null,
  13667. springConstant: null
  13668. },
  13669. clustering: { // Per Node in Cluster = PNiC
  13670. enabled: false, // (Boolean) | global on/off switch for clustering.
  13671. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  13672. 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
  13673. 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
  13674. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  13675. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  13676. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  13677. 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.
  13678. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  13679. maxFontSize: 1000,
  13680. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  13681. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  13682. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  13683. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  13684. height: 1, // (px PNiC) | growth of the height per node in cluster.
  13685. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  13686. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  13687. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  13688. clusterLevelDifference: 2
  13689. },
  13690. navigation: {
  13691. enabled: false
  13692. },
  13693. keyboard: {
  13694. enabled: false,
  13695. speed: {x: 10, y: 10, zoom: 0.02}
  13696. },
  13697. dataManipulation: {
  13698. enabled: false,
  13699. initiallyVisible: false
  13700. },
  13701. hierarchicalLayout: {
  13702. enabled:false,
  13703. levelSeparation: 150,
  13704. nodeSpacing: 100,
  13705. direction: "UD" // UD, DU, LR, RL
  13706. },
  13707. freezeForStabilization: false,
  13708. smoothCurves: true,
  13709. maxVelocity: 10,
  13710. minVelocity: 0.1, // px/s
  13711. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  13712. labels:{
  13713. add:"Add Node",
  13714. edit:"Edit",
  13715. link:"Add Link",
  13716. del:"Delete selected",
  13717. editNode:"Edit Node",
  13718. back:"Back",
  13719. addDescription:"Click in an empty space to place a new node.",
  13720. linkDescription:"Click on a node and drag the edge to another node to connect them.",
  13721. addError:"The function for add does not support two arguments (data,callback).",
  13722. linkError:"The function for connect does not support two arguments (data,callback).",
  13723. editError:"The function for edit does not support two arguments (data, callback).",
  13724. editBoundError:"No edit function has been bound to this button.",
  13725. deleteError:"The function for delete does not support two arguments (data, callback).",
  13726. deleteClusterError:"Clusters cannot be deleted."
  13727. },
  13728. tooltip: {
  13729. delay: 300,
  13730. fontColor: 'black',
  13731. fontSize: 14, // px
  13732. fontFace: 'verdana',
  13733. color: {
  13734. border: '#666',
  13735. background: '#FFFFC6'
  13736. }
  13737. }
  13738. };
  13739. this.editMode = this.constants.dataManipulation.initiallyVisible;
  13740. // Node variables
  13741. var graph = this;
  13742. this.groups = new Groups(); // object with groups
  13743. this.images = new Images(); // object with images
  13744. this.images.setOnloadCallback(function () {
  13745. graph._redraw();
  13746. });
  13747. // keyboard navigation variables
  13748. this.xIncrement = 0;
  13749. this.yIncrement = 0;
  13750. this.zoomIncrement = 0;
  13751. // loading all the mixins:
  13752. // load the force calculation functions, grouped under the physics system.
  13753. this._loadPhysicsSystem();
  13754. // create a frame and canvas
  13755. this._create();
  13756. // load the sector system. (mandatory, fully integrated with Graph)
  13757. this._loadSectorSystem();
  13758. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  13759. this._loadClusterSystem();
  13760. // load the selection system. (mandatory, required by Graph)
  13761. this._loadSelectionSystem();
  13762. // load the selection system. (mandatory, required by Graph)
  13763. this._loadHierarchySystem();
  13764. // apply options
  13765. this.setOptions(options);
  13766. // other vars
  13767. this.freezeSimulation = false;// freeze the simulation
  13768. this.cachedFunctions = {};
  13769. // containers for nodes and edges
  13770. this.calculationNodes = {};
  13771. this.calculationNodeIndices = [];
  13772. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  13773. this.nodes = {}; // object with Node objects
  13774. this.edges = {}; // object with Edge objects
  13775. // position and scale variables and objects
  13776. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  13777. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13778. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13779. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  13780. this.scale = 1; // defining the global scale variable in the constructor
  13781. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  13782. // datasets or dataviews
  13783. this.nodesData = null; // A DataSet or DataView
  13784. this.edgesData = null; // A DataSet or DataView
  13785. // create event listeners used to subscribe on the DataSets of the nodes and edges
  13786. this.nodesListeners = {
  13787. 'add': function (event, params) {
  13788. graph._addNodes(params.items);
  13789. graph.start();
  13790. },
  13791. 'update': function (event, params) {
  13792. graph._updateNodes(params.items);
  13793. graph.start();
  13794. },
  13795. 'remove': function (event, params) {
  13796. graph._removeNodes(params.items);
  13797. graph.start();
  13798. }
  13799. };
  13800. this.edgesListeners = {
  13801. 'add': function (event, params) {
  13802. graph._addEdges(params.items);
  13803. graph.start();
  13804. },
  13805. 'update': function (event, params) {
  13806. graph._updateEdges(params.items);
  13807. graph.start();
  13808. },
  13809. 'remove': function (event, params) {
  13810. graph._removeEdges(params.items);
  13811. graph.start();
  13812. }
  13813. };
  13814. // properties for the animation
  13815. this.moving = true;
  13816. this.timer = undefined; // Scheduling function. Is definded in this.start();
  13817. // load data (the disable start variable will be the same as the enabled clustering)
  13818. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  13819. // hierarchical layout
  13820. this.initializing = false;
  13821. if (this.constants.hierarchicalLayout.enabled == true) {
  13822. this._setupHierarchicalLayout();
  13823. }
  13824. else {
  13825. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  13826. if (this.stabilize == false) {
  13827. this.zoomExtent(true,this.constants.clustering.enabled);
  13828. }
  13829. }
  13830. // if clustering is disabled, the simulation will have started in the setData function
  13831. if (this.constants.clustering.enabled) {
  13832. this.startWithClustering();
  13833. }
  13834. }
  13835. // Extend Graph with an Emitter mixin
  13836. Emitter(Graph.prototype);
  13837. /**
  13838. * Get the script path where the vis.js library is located
  13839. *
  13840. * @returns {string | null} path Path or null when not found. Path does not
  13841. * end with a slash.
  13842. * @private
  13843. */
  13844. Graph.prototype._getScriptPath = function() {
  13845. var scripts = document.getElementsByTagName( 'script' );
  13846. // find script named vis.js or vis.min.js
  13847. for (var i = 0; i < scripts.length; i++) {
  13848. var src = scripts[i].src;
  13849. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  13850. if (match) {
  13851. // return path without the script name
  13852. return src.substring(0, src.length - match[0].length);
  13853. }
  13854. }
  13855. return null;
  13856. };
  13857. /**
  13858. * Find the center position of the graph
  13859. * @private
  13860. */
  13861. Graph.prototype._getRange = function() {
  13862. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  13863. for (var nodeId in this.nodes) {
  13864. if (this.nodes.hasOwnProperty(nodeId)) {
  13865. node = this.nodes[nodeId];
  13866. if (minX > (node.x)) {minX = node.x;}
  13867. if (maxX < (node.x)) {maxX = node.x;}
  13868. if (minY > (node.y)) {minY = node.y;}
  13869. if (maxY < (node.y)) {maxY = node.y;}
  13870. }
  13871. }
  13872. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  13873. minY = 0, maxY = 0, minX = 0, maxX = 0;
  13874. }
  13875. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13876. };
  13877. /**
  13878. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13879. * @returns {{x: number, y: number}}
  13880. * @private
  13881. */
  13882. Graph.prototype._findCenter = function(range) {
  13883. return {x: (0.5 * (range.maxX + range.minX)),
  13884. y: (0.5 * (range.maxY + range.minY))};
  13885. };
  13886. /**
  13887. * center the graph
  13888. *
  13889. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13890. */
  13891. Graph.prototype._centerGraph = function(range) {
  13892. var center = this._findCenter(range);
  13893. center.x *= this.scale;
  13894. center.y *= this.scale;
  13895. center.x -= 0.5 * this.frame.canvas.clientWidth;
  13896. center.y -= 0.5 * this.frame.canvas.clientHeight;
  13897. this._setTranslation(-center.x,-center.y); // set at 0,0
  13898. };
  13899. /**
  13900. * This function zooms out to fit all data on screen based on amount of nodes
  13901. *
  13902. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  13903. * @param {Boolean} [disableStart] | If true, start is not called.
  13904. */
  13905. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  13906. if (initialZoom === undefined) {
  13907. initialZoom = false;
  13908. }
  13909. if (disableStart === undefined) {
  13910. disableStart = false;
  13911. }
  13912. var range = this._getRange();
  13913. var zoomLevel;
  13914. if (initialZoom == true) {
  13915. var numberOfNodes = this.nodeIndices.length;
  13916. if (this.constants.smoothCurves == true) {
  13917. if (this.constants.clustering.enabled == true &&
  13918. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  13919. 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.
  13920. }
  13921. else {
  13922. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13923. }
  13924. }
  13925. else {
  13926. if (this.constants.clustering.enabled == true &&
  13927. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  13928. 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.
  13929. }
  13930. else {
  13931. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13932. }
  13933. }
  13934. // correct for larger canvasses.
  13935. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  13936. zoomLevel *= factor;
  13937. }
  13938. else {
  13939. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  13940. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  13941. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  13942. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  13943. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  13944. }
  13945. if (zoomLevel > 1.0) {
  13946. zoomLevel = 1.0;
  13947. }
  13948. this._setScale(zoomLevel);
  13949. this._centerGraph(range);
  13950. if (disableStart == false) {
  13951. this.moving = true;
  13952. this.start();
  13953. }
  13954. };
  13955. /**
  13956. * Update the this.nodeIndices with the most recent node index list
  13957. * @private
  13958. */
  13959. Graph.prototype._updateNodeIndexList = function() {
  13960. this._clearNodeIndexList();
  13961. for (var idx in this.nodes) {
  13962. if (this.nodes.hasOwnProperty(idx)) {
  13963. this.nodeIndices.push(idx);
  13964. }
  13965. }
  13966. };
  13967. /**
  13968. * Set nodes and edges, and optionally options as well.
  13969. *
  13970. * @param {Object} data Object containing parameters:
  13971. * {Array | DataSet | DataView} [nodes] Array with nodes
  13972. * {Array | DataSet | DataView} [edges] Array with edges
  13973. * {String} [dot] String containing data in DOT format
  13974. * {Options} [options] Object with options
  13975. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  13976. */
  13977. Graph.prototype.setData = function(data, disableStart) {
  13978. if (disableStart === undefined) {
  13979. disableStart = false;
  13980. }
  13981. if (data && data.dot && (data.nodes || data.edges)) {
  13982. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  13983. ' parameter pair "nodes" and "edges", but not both.');
  13984. }
  13985. // set options
  13986. this.setOptions(data && data.options);
  13987. // set all data
  13988. if (data && data.dot) {
  13989. // parse DOT file
  13990. if(data && data.dot) {
  13991. var dotData = vis.util.DOTToGraph(data.dot);
  13992. this.setData(dotData);
  13993. return;
  13994. }
  13995. }
  13996. else {
  13997. this._setNodes(data && data.nodes);
  13998. this._setEdges(data && data.edges);
  13999. }
  14000. this._putDataInSector();
  14001. if (!disableStart) {
  14002. // find a stable position or start animating to a stable position
  14003. if (this.stabilize) {
  14004. this._stabilize();
  14005. }
  14006. this.start();
  14007. }
  14008. };
  14009. /**
  14010. * Set options
  14011. * @param {Object} options
  14012. */
  14013. Graph.prototype.setOptions = function (options) {
  14014. if (options) {
  14015. var prop;
  14016. // retrieve parameter values
  14017. if (options.width !== undefined) {this.width = options.width;}
  14018. if (options.height !== undefined) {this.height = options.height;}
  14019. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14020. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14021. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14022. if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;}
  14023. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14024. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  14025. if (options.labels !== undefined) {
  14026. for (prop in options.labels) {
  14027. if (options.labels.hasOwnProperty(prop)) {
  14028. this.constants.labels[prop] = options.labels[prop];
  14029. }
  14030. }
  14031. }
  14032. if (options.onAdd) {
  14033. this.triggerFunctions.add = options.onAdd;
  14034. }
  14035. if (options.onEdit) {
  14036. this.triggerFunctions.edit = options.onEdit;
  14037. }
  14038. if (options.onConnect) {
  14039. this.triggerFunctions.connect = options.onConnect;
  14040. }
  14041. if (options.onDelete) {
  14042. this.triggerFunctions.del = options.onDelete;
  14043. }
  14044. if (options.physics) {
  14045. if (options.physics.barnesHut) {
  14046. this.constants.physics.barnesHut.enabled = true;
  14047. for (prop in options.physics.barnesHut) {
  14048. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14049. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14050. }
  14051. }
  14052. }
  14053. if (options.physics.repulsion) {
  14054. this.constants.physics.barnesHut.enabled = false;
  14055. for (prop in options.physics.repulsion) {
  14056. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14057. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14058. }
  14059. }
  14060. }
  14061. }
  14062. if (options.hierarchicalLayout) {
  14063. this.constants.hierarchicalLayout.enabled = true;
  14064. for (prop in options.hierarchicalLayout) {
  14065. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14066. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14067. }
  14068. }
  14069. }
  14070. else if (options.hierarchicalLayout !== undefined) {
  14071. this.constants.hierarchicalLayout.enabled = false;
  14072. }
  14073. if (options.clustering) {
  14074. this.constants.clustering.enabled = true;
  14075. for (prop in options.clustering) {
  14076. if (options.clustering.hasOwnProperty(prop)) {
  14077. this.constants.clustering[prop] = options.clustering[prop];
  14078. }
  14079. }
  14080. }
  14081. else if (options.clustering !== undefined) {
  14082. this.constants.clustering.enabled = false;
  14083. }
  14084. if (options.navigation) {
  14085. this.constants.navigation.enabled = true;
  14086. for (prop in options.navigation) {
  14087. if (options.navigation.hasOwnProperty(prop)) {
  14088. this.constants.navigation[prop] = options.navigation[prop];
  14089. }
  14090. }
  14091. }
  14092. else if (options.navigation !== undefined) {
  14093. this.constants.navigation.enabled = false;
  14094. }
  14095. if (options.keyboard) {
  14096. this.constants.keyboard.enabled = true;
  14097. for (prop in options.keyboard) {
  14098. if (options.keyboard.hasOwnProperty(prop)) {
  14099. this.constants.keyboard[prop] = options.keyboard[prop];
  14100. }
  14101. }
  14102. }
  14103. else if (options.keyboard !== undefined) {
  14104. this.constants.keyboard.enabled = false;
  14105. }
  14106. if (options.dataManipulation) {
  14107. this.constants.dataManipulation.enabled = true;
  14108. for (prop in options.dataManipulation) {
  14109. if (options.dataManipulation.hasOwnProperty(prop)) {
  14110. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14111. }
  14112. }
  14113. }
  14114. else if (options.dataManipulation !== undefined) {
  14115. this.constants.dataManipulation.enabled = false;
  14116. }
  14117. // TODO: work out these options and document them
  14118. if (options.edges) {
  14119. for (prop in options.edges) {
  14120. if (options.edges.hasOwnProperty(prop)) {
  14121. if (typeof options.edges[prop] != "object") {
  14122. this.constants.edges[prop] = options.edges[prop];
  14123. }
  14124. }
  14125. }
  14126. if (options.edges.color !== undefined) {
  14127. if (util.isString(options.edges.color)) {
  14128. this.constants.edges.color = {};
  14129. this.constants.edges.color.color = options.edges.color;
  14130. this.constants.edges.color.highlight = options.edges.color;
  14131. }
  14132. else {
  14133. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  14134. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  14135. }
  14136. }
  14137. if (!options.edges.fontColor) {
  14138. if (options.edges.color !== undefined) {
  14139. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  14140. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  14141. }
  14142. }
  14143. // Added to support dashed lines
  14144. // David Jordan
  14145. // 2012-08-08
  14146. if (options.edges.dash) {
  14147. if (options.edges.dash.length !== undefined) {
  14148. this.constants.edges.dash.length = options.edges.dash.length;
  14149. }
  14150. if (options.edges.dash.gap !== undefined) {
  14151. this.constants.edges.dash.gap = options.edges.dash.gap;
  14152. }
  14153. if (options.edges.dash.altLength !== undefined) {
  14154. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14155. }
  14156. }
  14157. }
  14158. if (options.nodes) {
  14159. for (prop in options.nodes) {
  14160. if (options.nodes.hasOwnProperty(prop)) {
  14161. this.constants.nodes[prop] = options.nodes[prop];
  14162. }
  14163. }
  14164. if (options.nodes.color) {
  14165. this.constants.nodes.color = util.parseColor(options.nodes.color);
  14166. }
  14167. /*
  14168. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14169. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14170. */
  14171. }
  14172. if (options.groups) {
  14173. for (var groupname in options.groups) {
  14174. if (options.groups.hasOwnProperty(groupname)) {
  14175. var group = options.groups[groupname];
  14176. this.groups.add(groupname, group);
  14177. }
  14178. }
  14179. }
  14180. if (options.tooltip) {
  14181. for (prop in options.tooltip) {
  14182. if (options.tooltip.hasOwnProperty(prop)) {
  14183. this.constants.tooltip[prop] = options.tooltip[prop];
  14184. }
  14185. }
  14186. if (options.tooltip.color) {
  14187. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  14188. }
  14189. }
  14190. }
  14191. // (Re)loading the mixins that can be enabled or disabled in the options.
  14192. // load the force calculation functions, grouped under the physics system.
  14193. this._loadPhysicsSystem();
  14194. // load the navigation system.
  14195. this._loadNavigationControls();
  14196. // load the data manipulation system
  14197. this._loadManipulationSystem();
  14198. // configure the smooth curves
  14199. this._configureSmoothCurves();
  14200. // bind keys. If disabled, this will not do anything;
  14201. this._createKeyBinds();
  14202. this.setSize(this.width, this.height);
  14203. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14204. this._setScale(1);
  14205. this._redraw();
  14206. };
  14207. /**
  14208. * Create the main frame for the Graph.
  14209. * This function is executed once when a Graph object is created. The frame
  14210. * contains a canvas, and this canvas contains all objects like the axis and
  14211. * nodes.
  14212. * @private
  14213. */
  14214. Graph.prototype._create = function () {
  14215. // remove all elements from the container element.
  14216. while (this.containerElement.hasChildNodes()) {
  14217. this.containerElement.removeChild(this.containerElement.firstChild);
  14218. }
  14219. this.frame = document.createElement('div');
  14220. this.frame.className = 'graph-frame';
  14221. this.frame.style.position = 'relative';
  14222. this.frame.style.overflow = 'hidden';
  14223. // create the graph canvas (HTML canvas element)
  14224. this.frame.canvas = document.createElement( 'canvas' );
  14225. this.frame.canvas.style.position = 'relative';
  14226. this.frame.appendChild(this.frame.canvas);
  14227. if (!this.frame.canvas.getContext) {
  14228. var noCanvas = document.createElement( 'DIV' );
  14229. noCanvas.style.color = 'red';
  14230. noCanvas.style.fontWeight = 'bold' ;
  14231. noCanvas.style.padding = '10px';
  14232. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14233. this.frame.canvas.appendChild(noCanvas);
  14234. }
  14235. var me = this;
  14236. this.drag = {};
  14237. this.pinch = {};
  14238. this.hammer = Hammer(this.frame.canvas, {
  14239. prevent_default: true
  14240. });
  14241. this.hammer.on('tap', me._onTap.bind(me) );
  14242. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14243. this.hammer.on('hold', me._onHold.bind(me) );
  14244. this.hammer.on('pinch', me._onPinch.bind(me) );
  14245. this.hammer.on('touch', me._onTouch.bind(me) );
  14246. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14247. this.hammer.on('drag', me._onDrag.bind(me) );
  14248. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14249. this.hammer.on('release', me._onRelease.bind(me) );
  14250. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14251. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14252. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14253. // add the frame to the container element
  14254. this.containerElement.appendChild(this.frame);
  14255. };
  14256. /**
  14257. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14258. * @private
  14259. */
  14260. Graph.prototype._createKeyBinds = function() {
  14261. var me = this;
  14262. this.mousetrap = mousetrap;
  14263. this.mousetrap.reset();
  14264. if (this.constants.keyboard.enabled == true) {
  14265. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14266. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14267. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14268. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14269. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14270. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14271. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14272. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14273. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14274. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14275. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14276. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14277. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14278. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14279. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14280. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14281. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14282. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14283. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14284. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14285. }
  14286. if (this.constants.dataManipulation.enabled == true) {
  14287. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14288. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14289. }
  14290. };
  14291. /**
  14292. * Get the pointer location from a touch location
  14293. * @param {{pageX: Number, pageY: Number}} touch
  14294. * @return {{x: Number, y: Number}} pointer
  14295. * @private
  14296. */
  14297. Graph.prototype._getPointer = function (touch) {
  14298. return {
  14299. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14300. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14301. };
  14302. };
  14303. /**
  14304. * On start of a touch gesture, store the pointer
  14305. * @param event
  14306. * @private
  14307. */
  14308. Graph.prototype._onTouch = function (event) {
  14309. this.drag.pointer = this._getPointer(event.gesture.center);
  14310. this.drag.pinched = false;
  14311. this.pinch.scale = this._getScale();
  14312. this._handleTouch(this.drag.pointer);
  14313. };
  14314. /**
  14315. * handle drag start event
  14316. * @private
  14317. */
  14318. Graph.prototype._onDragStart = function () {
  14319. this._handleDragStart();
  14320. };
  14321. /**
  14322. * This function is called by _onDragStart.
  14323. * It is separated out because we can then overload it for the datamanipulation system.
  14324. *
  14325. * @private
  14326. */
  14327. Graph.prototype._handleDragStart = function() {
  14328. var drag = this.drag;
  14329. var node = this._getNodeAt(drag.pointer);
  14330. // note: drag.pointer is set in _onTouch to get the initial touch location
  14331. drag.dragging = true;
  14332. drag.selection = [];
  14333. drag.translation = this._getTranslation();
  14334. drag.nodeId = null;
  14335. if (node != null) {
  14336. drag.nodeId = node.id;
  14337. // select the clicked node if not yet selected
  14338. if (!node.isSelected()) {
  14339. this._selectObject(node,false);
  14340. }
  14341. // create an array with the selected nodes and their original location and status
  14342. for (var objectId in this.selectionObj.nodes) {
  14343. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  14344. var object = this.selectionObj.nodes[objectId];
  14345. var s = {
  14346. id: object.id,
  14347. node: object,
  14348. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14349. x: object.x,
  14350. y: object.y,
  14351. xFixed: object.xFixed,
  14352. yFixed: object.yFixed
  14353. };
  14354. object.xFixed = true;
  14355. object.yFixed = true;
  14356. drag.selection.push(s);
  14357. }
  14358. }
  14359. }
  14360. };
  14361. /**
  14362. * handle drag event
  14363. * @private
  14364. */
  14365. Graph.prototype._onDrag = function (event) {
  14366. this._handleOnDrag(event)
  14367. };
  14368. /**
  14369. * This function is called by _onDrag.
  14370. * It is separated out because we can then overload it for the datamanipulation system.
  14371. *
  14372. * @private
  14373. */
  14374. Graph.prototype._handleOnDrag = function(event) {
  14375. if (this.drag.pinched) {
  14376. return;
  14377. }
  14378. var pointer = this._getPointer(event.gesture.center);
  14379. var me = this,
  14380. drag = this.drag,
  14381. selection = drag.selection;
  14382. if (selection && selection.length) {
  14383. // calculate delta's and new location
  14384. var deltaX = pointer.x - drag.pointer.x,
  14385. deltaY = pointer.y - drag.pointer.y;
  14386. // update position of all selected nodes
  14387. selection.forEach(function (s) {
  14388. var node = s.node;
  14389. if (!s.xFixed) {
  14390. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14391. }
  14392. if (!s.yFixed) {
  14393. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14394. }
  14395. });
  14396. // start _animationStep if not yet running
  14397. if (!this.moving) {
  14398. this.moving = true;
  14399. this.start();
  14400. }
  14401. }
  14402. else {
  14403. // move the graph
  14404. var diffX = pointer.x - this.drag.pointer.x;
  14405. var diffY = pointer.y - this.drag.pointer.y;
  14406. this._setTranslation(
  14407. this.drag.translation.x + diffX,
  14408. this.drag.translation.y + diffY);
  14409. this._redraw();
  14410. this.moving = true;
  14411. }
  14412. };
  14413. /**
  14414. * handle drag start event
  14415. * @private
  14416. */
  14417. Graph.prototype._onDragEnd = function () {
  14418. this.drag.dragging = false;
  14419. var selection = this.drag.selection;
  14420. if (selection) {
  14421. selection.forEach(function (s) {
  14422. // restore original xFixed and yFixed
  14423. s.node.xFixed = s.xFixed;
  14424. s.node.yFixed = s.yFixed;
  14425. });
  14426. }
  14427. };
  14428. /**
  14429. * handle tap/click event: select/unselect a node
  14430. * @private
  14431. */
  14432. Graph.prototype._onTap = function (event) {
  14433. var pointer = this._getPointer(event.gesture.center);
  14434. this.pointerPosition = pointer;
  14435. this._handleTap(pointer);
  14436. };
  14437. /**
  14438. * handle doubletap event
  14439. * @private
  14440. */
  14441. Graph.prototype._onDoubleTap = function (event) {
  14442. var pointer = this._getPointer(event.gesture.center);
  14443. this._handleDoubleTap(pointer);
  14444. };
  14445. /**
  14446. * handle long tap event: multi select nodes
  14447. * @private
  14448. */
  14449. Graph.prototype._onHold = function (event) {
  14450. var pointer = this._getPointer(event.gesture.center);
  14451. this.pointerPosition = pointer;
  14452. this._handleOnHold(pointer);
  14453. };
  14454. /**
  14455. * handle the release of the screen
  14456. *
  14457. * @private
  14458. */
  14459. Graph.prototype._onRelease = function (event) {
  14460. var pointer = this._getPointer(event.gesture.center);
  14461. this._handleOnRelease(pointer);
  14462. };
  14463. /**
  14464. * Handle pinch event
  14465. * @param event
  14466. * @private
  14467. */
  14468. Graph.prototype._onPinch = function (event) {
  14469. var pointer = this._getPointer(event.gesture.center);
  14470. this.drag.pinched = true;
  14471. if (!('scale' in this.pinch)) {
  14472. this.pinch.scale = 1;
  14473. }
  14474. // TODO: enabled moving while pinching?
  14475. var scale = this.pinch.scale * event.gesture.scale;
  14476. this._zoom(scale, pointer)
  14477. };
  14478. /**
  14479. * Zoom the graph in or out
  14480. * @param {Number} scale a number around 1, and between 0.01 and 10
  14481. * @param {{x: Number, y: Number}} pointer Position on screen
  14482. * @return {Number} appliedScale scale is limited within the boundaries
  14483. * @private
  14484. */
  14485. Graph.prototype._zoom = function(scale, pointer) {
  14486. var scaleOld = this._getScale();
  14487. if (scale < 0.00001) {
  14488. scale = 0.00001;
  14489. }
  14490. if (scale > 10) {
  14491. scale = 10;
  14492. }
  14493. // + this.frame.canvas.clientHeight / 2
  14494. var translation = this._getTranslation();
  14495. var scaleFrac = scale / scaleOld;
  14496. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14497. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14498. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  14499. "y" : this._canvasToY(pointer.y)};
  14500. this._setScale(scale);
  14501. this._setTranslation(tx, ty);
  14502. this.updateClustersDefault();
  14503. this._redraw();
  14504. return scale;
  14505. };
  14506. /**
  14507. * Event handler for mouse wheel event, used to zoom the timeline
  14508. * See http://adomas.org/javascript-mouse-wheel/
  14509. * https://github.com/EightMedia/hammer.js/issues/256
  14510. * @param {MouseEvent} event
  14511. * @private
  14512. */
  14513. Graph.prototype._onMouseWheel = function(event) {
  14514. // retrieve delta
  14515. var delta = 0;
  14516. if (event.wheelDelta) { /* IE/Opera. */
  14517. delta = event.wheelDelta/120;
  14518. } else if (event.detail) { /* Mozilla case. */
  14519. // In Mozilla, sign of delta is different than in IE.
  14520. // Also, delta is multiple of 3.
  14521. delta = -event.detail/3;
  14522. }
  14523. // If delta is nonzero, handle it.
  14524. // Basically, delta is now positive if wheel was scrolled up,
  14525. // and negative, if wheel was scrolled down.
  14526. if (delta) {
  14527. // calculate the new scale
  14528. var scale = this._getScale();
  14529. var zoom = delta / 10;
  14530. if (delta < 0) {
  14531. zoom = zoom / (1 - zoom);
  14532. }
  14533. scale *= (1 + zoom);
  14534. // calculate the pointer location
  14535. var gesture = util.fakeGesture(this, event);
  14536. var pointer = this._getPointer(gesture.center);
  14537. // apply the new scale
  14538. this._zoom(scale, pointer);
  14539. }
  14540. // Prevent default actions caused by mouse wheel.
  14541. event.preventDefault();
  14542. };
  14543. /**
  14544. * Mouse move handler for checking whether the title moves over a node with a title.
  14545. * @param {Event} event
  14546. * @private
  14547. */
  14548. Graph.prototype._onMouseMoveTitle = function (event) {
  14549. var gesture = util.fakeGesture(this, event);
  14550. var pointer = this._getPointer(gesture.center);
  14551. // check if the previously selected node is still selected
  14552. if (this.popupNode) {
  14553. this._checkHidePopup(pointer);
  14554. }
  14555. // start a timeout that will check if the mouse is positioned above
  14556. // an element
  14557. var me = this;
  14558. var checkShow = function() {
  14559. me._checkShowPopup(pointer);
  14560. };
  14561. if (this.popupTimer) {
  14562. clearInterval(this.popupTimer); // stop any running calculationTimer
  14563. }
  14564. if (!this.drag.dragging) {
  14565. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  14566. }
  14567. };
  14568. /**
  14569. * Check if there is an element on the given position in the graph
  14570. * (a node or edge). If so, and if this element has a title,
  14571. * show a popup window with its title.
  14572. *
  14573. * @param {{x:Number, y:Number}} pointer
  14574. * @private
  14575. */
  14576. Graph.prototype._checkShowPopup = function (pointer) {
  14577. var obj = {
  14578. left: this._canvasToX(pointer.x),
  14579. top: this._canvasToY(pointer.y),
  14580. right: this._canvasToX(pointer.x),
  14581. bottom: this._canvasToY(pointer.y)
  14582. };
  14583. var id;
  14584. var lastPopupNode = this.popupNode;
  14585. if (this.popupNode == undefined) {
  14586. // search the nodes for overlap, select the top one in case of multiple nodes
  14587. var nodes = this.nodes;
  14588. for (id in nodes) {
  14589. if (nodes.hasOwnProperty(id)) {
  14590. var node = nodes[id];
  14591. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14592. this.popupNode = node;
  14593. break;
  14594. }
  14595. }
  14596. }
  14597. }
  14598. if (this.popupNode === undefined) {
  14599. // search the edges for overlap
  14600. var edges = this.edges;
  14601. for (id in edges) {
  14602. if (edges.hasOwnProperty(id)) {
  14603. var edge = edges[id];
  14604. if (edge.connected && (edge.getTitle() !== undefined) &&
  14605. edge.isOverlappingWith(obj)) {
  14606. this.popupNode = edge;
  14607. break;
  14608. }
  14609. }
  14610. }
  14611. }
  14612. if (this.popupNode) {
  14613. // show popup message window
  14614. if (this.popupNode != lastPopupNode) {
  14615. var me = this;
  14616. if (!me.popup) {
  14617. me.popup = new Popup(me.frame, me.constants.tooltip);
  14618. }
  14619. // adjust a small offset such that the mouse cursor is located in the
  14620. // bottom left location of the popup, and you can easily move over the
  14621. // popup area
  14622. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14623. me.popup.setText(me.popupNode.getTitle());
  14624. me.popup.show();
  14625. }
  14626. }
  14627. else {
  14628. if (this.popup) {
  14629. this.popup.hide();
  14630. }
  14631. }
  14632. };
  14633. /**
  14634. * Check if the popup must be hided, which is the case when the mouse is no
  14635. * longer hovering on the object
  14636. * @param {{x:Number, y:Number}} pointer
  14637. * @private
  14638. */
  14639. Graph.prototype._checkHidePopup = function (pointer) {
  14640. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  14641. this.popupNode = undefined;
  14642. if (this.popup) {
  14643. this.popup.hide();
  14644. }
  14645. }
  14646. };
  14647. /**
  14648. * Set a new size for the graph
  14649. * @param {string} width Width in pixels or percentage (for example '800px'
  14650. * or '50%')
  14651. * @param {string} height Height in pixels or percentage (for example '400px'
  14652. * or '30%')
  14653. */
  14654. Graph.prototype.setSize = function(width, height) {
  14655. this.frame.style.width = width;
  14656. this.frame.style.height = height;
  14657. this.frame.canvas.style.width = '100%';
  14658. this.frame.canvas.style.height = '100%';
  14659. this.frame.canvas.width = this.frame.canvas.clientWidth;
  14660. this.frame.canvas.height = this.frame.canvas.clientHeight;
  14661. if (this.manipulationDiv !== undefined) {
  14662. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  14663. }
  14664. if (this.navigationDivs !== undefined) {
  14665. if (this.navigationDivs['wrapper'] !== undefined) {
  14666. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  14667. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  14668. }
  14669. }
  14670. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  14671. };
  14672. /**
  14673. * Set a data set with nodes for the graph
  14674. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14675. * @private
  14676. */
  14677. Graph.prototype._setNodes = function(nodes) {
  14678. var oldNodesData = this.nodesData;
  14679. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14680. this.nodesData = nodes;
  14681. }
  14682. else if (nodes instanceof Array) {
  14683. this.nodesData = new DataSet();
  14684. this.nodesData.add(nodes);
  14685. }
  14686. else if (!nodes) {
  14687. this.nodesData = new DataSet();
  14688. }
  14689. else {
  14690. throw new TypeError('Array or DataSet expected');
  14691. }
  14692. if (oldNodesData) {
  14693. // unsubscribe from old dataset
  14694. util.forEach(this.nodesListeners, function (callback, event) {
  14695. oldNodesData.off(event, callback);
  14696. });
  14697. }
  14698. // remove drawn nodes
  14699. this.nodes = {};
  14700. if (this.nodesData) {
  14701. // subscribe to new dataset
  14702. var me = this;
  14703. util.forEach(this.nodesListeners, function (callback, event) {
  14704. me.nodesData.on(event, callback);
  14705. });
  14706. // draw all new nodes
  14707. var ids = this.nodesData.getIds();
  14708. this._addNodes(ids);
  14709. }
  14710. this._updateSelection();
  14711. };
  14712. /**
  14713. * Add nodes
  14714. * @param {Number[] | String[]} ids
  14715. * @private
  14716. */
  14717. Graph.prototype._addNodes = function(ids) {
  14718. var id;
  14719. for (var i = 0, len = ids.length; i < len; i++) {
  14720. id = ids[i];
  14721. var data = this.nodesData.get(id);
  14722. var node = new Node(data, this.images, this.groups, this.constants);
  14723. this.nodes[id] = node; // note: this may replace an existing node
  14724. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  14725. var radius = 10 * 0.1*ids.length;
  14726. var angle = 2 * Math.PI * Math.random();
  14727. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  14728. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  14729. }
  14730. this.moving = true;
  14731. }
  14732. this._updateNodeIndexList();
  14733. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14734. this._resetLevels();
  14735. this._setupHierarchicalLayout();
  14736. }
  14737. this._updateCalculationNodes();
  14738. this._reconnectEdges();
  14739. this._updateValueRange(this.nodes);
  14740. this.updateLabels();
  14741. };
  14742. /**
  14743. * Update existing nodes, or create them when not yet existing
  14744. * @param {Number[] | String[]} ids
  14745. * @private
  14746. */
  14747. Graph.prototype._updateNodes = function(ids) {
  14748. var nodes = this.nodes,
  14749. nodesData = this.nodesData;
  14750. for (var i = 0, len = ids.length; i < len; i++) {
  14751. var id = ids[i];
  14752. var node = nodes[id];
  14753. var data = nodesData.get(id);
  14754. if (node) {
  14755. // update node
  14756. node.setProperties(data, this.constants);
  14757. }
  14758. else {
  14759. // create node
  14760. node = new Node(properties, this.images, this.groups, this.constants);
  14761. nodes[id] = node;
  14762. }
  14763. }
  14764. this.moving = true;
  14765. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14766. this._resetLevels();
  14767. this._setupHierarchicalLayout();
  14768. }
  14769. this._updateNodeIndexList();
  14770. this._reconnectEdges();
  14771. this._updateValueRange(nodes);
  14772. };
  14773. /**
  14774. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  14775. * @param {Number[] | String[]} ids
  14776. * @private
  14777. */
  14778. Graph.prototype._removeNodes = function(ids) {
  14779. var nodes = this.nodes;
  14780. for (var i = 0, len = ids.length; i < len; i++) {
  14781. var id = ids[i];
  14782. delete nodes[id];
  14783. }
  14784. this._updateNodeIndexList();
  14785. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14786. this._resetLevels();
  14787. this._setupHierarchicalLayout();
  14788. }
  14789. this._updateCalculationNodes();
  14790. this._reconnectEdges();
  14791. this._updateSelection();
  14792. this._updateValueRange(nodes);
  14793. };
  14794. /**
  14795. * Load edges by reading the data table
  14796. * @param {Array | DataSet | DataView} edges The data containing the edges.
  14797. * @private
  14798. * @private
  14799. */
  14800. Graph.prototype._setEdges = function(edges) {
  14801. var oldEdgesData = this.edgesData;
  14802. if (edges instanceof DataSet || edges instanceof DataView) {
  14803. this.edgesData = edges;
  14804. }
  14805. else if (edges instanceof Array) {
  14806. this.edgesData = new DataSet();
  14807. this.edgesData.add(edges);
  14808. }
  14809. else if (!edges) {
  14810. this.edgesData = new DataSet();
  14811. }
  14812. else {
  14813. throw new TypeError('Array or DataSet expected');
  14814. }
  14815. if (oldEdgesData) {
  14816. // unsubscribe from old dataset
  14817. util.forEach(this.edgesListeners, function (callback, event) {
  14818. oldEdgesData.off(event, callback);
  14819. });
  14820. }
  14821. // remove drawn edges
  14822. this.edges = {};
  14823. if (this.edgesData) {
  14824. // subscribe to new dataset
  14825. var me = this;
  14826. util.forEach(this.edgesListeners, function (callback, event) {
  14827. me.edgesData.on(event, callback);
  14828. });
  14829. // draw all new nodes
  14830. var ids = this.edgesData.getIds();
  14831. this._addEdges(ids);
  14832. }
  14833. this._reconnectEdges();
  14834. };
  14835. /**
  14836. * Add edges
  14837. * @param {Number[] | String[]} ids
  14838. * @private
  14839. */
  14840. Graph.prototype._addEdges = function (ids) {
  14841. var edges = this.edges,
  14842. edgesData = this.edgesData;
  14843. for (var i = 0, len = ids.length; i < len; i++) {
  14844. var id = ids[i];
  14845. var oldEdge = edges[id];
  14846. if (oldEdge) {
  14847. oldEdge.disconnect();
  14848. }
  14849. var data = edgesData.get(id, {"showInternalIds" : true});
  14850. edges[id] = new Edge(data, this, this.constants);
  14851. }
  14852. this.moving = true;
  14853. this._updateValueRange(edges);
  14854. this._createBezierNodes();
  14855. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14856. this._resetLevels();
  14857. this._setupHierarchicalLayout();
  14858. }
  14859. this._updateCalculationNodes();
  14860. };
  14861. /**
  14862. * Update existing edges, or create them when not yet existing
  14863. * @param {Number[] | String[]} ids
  14864. * @private
  14865. */
  14866. Graph.prototype._updateEdges = function (ids) {
  14867. var edges = this.edges,
  14868. edgesData = this.edgesData;
  14869. for (var i = 0, len = ids.length; i < len; i++) {
  14870. var id = ids[i];
  14871. var data = edgesData.get(id);
  14872. var edge = edges[id];
  14873. if (edge) {
  14874. // update edge
  14875. edge.disconnect();
  14876. edge.setProperties(data, this.constants);
  14877. edge.connect();
  14878. }
  14879. else {
  14880. // create edge
  14881. edge = new Edge(data, this, this.constants);
  14882. this.edges[id] = edge;
  14883. }
  14884. }
  14885. this._createBezierNodes();
  14886. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14887. this._resetLevels();
  14888. this._setupHierarchicalLayout();
  14889. }
  14890. this.moving = true;
  14891. this._updateValueRange(edges);
  14892. };
  14893. /**
  14894. * Remove existing edges. Non existing ids will be ignored
  14895. * @param {Number[] | String[]} ids
  14896. * @private
  14897. */
  14898. Graph.prototype._removeEdges = function (ids) {
  14899. var edges = this.edges;
  14900. for (var i = 0, len = ids.length; i < len; i++) {
  14901. var id = ids[i];
  14902. var edge = edges[id];
  14903. if (edge) {
  14904. if (edge.via != null) {
  14905. delete this.sectors['support']['nodes'][edge.via.id];
  14906. }
  14907. edge.disconnect();
  14908. delete edges[id];
  14909. }
  14910. }
  14911. this.moving = true;
  14912. this._updateValueRange(edges);
  14913. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14914. this._resetLevels();
  14915. this._setupHierarchicalLayout();
  14916. }
  14917. this._updateCalculationNodes();
  14918. };
  14919. /**
  14920. * Reconnect all edges
  14921. * @private
  14922. */
  14923. Graph.prototype._reconnectEdges = function() {
  14924. var id,
  14925. nodes = this.nodes,
  14926. edges = this.edges;
  14927. for (id in nodes) {
  14928. if (nodes.hasOwnProperty(id)) {
  14929. nodes[id].edges = [];
  14930. }
  14931. }
  14932. for (id in edges) {
  14933. if (edges.hasOwnProperty(id)) {
  14934. var edge = edges[id];
  14935. edge.from = null;
  14936. edge.to = null;
  14937. edge.connect();
  14938. }
  14939. }
  14940. };
  14941. /**
  14942. * Update the values of all object in the given array according to the current
  14943. * value range of the objects in the array.
  14944. * @param {Object} obj An object containing a set of Edges or Nodes
  14945. * The objects must have a method getValue() and
  14946. * setValueRange(min, max).
  14947. * @private
  14948. */
  14949. Graph.prototype._updateValueRange = function(obj) {
  14950. var id;
  14951. // determine the range of the objects
  14952. var valueMin = undefined;
  14953. var valueMax = undefined;
  14954. for (id in obj) {
  14955. if (obj.hasOwnProperty(id)) {
  14956. var value = obj[id].getValue();
  14957. if (value !== undefined) {
  14958. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  14959. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  14960. }
  14961. }
  14962. }
  14963. // adjust the range of all objects
  14964. if (valueMin !== undefined && valueMax !== undefined) {
  14965. for (id in obj) {
  14966. if (obj.hasOwnProperty(id)) {
  14967. obj[id].setValueRange(valueMin, valueMax);
  14968. }
  14969. }
  14970. }
  14971. };
  14972. /**
  14973. * Redraw the graph with the current data
  14974. * chart will be resized too.
  14975. */
  14976. Graph.prototype.redraw = function() {
  14977. this.setSize(this.width, this.height);
  14978. this._redraw();
  14979. };
  14980. /**
  14981. * Redraw the graph with the current data
  14982. * @private
  14983. */
  14984. Graph.prototype._redraw = function() {
  14985. var ctx = this.frame.canvas.getContext('2d');
  14986. // clear the canvas
  14987. var w = this.frame.canvas.width;
  14988. var h = this.frame.canvas.height;
  14989. ctx.clearRect(0, 0, w, h);
  14990. // set scaling and translation
  14991. ctx.save();
  14992. ctx.translate(this.translation.x, this.translation.y);
  14993. ctx.scale(this.scale, this.scale);
  14994. this.canvasTopLeft = {
  14995. "x": this._canvasToX(0),
  14996. "y": this._canvasToY(0)
  14997. };
  14998. this.canvasBottomRight = {
  14999. "x": this._canvasToX(this.frame.canvas.clientWidth),
  15000. "y": this._canvasToY(this.frame.canvas.clientHeight)
  15001. };
  15002. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15003. this._doInAllSectors("_drawEdges",ctx);
  15004. this._doInAllSectors("_drawNodes",ctx,false);
  15005. // this._doInSupportSector("_drawNodes",ctx,true);
  15006. // this._drawTree(ctx,"#F00F0F");
  15007. // restore original scaling and translation
  15008. ctx.restore();
  15009. };
  15010. /**
  15011. * Set the translation of the graph
  15012. * @param {Number} offsetX Horizontal offset
  15013. * @param {Number} offsetY Vertical offset
  15014. * @private
  15015. */
  15016. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15017. if (this.translation === undefined) {
  15018. this.translation = {
  15019. x: 0,
  15020. y: 0
  15021. };
  15022. }
  15023. if (offsetX !== undefined) {
  15024. this.translation.x = offsetX;
  15025. }
  15026. if (offsetY !== undefined) {
  15027. this.translation.y = offsetY;
  15028. }
  15029. };
  15030. /**
  15031. * Get the translation of the graph
  15032. * @return {Object} translation An object with parameters x and y, both a number
  15033. * @private
  15034. */
  15035. Graph.prototype._getTranslation = function() {
  15036. return {
  15037. x: this.translation.x,
  15038. y: this.translation.y
  15039. };
  15040. };
  15041. /**
  15042. * Scale the graph
  15043. * @param {Number} scale Scaling factor 1.0 is unscaled
  15044. * @private
  15045. */
  15046. Graph.prototype._setScale = function(scale) {
  15047. this.scale = scale;
  15048. };
  15049. /**
  15050. * Get the current scale of the graph
  15051. * @return {Number} scale Scaling factor 1.0 is unscaled
  15052. * @private
  15053. */
  15054. Graph.prototype._getScale = function() {
  15055. return this.scale;
  15056. };
  15057. /**
  15058. * Convert a horizontal point on the HTML canvas to the x-value of the model
  15059. * @param {number} x
  15060. * @returns {number}
  15061. * @private
  15062. */
  15063. Graph.prototype._canvasToX = function(x) {
  15064. return (x - this.translation.x) / this.scale;
  15065. };
  15066. /**
  15067. * Convert an x-value in the model to a horizontal point on the HTML canvas
  15068. * @param {number} x
  15069. * @returns {number}
  15070. * @private
  15071. */
  15072. Graph.prototype._xToCanvas = function(x) {
  15073. return x * this.scale + this.translation.x;
  15074. };
  15075. /**
  15076. * Convert a vertical point on the HTML canvas to the y-value of the model
  15077. * @param {number} y
  15078. * @returns {number}
  15079. * @private
  15080. */
  15081. Graph.prototype._canvasToY = function(y) {
  15082. return (y - this.translation.y) / this.scale;
  15083. };
  15084. /**
  15085. * Convert an y-value in the model to a vertical point on the HTML canvas
  15086. * @param {number} y
  15087. * @returns {number}
  15088. * @private
  15089. */
  15090. Graph.prototype._yToCanvas = function(y) {
  15091. return y * this.scale + this.translation.y ;
  15092. };
  15093. /**
  15094. * Redraw all nodes
  15095. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15096. * @param {CanvasRenderingContext2D} ctx
  15097. * @param {Boolean} [alwaysShow]
  15098. * @private
  15099. */
  15100. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  15101. if (alwaysShow === undefined) {
  15102. alwaysShow = false;
  15103. }
  15104. // first draw the unselected nodes
  15105. var nodes = this.nodes;
  15106. var selected = [];
  15107. for (var id in nodes) {
  15108. if (nodes.hasOwnProperty(id)) {
  15109. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15110. if (nodes[id].isSelected()) {
  15111. selected.push(id);
  15112. }
  15113. else {
  15114. if (nodes[id].inArea() || alwaysShow) {
  15115. nodes[id].draw(ctx);
  15116. }
  15117. }
  15118. }
  15119. }
  15120. // draw the selected nodes on top
  15121. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15122. if (nodes[selected[s]].inArea() || alwaysShow) {
  15123. nodes[selected[s]].draw(ctx);
  15124. }
  15125. }
  15126. };
  15127. /**
  15128. * Redraw all edges
  15129. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15130. * @param {CanvasRenderingContext2D} ctx
  15131. * @private
  15132. */
  15133. Graph.prototype._drawEdges = function(ctx) {
  15134. var edges = this.edges;
  15135. for (var id in edges) {
  15136. if (edges.hasOwnProperty(id)) {
  15137. var edge = edges[id];
  15138. edge.setScale(this.scale);
  15139. if (edge.connected) {
  15140. edges[id].draw(ctx);
  15141. }
  15142. }
  15143. }
  15144. };
  15145. /**
  15146. * Find a stable position for all nodes
  15147. * @private
  15148. */
  15149. Graph.prototype._stabilize = function() {
  15150. if (this.constants.freezeForStabilization == true) {
  15151. this._freezeDefinedNodes();
  15152. }
  15153. // find stable position
  15154. var count = 0;
  15155. while (this.moving && count < this.constants.stabilizationIterations) {
  15156. this._physicsTick();
  15157. count++;
  15158. }
  15159. this.zoomExtent(false,true);
  15160. if (this.constants.freezeForStabilization == true) {
  15161. this._restoreFrozenNodes();
  15162. }
  15163. this.emit("stabilized",{iterations:count});
  15164. };
  15165. /**
  15166. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  15167. * because only the supportnodes for the smoothCurves have to settle.
  15168. *
  15169. * @private
  15170. */
  15171. Graph.prototype._freezeDefinedNodes = function() {
  15172. var nodes = this.nodes;
  15173. for (var id in nodes) {
  15174. if (nodes.hasOwnProperty(id)) {
  15175. if (nodes[id].x != null && nodes[id].y != null) {
  15176. nodes[id].fixedData.x = nodes[id].xFixed;
  15177. nodes[id].fixedData.y = nodes[id].yFixed;
  15178. nodes[id].xFixed = true;
  15179. nodes[id].yFixed = true;
  15180. }
  15181. }
  15182. }
  15183. };
  15184. /**
  15185. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  15186. *
  15187. * @private
  15188. */
  15189. Graph.prototype._restoreFrozenNodes = function() {
  15190. var nodes = this.nodes;
  15191. for (var id in nodes) {
  15192. if (nodes.hasOwnProperty(id)) {
  15193. if (nodes[id].fixedData.x != null) {
  15194. nodes[id].xFixed = nodes[id].fixedData.x;
  15195. nodes[id].yFixed = nodes[id].fixedData.y;
  15196. }
  15197. }
  15198. }
  15199. };
  15200. /**
  15201. * Check if any of the nodes is still moving
  15202. * @param {number} vmin the minimum velocity considered as 'moving'
  15203. * @return {boolean} true if moving, false if non of the nodes is moving
  15204. * @private
  15205. */
  15206. Graph.prototype._isMoving = function(vmin) {
  15207. var nodes = this.nodes;
  15208. for (var id in nodes) {
  15209. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15210. return true;
  15211. }
  15212. }
  15213. return false;
  15214. };
  15215. /**
  15216. * /**
  15217. * Perform one discrete step for all nodes
  15218. *
  15219. * @private
  15220. */
  15221. Graph.prototype._discreteStepNodes = function() {
  15222. var interval = this.physicsDiscreteStepsize;
  15223. var nodes = this.nodes;
  15224. var nodeId;
  15225. var nodesPresent = false;
  15226. if (this.constants.maxVelocity > 0) {
  15227. for (nodeId in nodes) {
  15228. if (nodes.hasOwnProperty(nodeId)) {
  15229. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15230. nodesPresent = true;
  15231. }
  15232. }
  15233. }
  15234. else {
  15235. for (nodeId in nodes) {
  15236. if (nodes.hasOwnProperty(nodeId)) {
  15237. nodes[nodeId].discreteStep(interval);
  15238. nodesPresent = true;
  15239. }
  15240. }
  15241. }
  15242. if (nodesPresent == true) {
  15243. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15244. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15245. this.moving = true;
  15246. }
  15247. else {
  15248. this.moving = this._isMoving(vminCorrected);
  15249. }
  15250. }
  15251. };
  15252. /**
  15253. * A single simulation step (or "tick") in the physics simulation
  15254. *
  15255. * @private
  15256. */
  15257. Graph.prototype._physicsTick = function() {
  15258. if (!this.freezeSimulation) {
  15259. if (this.moving) {
  15260. this._doInAllActiveSectors("_initializeForceCalculation");
  15261. this._doInAllActiveSectors("_discreteStepNodes");
  15262. if (this.constants.smoothCurves) {
  15263. this._doInSupportSector("_discreteStepNodes");
  15264. }
  15265. this._findCenter(this._getRange())
  15266. }
  15267. }
  15268. };
  15269. /**
  15270. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15271. * It reschedules itself at the beginning of the function
  15272. *
  15273. * @private
  15274. */
  15275. Graph.prototype._animationStep = function() {
  15276. // reset the timer so a new scheduled animation step can be set
  15277. this.timer = undefined;
  15278. // handle the keyboad movement
  15279. this._handleNavigation();
  15280. // this schedules a new animation step
  15281. this.start();
  15282. // start the physics simulation
  15283. var calculationTime = Date.now();
  15284. var maxSteps = 1;
  15285. this._physicsTick();
  15286. var timeRequired = Date.now() - calculationTime;
  15287. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  15288. this._physicsTick();
  15289. timeRequired = Date.now() - calculationTime;
  15290. maxSteps++;
  15291. }
  15292. // start the rendering process
  15293. var renderTime = Date.now();
  15294. this._redraw();
  15295. this.renderTime = Date.now() - renderTime;
  15296. };
  15297. if (typeof window !== 'undefined') {
  15298. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15299. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15300. }
  15301. /**
  15302. * Schedule a animation step with the refreshrate interval.
  15303. */
  15304. Graph.prototype.start = function() {
  15305. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15306. if (!this.timer) {
  15307. var ua = navigator.userAgent.toLowerCase();
  15308. var requiresTimeout = false;
  15309. if (ua.indexOf('msie 9.0') != -1) { // IE 9
  15310. requiresTimeout = true;
  15311. }
  15312. else if (ua.indexOf('safari') != -1) { // safari
  15313. if (ua.indexOf('chrome') <= -1) {
  15314. requiresTimeout = true;
  15315. }
  15316. }
  15317. if (requiresTimeout == true) {
  15318. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15319. }
  15320. else{
  15321. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15322. }
  15323. }
  15324. }
  15325. else {
  15326. this._redraw();
  15327. }
  15328. };
  15329. /**
  15330. * Move the graph according to the keyboard presses.
  15331. *
  15332. * @private
  15333. */
  15334. Graph.prototype._handleNavigation = function() {
  15335. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15336. var translation = this._getTranslation();
  15337. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15338. }
  15339. if (this.zoomIncrement != 0) {
  15340. var center = {
  15341. x: this.frame.canvas.clientWidth / 2,
  15342. y: this.frame.canvas.clientHeight / 2
  15343. };
  15344. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15345. }
  15346. };
  15347. /**
  15348. * Freeze the _animationStep
  15349. */
  15350. Graph.prototype.toggleFreeze = function() {
  15351. if (this.freezeSimulation == false) {
  15352. this.freezeSimulation = true;
  15353. }
  15354. else {
  15355. this.freezeSimulation = false;
  15356. this.start();
  15357. }
  15358. };
  15359. /**
  15360. * This function cleans the support nodes if they are not needed and adds them when they are.
  15361. *
  15362. * @param {boolean} [disableStart]
  15363. * @private
  15364. */
  15365. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15366. if (disableStart === undefined) {
  15367. disableStart = true;
  15368. }
  15369. if (this.constants.smoothCurves == true) {
  15370. this._createBezierNodes();
  15371. }
  15372. else {
  15373. // delete the support nodes
  15374. this.sectors['support']['nodes'] = {};
  15375. for (var edgeId in this.edges) {
  15376. if (this.edges.hasOwnProperty(edgeId)) {
  15377. this.edges[edgeId].smooth = false;
  15378. this.edges[edgeId].via = null;
  15379. }
  15380. }
  15381. }
  15382. this._updateCalculationNodes();
  15383. if (!disableStart) {
  15384. this.moving = true;
  15385. this.start();
  15386. }
  15387. };
  15388. /**
  15389. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  15390. * are used for the force calculation.
  15391. *
  15392. * @private
  15393. */
  15394. Graph.prototype._createBezierNodes = function() {
  15395. if (this.constants.smoothCurves == true) {
  15396. for (var edgeId in this.edges) {
  15397. if (this.edges.hasOwnProperty(edgeId)) {
  15398. var edge = this.edges[edgeId];
  15399. if (edge.via == null) {
  15400. edge.smooth = true;
  15401. var nodeId = "edgeId:".concat(edge.id);
  15402. this.sectors['support']['nodes'][nodeId] = new Node(
  15403. {id:nodeId,
  15404. mass:1,
  15405. shape:'circle',
  15406. image:"",
  15407. internalMultiplier:1
  15408. },{},{},this.constants);
  15409. edge.via = this.sectors['support']['nodes'][nodeId];
  15410. edge.via.parentEdgeId = edge.id;
  15411. edge.positionBezierNode();
  15412. }
  15413. }
  15414. }
  15415. }
  15416. };
  15417. /**
  15418. * load the functions that load the mixins into the prototype.
  15419. *
  15420. * @private
  15421. */
  15422. Graph.prototype._initializeMixinLoaders = function () {
  15423. for (var mixinFunction in graphMixinLoaders) {
  15424. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15425. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15426. }
  15427. }
  15428. };
  15429. /**
  15430. * Load the XY positions of the nodes into the dataset.
  15431. */
  15432. Graph.prototype.storePosition = function() {
  15433. var dataArray = [];
  15434. for (var nodeId in this.nodes) {
  15435. if (this.nodes.hasOwnProperty(nodeId)) {
  15436. var node = this.nodes[nodeId];
  15437. var allowedToMoveX = !this.nodes.xFixed;
  15438. var allowedToMoveY = !this.nodes.yFixed;
  15439. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  15440. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15441. }
  15442. }
  15443. }
  15444. this.nodesData.update(dataArray);
  15445. };
  15446. /**
  15447. * vis.js module exports
  15448. */
  15449. var vis = {
  15450. util: util,
  15451. DataSet: DataSet,
  15452. DataView: DataView,
  15453. Range: Range,
  15454. stack: stack,
  15455. TimeStep: TimeStep,
  15456. components: {
  15457. items: {
  15458. Item: Item,
  15459. ItemBox: ItemBox,
  15460. ItemPoint: ItemPoint,
  15461. ItemRange: ItemRange
  15462. },
  15463. Component: Component,
  15464. Panel: Panel,
  15465. RootPanel: RootPanel,
  15466. ItemSet: ItemSet,
  15467. TimeAxis: TimeAxis
  15468. },
  15469. graph: {
  15470. Node: Node,
  15471. Edge: Edge,
  15472. Popup: Popup,
  15473. Groups: Groups,
  15474. Images: Images
  15475. },
  15476. Timeline: Timeline,
  15477. Graph: Graph
  15478. };
  15479. /**
  15480. * CommonJS module exports
  15481. */
  15482. if (typeof exports !== 'undefined') {
  15483. exports = vis;
  15484. }
  15485. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15486. module.exports = vis;
  15487. }
  15488. /**
  15489. * AMD module exports
  15490. */
  15491. if (typeof(define) === 'function') {
  15492. define(function () {
  15493. return vis;
  15494. });
  15495. }
  15496. /**
  15497. * Window exports
  15498. */
  15499. if (typeof window !== 'undefined') {
  15500. // attach the module to the window, load as a regular javascript file
  15501. window['vis'] = vis;
  15502. }
  15503. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15504. /**
  15505. * Expose `Emitter`.
  15506. */
  15507. module.exports = Emitter;
  15508. /**
  15509. * Initialize a new `Emitter`.
  15510. *
  15511. * @api public
  15512. */
  15513. function Emitter(obj) {
  15514. if (obj) return mixin(obj);
  15515. };
  15516. /**
  15517. * Mixin the emitter properties.
  15518. *
  15519. * @param {Object} obj
  15520. * @return {Object}
  15521. * @api private
  15522. */
  15523. function mixin(obj) {
  15524. for (var key in Emitter.prototype) {
  15525. obj[key] = Emitter.prototype[key];
  15526. }
  15527. return obj;
  15528. }
  15529. /**
  15530. * Listen on the given `event` with `fn`.
  15531. *
  15532. * @param {String} event
  15533. * @param {Function} fn
  15534. * @return {Emitter}
  15535. * @api public
  15536. */
  15537. Emitter.prototype.on =
  15538. Emitter.prototype.addEventListener = function(event, fn){
  15539. this._callbacks = this._callbacks || {};
  15540. (this._callbacks[event] = this._callbacks[event] || [])
  15541. .push(fn);
  15542. return this;
  15543. };
  15544. /**
  15545. * Adds an `event` listener that will be invoked a single
  15546. * time then automatically removed.
  15547. *
  15548. * @param {String} event
  15549. * @param {Function} fn
  15550. * @return {Emitter}
  15551. * @api public
  15552. */
  15553. Emitter.prototype.once = function(event, fn){
  15554. var self = this;
  15555. this._callbacks = this._callbacks || {};
  15556. function on() {
  15557. self.off(event, on);
  15558. fn.apply(this, arguments);
  15559. }
  15560. on.fn = fn;
  15561. this.on(event, on);
  15562. return this;
  15563. };
  15564. /**
  15565. * Remove the given callback for `event` or all
  15566. * registered callbacks.
  15567. *
  15568. * @param {String} event
  15569. * @param {Function} fn
  15570. * @return {Emitter}
  15571. * @api public
  15572. */
  15573. Emitter.prototype.off =
  15574. Emitter.prototype.removeListener =
  15575. Emitter.prototype.removeAllListeners =
  15576. Emitter.prototype.removeEventListener = function(event, fn){
  15577. this._callbacks = this._callbacks || {};
  15578. // all
  15579. if (0 == arguments.length) {
  15580. this._callbacks = {};
  15581. return this;
  15582. }
  15583. // specific event
  15584. var callbacks = this._callbacks[event];
  15585. if (!callbacks) return this;
  15586. // remove all handlers
  15587. if (1 == arguments.length) {
  15588. delete this._callbacks[event];
  15589. return this;
  15590. }
  15591. // remove specific handler
  15592. var cb;
  15593. for (var i = 0; i < callbacks.length; i++) {
  15594. cb = callbacks[i];
  15595. if (cb === fn || cb.fn === fn) {
  15596. callbacks.splice(i, 1);
  15597. break;
  15598. }
  15599. }
  15600. return this;
  15601. };
  15602. /**
  15603. * Emit `event` with the given args.
  15604. *
  15605. * @param {String} event
  15606. * @param {Mixed} ...
  15607. * @return {Emitter}
  15608. */
  15609. Emitter.prototype.emit = function(event){
  15610. this._callbacks = this._callbacks || {};
  15611. var args = [].slice.call(arguments, 1)
  15612. , callbacks = this._callbacks[event];
  15613. if (callbacks) {
  15614. callbacks = callbacks.slice(0);
  15615. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15616. callbacks[i].apply(this, args);
  15617. }
  15618. }
  15619. return this;
  15620. };
  15621. /**
  15622. * Return array of callbacks for `event`.
  15623. *
  15624. * @param {String} event
  15625. * @return {Array}
  15626. * @api public
  15627. */
  15628. Emitter.prototype.listeners = function(event){
  15629. this._callbacks = this._callbacks || {};
  15630. return this._callbacks[event] || [];
  15631. };
  15632. /**
  15633. * Check if this emitter has `event` handlers.
  15634. *
  15635. * @param {String} event
  15636. * @return {Boolean}
  15637. * @api public
  15638. */
  15639. Emitter.prototype.hasListeners = function(event){
  15640. return !! this.listeners(event).length;
  15641. };
  15642. },{}],3:[function(require,module,exports){
  15643. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15644. * http://eightmedia.github.com/hammer.js
  15645. *
  15646. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  15647. * Licensed under the MIT license */
  15648. (function(window, undefined) {
  15649. 'use strict';
  15650. /**
  15651. * Hammer
  15652. * use this to create instances
  15653. * @param {HTMLElement} element
  15654. * @param {Object} options
  15655. * @returns {Hammer.Instance}
  15656. * @constructor
  15657. */
  15658. var Hammer = function(element, options) {
  15659. return new Hammer.Instance(element, options || {});
  15660. };
  15661. // default settings
  15662. Hammer.defaults = {
  15663. // add styles and attributes to the element to prevent the browser from doing
  15664. // its native behavior. this doesnt prevent the scrolling, but cancels
  15665. // the contextmenu, tap highlighting etc
  15666. // set to false to disable this
  15667. stop_browser_behavior: {
  15668. // this also triggers onselectstart=false for IE
  15669. userSelect: 'none',
  15670. // this makes the element blocking in IE10 >, you could experiment with the value
  15671. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  15672. touchAction: 'none',
  15673. touchCallout: 'none',
  15674. contentZooming: 'none',
  15675. userDrag: 'none',
  15676. tapHighlightColor: 'rgba(0,0,0,0)'
  15677. }
  15678. // more settings are defined per gesture at gestures.js
  15679. };
  15680. // detect touchevents
  15681. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  15682. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  15683. // dont use mouseevents on mobile devices
  15684. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  15685. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  15686. // eventtypes per touchevent (start, move, end)
  15687. // are filled by Hammer.event.determineEventTypes on setup
  15688. Hammer.EVENT_TYPES = {};
  15689. // direction defines
  15690. Hammer.DIRECTION_DOWN = 'down';
  15691. Hammer.DIRECTION_LEFT = 'left';
  15692. Hammer.DIRECTION_UP = 'up';
  15693. Hammer.DIRECTION_RIGHT = 'right';
  15694. // pointer type
  15695. Hammer.POINTER_MOUSE = 'mouse';
  15696. Hammer.POINTER_TOUCH = 'touch';
  15697. Hammer.POINTER_PEN = 'pen';
  15698. // touch event defines
  15699. Hammer.EVENT_START = 'start';
  15700. Hammer.EVENT_MOVE = 'move';
  15701. Hammer.EVENT_END = 'end';
  15702. // hammer document where the base events are added at
  15703. Hammer.DOCUMENT = document;
  15704. // plugins namespace
  15705. Hammer.plugins = {};
  15706. // if the window events are set...
  15707. Hammer.READY = false;
  15708. /**
  15709. * setup events to detect gestures on the document
  15710. */
  15711. function setup() {
  15712. if(Hammer.READY) {
  15713. return;
  15714. }
  15715. // find what eventtypes we add listeners to
  15716. Hammer.event.determineEventTypes();
  15717. // Register all gestures inside Hammer.gestures
  15718. for(var name in Hammer.gestures) {
  15719. if(Hammer.gestures.hasOwnProperty(name)) {
  15720. Hammer.detection.register(Hammer.gestures[name]);
  15721. }
  15722. }
  15723. // Add touch events on the document
  15724. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  15725. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  15726. // Hammer is ready...!
  15727. Hammer.READY = true;
  15728. }
  15729. /**
  15730. * create new hammer instance
  15731. * all methods should return the instance itself, so it is chainable.
  15732. * @param {HTMLElement} element
  15733. * @param {Object} [options={}]
  15734. * @returns {Hammer.Instance}
  15735. * @constructor
  15736. */
  15737. Hammer.Instance = function(element, options) {
  15738. var self = this;
  15739. // setup HammerJS window events and register all gestures
  15740. // this also sets up the default options
  15741. setup();
  15742. this.element = element;
  15743. // start/stop detection option
  15744. this.enabled = true;
  15745. // merge options
  15746. this.options = Hammer.utils.extend(
  15747. Hammer.utils.extend({}, Hammer.defaults),
  15748. options || {});
  15749. // add some css to the element to prevent the browser from doing its native behavoir
  15750. if(this.options.stop_browser_behavior) {
  15751. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  15752. }
  15753. // start detection on touchstart
  15754. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  15755. if(self.enabled) {
  15756. Hammer.detection.startDetect(self, ev);
  15757. }
  15758. });
  15759. // return instance
  15760. return this;
  15761. };
  15762. Hammer.Instance.prototype = {
  15763. /**
  15764. * bind events to the instance
  15765. * @param {String} gesture
  15766. * @param {Function} handler
  15767. * @returns {Hammer.Instance}
  15768. */
  15769. on: function onEvent(gesture, handler){
  15770. var gestures = gesture.split(' ');
  15771. for(var t=0; t<gestures.length; t++) {
  15772. this.element.addEventListener(gestures[t], handler, false);
  15773. }
  15774. return this;
  15775. },
  15776. /**
  15777. * unbind events to the instance
  15778. * @param {String} gesture
  15779. * @param {Function} handler
  15780. * @returns {Hammer.Instance}
  15781. */
  15782. off: function offEvent(gesture, handler){
  15783. var gestures = gesture.split(' ');
  15784. for(var t=0; t<gestures.length; t++) {
  15785. this.element.removeEventListener(gestures[t], handler, false);
  15786. }
  15787. return this;
  15788. },
  15789. /**
  15790. * trigger gesture event
  15791. * @param {String} gesture
  15792. * @param {Object} eventData
  15793. * @returns {Hammer.Instance}
  15794. */
  15795. trigger: function triggerEvent(gesture, eventData){
  15796. // create DOM event
  15797. var event = Hammer.DOCUMENT.createEvent('Event');
  15798. event.initEvent(gesture, true, true);
  15799. event.gesture = eventData;
  15800. // trigger on the target if it is in the instance element,
  15801. // this is for event delegation tricks
  15802. var element = this.element;
  15803. if(Hammer.utils.hasParent(eventData.target, element)) {
  15804. element = eventData.target;
  15805. }
  15806. element.dispatchEvent(event);
  15807. return this;
  15808. },
  15809. /**
  15810. * enable of disable hammer.js detection
  15811. * @param {Boolean} state
  15812. * @returns {Hammer.Instance}
  15813. */
  15814. enable: function enable(state) {
  15815. this.enabled = state;
  15816. return this;
  15817. }
  15818. };
  15819. /**
  15820. * this holds the last move event,
  15821. * used to fix empty touchend issue
  15822. * see the onTouch event for an explanation
  15823. * @type {Object}
  15824. */
  15825. var last_move_event = null;
  15826. /**
  15827. * when the mouse is hold down, this is true
  15828. * @type {Boolean}
  15829. */
  15830. var enable_detect = false;
  15831. /**
  15832. * when touch events have been fired, this is true
  15833. * @type {Boolean}
  15834. */
  15835. var touch_triggered = false;
  15836. Hammer.event = {
  15837. /**
  15838. * simple addEventListener
  15839. * @param {HTMLElement} element
  15840. * @param {String} type
  15841. * @param {Function} handler
  15842. */
  15843. bindDom: function(element, type, handler) {
  15844. var types = type.split(' ');
  15845. for(var t=0; t<types.length; t++) {
  15846. element.addEventListener(types[t], handler, false);
  15847. }
  15848. },
  15849. /**
  15850. * touch events with mouse fallback
  15851. * @param {HTMLElement} element
  15852. * @param {String} eventType like Hammer.EVENT_MOVE
  15853. * @param {Function} handler
  15854. */
  15855. onTouch: function onTouch(element, eventType, handler) {
  15856. var self = this;
  15857. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  15858. var sourceEventType = ev.type.toLowerCase();
  15859. // onmouseup, but when touchend has been fired we do nothing.
  15860. // this is for touchdevices which also fire a mouseup on touchend
  15861. if(sourceEventType.match(/mouse/) && touch_triggered) {
  15862. return;
  15863. }
  15864. // mousebutton must be down or a touch event
  15865. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  15866. sourceEventType.match(/pointerdown/) || // pointerevents touch
  15867. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  15868. ){
  15869. enable_detect = true;
  15870. }
  15871. // we are in a touch event, set the touch triggered bool to true,
  15872. // this for the conflicts that may occur on ios and android
  15873. if(sourceEventType.match(/touch|pointer/)) {
  15874. touch_triggered = true;
  15875. }
  15876. // count the total touches on the screen
  15877. var count_touches = 0;
  15878. // when touch has been triggered in this detection session
  15879. // and we are now handling a mouse event, we stop that to prevent conflicts
  15880. if(enable_detect) {
  15881. // update pointerevent
  15882. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  15883. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15884. }
  15885. // touch
  15886. else if(sourceEventType.match(/touch/)) {
  15887. count_touches = ev.touches.length;
  15888. }
  15889. // mouse
  15890. else if(!touch_triggered) {
  15891. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  15892. }
  15893. // if we are in a end event, but when we remove one touch and
  15894. // we still have enough, set eventType to move
  15895. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  15896. eventType = Hammer.EVENT_MOVE;
  15897. }
  15898. // no touches, force the end event
  15899. else if(!count_touches) {
  15900. eventType = Hammer.EVENT_END;
  15901. }
  15902. // because touchend has no touches, and we often want to use these in our gestures,
  15903. // we send the last move event as our eventData in touchend
  15904. if(!count_touches && last_move_event !== null) {
  15905. ev = last_move_event;
  15906. }
  15907. // store the last move event
  15908. else {
  15909. last_move_event = ev;
  15910. }
  15911. // trigger the handler
  15912. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  15913. // remove pointerevent from list
  15914. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  15915. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15916. }
  15917. }
  15918. //debug(sourceEventType +" "+ eventType);
  15919. // on the end we reset everything
  15920. if(!count_touches) {
  15921. last_move_event = null;
  15922. enable_detect = false;
  15923. touch_triggered = false;
  15924. Hammer.PointerEvent.reset();
  15925. }
  15926. });
  15927. },
  15928. /**
  15929. * we have different events for each device/browser
  15930. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  15931. */
  15932. determineEventTypes: function determineEventTypes() {
  15933. // determine the eventtype we want to set
  15934. var types;
  15935. // pointerEvents magic
  15936. if(Hammer.HAS_POINTEREVENTS) {
  15937. types = Hammer.PointerEvent.getEvents();
  15938. }
  15939. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  15940. else if(Hammer.NO_MOUSEEVENTS) {
  15941. types = [
  15942. 'touchstart',
  15943. 'touchmove',
  15944. 'touchend touchcancel'];
  15945. }
  15946. // for non pointer events browsers and mixed browsers,
  15947. // like chrome on windows8 touch laptop
  15948. else {
  15949. types = [
  15950. 'touchstart mousedown',
  15951. 'touchmove mousemove',
  15952. 'touchend touchcancel mouseup'];
  15953. }
  15954. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  15955. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  15956. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  15957. },
  15958. /**
  15959. * create touchlist depending on the event
  15960. * @param {Object} ev
  15961. * @param {String} eventType used by the fakemultitouch plugin
  15962. */
  15963. getTouchList: function getTouchList(ev/*, eventType*/) {
  15964. // get the fake pointerEvent touchlist
  15965. if(Hammer.HAS_POINTEREVENTS) {
  15966. return Hammer.PointerEvent.getTouchList();
  15967. }
  15968. // get the touchlist
  15969. else if(ev.touches) {
  15970. return ev.touches;
  15971. }
  15972. // make fake touchlist from mouse position
  15973. else {
  15974. return [{
  15975. identifier: 1,
  15976. pageX: ev.pageX,
  15977. pageY: ev.pageY,
  15978. target: ev.target
  15979. }];
  15980. }
  15981. },
  15982. /**
  15983. * collect event data for Hammer js
  15984. * @param {HTMLElement} element
  15985. * @param {String} eventType like Hammer.EVENT_MOVE
  15986. * @param {Object} eventData
  15987. */
  15988. collectEventData: function collectEventData(element, eventType, ev) {
  15989. var touches = this.getTouchList(ev, eventType);
  15990. // find out pointerType
  15991. var pointerType = Hammer.POINTER_TOUCH;
  15992. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  15993. pointerType = Hammer.POINTER_MOUSE;
  15994. }
  15995. return {
  15996. center : Hammer.utils.getCenter(touches),
  15997. timeStamp : new Date().getTime(),
  15998. target : ev.target,
  15999. touches : touches,
  16000. eventType : eventType,
  16001. pointerType : pointerType,
  16002. srcEvent : ev,
  16003. /**
  16004. * prevent the browser default actions
  16005. * mostly used to disable scrolling of the browser
  16006. */
  16007. preventDefault: function() {
  16008. if(this.srcEvent.preventManipulation) {
  16009. this.srcEvent.preventManipulation();
  16010. }
  16011. if(this.srcEvent.preventDefault) {
  16012. this.srcEvent.preventDefault();
  16013. }
  16014. },
  16015. /**
  16016. * stop bubbling the event up to its parents
  16017. */
  16018. stopPropagation: function() {
  16019. this.srcEvent.stopPropagation();
  16020. },
  16021. /**
  16022. * immediately stop gesture detection
  16023. * might be useful after a swipe was detected
  16024. * @return {*}
  16025. */
  16026. stopDetect: function() {
  16027. return Hammer.detection.stopDetect();
  16028. }
  16029. };
  16030. }
  16031. };
  16032. Hammer.PointerEvent = {
  16033. /**
  16034. * holds all pointers
  16035. * @type {Object}
  16036. */
  16037. pointers: {},
  16038. /**
  16039. * get a list of pointers
  16040. * @returns {Array} touchlist
  16041. */
  16042. getTouchList: function() {
  16043. var self = this;
  16044. var touchlist = [];
  16045. // we can use forEach since pointerEvents only is in IE10
  16046. Object.keys(self.pointers).sort().forEach(function(id) {
  16047. touchlist.push(self.pointers[id]);
  16048. });
  16049. return touchlist;
  16050. },
  16051. /**
  16052. * update the position of a pointer
  16053. * @param {String} type Hammer.EVENT_END
  16054. * @param {Object} pointerEvent
  16055. */
  16056. updatePointer: function(type, pointerEvent) {
  16057. if(type == Hammer.EVENT_END) {
  16058. this.pointers = {};
  16059. }
  16060. else {
  16061. pointerEvent.identifier = pointerEvent.pointerId;
  16062. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16063. }
  16064. return Object.keys(this.pointers).length;
  16065. },
  16066. /**
  16067. * check if ev matches pointertype
  16068. * @param {String} pointerType Hammer.POINTER_MOUSE
  16069. * @param {PointerEvent} ev
  16070. */
  16071. matchType: function(pointerType, ev) {
  16072. if(!ev.pointerType) {
  16073. return false;
  16074. }
  16075. var types = {};
  16076. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16077. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16078. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16079. return types[pointerType];
  16080. },
  16081. /**
  16082. * get events
  16083. */
  16084. getEvents: function() {
  16085. return [
  16086. 'pointerdown MSPointerDown',
  16087. 'pointermove MSPointerMove',
  16088. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16089. ];
  16090. },
  16091. /**
  16092. * reset the list
  16093. */
  16094. reset: function() {
  16095. this.pointers = {};
  16096. }
  16097. };
  16098. Hammer.utils = {
  16099. /**
  16100. * extend method,
  16101. * also used for cloning when dest is an empty object
  16102. * @param {Object} dest
  16103. * @param {Object} src
  16104. * @parm {Boolean} merge do a merge
  16105. * @returns {Object} dest
  16106. */
  16107. extend: function extend(dest, src, merge) {
  16108. for (var key in src) {
  16109. if(dest[key] !== undefined && merge) {
  16110. continue;
  16111. }
  16112. dest[key] = src[key];
  16113. }
  16114. return dest;
  16115. },
  16116. /**
  16117. * find if a node is in the given parent
  16118. * used for event delegation tricks
  16119. * @param {HTMLElement} node
  16120. * @param {HTMLElement} parent
  16121. * @returns {boolean} has_parent
  16122. */
  16123. hasParent: function(node, parent) {
  16124. while(node){
  16125. if(node == parent) {
  16126. return true;
  16127. }
  16128. node = node.parentNode;
  16129. }
  16130. return false;
  16131. },
  16132. /**
  16133. * get the center of all the touches
  16134. * @param {Array} touches
  16135. * @returns {Object} center
  16136. */
  16137. getCenter: function getCenter(touches) {
  16138. var valuesX = [], valuesY = [];
  16139. for(var t= 0,len=touches.length; t<len; t++) {
  16140. valuesX.push(touches[t].pageX);
  16141. valuesY.push(touches[t].pageY);
  16142. }
  16143. return {
  16144. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  16145. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  16146. };
  16147. },
  16148. /**
  16149. * calculate the velocity between two points
  16150. * @param {Number} delta_time
  16151. * @param {Number} delta_x
  16152. * @param {Number} delta_y
  16153. * @returns {Object} velocity
  16154. */
  16155. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  16156. return {
  16157. x: Math.abs(delta_x / delta_time) || 0,
  16158. y: Math.abs(delta_y / delta_time) || 0
  16159. };
  16160. },
  16161. /**
  16162. * calculate the angle between two coordinates
  16163. * @param {Touch} touch1
  16164. * @param {Touch} touch2
  16165. * @returns {Number} angle
  16166. */
  16167. getAngle: function getAngle(touch1, touch2) {
  16168. var y = touch2.pageY - touch1.pageY,
  16169. x = touch2.pageX - touch1.pageX;
  16170. return Math.atan2(y, x) * 180 / Math.PI;
  16171. },
  16172. /**
  16173. * angle to direction define
  16174. * @param {Touch} touch1
  16175. * @param {Touch} touch2
  16176. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  16177. */
  16178. getDirection: function getDirection(touch1, touch2) {
  16179. var x = Math.abs(touch1.pageX - touch2.pageX),
  16180. y = Math.abs(touch1.pageY - touch2.pageY);
  16181. if(x >= y) {
  16182. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16183. }
  16184. else {
  16185. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16186. }
  16187. },
  16188. /**
  16189. * calculate the distance between two touches
  16190. * @param {Touch} touch1
  16191. * @param {Touch} touch2
  16192. * @returns {Number} distance
  16193. */
  16194. getDistance: function getDistance(touch1, touch2) {
  16195. var x = touch2.pageX - touch1.pageX,
  16196. y = touch2.pageY - touch1.pageY;
  16197. return Math.sqrt((x*x) + (y*y));
  16198. },
  16199. /**
  16200. * calculate the scale factor between two touchLists (fingers)
  16201. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16202. * @param {Array} start
  16203. * @param {Array} end
  16204. * @returns {Number} scale
  16205. */
  16206. getScale: function getScale(start, end) {
  16207. // need two fingers...
  16208. if(start.length >= 2 && end.length >= 2) {
  16209. return this.getDistance(end[0], end[1]) /
  16210. this.getDistance(start[0], start[1]);
  16211. }
  16212. return 1;
  16213. },
  16214. /**
  16215. * calculate the rotation degrees between two touchLists (fingers)
  16216. * @param {Array} start
  16217. * @param {Array} end
  16218. * @returns {Number} rotation
  16219. */
  16220. getRotation: function getRotation(start, end) {
  16221. // need two fingers
  16222. if(start.length >= 2 && end.length >= 2) {
  16223. return this.getAngle(end[1], end[0]) -
  16224. this.getAngle(start[1], start[0]);
  16225. }
  16226. return 0;
  16227. },
  16228. /**
  16229. * boolean if the direction is vertical
  16230. * @param {String} direction
  16231. * @returns {Boolean} is_vertical
  16232. */
  16233. isVertical: function isVertical(direction) {
  16234. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16235. },
  16236. /**
  16237. * stop browser default behavior with css props
  16238. * @param {HtmlElement} element
  16239. * @param {Object} css_props
  16240. */
  16241. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16242. var prop,
  16243. vendors = ['webkit','khtml','moz','ms','o',''];
  16244. if(!css_props || !element.style) {
  16245. return;
  16246. }
  16247. // with css properties for modern browsers
  16248. for(var i = 0; i < vendors.length; i++) {
  16249. for(var p in css_props) {
  16250. if(css_props.hasOwnProperty(p)) {
  16251. prop = p;
  16252. // vender prefix at the property
  16253. if(vendors[i]) {
  16254. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16255. }
  16256. // set the style
  16257. element.style[prop] = css_props[p];
  16258. }
  16259. }
  16260. }
  16261. // also the disable onselectstart
  16262. if(css_props.userSelect == 'none') {
  16263. element.onselectstart = function() {
  16264. return false;
  16265. };
  16266. }
  16267. }
  16268. };
  16269. Hammer.detection = {
  16270. // contains all registred Hammer.gestures in the correct order
  16271. gestures: [],
  16272. // data of the current Hammer.gesture detection session
  16273. current: null,
  16274. // the previous Hammer.gesture session data
  16275. // is a full clone of the previous gesture.current object
  16276. previous: null,
  16277. // when this becomes true, no gestures are fired
  16278. stopped: false,
  16279. /**
  16280. * start Hammer.gesture detection
  16281. * @param {Hammer.Instance} inst
  16282. * @param {Object} eventData
  16283. */
  16284. startDetect: function startDetect(inst, eventData) {
  16285. // already busy with a Hammer.gesture detection on an element
  16286. if(this.current) {
  16287. return;
  16288. }
  16289. this.stopped = false;
  16290. this.current = {
  16291. inst : inst, // reference to HammerInstance we're working for
  16292. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16293. lastEvent : false, // last eventData
  16294. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16295. };
  16296. this.detect(eventData);
  16297. },
  16298. /**
  16299. * Hammer.gesture detection
  16300. * @param {Object} eventData
  16301. * @param {Object} eventData
  16302. */
  16303. detect: function detect(eventData) {
  16304. if(!this.current || this.stopped) {
  16305. return;
  16306. }
  16307. // extend event data with calculations about scale, distance etc
  16308. eventData = this.extendEventData(eventData);
  16309. // instance options
  16310. var inst_options = this.current.inst.options;
  16311. // call Hammer.gesture handlers
  16312. for(var g=0,len=this.gestures.length; g<len; g++) {
  16313. var gesture = this.gestures[g];
  16314. // only when the instance options have enabled this gesture
  16315. if(!this.stopped && inst_options[gesture.name] !== false) {
  16316. // if a handler returns false, we stop with the detection
  16317. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16318. this.stopDetect();
  16319. break;
  16320. }
  16321. }
  16322. }
  16323. // store as previous event event
  16324. if(this.current) {
  16325. this.current.lastEvent = eventData;
  16326. }
  16327. // endevent, but not the last touch, so dont stop
  16328. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16329. this.stopDetect();
  16330. }
  16331. return eventData;
  16332. },
  16333. /**
  16334. * clear the Hammer.gesture vars
  16335. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16336. * to stop other Hammer.gestures from being fired
  16337. */
  16338. stopDetect: function stopDetect() {
  16339. // clone current data to the store as the previous gesture
  16340. // used for the double tap gesture, since this is an other gesture detect session
  16341. this.previous = Hammer.utils.extend({}, this.current);
  16342. // reset the current
  16343. this.current = null;
  16344. // stopped!
  16345. this.stopped = true;
  16346. },
  16347. /**
  16348. * extend eventData for Hammer.gestures
  16349. * @param {Object} ev
  16350. * @returns {Object} ev
  16351. */
  16352. extendEventData: function extendEventData(ev) {
  16353. var startEv = this.current.startEvent;
  16354. // if the touches change, set the new touches over the startEvent touches
  16355. // this because touchevents don't have all the touches on touchstart, or the
  16356. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16357. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16358. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16359. // extend 1 level deep to get the touchlist with the touch objects
  16360. startEv.touches = [];
  16361. for(var i=0,len=ev.touches.length; i<len; i++) {
  16362. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16363. }
  16364. }
  16365. var delta_time = ev.timeStamp - startEv.timeStamp,
  16366. delta_x = ev.center.pageX - startEv.center.pageX,
  16367. delta_y = ev.center.pageY - startEv.center.pageY,
  16368. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16369. Hammer.utils.extend(ev, {
  16370. deltaTime : delta_time,
  16371. deltaX : delta_x,
  16372. deltaY : delta_y,
  16373. velocityX : velocity.x,
  16374. velocityY : velocity.y,
  16375. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16376. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16377. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16378. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16379. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16380. startEvent : startEv
  16381. });
  16382. return ev;
  16383. },
  16384. /**
  16385. * register new gesture
  16386. * @param {Object} gesture object, see gestures.js for documentation
  16387. * @returns {Array} gestures
  16388. */
  16389. register: function register(gesture) {
  16390. // add an enable gesture options if there is no given
  16391. var options = gesture.defaults || {};
  16392. if(options[gesture.name] === undefined) {
  16393. options[gesture.name] = true;
  16394. }
  16395. // extend Hammer default options with the Hammer.gesture options
  16396. Hammer.utils.extend(Hammer.defaults, options, true);
  16397. // set its index
  16398. gesture.index = gesture.index || 1000;
  16399. // add Hammer.gesture to the list
  16400. this.gestures.push(gesture);
  16401. // sort the list by index
  16402. this.gestures.sort(function(a, b) {
  16403. if (a.index < b.index) {
  16404. return -1;
  16405. }
  16406. if (a.index > b.index) {
  16407. return 1;
  16408. }
  16409. return 0;
  16410. });
  16411. return this.gestures;
  16412. }
  16413. };
  16414. Hammer.gestures = Hammer.gestures || {};
  16415. /**
  16416. * Custom gestures
  16417. * ==============================
  16418. *
  16419. * Gesture object
  16420. * --------------------
  16421. * The object structure of a gesture:
  16422. *
  16423. * { name: 'mygesture',
  16424. * index: 1337,
  16425. * defaults: {
  16426. * mygesture_option: true
  16427. * }
  16428. * handler: function(type, ev, inst) {
  16429. * // trigger gesture event
  16430. * inst.trigger(this.name, ev);
  16431. * }
  16432. * }
  16433. * @param {String} name
  16434. * this should be the name of the gesture, lowercase
  16435. * it is also being used to disable/enable the gesture per instance config.
  16436. *
  16437. * @param {Number} [index=1000]
  16438. * the index of the gesture, where it is going to be in the stack of gestures detection
  16439. * like when you build an gesture that depends on the drag gesture, it is a good
  16440. * idea to place it after the index of the drag gesture.
  16441. *
  16442. * @param {Object} [defaults={}]
  16443. * the default settings of the gesture. these are added to the instance settings,
  16444. * and can be overruled per instance. you can also add the name of the gesture,
  16445. * but this is also added by default (and set to true).
  16446. *
  16447. * @param {Function} handler
  16448. * this handles the gesture detection of your custom gesture and receives the
  16449. * following arguments:
  16450. *
  16451. * @param {Object} eventData
  16452. * event data containing the following properties:
  16453. * timeStamp {Number} time the event occurred
  16454. * target {HTMLElement} target element
  16455. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16456. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16457. * center {Object} center position of the touches. contains pageX and pageY
  16458. * deltaTime {Number} the total time of the touches in the screen
  16459. * deltaX {Number} the delta on x axis we haved moved
  16460. * deltaY {Number} the delta on y axis we haved moved
  16461. * velocityX {Number} the velocity on the x
  16462. * velocityY {Number} the velocity on y
  16463. * angle {Number} the angle we are moving
  16464. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16465. * distance {Number} the distance we haved moved
  16466. * scale {Number} scaling of the touches, needs 2 touches
  16467. * rotation {Number} rotation of the touches, needs 2 touches *
  16468. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16469. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16470. * startEvent {Object} contains the same properties as above,
  16471. * but from the first touch. this is used to calculate
  16472. * distances, deltaTime, scaling etc
  16473. *
  16474. * @param {Hammer.Instance} inst
  16475. * the instance we are doing the detection for. you can get the options from
  16476. * the inst.options object and trigger the gesture event by calling inst.trigger
  16477. *
  16478. *
  16479. * Handle gestures
  16480. * --------------------
  16481. * inside the handler you can get/set Hammer.detection.current. This is the current
  16482. * detection session. It has the following properties
  16483. * @param {String} name
  16484. * contains the name of the gesture we have detected. it has not a real function,
  16485. * only to check in other gestures if something is detected.
  16486. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16487. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16488. *
  16489. * @readonly
  16490. * @param {Hammer.Instance} inst
  16491. * the instance we do the detection for
  16492. *
  16493. * @readonly
  16494. * @param {Object} startEvent
  16495. * contains the properties of the first gesture detection in this session.
  16496. * Used for calculations about timing, distance, etc.
  16497. *
  16498. * @readonly
  16499. * @param {Object} lastEvent
  16500. * contains all the properties of the last gesture detect in this session.
  16501. *
  16502. * after the gesture detection session has been completed (user has released the screen)
  16503. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16504. * this is usefull for gestures like doubletap, where you need to know if the
  16505. * previous gesture was a tap
  16506. *
  16507. * options that have been set by the instance can be received by calling inst.options
  16508. *
  16509. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16510. * The first param is the name of your gesture, the second the event argument
  16511. *
  16512. *
  16513. * Register gestures
  16514. * --------------------
  16515. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16516. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16517. * manually and pass your gesture object as a param
  16518. *
  16519. */
  16520. /**
  16521. * Hold
  16522. * Touch stays at the same place for x time
  16523. * @events hold
  16524. */
  16525. Hammer.gestures.Hold = {
  16526. name: 'hold',
  16527. index: 10,
  16528. defaults: {
  16529. hold_timeout : 500,
  16530. hold_threshold : 1
  16531. },
  16532. timer: null,
  16533. handler: function holdGesture(ev, inst) {
  16534. switch(ev.eventType) {
  16535. case Hammer.EVENT_START:
  16536. // clear any running timers
  16537. clearTimeout(this.timer);
  16538. // set the gesture so we can check in the timeout if it still is
  16539. Hammer.detection.current.name = this.name;
  16540. // set timer and if after the timeout it still is hold,
  16541. // we trigger the hold event
  16542. this.timer = setTimeout(function() {
  16543. if(Hammer.detection.current.name == 'hold') {
  16544. inst.trigger('hold', ev);
  16545. }
  16546. }, inst.options.hold_timeout);
  16547. break;
  16548. // when you move or end we clear the timer
  16549. case Hammer.EVENT_MOVE:
  16550. if(ev.distance > inst.options.hold_threshold) {
  16551. clearTimeout(this.timer);
  16552. }
  16553. break;
  16554. case Hammer.EVENT_END:
  16555. clearTimeout(this.timer);
  16556. break;
  16557. }
  16558. }
  16559. };
  16560. /**
  16561. * Tap/DoubleTap
  16562. * Quick touch at a place or double at the same place
  16563. * @events tap, doubletap
  16564. */
  16565. Hammer.gestures.Tap = {
  16566. name: 'tap',
  16567. index: 100,
  16568. defaults: {
  16569. tap_max_touchtime : 250,
  16570. tap_max_distance : 10,
  16571. tap_always : true,
  16572. doubletap_distance : 20,
  16573. doubletap_interval : 300
  16574. },
  16575. handler: function tapGesture(ev, inst) {
  16576. if(ev.eventType == Hammer.EVENT_END) {
  16577. // previous gesture, for the double tap since these are two different gesture detections
  16578. var prev = Hammer.detection.previous,
  16579. did_doubletap = false;
  16580. // when the touchtime is higher then the max touch time
  16581. // or when the moving distance is too much
  16582. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16583. ev.distance > inst.options.tap_max_distance) {
  16584. return;
  16585. }
  16586. // check if double tap
  16587. if(prev && prev.name == 'tap' &&
  16588. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16589. ev.distance < inst.options.doubletap_distance) {
  16590. inst.trigger('doubletap', ev);
  16591. did_doubletap = true;
  16592. }
  16593. // do a single tap
  16594. if(!did_doubletap || inst.options.tap_always) {
  16595. Hammer.detection.current.name = 'tap';
  16596. inst.trigger(Hammer.detection.current.name, ev);
  16597. }
  16598. }
  16599. }
  16600. };
  16601. /**
  16602. * Swipe
  16603. * triggers swipe events when the end velocity is above the threshold
  16604. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16605. */
  16606. Hammer.gestures.Swipe = {
  16607. name: 'swipe',
  16608. index: 40,
  16609. defaults: {
  16610. // set 0 for unlimited, but this can conflict with transform
  16611. swipe_max_touches : 1,
  16612. swipe_velocity : 0.7
  16613. },
  16614. handler: function swipeGesture(ev, inst) {
  16615. if(ev.eventType == Hammer.EVENT_END) {
  16616. // max touches
  16617. if(inst.options.swipe_max_touches > 0 &&
  16618. ev.touches.length > inst.options.swipe_max_touches) {
  16619. return;
  16620. }
  16621. // when the distance we moved is too small we skip this gesture
  16622. // or we can be already in dragging
  16623. if(ev.velocityX > inst.options.swipe_velocity ||
  16624. ev.velocityY > inst.options.swipe_velocity) {
  16625. // trigger swipe events
  16626. inst.trigger(this.name, ev);
  16627. inst.trigger(this.name + ev.direction, ev);
  16628. }
  16629. }
  16630. }
  16631. };
  16632. /**
  16633. * Drag
  16634. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16635. * moving left and right is a good practice. When all the drag events are blocking
  16636. * you disable scrolling on that area.
  16637. * @events drag, drapleft, dragright, dragup, dragdown
  16638. */
  16639. Hammer.gestures.Drag = {
  16640. name: 'drag',
  16641. index: 50,
  16642. defaults: {
  16643. drag_min_distance : 10,
  16644. // set 0 for unlimited, but this can conflict with transform
  16645. drag_max_touches : 1,
  16646. // prevent default browser behavior when dragging occurs
  16647. // be careful with it, it makes the element a blocking element
  16648. // when you are using the drag gesture, it is a good practice to set this true
  16649. drag_block_horizontal : false,
  16650. drag_block_vertical : false,
  16651. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  16652. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  16653. drag_lock_to_axis : false,
  16654. // drag lock only kicks in when distance > drag_lock_min_distance
  16655. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  16656. drag_lock_min_distance : 25
  16657. },
  16658. triggered: false,
  16659. handler: function dragGesture(ev, inst) {
  16660. // current gesture isnt drag, but dragged is true
  16661. // this means an other gesture is busy. now call dragend
  16662. if(Hammer.detection.current.name != this.name && this.triggered) {
  16663. inst.trigger(this.name +'end', ev);
  16664. this.triggered = false;
  16665. return;
  16666. }
  16667. // max touches
  16668. if(inst.options.drag_max_touches > 0 &&
  16669. ev.touches.length > inst.options.drag_max_touches) {
  16670. return;
  16671. }
  16672. switch(ev.eventType) {
  16673. case Hammer.EVENT_START:
  16674. this.triggered = false;
  16675. break;
  16676. case Hammer.EVENT_MOVE:
  16677. // when the distance we moved is too small we skip this gesture
  16678. // or we can be already in dragging
  16679. if(ev.distance < inst.options.drag_min_distance &&
  16680. Hammer.detection.current.name != this.name) {
  16681. return;
  16682. }
  16683. // we are dragging!
  16684. Hammer.detection.current.name = this.name;
  16685. // lock drag to axis?
  16686. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  16687. ev.drag_locked_to_axis = true;
  16688. }
  16689. var last_direction = Hammer.detection.current.lastEvent.direction;
  16690. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  16691. // keep direction on the axis that the drag gesture started on
  16692. if(Hammer.utils.isVertical(last_direction)) {
  16693. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16694. }
  16695. else {
  16696. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16697. }
  16698. }
  16699. // first time, trigger dragstart event
  16700. if(!this.triggered) {
  16701. inst.trigger(this.name +'start', ev);
  16702. this.triggered = true;
  16703. }
  16704. // trigger normal event
  16705. inst.trigger(this.name, ev);
  16706. // direction event, like dragdown
  16707. inst.trigger(this.name + ev.direction, ev);
  16708. // block the browser events
  16709. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  16710. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  16711. ev.preventDefault();
  16712. }
  16713. break;
  16714. case Hammer.EVENT_END:
  16715. // trigger dragend
  16716. if(this.triggered) {
  16717. inst.trigger(this.name +'end', ev);
  16718. }
  16719. this.triggered = false;
  16720. break;
  16721. }
  16722. }
  16723. };
  16724. /**
  16725. * Transform
  16726. * User want to scale or rotate with 2 fingers
  16727. * @events transform, pinch, pinchin, pinchout, rotate
  16728. */
  16729. Hammer.gestures.Transform = {
  16730. name: 'transform',
  16731. index: 45,
  16732. defaults: {
  16733. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  16734. transform_min_scale : 0.01,
  16735. // rotation in degrees
  16736. transform_min_rotation : 1,
  16737. // prevent default browser behavior when two touches are on the screen
  16738. // but it makes the element a blocking element
  16739. // when you are using the transform gesture, it is a good practice to set this true
  16740. transform_always_block : false
  16741. },
  16742. triggered: false,
  16743. handler: function transformGesture(ev, inst) {
  16744. // current gesture isnt drag, but dragged is true
  16745. // this means an other gesture is busy. now call dragend
  16746. if(Hammer.detection.current.name != this.name && this.triggered) {
  16747. inst.trigger(this.name +'end', ev);
  16748. this.triggered = false;
  16749. return;
  16750. }
  16751. // atleast multitouch
  16752. if(ev.touches.length < 2) {
  16753. return;
  16754. }
  16755. // prevent default when two fingers are on the screen
  16756. if(inst.options.transform_always_block) {
  16757. ev.preventDefault();
  16758. }
  16759. switch(ev.eventType) {
  16760. case Hammer.EVENT_START:
  16761. this.triggered = false;
  16762. break;
  16763. case Hammer.EVENT_MOVE:
  16764. var scale_threshold = Math.abs(1-ev.scale);
  16765. var rotation_threshold = Math.abs(ev.rotation);
  16766. // when the distance we moved is too small we skip this gesture
  16767. // or we can be already in dragging
  16768. if(scale_threshold < inst.options.transform_min_scale &&
  16769. rotation_threshold < inst.options.transform_min_rotation) {
  16770. return;
  16771. }
  16772. // we are transforming!
  16773. Hammer.detection.current.name = this.name;
  16774. // first time, trigger dragstart event
  16775. if(!this.triggered) {
  16776. inst.trigger(this.name +'start', ev);
  16777. this.triggered = true;
  16778. }
  16779. inst.trigger(this.name, ev); // basic transform event
  16780. // trigger rotate event
  16781. if(rotation_threshold > inst.options.transform_min_rotation) {
  16782. inst.trigger('rotate', ev);
  16783. }
  16784. // trigger pinch event
  16785. if(scale_threshold > inst.options.transform_min_scale) {
  16786. inst.trigger('pinch', ev);
  16787. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  16788. }
  16789. break;
  16790. case Hammer.EVENT_END:
  16791. // trigger dragend
  16792. if(this.triggered) {
  16793. inst.trigger(this.name +'end', ev);
  16794. }
  16795. this.triggered = false;
  16796. break;
  16797. }
  16798. }
  16799. };
  16800. /**
  16801. * Touch
  16802. * Called as first, tells the user has touched the screen
  16803. * @events touch
  16804. */
  16805. Hammer.gestures.Touch = {
  16806. name: 'touch',
  16807. index: -Infinity,
  16808. defaults: {
  16809. // call preventDefault at touchstart, and makes the element blocking by
  16810. // disabling the scrolling of the page, but it improves gestures like
  16811. // transforming and dragging.
  16812. // be careful with using this, it can be very annoying for users to be stuck
  16813. // on the page
  16814. prevent_default: false,
  16815. // disable mouse events, so only touch (or pen!) input triggers events
  16816. prevent_mouseevents: false
  16817. },
  16818. handler: function touchGesture(ev, inst) {
  16819. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  16820. ev.stopDetect();
  16821. return;
  16822. }
  16823. if(inst.options.prevent_default) {
  16824. ev.preventDefault();
  16825. }
  16826. if(ev.eventType == Hammer.EVENT_START) {
  16827. inst.trigger(this.name, ev);
  16828. }
  16829. }
  16830. };
  16831. /**
  16832. * Release
  16833. * Called as last, tells the user has released the screen
  16834. * @events release
  16835. */
  16836. Hammer.gestures.Release = {
  16837. name: 'release',
  16838. index: Infinity,
  16839. handler: function releaseGesture(ev, inst) {
  16840. if(ev.eventType == Hammer.EVENT_END) {
  16841. inst.trigger(this.name, ev);
  16842. }
  16843. }
  16844. };
  16845. // node export
  16846. if(typeof module === 'object' && typeof module.exports === 'object'){
  16847. module.exports = Hammer;
  16848. }
  16849. // just window export
  16850. else {
  16851. window.Hammer = Hammer;
  16852. // requireJS module definition
  16853. if(typeof window.define === 'function' && window.define.amd) {
  16854. window.define('hammer', [], function() {
  16855. return Hammer;
  16856. });
  16857. }
  16858. }
  16859. })(this);
  16860. },{}],4:[function(require,module,exports){
  16861. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};//! moment.js
  16862. //! version : 2.6.0
  16863. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  16864. //! license : MIT
  16865. //! momentjs.com
  16866. (function (undefined) {
  16867. /************************************
  16868. Constants
  16869. ************************************/
  16870. var moment,
  16871. VERSION = "2.6.0",
  16872. // the global-scope this is NOT the global object in Node.js
  16873. globalScope = typeof global !== 'undefined' ? global : this,
  16874. oldGlobalMoment,
  16875. round = Math.round,
  16876. i,
  16877. YEAR = 0,
  16878. MONTH = 1,
  16879. DATE = 2,
  16880. HOUR = 3,
  16881. MINUTE = 4,
  16882. SECOND = 5,
  16883. MILLISECOND = 6,
  16884. // internal storage for language config files
  16885. languages = {},
  16886. // moment internal properties
  16887. momentProperties = {
  16888. _isAMomentObject: null,
  16889. _i : null,
  16890. _f : null,
  16891. _l : null,
  16892. _strict : null,
  16893. _isUTC : null,
  16894. _offset : null, // optional. Combine with _isUTC
  16895. _pf : null,
  16896. _lang : null // optional
  16897. },
  16898. // check for nodeJS
  16899. hasModule = (typeof module !== 'undefined' && module.exports),
  16900. // ASP.NET json date format regex
  16901. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  16902. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  16903. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  16904. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  16905. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  16906. // format tokens
  16907. formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,
  16908. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  16909. // parsing token regexes
  16910. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  16911. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  16912. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  16913. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  16914. parseTokenDigits = /\d+/, // nonzero number of digits
  16915. 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.
  16916. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  16917. parseTokenT = /T/i, // T (ISO separator)
  16918. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  16919. parseTokenOrdinal = /\d{1,2}/,
  16920. //strict parsing regexes
  16921. parseTokenOneDigit = /\d/, // 0 - 9
  16922. parseTokenTwoDigits = /\d\d/, // 00 - 99
  16923. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  16924. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  16925. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  16926. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  16927. // iso 8601 regex
  16928. // 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)
  16929. 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)?)?$/,
  16930. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  16931. isoDates = [
  16932. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  16933. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  16934. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  16935. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  16936. ['YYYY-DDD', /\d{4}-\d{3}/]
  16937. ],
  16938. // iso time formats and regexes
  16939. isoTimes = [
  16940. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
  16941. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  16942. ['HH:mm', /(T| )\d\d:\d\d/],
  16943. ['HH', /(T| )\d\d/]
  16944. ],
  16945. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  16946. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  16947. // getter and setter names
  16948. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  16949. unitMillisecondFactors = {
  16950. 'Milliseconds' : 1,
  16951. 'Seconds' : 1e3,
  16952. 'Minutes' : 6e4,
  16953. 'Hours' : 36e5,
  16954. 'Days' : 864e5,
  16955. 'Months' : 2592e6,
  16956. 'Years' : 31536e6
  16957. },
  16958. unitAliases = {
  16959. ms : 'millisecond',
  16960. s : 'second',
  16961. m : 'minute',
  16962. h : 'hour',
  16963. d : 'day',
  16964. D : 'date',
  16965. w : 'week',
  16966. W : 'isoWeek',
  16967. M : 'month',
  16968. Q : 'quarter',
  16969. y : 'year',
  16970. DDD : 'dayOfYear',
  16971. e : 'weekday',
  16972. E : 'isoWeekday',
  16973. gg: 'weekYear',
  16974. GG: 'isoWeekYear'
  16975. },
  16976. camelFunctions = {
  16977. dayofyear : 'dayOfYear',
  16978. isoweekday : 'isoWeekday',
  16979. isoweek : 'isoWeek',
  16980. weekyear : 'weekYear',
  16981. isoweekyear : 'isoWeekYear'
  16982. },
  16983. // format function strings
  16984. formatFunctions = {},
  16985. // tokens to ordinalize and pad
  16986. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  16987. paddedTokens = 'M D H h m s w W'.split(' '),
  16988. formatTokenFunctions = {
  16989. M : function () {
  16990. return this.month() + 1;
  16991. },
  16992. MMM : function (format) {
  16993. return this.lang().monthsShort(this, format);
  16994. },
  16995. MMMM : function (format) {
  16996. return this.lang().months(this, format);
  16997. },
  16998. D : function () {
  16999. return this.date();
  17000. },
  17001. DDD : function () {
  17002. return this.dayOfYear();
  17003. },
  17004. d : function () {
  17005. return this.day();
  17006. },
  17007. dd : function (format) {
  17008. return this.lang().weekdaysMin(this, format);
  17009. },
  17010. ddd : function (format) {
  17011. return this.lang().weekdaysShort(this, format);
  17012. },
  17013. dddd : function (format) {
  17014. return this.lang().weekdays(this, format);
  17015. },
  17016. w : function () {
  17017. return this.week();
  17018. },
  17019. W : function () {
  17020. return this.isoWeek();
  17021. },
  17022. YY : function () {
  17023. return leftZeroFill(this.year() % 100, 2);
  17024. },
  17025. YYYY : function () {
  17026. return leftZeroFill(this.year(), 4);
  17027. },
  17028. YYYYY : function () {
  17029. return leftZeroFill(this.year(), 5);
  17030. },
  17031. YYYYYY : function () {
  17032. var y = this.year(), sign = y >= 0 ? '+' : '-';
  17033. return sign + leftZeroFill(Math.abs(y), 6);
  17034. },
  17035. gg : function () {
  17036. return leftZeroFill(this.weekYear() % 100, 2);
  17037. },
  17038. gggg : function () {
  17039. return leftZeroFill(this.weekYear(), 4);
  17040. },
  17041. ggggg : function () {
  17042. return leftZeroFill(this.weekYear(), 5);
  17043. },
  17044. GG : function () {
  17045. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17046. },
  17047. GGGG : function () {
  17048. return leftZeroFill(this.isoWeekYear(), 4);
  17049. },
  17050. GGGGG : function () {
  17051. return leftZeroFill(this.isoWeekYear(), 5);
  17052. },
  17053. e : function () {
  17054. return this.weekday();
  17055. },
  17056. E : function () {
  17057. return this.isoWeekday();
  17058. },
  17059. a : function () {
  17060. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17061. },
  17062. A : function () {
  17063. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17064. },
  17065. H : function () {
  17066. return this.hours();
  17067. },
  17068. h : function () {
  17069. return this.hours() % 12 || 12;
  17070. },
  17071. m : function () {
  17072. return this.minutes();
  17073. },
  17074. s : function () {
  17075. return this.seconds();
  17076. },
  17077. S : function () {
  17078. return toInt(this.milliseconds() / 100);
  17079. },
  17080. SS : function () {
  17081. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17082. },
  17083. SSS : function () {
  17084. return leftZeroFill(this.milliseconds(), 3);
  17085. },
  17086. SSSS : function () {
  17087. return leftZeroFill(this.milliseconds(), 3);
  17088. },
  17089. Z : function () {
  17090. var a = -this.zone(),
  17091. b = "+";
  17092. if (a < 0) {
  17093. a = -a;
  17094. b = "-";
  17095. }
  17096. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  17097. },
  17098. ZZ : function () {
  17099. var a = -this.zone(),
  17100. b = "+";
  17101. if (a < 0) {
  17102. a = -a;
  17103. b = "-";
  17104. }
  17105. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  17106. },
  17107. z : function () {
  17108. return this.zoneAbbr();
  17109. },
  17110. zz : function () {
  17111. return this.zoneName();
  17112. },
  17113. X : function () {
  17114. return this.unix();
  17115. },
  17116. Q : function () {
  17117. return this.quarter();
  17118. }
  17119. },
  17120. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  17121. function defaultParsingFlags() {
  17122. // We need to deep clone this object, and es5 standard is not very
  17123. // helpful.
  17124. return {
  17125. empty : false,
  17126. unusedTokens : [],
  17127. unusedInput : [],
  17128. overflow : -2,
  17129. charsLeftOver : 0,
  17130. nullInput : false,
  17131. invalidMonth : null,
  17132. invalidFormat : false,
  17133. userInvalidated : false,
  17134. iso: false
  17135. };
  17136. }
  17137. function deprecate(msg, fn) {
  17138. var firstTime = true;
  17139. function printMsg() {
  17140. if (moment.suppressDeprecationWarnings === false &&
  17141. typeof console !== 'undefined' && console.warn) {
  17142. console.warn("Deprecation warning: " + msg);
  17143. }
  17144. }
  17145. return extend(function () {
  17146. if (firstTime) {
  17147. printMsg();
  17148. firstTime = false;
  17149. }
  17150. return fn.apply(this, arguments);
  17151. }, fn);
  17152. }
  17153. function padToken(func, count) {
  17154. return function (a) {
  17155. return leftZeroFill(func.call(this, a), count);
  17156. };
  17157. }
  17158. function ordinalizeToken(func, period) {
  17159. return function (a) {
  17160. return this.lang().ordinal(func.call(this, a), period);
  17161. };
  17162. }
  17163. while (ordinalizeTokens.length) {
  17164. i = ordinalizeTokens.pop();
  17165. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  17166. }
  17167. while (paddedTokens.length) {
  17168. i = paddedTokens.pop();
  17169. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  17170. }
  17171. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  17172. /************************************
  17173. Constructors
  17174. ************************************/
  17175. function Language() {
  17176. }
  17177. // Moment prototype object
  17178. function Moment(config) {
  17179. checkOverflow(config);
  17180. extend(this, config);
  17181. }
  17182. // Duration Constructor
  17183. function Duration(duration) {
  17184. var normalizedInput = normalizeObjectUnits(duration),
  17185. years = normalizedInput.year || 0,
  17186. quarters = normalizedInput.quarter || 0,
  17187. months = normalizedInput.month || 0,
  17188. weeks = normalizedInput.week || 0,
  17189. days = normalizedInput.day || 0,
  17190. hours = normalizedInput.hour || 0,
  17191. minutes = normalizedInput.minute || 0,
  17192. seconds = normalizedInput.second || 0,
  17193. milliseconds = normalizedInput.millisecond || 0;
  17194. // representation for dateAddRemove
  17195. this._milliseconds = +milliseconds +
  17196. seconds * 1e3 + // 1000
  17197. minutes * 6e4 + // 1000 * 60
  17198. hours * 36e5; // 1000 * 60 * 60
  17199. // Because of dateAddRemove treats 24 hours as different from a
  17200. // day when working around DST, we need to store them separately
  17201. this._days = +days +
  17202. weeks * 7;
  17203. // It is impossible translate months into days without knowing
  17204. // which months you are are talking about, so we have to store
  17205. // it separately.
  17206. this._months = +months +
  17207. quarters * 3 +
  17208. years * 12;
  17209. this._data = {};
  17210. this._bubble();
  17211. }
  17212. /************************************
  17213. Helpers
  17214. ************************************/
  17215. function extend(a, b) {
  17216. for (var i in b) {
  17217. if (b.hasOwnProperty(i)) {
  17218. a[i] = b[i];
  17219. }
  17220. }
  17221. if (b.hasOwnProperty("toString")) {
  17222. a.toString = b.toString;
  17223. }
  17224. if (b.hasOwnProperty("valueOf")) {
  17225. a.valueOf = b.valueOf;
  17226. }
  17227. return a;
  17228. }
  17229. function cloneMoment(m) {
  17230. var result = {}, i;
  17231. for (i in m) {
  17232. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17233. result[i] = m[i];
  17234. }
  17235. }
  17236. return result;
  17237. }
  17238. function absRound(number) {
  17239. if (number < 0) {
  17240. return Math.ceil(number);
  17241. } else {
  17242. return Math.floor(number);
  17243. }
  17244. }
  17245. // left zero fill a number
  17246. // see http://jsperf.com/left-zero-filling for performance comparison
  17247. function leftZeroFill(number, targetLength, forceSign) {
  17248. var output = '' + Math.abs(number),
  17249. sign = number >= 0;
  17250. while (output.length < targetLength) {
  17251. output = '0' + output;
  17252. }
  17253. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17254. }
  17255. // helper function for _.addTime and _.subtractTime
  17256. function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
  17257. var milliseconds = duration._milliseconds,
  17258. days = duration._days,
  17259. months = duration._months;
  17260. updateOffset = updateOffset == null ? true : updateOffset;
  17261. if (milliseconds) {
  17262. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17263. }
  17264. if (days) {
  17265. rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
  17266. }
  17267. if (months) {
  17268. rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
  17269. }
  17270. if (updateOffset) {
  17271. moment.updateOffset(mom, days || months);
  17272. }
  17273. }
  17274. // check if is an array
  17275. function isArray(input) {
  17276. return Object.prototype.toString.call(input) === '[object Array]';
  17277. }
  17278. function isDate(input) {
  17279. return Object.prototype.toString.call(input) === '[object Date]' ||
  17280. input instanceof Date;
  17281. }
  17282. // compare two arrays, return the number of differences
  17283. function compareArrays(array1, array2, dontConvert) {
  17284. var len = Math.min(array1.length, array2.length),
  17285. lengthDiff = Math.abs(array1.length - array2.length),
  17286. diffs = 0,
  17287. i;
  17288. for (i = 0; i < len; i++) {
  17289. if ((dontConvert && array1[i] !== array2[i]) ||
  17290. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17291. diffs++;
  17292. }
  17293. }
  17294. return diffs + lengthDiff;
  17295. }
  17296. function normalizeUnits(units) {
  17297. if (units) {
  17298. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17299. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17300. }
  17301. return units;
  17302. }
  17303. function normalizeObjectUnits(inputObject) {
  17304. var normalizedInput = {},
  17305. normalizedProp,
  17306. prop;
  17307. for (prop in inputObject) {
  17308. if (inputObject.hasOwnProperty(prop)) {
  17309. normalizedProp = normalizeUnits(prop);
  17310. if (normalizedProp) {
  17311. normalizedInput[normalizedProp] = inputObject[prop];
  17312. }
  17313. }
  17314. }
  17315. return normalizedInput;
  17316. }
  17317. function makeList(field) {
  17318. var count, setter;
  17319. if (field.indexOf('week') === 0) {
  17320. count = 7;
  17321. setter = 'day';
  17322. }
  17323. else if (field.indexOf('month') === 0) {
  17324. count = 12;
  17325. setter = 'month';
  17326. }
  17327. else {
  17328. return;
  17329. }
  17330. moment[field] = function (format, index) {
  17331. var i, getter,
  17332. method = moment.fn._lang[field],
  17333. results = [];
  17334. if (typeof format === 'number') {
  17335. index = format;
  17336. format = undefined;
  17337. }
  17338. getter = function (i) {
  17339. var m = moment().utc().set(setter, i);
  17340. return method.call(moment.fn._lang, m, format || '');
  17341. };
  17342. if (index != null) {
  17343. return getter(index);
  17344. }
  17345. else {
  17346. for (i = 0; i < count; i++) {
  17347. results.push(getter(i));
  17348. }
  17349. return results;
  17350. }
  17351. };
  17352. }
  17353. function toInt(argumentForCoercion) {
  17354. var coercedNumber = +argumentForCoercion,
  17355. value = 0;
  17356. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17357. if (coercedNumber >= 0) {
  17358. value = Math.floor(coercedNumber);
  17359. } else {
  17360. value = Math.ceil(coercedNumber);
  17361. }
  17362. }
  17363. return value;
  17364. }
  17365. function daysInMonth(year, month) {
  17366. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17367. }
  17368. function weeksInYear(year, dow, doy) {
  17369. return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
  17370. }
  17371. function daysInYear(year) {
  17372. return isLeapYear(year) ? 366 : 365;
  17373. }
  17374. function isLeapYear(year) {
  17375. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17376. }
  17377. function checkOverflow(m) {
  17378. var overflow;
  17379. if (m._a && m._pf.overflow === -2) {
  17380. overflow =
  17381. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17382. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17383. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17384. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17385. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17386. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17387. -1;
  17388. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17389. overflow = DATE;
  17390. }
  17391. m._pf.overflow = overflow;
  17392. }
  17393. }
  17394. function isValid(m) {
  17395. if (m._isValid == null) {
  17396. m._isValid = !isNaN(m._d.getTime()) &&
  17397. m._pf.overflow < 0 &&
  17398. !m._pf.empty &&
  17399. !m._pf.invalidMonth &&
  17400. !m._pf.nullInput &&
  17401. !m._pf.invalidFormat &&
  17402. !m._pf.userInvalidated;
  17403. if (m._strict) {
  17404. m._isValid = m._isValid &&
  17405. m._pf.charsLeftOver === 0 &&
  17406. m._pf.unusedTokens.length === 0;
  17407. }
  17408. }
  17409. return m._isValid;
  17410. }
  17411. function normalizeLanguage(key) {
  17412. return key ? key.toLowerCase().replace('_', '-') : key;
  17413. }
  17414. // Return a moment from input, that is local/utc/zone equivalent to model.
  17415. function makeAs(input, model) {
  17416. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17417. moment(input).local();
  17418. }
  17419. /************************************
  17420. Languages
  17421. ************************************/
  17422. extend(Language.prototype, {
  17423. set : function (config) {
  17424. var prop, i;
  17425. for (i in config) {
  17426. prop = config[i];
  17427. if (typeof prop === 'function') {
  17428. this[i] = prop;
  17429. } else {
  17430. this['_' + i] = prop;
  17431. }
  17432. }
  17433. },
  17434. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17435. months : function (m) {
  17436. return this._months[m.month()];
  17437. },
  17438. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17439. monthsShort : function (m) {
  17440. return this._monthsShort[m.month()];
  17441. },
  17442. monthsParse : function (monthName) {
  17443. var i, mom, regex;
  17444. if (!this._monthsParse) {
  17445. this._monthsParse = [];
  17446. }
  17447. for (i = 0; i < 12; i++) {
  17448. // make the regex if we don't have it already
  17449. if (!this._monthsParse[i]) {
  17450. mom = moment.utc([2000, i]);
  17451. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17452. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17453. }
  17454. // test the regex
  17455. if (this._monthsParse[i].test(monthName)) {
  17456. return i;
  17457. }
  17458. }
  17459. },
  17460. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17461. weekdays : function (m) {
  17462. return this._weekdays[m.day()];
  17463. },
  17464. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17465. weekdaysShort : function (m) {
  17466. return this._weekdaysShort[m.day()];
  17467. },
  17468. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17469. weekdaysMin : function (m) {
  17470. return this._weekdaysMin[m.day()];
  17471. },
  17472. weekdaysParse : function (weekdayName) {
  17473. var i, mom, regex;
  17474. if (!this._weekdaysParse) {
  17475. this._weekdaysParse = [];
  17476. }
  17477. for (i = 0; i < 7; i++) {
  17478. // make the regex if we don't have it already
  17479. if (!this._weekdaysParse[i]) {
  17480. mom = moment([2000, 1]).day(i);
  17481. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17482. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17483. }
  17484. // test the regex
  17485. if (this._weekdaysParse[i].test(weekdayName)) {
  17486. return i;
  17487. }
  17488. }
  17489. },
  17490. _longDateFormat : {
  17491. LT : "h:mm A",
  17492. L : "MM/DD/YYYY",
  17493. LL : "MMMM D YYYY",
  17494. LLL : "MMMM D YYYY LT",
  17495. LLLL : "dddd, MMMM D YYYY LT"
  17496. },
  17497. longDateFormat : function (key) {
  17498. var output = this._longDateFormat[key];
  17499. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17500. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17501. return val.slice(1);
  17502. });
  17503. this._longDateFormat[key] = output;
  17504. }
  17505. return output;
  17506. },
  17507. isPM : function (input) {
  17508. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17509. // Using charAt should be more compatible.
  17510. return ((input + '').toLowerCase().charAt(0) === 'p');
  17511. },
  17512. _meridiemParse : /[ap]\.?m?\.?/i,
  17513. meridiem : function (hours, minutes, isLower) {
  17514. if (hours > 11) {
  17515. return isLower ? 'pm' : 'PM';
  17516. } else {
  17517. return isLower ? 'am' : 'AM';
  17518. }
  17519. },
  17520. _calendar : {
  17521. sameDay : '[Today at] LT',
  17522. nextDay : '[Tomorrow at] LT',
  17523. nextWeek : 'dddd [at] LT',
  17524. lastDay : '[Yesterday at] LT',
  17525. lastWeek : '[Last] dddd [at] LT',
  17526. sameElse : 'L'
  17527. },
  17528. calendar : function (key, mom) {
  17529. var output = this._calendar[key];
  17530. return typeof output === 'function' ? output.apply(mom) : output;
  17531. },
  17532. _relativeTime : {
  17533. future : "in %s",
  17534. past : "%s ago",
  17535. s : "a few seconds",
  17536. m : "a minute",
  17537. mm : "%d minutes",
  17538. h : "an hour",
  17539. hh : "%d hours",
  17540. d : "a day",
  17541. dd : "%d days",
  17542. M : "a month",
  17543. MM : "%d months",
  17544. y : "a year",
  17545. yy : "%d years"
  17546. },
  17547. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17548. var output = this._relativeTime[string];
  17549. return (typeof output === 'function') ?
  17550. output(number, withoutSuffix, string, isFuture) :
  17551. output.replace(/%d/i, number);
  17552. },
  17553. pastFuture : function (diff, output) {
  17554. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17555. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17556. },
  17557. ordinal : function (number) {
  17558. return this._ordinal.replace("%d", number);
  17559. },
  17560. _ordinal : "%d",
  17561. preparse : function (string) {
  17562. return string;
  17563. },
  17564. postformat : function (string) {
  17565. return string;
  17566. },
  17567. week : function (mom) {
  17568. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17569. },
  17570. _week : {
  17571. dow : 0, // Sunday is the first day of the week.
  17572. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17573. },
  17574. _invalidDate: 'Invalid date',
  17575. invalidDate: function () {
  17576. return this._invalidDate;
  17577. }
  17578. });
  17579. // Loads a language definition into the `languages` cache. The function
  17580. // takes a key and optionally values. If not in the browser and no values
  17581. // are provided, it will load the language file module. As a convenience,
  17582. // this function also returns the language values.
  17583. function loadLang(key, values) {
  17584. values.abbr = key;
  17585. if (!languages[key]) {
  17586. languages[key] = new Language();
  17587. }
  17588. languages[key].set(values);
  17589. return languages[key];
  17590. }
  17591. // Remove a language from the `languages` cache. Mostly useful in tests.
  17592. function unloadLang(key) {
  17593. delete languages[key];
  17594. }
  17595. // Determines which language definition to use and returns it.
  17596. //
  17597. // With no parameters, it will return the global language. If you
  17598. // pass in a language key, such as 'en', it will return the
  17599. // definition for 'en', so long as 'en' has already been loaded using
  17600. // moment.lang.
  17601. function getLangDefinition(key) {
  17602. var i = 0, j, lang, next, split,
  17603. get = function (k) {
  17604. if (!languages[k] && hasModule) {
  17605. try {
  17606. require('./lang/' + k);
  17607. } catch (e) { }
  17608. }
  17609. return languages[k];
  17610. };
  17611. if (!key) {
  17612. return moment.fn._lang;
  17613. }
  17614. if (!isArray(key)) {
  17615. //short-circuit everything else
  17616. lang = get(key);
  17617. if (lang) {
  17618. return lang;
  17619. }
  17620. key = [key];
  17621. }
  17622. //pick the language from the array
  17623. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17624. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17625. while (i < key.length) {
  17626. split = normalizeLanguage(key[i]).split('-');
  17627. j = split.length;
  17628. next = normalizeLanguage(key[i + 1]);
  17629. next = next ? next.split('-') : null;
  17630. while (j > 0) {
  17631. lang = get(split.slice(0, j).join('-'));
  17632. if (lang) {
  17633. return lang;
  17634. }
  17635. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17636. //the next array item is better than a shallower substring of this one
  17637. break;
  17638. }
  17639. j--;
  17640. }
  17641. i++;
  17642. }
  17643. return moment.fn._lang;
  17644. }
  17645. /************************************
  17646. Formatting
  17647. ************************************/
  17648. function removeFormattingTokens(input) {
  17649. if (input.match(/\[[\s\S]/)) {
  17650. return input.replace(/^\[|\]$/g, "");
  17651. }
  17652. return input.replace(/\\/g, "");
  17653. }
  17654. function makeFormatFunction(format) {
  17655. var array = format.match(formattingTokens), i, length;
  17656. for (i = 0, length = array.length; i < length; i++) {
  17657. if (formatTokenFunctions[array[i]]) {
  17658. array[i] = formatTokenFunctions[array[i]];
  17659. } else {
  17660. array[i] = removeFormattingTokens(array[i]);
  17661. }
  17662. }
  17663. return function (mom) {
  17664. var output = "";
  17665. for (i = 0; i < length; i++) {
  17666. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  17667. }
  17668. return output;
  17669. };
  17670. }
  17671. // format date using native date object
  17672. function formatMoment(m, format) {
  17673. if (!m.isValid()) {
  17674. return m.lang().invalidDate();
  17675. }
  17676. format = expandFormat(format, m.lang());
  17677. if (!formatFunctions[format]) {
  17678. formatFunctions[format] = makeFormatFunction(format);
  17679. }
  17680. return formatFunctions[format](m);
  17681. }
  17682. function expandFormat(format, lang) {
  17683. var i = 5;
  17684. function replaceLongDateFormatTokens(input) {
  17685. return lang.longDateFormat(input) || input;
  17686. }
  17687. localFormattingTokens.lastIndex = 0;
  17688. while (i >= 0 && localFormattingTokens.test(format)) {
  17689. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  17690. localFormattingTokens.lastIndex = 0;
  17691. i -= 1;
  17692. }
  17693. return format;
  17694. }
  17695. /************************************
  17696. Parsing
  17697. ************************************/
  17698. // get the regex to find the next token
  17699. function getParseRegexForToken(token, config) {
  17700. var a, strict = config._strict;
  17701. switch (token) {
  17702. case 'Q':
  17703. return parseTokenOneDigit;
  17704. case 'DDDD':
  17705. return parseTokenThreeDigits;
  17706. case 'YYYY':
  17707. case 'GGGG':
  17708. case 'gggg':
  17709. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  17710. case 'Y':
  17711. case 'G':
  17712. case 'g':
  17713. return parseTokenSignedNumber;
  17714. case 'YYYYYY':
  17715. case 'YYYYY':
  17716. case 'GGGGG':
  17717. case 'ggggg':
  17718. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  17719. case 'S':
  17720. if (strict) { return parseTokenOneDigit; }
  17721. /* falls through */
  17722. case 'SS':
  17723. if (strict) { return parseTokenTwoDigits; }
  17724. /* falls through */
  17725. case 'SSS':
  17726. if (strict) { return parseTokenThreeDigits; }
  17727. /* falls through */
  17728. case 'DDD':
  17729. return parseTokenOneToThreeDigits;
  17730. case 'MMM':
  17731. case 'MMMM':
  17732. case 'dd':
  17733. case 'ddd':
  17734. case 'dddd':
  17735. return parseTokenWord;
  17736. case 'a':
  17737. case 'A':
  17738. return getLangDefinition(config._l)._meridiemParse;
  17739. case 'X':
  17740. return parseTokenTimestampMs;
  17741. case 'Z':
  17742. case 'ZZ':
  17743. return parseTokenTimezone;
  17744. case 'T':
  17745. return parseTokenT;
  17746. case 'SSSS':
  17747. return parseTokenDigits;
  17748. case 'MM':
  17749. case 'DD':
  17750. case 'YY':
  17751. case 'GG':
  17752. case 'gg':
  17753. case 'HH':
  17754. case 'hh':
  17755. case 'mm':
  17756. case 'ss':
  17757. case 'ww':
  17758. case 'WW':
  17759. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  17760. case 'M':
  17761. case 'D':
  17762. case 'd':
  17763. case 'H':
  17764. case 'h':
  17765. case 'm':
  17766. case 's':
  17767. case 'w':
  17768. case 'W':
  17769. case 'e':
  17770. case 'E':
  17771. return parseTokenOneOrTwoDigits;
  17772. case 'Do':
  17773. return parseTokenOrdinal;
  17774. default :
  17775. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  17776. return a;
  17777. }
  17778. }
  17779. function timezoneMinutesFromString(string) {
  17780. string = string || "";
  17781. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  17782. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  17783. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  17784. minutes = +(parts[1] * 60) + toInt(parts[2]);
  17785. return parts[0] === '+' ? -minutes : minutes;
  17786. }
  17787. // function to convert string input to date
  17788. function addTimeToArrayFromToken(token, input, config) {
  17789. var a, datePartArray = config._a;
  17790. switch (token) {
  17791. // QUARTER
  17792. case 'Q':
  17793. if (input != null) {
  17794. datePartArray[MONTH] = (toInt(input) - 1) * 3;
  17795. }
  17796. break;
  17797. // MONTH
  17798. case 'M' : // fall through to MM
  17799. case 'MM' :
  17800. if (input != null) {
  17801. datePartArray[MONTH] = toInt(input) - 1;
  17802. }
  17803. break;
  17804. case 'MMM' : // fall through to MMMM
  17805. case 'MMMM' :
  17806. a = getLangDefinition(config._l).monthsParse(input);
  17807. // if we didn't find a month name, mark the date as invalid.
  17808. if (a != null) {
  17809. datePartArray[MONTH] = a;
  17810. } else {
  17811. config._pf.invalidMonth = input;
  17812. }
  17813. break;
  17814. // DAY OF MONTH
  17815. case 'D' : // fall through to DD
  17816. case 'DD' :
  17817. if (input != null) {
  17818. datePartArray[DATE] = toInt(input);
  17819. }
  17820. break;
  17821. case 'Do' :
  17822. if (input != null) {
  17823. datePartArray[DATE] = toInt(parseInt(input, 10));
  17824. }
  17825. break;
  17826. // DAY OF YEAR
  17827. case 'DDD' : // fall through to DDDD
  17828. case 'DDDD' :
  17829. if (input != null) {
  17830. config._dayOfYear = toInt(input);
  17831. }
  17832. break;
  17833. // YEAR
  17834. case 'YY' :
  17835. datePartArray[YEAR] = moment.parseTwoDigitYear(input);
  17836. break;
  17837. case 'YYYY' :
  17838. case 'YYYYY' :
  17839. case 'YYYYYY' :
  17840. datePartArray[YEAR] = toInt(input);
  17841. break;
  17842. // AM / PM
  17843. case 'a' : // fall through to A
  17844. case 'A' :
  17845. config._isPm = getLangDefinition(config._l).isPM(input);
  17846. break;
  17847. // 24 HOUR
  17848. case 'H' : // fall through to hh
  17849. case 'HH' : // fall through to hh
  17850. case 'h' : // fall through to hh
  17851. case 'hh' :
  17852. datePartArray[HOUR] = toInt(input);
  17853. break;
  17854. // MINUTE
  17855. case 'm' : // fall through to mm
  17856. case 'mm' :
  17857. datePartArray[MINUTE] = toInt(input);
  17858. break;
  17859. // SECOND
  17860. case 's' : // fall through to ss
  17861. case 'ss' :
  17862. datePartArray[SECOND] = toInt(input);
  17863. break;
  17864. // MILLISECOND
  17865. case 'S' :
  17866. case 'SS' :
  17867. case 'SSS' :
  17868. case 'SSSS' :
  17869. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  17870. break;
  17871. // UNIX TIMESTAMP WITH MS
  17872. case 'X':
  17873. config._d = new Date(parseFloat(input) * 1000);
  17874. break;
  17875. // TIMEZONE
  17876. case 'Z' : // fall through to ZZ
  17877. case 'ZZ' :
  17878. config._useUTC = true;
  17879. config._tzm = timezoneMinutesFromString(input);
  17880. break;
  17881. case 'w':
  17882. case 'ww':
  17883. case 'W':
  17884. case 'WW':
  17885. case 'd':
  17886. case 'dd':
  17887. case 'ddd':
  17888. case 'dddd':
  17889. case 'e':
  17890. case 'E':
  17891. token = token.substr(0, 1);
  17892. /* falls through */
  17893. case 'gg':
  17894. case 'gggg':
  17895. case 'GG':
  17896. case 'GGGG':
  17897. case 'GGGGG':
  17898. token = token.substr(0, 2);
  17899. if (input) {
  17900. config._w = config._w || {};
  17901. config._w[token] = input;
  17902. }
  17903. break;
  17904. }
  17905. }
  17906. // convert an array to a date.
  17907. // the array should mirror the parameters below
  17908. // note: all values past the year are optional and will default to the lowest possible value.
  17909. // [year, month, day , hour, minute, second, millisecond]
  17910. function dateFromConfig(config) {
  17911. var i, date, input = [], currentDate,
  17912. yearToUse, fixYear, w, temp, lang, weekday, week;
  17913. if (config._d) {
  17914. return;
  17915. }
  17916. currentDate = currentDateArray(config);
  17917. //compute day of the year from weeks and weekdays
  17918. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  17919. fixYear = function (val) {
  17920. var intVal = parseInt(val, 10);
  17921. return val ?
  17922. (val.length < 3 ? (intVal > 68 ? 1900 + intVal : 2000 + intVal) : intVal) :
  17923. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  17924. };
  17925. w = config._w;
  17926. if (w.GG != null || w.W != null || w.E != null) {
  17927. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  17928. }
  17929. else {
  17930. lang = getLangDefinition(config._l);
  17931. weekday = w.d != null ? parseWeekday(w.d, lang) :
  17932. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  17933. week = parseInt(w.w, 10) || 1;
  17934. //if we're parsing 'd', then the low day numbers may be next week
  17935. if (w.d != null && weekday < lang._week.dow) {
  17936. week++;
  17937. }
  17938. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  17939. }
  17940. config._a[YEAR] = temp.year;
  17941. config._dayOfYear = temp.dayOfYear;
  17942. }
  17943. //if the day of the year is set, figure out what it is
  17944. if (config._dayOfYear) {
  17945. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  17946. if (config._dayOfYear > daysInYear(yearToUse)) {
  17947. config._pf._overflowDayOfYear = true;
  17948. }
  17949. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  17950. config._a[MONTH] = date.getUTCMonth();
  17951. config._a[DATE] = date.getUTCDate();
  17952. }
  17953. // Default to current date.
  17954. // * if no year, month, day of month are given, default to today
  17955. // * if day of month is given, default month and year
  17956. // * if month is given, default only year
  17957. // * if year is given, don't default anything
  17958. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  17959. config._a[i] = input[i] = currentDate[i];
  17960. }
  17961. // Zero out whatever was not defaulted, including time
  17962. for (; i < 7; i++) {
  17963. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  17964. }
  17965. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  17966. input[HOUR] += toInt((config._tzm || 0) / 60);
  17967. input[MINUTE] += toInt((config._tzm || 0) % 60);
  17968. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  17969. }
  17970. function dateFromObject(config) {
  17971. var normalizedInput;
  17972. if (config._d) {
  17973. return;
  17974. }
  17975. normalizedInput = normalizeObjectUnits(config._i);
  17976. config._a = [
  17977. normalizedInput.year,
  17978. normalizedInput.month,
  17979. normalizedInput.day,
  17980. normalizedInput.hour,
  17981. normalizedInput.minute,
  17982. normalizedInput.second,
  17983. normalizedInput.millisecond
  17984. ];
  17985. dateFromConfig(config);
  17986. }
  17987. function currentDateArray(config) {
  17988. var now = new Date();
  17989. if (config._useUTC) {
  17990. return [
  17991. now.getUTCFullYear(),
  17992. now.getUTCMonth(),
  17993. now.getUTCDate()
  17994. ];
  17995. } else {
  17996. return [now.getFullYear(), now.getMonth(), now.getDate()];
  17997. }
  17998. }
  17999. // date from string and format string
  18000. function makeDateFromStringAndFormat(config) {
  18001. config._a = [];
  18002. config._pf.empty = true;
  18003. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  18004. var lang = getLangDefinition(config._l),
  18005. string = '' + config._i,
  18006. i, parsedInput, tokens, token, skipped,
  18007. stringLength = string.length,
  18008. totalParsedInputLength = 0;
  18009. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  18010. for (i = 0; i < tokens.length; i++) {
  18011. token = tokens[i];
  18012. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  18013. if (parsedInput) {
  18014. skipped = string.substr(0, string.indexOf(parsedInput));
  18015. if (skipped.length > 0) {
  18016. config._pf.unusedInput.push(skipped);
  18017. }
  18018. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  18019. totalParsedInputLength += parsedInput.length;
  18020. }
  18021. // don't parse if it's not a known token
  18022. if (formatTokenFunctions[token]) {
  18023. if (parsedInput) {
  18024. config._pf.empty = false;
  18025. }
  18026. else {
  18027. config._pf.unusedTokens.push(token);
  18028. }
  18029. addTimeToArrayFromToken(token, parsedInput, config);
  18030. }
  18031. else if (config._strict && !parsedInput) {
  18032. config._pf.unusedTokens.push(token);
  18033. }
  18034. }
  18035. // add remaining unparsed input length to the string
  18036. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  18037. if (string.length > 0) {
  18038. config._pf.unusedInput.push(string);
  18039. }
  18040. // handle am pm
  18041. if (config._isPm && config._a[HOUR] < 12) {
  18042. config._a[HOUR] += 12;
  18043. }
  18044. // if is 12 am, change hours to 0
  18045. if (config._isPm === false && config._a[HOUR] === 12) {
  18046. config._a[HOUR] = 0;
  18047. }
  18048. dateFromConfig(config);
  18049. checkOverflow(config);
  18050. }
  18051. function unescapeFormat(s) {
  18052. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  18053. return p1 || p2 || p3 || p4;
  18054. });
  18055. }
  18056. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  18057. function regexpEscape(s) {
  18058. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18059. }
  18060. // date from string and array of format strings
  18061. function makeDateFromStringAndArray(config) {
  18062. var tempConfig,
  18063. bestMoment,
  18064. scoreToBeat,
  18065. i,
  18066. currentScore;
  18067. if (config._f.length === 0) {
  18068. config._pf.invalidFormat = true;
  18069. config._d = new Date(NaN);
  18070. return;
  18071. }
  18072. for (i = 0; i < config._f.length; i++) {
  18073. currentScore = 0;
  18074. tempConfig = extend({}, config);
  18075. tempConfig._pf = defaultParsingFlags();
  18076. tempConfig._f = config._f[i];
  18077. makeDateFromStringAndFormat(tempConfig);
  18078. if (!isValid(tempConfig)) {
  18079. continue;
  18080. }
  18081. // if there is any input that was not parsed add a penalty for that format
  18082. currentScore += tempConfig._pf.charsLeftOver;
  18083. //or tokens
  18084. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18085. tempConfig._pf.score = currentScore;
  18086. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18087. scoreToBeat = currentScore;
  18088. bestMoment = tempConfig;
  18089. }
  18090. }
  18091. extend(config, bestMoment || tempConfig);
  18092. }
  18093. // date from iso format
  18094. function makeDateFromString(config) {
  18095. var i, l,
  18096. string = config._i,
  18097. match = isoRegex.exec(string);
  18098. if (match) {
  18099. config._pf.iso = true;
  18100. for (i = 0, l = isoDates.length; i < l; i++) {
  18101. if (isoDates[i][1].exec(string)) {
  18102. // match[5] should be "T" or undefined
  18103. config._f = isoDates[i][0] + (match[6] || " ");
  18104. break;
  18105. }
  18106. }
  18107. for (i = 0, l = isoTimes.length; i < l; i++) {
  18108. if (isoTimes[i][1].exec(string)) {
  18109. config._f += isoTimes[i][0];
  18110. break;
  18111. }
  18112. }
  18113. if (string.match(parseTokenTimezone)) {
  18114. config._f += "Z";
  18115. }
  18116. makeDateFromStringAndFormat(config);
  18117. }
  18118. else {
  18119. moment.createFromInputFallback(config);
  18120. }
  18121. }
  18122. function makeDateFromInput(config) {
  18123. var input = config._i,
  18124. matched = aspNetJsonRegex.exec(input);
  18125. if (input === undefined) {
  18126. config._d = new Date();
  18127. } else if (matched) {
  18128. config._d = new Date(+matched[1]);
  18129. } else if (typeof input === 'string') {
  18130. makeDateFromString(config);
  18131. } else if (isArray(input)) {
  18132. config._a = input.slice(0);
  18133. dateFromConfig(config);
  18134. } else if (isDate(input)) {
  18135. config._d = new Date(+input);
  18136. } else if (typeof(input) === 'object') {
  18137. dateFromObject(config);
  18138. } else if (typeof(input) === 'number') {
  18139. // from milliseconds
  18140. config._d = new Date(input);
  18141. } else {
  18142. moment.createFromInputFallback(config);
  18143. }
  18144. }
  18145. function makeDate(y, m, d, h, M, s, ms) {
  18146. //can't just apply() to create a date:
  18147. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  18148. var date = new Date(y, m, d, h, M, s, ms);
  18149. //the date constructor doesn't accept years < 1970
  18150. if (y < 1970) {
  18151. date.setFullYear(y);
  18152. }
  18153. return date;
  18154. }
  18155. function makeUTCDate(y) {
  18156. var date = new Date(Date.UTC.apply(null, arguments));
  18157. if (y < 1970) {
  18158. date.setUTCFullYear(y);
  18159. }
  18160. return date;
  18161. }
  18162. function parseWeekday(input, language) {
  18163. if (typeof input === 'string') {
  18164. if (!isNaN(input)) {
  18165. input = parseInt(input, 10);
  18166. }
  18167. else {
  18168. input = language.weekdaysParse(input);
  18169. if (typeof input !== 'number') {
  18170. return null;
  18171. }
  18172. }
  18173. }
  18174. return input;
  18175. }
  18176. /************************************
  18177. Relative Time
  18178. ************************************/
  18179. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  18180. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  18181. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  18182. }
  18183. function relativeTime(milliseconds, withoutSuffix, lang) {
  18184. var seconds = round(Math.abs(milliseconds) / 1000),
  18185. minutes = round(seconds / 60),
  18186. hours = round(minutes / 60),
  18187. days = round(hours / 24),
  18188. years = round(days / 365),
  18189. args = seconds < 45 && ['s', seconds] ||
  18190. minutes === 1 && ['m'] ||
  18191. minutes < 45 && ['mm', minutes] ||
  18192. hours === 1 && ['h'] ||
  18193. hours < 22 && ['hh', hours] ||
  18194. days === 1 && ['d'] ||
  18195. days <= 25 && ['dd', days] ||
  18196. days <= 45 && ['M'] ||
  18197. days < 345 && ['MM', round(days / 30)] ||
  18198. years === 1 && ['y'] || ['yy', years];
  18199. args[2] = withoutSuffix;
  18200. args[3] = milliseconds > 0;
  18201. args[4] = lang;
  18202. return substituteTimeAgo.apply({}, args);
  18203. }
  18204. /************************************
  18205. Week of Year
  18206. ************************************/
  18207. // firstDayOfWeek 0 = sun, 6 = sat
  18208. // the day of the week that starts the week
  18209. // (usually sunday or monday)
  18210. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18211. // the first week is the week that contains the first
  18212. // of this day of the week
  18213. // (eg. ISO weeks use thursday (4))
  18214. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18215. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18216. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18217. adjustedMoment;
  18218. if (daysToDayOfWeek > end) {
  18219. daysToDayOfWeek -= 7;
  18220. }
  18221. if (daysToDayOfWeek < end - 7) {
  18222. daysToDayOfWeek += 7;
  18223. }
  18224. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18225. return {
  18226. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18227. year: adjustedMoment.year()
  18228. };
  18229. }
  18230. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18231. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18232. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18233. weekday = weekday != null ? weekday : firstDayOfWeek;
  18234. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18235. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18236. return {
  18237. year: dayOfYear > 0 ? year : year - 1,
  18238. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18239. };
  18240. }
  18241. /************************************
  18242. Top Level Functions
  18243. ************************************/
  18244. function makeMoment(config) {
  18245. var input = config._i,
  18246. format = config._f;
  18247. if (input === null || (format === undefined && input === '')) {
  18248. return moment.invalid({nullInput: true});
  18249. }
  18250. if (typeof input === 'string') {
  18251. config._i = input = getLangDefinition().preparse(input);
  18252. }
  18253. if (moment.isMoment(input)) {
  18254. config = cloneMoment(input);
  18255. config._d = new Date(+input._d);
  18256. } else if (format) {
  18257. if (isArray(format)) {
  18258. makeDateFromStringAndArray(config);
  18259. } else {
  18260. makeDateFromStringAndFormat(config);
  18261. }
  18262. } else {
  18263. makeDateFromInput(config);
  18264. }
  18265. return new Moment(config);
  18266. }
  18267. moment = function (input, format, lang, strict) {
  18268. var c;
  18269. if (typeof(lang) === "boolean") {
  18270. strict = lang;
  18271. lang = undefined;
  18272. }
  18273. // object construction must be done this way.
  18274. // https://github.com/moment/moment/issues/1423
  18275. c = {};
  18276. c._isAMomentObject = true;
  18277. c._i = input;
  18278. c._f = format;
  18279. c._l = lang;
  18280. c._strict = strict;
  18281. c._isUTC = false;
  18282. c._pf = defaultParsingFlags();
  18283. return makeMoment(c);
  18284. };
  18285. moment.suppressDeprecationWarnings = false;
  18286. moment.createFromInputFallback = deprecate(
  18287. "moment construction falls back to js Date. This is " +
  18288. "discouraged and will be removed in upcoming major " +
  18289. "release. Please refer to " +
  18290. "https://github.com/moment/moment/issues/1407 for more info.",
  18291. function (config) {
  18292. config._d = new Date(config._i);
  18293. });
  18294. // creating with utc
  18295. moment.utc = function (input, format, lang, strict) {
  18296. var c;
  18297. if (typeof(lang) === "boolean") {
  18298. strict = lang;
  18299. lang = undefined;
  18300. }
  18301. // object construction must be done this way.
  18302. // https://github.com/moment/moment/issues/1423
  18303. c = {};
  18304. c._isAMomentObject = true;
  18305. c._useUTC = true;
  18306. c._isUTC = true;
  18307. c._l = lang;
  18308. c._i = input;
  18309. c._f = format;
  18310. c._strict = strict;
  18311. c._pf = defaultParsingFlags();
  18312. return makeMoment(c).utc();
  18313. };
  18314. // creating with unix timestamp (in seconds)
  18315. moment.unix = function (input) {
  18316. return moment(input * 1000);
  18317. };
  18318. // duration
  18319. moment.duration = function (input, key) {
  18320. var duration = input,
  18321. // matching against regexp is expensive, do it on demand
  18322. match = null,
  18323. sign,
  18324. ret,
  18325. parseIso;
  18326. if (moment.isDuration(input)) {
  18327. duration = {
  18328. ms: input._milliseconds,
  18329. d: input._days,
  18330. M: input._months
  18331. };
  18332. } else if (typeof input === 'number') {
  18333. duration = {};
  18334. if (key) {
  18335. duration[key] = input;
  18336. } else {
  18337. duration.milliseconds = input;
  18338. }
  18339. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18340. sign = (match[1] === "-") ? -1 : 1;
  18341. duration = {
  18342. y: 0,
  18343. d: toInt(match[DATE]) * sign,
  18344. h: toInt(match[HOUR]) * sign,
  18345. m: toInt(match[MINUTE]) * sign,
  18346. s: toInt(match[SECOND]) * sign,
  18347. ms: toInt(match[MILLISECOND]) * sign
  18348. };
  18349. } else if (!!(match = isoDurationRegex.exec(input))) {
  18350. sign = (match[1] === "-") ? -1 : 1;
  18351. parseIso = function (inp) {
  18352. // We'd normally use ~~inp for this, but unfortunately it also
  18353. // converts floats to ints.
  18354. // inp may be undefined, so careful calling replace on it.
  18355. var res = inp && parseFloat(inp.replace(',', '.'));
  18356. // apply sign while we're at it
  18357. return (isNaN(res) ? 0 : res) * sign;
  18358. };
  18359. duration = {
  18360. y: parseIso(match[2]),
  18361. M: parseIso(match[3]),
  18362. d: parseIso(match[4]),
  18363. h: parseIso(match[5]),
  18364. m: parseIso(match[6]),
  18365. s: parseIso(match[7]),
  18366. w: parseIso(match[8])
  18367. };
  18368. }
  18369. ret = new Duration(duration);
  18370. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18371. ret._lang = input._lang;
  18372. }
  18373. return ret;
  18374. };
  18375. // version number
  18376. moment.version = VERSION;
  18377. // default format
  18378. moment.defaultFormat = isoFormat;
  18379. // Plugins that add properties should also add the key here (null value),
  18380. // so we can properly clone ourselves.
  18381. moment.momentProperties = momentProperties;
  18382. // This function will be called whenever a moment is mutated.
  18383. // It is intended to keep the offset in sync with the timezone.
  18384. moment.updateOffset = function () {};
  18385. // This function will load languages and then set the global language. If
  18386. // no arguments are passed in, it will simply return the current global
  18387. // language key.
  18388. moment.lang = function (key, values) {
  18389. var r;
  18390. if (!key) {
  18391. return moment.fn._lang._abbr;
  18392. }
  18393. if (values) {
  18394. loadLang(normalizeLanguage(key), values);
  18395. } else if (values === null) {
  18396. unloadLang(key);
  18397. key = 'en';
  18398. } else if (!languages[key]) {
  18399. getLangDefinition(key);
  18400. }
  18401. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18402. return r._abbr;
  18403. };
  18404. // returns language data
  18405. moment.langData = function (key) {
  18406. if (key && key._lang && key._lang._abbr) {
  18407. key = key._lang._abbr;
  18408. }
  18409. return getLangDefinition(key);
  18410. };
  18411. // compare moment object
  18412. moment.isMoment = function (obj) {
  18413. return obj instanceof Moment ||
  18414. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18415. };
  18416. // for typechecking Duration objects
  18417. moment.isDuration = function (obj) {
  18418. return obj instanceof Duration;
  18419. };
  18420. for (i = lists.length - 1; i >= 0; --i) {
  18421. makeList(lists[i]);
  18422. }
  18423. moment.normalizeUnits = function (units) {
  18424. return normalizeUnits(units);
  18425. };
  18426. moment.invalid = function (flags) {
  18427. var m = moment.utc(NaN);
  18428. if (flags != null) {
  18429. extend(m._pf, flags);
  18430. }
  18431. else {
  18432. m._pf.userInvalidated = true;
  18433. }
  18434. return m;
  18435. };
  18436. moment.parseZone = function () {
  18437. return moment.apply(null, arguments).parseZone();
  18438. };
  18439. moment.parseTwoDigitYear = function (input) {
  18440. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  18441. };
  18442. /************************************
  18443. Moment Prototype
  18444. ************************************/
  18445. extend(moment.fn = Moment.prototype, {
  18446. clone : function () {
  18447. return moment(this);
  18448. },
  18449. valueOf : function () {
  18450. return +this._d + ((this._offset || 0) * 60000);
  18451. },
  18452. unix : function () {
  18453. return Math.floor(+this / 1000);
  18454. },
  18455. toString : function () {
  18456. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18457. },
  18458. toDate : function () {
  18459. return this._offset ? new Date(+this) : this._d;
  18460. },
  18461. toISOString : function () {
  18462. var m = moment(this).utc();
  18463. if (0 < m.year() && m.year() <= 9999) {
  18464. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18465. } else {
  18466. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18467. }
  18468. },
  18469. toArray : function () {
  18470. var m = this;
  18471. return [
  18472. m.year(),
  18473. m.month(),
  18474. m.date(),
  18475. m.hours(),
  18476. m.minutes(),
  18477. m.seconds(),
  18478. m.milliseconds()
  18479. ];
  18480. },
  18481. isValid : function () {
  18482. return isValid(this);
  18483. },
  18484. isDSTShifted : function () {
  18485. if (this._a) {
  18486. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18487. }
  18488. return false;
  18489. },
  18490. parsingFlags : function () {
  18491. return extend({}, this._pf);
  18492. },
  18493. invalidAt: function () {
  18494. return this._pf.overflow;
  18495. },
  18496. utc : function () {
  18497. return this.zone(0);
  18498. },
  18499. local : function () {
  18500. this.zone(0);
  18501. this._isUTC = false;
  18502. return this;
  18503. },
  18504. format : function (inputString) {
  18505. var output = formatMoment(this, inputString || moment.defaultFormat);
  18506. return this.lang().postformat(output);
  18507. },
  18508. add : function (input, val) {
  18509. var dur;
  18510. // switch args to support add('s', 1) and add(1, 's')
  18511. if (typeof input === 'string') {
  18512. dur = moment.duration(+val, input);
  18513. } else {
  18514. dur = moment.duration(input, val);
  18515. }
  18516. addOrSubtractDurationFromMoment(this, dur, 1);
  18517. return this;
  18518. },
  18519. subtract : function (input, val) {
  18520. var dur;
  18521. // switch args to support subtract('s', 1) and subtract(1, 's')
  18522. if (typeof input === 'string') {
  18523. dur = moment.duration(+val, input);
  18524. } else {
  18525. dur = moment.duration(input, val);
  18526. }
  18527. addOrSubtractDurationFromMoment(this, dur, -1);
  18528. return this;
  18529. },
  18530. diff : function (input, units, asFloat) {
  18531. var that = makeAs(input, this),
  18532. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18533. diff, output;
  18534. units = normalizeUnits(units);
  18535. if (units === 'year' || units === 'month') {
  18536. // average number of days in the months in the given dates
  18537. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18538. // difference in months
  18539. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18540. // adjust by taking difference in days, average number of days
  18541. // and dst in the given months.
  18542. output += ((this - moment(this).startOf('month')) -
  18543. (that - moment(that).startOf('month'))) / diff;
  18544. // same as above but with zones, to negate all dst
  18545. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18546. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18547. if (units === 'year') {
  18548. output = output / 12;
  18549. }
  18550. } else {
  18551. diff = (this - that);
  18552. output = units === 'second' ? diff / 1e3 : // 1000
  18553. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18554. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18555. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18556. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18557. diff;
  18558. }
  18559. return asFloat ? output : absRound(output);
  18560. },
  18561. from : function (time, withoutSuffix) {
  18562. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18563. },
  18564. fromNow : function (withoutSuffix) {
  18565. return this.from(moment(), withoutSuffix);
  18566. },
  18567. calendar : function () {
  18568. // We want to compare the start of today, vs this.
  18569. // Getting start-of-today depends on whether we're zone'd or not.
  18570. var sod = makeAs(moment(), this).startOf('day'),
  18571. diff = this.diff(sod, 'days', true),
  18572. format = diff < -6 ? 'sameElse' :
  18573. diff < -1 ? 'lastWeek' :
  18574. diff < 0 ? 'lastDay' :
  18575. diff < 1 ? 'sameDay' :
  18576. diff < 2 ? 'nextDay' :
  18577. diff < 7 ? 'nextWeek' : 'sameElse';
  18578. return this.format(this.lang().calendar(format, this));
  18579. },
  18580. isLeapYear : function () {
  18581. return isLeapYear(this.year());
  18582. },
  18583. isDST : function () {
  18584. return (this.zone() < this.clone().month(0).zone() ||
  18585. this.zone() < this.clone().month(5).zone());
  18586. },
  18587. day : function (input) {
  18588. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18589. if (input != null) {
  18590. input = parseWeekday(input, this.lang());
  18591. return this.add({ d : input - day });
  18592. } else {
  18593. return day;
  18594. }
  18595. },
  18596. month : makeAccessor('Month', true),
  18597. startOf: function (units) {
  18598. units = normalizeUnits(units);
  18599. // the following switch intentionally omits break keywords
  18600. // to utilize falling through the cases.
  18601. switch (units) {
  18602. case 'year':
  18603. this.month(0);
  18604. /* falls through */
  18605. case 'quarter':
  18606. case 'month':
  18607. this.date(1);
  18608. /* falls through */
  18609. case 'week':
  18610. case 'isoWeek':
  18611. case 'day':
  18612. this.hours(0);
  18613. /* falls through */
  18614. case 'hour':
  18615. this.minutes(0);
  18616. /* falls through */
  18617. case 'minute':
  18618. this.seconds(0);
  18619. /* falls through */
  18620. case 'second':
  18621. this.milliseconds(0);
  18622. /* falls through */
  18623. }
  18624. // weeks are a special case
  18625. if (units === 'week') {
  18626. this.weekday(0);
  18627. } else if (units === 'isoWeek') {
  18628. this.isoWeekday(1);
  18629. }
  18630. // quarters are also special
  18631. if (units === 'quarter') {
  18632. this.month(Math.floor(this.month() / 3) * 3);
  18633. }
  18634. return this;
  18635. },
  18636. endOf: function (units) {
  18637. units = normalizeUnits(units);
  18638. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18639. },
  18640. isAfter: function (input, units) {
  18641. units = typeof units !== 'undefined' ? units : 'millisecond';
  18642. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18643. },
  18644. isBefore: function (input, units) {
  18645. units = typeof units !== 'undefined' ? units : 'millisecond';
  18646. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18647. },
  18648. isSame: function (input, units) {
  18649. units = units || 'ms';
  18650. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18651. },
  18652. min: function (other) {
  18653. other = moment.apply(null, arguments);
  18654. return other < this ? this : other;
  18655. },
  18656. max: function (other) {
  18657. other = moment.apply(null, arguments);
  18658. return other > this ? this : other;
  18659. },
  18660. // keepTime = true means only change the timezone, without affecting
  18661. // the local hour. So 5:31:26 +0300 --[zone(2, true)]--> 5:31:26 +0200
  18662. // It is possible that 5:31:26 doesn't exist int zone +0200, so we
  18663. // adjust the time as needed, to be valid.
  18664. //
  18665. // Keeping the time actually adds/subtracts (one hour)
  18666. // from the actual represented time. That is why we call updateOffset
  18667. // a second time. In case it wants us to change the offset again
  18668. // _changeInProgress == true case, then we have to adjust, because
  18669. // there is no such time in the given timezone.
  18670. zone : function (input, keepTime) {
  18671. var offset = this._offset || 0;
  18672. if (input != null) {
  18673. if (typeof input === "string") {
  18674. input = timezoneMinutesFromString(input);
  18675. }
  18676. if (Math.abs(input) < 16) {
  18677. input = input * 60;
  18678. }
  18679. this._offset = input;
  18680. this._isUTC = true;
  18681. if (offset !== input) {
  18682. if (!keepTime || this._changeInProgress) {
  18683. addOrSubtractDurationFromMoment(this,
  18684. moment.duration(offset - input, 'm'), 1, false);
  18685. } else if (!this._changeInProgress) {
  18686. this._changeInProgress = true;
  18687. moment.updateOffset(this, true);
  18688. this._changeInProgress = null;
  18689. }
  18690. }
  18691. } else {
  18692. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18693. }
  18694. return this;
  18695. },
  18696. zoneAbbr : function () {
  18697. return this._isUTC ? "UTC" : "";
  18698. },
  18699. zoneName : function () {
  18700. return this._isUTC ? "Coordinated Universal Time" : "";
  18701. },
  18702. parseZone : function () {
  18703. if (this._tzm) {
  18704. this.zone(this._tzm);
  18705. } else if (typeof this._i === 'string') {
  18706. this.zone(this._i);
  18707. }
  18708. return this;
  18709. },
  18710. hasAlignedHourOffset : function (input) {
  18711. if (!input) {
  18712. input = 0;
  18713. }
  18714. else {
  18715. input = moment(input).zone();
  18716. }
  18717. return (this.zone() - input) % 60 === 0;
  18718. },
  18719. daysInMonth : function () {
  18720. return daysInMonth(this.year(), this.month());
  18721. },
  18722. dayOfYear : function (input) {
  18723. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  18724. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  18725. },
  18726. quarter : function (input) {
  18727. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  18728. },
  18729. weekYear : function (input) {
  18730. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  18731. return input == null ? year : this.add("y", (input - year));
  18732. },
  18733. isoWeekYear : function (input) {
  18734. var year = weekOfYear(this, 1, 4).year;
  18735. return input == null ? year : this.add("y", (input - year));
  18736. },
  18737. week : function (input) {
  18738. var week = this.lang().week(this);
  18739. return input == null ? week : this.add("d", (input - week) * 7);
  18740. },
  18741. isoWeek : function (input) {
  18742. var week = weekOfYear(this, 1, 4).week;
  18743. return input == null ? week : this.add("d", (input - week) * 7);
  18744. },
  18745. weekday : function (input) {
  18746. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  18747. return input == null ? weekday : this.add("d", input - weekday);
  18748. },
  18749. isoWeekday : function (input) {
  18750. // behaves the same as moment#day except
  18751. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  18752. // as a setter, sunday should belong to the previous week.
  18753. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  18754. },
  18755. isoWeeksInYear : function () {
  18756. return weeksInYear(this.year(), 1, 4);
  18757. },
  18758. weeksInYear : function () {
  18759. var weekInfo = this._lang._week;
  18760. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  18761. },
  18762. get : function (units) {
  18763. units = normalizeUnits(units);
  18764. return this[units]();
  18765. },
  18766. set : function (units, value) {
  18767. units = normalizeUnits(units);
  18768. if (typeof this[units] === 'function') {
  18769. this[units](value);
  18770. }
  18771. return this;
  18772. },
  18773. // If passed a language key, it will set the language for this
  18774. // instance. Otherwise, it will return the language configuration
  18775. // variables for this instance.
  18776. lang : function (key) {
  18777. if (key === undefined) {
  18778. return this._lang;
  18779. } else {
  18780. this._lang = getLangDefinition(key);
  18781. return this;
  18782. }
  18783. }
  18784. });
  18785. function rawMonthSetter(mom, value) {
  18786. var dayOfMonth;
  18787. // TODO: Move this out of here!
  18788. if (typeof value === 'string') {
  18789. value = mom.lang().monthsParse(value);
  18790. // TODO: Another silent failure?
  18791. if (typeof value !== 'number') {
  18792. return mom;
  18793. }
  18794. }
  18795. dayOfMonth = Math.min(mom.date(),
  18796. daysInMonth(mom.year(), value));
  18797. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  18798. return mom;
  18799. }
  18800. function rawGetter(mom, unit) {
  18801. return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
  18802. }
  18803. function rawSetter(mom, unit, value) {
  18804. if (unit === 'Month') {
  18805. return rawMonthSetter(mom, value);
  18806. } else {
  18807. return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  18808. }
  18809. }
  18810. function makeAccessor(unit, keepTime) {
  18811. return function (value) {
  18812. if (value != null) {
  18813. rawSetter(this, unit, value);
  18814. moment.updateOffset(this, keepTime);
  18815. return this;
  18816. } else {
  18817. return rawGetter(this, unit);
  18818. }
  18819. };
  18820. }
  18821. moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
  18822. moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
  18823. moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
  18824. // Setting the hour should keep the time, because the user explicitly
  18825. // specified which hour he wants. So trying to maintain the same hour (in
  18826. // a new timezone) makes sense. Adding/subtracting hours does not follow
  18827. // this rule.
  18828. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
  18829. // moment.fn.month is defined separately
  18830. moment.fn.date = makeAccessor('Date', true);
  18831. moment.fn.dates = deprecate("dates accessor is deprecated. Use date instead.", makeAccessor('Date', true));
  18832. moment.fn.year = makeAccessor('FullYear', true);
  18833. moment.fn.years = deprecate("years accessor is deprecated. Use year instead.", makeAccessor('FullYear', true));
  18834. // add plural methods
  18835. moment.fn.days = moment.fn.day;
  18836. moment.fn.months = moment.fn.month;
  18837. moment.fn.weeks = moment.fn.week;
  18838. moment.fn.isoWeeks = moment.fn.isoWeek;
  18839. moment.fn.quarters = moment.fn.quarter;
  18840. // add aliased format methods
  18841. moment.fn.toJSON = moment.fn.toISOString;
  18842. /************************************
  18843. Duration Prototype
  18844. ************************************/
  18845. extend(moment.duration.fn = Duration.prototype, {
  18846. _bubble : function () {
  18847. var milliseconds = this._milliseconds,
  18848. days = this._days,
  18849. months = this._months,
  18850. data = this._data,
  18851. seconds, minutes, hours, years;
  18852. // The following code bubbles up values, see the tests for
  18853. // examples of what that means.
  18854. data.milliseconds = milliseconds % 1000;
  18855. seconds = absRound(milliseconds / 1000);
  18856. data.seconds = seconds % 60;
  18857. minutes = absRound(seconds / 60);
  18858. data.minutes = minutes % 60;
  18859. hours = absRound(minutes / 60);
  18860. data.hours = hours % 24;
  18861. days += absRound(hours / 24);
  18862. data.days = days % 30;
  18863. months += absRound(days / 30);
  18864. data.months = months % 12;
  18865. years = absRound(months / 12);
  18866. data.years = years;
  18867. },
  18868. weeks : function () {
  18869. return absRound(this.days() / 7);
  18870. },
  18871. valueOf : function () {
  18872. return this._milliseconds +
  18873. this._days * 864e5 +
  18874. (this._months % 12) * 2592e6 +
  18875. toInt(this._months / 12) * 31536e6;
  18876. },
  18877. humanize : function (withSuffix) {
  18878. var difference = +this,
  18879. output = relativeTime(difference, !withSuffix, this.lang());
  18880. if (withSuffix) {
  18881. output = this.lang().pastFuture(difference, output);
  18882. }
  18883. return this.lang().postformat(output);
  18884. },
  18885. add : function (input, val) {
  18886. // supports only 2.0-style add(1, 's') or add(moment)
  18887. var dur = moment.duration(input, val);
  18888. this._milliseconds += dur._milliseconds;
  18889. this._days += dur._days;
  18890. this._months += dur._months;
  18891. this._bubble();
  18892. return this;
  18893. },
  18894. subtract : function (input, val) {
  18895. var dur = moment.duration(input, val);
  18896. this._milliseconds -= dur._milliseconds;
  18897. this._days -= dur._days;
  18898. this._months -= dur._months;
  18899. this._bubble();
  18900. return this;
  18901. },
  18902. get : function (units) {
  18903. units = normalizeUnits(units);
  18904. return this[units.toLowerCase() + 's']();
  18905. },
  18906. as : function (units) {
  18907. units = normalizeUnits(units);
  18908. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  18909. },
  18910. lang : moment.fn.lang,
  18911. toIsoString : function () {
  18912. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  18913. var years = Math.abs(this.years()),
  18914. months = Math.abs(this.months()),
  18915. days = Math.abs(this.days()),
  18916. hours = Math.abs(this.hours()),
  18917. minutes = Math.abs(this.minutes()),
  18918. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  18919. if (!this.asSeconds()) {
  18920. // this is the same as C#'s (Noda) and python (isodate)...
  18921. // but not other JS (goog.date)
  18922. return 'P0D';
  18923. }
  18924. return (this.asSeconds() < 0 ? '-' : '') +
  18925. 'P' +
  18926. (years ? years + 'Y' : '') +
  18927. (months ? months + 'M' : '') +
  18928. (days ? days + 'D' : '') +
  18929. ((hours || minutes || seconds) ? 'T' : '') +
  18930. (hours ? hours + 'H' : '') +
  18931. (minutes ? minutes + 'M' : '') +
  18932. (seconds ? seconds + 'S' : '');
  18933. }
  18934. });
  18935. function makeDurationGetter(name) {
  18936. moment.duration.fn[name] = function () {
  18937. return this._data[name];
  18938. };
  18939. }
  18940. function makeDurationAsGetter(name, factor) {
  18941. moment.duration.fn['as' + name] = function () {
  18942. return +this / factor;
  18943. };
  18944. }
  18945. for (i in unitMillisecondFactors) {
  18946. if (unitMillisecondFactors.hasOwnProperty(i)) {
  18947. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  18948. makeDurationGetter(i.toLowerCase());
  18949. }
  18950. }
  18951. makeDurationAsGetter('Weeks', 6048e5);
  18952. moment.duration.fn.asMonths = function () {
  18953. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  18954. };
  18955. /************************************
  18956. Default Lang
  18957. ************************************/
  18958. // Set default language, other languages will inherit from English.
  18959. moment.lang('en', {
  18960. ordinal : function (number) {
  18961. var b = number % 10,
  18962. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  18963. (b === 1) ? 'st' :
  18964. (b === 2) ? 'nd' :
  18965. (b === 3) ? 'rd' : 'th';
  18966. return number + output;
  18967. }
  18968. });
  18969. /* EMBED_LANGUAGES */
  18970. /************************************
  18971. Exposing Moment
  18972. ************************************/
  18973. function makeGlobal(shouldDeprecate) {
  18974. /*global ender:false */
  18975. if (typeof ender !== 'undefined') {
  18976. return;
  18977. }
  18978. oldGlobalMoment = globalScope.moment;
  18979. if (shouldDeprecate) {
  18980. globalScope.moment = deprecate(
  18981. "Accessing Moment through the global scope is " +
  18982. "deprecated, and will be removed in an upcoming " +
  18983. "release.",
  18984. moment);
  18985. } else {
  18986. globalScope.moment = moment;
  18987. }
  18988. }
  18989. // CommonJS module is defined
  18990. if (hasModule) {
  18991. module.exports = moment;
  18992. } else if (typeof define === "function" && define.amd) {
  18993. define("moment", function (require, exports, module) {
  18994. if (module.config && module.config() && module.config().noGlobal === true) {
  18995. // release the global variable
  18996. globalScope.moment = oldGlobalMoment;
  18997. }
  18998. return moment;
  18999. });
  19000. makeGlobal(true);
  19001. } else {
  19002. makeGlobal();
  19003. }
  19004. }).call(this);
  19005. },{}],5:[function(require,module,exports){
  19006. /**
  19007. * Copyright 2012 Craig Campbell
  19008. *
  19009. * Licensed under the Apache License, Version 2.0 (the "License");
  19010. * you may not use this file except in compliance with the License.
  19011. * You may obtain a copy of the License at
  19012. *
  19013. * http://www.apache.org/licenses/LICENSE-2.0
  19014. *
  19015. * Unless required by applicable law or agreed to in writing, software
  19016. * distributed under the License is distributed on an "AS IS" BASIS,
  19017. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19018. * See the License for the specific language governing permissions and
  19019. * limitations under the License.
  19020. *
  19021. * Mousetrap is a simple keyboard shortcut library for Javascript with
  19022. * no external dependencies
  19023. *
  19024. * @version 1.1.2
  19025. * @url craig.is/killing/mice
  19026. */
  19027. /**
  19028. * mapping of special keycodes to their corresponding keys
  19029. *
  19030. * everything in this dictionary cannot use keypress events
  19031. * so it has to be here to map to the correct keycodes for
  19032. * keyup/keydown events
  19033. *
  19034. * @type {Object}
  19035. */
  19036. var _MAP = {
  19037. 8: 'backspace',
  19038. 9: 'tab',
  19039. 13: 'enter',
  19040. 16: 'shift',
  19041. 17: 'ctrl',
  19042. 18: 'alt',
  19043. 20: 'capslock',
  19044. 27: 'esc',
  19045. 32: 'space',
  19046. 33: 'pageup',
  19047. 34: 'pagedown',
  19048. 35: 'end',
  19049. 36: 'home',
  19050. 37: 'left',
  19051. 38: 'up',
  19052. 39: 'right',
  19053. 40: 'down',
  19054. 45: 'ins',
  19055. 46: 'del',
  19056. 91: 'meta',
  19057. 93: 'meta',
  19058. 224: 'meta'
  19059. },
  19060. /**
  19061. * mapping for special characters so they can support
  19062. *
  19063. * this dictionary is only used incase you want to bind a
  19064. * keyup or keydown event to one of these keys
  19065. *
  19066. * @type {Object}
  19067. */
  19068. _KEYCODE_MAP = {
  19069. 106: '*',
  19070. 107: '+',
  19071. 109: '-',
  19072. 110: '.',
  19073. 111 : '/',
  19074. 186: ';',
  19075. 187: '=',
  19076. 188: ',',
  19077. 189: '-',
  19078. 190: '.',
  19079. 191: '/',
  19080. 192: '`',
  19081. 219: '[',
  19082. 220: '\\',
  19083. 221: ']',
  19084. 222: '\''
  19085. },
  19086. /**
  19087. * this is a mapping of keys that require shift on a US keypad
  19088. * back to the non shift equivelents
  19089. *
  19090. * this is so you can use keyup events with these keys
  19091. *
  19092. * note that this will only work reliably on US keyboards
  19093. *
  19094. * @type {Object}
  19095. */
  19096. _SHIFT_MAP = {
  19097. '~': '`',
  19098. '!': '1',
  19099. '@': '2',
  19100. '#': '3',
  19101. '$': '4',
  19102. '%': '5',
  19103. '^': '6',
  19104. '&': '7',
  19105. '*': '8',
  19106. '(': '9',
  19107. ')': '0',
  19108. '_': '-',
  19109. '+': '=',
  19110. ':': ';',
  19111. '\"': '\'',
  19112. '<': ',',
  19113. '>': '.',
  19114. '?': '/',
  19115. '|': '\\'
  19116. },
  19117. /**
  19118. * this is a list of special strings you can use to map
  19119. * to modifier keys when you specify your keyboard shortcuts
  19120. *
  19121. * @type {Object}
  19122. */
  19123. _SPECIAL_ALIASES = {
  19124. 'option': 'alt',
  19125. 'command': 'meta',
  19126. 'return': 'enter',
  19127. 'escape': 'esc'
  19128. },
  19129. /**
  19130. * variable to store the flipped version of _MAP from above
  19131. * needed to check if we should use keypress or not when no action
  19132. * is specified
  19133. *
  19134. * @type {Object|undefined}
  19135. */
  19136. _REVERSE_MAP,
  19137. /**
  19138. * a list of all the callbacks setup via Mousetrap.bind()
  19139. *
  19140. * @type {Object}
  19141. */
  19142. _callbacks = {},
  19143. /**
  19144. * direct map of string combinations to callbacks used for trigger()
  19145. *
  19146. * @type {Object}
  19147. */
  19148. _direct_map = {},
  19149. /**
  19150. * keeps track of what level each sequence is at since multiple
  19151. * sequences can start out with the same sequence
  19152. *
  19153. * @type {Object}
  19154. */
  19155. _sequence_levels = {},
  19156. /**
  19157. * variable to store the setTimeout call
  19158. *
  19159. * @type {null|number}
  19160. */
  19161. _reset_timer,
  19162. /**
  19163. * temporary state where we will ignore the next keyup
  19164. *
  19165. * @type {boolean|string}
  19166. */
  19167. _ignore_next_keyup = false,
  19168. /**
  19169. * are we currently inside of a sequence?
  19170. * type of action ("keyup" or "keydown" or "keypress") or false
  19171. *
  19172. * @type {boolean|string}
  19173. */
  19174. _inside_sequence = false;
  19175. /**
  19176. * loop through the f keys, f1 to f19 and add them to the map
  19177. * programatically
  19178. */
  19179. for (var i = 1; i < 20; ++i) {
  19180. _MAP[111 + i] = 'f' + i;
  19181. }
  19182. /**
  19183. * loop through to map numbers on the numeric keypad
  19184. */
  19185. for (i = 0; i <= 9; ++i) {
  19186. _MAP[i + 96] = i;
  19187. }
  19188. /**
  19189. * cross browser add event method
  19190. *
  19191. * @param {Element|HTMLDocument} object
  19192. * @param {string} type
  19193. * @param {Function} callback
  19194. * @returns void
  19195. */
  19196. function _addEvent(object, type, callback) {
  19197. if (object.addEventListener) {
  19198. return object.addEventListener(type, callback, false);
  19199. }
  19200. object.attachEvent('on' + type, callback);
  19201. }
  19202. /**
  19203. * takes the event and returns the key character
  19204. *
  19205. * @param {Event} e
  19206. * @return {string}
  19207. */
  19208. function _characterFromEvent(e) {
  19209. // for keypress events we should return the character as is
  19210. if (e.type == 'keypress') {
  19211. return String.fromCharCode(e.which);
  19212. }
  19213. // for non keypress events the special maps are needed
  19214. if (_MAP[e.which]) {
  19215. return _MAP[e.which];
  19216. }
  19217. if (_KEYCODE_MAP[e.which]) {
  19218. return _KEYCODE_MAP[e.which];
  19219. }
  19220. // if it is not in the special map
  19221. return String.fromCharCode(e.which).toLowerCase();
  19222. }
  19223. /**
  19224. * should we stop this event before firing off callbacks
  19225. *
  19226. * @param {Event} e
  19227. * @return {boolean}
  19228. */
  19229. function _stop(e) {
  19230. var element = e.target || e.srcElement,
  19231. tag_name = element.tagName;
  19232. // if the element has the class "mousetrap" then no need to stop
  19233. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19234. return false;
  19235. }
  19236. // stop for input, select, and textarea
  19237. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19238. }
  19239. /**
  19240. * checks if two arrays are equal
  19241. *
  19242. * @param {Array} modifiers1
  19243. * @param {Array} modifiers2
  19244. * @returns {boolean}
  19245. */
  19246. function _modifiersMatch(modifiers1, modifiers2) {
  19247. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19248. }
  19249. /**
  19250. * resets all sequence counters except for the ones passed in
  19251. *
  19252. * @param {Object} do_not_reset
  19253. * @returns void
  19254. */
  19255. function _resetSequences(do_not_reset) {
  19256. do_not_reset = do_not_reset || {};
  19257. var active_sequences = false,
  19258. key;
  19259. for (key in _sequence_levels) {
  19260. if (do_not_reset[key]) {
  19261. active_sequences = true;
  19262. continue;
  19263. }
  19264. _sequence_levels[key] = 0;
  19265. }
  19266. if (!active_sequences) {
  19267. _inside_sequence = false;
  19268. }
  19269. }
  19270. /**
  19271. * finds all callbacks that match based on the keycode, modifiers,
  19272. * and action
  19273. *
  19274. * @param {string} character
  19275. * @param {Array} modifiers
  19276. * @param {string} action
  19277. * @param {boolean=} remove - should we remove any matches
  19278. * @param {string=} combination
  19279. * @returns {Array}
  19280. */
  19281. function _getMatches(character, modifiers, action, remove, combination) {
  19282. var i,
  19283. callback,
  19284. matches = [];
  19285. // if there are no events related to this keycode
  19286. if (!_callbacks[character]) {
  19287. return [];
  19288. }
  19289. // if a modifier key is coming up on its own we should allow it
  19290. if (action == 'keyup' && _isModifier(character)) {
  19291. modifiers = [character];
  19292. }
  19293. // loop through all callbacks for the key that was pressed
  19294. // and see if any of them match
  19295. for (i = 0; i < _callbacks[character].length; ++i) {
  19296. callback = _callbacks[character][i];
  19297. // if this is a sequence but it is not at the right level
  19298. // then move onto the next match
  19299. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19300. continue;
  19301. }
  19302. // if the action we are looking for doesn't match the action we got
  19303. // then we should keep going
  19304. if (action != callback.action) {
  19305. continue;
  19306. }
  19307. // if this is a keypress event that means that we need to only
  19308. // look at the character, otherwise check the modifiers as
  19309. // well
  19310. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19311. // remove is used so if you change your mind and call bind a
  19312. // second time with a new function the first one is overwritten
  19313. if (remove && callback.combo == combination) {
  19314. _callbacks[character].splice(i, 1);
  19315. }
  19316. matches.push(callback);
  19317. }
  19318. }
  19319. return matches;
  19320. }
  19321. /**
  19322. * takes a key event and figures out what the modifiers are
  19323. *
  19324. * @param {Event} e
  19325. * @returns {Array}
  19326. */
  19327. function _eventModifiers(e) {
  19328. var modifiers = [];
  19329. if (e.shiftKey) {
  19330. modifiers.push('shift');
  19331. }
  19332. if (e.altKey) {
  19333. modifiers.push('alt');
  19334. }
  19335. if (e.ctrlKey) {
  19336. modifiers.push('ctrl');
  19337. }
  19338. if (e.metaKey) {
  19339. modifiers.push('meta');
  19340. }
  19341. return modifiers;
  19342. }
  19343. /**
  19344. * actually calls the callback function
  19345. *
  19346. * if your callback function returns false this will use the jquery
  19347. * convention - prevent default and stop propogation on the event
  19348. *
  19349. * @param {Function} callback
  19350. * @param {Event} e
  19351. * @returns void
  19352. */
  19353. function _fireCallback(callback, e) {
  19354. if (callback(e) === false) {
  19355. if (e.preventDefault) {
  19356. e.preventDefault();
  19357. }
  19358. if (e.stopPropagation) {
  19359. e.stopPropagation();
  19360. }
  19361. e.returnValue = false;
  19362. e.cancelBubble = true;
  19363. }
  19364. }
  19365. /**
  19366. * handles a character key event
  19367. *
  19368. * @param {string} character
  19369. * @param {Event} e
  19370. * @returns void
  19371. */
  19372. function _handleCharacter(character, e) {
  19373. // if this event should not happen stop here
  19374. if (_stop(e)) {
  19375. return;
  19376. }
  19377. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19378. i,
  19379. do_not_reset = {},
  19380. processed_sequence_callback = false;
  19381. // loop through matching callbacks for this key event
  19382. for (i = 0; i < callbacks.length; ++i) {
  19383. // fire for all sequence callbacks
  19384. // this is because if for example you have multiple sequences
  19385. // bound such as "g i" and "g t" they both need to fire the
  19386. // callback for matching g cause otherwise you can only ever
  19387. // match the first one
  19388. if (callbacks[i].seq) {
  19389. processed_sequence_callback = true;
  19390. // keep a list of which sequences were matches for later
  19391. do_not_reset[callbacks[i].seq] = 1;
  19392. _fireCallback(callbacks[i].callback, e);
  19393. continue;
  19394. }
  19395. // if there were no sequence matches but we are still here
  19396. // that means this is a regular match so we should fire that
  19397. if (!processed_sequence_callback && !_inside_sequence) {
  19398. _fireCallback(callbacks[i].callback, e);
  19399. }
  19400. }
  19401. // if you are inside of a sequence and the key you are pressing
  19402. // is not a modifier key then we should reset all sequences
  19403. // that were not matched by this key event
  19404. if (e.type == _inside_sequence && !_isModifier(character)) {
  19405. _resetSequences(do_not_reset);
  19406. }
  19407. }
  19408. /**
  19409. * handles a keydown event
  19410. *
  19411. * @param {Event} e
  19412. * @returns void
  19413. */
  19414. function _handleKey(e) {
  19415. // normalize e.which for key events
  19416. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19417. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19418. var character = _characterFromEvent(e);
  19419. // no character found then stop
  19420. if (!character) {
  19421. return;
  19422. }
  19423. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19424. _ignore_next_keyup = false;
  19425. return;
  19426. }
  19427. _handleCharacter(character, e);
  19428. }
  19429. /**
  19430. * determines if the keycode specified is a modifier key or not
  19431. *
  19432. * @param {string} key
  19433. * @returns {boolean}
  19434. */
  19435. function _isModifier(key) {
  19436. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19437. }
  19438. /**
  19439. * called to set a 1 second timeout on the specified sequence
  19440. *
  19441. * this is so after each key press in the sequence you have 1 second
  19442. * to press the next key before you have to start over
  19443. *
  19444. * @returns void
  19445. */
  19446. function _resetSequenceTimer() {
  19447. clearTimeout(_reset_timer);
  19448. _reset_timer = setTimeout(_resetSequences, 1000);
  19449. }
  19450. /**
  19451. * reverses the map lookup so that we can look for specific keys
  19452. * to see what can and can't use keypress
  19453. *
  19454. * @return {Object}
  19455. */
  19456. function _getReverseMap() {
  19457. if (!_REVERSE_MAP) {
  19458. _REVERSE_MAP = {};
  19459. for (var key in _MAP) {
  19460. // pull out the numeric keypad from here cause keypress should
  19461. // be able to detect the keys from the character
  19462. if (key > 95 && key < 112) {
  19463. continue;
  19464. }
  19465. if (_MAP.hasOwnProperty(key)) {
  19466. _REVERSE_MAP[_MAP[key]] = key;
  19467. }
  19468. }
  19469. }
  19470. return _REVERSE_MAP;
  19471. }
  19472. /**
  19473. * picks the best action based on the key combination
  19474. *
  19475. * @param {string} key - character for key
  19476. * @param {Array} modifiers
  19477. * @param {string=} action passed in
  19478. */
  19479. function _pickBestAction(key, modifiers, action) {
  19480. // if no action was picked in we should try to pick the one
  19481. // that we think would work best for this key
  19482. if (!action) {
  19483. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19484. }
  19485. // modifier keys don't work as expected with keypress,
  19486. // switch to keydown
  19487. if (action == 'keypress' && modifiers.length) {
  19488. action = 'keydown';
  19489. }
  19490. return action;
  19491. }
  19492. /**
  19493. * binds a key sequence to an event
  19494. *
  19495. * @param {string} combo - combo specified in bind call
  19496. * @param {Array} keys
  19497. * @param {Function} callback
  19498. * @param {string=} action
  19499. * @returns void
  19500. */
  19501. function _bindSequence(combo, keys, callback, action) {
  19502. // start off by adding a sequence level record for this combination
  19503. // and setting the level to 0
  19504. _sequence_levels[combo] = 0;
  19505. // if there is no action pick the best one for the first key
  19506. // in the sequence
  19507. if (!action) {
  19508. action = _pickBestAction(keys[0], []);
  19509. }
  19510. /**
  19511. * callback to increase the sequence level for this sequence and reset
  19512. * all other sequences that were active
  19513. *
  19514. * @param {Event} e
  19515. * @returns void
  19516. */
  19517. var _increaseSequence = function(e) {
  19518. _inside_sequence = action;
  19519. ++_sequence_levels[combo];
  19520. _resetSequenceTimer();
  19521. },
  19522. /**
  19523. * wraps the specified callback inside of another function in order
  19524. * to reset all sequence counters as soon as this sequence is done
  19525. *
  19526. * @param {Event} e
  19527. * @returns void
  19528. */
  19529. _callbackAndReset = function(e) {
  19530. _fireCallback(callback, e);
  19531. // we should ignore the next key up if the action is key down
  19532. // or keypress. this is so if you finish a sequence and
  19533. // release the key the final key will not trigger a keyup
  19534. if (action !== 'keyup') {
  19535. _ignore_next_keyup = _characterFromEvent(e);
  19536. }
  19537. // weird race condition if a sequence ends with the key
  19538. // another sequence begins with
  19539. setTimeout(_resetSequences, 10);
  19540. },
  19541. i;
  19542. // loop through keys one at a time and bind the appropriate callback
  19543. // function. for any key leading up to the final one it should
  19544. // increase the sequence. after the final, it should reset all sequences
  19545. for (i = 0; i < keys.length; ++i) {
  19546. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19547. }
  19548. }
  19549. /**
  19550. * binds a single keyboard combination
  19551. *
  19552. * @param {string} combination
  19553. * @param {Function} callback
  19554. * @param {string=} action
  19555. * @param {string=} sequence_name - name of sequence if part of sequence
  19556. * @param {number=} level - what part of the sequence the command is
  19557. * @returns void
  19558. */
  19559. function _bindSingle(combination, callback, action, sequence_name, level) {
  19560. // make sure multiple spaces in a row become a single space
  19561. combination = combination.replace(/\s+/g, ' ');
  19562. var sequence = combination.split(' '),
  19563. i,
  19564. key,
  19565. keys,
  19566. modifiers = [];
  19567. // if this pattern is a sequence of keys then run through this method
  19568. // to reprocess each pattern one key at a time
  19569. if (sequence.length > 1) {
  19570. return _bindSequence(combination, sequence, callback, action);
  19571. }
  19572. // take the keys from this pattern and figure out what the actual
  19573. // pattern is all about
  19574. keys = combination === '+' ? ['+'] : combination.split('+');
  19575. for (i = 0; i < keys.length; ++i) {
  19576. key = keys[i];
  19577. // normalize key names
  19578. if (_SPECIAL_ALIASES[key]) {
  19579. key = _SPECIAL_ALIASES[key];
  19580. }
  19581. // if this is not a keypress event then we should
  19582. // be smart about using shift keys
  19583. // this will only work for US keyboards however
  19584. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19585. key = _SHIFT_MAP[key];
  19586. modifiers.push('shift');
  19587. }
  19588. // if this key is a modifier then add it to the list of modifiers
  19589. if (_isModifier(key)) {
  19590. modifiers.push(key);
  19591. }
  19592. }
  19593. // depending on what the key combination is
  19594. // we will try to pick the best event for it
  19595. action = _pickBestAction(key, modifiers, action);
  19596. // make sure to initialize array if this is the first time
  19597. // a callback is added for this key
  19598. if (!_callbacks[key]) {
  19599. _callbacks[key] = [];
  19600. }
  19601. // remove an existing match if there is one
  19602. _getMatches(key, modifiers, action, !sequence_name, combination);
  19603. // add this call back to the array
  19604. // if it is a sequence put it at the beginning
  19605. // if not put it at the end
  19606. //
  19607. // this is important because the way these are processed expects
  19608. // the sequence ones to come first
  19609. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19610. callback: callback,
  19611. modifiers: modifiers,
  19612. action: action,
  19613. seq: sequence_name,
  19614. level: level,
  19615. combo: combination
  19616. });
  19617. }
  19618. /**
  19619. * binds multiple combinations to the same callback
  19620. *
  19621. * @param {Array} combinations
  19622. * @param {Function} callback
  19623. * @param {string|undefined} action
  19624. * @returns void
  19625. */
  19626. function _bindMultiple(combinations, callback, action) {
  19627. for (var i = 0; i < combinations.length; ++i) {
  19628. _bindSingle(combinations[i], callback, action);
  19629. }
  19630. }
  19631. // start!
  19632. _addEvent(document, 'keypress', _handleKey);
  19633. _addEvent(document, 'keydown', _handleKey);
  19634. _addEvent(document, 'keyup', _handleKey);
  19635. var mousetrap = {
  19636. /**
  19637. * binds an event to mousetrap
  19638. *
  19639. * can be a single key, a combination of keys separated with +,
  19640. * a comma separated list of keys, an array of keys, or
  19641. * a sequence of keys separated by spaces
  19642. *
  19643. * be sure to list the modifier keys first to make sure that the
  19644. * correct key ends up getting bound (the last key in the pattern)
  19645. *
  19646. * @param {string|Array} keys
  19647. * @param {Function} callback
  19648. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19649. * @returns void
  19650. */
  19651. bind: function(keys, callback, action) {
  19652. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19653. _direct_map[keys + ':' + action] = callback;
  19654. return this;
  19655. },
  19656. /**
  19657. * unbinds an event to mousetrap
  19658. *
  19659. * the unbinding sets the callback function of the specified key combo
  19660. * to an empty function and deletes the corresponding key in the
  19661. * _direct_map dict.
  19662. *
  19663. * the keycombo+action has to be exactly the same as
  19664. * it was defined in the bind method
  19665. *
  19666. * TODO: actually remove this from the _callbacks dictionary instead
  19667. * of binding an empty function
  19668. *
  19669. * @param {string|Array} keys
  19670. * @param {string} action
  19671. * @returns void
  19672. */
  19673. unbind: function(keys, action) {
  19674. if (_direct_map[keys + ':' + action]) {
  19675. delete _direct_map[keys + ':' + action];
  19676. this.bind(keys, function() {}, action);
  19677. }
  19678. return this;
  19679. },
  19680. /**
  19681. * triggers an event that has already been bound
  19682. *
  19683. * @param {string} keys
  19684. * @param {string=} action
  19685. * @returns void
  19686. */
  19687. trigger: function(keys, action) {
  19688. _direct_map[keys + ':' + action]();
  19689. return this;
  19690. },
  19691. /**
  19692. * resets the library back to its initial state. this is useful
  19693. * if you want to clear out the current keyboard shortcuts and bind
  19694. * new ones - for example if you switch to another page
  19695. *
  19696. * @returns void
  19697. */
  19698. reset: function() {
  19699. _callbacks = {};
  19700. _direct_map = {};
  19701. return this;
  19702. }
  19703. };
  19704. module.exports = mousetrap;
  19705. },{}]},{},[1])
  19706. (1)
  19707. });