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.

22424 lines
663 KiB

10 years ago
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. <<<<<<< HEAD
  8. * @version 0.7.4-SNAPSHOT
  9. * @date 2014-04-23
  10. =======
  11. * @version 0.7.5-SNAPSHOT
  12. * @date 2014-04-22
  13. >>>>>>> fc75aed4cec56adbced08aa1804e23797703776f
  14. *
  15. * @license
  16. * Copyright (C) 2011-2014 Almende B.V, http://almende.com
  17. *
  18. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  19. * use this file except in compliance with the License. You may obtain a copy
  20. * of the License at
  21. *
  22. * http://www.apache.org/licenses/LICENSE-2.0
  23. *
  24. * Unless required by applicable law or agreed to in writing, software
  25. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  26. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  27. * License for the specific language governing permissions and limitations under
  28. * the License.
  29. */
  30. !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){
  31. /**
  32. * vis.js module imports
  33. */
  34. // Try to load dependencies from the global window object.
  35. // If not available there, load via require.
  36. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment');
  37. var Emitter = require('emitter-component');
  38. var Hammer;
  39. if (typeof window !== 'undefined') {
  40. // load hammer.js only when running in a browser (where window is available)
  41. Hammer = window['Hammer'] || require('hammerjs');
  42. }
  43. else {
  44. Hammer = function () {
  45. throw Error('hammer.js is only available in a browser, not in node.js.');
  46. }
  47. }
  48. var mousetrap;
  49. if (typeof window !== 'undefined') {
  50. // load mousetrap.js only when running in a browser (where window is available)
  51. mousetrap = window['mousetrap'] || require('mousetrap');
  52. }
  53. else {
  54. mousetrap = function () {
  55. throw Error('mouseTrap is only available in a browser, not in node.js.');
  56. }
  57. }
  58. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  59. // it here in that case.
  60. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  61. if(!Array.prototype.indexOf) {
  62. Array.prototype.indexOf = function(obj){
  63. for(var i = 0; i < this.length; i++){
  64. if(this[i] == obj){
  65. return i;
  66. }
  67. }
  68. return -1;
  69. };
  70. try {
  71. console.log("Warning: Ancient browser detected. Please update your browser");
  72. }
  73. catch (err) {
  74. }
  75. }
  76. // Internet Explorer 8 and older does not support Array.forEach, so we define
  77. // it here in that case.
  78. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  79. if (!Array.prototype.forEach) {
  80. Array.prototype.forEach = function(fn, scope) {
  81. for(var i = 0, len = this.length; i < len; ++i) {
  82. fn.call(scope || this, this[i], i, this);
  83. }
  84. }
  85. }
  86. // Internet Explorer 8 and older does not support Array.map, so we define it
  87. // here in that case.
  88. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  89. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  90. // Reference: http://es5.github.com/#x15.4.4.19
  91. if (!Array.prototype.map) {
  92. Array.prototype.map = function(callback, thisArg) {
  93. var T, A, k;
  94. if (this == null) {
  95. throw new TypeError(" this is null or not defined");
  96. }
  97. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  98. var O = Object(this);
  99. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  100. // 3. Let len be ToUint32(lenValue).
  101. var len = O.length >>> 0;
  102. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  103. // See: http://es5.github.com/#x9.11
  104. if (typeof callback !== "function") {
  105. throw new TypeError(callback + " is not a function");
  106. }
  107. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  108. if (thisArg) {
  109. T = thisArg;
  110. }
  111. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  112. // the standard built-in constructor with that name and len is the value of len.
  113. A = new Array(len);
  114. // 7. Let k be 0
  115. k = 0;
  116. // 8. Repeat, while k < len
  117. while(k < len) {
  118. var kValue, mappedValue;
  119. // a. Let Pk be ToString(k).
  120. // This is implicit for LHS operands of the in operator
  121. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  122. // This step can be combined with c
  123. // c. If kPresent is true, then
  124. if (k in O) {
  125. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  126. kValue = O[ k ];
  127. // ii. Let mappedValue be the result of calling the Call internal method of callback
  128. // with T as the this value and argument list containing kValue, k, and O.
  129. mappedValue = callback.call(T, kValue, k, O);
  130. // iii. Call the DefineOwnProperty internal method of A with arguments
  131. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  132. // and false.
  133. // In browsers that support Object.defineProperty, use the following:
  134. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  135. // For best browser support, use the following:
  136. A[ k ] = mappedValue;
  137. }
  138. // d. Increase k by 1.
  139. k++;
  140. }
  141. // 9. return A
  142. return A;
  143. };
  144. }
  145. // Internet Explorer 8 and older does not support Array.filter, so we define it
  146. // here in that case.
  147. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  148. if (!Array.prototype.filter) {
  149. Array.prototype.filter = function(fun /*, thisp */) {
  150. "use strict";
  151. if (this == null) {
  152. throw new TypeError();
  153. }
  154. var t = Object(this);
  155. var len = t.length >>> 0;
  156. if (typeof fun != "function") {
  157. throw new TypeError();
  158. }
  159. var res = [];
  160. var thisp = arguments[1];
  161. for (var i = 0; i < len; i++) {
  162. if (i in t) {
  163. var val = t[i]; // in case fun mutates this
  164. if (fun.call(thisp, val, i, t))
  165. res.push(val);
  166. }
  167. }
  168. return res;
  169. };
  170. }
  171. // Internet Explorer 8 and older does not support Object.keys, so we define it
  172. // here in that case.
  173. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  174. if (!Object.keys) {
  175. Object.keys = (function () {
  176. var hasOwnProperty = Object.prototype.hasOwnProperty,
  177. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  178. dontEnums = [
  179. 'toString',
  180. 'toLocaleString',
  181. 'valueOf',
  182. 'hasOwnProperty',
  183. 'isPrototypeOf',
  184. 'propertyIsEnumerable',
  185. 'constructor'
  186. ],
  187. dontEnumsLength = dontEnums.length;
  188. return function (obj) {
  189. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  190. throw new TypeError('Object.keys called on non-object');
  191. }
  192. var result = [];
  193. for (var prop in obj) {
  194. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  195. }
  196. if (hasDontEnumBug) {
  197. for (var i=0; i < dontEnumsLength; i++) {
  198. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  199. }
  200. }
  201. return result;
  202. }
  203. })()
  204. }
  205. // Internet Explorer 8 and older does not support Array.isArray,
  206. // so we define it here in that case.
  207. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  208. if(!Array.isArray) {
  209. Array.isArray = function (vArg) {
  210. return Object.prototype.toString.call(vArg) === "[object Array]";
  211. };
  212. }
  213. // Internet Explorer 8 and older does not support Function.bind,
  214. // so we define it here in that case.
  215. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  216. if (!Function.prototype.bind) {
  217. Function.prototype.bind = function (oThis) {
  218. if (typeof this !== "function") {
  219. // closest thing possible to the ECMAScript 5 internal IsCallable function
  220. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  221. }
  222. var aArgs = Array.prototype.slice.call(arguments, 1),
  223. fToBind = this,
  224. fNOP = function () {},
  225. fBound = function () {
  226. return fToBind.apply(this instanceof fNOP && oThis
  227. ? this
  228. : oThis,
  229. aArgs.concat(Array.prototype.slice.call(arguments)));
  230. };
  231. fNOP.prototype = this.prototype;
  232. fBound.prototype = new fNOP();
  233. return fBound;
  234. };
  235. }
  236. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  237. if (!Object.create) {
  238. Object.create = function (o) {
  239. if (arguments.length > 1) {
  240. throw new Error('Object.create implementation only accepts the first parameter.');
  241. }
  242. function F() {}
  243. F.prototype = o;
  244. return new F();
  245. };
  246. }
  247. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  248. if (!Function.prototype.bind) {
  249. Function.prototype.bind = function (oThis) {
  250. if (typeof this !== "function") {
  251. // closest thing possible to the ECMAScript 5 internal IsCallable function
  252. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  253. }
  254. var aArgs = Array.prototype.slice.call(arguments, 1),
  255. fToBind = this,
  256. fNOP = function () {},
  257. fBound = function () {
  258. return fToBind.apply(this instanceof fNOP && oThis
  259. ? this
  260. : oThis,
  261. aArgs.concat(Array.prototype.slice.call(arguments)));
  262. };
  263. fNOP.prototype = this.prototype;
  264. fBound.prototype = new fNOP();
  265. return fBound;
  266. };
  267. }
  268. /**
  269. * utility functions
  270. */
  271. var util = {};
  272. /**
  273. * Test whether given object is a number
  274. * @param {*} object
  275. * @return {Boolean} isNumber
  276. */
  277. util.isNumber = function isNumber(object) {
  278. return (object instanceof Number || typeof object == 'number');
  279. };
  280. /**
  281. * Test whether given object is a string
  282. * @param {*} object
  283. * @return {Boolean} isString
  284. */
  285. util.isString = function isString(object) {
  286. return (object instanceof String || typeof object == 'string');
  287. };
  288. /**
  289. * Test whether given object is a Date, or a String containing a Date
  290. * @param {Date | String} object
  291. * @return {Boolean} isDate
  292. */
  293. util.isDate = function isDate(object) {
  294. if (object instanceof Date) {
  295. return true;
  296. }
  297. else if (util.isString(object)) {
  298. // test whether this string contains a date
  299. var match = ASPDateRegex.exec(object);
  300. if (match) {
  301. return true;
  302. }
  303. else if (!isNaN(Date.parse(object))) {
  304. return true;
  305. }
  306. }
  307. return false;
  308. };
  309. /**
  310. * Test whether given object is an instance of google.visualization.DataTable
  311. * @param {*} object
  312. * @return {Boolean} isDataTable
  313. */
  314. util.isDataTable = function isDataTable(object) {
  315. return (typeof (google) !== 'undefined') &&
  316. (google.visualization) &&
  317. (google.visualization.DataTable) &&
  318. (object instanceof google.visualization.DataTable);
  319. };
  320. /**
  321. * Create a semi UUID
  322. * source: http://stackoverflow.com/a/105074/1262753
  323. * @return {String} uuid
  324. */
  325. util.randomUUID = function randomUUID () {
  326. var S4 = function () {
  327. return Math.floor(
  328. Math.random() * 0x10000 /* 65536 */
  329. ).toString(16);
  330. };
  331. return (
  332. S4() + S4() + '-' +
  333. S4() + '-' +
  334. S4() + '-' +
  335. S4() + '-' +
  336. S4() + S4() + S4()
  337. );
  338. };
  339. /**
  340. * Extend object a with the properties of object b or a series of objects
  341. * Only properties with defined values are copied
  342. * @param {Object} a
  343. * @param {... Object} b
  344. * @return {Object} a
  345. */
  346. util.extend = function (a, b) {
  347. for (var i = 1, len = arguments.length; i < len; i++) {
  348. var other = arguments[i];
  349. for (var prop in other) {
  350. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  351. a[prop] = other[prop];
  352. }
  353. }
  354. }
  355. return a;
  356. };
  357. /**
  358. * Test whether all elements in two arrays are equal.
  359. * @param {Array} a
  360. * @param {Array} b
  361. * @return {boolean} Returns true if both arrays have the same length and same
  362. * elements.
  363. */
  364. util.equalArray = function (a, b) {
  365. if (a.length != b.length) return false;
  366. for (var i = 1, len = a.length; i < len; i++) {
  367. if (a[i] != b[i]) return false;
  368. }
  369. return true;
  370. };
  371. /**
  372. * Convert an object to another type
  373. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  374. * @param {String | undefined} type Name of the type. Available types:
  375. * 'Boolean', 'Number', 'String',
  376. * 'Date', 'Moment', ISODate', 'ASPDate'.
  377. * @return {*} object
  378. * @throws Error
  379. */
  380. util.convert = function convert(object, type) {
  381. var match;
  382. if (object === undefined) {
  383. return undefined;
  384. }
  385. if (object === null) {
  386. return null;
  387. }
  388. if (!type) {
  389. return object;
  390. }
  391. if (!(typeof type === 'string') && !(type instanceof String)) {
  392. throw new Error('Type must be a string');
  393. }
  394. //noinspection FallthroughInSwitchStatementJS
  395. switch (type) {
  396. case 'boolean':
  397. case 'Boolean':
  398. return Boolean(object);
  399. case 'number':
  400. case 'Number':
  401. return Number(object.valueOf());
  402. case 'string':
  403. case 'String':
  404. return String(object);
  405. case 'Date':
  406. if (util.isNumber(object)) {
  407. return new Date(object);
  408. }
  409. if (object instanceof Date) {
  410. return new Date(object.valueOf());
  411. }
  412. else if (moment.isMoment(object)) {
  413. return new Date(object.valueOf());
  414. }
  415. if (util.isString(object)) {
  416. match = ASPDateRegex.exec(object);
  417. if (match) {
  418. // object is an ASP date
  419. return new Date(Number(match[1])); // parse number
  420. }
  421. else {
  422. return moment(object).toDate(); // parse string
  423. }
  424. }
  425. else {
  426. throw new Error(
  427. 'Cannot convert object of type ' + util.getType(object) +
  428. ' to type Date');
  429. }
  430. case 'Moment':
  431. if (util.isNumber(object)) {
  432. return moment(object);
  433. }
  434. if (object instanceof Date) {
  435. return moment(object.valueOf());
  436. }
  437. else if (moment.isMoment(object)) {
  438. return moment(object);
  439. }
  440. if (util.isString(object)) {
  441. match = ASPDateRegex.exec(object);
  442. if (match) {
  443. // object is an ASP date
  444. return moment(Number(match[1])); // parse number
  445. }
  446. else {
  447. return moment(object); // parse string
  448. }
  449. }
  450. else {
  451. throw new Error(
  452. 'Cannot convert object of type ' + util.getType(object) +
  453. ' to type Date');
  454. }
  455. case 'ISODate':
  456. if (util.isNumber(object)) {
  457. return new Date(object);
  458. }
  459. else if (object instanceof Date) {
  460. return object.toISOString();
  461. }
  462. else if (moment.isMoment(object)) {
  463. return object.toDate().toISOString();
  464. }
  465. else if (util.isString(object)) {
  466. match = ASPDateRegex.exec(object);
  467. if (match) {
  468. // object is an ASP date
  469. return new Date(Number(match[1])).toISOString(); // parse number
  470. }
  471. else {
  472. return new Date(object).toISOString(); // parse string
  473. }
  474. }
  475. else {
  476. throw new Error(
  477. 'Cannot convert object of type ' + util.getType(object) +
  478. ' to type ISODate');
  479. }
  480. case 'ASPDate':
  481. if (util.isNumber(object)) {
  482. return '/Date(' + object + ')/';
  483. }
  484. else if (object instanceof Date) {
  485. return '/Date(' + object.valueOf() + ')/';
  486. }
  487. else if (util.isString(object)) {
  488. match = ASPDateRegex.exec(object);
  489. var value;
  490. if (match) {
  491. // object is an ASP date
  492. value = new Date(Number(match[1])).valueOf(); // parse number
  493. }
  494. else {
  495. value = new Date(object).valueOf(); // parse string
  496. }
  497. return '/Date(' + value + ')/';
  498. }
  499. else {
  500. throw new Error(
  501. 'Cannot convert object of type ' + util.getType(object) +
  502. ' to type ASPDate');
  503. }
  504. default:
  505. throw new Error('Cannot convert object of type ' + util.getType(object) +
  506. ' to type "' + type + '"');
  507. }
  508. };
  509. // parse ASP.Net Date pattern,
  510. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  511. // code from http://momentjs.com/
  512. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  513. /**
  514. * Get the type of an object, for example util.getType([]) returns 'Array'
  515. * @param {*} object
  516. * @return {String} type
  517. */
  518. util.getType = function getType(object) {
  519. var type = typeof object;
  520. if (type == 'object') {
  521. if (object == null) {
  522. return 'null';
  523. }
  524. if (object instanceof Boolean) {
  525. return 'Boolean';
  526. }
  527. if (object instanceof Number) {
  528. return 'Number';
  529. }
  530. if (object instanceof String) {
  531. return 'String';
  532. }
  533. if (object instanceof Array) {
  534. return 'Array';
  535. }
  536. if (object instanceof Date) {
  537. return 'Date';
  538. }
  539. return 'Object';
  540. }
  541. else if (type == 'number') {
  542. return 'Number';
  543. }
  544. else if (type == 'boolean') {
  545. return 'Boolean';
  546. }
  547. else if (type == 'string') {
  548. return 'String';
  549. }
  550. return type;
  551. };
  552. /**
  553. * Retrieve the absolute left value of a DOM element
  554. * @param {Element} elem A dom element, for example a div
  555. * @return {number} left The absolute left position of this element
  556. * in the browser page.
  557. */
  558. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  559. var doc = document.documentElement;
  560. var body = document.body;
  561. var left = elem.offsetLeft;
  562. var e = elem.offsetParent;
  563. while (e != null && e != body && e != doc) {
  564. left += e.offsetLeft;
  565. left -= e.scrollLeft;
  566. e = e.offsetParent;
  567. }
  568. return left;
  569. };
  570. /**
  571. * Retrieve the absolute top value of a DOM element
  572. * @param {Element} elem A dom element, for example a div
  573. * @return {number} top The absolute top position of this element
  574. * in the browser page.
  575. */
  576. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  577. var doc = document.documentElement;
  578. var body = document.body;
  579. var top = elem.offsetTop;
  580. var e = elem.offsetParent;
  581. while (e != null && e != body && e != doc) {
  582. top += e.offsetTop;
  583. top -= e.scrollTop;
  584. e = e.offsetParent;
  585. }
  586. return top;
  587. };
  588. /**
  589. * Get the absolute, vertical mouse position from an event.
  590. * @param {Event} event
  591. * @return {Number} pageY
  592. */
  593. util.getPageY = function getPageY (event) {
  594. if ('pageY' in event) {
  595. return event.pageY;
  596. }
  597. else {
  598. var clientY;
  599. if (('targetTouches' in event) && event.targetTouches.length) {
  600. clientY = event.targetTouches[0].clientY;
  601. }
  602. else {
  603. clientY = event.clientY;
  604. }
  605. var doc = document.documentElement;
  606. var body = document.body;
  607. return clientY +
  608. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  609. ( doc && doc.clientTop || body && body.clientTop || 0 );
  610. }
  611. };
  612. /**
  613. * Get the absolute, horizontal mouse position from an event.
  614. * @param {Event} event
  615. * @return {Number} pageX
  616. */
  617. util.getPageX = function getPageX (event) {
  618. if ('pageY' in event) {
  619. return event.pageX;
  620. }
  621. else {
  622. var clientX;
  623. if (('targetTouches' in event) && event.targetTouches.length) {
  624. clientX = event.targetTouches[0].clientX;
  625. }
  626. else {
  627. clientX = event.clientX;
  628. }
  629. var doc = document.documentElement;
  630. var body = document.body;
  631. return clientX +
  632. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  633. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  634. }
  635. };
  636. /**
  637. * add a className to the given elements style
  638. * @param {Element} elem
  639. * @param {String} className
  640. */
  641. util.addClassName = function addClassName(elem, className) {
  642. var classes = elem.className.split(' ');
  643. if (classes.indexOf(className) == -1) {
  644. classes.push(className); // add the class to the array
  645. elem.className = classes.join(' ');
  646. }
  647. };
  648. /**
  649. * add a className to the given elements style
  650. * @param {Element} elem
  651. * @param {String} className
  652. */
  653. util.removeClassName = function removeClassname(elem, className) {
  654. var classes = elem.className.split(' ');
  655. var index = classes.indexOf(className);
  656. if (index != -1) {
  657. classes.splice(index, 1); // remove the class from the array
  658. elem.className = classes.join(' ');
  659. }
  660. };
  661. /**
  662. * For each method for both arrays and objects.
  663. * In case of an array, the built-in Array.forEach() is applied.
  664. * In case of an Object, the method loops over all properties of the object.
  665. * @param {Object | Array} object An Object or Array
  666. * @param {function} callback Callback method, called for each item in
  667. * the object or array with three parameters:
  668. * callback(value, index, object)
  669. */
  670. util.forEach = function forEach (object, callback) {
  671. var i,
  672. len;
  673. if (object instanceof Array) {
  674. // array
  675. for (i = 0, len = object.length; i < len; i++) {
  676. callback(object[i], i, object);
  677. }
  678. }
  679. else {
  680. // object
  681. for (i in object) {
  682. if (object.hasOwnProperty(i)) {
  683. callback(object[i], i, object);
  684. }
  685. }
  686. }
  687. };
  688. /**
  689. * Convert an object into an array: all objects properties are put into the
  690. * array. The resulting array is unordered.
  691. * @param {Object} object
  692. * @param {Array} array
  693. */
  694. util.toArray = function toArray(object) {
  695. var array = [];
  696. for (var prop in object) {
  697. if (object.hasOwnProperty(prop)) array.push(object[prop]);
  698. }
  699. return array;
  700. }
  701. /**
  702. * Update a property in an object
  703. * @param {Object} object
  704. * @param {String} key
  705. * @param {*} value
  706. * @return {Boolean} changed
  707. */
  708. util.updateProperty = function updateProperty (object, key, value) {
  709. if (object[key] !== value) {
  710. object[key] = value;
  711. return true;
  712. }
  713. else {
  714. return false;
  715. }
  716. };
  717. /**
  718. * Add and event listener. Works for all browsers
  719. * @param {Element} element An html element
  720. * @param {string} action The action, for example "click",
  721. * without the prefix "on"
  722. * @param {function} listener The callback function to be executed
  723. * @param {boolean} [useCapture]
  724. */
  725. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  726. if (element.addEventListener) {
  727. if (useCapture === undefined)
  728. useCapture = false;
  729. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  730. action = "DOMMouseScroll"; // For Firefox
  731. }
  732. element.addEventListener(action, listener, useCapture);
  733. } else {
  734. element.attachEvent("on" + action, listener); // IE browsers
  735. }
  736. };
  737. /**
  738. * Remove an event listener from an element
  739. * @param {Element} element An html dom element
  740. * @param {string} action The name of the event, for example "mousedown"
  741. * @param {function} listener The listener function
  742. * @param {boolean} [useCapture]
  743. */
  744. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  745. if (element.removeEventListener) {
  746. // non-IE browsers
  747. if (useCapture === undefined)
  748. useCapture = false;
  749. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  750. action = "DOMMouseScroll"; // For Firefox
  751. }
  752. element.removeEventListener(action, listener, useCapture);
  753. } else {
  754. // IE browsers
  755. element.detachEvent("on" + action, listener);
  756. }
  757. };
  758. /**
  759. * Get HTML element which is the target of the event
  760. * @param {Event} event
  761. * @return {Element} target element
  762. */
  763. util.getTarget = function getTarget(event) {
  764. // code from http://www.quirksmode.org/js/events_properties.html
  765. if (!event) {
  766. event = window.event;
  767. }
  768. var target;
  769. if (event.target) {
  770. target = event.target;
  771. }
  772. else if (event.srcElement) {
  773. target = event.srcElement;
  774. }
  775. if (target.nodeType != undefined && target.nodeType == 3) {
  776. // defeat Safari bug
  777. target = target.parentNode;
  778. }
  779. return target;
  780. };
  781. /**
  782. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  783. * @param {Element} element
  784. * @param {Event} event
  785. */
  786. util.fakeGesture = function fakeGesture (element, event) {
  787. var eventType = null;
  788. // for hammer.js 1.0.5
  789. var gesture = Hammer.event.collectEventData(this, eventType, event);
  790. // for hammer.js 1.0.6
  791. //var touches = Hammer.event.getTouchList(event, eventType);
  792. // var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  793. // on IE in standards mode, no touches are recognized by hammer.js,
  794. // resulting in NaN values for center.pageX and center.pageY
  795. if (isNaN(gesture.center.pageX)) {
  796. gesture.center.pageX = event.pageX;
  797. }
  798. if (isNaN(gesture.center.pageY)) {
  799. gesture.center.pageY = event.pageY;
  800. }
  801. return gesture;
  802. };
  803. util.option = {};
  804. /**
  805. * Convert a value into a boolean
  806. * @param {Boolean | function | undefined} value
  807. * @param {Boolean} [defaultValue]
  808. * @returns {Boolean} bool
  809. */
  810. util.option.asBoolean = function (value, defaultValue) {
  811. if (typeof value == 'function') {
  812. value = value();
  813. }
  814. if (value != null) {
  815. return (value != false);
  816. }
  817. return defaultValue || null;
  818. };
  819. /**
  820. * Convert a value into a number
  821. * @param {Boolean | function | undefined} value
  822. * @param {Number} [defaultValue]
  823. * @returns {Number} number
  824. */
  825. util.option.asNumber = function (value, defaultValue) {
  826. if (typeof value == 'function') {
  827. value = value();
  828. }
  829. if (value != null) {
  830. return Number(value) || defaultValue || null;
  831. }
  832. return defaultValue || null;
  833. };
  834. /**
  835. * Convert a value into a string
  836. * @param {String | function | undefined} value
  837. * @param {String} [defaultValue]
  838. * @returns {String} str
  839. */
  840. util.option.asString = function (value, defaultValue) {
  841. if (typeof value == 'function') {
  842. value = value();
  843. }
  844. if (value != null) {
  845. return String(value);
  846. }
  847. return defaultValue || null;
  848. };
  849. /**
  850. * Convert a size or location into a string with pixels or a percentage
  851. * @param {String | Number | function | undefined} value
  852. * @param {String} [defaultValue]
  853. * @returns {String} size
  854. */
  855. util.option.asSize = function (value, defaultValue) {
  856. if (typeof value == 'function') {
  857. value = value();
  858. }
  859. if (util.isString(value)) {
  860. return value;
  861. }
  862. else if (util.isNumber(value)) {
  863. return value + 'px';
  864. }
  865. else {
  866. return defaultValue || null;
  867. }
  868. };
  869. /**
  870. * Convert a value into a DOM element
  871. * @param {HTMLElement | function | undefined} value
  872. * @param {HTMLElement} [defaultValue]
  873. * @returns {HTMLElement | null} dom
  874. */
  875. util.option.asElement = function (value, defaultValue) {
  876. if (typeof value == 'function') {
  877. value = value();
  878. }
  879. return value || defaultValue || null;
  880. };
  881. util.GiveDec = function GiveDec(Hex) {
  882. var Value;
  883. if (Hex == "A")
  884. Value = 10;
  885. else if (Hex == "B")
  886. Value = 11;
  887. else if (Hex == "C")
  888. Value = 12;
  889. else if (Hex == "D")
  890. Value = 13;
  891. else if (Hex == "E")
  892. Value = 14;
  893. else if (Hex == "F")
  894. Value = 15;
  895. else
  896. Value = eval(Hex);
  897. return Value;
  898. };
  899. util.GiveHex = function GiveHex(Dec) {
  900. var Value;
  901. if(Dec == 10)
  902. Value = "A";
  903. else if (Dec == 11)
  904. Value = "B";
  905. else if (Dec == 12)
  906. Value = "C";
  907. else if (Dec == 13)
  908. Value = "D";
  909. else if (Dec == 14)
  910. Value = "E";
  911. else if (Dec == 15)
  912. Value = "F";
  913. else
  914. Value = "" + Dec;
  915. return Value;
  916. };
  917. /**
  918. * Parse a color property into an object with border, background, and
  919. * highlight colors
  920. * @param {Object | String} color
  921. * @return {Object} colorObject
  922. */
  923. util.parseColor = function(color) {
  924. var c;
  925. if (util.isString(color)) {
  926. if (util.isValidHex(color)) {
  927. var hsv = util.hexToHSV(color);
  928. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  929. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  930. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  931. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  932. c = {
  933. background: color,
  934. border:darkerColorHex,
  935. highlight: {
  936. background:lighterColorHex,
  937. border:darkerColorHex
  938. }
  939. };
  940. }
  941. else {
  942. c = {
  943. background:color,
  944. border:color,
  945. highlight: {
  946. background:color,
  947. border:color
  948. }
  949. };
  950. }
  951. }
  952. else {
  953. c = {};
  954. c.background = color.background || 'white';
  955. c.border = color.border || c.background;
  956. if (util.isString(color.highlight)) {
  957. c.highlight = {
  958. border: color.highlight,
  959. background: color.highlight
  960. }
  961. }
  962. else {
  963. c.highlight = {};
  964. c.highlight.background = color.highlight && color.highlight.background || c.background;
  965. c.highlight.border = color.highlight && color.highlight.border || c.border;
  966. }
  967. }
  968. return c;
  969. };
  970. /**
  971. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  972. *
  973. * @param {String} hex
  974. * @returns {{r: *, g: *, b: *}}
  975. */
  976. util.hexToRGB = function hexToRGB(hex) {
  977. hex = hex.replace("#","").toUpperCase();
  978. var a = util.GiveDec(hex.substring(0, 1));
  979. var b = util.GiveDec(hex.substring(1, 2));
  980. var c = util.GiveDec(hex.substring(2, 3));
  981. var d = util.GiveDec(hex.substring(3, 4));
  982. var e = util.GiveDec(hex.substring(4, 5));
  983. var f = util.GiveDec(hex.substring(5, 6));
  984. var r = (a * 16) + b;
  985. var g = (c * 16) + d;
  986. var b = (e * 16) + f;
  987. return {r:r,g:g,b:b};
  988. };
  989. util.RGBToHex = function RGBToHex(red,green,blue) {
  990. var a = util.GiveHex(Math.floor(red / 16));
  991. var b = util.GiveHex(red % 16);
  992. var c = util.GiveHex(Math.floor(green / 16));
  993. var d = util.GiveHex(green % 16);
  994. var e = util.GiveHex(Math.floor(blue / 16));
  995. var f = util.GiveHex(blue % 16);
  996. var hex = a + b + c + d + e + f;
  997. return "#" + hex;
  998. };
  999. /**
  1000. * http://www.javascripter.net/faq/rgb2hsv.htm
  1001. *
  1002. * @param red
  1003. * @param green
  1004. * @param blue
  1005. * @returns {*}
  1006. * @constructor
  1007. */
  1008. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  1009. red=red/255; green=green/255; blue=blue/255;
  1010. var minRGB = Math.min(red,Math.min(green,blue));
  1011. var maxRGB = Math.max(red,Math.max(green,blue));
  1012. // Black-gray-white
  1013. if (minRGB == maxRGB) {
  1014. return {h:0,s:0,v:minRGB};
  1015. }
  1016. // Colors other than black-gray-white:
  1017. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  1018. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  1019. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  1020. var saturation = (maxRGB - minRGB)/maxRGB;
  1021. var value = maxRGB;
  1022. return {h:hue,s:saturation,v:value};
  1023. };
  1024. /**
  1025. * https://gist.github.com/mjijackson/5311256
  1026. * @param hue
  1027. * @param saturation
  1028. * @param value
  1029. * @returns {{r: number, g: number, b: number}}
  1030. * @constructor
  1031. */
  1032. util.HSVToRGB = function HSVToRGB(h, s, v) {
  1033. var r, g, b;
  1034. var i = Math.floor(h * 6);
  1035. var f = h * 6 - i;
  1036. var p = v * (1 - s);
  1037. var q = v * (1 - f * s);
  1038. var t = v * (1 - (1 - f) * s);
  1039. switch (i % 6) {
  1040. case 0: r = v, g = t, b = p; break;
  1041. case 1: r = q, g = v, b = p; break;
  1042. case 2: r = p, g = v, b = t; break;
  1043. case 3: r = p, g = q, b = v; break;
  1044. case 4: r = t, g = p, b = v; break;
  1045. case 5: r = v, g = p, b = q; break;
  1046. }
  1047. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  1048. };
  1049. util.HSVToHex = function HSVToHex(h, s, v) {
  1050. var rgb = util.HSVToRGB(h, s, v);
  1051. return util.RGBToHex(rgb.r, rgb.g, rgb.b);
  1052. };
  1053. util.hexToHSV = function hexToHSV(hex) {
  1054. var rgb = util.hexToRGB(hex);
  1055. return util.RGBToHSV(rgb.r, rgb.g, rgb.b);
  1056. };
  1057. util.isValidHex = function isValidHex(hex) {
  1058. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1059. return isOk;
  1060. };
  1061. util.copyObject = function copyObject(objectFrom, objectTo) {
  1062. for (var i in objectFrom) {
  1063. if (objectFrom.hasOwnProperty(i)) {
  1064. if (typeof objectFrom[i] == "object") {
  1065. objectTo[i] = {};
  1066. util.copyObject(objectFrom[i], objectTo[i]);
  1067. }
  1068. else {
  1069. objectTo[i] = objectFrom[i];
  1070. }
  1071. }
  1072. }
  1073. };
  1074. /**
  1075. * DataSet
  1076. *
  1077. * Usage:
  1078. * var dataSet = new DataSet({
  1079. * fieldId: '_id',
  1080. * convert: {
  1081. * // ...
  1082. * }
  1083. * });
  1084. *
  1085. * dataSet.add(item);
  1086. * dataSet.add(data);
  1087. * dataSet.update(item);
  1088. * dataSet.update(data);
  1089. * dataSet.remove(id);
  1090. * dataSet.remove(ids);
  1091. * var data = dataSet.get();
  1092. * var data = dataSet.get(id);
  1093. * var data = dataSet.get(ids);
  1094. * var data = dataSet.get(ids, options, data);
  1095. * dataSet.clear();
  1096. *
  1097. * A data set can:
  1098. * - add/remove/update data
  1099. * - gives triggers upon changes in the data
  1100. * - can import/export data in various data formats
  1101. *
  1102. * @param {Object} [options] Available options:
  1103. * {String} fieldId Field name of the id in the
  1104. * items, 'id' by default.
  1105. * {Object.<String, String} convert
  1106. * A map with field names as key,
  1107. * and the field type as value.
  1108. * @constructor DataSet
  1109. */
  1110. // TODO: add a DataSet constructor DataSet(data, options)
  1111. function DataSet (options) {
  1112. this.id = util.randomUUID();
  1113. this.options = options || {};
  1114. this.data = {}; // map with data indexed by id
  1115. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1116. this.convert = {}; // field types by field name
  1117. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1118. if (this.options.convert) {
  1119. for (var field in this.options.convert) {
  1120. if (this.options.convert.hasOwnProperty(field)) {
  1121. var value = this.options.convert[field];
  1122. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1123. this.convert[field] = 'Date';
  1124. }
  1125. else {
  1126. this.convert[field] = value;
  1127. }
  1128. }
  1129. }
  1130. }
  1131. // event subscribers
  1132. this.subscribers = {};
  1133. this.internalIds = {}; // internally generated id's
  1134. }
  1135. /**
  1136. * Subscribe to an event, add an event listener
  1137. * @param {String} event Event name. Available events: 'put', 'update',
  1138. * 'remove'
  1139. * @param {function} callback Callback method. Called with three parameters:
  1140. * {String} event
  1141. * {Object | null} params
  1142. * {String | Number} senderId
  1143. */
  1144. DataSet.prototype.on = function on (event, callback) {
  1145. var subscribers = this.subscribers[event];
  1146. if (!subscribers) {
  1147. subscribers = [];
  1148. this.subscribers[event] = subscribers;
  1149. }
  1150. subscribers.push({
  1151. callback: callback
  1152. });
  1153. };
  1154. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1155. DataSet.prototype.subscribe = DataSet.prototype.on;
  1156. /**
  1157. * Unsubscribe from an event, remove an event listener
  1158. * @param {String} event
  1159. * @param {function} callback
  1160. */
  1161. DataSet.prototype.off = function off(event, callback) {
  1162. var subscribers = this.subscribers[event];
  1163. if (subscribers) {
  1164. this.subscribers[event] = subscribers.filter(function (listener) {
  1165. return (listener.callback != callback);
  1166. });
  1167. }
  1168. };
  1169. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1170. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1171. /**
  1172. * Trigger an event
  1173. * @param {String} event
  1174. * @param {Object | null} params
  1175. * @param {String} [senderId] Optional id of the sender.
  1176. * @private
  1177. */
  1178. DataSet.prototype._trigger = function (event, params, senderId) {
  1179. if (event == '*') {
  1180. throw new Error('Cannot trigger event *');
  1181. }
  1182. var subscribers = [];
  1183. if (event in this.subscribers) {
  1184. subscribers = subscribers.concat(this.subscribers[event]);
  1185. }
  1186. if ('*' in this.subscribers) {
  1187. subscribers = subscribers.concat(this.subscribers['*']);
  1188. }
  1189. for (var i = 0; i < subscribers.length; i++) {
  1190. var subscriber = subscribers[i];
  1191. if (subscriber.callback) {
  1192. subscriber.callback(event, params, senderId || null);
  1193. }
  1194. }
  1195. };
  1196. /**
  1197. * Add data.
  1198. * Adding an item will fail when there already is an item with the same id.
  1199. * @param {Object | Array | DataTable} data
  1200. * @param {String} [senderId] Optional sender id
  1201. * @return {Array} addedIds Array with the ids of the added items
  1202. */
  1203. DataSet.prototype.add = function (data, senderId) {
  1204. var addedIds = [],
  1205. id,
  1206. me = this;
  1207. if (data instanceof Array) {
  1208. // Array
  1209. for (var i = 0, len = data.length; i < len; i++) {
  1210. id = me._addItem(data[i]);
  1211. addedIds.push(id);
  1212. }
  1213. }
  1214. else if (util.isDataTable(data)) {
  1215. // Google DataTable
  1216. var columns = this._getColumnNames(data);
  1217. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1218. var item = {};
  1219. for (var col = 0, cols = columns.length; col < cols; col++) {
  1220. var field = columns[col];
  1221. item[field] = data.getValue(row, col);
  1222. }
  1223. id = me._addItem(item);
  1224. addedIds.push(id);
  1225. }
  1226. }
  1227. else if (data instanceof Object) {
  1228. // Single item
  1229. id = me._addItem(data);
  1230. addedIds.push(id);
  1231. }
  1232. else {
  1233. throw new Error('Unknown dataType');
  1234. }
  1235. if (addedIds.length) {
  1236. this._trigger('add', {items: addedIds}, senderId);
  1237. }
  1238. return addedIds;
  1239. };
  1240. /**
  1241. * Update existing items. When an item does not exist, it will be created
  1242. * @param {Object | Array | DataTable} data
  1243. * @param {String} [senderId] Optional sender id
  1244. * @return {Array} updatedIds The ids of the added or updated items
  1245. */
  1246. DataSet.prototype.update = function (data, senderId) {
  1247. var addedIds = [],
  1248. updatedIds = [],
  1249. me = this,
  1250. fieldId = me.fieldId;
  1251. var addOrUpdate = function (item) {
  1252. var id = item[fieldId];
  1253. if (me.data[id]) {
  1254. // update item
  1255. id = me._updateItem(item);
  1256. updatedIds.push(id);
  1257. }
  1258. else {
  1259. // add new item
  1260. id = me._addItem(item);
  1261. addedIds.push(id);
  1262. }
  1263. };
  1264. if (data instanceof Array) {
  1265. // Array
  1266. for (var i = 0, len = data.length; i < len; i++) {
  1267. addOrUpdate(data[i]);
  1268. }
  1269. }
  1270. else if (util.isDataTable(data)) {
  1271. // Google DataTable
  1272. var columns = this._getColumnNames(data);
  1273. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1274. var item = {};
  1275. for (var col = 0, cols = columns.length; col < cols; col++) {
  1276. var field = columns[col];
  1277. item[field] = data.getValue(row, col);
  1278. }
  1279. addOrUpdate(item);
  1280. }
  1281. }
  1282. else if (data instanceof Object) {
  1283. // Single item
  1284. addOrUpdate(data);
  1285. }
  1286. else {
  1287. throw new Error('Unknown dataType');
  1288. }
  1289. if (addedIds.length) {
  1290. this._trigger('add', {items: addedIds}, senderId);
  1291. }
  1292. if (updatedIds.length) {
  1293. this._trigger('update', {items: updatedIds}, senderId);
  1294. }
  1295. return addedIds.concat(updatedIds);
  1296. };
  1297. /**
  1298. * Get a data item or multiple items.
  1299. *
  1300. * Usage:
  1301. *
  1302. * get()
  1303. * get(options: Object)
  1304. * get(options: Object, data: Array | DataTable)
  1305. *
  1306. * get(id: Number | String)
  1307. * get(id: Number | String, options: Object)
  1308. * get(id: Number | String, options: Object, data: Array | DataTable)
  1309. *
  1310. * get(ids: Number[] | String[])
  1311. * get(ids: Number[] | String[], options: Object)
  1312. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1313. *
  1314. * Where:
  1315. *
  1316. * {Number | String} id The id of an item
  1317. * {Number[] | String{}} ids An array with ids of items
  1318. * {Object} options An Object with options. Available options:
  1319. * {String} [type] Type of data to be returned. Can
  1320. * be 'DataTable' or 'Array' (default)
  1321. * {Object.<String, String>} [convert]
  1322. * {String[]} [fields] field names to be returned
  1323. * {function} [filter] filter items
  1324. * {String | function} [order] Order the items by
  1325. * a field name or custom sort function.
  1326. * {Array | DataTable} [data] If provided, items will be appended to this
  1327. * array or table. Required in case of Google
  1328. * DataTable.
  1329. *
  1330. * @throws Error
  1331. */
  1332. DataSet.prototype.get = function (args) {
  1333. var me = this;
  1334. var globalShowInternalIds = this.showInternalIds;
  1335. // parse the arguments
  1336. var id, ids, options, data;
  1337. var firstType = util.getType(arguments[0]);
  1338. if (firstType == 'String' || firstType == 'Number') {
  1339. // get(id [, options] [, data])
  1340. id = arguments[0];
  1341. options = arguments[1];
  1342. data = arguments[2];
  1343. }
  1344. else if (firstType == 'Array') {
  1345. // get(ids [, options] [, data])
  1346. ids = arguments[0];
  1347. options = arguments[1];
  1348. data = arguments[2];
  1349. }
  1350. else {
  1351. // get([, options] [, data])
  1352. options = arguments[0];
  1353. data = arguments[1];
  1354. }
  1355. // determine the return type
  1356. var type;
  1357. if (options && options.type) {
  1358. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1359. if (data && (type != util.getType(data))) {
  1360. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1361. 'does not correspond with specified options.type (' + options.type + ')');
  1362. }
  1363. if (type == 'DataTable' && !util.isDataTable(data)) {
  1364. throw new Error('Parameter "data" must be a DataTable ' +
  1365. 'when options.type is "DataTable"');
  1366. }
  1367. }
  1368. else if (data) {
  1369. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1370. }
  1371. else {
  1372. type = 'Array';
  1373. }
  1374. // we allow the setting of this value for a single get request.
  1375. if (options != undefined) {
  1376. if (options.showInternalIds != undefined) {
  1377. this.showInternalIds = options.showInternalIds;
  1378. }
  1379. }
  1380. // build options
  1381. var convert = options && options.convert || this.options.convert;
  1382. var filter = options && options.filter;
  1383. var items = [], item, itemId, i, len;
  1384. // convert items
  1385. if (id != undefined) {
  1386. // return a single item
  1387. item = me._getItem(id, convert);
  1388. if (filter && !filter(item)) {
  1389. item = null;
  1390. }
  1391. }
  1392. else if (ids != undefined) {
  1393. // return a subset of items
  1394. for (i = 0, len = ids.length; i < len; i++) {
  1395. item = me._getItem(ids[i], convert);
  1396. if (!filter || filter(item)) {
  1397. items.push(item);
  1398. }
  1399. }
  1400. }
  1401. else {
  1402. // return all items
  1403. for (itemId in this.data) {
  1404. if (this.data.hasOwnProperty(itemId)) {
  1405. item = me._getItem(itemId, convert);
  1406. if (!filter || filter(item)) {
  1407. items.push(item);
  1408. }
  1409. }
  1410. }
  1411. }
  1412. // restore the global value of showInternalIds
  1413. this.showInternalIds = globalShowInternalIds;
  1414. // order the results
  1415. if (options && options.order && id == undefined) {
  1416. this._sort(items, options.order);
  1417. }
  1418. // filter fields of the items
  1419. if (options && options.fields) {
  1420. var fields = options.fields;
  1421. if (id != undefined) {
  1422. item = this._filterFields(item, fields);
  1423. }
  1424. else {
  1425. for (i = 0, len = items.length; i < len; i++) {
  1426. items[i] = this._filterFields(items[i], fields);
  1427. }
  1428. }
  1429. }
  1430. // return the results
  1431. if (type == 'DataTable') {
  1432. var columns = this._getColumnNames(data);
  1433. if (id != undefined) {
  1434. // append a single item to the data table
  1435. me._appendRow(data, columns, item);
  1436. }
  1437. else {
  1438. // copy the items to the provided data table
  1439. for (i = 0, len = items.length; i < len; i++) {
  1440. me._appendRow(data, columns, items[i]);
  1441. }
  1442. }
  1443. return data;
  1444. }
  1445. else {
  1446. // return an array
  1447. if (id != undefined) {
  1448. // a single item
  1449. return item;
  1450. }
  1451. else {
  1452. // multiple items
  1453. if (data) {
  1454. // copy the items to the provided array
  1455. for (i = 0, len = items.length; i < len; i++) {
  1456. data.push(items[i]);
  1457. }
  1458. return data;
  1459. }
  1460. else {
  1461. // just return our array
  1462. return items;
  1463. }
  1464. }
  1465. }
  1466. };
  1467. /**
  1468. * Get ids of all items or from a filtered set of items.
  1469. * @param {Object} [options] An Object with options. Available options:
  1470. * {function} [filter] filter items
  1471. * {String | function} [order] Order the items by
  1472. * a field name or custom sort function.
  1473. * @return {Array} ids
  1474. */
  1475. DataSet.prototype.getIds = function (options) {
  1476. var data = this.data,
  1477. filter = options && options.filter,
  1478. order = options && options.order,
  1479. convert = options && options.convert || this.options.convert,
  1480. i,
  1481. len,
  1482. id,
  1483. item,
  1484. items,
  1485. ids = [];
  1486. if (filter) {
  1487. // get filtered items
  1488. if (order) {
  1489. // create ordered list
  1490. items = [];
  1491. for (id in data) {
  1492. if (data.hasOwnProperty(id)) {
  1493. item = this._getItem(id, convert);
  1494. if (filter(item)) {
  1495. items.push(item);
  1496. }
  1497. }
  1498. }
  1499. this._sort(items, order);
  1500. for (i = 0, len = items.length; i < len; i++) {
  1501. ids[i] = items[i][this.fieldId];
  1502. }
  1503. }
  1504. else {
  1505. // create unordered list
  1506. for (id in data) {
  1507. if (data.hasOwnProperty(id)) {
  1508. item = this._getItem(id, convert);
  1509. if (filter(item)) {
  1510. ids.push(item[this.fieldId]);
  1511. }
  1512. }
  1513. }
  1514. }
  1515. }
  1516. else {
  1517. // get all items
  1518. if (order) {
  1519. // create an ordered list
  1520. items = [];
  1521. for (id in data) {
  1522. if (data.hasOwnProperty(id)) {
  1523. items.push(data[id]);
  1524. }
  1525. }
  1526. this._sort(items, order);
  1527. for (i = 0, len = items.length; i < len; i++) {
  1528. ids[i] = items[i][this.fieldId];
  1529. }
  1530. }
  1531. else {
  1532. // create unordered list
  1533. for (id in data) {
  1534. if (data.hasOwnProperty(id)) {
  1535. item = data[id];
  1536. ids.push(item[this.fieldId]);
  1537. }
  1538. }
  1539. }
  1540. }
  1541. return ids;
  1542. };
  1543. /**
  1544. * Execute a callback function for every item in the dataset.
  1545. * The order of the items is not determined.
  1546. * @param {function} callback
  1547. * @param {Object} [options] Available options:
  1548. * {Object.<String, String>} [convert]
  1549. * {String[]} [fields] filter fields
  1550. * {function} [filter] filter items
  1551. * {String | function} [order] Order the items by
  1552. * a field name or custom sort function.
  1553. */
  1554. DataSet.prototype.forEach = function (callback, options) {
  1555. var filter = options && options.filter,
  1556. convert = options && options.convert || this.options.convert,
  1557. data = this.data,
  1558. item,
  1559. id;
  1560. if (options && options.order) {
  1561. // execute forEach on ordered list
  1562. var items = this.get(options);
  1563. for (var i = 0, len = items.length; i < len; i++) {
  1564. item = items[i];
  1565. id = item[this.fieldId];
  1566. callback(item, id);
  1567. }
  1568. }
  1569. else {
  1570. // unordered
  1571. for (id in data) {
  1572. if (data.hasOwnProperty(id)) {
  1573. item = this._getItem(id, convert);
  1574. if (!filter || filter(item)) {
  1575. callback(item, id);
  1576. }
  1577. }
  1578. }
  1579. }
  1580. };
  1581. /**
  1582. * Map every item in the dataset.
  1583. * @param {function} callback
  1584. * @param {Object} [options] Available options:
  1585. * {Object.<String, String>} [convert]
  1586. * {String[]} [fields] filter fields
  1587. * {function} [filter] filter items
  1588. * {String | function} [order] Order the items by
  1589. * a field name or custom sort function.
  1590. * @return {Object[]} mappedItems
  1591. */
  1592. DataSet.prototype.map = function (callback, options) {
  1593. var filter = options && options.filter,
  1594. convert = options && options.convert || this.options.convert,
  1595. mappedItems = [],
  1596. data = this.data,
  1597. item;
  1598. // convert and filter items
  1599. for (var id in data) {
  1600. if (data.hasOwnProperty(id)) {
  1601. item = this._getItem(id, convert);
  1602. if (!filter || filter(item)) {
  1603. mappedItems.push(callback(item, id));
  1604. }
  1605. }
  1606. }
  1607. // order items
  1608. if (options && options.order) {
  1609. this._sort(mappedItems, options.order);
  1610. }
  1611. return mappedItems;
  1612. };
  1613. /**
  1614. * Filter the fields of an item
  1615. * @param {Object} item
  1616. * @param {String[]} fields Field names
  1617. * @return {Object} filteredItem
  1618. * @private
  1619. */
  1620. DataSet.prototype._filterFields = function (item, fields) {
  1621. var filteredItem = {};
  1622. for (var field in item) {
  1623. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1624. filteredItem[field] = item[field];
  1625. }
  1626. }
  1627. return filteredItem;
  1628. };
  1629. /**
  1630. * Sort the provided array with items
  1631. * @param {Object[]} items
  1632. * @param {String | function} order A field name or custom sort function.
  1633. * @private
  1634. */
  1635. DataSet.prototype._sort = function (items, order) {
  1636. if (util.isString(order)) {
  1637. // order by provided field name
  1638. var name = order; // field name
  1639. items.sort(function (a, b) {
  1640. var av = a[name];
  1641. var bv = b[name];
  1642. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1643. });
  1644. }
  1645. else if (typeof order === 'function') {
  1646. // order by sort function
  1647. items.sort(order);
  1648. }
  1649. // TODO: extend order by an Object {field:String, direction:String}
  1650. // where direction can be 'asc' or 'desc'
  1651. else {
  1652. throw new TypeError('Order must be a function or a string');
  1653. }
  1654. };
  1655. /**
  1656. * Remove an object by pointer or by id
  1657. * @param {String | Number | Object | Array} id Object or id, or an array with
  1658. * objects or ids to be removed
  1659. * @param {String} [senderId] Optional sender id
  1660. * @return {Array} removedIds
  1661. */
  1662. DataSet.prototype.remove = function (id, senderId) {
  1663. var removedIds = [],
  1664. i, len, removedId;
  1665. if (id instanceof Array) {
  1666. for (i = 0, len = id.length; i < len; i++) {
  1667. removedId = this._remove(id[i]);
  1668. if (removedId != null) {
  1669. removedIds.push(removedId);
  1670. }
  1671. }
  1672. }
  1673. else {
  1674. removedId = this._remove(id);
  1675. if (removedId != null) {
  1676. removedIds.push(removedId);
  1677. }
  1678. }
  1679. if (removedIds.length) {
  1680. this._trigger('remove', {items: removedIds}, senderId);
  1681. }
  1682. return removedIds;
  1683. };
  1684. /**
  1685. * Remove an item by its id
  1686. * @param {Number | String | Object} id id or item
  1687. * @returns {Number | String | null} id
  1688. * @private
  1689. */
  1690. DataSet.prototype._remove = function (id) {
  1691. if (util.isNumber(id) || util.isString(id)) {
  1692. if (this.data[id]) {
  1693. delete this.data[id];
  1694. delete this.internalIds[id];
  1695. return id;
  1696. }
  1697. }
  1698. else if (id instanceof Object) {
  1699. var itemId = id[this.fieldId];
  1700. if (itemId && this.data[itemId]) {
  1701. delete this.data[itemId];
  1702. delete this.internalIds[itemId];
  1703. return itemId;
  1704. }
  1705. }
  1706. return null;
  1707. };
  1708. /**
  1709. * Clear the data
  1710. * @param {String} [senderId] Optional sender id
  1711. * @return {Array} removedIds The ids of all removed items
  1712. */
  1713. DataSet.prototype.clear = function (senderId) {
  1714. var ids = Object.keys(this.data);
  1715. this.data = {};
  1716. this.internalIds = {};
  1717. this._trigger('remove', {items: ids}, senderId);
  1718. return ids;
  1719. };
  1720. /**
  1721. * Find the item with maximum value of a specified field
  1722. * @param {String} field
  1723. * @return {Object | null} item Item containing max value, or null if no items
  1724. */
  1725. DataSet.prototype.max = function (field) {
  1726. var data = this.data,
  1727. max = null,
  1728. maxField = null;
  1729. for (var id in data) {
  1730. if (data.hasOwnProperty(id)) {
  1731. var item = data[id];
  1732. var itemField = item[field];
  1733. if (itemField != null && (!max || itemField > maxField)) {
  1734. max = item;
  1735. maxField = itemField;
  1736. }
  1737. }
  1738. }
  1739. return max;
  1740. };
  1741. /**
  1742. * Find the item with minimum value of a specified field
  1743. * @param {String} field
  1744. * @return {Object | null} item Item containing max value, or null if no items
  1745. */
  1746. DataSet.prototype.min = function (field) {
  1747. var data = this.data,
  1748. min = null,
  1749. minField = null;
  1750. for (var id in data) {
  1751. if (data.hasOwnProperty(id)) {
  1752. var item = data[id];
  1753. var itemField = item[field];
  1754. if (itemField != null && (!min || itemField < minField)) {
  1755. min = item;
  1756. minField = itemField;
  1757. }
  1758. }
  1759. }
  1760. return min;
  1761. };
  1762. /**
  1763. * Find all distinct values of a specified field
  1764. * @param {String} field
  1765. * @return {Array} values Array containing all distinct values. If the data
  1766. * items do not contain the specified field, an array
  1767. * containing a single value undefined is returned.
  1768. * The returned array is unordered.
  1769. */
  1770. DataSet.prototype.distinct = function (field) {
  1771. var data = this.data,
  1772. values = [],
  1773. fieldType = this.options.convert[field],
  1774. count = 0;
  1775. for (var prop in data) {
  1776. if (data.hasOwnProperty(prop)) {
  1777. var item = data[prop];
  1778. var value = util.convert(item[field], fieldType);
  1779. var exists = false;
  1780. for (var i = 0; i < count; i++) {
  1781. if (values[i] == value) {
  1782. exists = true;
  1783. break;
  1784. }
  1785. }
  1786. if (!exists) {
  1787. values[count] = value;
  1788. count++;
  1789. }
  1790. }
  1791. }
  1792. return values;
  1793. };
  1794. /**
  1795. * Add a single item. Will fail when an item with the same id already exists.
  1796. * @param {Object} item
  1797. * @return {String} id
  1798. * @private
  1799. */
  1800. DataSet.prototype._addItem = function (item) {
  1801. var id = item[this.fieldId];
  1802. if (id != undefined) {
  1803. // check whether this id is already taken
  1804. if (this.data[id]) {
  1805. // item already exists
  1806. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1807. }
  1808. }
  1809. else {
  1810. // generate an id
  1811. id = util.randomUUID();
  1812. item[this.fieldId] = id;
  1813. this.internalIds[id] = item;
  1814. }
  1815. var d = {};
  1816. for (var field in item) {
  1817. if (item.hasOwnProperty(field)) {
  1818. var fieldType = this.convert[field]; // type may be undefined
  1819. d[field] = util.convert(item[field], fieldType);
  1820. }
  1821. }
  1822. this.data[id] = d;
  1823. return id;
  1824. };
  1825. /**
  1826. * Get an item. Fields can be converted to a specific type
  1827. * @param {String} id
  1828. * @param {Object.<String, String>} [convert] field types to convert
  1829. * @return {Object | null} item
  1830. * @private
  1831. */
  1832. DataSet.prototype._getItem = function (id, convert) {
  1833. var field, value;
  1834. // get the item from the dataset
  1835. var raw = this.data[id];
  1836. if (!raw) {
  1837. return null;
  1838. }
  1839. // convert the items field types
  1840. var converted = {},
  1841. fieldId = this.fieldId,
  1842. internalIds = this.internalIds;
  1843. if (convert) {
  1844. for (field in raw) {
  1845. if (raw.hasOwnProperty(field)) {
  1846. value = raw[field];
  1847. // output all fields, except internal ids
  1848. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1849. converted[field] = util.convert(value, convert[field]);
  1850. }
  1851. }
  1852. }
  1853. }
  1854. else {
  1855. // no field types specified, no converting needed
  1856. for (field in raw) {
  1857. if (raw.hasOwnProperty(field)) {
  1858. value = raw[field];
  1859. // output all fields, except internal ids
  1860. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1861. converted[field] = value;
  1862. }
  1863. }
  1864. }
  1865. }
  1866. return converted;
  1867. };
  1868. /**
  1869. * Update a single item: merge with existing item.
  1870. * Will fail when the item has no id, or when there does not exist an item
  1871. * with the same id.
  1872. * @param {Object} item
  1873. * @return {String} id
  1874. * @private
  1875. */
  1876. DataSet.prototype._updateItem = function (item) {
  1877. var id = item[this.fieldId];
  1878. if (id == undefined) {
  1879. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1880. }
  1881. var d = this.data[id];
  1882. if (!d) {
  1883. // item doesn't exist
  1884. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1885. }
  1886. // merge with current item
  1887. for (var field in item) {
  1888. if (item.hasOwnProperty(field)) {
  1889. var fieldType = this.convert[field]; // type may be undefined
  1890. d[field] = util.convert(item[field], fieldType);
  1891. }
  1892. }
  1893. return id;
  1894. };
  1895. /**
  1896. * check if an id is an internal or external id
  1897. * @param id
  1898. * @returns {boolean}
  1899. * @private
  1900. */
  1901. DataSet.prototype.isInternalId = function(id) {
  1902. return (id in this.internalIds);
  1903. };
  1904. /**
  1905. * Get an array with the column names of a Google DataTable
  1906. * @param {DataTable} dataTable
  1907. * @return {String[]} columnNames
  1908. * @private
  1909. */
  1910. DataSet.prototype._getColumnNames = function (dataTable) {
  1911. var columns = [];
  1912. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1913. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1914. }
  1915. return columns;
  1916. };
  1917. /**
  1918. * Append an item as a row to the dataTable
  1919. * @param dataTable
  1920. * @param columns
  1921. * @param item
  1922. * @private
  1923. */
  1924. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1925. var row = dataTable.addRow();
  1926. for (var col = 0, cols = columns.length; col < cols; col++) {
  1927. var field = columns[col];
  1928. dataTable.setValue(row, col, item[field]);
  1929. }
  1930. };
  1931. /**
  1932. * DataView
  1933. *
  1934. * a dataview offers a filtered view on a dataset or an other dataview.
  1935. *
  1936. * @param {DataSet | DataView} data
  1937. * @param {Object} [options] Available options: see method get
  1938. *
  1939. * @constructor DataView
  1940. */
  1941. function DataView (data, options) {
  1942. this.id = util.randomUUID();
  1943. this.data = null;
  1944. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1945. this.options = options || {};
  1946. this.fieldId = 'id'; // name of the field containing id
  1947. this.subscribers = {}; // event subscribers
  1948. var me = this;
  1949. this.listener = function () {
  1950. me._onEvent.apply(me, arguments);
  1951. };
  1952. this.setData(data);
  1953. }
  1954. // TODO: implement a function .config() to dynamically update things like configured filter
  1955. // and trigger changes accordingly
  1956. /**
  1957. * Set a data source for the view
  1958. * @param {DataSet | DataView} data
  1959. */
  1960. DataView.prototype.setData = function (data) {
  1961. var ids, dataItems, i, len;
  1962. if (this.data) {
  1963. // unsubscribe from current dataset
  1964. if (this.data.unsubscribe) {
  1965. this.data.unsubscribe('*', this.listener);
  1966. }
  1967. // trigger a remove of all items in memory
  1968. ids = [];
  1969. for (var id in this.ids) {
  1970. if (this.ids.hasOwnProperty(id)) {
  1971. ids.push(id);
  1972. }
  1973. }
  1974. this.ids = {};
  1975. this._trigger('remove', {items: ids});
  1976. }
  1977. this.data = data;
  1978. if (this.data) {
  1979. // update fieldId
  1980. this.fieldId = this.options.fieldId ||
  1981. (this.data && this.data.options && this.data.options.fieldId) ||
  1982. 'id';
  1983. // trigger an add of all added items
  1984. ids = this.data.getIds({filter: this.options && this.options.filter});
  1985. for (i = 0, len = ids.length; i < len; i++) {
  1986. id = ids[i];
  1987. this.ids[id] = true;
  1988. }
  1989. this._trigger('add', {items: ids});
  1990. // subscribe to new dataset
  1991. if (this.data.on) {
  1992. this.data.on('*', this.listener);
  1993. }
  1994. }
  1995. };
  1996. /**
  1997. * Get data from the data view
  1998. *
  1999. * Usage:
  2000. *
  2001. * get()
  2002. * get(options: Object)
  2003. * get(options: Object, data: Array | DataTable)
  2004. *
  2005. * get(id: Number)
  2006. * get(id: Number, options: Object)
  2007. * get(id: Number, options: Object, data: Array | DataTable)
  2008. *
  2009. * get(ids: Number[])
  2010. * get(ids: Number[], options: Object)
  2011. * get(ids: Number[], options: Object, data: Array | DataTable)
  2012. *
  2013. * Where:
  2014. *
  2015. * {Number | String} id The id of an item
  2016. * {Number[] | String{}} ids An array with ids of items
  2017. * {Object} options An Object with options. Available options:
  2018. * {String} [type] Type of data to be returned. Can
  2019. * be 'DataTable' or 'Array' (default)
  2020. * {Object.<String, String>} [convert]
  2021. * {String[]} [fields] field names to be returned
  2022. * {function} [filter] filter items
  2023. * {String | function} [order] Order the items by
  2024. * a field name or custom sort function.
  2025. * {Array | DataTable} [data] If provided, items will be appended to this
  2026. * array or table. Required in case of Google
  2027. * DataTable.
  2028. * @param args
  2029. */
  2030. DataView.prototype.get = function (args) {
  2031. var me = this;
  2032. // parse the arguments
  2033. var ids, options, data;
  2034. var firstType = util.getType(arguments[0]);
  2035. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2036. // get(id(s) [, options] [, data])
  2037. ids = arguments[0]; // can be a single id or an array with ids
  2038. options = arguments[1];
  2039. data = arguments[2];
  2040. }
  2041. else {
  2042. // get([, options] [, data])
  2043. options = arguments[0];
  2044. data = arguments[1];
  2045. }
  2046. // extend the options with the default options and provided options
  2047. var viewOptions = util.extend({}, this.options, options);
  2048. // create a combined filter method when needed
  2049. if (this.options.filter && options && options.filter) {
  2050. viewOptions.filter = function (item) {
  2051. return me.options.filter(item) && options.filter(item);
  2052. }
  2053. }
  2054. // build up the call to the linked data set
  2055. var getArguments = [];
  2056. if (ids != undefined) {
  2057. getArguments.push(ids);
  2058. }
  2059. getArguments.push(viewOptions);
  2060. getArguments.push(data);
  2061. return this.data && this.data.get.apply(this.data, getArguments);
  2062. };
  2063. /**
  2064. * Get ids of all items or from a filtered set of items.
  2065. * @param {Object} [options] An Object with options. Available options:
  2066. * {function} [filter] filter items
  2067. * {String | function} [order] Order the items by
  2068. * a field name or custom sort function.
  2069. * @return {Array} ids
  2070. */
  2071. DataView.prototype.getIds = function (options) {
  2072. var ids;
  2073. if (this.data) {
  2074. var defaultFilter = this.options.filter;
  2075. var filter;
  2076. if (options && options.filter) {
  2077. if (defaultFilter) {
  2078. filter = function (item) {
  2079. return defaultFilter(item) && options.filter(item);
  2080. }
  2081. }
  2082. else {
  2083. filter = options.filter;
  2084. }
  2085. }
  2086. else {
  2087. filter = defaultFilter;
  2088. }
  2089. ids = this.data.getIds({
  2090. filter: filter,
  2091. order: options && options.order
  2092. });
  2093. }
  2094. else {
  2095. ids = [];
  2096. }
  2097. return ids;
  2098. };
  2099. /**
  2100. * Event listener. Will propagate all events from the connected data set to
  2101. * the subscribers of the DataView, but will filter the items and only trigger
  2102. * when there are changes in the filtered data set.
  2103. * @param {String} event
  2104. * @param {Object | null} params
  2105. * @param {String} senderId
  2106. * @private
  2107. */
  2108. DataView.prototype._onEvent = function (event, params, senderId) {
  2109. var i, len, id, item,
  2110. ids = params && params.items,
  2111. data = this.data,
  2112. added = [],
  2113. updated = [],
  2114. removed = [];
  2115. if (ids && data) {
  2116. switch (event) {
  2117. case 'add':
  2118. // filter the ids of the added items
  2119. for (i = 0, len = ids.length; i < len; i++) {
  2120. id = ids[i];
  2121. item = this.get(id);
  2122. if (item) {
  2123. this.ids[id] = true;
  2124. added.push(id);
  2125. }
  2126. }
  2127. break;
  2128. case 'update':
  2129. // determine the event from the views viewpoint: an updated
  2130. // item can be added, updated, or removed from this view.
  2131. for (i = 0, len = ids.length; i < len; i++) {
  2132. id = ids[i];
  2133. item = this.get(id);
  2134. if (item) {
  2135. if (this.ids[id]) {
  2136. updated.push(id);
  2137. }
  2138. else {
  2139. this.ids[id] = true;
  2140. added.push(id);
  2141. }
  2142. }
  2143. else {
  2144. if (this.ids[id]) {
  2145. delete this.ids[id];
  2146. removed.push(id);
  2147. }
  2148. else {
  2149. // nothing interesting for me :-(
  2150. }
  2151. }
  2152. }
  2153. break;
  2154. case 'remove':
  2155. // filter the ids of the removed items
  2156. for (i = 0, len = ids.length; i < len; i++) {
  2157. id = ids[i];
  2158. if (this.ids[id]) {
  2159. delete this.ids[id];
  2160. removed.push(id);
  2161. }
  2162. }
  2163. break;
  2164. }
  2165. if (added.length) {
  2166. this._trigger('add', {items: added}, senderId);
  2167. }
  2168. if (updated.length) {
  2169. this._trigger('update', {items: updated}, senderId);
  2170. }
  2171. if (removed.length) {
  2172. this._trigger('remove', {items: removed}, senderId);
  2173. }
  2174. }
  2175. };
  2176. // copy subscription functionality from DataSet
  2177. DataView.prototype.on = DataSet.prototype.on;
  2178. DataView.prototype.off = DataSet.prototype.off;
  2179. DataView.prototype._trigger = DataSet.prototype._trigger;
  2180. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2181. DataView.prototype.subscribe = DataView.prototype.on;
  2182. DataView.prototype.unsubscribe = DataView.prototype.off;
  2183. /**
  2184. * @constructor TimeStep
  2185. * The class TimeStep is an iterator for dates. You provide a start date and an
  2186. * end date. The class itself determines the best scale (step size) based on the
  2187. * provided start Date, end Date, and minimumStep.
  2188. *
  2189. * If minimumStep is provided, the step size is chosen as close as possible
  2190. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2191. * provided, the scale is set to 1 DAY.
  2192. * The minimumStep should correspond with the onscreen size of about 6 characters
  2193. *
  2194. * Alternatively, you can set a scale by hand.
  2195. * After creation, you can initialize the class by executing first(). Then you
  2196. * can iterate from the start date to the end date via next(). You can check if
  2197. * the end date is reached with the function hasNext(). After each step, you can
  2198. * retrieve the current date via getCurrent().
  2199. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2200. * days, to years.
  2201. *
  2202. * Version: 1.2
  2203. *
  2204. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2205. * or new Date(2010, 9, 21, 23, 45, 00)
  2206. * @param {Date} [end] The end date
  2207. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2208. */
  2209. TimeStep = function(start, end, minimumStep) {
  2210. // variables
  2211. this.current = new Date();
  2212. this._start = new Date();
  2213. this._end = new Date();
  2214. this.autoScale = true;
  2215. this.scale = TimeStep.SCALE.DAY;
  2216. this.step = 1;
  2217. // initialize the range
  2218. this.setRange(start, end, minimumStep);
  2219. };
  2220. /// enum scale
  2221. TimeStep.SCALE = {
  2222. MILLISECOND: 1,
  2223. SECOND: 2,
  2224. MINUTE: 3,
  2225. HOUR: 4,
  2226. DAY: 5,
  2227. WEEKDAY: 6,
  2228. MONTH: 7,
  2229. YEAR: 8
  2230. };
  2231. /**
  2232. * Set a new range
  2233. * If minimumStep is provided, the step size is chosen as close as possible
  2234. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2235. * provided, the scale is set to 1 DAY.
  2236. * The minimumStep should correspond with the onscreen size of about 6 characters
  2237. * @param {Date} [start] The start date and time.
  2238. * @param {Date} [end] The end date and time.
  2239. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2240. */
  2241. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2242. if (!(start instanceof Date) || !(end instanceof Date)) {
  2243. throw "No legal start or end date in method setRange";
  2244. }
  2245. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2246. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2247. if (this.autoScale) {
  2248. this.setMinimumStep(minimumStep);
  2249. }
  2250. };
  2251. /**
  2252. * Set the range iterator to the start date.
  2253. */
  2254. TimeStep.prototype.first = function() {
  2255. this.current = new Date(this._start.valueOf());
  2256. this.roundToMinor();
  2257. };
  2258. /**
  2259. * Round the current date to the first minor date value
  2260. * This must be executed once when the current date is set to start Date
  2261. */
  2262. TimeStep.prototype.roundToMinor = function() {
  2263. // round to floor
  2264. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2265. //noinspection FallthroughInSwitchStatementJS
  2266. switch (this.scale) {
  2267. case TimeStep.SCALE.YEAR:
  2268. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2269. this.current.setMonth(0);
  2270. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2271. case TimeStep.SCALE.DAY: // intentional fall through
  2272. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2273. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2274. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2275. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2276. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2277. }
  2278. if (this.step != 1) {
  2279. // round down to the first minor value that is a multiple of the current step size
  2280. switch (this.scale) {
  2281. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2282. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2283. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2284. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2285. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2286. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2287. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2288. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2289. default: break;
  2290. }
  2291. }
  2292. };
  2293. /**
  2294. * Check if the there is a next step
  2295. * @return {boolean} true if the current date has not passed the end date
  2296. */
  2297. TimeStep.prototype.hasNext = function () {
  2298. return (this.current.valueOf() <= this._end.valueOf());
  2299. };
  2300. /**
  2301. * Do the next step
  2302. */
  2303. TimeStep.prototype.next = function() {
  2304. var prev = this.current.valueOf();
  2305. // Two cases, needed to prevent issues with switching daylight savings
  2306. // (end of March and end of October)
  2307. if (this.current.getMonth() < 6) {
  2308. switch (this.scale) {
  2309. case TimeStep.SCALE.MILLISECOND:
  2310. this.current = new Date(this.current.valueOf() + this.step); break;
  2311. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2312. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2313. case TimeStep.SCALE.HOUR:
  2314. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2315. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2316. var h = this.current.getHours();
  2317. this.current.setHours(h - (h % this.step));
  2318. break;
  2319. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2320. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2321. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2322. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2323. default: break;
  2324. }
  2325. }
  2326. else {
  2327. switch (this.scale) {
  2328. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2329. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2330. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2331. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2332. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2333. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2334. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2335. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2336. default: break;
  2337. }
  2338. }
  2339. if (this.step != 1) {
  2340. // round down to the correct major value
  2341. switch (this.scale) {
  2342. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2343. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2344. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2345. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2346. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2347. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2348. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2349. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2350. default: break;
  2351. }
  2352. }
  2353. // safety mechanism: if current time is still unchanged, move to the end
  2354. if (this.current.valueOf() == prev) {
  2355. this.current = new Date(this._end.valueOf());
  2356. }
  2357. };
  2358. /**
  2359. * Get the current datetime
  2360. * @return {Date} current The current date
  2361. */
  2362. TimeStep.prototype.getCurrent = function() {
  2363. return this.current;
  2364. };
  2365. /**
  2366. * Set a custom scale. Autoscaling will be disabled.
  2367. * For example setScale(SCALE.MINUTES, 5) will result
  2368. * in minor steps of 5 minutes, and major steps of an hour.
  2369. *
  2370. * @param {TimeStep.SCALE} newScale
  2371. * A scale. Choose from SCALE.MILLISECOND,
  2372. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2373. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2374. * SCALE.YEAR.
  2375. * @param {Number} newStep A step size, by default 1. Choose for
  2376. * example 1, 2, 5, or 10.
  2377. */
  2378. TimeStep.prototype.setScale = function(newScale, newStep) {
  2379. this.scale = newScale;
  2380. if (newStep > 0) {
  2381. this.step = newStep;
  2382. }
  2383. this.autoScale = false;
  2384. };
  2385. /**
  2386. * Enable or disable autoscaling
  2387. * @param {boolean} enable If true, autoascaling is set true
  2388. */
  2389. TimeStep.prototype.setAutoScale = function (enable) {
  2390. this.autoScale = enable;
  2391. };
  2392. /**
  2393. * Automatically determine the scale that bests fits the provided minimum step
  2394. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2395. */
  2396. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2397. if (minimumStep == undefined) {
  2398. return;
  2399. }
  2400. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2401. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2402. var stepDay = (1000 * 60 * 60 * 24);
  2403. var stepHour = (1000 * 60 * 60);
  2404. var stepMinute = (1000 * 60);
  2405. var stepSecond = (1000);
  2406. var stepMillisecond= (1);
  2407. // find the smallest step that is larger than the provided minimumStep
  2408. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2409. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2410. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2411. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2412. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2413. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2414. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2415. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2416. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2417. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2418. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2419. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2420. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2421. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2422. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2423. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2424. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2425. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2426. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2427. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2428. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2429. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2430. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2431. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2432. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2433. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2434. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2435. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2436. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2437. };
  2438. /**
  2439. * Snap a date to a rounded value.
  2440. * The snap intervals are dependent on the current scale and step.
  2441. * @param {Date} date the date to be snapped.
  2442. * @return {Date} snappedDate
  2443. */
  2444. TimeStep.prototype.snap = function(date) {
  2445. var clone = new Date(date.valueOf());
  2446. if (this.scale == TimeStep.SCALE.YEAR) {
  2447. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2448. clone.setFullYear(Math.round(year / this.step) * this.step);
  2449. clone.setMonth(0);
  2450. clone.setDate(0);
  2451. clone.setHours(0);
  2452. clone.setMinutes(0);
  2453. clone.setSeconds(0);
  2454. clone.setMilliseconds(0);
  2455. }
  2456. else if (this.scale == TimeStep.SCALE.MONTH) {
  2457. if (clone.getDate() > 15) {
  2458. clone.setDate(1);
  2459. clone.setMonth(clone.getMonth() + 1);
  2460. // important: first set Date to 1, after that change the month.
  2461. }
  2462. else {
  2463. clone.setDate(1);
  2464. }
  2465. clone.setHours(0);
  2466. clone.setMinutes(0);
  2467. clone.setSeconds(0);
  2468. clone.setMilliseconds(0);
  2469. }
  2470. else if (this.scale == TimeStep.SCALE.DAY ||
  2471. this.scale == TimeStep.SCALE.WEEKDAY) {
  2472. //noinspection FallthroughInSwitchStatementJS
  2473. switch (this.step) {
  2474. case 5:
  2475. case 2:
  2476. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2477. default:
  2478. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2479. }
  2480. clone.setMinutes(0);
  2481. clone.setSeconds(0);
  2482. clone.setMilliseconds(0);
  2483. }
  2484. else if (this.scale == TimeStep.SCALE.HOUR) {
  2485. switch (this.step) {
  2486. case 4:
  2487. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2488. default:
  2489. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2490. }
  2491. clone.setSeconds(0);
  2492. clone.setMilliseconds(0);
  2493. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2494. //noinspection FallthroughInSwitchStatementJS
  2495. switch (this.step) {
  2496. case 15:
  2497. case 10:
  2498. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2499. clone.setSeconds(0);
  2500. break;
  2501. case 5:
  2502. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2503. default:
  2504. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2505. }
  2506. clone.setMilliseconds(0);
  2507. }
  2508. else if (this.scale == TimeStep.SCALE.SECOND) {
  2509. //noinspection FallthroughInSwitchStatementJS
  2510. switch (this.step) {
  2511. case 15:
  2512. case 10:
  2513. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2514. clone.setMilliseconds(0);
  2515. break;
  2516. case 5:
  2517. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2518. default:
  2519. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2520. }
  2521. }
  2522. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2523. var step = this.step > 5 ? this.step / 2 : 1;
  2524. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2525. }
  2526. return clone;
  2527. };
  2528. /**
  2529. * Check if the current value is a major value (for example when the step
  2530. * is DAY, a major value is each first day of the MONTH)
  2531. * @return {boolean} true if current date is major, else false.
  2532. */
  2533. TimeStep.prototype.isMajor = function() {
  2534. switch (this.scale) {
  2535. case TimeStep.SCALE.MILLISECOND:
  2536. return (this.current.getMilliseconds() == 0);
  2537. case TimeStep.SCALE.SECOND:
  2538. return (this.current.getSeconds() == 0);
  2539. case TimeStep.SCALE.MINUTE:
  2540. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2541. // Note: this is no bug. Major label is equal for both minute and hour scale
  2542. case TimeStep.SCALE.HOUR:
  2543. return (this.current.getHours() == 0);
  2544. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2545. case TimeStep.SCALE.DAY:
  2546. return (this.current.getDate() == 1);
  2547. case TimeStep.SCALE.MONTH:
  2548. return (this.current.getMonth() == 0);
  2549. case TimeStep.SCALE.YEAR:
  2550. return false;
  2551. default:
  2552. return false;
  2553. }
  2554. };
  2555. /**
  2556. * Returns formatted text for the minor axislabel, depending on the current
  2557. * date and the scale. For example when scale is MINUTE, the current time is
  2558. * formatted as "hh:mm".
  2559. * @param {Date} [date] custom date. if not provided, current date is taken
  2560. */
  2561. TimeStep.prototype.getLabelMinor = function(date) {
  2562. if (date == undefined) {
  2563. date = this.current;
  2564. }
  2565. switch (this.scale) {
  2566. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2567. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2568. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2569. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2570. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2571. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2572. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2573. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2574. default: return '';
  2575. }
  2576. };
  2577. /**
  2578. * Returns formatted text for the major axis label, depending on the current
  2579. * date and the scale. For example when scale is MINUTE, the major scale is
  2580. * hours, and the hour will be formatted as "hh".
  2581. * @param {Date} [date] custom date. if not provided, current date is taken
  2582. */
  2583. TimeStep.prototype.getLabelMajor = function(date) {
  2584. if (date == undefined) {
  2585. date = this.current;
  2586. }
  2587. //noinspection FallthroughInSwitchStatementJS
  2588. switch (this.scale) {
  2589. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2590. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2591. case TimeStep.SCALE.MINUTE:
  2592. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2593. case TimeStep.SCALE.WEEKDAY:
  2594. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2595. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2596. case TimeStep.SCALE.YEAR: return '';
  2597. default: return '';
  2598. }
  2599. };
  2600. // TODO: turn Stack into a Mixin?
  2601. /**
  2602. * @constructor Stack
  2603. * Stacks items on top of each other.
  2604. * @param {Object} [options]
  2605. */
  2606. function Stack (options) {
  2607. this.options = options || {};
  2608. this.defaultOptions = {
  2609. order: function (a, b) {
  2610. // Order: ranges over non-ranges, ranged ordered by width,
  2611. // and non-ranges ordered by start.
  2612. if (a instanceof ItemRange) {
  2613. if (b instanceof ItemRange) {
  2614. var aInt = (a.data.end - a.data.start);
  2615. var bInt = (b.data.end - b.data.start);
  2616. return (aInt - bInt) || (a.data.start - b.data.start);
  2617. }
  2618. else {
  2619. return -1;
  2620. }
  2621. }
  2622. else {
  2623. if (b instanceof ItemRange) {
  2624. return 1;
  2625. }
  2626. else {
  2627. return (a.data.start - b.data.start);
  2628. }
  2629. }
  2630. },
  2631. margin: {
  2632. item: 10,
  2633. axis: 20
  2634. }
  2635. };
  2636. }
  2637. /**
  2638. * Set options for the stack
  2639. * @param {Object} options Available options:
  2640. * {Number} [margin.item=10]
  2641. * {Number} [margin.axis=20]
  2642. * {function} [order] Stacking order
  2643. */
  2644. Stack.prototype.setOptions = function setOptions (options) {
  2645. util.extend(this.options, options);
  2646. };
  2647. /**
  2648. * Order an array with items using a predefined order function for items
  2649. * @param {Item[]} items
  2650. */
  2651. Stack.prototype.order = function order(items) {
  2652. //order the items
  2653. var order = this.options.order || this.defaultOptions.order;
  2654. if (!(typeof order === 'function')) {
  2655. throw new Error('Option order must be a function');
  2656. }
  2657. items.sort(order);
  2658. };
  2659. /**
  2660. * Order items by their start data
  2661. * @param {Item[]} items
  2662. */
  2663. Stack.prototype.orderByStart = function orderByStart(items) {
  2664. items.sort(function (a, b) {
  2665. return a.data.start - b.data.start;
  2666. });
  2667. };
  2668. /**
  2669. * Order items by their end date. If they have no end date, their start date
  2670. * is used.
  2671. * @param {Item[]} items
  2672. */
  2673. Stack.prototype.orderByEnd = function orderByEnd(items) {
  2674. items.sort(function (a, b) {
  2675. var aTime = ('end' in a.data) ? a.data.end : a.data.start,
  2676. bTime = ('end' in b.data) ? b.data.end : b.data.start;
  2677. return aTime - bTime;
  2678. });
  2679. };
  2680. /**
  2681. * Adjust vertical positions of the events such that they don't overlap each
  2682. * other.
  2683. * @param {Item[]} items All visible items
  2684. * @param {boolean} [force=false] If true, all items will be re-stacked.
  2685. * If false (default), only items having a
  2686. * top===null will be re-stacked
  2687. * @private
  2688. */
  2689. Stack.prototype.stack = function stack (items, force) {
  2690. var i,
  2691. iMax,
  2692. options = this.options,
  2693. marginItem,
  2694. marginAxis;
  2695. if (options.margin && options.margin.item !== undefined) {
  2696. marginItem = options.margin.item;
  2697. }
  2698. else {
  2699. marginItem = this.defaultOptions.margin.item
  2700. }
  2701. if (options.margin && options.margin.axis !== undefined) {
  2702. marginAxis = options.margin.axis;
  2703. }
  2704. else {
  2705. marginAxis = this.defaultOptions.margin.axis
  2706. }
  2707. if (force) {
  2708. // reset top position of all items
  2709. for (i = 0, iMax = items.length; i < iMax; i++) {
  2710. items[i].top = null;
  2711. }
  2712. }
  2713. // calculate new, non-overlapping positions
  2714. for (i = 0, iMax = items.length; i < iMax; i++) {
  2715. var item = items[i];
  2716. if (item.top === null) {
  2717. // initialize top position
  2718. item.top = marginAxis;
  2719. do {
  2720. // TODO: optimize checking for overlap. when there is a gap without items,
  2721. // you only need to check for items from the next item on, not from zero
  2722. var collidingItem = null;
  2723. for (var j = 0, jj = items.length; j < jj; j++) {
  2724. var other = items[j];
  2725. if (other.top !== null && other !== item && this.collision(item, other, marginItem)) {
  2726. collidingItem = other;
  2727. break;
  2728. }
  2729. }
  2730. if (collidingItem != null) {
  2731. // There is a collision. Reposition the event above the colliding element
  2732. item.top = collidingItem.top + collidingItem.height + marginItem;
  2733. }
  2734. } while (collidingItem);
  2735. }
  2736. }
  2737. };
  2738. /**
  2739. * Test if the two provided items collide
  2740. * The items must have parameters left, width, top, and height.
  2741. * @param {Component} a The first item
  2742. * @param {Component} b The second item
  2743. * @param {Number} margin A minimum required margin.
  2744. * If margin is provided, the two items will be
  2745. * marked colliding when they overlap or
  2746. * when the margin between the two is smaller than
  2747. * the requested margin.
  2748. * @return {boolean} true if a and b collide, else false
  2749. */
  2750. Stack.prototype.collision = function collision (a, b, margin) {
  2751. return ((a.left - margin) < (b.left + b.width) &&
  2752. (a.left + a.width + margin) > b.left &&
  2753. (a.top - margin) < (b.top + b.height) &&
  2754. (a.top + a.height + margin) > b.top);
  2755. };
  2756. /**
  2757. * @constructor Range
  2758. * A Range controls a numeric range with a start and end value.
  2759. * The Range adjusts the range based on mouse events or programmatic changes,
  2760. * and triggers events when the range is changing or has been changed.
  2761. * @param {RootPanel} root Root panel, used to subscribe to events
  2762. * @param {Panel} parent Parent panel, used to attach to the DOM
  2763. * @param {Object} [options] See description at Range.setOptions
  2764. */
  2765. function Range(root, parent, options) {
  2766. this.id = util.randomUUID();
  2767. this.start = null; // Number
  2768. this.end = null; // Number
  2769. this.root = root;
  2770. this.parent = parent;
  2771. this.options = options || {};
  2772. // drag listeners for dragging
  2773. this.root.on('dragstart', this._onDragStart.bind(this));
  2774. this.root.on('drag', this._onDrag.bind(this));
  2775. this.root.on('dragend', this._onDragEnd.bind(this));
  2776. // ignore dragging when holding
  2777. this.root.on('hold', this._onHold.bind(this));
  2778. // mouse wheel for zooming
  2779. this.root.on('mousewheel', this._onMouseWheel.bind(this));
  2780. this.root.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF
  2781. // pinch to zoom
  2782. this.root.on('touch', this._onTouch.bind(this));
  2783. this.root.on('pinch', this._onPinch.bind(this));
  2784. this.setOptions(options);
  2785. }
  2786. // turn Range into an event emitter
  2787. Emitter(Range.prototype);
  2788. /**
  2789. * Set options for the range controller
  2790. * @param {Object} options Available options:
  2791. * {Number} min Minimum value for start
  2792. * {Number} max Maximum value for end
  2793. * {Number} zoomMin Set a minimum value for
  2794. * (end - start).
  2795. * {Number} zoomMax Set a maximum value for
  2796. * (end - start).
  2797. */
  2798. Range.prototype.setOptions = function (options) {
  2799. util.extend(this.options, options);
  2800. // re-apply range with new limitations
  2801. if (this.start !== null && this.end !== null) {
  2802. this.setRange(this.start, this.end);
  2803. }
  2804. };
  2805. /**
  2806. * Test whether direction has a valid value
  2807. * @param {String} direction 'horizontal' or 'vertical'
  2808. */
  2809. function validateDirection (direction) {
  2810. if (direction != 'horizontal' && direction != 'vertical') {
  2811. throw new TypeError('Unknown direction "' + direction + '". ' +
  2812. 'Choose "horizontal" or "vertical".');
  2813. }
  2814. }
  2815. /**
  2816. * Set a new start and end range
  2817. * @param {Number} [start]
  2818. * @param {Number} [end]
  2819. */
  2820. Range.prototype.setRange = function(start, end) {
  2821. var changed = this._applyRange(start, end);
  2822. if (changed) {
  2823. var params = {
  2824. start: new Date(this.start),
  2825. end: new Date(this.end)
  2826. };
  2827. this.emit('rangechange', params);
  2828. this.emit('rangechanged', params);
  2829. }
  2830. };
  2831. /**
  2832. * Set a new start and end range. This method is the same as setRange, but
  2833. * does not trigger a range change and range changed event, and it returns
  2834. * true when the range is changed
  2835. * @param {Number} [start]
  2836. * @param {Number} [end]
  2837. * @return {Boolean} changed
  2838. * @private
  2839. */
  2840. Range.prototype._applyRange = function(start, end) {
  2841. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2842. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2843. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2844. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2845. diff;
  2846. // check for valid number
  2847. if (isNaN(newStart) || newStart === null) {
  2848. throw new Error('Invalid start "' + start + '"');
  2849. }
  2850. if (isNaN(newEnd) || newEnd === null) {
  2851. throw new Error('Invalid end "' + end + '"');
  2852. }
  2853. // prevent start < end
  2854. if (newEnd < newStart) {
  2855. newEnd = newStart;
  2856. }
  2857. // prevent start < min
  2858. if (min !== null) {
  2859. if (newStart < min) {
  2860. diff = (min - newStart);
  2861. newStart += diff;
  2862. newEnd += diff;
  2863. // prevent end > max
  2864. if (max != null) {
  2865. if (newEnd > max) {
  2866. newEnd = max;
  2867. }
  2868. }
  2869. }
  2870. }
  2871. // prevent end > max
  2872. if (max !== null) {
  2873. if (newEnd > max) {
  2874. diff = (newEnd - max);
  2875. newStart -= diff;
  2876. newEnd -= diff;
  2877. // prevent start < min
  2878. if (min != null) {
  2879. if (newStart < min) {
  2880. newStart = min;
  2881. }
  2882. }
  2883. }
  2884. }
  2885. // prevent (end-start) < zoomMin
  2886. if (this.options.zoomMin !== null) {
  2887. var zoomMin = parseFloat(this.options.zoomMin);
  2888. if (zoomMin < 0) {
  2889. zoomMin = 0;
  2890. }
  2891. if ((newEnd - newStart) < zoomMin) {
  2892. if ((this.end - this.start) === zoomMin) {
  2893. // ignore this action, we are already zoomed to the minimum
  2894. newStart = this.start;
  2895. newEnd = this.end;
  2896. }
  2897. else {
  2898. // zoom to the minimum
  2899. diff = (zoomMin - (newEnd - newStart));
  2900. newStart -= diff / 2;
  2901. newEnd += diff / 2;
  2902. }
  2903. }
  2904. }
  2905. // prevent (end-start) > zoomMax
  2906. if (this.options.zoomMax !== null) {
  2907. var zoomMax = parseFloat(this.options.zoomMax);
  2908. if (zoomMax < 0) {
  2909. zoomMax = 0;
  2910. }
  2911. if ((newEnd - newStart) > zoomMax) {
  2912. if ((this.end - this.start) === zoomMax) {
  2913. // ignore this action, we are already zoomed to the maximum
  2914. newStart = this.start;
  2915. newEnd = this.end;
  2916. }
  2917. else {
  2918. // zoom to the maximum
  2919. diff = ((newEnd - newStart) - zoomMax);
  2920. newStart += diff / 2;
  2921. newEnd -= diff / 2;
  2922. }
  2923. }
  2924. }
  2925. var changed = (this.start != newStart || this.end != newEnd);
  2926. this.start = newStart;
  2927. this.end = newEnd;
  2928. return changed;
  2929. };
  2930. /**
  2931. * Retrieve the current range.
  2932. * @return {Object} An object with start and end properties
  2933. */
  2934. Range.prototype.getRange = function() {
  2935. return {
  2936. start: this.start,
  2937. end: this.end
  2938. };
  2939. };
  2940. /**
  2941. * Calculate the conversion offset and scale for current range, based on
  2942. * the provided width
  2943. * @param {Number} width
  2944. * @returns {{offset: number, scale: number}} conversion
  2945. */
  2946. Range.prototype.conversion = function (width) {
  2947. return Range.conversion(this.start, this.end, width);
  2948. };
  2949. /**
  2950. * Static method to calculate the conversion offset and scale for a range,
  2951. * based on the provided start, end, and width
  2952. * @param {Number} start
  2953. * @param {Number} end
  2954. * @param {Number} width
  2955. * @returns {{offset: number, scale: number}} conversion
  2956. */
  2957. Range.conversion = function (start, end, width) {
  2958. if (width != 0 && (end - start != 0)) {
  2959. return {
  2960. offset: start,
  2961. scale: width / (end - start)
  2962. }
  2963. }
  2964. else {
  2965. return {
  2966. offset: 0,
  2967. scale: 1
  2968. };
  2969. }
  2970. };
  2971. // global (private) object to store drag params
  2972. var touchParams = {};
  2973. /**
  2974. * Start dragging horizontally or vertically
  2975. * @param {Event} event
  2976. * @private
  2977. */
  2978. Range.prototype._onDragStart = function(event) {
  2979. // refuse to drag when we where pinching to prevent the timeline make a jump
  2980. // when releasing the fingers in opposite order from the touch screen
  2981. if (touchParams.ignore) return;
  2982. // TODO: reckon with option movable
  2983. touchParams.start = this.start;
  2984. touchParams.end = this.end;
  2985. var frame = this.parent.frame;
  2986. if (frame) {
  2987. frame.style.cursor = 'move';
  2988. }
  2989. };
  2990. /**
  2991. * Perform dragging operating.
  2992. * @param {Event} event
  2993. * @private
  2994. */
  2995. Range.prototype._onDrag = function (event) {
  2996. var direction = this.options.direction;
  2997. validateDirection(direction);
  2998. // TODO: reckon with option movable
  2999. // refuse to drag when we where pinching to prevent the timeline make a jump
  3000. // when releasing the fingers in opposite order from the touch screen
  3001. if (touchParams.ignore) return;
  3002. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  3003. interval = (touchParams.end - touchParams.start),
  3004. width = (direction == 'horizontal') ? this.parent.width : this.parent.height,
  3005. diffRange = -delta / width * interval;
  3006. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  3007. this.emit('rangechange', {
  3008. start: new Date(this.start),
  3009. end: new Date(this.end)
  3010. });
  3011. };
  3012. /**
  3013. * Stop dragging operating.
  3014. * @param {event} event
  3015. * @private
  3016. */
  3017. Range.prototype._onDragEnd = function (event) {
  3018. // refuse to drag when we where pinching to prevent the timeline make a jump
  3019. // when releasing the fingers in opposite order from the touch screen
  3020. if (touchParams.ignore) return;
  3021. // TODO: reckon with option movable
  3022. if (this.parent.frame) {
  3023. this.parent.frame.style.cursor = 'auto';
  3024. }
  3025. // fire a rangechanged event
  3026. this.emit('rangechanged', {
  3027. start: new Date(this.start),
  3028. end: new Date(this.end)
  3029. });
  3030. };
  3031. /**
  3032. * Event handler for mouse wheel event, used to zoom
  3033. * Code from http://adomas.org/javascript-mouse-wheel/
  3034. * @param {Event} event
  3035. * @private
  3036. */
  3037. Range.prototype._onMouseWheel = function(event) {
  3038. // TODO: reckon with option zoomable
  3039. // retrieve delta
  3040. var delta = 0;
  3041. if (event.wheelDelta) { /* IE/Opera. */
  3042. delta = event.wheelDelta / 120;
  3043. } else if (event.detail) { /* Mozilla case. */
  3044. // In Mozilla, sign of delta is different than in IE.
  3045. // Also, delta is multiple of 3.
  3046. delta = -event.detail / 3;
  3047. }
  3048. // If delta is nonzero, handle it.
  3049. // Basically, delta is now positive if wheel was scrolled up,
  3050. // and negative, if wheel was scrolled down.
  3051. if (delta) {
  3052. // perform the zoom action. Delta is normally 1 or -1
  3053. // adjust a negative delta such that zooming in with delta 0.1
  3054. // equals zooming out with a delta -0.1
  3055. var scale;
  3056. if (delta < 0) {
  3057. scale = 1 - (delta / 5);
  3058. }
  3059. else {
  3060. scale = 1 / (1 + (delta / 5)) ;
  3061. }
  3062. // calculate center, the date to zoom around
  3063. var gesture = util.fakeGesture(this, event),
  3064. pointer = getPointer(gesture.center, this.parent.frame),
  3065. pointerDate = this._pointerToDate(pointer);
  3066. this.zoom(scale, pointerDate);
  3067. }
  3068. // Prevent default actions caused by mouse wheel
  3069. // (else the page and timeline both zoom and scroll)
  3070. event.preventDefault();
  3071. };
  3072. /**
  3073. * Start of a touch gesture
  3074. * @private
  3075. */
  3076. Range.prototype._onTouch = function (event) {
  3077. touchParams.start = this.start;
  3078. touchParams.end = this.end;
  3079. touchParams.ignore = false;
  3080. touchParams.center = null;
  3081. // don't move the range when dragging a selected event
  3082. // TODO: it's not so neat to have to know about the state of the ItemSet
  3083. var item = ItemSet.itemFromTarget(event);
  3084. if (item && item.selected && this.options.editable) {
  3085. touchParams.ignore = true;
  3086. }
  3087. };
  3088. /**
  3089. * On start of a hold gesture
  3090. * @private
  3091. */
  3092. Range.prototype._onHold = function () {
  3093. touchParams.ignore = true;
  3094. };
  3095. /**
  3096. * Handle pinch event
  3097. * @param {Event} event
  3098. * @private
  3099. */
  3100. Range.prototype._onPinch = function (event) {
  3101. var direction = this.options.direction;
  3102. touchParams.ignore = true;
  3103. // TODO: reckon with option zoomable
  3104. if (event.gesture.touches.length > 1) {
  3105. if (!touchParams.center) {
  3106. touchParams.center = getPointer(event.gesture.center, this.parent.frame);
  3107. }
  3108. var scale = 1 / event.gesture.scale,
  3109. initDate = this._pointerToDate(touchParams.center),
  3110. center = getPointer(event.gesture.center, this.parent.frame),
  3111. date = this._pointerToDate(this.parent, center),
  3112. delta = date - initDate; // TODO: utilize delta
  3113. // calculate new start and end
  3114. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3115. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3116. // apply new range
  3117. this.setRange(newStart, newEnd);
  3118. }
  3119. };
  3120. /**
  3121. * Helper function to calculate the center date for zooming
  3122. * @param {{x: Number, y: Number}} pointer
  3123. * @return {number} date
  3124. * @private
  3125. */
  3126. Range.prototype._pointerToDate = function (pointer) {
  3127. var conversion;
  3128. var direction = this.options.direction;
  3129. validateDirection(direction);
  3130. if (direction == 'horizontal') {
  3131. var width = this.parent.width;
  3132. conversion = this.conversion(width);
  3133. return pointer.x / conversion.scale + conversion.offset;
  3134. }
  3135. else {
  3136. var height = this.parent.height;
  3137. conversion = this.conversion(height);
  3138. return pointer.y / conversion.scale + conversion.offset;
  3139. }
  3140. };
  3141. /**
  3142. * Get the pointer location relative to the location of the dom element
  3143. * @param {{pageX: Number, pageY: Number}} touch
  3144. * @param {Element} element HTML DOM element
  3145. * @return {{x: Number, y: Number}} pointer
  3146. * @private
  3147. */
  3148. function getPointer (touch, element) {
  3149. return {
  3150. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3151. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3152. };
  3153. }
  3154. /**
  3155. * Zoom the range the given scale in or out. Start and end date will
  3156. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3157. * date around which to zoom.
  3158. * For example, try scale = 0.9 or 1.1
  3159. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3160. * values below 1 will zoom in.
  3161. * @param {Number} [center] Value representing a date around which will
  3162. * be zoomed.
  3163. */
  3164. Range.prototype.zoom = function(scale, center) {
  3165. // if centerDate is not provided, take it half between start Date and end Date
  3166. if (center == null) {
  3167. center = (this.start + this.end) / 2;
  3168. }
  3169. // calculate new start and end
  3170. var newStart = center + (this.start - center) * scale;
  3171. var newEnd = center + (this.end - center) * scale;
  3172. this.setRange(newStart, newEnd);
  3173. };
  3174. /**
  3175. * Move the range with a given delta to the left or right. Start and end
  3176. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3177. * @param {Number} delta Moving amount. Positive value will move right,
  3178. * negative value will move left
  3179. */
  3180. Range.prototype.move = function(delta) {
  3181. // zoom start Date and end Date relative to the centerDate
  3182. var diff = (this.end - this.start);
  3183. // apply new values
  3184. var newStart = this.start + diff * delta;
  3185. var newEnd = this.end + diff * delta;
  3186. // TODO: reckon with min and max range
  3187. this.start = newStart;
  3188. this.end = newEnd;
  3189. };
  3190. /**
  3191. * Move the range to a new center point
  3192. * @param {Number} moveTo New center point of the range
  3193. */
  3194. Range.prototype.moveTo = function(moveTo) {
  3195. var center = (this.start + this.end) / 2;
  3196. var diff = center - moveTo;
  3197. // calculate new start and end
  3198. var newStart = this.start - diff;
  3199. var newEnd = this.end - diff;
  3200. this.setRange(newStart, newEnd);
  3201. };
  3202. /**
  3203. * Prototype for visual components
  3204. */
  3205. function Component () {
  3206. this.id = null;
  3207. this.parent = null;
  3208. this.childs = null;
  3209. this.options = null;
  3210. this.top = 0;
  3211. this.left = 0;
  3212. this.width = 0;
  3213. this.height = 0;
  3214. }
  3215. // Turn the Component into an event emitter
  3216. Emitter(Component.prototype);
  3217. /**
  3218. * Set parameters for the frame. Parameters will be merged in current parameter
  3219. * set.
  3220. * @param {Object} options Available parameters:
  3221. * {String | function} [className]
  3222. * {String | Number | function} [left]
  3223. * {String | Number | function} [top]
  3224. * {String | Number | function} [width]
  3225. * {String | Number | function} [height]
  3226. */
  3227. Component.prototype.setOptions = function setOptions(options) {
  3228. if (options) {
  3229. util.extend(this.options, options);
  3230. this.repaint();
  3231. }
  3232. };
  3233. /**
  3234. * Get an option value by name
  3235. * The function will first check this.options object, and else will check
  3236. * this.defaultOptions.
  3237. * @param {String} name
  3238. * @return {*} value
  3239. */
  3240. Component.prototype.getOption = function getOption(name) {
  3241. var value;
  3242. if (this.options) {
  3243. value = this.options[name];
  3244. }
  3245. if (value === undefined && this.defaultOptions) {
  3246. value = this.defaultOptions[name];
  3247. }
  3248. return value;
  3249. };
  3250. /**
  3251. * Get the frame element of the component, the outer HTML DOM element.
  3252. * @returns {HTMLElement | null} frame
  3253. */
  3254. Component.prototype.getFrame = function getFrame() {
  3255. // should be implemented by the component
  3256. return null;
  3257. };
  3258. /**
  3259. * Repaint the component
  3260. * @return {boolean} Returns true if the component is resized
  3261. */
  3262. Component.prototype.repaint = function repaint() {
  3263. // should be implemented by the component
  3264. return false;
  3265. };
  3266. /**
  3267. * Test whether the component is resized since the last time _isResized() was
  3268. * called.
  3269. * @return {Boolean} Returns true if the component is resized
  3270. * @private
  3271. */
  3272. Component.prototype._isResized = function _isResized() {
  3273. var resized = (this._previousWidth !== this.width || this._previousHeight !== this.height);
  3274. this._previousWidth = this.width;
  3275. this._previousHeight = this.height;
  3276. return resized;
  3277. };
  3278. /**
  3279. * A panel can contain components
  3280. * @param {Object} [options] Available parameters:
  3281. * {String | Number | function} [left]
  3282. * {String | Number | function} [top]
  3283. * {String | Number | function} [width]
  3284. * {String | Number | function} [height]
  3285. * {String | function} [className]
  3286. * @constructor Panel
  3287. * @extends Component
  3288. */
  3289. function Panel(options) {
  3290. this.id = util.randomUUID();
  3291. this.parent = null;
  3292. this.childs = [];
  3293. this.options = options || {};
  3294. // create frame
  3295. this.frame = document.createElement('div');
  3296. }
  3297. Panel.prototype = new Component();
  3298. /**
  3299. * Set options. Will extend the current options.
  3300. * @param {Object} [options] Available parameters:
  3301. * {String | function} [className]
  3302. * {String | Number | function} [left]
  3303. * {String | Number | function} [top]
  3304. * {String | Number | function} [width]
  3305. * {String | Number | function} [height]
  3306. */
  3307. Panel.prototype.setOptions = Component.prototype.setOptions;
  3308. /**
  3309. * Get the outer frame of the panel
  3310. * @returns {HTMLElement} frame
  3311. */
  3312. Panel.prototype.getFrame = function () {
  3313. return this.frame;
  3314. };
  3315. /**
  3316. * Append a child to the panel
  3317. * @param {Component} child
  3318. */
  3319. Panel.prototype.appendChild = function (child) {
  3320. this.childs.push(child);
  3321. child.parent = this;
  3322. // attach to the DOM
  3323. var frame = child.getFrame();
  3324. if (frame) {
  3325. if (frame.parentNode) {
  3326. frame.parentNode.removeChild(frame);
  3327. }
  3328. this.frame.appendChild(frame);
  3329. }
  3330. };
  3331. /**
  3332. * Insert a child to the panel
  3333. * @param {Component} child
  3334. * @param {Component} beforeChild
  3335. */
  3336. Panel.prototype.insertBefore = function (child, beforeChild) {
  3337. var index = this.childs.indexOf(beforeChild);
  3338. if (index != -1) {
  3339. this.childs.splice(index, 0, child);
  3340. child.parent = this;
  3341. // attach to the DOM
  3342. var frame = child.getFrame();
  3343. if (frame) {
  3344. if (frame.parentNode) {
  3345. frame.parentNode.removeChild(frame);
  3346. }
  3347. var beforeFrame = beforeChild.getFrame();
  3348. if (beforeFrame) {
  3349. this.frame.insertBefore(frame, beforeFrame);
  3350. }
  3351. else {
  3352. this.frame.appendChild(frame);
  3353. }
  3354. }
  3355. }
  3356. };
  3357. /**
  3358. * Remove a child from the panel
  3359. * @param {Component} child
  3360. */
  3361. Panel.prototype.removeChild = function (child) {
  3362. var index = this.childs.indexOf(child);
  3363. if (index != -1) {
  3364. this.childs.splice(index, 1);
  3365. child.parent = null;
  3366. // remove from the DOM
  3367. var frame = child.getFrame();
  3368. if (frame && frame.parentNode) {
  3369. this.frame.removeChild(frame);
  3370. }
  3371. }
  3372. };
  3373. /**
  3374. * Test whether the panel contains given child
  3375. * @param {Component} child
  3376. */
  3377. Panel.prototype.hasChild = function (child) {
  3378. var index = this.childs.indexOf(child);
  3379. return (index != -1);
  3380. };
  3381. /**
  3382. * Repaint the component
  3383. * @return {boolean} Returns true if the component was resized since previous repaint
  3384. */
  3385. Panel.prototype.repaint = function () {
  3386. var asString = util.option.asString,
  3387. options = this.options,
  3388. frame = this.getFrame();
  3389. // update className
  3390. frame.className = 'vpanel' + (options.className ? (' ' + asString(options.className)) : '');
  3391. // repaint the child components
  3392. var childsResized = this._repaintChilds();
  3393. // update frame size
  3394. this._updateSize();
  3395. return this._isResized() || childsResized;
  3396. };
  3397. /**
  3398. * Repaint all childs of the panel
  3399. * @return {boolean} Returns true if the component is resized
  3400. * @private
  3401. */
  3402. Panel.prototype._repaintChilds = function () {
  3403. var resized = false;
  3404. for (var i = 0, ii = this.childs.length; i < ii; i++) {
  3405. resized = this.childs[i].repaint() || resized;
  3406. }
  3407. return resized;
  3408. };
  3409. /**
  3410. * Apply the size from options to the panel, and recalculate it's actual size.
  3411. * @private
  3412. */
  3413. Panel.prototype._updateSize = function () {
  3414. // apply size
  3415. this.frame.style.top = util.option.asSize(this.options.top);
  3416. this.frame.style.bottom = util.option.asSize(this.options.bottom);
  3417. this.frame.style.left = util.option.asSize(this.options.left);
  3418. this.frame.style.right = util.option.asSize(this.options.right);
  3419. this.frame.style.width = util.option.asSize(this.options.width, '100%');
  3420. this.frame.style.height = util.option.asSize(this.options.height, '');
  3421. // get actual size
  3422. this.top = this.frame.offsetTop;
  3423. this.left = this.frame.offsetLeft;
  3424. this.width = this.frame.offsetWidth;
  3425. this.height = this.frame.offsetHeight;
  3426. };
  3427. /**
  3428. * A root panel can hold components. The root panel must be initialized with
  3429. * a DOM element as container.
  3430. * @param {HTMLElement} container
  3431. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3432. * @constructor RootPanel
  3433. * @extends Panel
  3434. */
  3435. function RootPanel(container, options) {
  3436. this.id = util.randomUUID();
  3437. this.container = container;
  3438. this.options = options || {};
  3439. this.defaultOptions = {
  3440. autoResize: true
  3441. };
  3442. // create the HTML DOM
  3443. this._create();
  3444. // attach the root panel to the provided container
  3445. if (!this.container) throw new Error('Cannot repaint root panel: no container attached');
  3446. this.container.appendChild(this.getFrame());
  3447. this._initWatch();
  3448. }
  3449. RootPanel.prototype = new Panel();
  3450. /**
  3451. * Create the HTML DOM for the root panel
  3452. */
  3453. RootPanel.prototype._create = function _create() {
  3454. // create frame
  3455. this.frame = document.createElement('div');
  3456. // create event listeners for all interesting events, these events will be
  3457. // emitted via emitter
  3458. this.hammer = Hammer(this.frame, {
  3459. prevent_default: true
  3460. });
  3461. this.listeners = {};
  3462. var me = this;
  3463. var events = [
  3464. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3465. 'dragstart', 'drag', 'dragend',
  3466. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3467. ];
  3468. events.forEach(function (event) {
  3469. var listener = function () {
  3470. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3471. me.emit.apply(me, args);
  3472. };
  3473. me.hammer.on(event, listener);
  3474. me.listeners[event] = listener;
  3475. });
  3476. };
  3477. /**
  3478. * Set options. Will extend the current options.
  3479. * @param {Object} [options] Available parameters:
  3480. * {String | function} [className]
  3481. * {String | Number | function} [left]
  3482. * {String | Number | function} [top]
  3483. * {String | Number | function} [width]
  3484. * {String | Number | function} [height]
  3485. * {Boolean | function} [autoResize]
  3486. */
  3487. RootPanel.prototype.setOptions = function setOptions(options) {
  3488. if (options) {
  3489. util.extend(this.options, options);
  3490. this.repaint();
  3491. this._initWatch();
  3492. }
  3493. };
  3494. /**
  3495. * Get the frame of the root panel
  3496. */
  3497. RootPanel.prototype.getFrame = function getFrame() {
  3498. return this.frame;
  3499. };
  3500. /**
  3501. * Repaint the root panel
  3502. */
  3503. RootPanel.prototype.repaint = function repaint() {
  3504. // update class name
  3505. var options = this.options;
  3506. var className = 'vis timeline rootpanel ' + options.orientation + (options.editable ? ' editable' : '');
  3507. if (options.className) className += ' ' + util.option.asString(className);
  3508. this.frame.className = className;
  3509. // repaint the child components
  3510. var childsResized = this._repaintChilds();
  3511. // update frame size
  3512. this.frame.style.maxHeight = util.option.asSize(this.options.maxHeight, '');
  3513. this._updateSize();
  3514. // if the root panel or any of its childs is resized, repaint again,
  3515. // as other components may need to be resized accordingly
  3516. var resized = this._isResized() || childsResized;
  3517. if (resized) {
  3518. setTimeout(this.repaint.bind(this), 0);
  3519. }
  3520. };
  3521. /**
  3522. * Initialize watching when option autoResize is true
  3523. * @private
  3524. */
  3525. RootPanel.prototype._initWatch = function _initWatch() {
  3526. var autoResize = this.getOption('autoResize');
  3527. if (autoResize) {
  3528. this._watch();
  3529. }
  3530. else {
  3531. this._unwatch();
  3532. }
  3533. };
  3534. /**
  3535. * Watch for changes in the size of the frame. On resize, the Panel will
  3536. * automatically redraw itself.
  3537. * @private
  3538. */
  3539. RootPanel.prototype._watch = function _watch() {
  3540. var me = this;
  3541. this._unwatch();
  3542. var checkSize = function checkSize() {
  3543. var autoResize = me.getOption('autoResize');
  3544. if (!autoResize) {
  3545. // stop watching when the option autoResize is changed to false
  3546. me._unwatch();
  3547. return;
  3548. }
  3549. if (me.frame) {
  3550. // check whether the frame is resized
  3551. if ((me.frame.clientWidth != me.lastWidth) ||
  3552. (me.frame.clientHeight != me.lastHeight)) {
  3553. me.lastWidth = me.frame.clientWidth;
  3554. me.lastHeight = me.frame.clientHeight;
  3555. me.repaint();
  3556. // TODO: emit a resize event instead?
  3557. }
  3558. }
  3559. };
  3560. // TODO: automatically cleanup the event listener when the frame is deleted
  3561. util.addEventListener(window, 'resize', checkSize);
  3562. this.watchTimer = setInterval(checkSize, 1000);
  3563. };
  3564. /**
  3565. * Stop watching for a resize of the frame.
  3566. * @private
  3567. */
  3568. RootPanel.prototype._unwatch = function _unwatch() {
  3569. if (this.watchTimer) {
  3570. clearInterval(this.watchTimer);
  3571. this.watchTimer = undefined;
  3572. }
  3573. // TODO: remove event listener on window.resize
  3574. };
  3575. /**
  3576. * A horizontal time axis
  3577. * @param {Object} [options] See TimeAxis.setOptions for the available
  3578. * options.
  3579. * @constructor TimeAxis
  3580. * @extends Component
  3581. */
  3582. function TimeAxis (options) {
  3583. this.id = util.randomUUID();
  3584. this.dom = {
  3585. majorLines: [],
  3586. majorTexts: [],
  3587. minorLines: [],
  3588. minorTexts: [],
  3589. redundant: {
  3590. majorLines: [],
  3591. majorTexts: [],
  3592. minorLines: [],
  3593. minorTexts: []
  3594. }
  3595. };
  3596. this.props = {
  3597. range: {
  3598. start: 0,
  3599. end: 0,
  3600. minimumStep: 0
  3601. },
  3602. lineTop: 0
  3603. };
  3604. this.options = options || {};
  3605. this.defaultOptions = {
  3606. orientation: 'bottom', // supported: 'top', 'bottom'
  3607. // TODO: implement timeaxis orientations 'left' and 'right'
  3608. showMinorLabels: true,
  3609. showMajorLabels: true
  3610. };
  3611. this.range = null;
  3612. // create the HTML DOM
  3613. this._create();
  3614. }
  3615. TimeAxis.prototype = new Component();
  3616. // TODO: comment options
  3617. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3618. /**
  3619. * Create the HTML DOM for the TimeAxis
  3620. */
  3621. TimeAxis.prototype._create = function _create() {
  3622. this.frame = document.createElement('div');
  3623. };
  3624. /**
  3625. * Set a range (start and end)
  3626. * @param {Range | Object} range A Range or an object containing start and end.
  3627. */
  3628. TimeAxis.prototype.setRange = function (range) {
  3629. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3630. throw new TypeError('Range must be an instance of Range, ' +
  3631. 'or an object containing start and end.');
  3632. }
  3633. this.range = range;
  3634. };
  3635. /**
  3636. * Get the outer frame of the time axis
  3637. * @return {HTMLElement} frame
  3638. */
  3639. TimeAxis.prototype.getFrame = function getFrame() {
  3640. return this.frame;
  3641. };
  3642. /**
  3643. * Repaint the component
  3644. * @return {boolean} Returns true if the component is resized
  3645. */
  3646. TimeAxis.prototype.repaint = function () {
  3647. var asSize = util.option.asSize,
  3648. options = this.options,
  3649. props = this.props,
  3650. frame = this.frame;
  3651. // update classname
  3652. frame.className = 'timeaxis'; // TODO: add className from options if defined
  3653. var parent = frame.parentNode;
  3654. if (parent) {
  3655. // calculate character width and height
  3656. this._calculateCharSize();
  3657. // TODO: recalculate sizes only needed when parent is resized or options is changed
  3658. var orientation = this.getOption('orientation'),
  3659. showMinorLabels = this.getOption('showMinorLabels'),
  3660. showMajorLabels = this.getOption('showMajorLabels');
  3661. // determine the width and height of the elemens for the axis
  3662. var parentHeight = this.parent.height;
  3663. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  3664. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  3665. this.height = props.minorLabelHeight + props.majorLabelHeight;
  3666. this.width = frame.offsetWidth; // TODO: only update the width when the frame is resized?
  3667. props.minorLineHeight = parentHeight + props.minorLabelHeight;
  3668. props.minorLineWidth = 1; // TODO: really calculate width
  3669. props.majorLineHeight = parentHeight + this.height;
  3670. props.majorLineWidth = 1; // TODO: really calculate width
  3671. // take frame offline while updating (is almost twice as fast)
  3672. var beforeChild = frame.nextSibling;
  3673. parent.removeChild(frame);
  3674. // TODO: top/bottom positioning should be determined by options set in the Timeline, not here
  3675. if (orientation == 'top') {
  3676. frame.style.top = '0';
  3677. frame.style.left = '0';
  3678. frame.style.bottom = '';
  3679. frame.style.width = asSize(options.width, '100%');
  3680. frame.style.height = this.height + 'px';
  3681. }
  3682. else { // bottom
  3683. frame.style.top = '';
  3684. frame.style.bottom = '0';
  3685. frame.style.left = '0';
  3686. frame.style.width = asSize(options.width, '100%');
  3687. frame.style.height = this.height + 'px';
  3688. }
  3689. this._repaintLabels();
  3690. this._repaintLine();
  3691. // put frame online again
  3692. if (beforeChild) {
  3693. parent.insertBefore(frame, beforeChild);
  3694. }
  3695. else {
  3696. parent.appendChild(frame)
  3697. }
  3698. }
  3699. return this._isResized();
  3700. };
  3701. /**
  3702. * Repaint major and minor text labels and vertical grid lines
  3703. * @private
  3704. */
  3705. TimeAxis.prototype._repaintLabels = function () {
  3706. var orientation = this.getOption('orientation');
  3707. // calculate range and step
  3708. var start = util.convert(this.range.start, 'Number'),
  3709. end = util.convert(this.range.end, 'Number'),
  3710. minimumStep = this.options.toTime((this.props.minorCharWidth || 10) * 5).valueOf()
  3711. -this.options.toTime(0).valueOf();
  3712. var step = new TimeStep(new Date(start), new Date(end), minimumStep);
  3713. this.step = step;
  3714. // Move all DOM elements to a "redundant" list, where they
  3715. // can be picked for re-use, and clear the lists with lines and texts.
  3716. // At the end of the function _repaintLabels, left over elements will be cleaned up
  3717. var dom = this.dom;
  3718. dom.redundant.majorLines = dom.majorLines;
  3719. dom.redundant.majorTexts = dom.majorTexts;
  3720. dom.redundant.minorLines = dom.minorLines;
  3721. dom.redundant.minorTexts = dom.minorTexts;
  3722. dom.majorLines = [];
  3723. dom.majorTexts = [];
  3724. dom.minorLines = [];
  3725. dom.minorTexts = [];
  3726. step.first();
  3727. var xFirstMajorLabel = undefined;
  3728. var max = 0;
  3729. while (step.hasNext() && max < 1000) {
  3730. max++;
  3731. var cur = step.getCurrent(),
  3732. x = this.options.toScreen(cur),
  3733. isMajor = step.isMajor();
  3734. // TODO: lines must have a width, such that we can create css backgrounds
  3735. if (this.getOption('showMinorLabels')) {
  3736. this._repaintMinorText(x, step.getLabelMinor(), orientation);
  3737. }
  3738. if (isMajor && this.getOption('showMajorLabels')) {
  3739. if (x > 0) {
  3740. if (xFirstMajorLabel == undefined) {
  3741. xFirstMajorLabel = x;
  3742. }
  3743. this._repaintMajorText(x, step.getLabelMajor(), orientation);
  3744. }
  3745. this._repaintMajorLine(x, orientation);
  3746. }
  3747. else {
  3748. this._repaintMinorLine(x, orientation);
  3749. }
  3750. step.next();
  3751. }
  3752. // create a major label on the left when needed
  3753. if (this.getOption('showMajorLabels')) {
  3754. var leftTime = this.options.toTime(0),
  3755. leftText = step.getLabelMajor(leftTime),
  3756. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  3757. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3758. this._repaintMajorText(0, leftText, orientation);
  3759. }
  3760. }
  3761. // Cleanup leftover DOM elements from the redundant list
  3762. util.forEach(this.dom.redundant, function (arr) {
  3763. while (arr.length) {
  3764. var elem = arr.pop();
  3765. if (elem && elem.parentNode) {
  3766. elem.parentNode.removeChild(elem);
  3767. }
  3768. }
  3769. });
  3770. };
  3771. /**
  3772. * Create a minor label for the axis at position x
  3773. * @param {Number} x
  3774. * @param {String} text
  3775. * @param {String} orientation "top" or "bottom" (default)
  3776. * @private
  3777. */
  3778. TimeAxis.prototype._repaintMinorText = function (x, text, orientation) {
  3779. // reuse redundant label
  3780. var label = this.dom.redundant.minorTexts.shift();
  3781. if (!label) {
  3782. // create new label
  3783. var content = document.createTextNode('');
  3784. label = document.createElement('div');
  3785. label.appendChild(content);
  3786. label.className = 'text minor';
  3787. this.frame.appendChild(label);
  3788. }
  3789. this.dom.minorTexts.push(label);
  3790. label.childNodes[0].nodeValue = text;
  3791. if (orientation == 'top') {
  3792. label.style.top = this.props.majorLabelHeight + 'px';
  3793. label.style.bottom = '';
  3794. }
  3795. else {
  3796. label.style.top = '';
  3797. label.style.bottom = this.props.majorLabelHeight + 'px';
  3798. }
  3799. label.style.left = x + 'px';
  3800. //label.title = title; // TODO: this is a heavy operation
  3801. };
  3802. /**
  3803. * Create a Major label for the axis at position x
  3804. * @param {Number} x
  3805. * @param {String} text
  3806. * @param {String} orientation "top" or "bottom" (default)
  3807. * @private
  3808. */
  3809. TimeAxis.prototype._repaintMajorText = function (x, text, orientation) {
  3810. // reuse redundant label
  3811. var label = this.dom.redundant.majorTexts.shift();
  3812. if (!label) {
  3813. // create label
  3814. var content = document.createTextNode(text);
  3815. label = document.createElement('div');
  3816. label.className = 'text major';
  3817. label.appendChild(content);
  3818. this.frame.appendChild(label);
  3819. }
  3820. this.dom.majorTexts.push(label);
  3821. label.childNodes[0].nodeValue = text;
  3822. //label.title = title; // TODO: this is a heavy operation
  3823. if (orientation == 'top') {
  3824. label.style.top = '0px';
  3825. label.style.bottom = '';
  3826. }
  3827. else {
  3828. label.style.top = '';
  3829. label.style.bottom = '0px';
  3830. }
  3831. label.style.left = x + 'px';
  3832. };
  3833. /**
  3834. * Create a minor line for the axis at position x
  3835. * @param {Number} x
  3836. * @param {String} orientation "top" or "bottom" (default)
  3837. * @private
  3838. */
  3839. TimeAxis.prototype._repaintMinorLine = function (x, orientation) {
  3840. // reuse redundant line
  3841. var line = this.dom.redundant.minorLines.shift();
  3842. if (!line) {
  3843. // create vertical line
  3844. line = document.createElement('div');
  3845. line.className = 'grid vertical minor';
  3846. this.frame.appendChild(line);
  3847. }
  3848. this.dom.minorLines.push(line);
  3849. var props = this.props;
  3850. if (orientation == 'top') {
  3851. line.style.top = this.props.majorLabelHeight + 'px';
  3852. line.style.bottom = '';
  3853. }
  3854. else {
  3855. line.style.top = '';
  3856. line.style.bottom = this.props.majorLabelHeight + 'px';
  3857. }
  3858. line.style.height = props.minorLineHeight + 'px';
  3859. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  3860. };
  3861. /**
  3862. * Create a Major line for the axis at position x
  3863. * @param {Number} x
  3864. * @param {String} orientation "top" or "bottom" (default)
  3865. * @private
  3866. */
  3867. TimeAxis.prototype._repaintMajorLine = function (x, orientation) {
  3868. // reuse redundant line
  3869. var line = this.dom.redundant.majorLines.shift();
  3870. if (!line) {
  3871. // create vertical line
  3872. line = document.createElement('DIV');
  3873. line.className = 'grid vertical major';
  3874. this.frame.appendChild(line);
  3875. }
  3876. this.dom.majorLines.push(line);
  3877. var props = this.props;
  3878. if (orientation == 'top') {
  3879. line.style.top = '0px';
  3880. line.style.bottom = '';
  3881. }
  3882. else {
  3883. line.style.top = '';
  3884. line.style.bottom = '0px';
  3885. }
  3886. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  3887. line.style.height = props.majorLineHeight + 'px';
  3888. };
  3889. /**
  3890. * Repaint the horizontal line for the axis
  3891. * @private
  3892. */
  3893. TimeAxis.prototype._repaintLine = function() {
  3894. var line = this.dom.line,
  3895. frame = this.frame,
  3896. orientation = this.getOption('orientation');
  3897. // line before all axis elements
  3898. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  3899. if (line) {
  3900. // put this line at the end of all childs
  3901. frame.removeChild(line);
  3902. frame.appendChild(line);
  3903. }
  3904. else {
  3905. // create the axis line
  3906. line = document.createElement('div');
  3907. line.className = 'grid horizontal major';
  3908. frame.appendChild(line);
  3909. this.dom.line = line;
  3910. }
  3911. if (orientation == 'top') {
  3912. line.style.top = this.height + 'px';
  3913. line.style.bottom = '';
  3914. }
  3915. else {
  3916. line.style.top = '';
  3917. line.style.bottom = this.height + 'px';
  3918. }
  3919. }
  3920. else {
  3921. if (line && line.parentNode) {
  3922. line.parentNode.removeChild(line);
  3923. delete this.dom.line;
  3924. }
  3925. }
  3926. };
  3927. /**
  3928. * Determine the size of text on the axis (both major and minor axis).
  3929. * The size is calculated only once and then cached in this.props.
  3930. * @private
  3931. */
  3932. TimeAxis.prototype._calculateCharSize = function () {
  3933. // determine the char width and height on the minor axis
  3934. if (!('minorCharHeight' in this.props)) {
  3935. var textMinor = document.createTextNode('0');
  3936. var measureCharMinor = document.createElement('DIV');
  3937. measureCharMinor.className = 'text minor measure';
  3938. measureCharMinor.appendChild(textMinor);
  3939. this.frame.appendChild(measureCharMinor);
  3940. this.props.minorCharHeight = measureCharMinor.clientHeight;
  3941. this.props.minorCharWidth = measureCharMinor.clientWidth;
  3942. this.frame.removeChild(measureCharMinor);
  3943. }
  3944. if (!('majorCharHeight' in this.props)) {
  3945. var textMajor = document.createTextNode('0');
  3946. var measureCharMajor = document.createElement('DIV');
  3947. measureCharMajor.className = 'text major measure';
  3948. measureCharMajor.appendChild(textMajor);
  3949. this.frame.appendChild(measureCharMajor);
  3950. this.props.majorCharHeight = measureCharMajor.clientHeight;
  3951. this.props.majorCharWidth = measureCharMajor.clientWidth;
  3952. this.frame.removeChild(measureCharMajor);
  3953. }
  3954. };
  3955. /**
  3956. * Snap a date to a rounded value.
  3957. * The snap intervals are dependent on the current scale and step.
  3958. * @param {Date} date the date to be snapped.
  3959. * @return {Date} snappedDate
  3960. */
  3961. TimeAxis.prototype.snap = function snap (date) {
  3962. return this.step.snap(date);
  3963. };
  3964. /**
  3965. * A current time bar
  3966. * @param {Range} range
  3967. * @param {Object} [options] Available parameters:
  3968. * {Boolean} [showCurrentTime]
  3969. * @constructor CurrentTime
  3970. * @extends Component
  3971. */
  3972. function CurrentTime (range, options) {
  3973. this.id = util.randomUUID();
  3974. this.range = range;
  3975. this.options = options || {};
  3976. this.defaultOptions = {
  3977. showCurrentTime: false
  3978. };
  3979. this._create();
  3980. }
  3981. CurrentTime.prototype = new Component();
  3982. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  3983. /**
  3984. * Create the HTML DOM for the current time bar
  3985. * @private
  3986. */
  3987. CurrentTime.prototype._create = function _create () {
  3988. var bar = document.createElement('div');
  3989. bar.className = 'currenttime';
  3990. bar.style.position = 'absolute';
  3991. bar.style.top = '0px';
  3992. bar.style.height = '100%';
  3993. this.bar = bar;
  3994. };
  3995. /**
  3996. * Get the frame element of the current time bar
  3997. * @returns {HTMLElement} frame
  3998. */
  3999. CurrentTime.prototype.getFrame = function getFrame() {
  4000. return this.bar;
  4001. };
  4002. /**
  4003. * Repaint the component
  4004. * @return {boolean} Returns true if the component is resized
  4005. */
  4006. CurrentTime.prototype.repaint = function repaint() {
  4007. var parent = this.parent;
  4008. var now = new Date();
  4009. var x = this.options.toScreen(now);
  4010. this.bar.style.left = x + 'px';
  4011. this.bar.title = 'Current time: ' + now;
  4012. return false;
  4013. };
  4014. /**
  4015. * Start auto refreshing the current time bar
  4016. */
  4017. CurrentTime.prototype.start = function start() {
  4018. var me = this;
  4019. function update () {
  4020. me.stop();
  4021. // determine interval to refresh
  4022. var scale = me.range.conversion(me.parent.width).scale;
  4023. var interval = 1 / scale / 10;
  4024. if (interval < 30) interval = 30;
  4025. if (interval > 1000) interval = 1000;
  4026. me.repaint();
  4027. // start a timer to adjust for the new time
  4028. me.currentTimeTimer = setTimeout(update, interval);
  4029. }
  4030. update();
  4031. };
  4032. /**
  4033. * Stop auto refreshing the current time bar
  4034. */
  4035. CurrentTime.prototype.stop = function stop() {
  4036. if (this.currentTimeTimer !== undefined) {
  4037. clearTimeout(this.currentTimeTimer);
  4038. delete this.currentTimeTimer;
  4039. }
  4040. };
  4041. /**
  4042. * A custom time bar
  4043. * @param {Object} [options] Available parameters:
  4044. * {Boolean} [showCustomTime]
  4045. * @constructor CustomTime
  4046. * @extends Component
  4047. */
  4048. function CustomTime (options) {
  4049. this.id = util.randomUUID();
  4050. this.options = options || {};
  4051. this.defaultOptions = {
  4052. showCustomTime: false
  4053. };
  4054. this.customTime = new Date();
  4055. this.eventParams = {}; // stores state parameters while dragging the bar
  4056. // create the DOM
  4057. this._create();
  4058. }
  4059. CustomTime.prototype = new Component();
  4060. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4061. /**
  4062. * Create the DOM for the custom time
  4063. * @private
  4064. */
  4065. CustomTime.prototype._create = function _create () {
  4066. var bar = document.createElement('div');
  4067. bar.className = 'customtime';
  4068. bar.style.position = 'absolute';
  4069. bar.style.top = '0px';
  4070. bar.style.height = '100%';
  4071. this.bar = bar;
  4072. var drag = document.createElement('div');
  4073. drag.style.position = 'relative';
  4074. drag.style.top = '0px';
  4075. drag.style.left = '-10px';
  4076. drag.style.height = '100%';
  4077. drag.style.width = '20px';
  4078. bar.appendChild(drag);
  4079. // attach event listeners
  4080. this.hammer = Hammer(bar, {
  4081. prevent_default: true
  4082. });
  4083. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4084. this.hammer.on('drag', this._onDrag.bind(this));
  4085. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4086. };
  4087. /**
  4088. * Get the frame element of the custom time bar
  4089. * @returns {HTMLElement} frame
  4090. */
  4091. CustomTime.prototype.getFrame = function getFrame() {
  4092. return this.bar;
  4093. };
  4094. /**
  4095. * Repaint the component
  4096. * @return {boolean} Returns true if the component is resized
  4097. */
  4098. CustomTime.prototype.repaint = function () {
  4099. var x = this.options.toScreen(this.customTime);
  4100. this.bar.style.left = x + 'px';
  4101. this.bar.title = 'Time: ' + this.customTime;
  4102. return false;
  4103. };
  4104. /**
  4105. * Set custom time.
  4106. * @param {Date} time
  4107. */
  4108. CustomTime.prototype.setCustomTime = function(time) {
  4109. this.customTime = new Date(time.valueOf());
  4110. this.repaint();
  4111. };
  4112. /**
  4113. * Retrieve the current custom time.
  4114. * @return {Date} customTime
  4115. */
  4116. CustomTime.prototype.getCustomTime = function() {
  4117. return new Date(this.customTime.valueOf());
  4118. };
  4119. /**
  4120. * Start moving horizontally
  4121. * @param {Event} event
  4122. * @private
  4123. */
  4124. CustomTime.prototype._onDragStart = function(event) {
  4125. this.eventParams.dragging = true;
  4126. this.eventParams.customTime = this.customTime;
  4127. event.stopPropagation();
  4128. event.preventDefault();
  4129. };
  4130. /**
  4131. * Perform moving operating.
  4132. * @param {Event} event
  4133. * @private
  4134. */
  4135. CustomTime.prototype._onDrag = function (event) {
  4136. if (!this.eventParams.dragging) return;
  4137. var deltaX = event.gesture.deltaX,
  4138. x = this.options.toScreen(this.eventParams.customTime) + deltaX,
  4139. time = this.options.toTime(x);
  4140. this.setCustomTime(time);
  4141. // fire a timechange event
  4142. this.emit('timechange', {
  4143. time: new Date(this.customTime.valueOf())
  4144. });
  4145. event.stopPropagation();
  4146. event.preventDefault();
  4147. };
  4148. /**
  4149. * Stop moving operating.
  4150. * @param {event} event
  4151. * @private
  4152. */
  4153. CustomTime.prototype._onDragEnd = function (event) {
  4154. if (!this.eventParams.dragging) return;
  4155. // fire a timechanged event
  4156. this.emit('timechanged', {
  4157. time: new Date(this.customTime.valueOf())
  4158. });
  4159. event.stopPropagation();
  4160. event.preventDefault();
  4161. };
  4162. /**
  4163. * An ItemSet holds a set of items and ranges which can be displayed in a
  4164. * range. The width is determined by the parent of the ItemSet, and the height
  4165. * is determined by the size of the items.
  4166. * @param {Panel} backgroundPanel Panel which can be used to display the
  4167. * vertical lines of box items.
  4168. * @param {Panel} axisPanel Panel on the axis where the dots of box-items
  4169. * can be displayed.
  4170. * @param {Object} [options] See ItemSet.setOptions for the available options.
  4171. * @constructor ItemSet
  4172. * @extends Panel
  4173. */
  4174. function ItemSet(backgroundPanel, axisPanel, options) {
  4175. this.id = util.randomUUID();
  4176. // one options object is shared by this itemset and all its items
  4177. this.options = options || {};
  4178. this.backgroundPanel = backgroundPanel;
  4179. this.axisPanel = axisPanel;
  4180. this.itemOptions = Object.create(this.options);
  4181. this.dom = {};
  4182. this.hammer = null;
  4183. var me = this;
  4184. this.itemsData = null; // DataSet
  4185. this.range = null; // Range or Object {start: number, end: number}
  4186. // data change listeners
  4187. this.listeners = {
  4188. 'add': function (event, params, senderId) {
  4189. if (senderId != me.id) me._onAdd(params.items);
  4190. },
  4191. 'update': function (event, params, senderId) {
  4192. if (senderId != me.id) me._onUpdate(params.items);
  4193. },
  4194. 'remove': function (event, params, senderId) {
  4195. if (senderId != me.id) me._onRemove(params.items);
  4196. }
  4197. };
  4198. this.items = {}; // object with an Item for every data item
  4199. this.orderedItems = {
  4200. byStart: [],
  4201. byEnd: []
  4202. };
  4203. this.visibleItems = []; // visible, ordered items
  4204. this.visibleItemsStart = 0; // start index of visible items in this.orderedItems // TODO: cleanup
  4205. this.visibleItemsEnd = 0; // start index of visible items in this.orderedItems // TODO: cleanup
  4206. this.selection = []; // list with the ids of all selected nodes
  4207. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4208. this.stack = new Stack(Object.create(this.options));
  4209. this.stackDirty = true; // if true, all items will be restacked on next repaint
  4210. this.touchParams = {}; // stores properties while dragging
  4211. // create the HTML DOM
  4212. this._create();
  4213. }
  4214. ItemSet.prototype = new Panel();
  4215. // available item types will be registered here
  4216. ItemSet.types = {
  4217. box: ItemBox,
  4218. range: ItemRange,
  4219. rangeoverflow: ItemRangeOverflow,
  4220. point: ItemPoint
  4221. };
  4222. /**
  4223. * Create the HTML DOM for the ItemSet
  4224. */
  4225. ItemSet.prototype._create = function _create(){
  4226. var frame = document.createElement('div');
  4227. frame['timeline-itemset'] = this;
  4228. this.frame = frame;
  4229. // create background panel
  4230. var background = document.createElement('div');
  4231. background.className = 'background';
  4232. this.backgroundPanel.frame.appendChild(background);
  4233. this.dom.background = background;
  4234. // create foreground panel
  4235. var foreground = document.createElement('div');
  4236. foreground.className = 'foreground';
  4237. frame.appendChild(foreground);
  4238. this.dom.foreground = foreground;
  4239. // create axis panel
  4240. var axis = document.createElement('div');
  4241. axis.className = 'axis';
  4242. this.dom.axis = axis;
  4243. this.axisPanel.frame.appendChild(axis);
  4244. // attach event listeners
  4245. // TODO: use event listeners from the rootpanel to improve performance?
  4246. this.hammer = Hammer(frame, {
  4247. prevent_default: true
  4248. });
  4249. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4250. this.hammer.on('drag', this._onDrag.bind(this));
  4251. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4252. };
  4253. /**
  4254. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4255. * @param {Object} [options] The following options are available:
  4256. * {String | function} [className]
  4257. * class name for the itemset
  4258. * {String} [type]
  4259. * Default type for the items. Choose from 'box'
  4260. * (default), 'point', or 'range'. The default
  4261. * Style can be overwritten by individual items.
  4262. * {String} align
  4263. * Alignment for the items, only applicable for
  4264. * ItemBox. Choose 'center' (default), 'left', or
  4265. * 'right'.
  4266. * {String} orientation
  4267. * Orientation of the item set. Choose 'top' or
  4268. * 'bottom' (default).
  4269. * {Number} margin.axis
  4270. * Margin between the axis and the items in pixels.
  4271. * Default is 20.
  4272. * {Number} margin.item
  4273. * Margin between items in pixels. Default is 10.
  4274. * {Number} padding
  4275. * Padding of the contents of an item in pixels.
  4276. * Must correspond with the items css. Default is 5.
  4277. * {Function} snap
  4278. * Function to let items snap to nice dates when
  4279. * dragging items.
  4280. */
  4281. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4282. /**
  4283. * Hide the component from the DOM
  4284. */
  4285. ItemSet.prototype.hide = function hide() {
  4286. // remove the axis with dots
  4287. if (this.dom.axis.parentNode) {
  4288. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4289. }
  4290. // remove the background with vertical lines
  4291. if (this.dom.background.parentNode) {
  4292. this.dom.background.parentNode.removeChild(this.dom.background);
  4293. }
  4294. };
  4295. /**
  4296. * Show the component in the DOM (when not already visible).
  4297. * @return {Boolean} changed
  4298. */
  4299. ItemSet.prototype.show = function show() {
  4300. // show axis with dots
  4301. if (!this.dom.axis.parentNode) {
  4302. this.axisPanel.frame.appendChild(this.dom.axis);
  4303. }
  4304. // show background with vertical lines
  4305. if (!this.dom.background.parentNode) {
  4306. this.backgroundPanel.frame.appendChild(this.dom.background);
  4307. }
  4308. };
  4309. /**
  4310. * Set range (start and end).
  4311. * @param {Range | Object} range A Range or an object containing start and end.
  4312. */
  4313. ItemSet.prototype.setRange = function setRange(range) {
  4314. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4315. throw new TypeError('Range must be an instance of Range, ' +
  4316. 'or an object containing start and end.');
  4317. }
  4318. this.range = range;
  4319. };
  4320. /**
  4321. * Set selected items by their id. Replaces the current selection
  4322. * Unknown id's are silently ignored.
  4323. * @param {Array} [ids] An array with zero or more id's of the items to be
  4324. * selected. If ids is an empty array, all items will be
  4325. * unselected.
  4326. */
  4327. ItemSet.prototype.setSelection = function setSelection(ids) {
  4328. var i, ii, id, item;
  4329. if (ids) {
  4330. if (!Array.isArray(ids)) {
  4331. throw new TypeError('Array expected');
  4332. }
  4333. // unselect currently selected items
  4334. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4335. id = this.selection[i];
  4336. item = this.items[id];
  4337. if (item) item.unselect();
  4338. }
  4339. // select items
  4340. this.selection = [];
  4341. for (i = 0, ii = ids.length; i < ii; i++) {
  4342. id = ids[i];
  4343. item = this.items[id];
  4344. if (item) {
  4345. this.selection.push(id);
  4346. item.select();
  4347. }
  4348. }
  4349. }
  4350. };
  4351. /**
  4352. * Get the selected items by their id
  4353. * @return {Array} ids The ids of the selected items
  4354. */
  4355. ItemSet.prototype.getSelection = function getSelection() {
  4356. return this.selection.concat([]);
  4357. };
  4358. /**
  4359. * Deselect a selected item
  4360. * @param {String | Number} id
  4361. * @private
  4362. */
  4363. ItemSet.prototype._deselect = function _deselect(id) {
  4364. var selection = this.selection;
  4365. for (var i = 0, ii = selection.length; i < ii; i++) {
  4366. if (selection[i] == id) { // non-strict comparison!
  4367. selection.splice(i, 1);
  4368. break;
  4369. }
  4370. }
  4371. };
  4372. /**
  4373. * Return the item sets frame
  4374. * @returns {HTMLElement} frame
  4375. */
  4376. ItemSet.prototype.getFrame = function getFrame() {
  4377. return this.frame;
  4378. };
  4379. /**
  4380. * Repaint the component
  4381. * @return {boolean} Returns true if the component is resized
  4382. */
  4383. ItemSet.prototype.repaint = function repaint() {
  4384. var asSize = util.option.asSize,
  4385. asString = util.option.asString,
  4386. options = this.options,
  4387. orientation = this.getOption('orientation'),
  4388. frame = this.frame;
  4389. // update className
  4390. frame.className = 'itemset' + (options.className ? (' ' + asString(options.className)) : '');
  4391. // check whether zoomed (in that case we need to re-stack everything)
  4392. var visibleInterval = this.range.end - this.range.start;
  4393. var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth);
  4394. this.lastVisibleInterval = visibleInterval;
  4395. this.lastWidth = this.width;
  4396. /* TODO: implement+fix smarter way to update visible items
  4397. // find the first visible item
  4398. // TODO: use faster search, not linear
  4399. var byEnd = this.orderedItems.byEnd;
  4400. var start = 0;
  4401. var item = null;
  4402. while ((item = byEnd[start]) &&
  4403. (('end' in item.data) ? item.data.end : item.data.start) < this.range.start) {
  4404. start++;
  4405. }
  4406. // find the last visible item
  4407. // TODO: use faster search, not linear
  4408. var byStart = this.orderedItems.byStart;
  4409. var end = 0;
  4410. while ((item = byStart[end]) && item.data.start < this.range.end) {
  4411. end++;
  4412. }
  4413. console.log('visible items', start, end); // TODO: cleanup
  4414. console.log('visible item ids', byStart[start] && byStart[start].id, byEnd[end-1] && byEnd[end-1].id); // TODO: cleanup
  4415. this.visibleItems = [];
  4416. var i = start;
  4417. item = byStart[i];
  4418. var lastItem = byEnd[end];
  4419. while (item && item !== lastItem) {
  4420. this.visibleItems.push(item);
  4421. item = byStart[++i];
  4422. }
  4423. this.stack.order(this.visibleItems);
  4424. // show visible items
  4425. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  4426. item = this.visibleItems[i];
  4427. if (!item.displayed) item.show();
  4428. item.top = null; // reset stacking position
  4429. // reposition item horizontally
  4430. item.repositionX();
  4431. }
  4432. */
  4433. // simple, brute force calculation of visible items
  4434. // TODO: replace with a faster, more sophisticated solution
  4435. this.visibleItems = [];
  4436. for (var id in this.items) {
  4437. if (this.items.hasOwnProperty(id)) {
  4438. var item = this.items[id];
  4439. if (item.isVisible(this.range)) {
  4440. if (!item.displayed) item.show();
  4441. // reposition item horizontally
  4442. item.repositionX();
  4443. this.visibleItems.push(item);
  4444. }
  4445. else {
  4446. if (item.displayed) item.hide();
  4447. }
  4448. }
  4449. }
  4450. // reposition visible items vertically
  4451. //this.stack.order(this.visibleItems); // TODO: improve ordering
  4452. var force = this.stackDirty || zoomed; // force re-stacking of all items if true
  4453. this.stack.stack(this.visibleItems, force);
  4454. this.stackDirty = false;
  4455. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  4456. this.visibleItems[i].repositionY();
  4457. }
  4458. // recalculate the height of the itemset
  4459. var marginAxis = (options.margin && 'axis' in options.margin) ? options.margin.axis : this.itemOptions.margin.axis,
  4460. marginItem = (options.margin && 'item' in options.margin) ? options.margin.item : this.itemOptions.margin.item,
  4461. height;
  4462. // determine the height from the stacked items
  4463. var visibleItems = this.visibleItems;
  4464. if (visibleItems.length) {
  4465. var min = visibleItems[0].top;
  4466. var max = visibleItems[0].top + visibleItems[0].height;
  4467. util.forEach(visibleItems, function (item) {
  4468. min = Math.min(min, item.top);
  4469. max = Math.max(max, (item.top + item.height));
  4470. });
  4471. height = (max - min) + marginAxis + marginItem;
  4472. }
  4473. else {
  4474. height = marginAxis + marginItem;
  4475. }
  4476. // reposition frame
  4477. frame.style.left = asSize(options.left, '');
  4478. frame.style.right = asSize(options.right, '');
  4479. frame.style.top = asSize((orientation == 'top') ? '0' : '');
  4480. frame.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4481. frame.style.width = asSize(options.width, '100%');
  4482. frame.style.height = asSize(height);
  4483. //frame.style.height = asSize('height' in options ? options.height : height); // TODO: reckon with height
  4484. // calculate actual size and position
  4485. this.top = frame.offsetTop;
  4486. this.left = frame.offsetLeft;
  4487. this.width = frame.offsetWidth;
  4488. this.height = height;
  4489. // reposition axis
  4490. this.dom.axis.style.left = asSize(options.left, '0');
  4491. this.dom.axis.style.right = asSize(options.right, '');
  4492. this.dom.axis.style.width = asSize(options.width, '100%');
  4493. this.dom.axis.style.height = asSize(0);
  4494. this.dom.axis.style.top = asSize((orientation == 'top') ? '0' : '');
  4495. this.dom.axis.style.bottom = asSize((orientation == 'top') ? '' : '0');
  4496. return this._isResized();
  4497. };
  4498. /**
  4499. * Get the foreground container element
  4500. * @return {HTMLElement} foreground
  4501. */
  4502. ItemSet.prototype.getForeground = function getForeground() {
  4503. return this.dom.foreground;
  4504. };
  4505. /**
  4506. * Get the background container element
  4507. * @return {HTMLElement} background
  4508. */
  4509. ItemSet.prototype.getBackground = function getBackground() {
  4510. return this.dom.background;
  4511. };
  4512. /**
  4513. * Get the axis container element
  4514. * @return {HTMLElement} axis
  4515. */
  4516. ItemSet.prototype.getAxis = function getAxis() {
  4517. return this.dom.axis;
  4518. };
  4519. /**
  4520. * Set items
  4521. * @param {vis.DataSet | null} items
  4522. */
  4523. ItemSet.prototype.setItems = function setItems(items) {
  4524. var me = this,
  4525. ids,
  4526. oldItemsData = this.itemsData;
  4527. // replace the dataset
  4528. if (!items) {
  4529. this.itemsData = null;
  4530. }
  4531. else if (items instanceof DataSet || items instanceof DataView) {
  4532. this.itemsData = items;
  4533. }
  4534. else {
  4535. throw new TypeError('Data must be an instance of DataSet');
  4536. }
  4537. if (oldItemsData) {
  4538. // unsubscribe from old dataset
  4539. util.forEach(this.listeners, function (callback, event) {
  4540. oldItemsData.unsubscribe(event, callback);
  4541. });
  4542. // remove all drawn items
  4543. ids = oldItemsData.getIds();
  4544. this._onRemove(ids);
  4545. }
  4546. if (this.itemsData) {
  4547. // subscribe to new dataset
  4548. var id = this.id;
  4549. util.forEach(this.listeners, function (callback, event) {
  4550. me.itemsData.on(event, callback, id);
  4551. });
  4552. // draw all new items
  4553. ids = this.itemsData.getIds();
  4554. this._onAdd(ids);
  4555. }
  4556. };
  4557. /**
  4558. * Get the current items items
  4559. * @returns {vis.DataSet | null}
  4560. */
  4561. ItemSet.prototype.getItems = function getItems() {
  4562. return this.itemsData;
  4563. };
  4564. /**
  4565. * Remove an item by its id
  4566. * @param {String | Number} id
  4567. */
  4568. ItemSet.prototype.removeItem = function removeItem (id) {
  4569. var item = this.itemsData.get(id),
  4570. dataset = this._myDataSet();
  4571. if (item) {
  4572. // confirm deletion
  4573. this.options.onRemove(item, function (item) {
  4574. if (item) {
  4575. // remove by id here, it is possible that an item has no id defined
  4576. // itself, so better not delete by the item itself
  4577. dataset.remove(id);
  4578. }
  4579. });
  4580. }
  4581. };
  4582. /**
  4583. * Handle updated items
  4584. * @param {Number[]} ids
  4585. * @private
  4586. */
  4587. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4588. var me = this,
  4589. items = this.items,
  4590. itemOptions = this.itemOptions;
  4591. ids.forEach(function (id) {
  4592. var itemData = me.itemsData.get(id),
  4593. item = items[id],
  4594. type = itemData.type ||
  4595. (itemData.start && itemData.end && 'range') ||
  4596. me.options.type ||
  4597. 'box';
  4598. var constructor = ItemSet.types[type];
  4599. if (item) {
  4600. // update item
  4601. if (!constructor || !(item instanceof constructor)) {
  4602. // item type has changed, hide and delete the item
  4603. item.hide();
  4604. item = null;
  4605. }
  4606. else {
  4607. item.data = itemData; // TODO: create a method item.setData ?
  4608. }
  4609. }
  4610. if (!item) {
  4611. // create item
  4612. if (constructor) {
  4613. item = new constructor(me, itemData, me.options, itemOptions);
  4614. item.id = id;
  4615. }
  4616. else {
  4617. throw new TypeError('Unknown item type "' + type + '"');
  4618. }
  4619. }
  4620. me.items[id] = item;
  4621. });
  4622. this._order();
  4623. this.stackDirty = true; // force re-stacking of all items next repaint
  4624. this.emit('change');
  4625. };
  4626. /**
  4627. * Handle added items
  4628. * @param {Number[]} ids
  4629. * @private
  4630. */
  4631. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  4632. /**
  4633. * Handle removed items
  4634. * @param {Number[]} ids
  4635. * @private
  4636. */
  4637. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4638. var count = 0;
  4639. var me = this;
  4640. ids.forEach(function (id) {
  4641. var item = me.items[id];
  4642. if (item) {
  4643. count++;
  4644. item.hide();
  4645. delete me.items[id];
  4646. delete me.visibleItems[id];
  4647. // remove from selection
  4648. var index = me.selection.indexOf(id);
  4649. if (index != -1) me.selection.splice(index, 1);
  4650. }
  4651. });
  4652. if (count) {
  4653. // update order
  4654. this._order();
  4655. this.stackDirty = true; // force re-stacking of all items next repaint
  4656. this.emit('change');
  4657. }
  4658. };
  4659. /**
  4660. * Order the items
  4661. * @private
  4662. */
  4663. ItemSet.prototype._order = function _order() {
  4664. var array = util.toArray(this.items);
  4665. this.orderedItems.byStart = array;
  4666. this.orderedItems.byEnd = [].concat(array);
  4667. // reorder the items
  4668. this.stack.orderByStart(this.orderedItems.byStart);
  4669. this.stack.orderByEnd(this.orderedItems.byEnd);
  4670. };
  4671. /**
  4672. * Start dragging the selected events
  4673. * @param {Event} event
  4674. * @private
  4675. */
  4676. ItemSet.prototype._onDragStart = function (event) {
  4677. if (!this.options.editable) {
  4678. return;
  4679. }
  4680. var item = ItemSet.itemFromTarget(event),
  4681. me = this;
  4682. if (item && item.selected) {
  4683. var dragLeftItem = event.target.dragLeftItem;
  4684. var dragRightItem = event.target.dragRightItem;
  4685. if (dragLeftItem) {
  4686. this.touchParams.itemProps = [{
  4687. item: dragLeftItem,
  4688. start: item.data.start.valueOf()
  4689. }];
  4690. }
  4691. else if (dragRightItem) {
  4692. this.touchParams.itemProps = [{
  4693. item: dragRightItem,
  4694. end: item.data.end.valueOf()
  4695. }];
  4696. }
  4697. else {
  4698. this.touchParams.itemProps = this.getSelection().map(function (id) {
  4699. var item = me.items[id];
  4700. var props = {
  4701. item: item
  4702. };
  4703. if ('start' in item.data) {
  4704. props.start = item.data.start.valueOf()
  4705. }
  4706. if ('end' in item.data) {
  4707. props.end = item.data.end.valueOf()
  4708. }
  4709. return props;
  4710. });
  4711. }
  4712. event.stopPropagation();
  4713. }
  4714. };
  4715. /**
  4716. * Drag selected items
  4717. * @param {Event} event
  4718. * @private
  4719. */
  4720. ItemSet.prototype._onDrag = function (event) {
  4721. if (this.touchParams.itemProps) {
  4722. var snap = this.options.snap || null,
  4723. deltaX = event.gesture.deltaX,
  4724. scale = (this.width / (this.range.end - this.range.start)),
  4725. offset = deltaX / scale;
  4726. // move
  4727. this.touchParams.itemProps.forEach(function (props) {
  4728. if ('start' in props) {
  4729. var start = new Date(props.start + offset);
  4730. props.item.data.start = snap ? snap(start) : start;
  4731. }
  4732. if ('end' in props) {
  4733. var end = new Date(props.end + offset);
  4734. props.item.data.end = snap ? snap(end) : end;
  4735. }
  4736. });
  4737. // TODO: implement onMoving handler
  4738. // TODO: implement dragging from one group to another
  4739. this.stackDirty = true; // force re-stacking of all items next repaint
  4740. this.emit('change');
  4741. event.stopPropagation();
  4742. }
  4743. };
  4744. /**
  4745. * End of dragging selected items
  4746. * @param {Event} event
  4747. * @private
  4748. */
  4749. ItemSet.prototype._onDragEnd = function (event) {
  4750. if (this.touchParams.itemProps) {
  4751. // prepare a change set for the changed items
  4752. var changes = [],
  4753. me = this,
  4754. dataset = this._myDataSet();
  4755. this.touchParams.itemProps.forEach(function (props) {
  4756. var id = props.item.id,
  4757. item = me.itemsData.get(id);
  4758. var changed = false;
  4759. if ('start' in props.item.data) {
  4760. changed = (props.start != props.item.data.start.valueOf());
  4761. item.start = util.convert(props.item.data.start, dataset.convert['start']);
  4762. }
  4763. if ('end' in props.item.data) {
  4764. changed = changed || (props.end != props.item.data.end.valueOf());
  4765. item.end = util.convert(props.item.data.end, dataset.convert['end']);
  4766. }
  4767. // only apply changes when start or end is actually changed
  4768. if (changed) {
  4769. me.options.onMove(item, function (item) {
  4770. if (item) {
  4771. // apply changes
  4772. item[dataset.fieldId] = id; // ensure the item contains its id (can be undefined)
  4773. changes.push(item);
  4774. }
  4775. else {
  4776. // restore original values
  4777. if ('start' in props) props.item.data.start = props.start;
  4778. if ('end' in props) props.item.data.end = props.end;
  4779. this.stackDirty = true; // force re-stacking of all items next repaint
  4780. this.emit('change');
  4781. }
  4782. });
  4783. }
  4784. });
  4785. this.touchParams.itemProps = null;
  4786. // apply the changes to the data (if there are changes)
  4787. if (changes.length) {
  4788. dataset.update(changes);
  4789. }
  4790. event.stopPropagation();
  4791. }
  4792. };
  4793. /**
  4794. * Find an item from an event target:
  4795. * searches for the attribute 'timeline-item' in the event target's element tree
  4796. * @param {Event} event
  4797. * @return {Item | null} item
  4798. */
  4799. ItemSet.itemFromTarget = function itemFromTarget (event) {
  4800. var target = event.target;
  4801. while (target) {
  4802. if (target.hasOwnProperty('timeline-item')) {
  4803. return target['timeline-item'];
  4804. }
  4805. target = target.parentNode;
  4806. }
  4807. return null;
  4808. };
  4809. /**
  4810. * Find the ItemSet from an event target:
  4811. * searches for the attribute 'timeline-itemset' in the event target's element tree
  4812. * @param {Event} event
  4813. * @return {ItemSet | null} item
  4814. */
  4815. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  4816. var target = event.target;
  4817. while (target) {
  4818. if (target.hasOwnProperty('timeline-itemset')) {
  4819. return target['timeline-itemset'];
  4820. }
  4821. target = target.parentNode;
  4822. }
  4823. return null;
  4824. };
  4825. /**
  4826. * Find the DataSet to which this ItemSet is connected
  4827. * @returns {null | DataSet} dataset
  4828. * @private
  4829. */
  4830. ItemSet.prototype._myDataSet = function _myDataSet() {
  4831. // find the root DataSet
  4832. var dataset = this.itemsData;
  4833. while (dataset instanceof DataView) {
  4834. dataset = dataset.data;
  4835. }
  4836. return dataset;
  4837. };
  4838. /**
  4839. * @constructor Item
  4840. * @param {ItemSet} parent
  4841. * @param {Object} data Object containing (optional) parameters type,
  4842. * start, end, content, group, className.
  4843. * @param {Object} [options] Options to set initial property values
  4844. * @param {Object} [defaultOptions] default options
  4845. * // TODO: describe available options
  4846. */
  4847. function Item (parent, data, options, defaultOptions) {
  4848. this.parent = parent;
  4849. this.data = data;
  4850. this.dom = null;
  4851. this.options = options || {};
  4852. this.defaultOptions = defaultOptions || {};
  4853. this.selected = false;
  4854. this.displayed = false;
  4855. this.dirty = true;
  4856. this.top = null;
  4857. this.left = null;
  4858. this.width = null;
  4859. this.height = null;
  4860. }
  4861. /**
  4862. * Select current item
  4863. */
  4864. Item.prototype.select = function select() {
  4865. this.selected = true;
  4866. if (this.displayed) this.repaint();
  4867. };
  4868. /**
  4869. * Unselect current item
  4870. */
  4871. Item.prototype.unselect = function unselect() {
  4872. this.selected = false;
  4873. if (this.displayed) this.repaint();
  4874. };
  4875. /**
  4876. * Show the Item in the DOM (when not already visible)
  4877. * @return {Boolean} changed
  4878. */
  4879. Item.prototype.show = function show() {
  4880. return false;
  4881. };
  4882. /**
  4883. * Hide the Item from the DOM (when visible)
  4884. * @return {Boolean} changed
  4885. */
  4886. Item.prototype.hide = function hide() {
  4887. return false;
  4888. };
  4889. /**
  4890. * Repaint the item
  4891. */
  4892. Item.prototype.repaint = function repaint() {
  4893. // should be implemented by the item
  4894. };
  4895. /**
  4896. * Reposition the Item horizontally
  4897. */
  4898. Item.prototype.repositionX = function repositionX() {
  4899. // should be implemented by the item
  4900. };
  4901. /**
  4902. * Reposition the Item vertically
  4903. */
  4904. Item.prototype.repositionY = function repositionY() {
  4905. // should be implemented by the item
  4906. };
  4907. /**
  4908. * Repaint a delete button on the top right of the item when the item is selected
  4909. * @param {HTMLElement} anchor
  4910. * @private
  4911. */
  4912. Item.prototype._repaintDeleteButton = function (anchor) {
  4913. if (this.selected && this.options.editable && !this.dom.deleteButton) {
  4914. // create and show button
  4915. var parent = this.parent;
  4916. var id = this.id;
  4917. var deleteButton = document.createElement('div');
  4918. deleteButton.className = 'delete';
  4919. deleteButton.title = 'Delete this item';
  4920. Hammer(deleteButton, {
  4921. preventDefault: true
  4922. }).on('tap', function (event) {
  4923. parent.removeItem(id);
  4924. event.stopPropagation();
  4925. });
  4926. anchor.appendChild(deleteButton);
  4927. this.dom.deleteButton = deleteButton;
  4928. }
  4929. else if (!this.selected && this.dom.deleteButton) {
  4930. // remove button
  4931. if (this.dom.deleteButton.parentNode) {
  4932. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  4933. }
  4934. this.dom.deleteButton = null;
  4935. }
  4936. };
  4937. /**
  4938. * @constructor ItemBox
  4939. * @extends Item
  4940. * @param {ItemSet} parent
  4941. * @param {Object} data Object containing parameters start
  4942. * content, className.
  4943. * @param {Object} [options] Options to set initial property values
  4944. * @param {Object} [defaultOptions] default options
  4945. * // TODO: describe available options
  4946. */
  4947. function ItemBox (parent, data, options, defaultOptions) {
  4948. this.props = {
  4949. dot: {
  4950. width: 0,
  4951. height: 0
  4952. },
  4953. line: {
  4954. width: 0,
  4955. height: 0
  4956. }
  4957. };
  4958. // validate data
  4959. if (data) {
  4960. if (data.start == undefined) {
  4961. throw new Error('Property "start" missing in item ' + data);
  4962. }
  4963. }
  4964. Item.call(this, parent, data, options, defaultOptions);
  4965. }
  4966. ItemBox.prototype = new Item (null, null);
  4967. /**
  4968. * Check whether this item is visible inside given range
  4969. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  4970. * @returns {boolean} True if visible
  4971. */
  4972. ItemBox.prototype.isVisible = function isVisible (range) {
  4973. // determine visibility
  4974. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  4975. var interval = (range.end - range.start) / 4;
  4976. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  4977. };
  4978. /**
  4979. * Repaint the item
  4980. */
  4981. ItemBox.prototype.repaint = function repaint() {
  4982. var dom = this.dom;
  4983. if (!dom) {
  4984. // create DOM
  4985. this.dom = {};
  4986. dom = this.dom;
  4987. // create main box
  4988. dom.box = document.createElement('DIV');
  4989. // contents box (inside the background box). used for making margins
  4990. dom.content = document.createElement('DIV');
  4991. dom.content.className = 'content';
  4992. dom.box.appendChild(dom.content);
  4993. // line to axis
  4994. dom.line = document.createElement('DIV');
  4995. dom.line.className = 'line';
  4996. // dot on axis
  4997. dom.dot = document.createElement('DIV');
  4998. dom.dot.className = 'dot';
  4999. // attach this item as attribute
  5000. dom.box['timeline-item'] = this;
  5001. }
  5002. // append DOM to parent DOM
  5003. if (!this.parent) {
  5004. throw new Error('Cannot repaint item: no parent attached');
  5005. }
  5006. if (!dom.box.parentNode) {
  5007. var foreground = this.parent.getForeground();
  5008. if (!foreground) throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5009. foreground.appendChild(dom.box);
  5010. }
  5011. if (!dom.line.parentNode) {
  5012. var background = this.parent.getBackground();
  5013. if (!background) throw new Error('Cannot repaint time axis: parent has no background container element');
  5014. background.appendChild(dom.line);
  5015. }
  5016. if (!dom.dot.parentNode) {
  5017. var axis = this.parent.getAxis();
  5018. if (!background) throw new Error('Cannot repaint time axis: parent has no axis container element');
  5019. axis.appendChild(dom.dot);
  5020. }
  5021. this.displayed = true;
  5022. // update contents
  5023. if (this.data.content != this.content) {
  5024. this.content = this.data.content;
  5025. if (this.content instanceof Element) {
  5026. dom.content.innerHTML = '';
  5027. dom.content.appendChild(this.content);
  5028. }
  5029. else if (this.data.content != undefined) {
  5030. dom.content.innerHTML = this.content;
  5031. }
  5032. else {
  5033. throw new Error('Property "content" missing in item ' + this.data.id);
  5034. }
  5035. this.dirty = true;
  5036. }
  5037. // update class
  5038. var className = (this.data.className? ' ' + this.data.className : '') +
  5039. (this.selected ? ' selected' : '');
  5040. if (this.className != className) {
  5041. this.className = className;
  5042. dom.box.className = 'item box' + className;
  5043. dom.line.className = 'item line' + className;
  5044. dom.dot.className = 'item dot' + className;
  5045. this.dirty = true;
  5046. }
  5047. // recalculate size
  5048. if (this.dirty) {
  5049. this.props.dot.height = dom.dot.offsetHeight;
  5050. this.props.dot.width = dom.dot.offsetWidth;
  5051. this.props.line.width = dom.line.offsetWidth;
  5052. this.width = dom.box.offsetWidth;
  5053. this.height = dom.box.offsetHeight;
  5054. this.dirty = false;
  5055. }
  5056. this._repaintDeleteButton(dom.box);
  5057. };
  5058. /**
  5059. * Show the item in the DOM (when not already displayed). The items DOM will
  5060. * be created when needed.
  5061. */
  5062. ItemBox.prototype.show = function show() {
  5063. if (!this.displayed) {
  5064. this.repaint();
  5065. }
  5066. };
  5067. /**
  5068. * Hide the item from the DOM (when visible)
  5069. */
  5070. ItemBox.prototype.hide = function hide() {
  5071. if (this.displayed) {
  5072. var dom = this.dom;
  5073. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  5074. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  5075. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  5076. this.top = null;
  5077. this.left = null;
  5078. this.displayed = false;
  5079. }
  5080. };
  5081. /**
  5082. * Reposition the item horizontally
  5083. * @Override
  5084. */
  5085. ItemBox.prototype.repositionX = function repositionX() {
  5086. var start = this.defaultOptions.toScreen(this.data.start),
  5087. align = this.options.align || this.defaultOptions.align,
  5088. left,
  5089. box = this.dom.box,
  5090. line = this.dom.line,
  5091. dot = this.dom.dot;
  5092. // calculate left position of the box
  5093. if (align == 'right') {
  5094. this.left = start - this.width;
  5095. }
  5096. else if (align == 'left') {
  5097. this.left = start;
  5098. }
  5099. else {
  5100. // default or 'center'
  5101. this.left = start - this.width / 2;
  5102. }
  5103. // reposition box
  5104. box.style.left = this.left + 'px';
  5105. // reposition line
  5106. line.style.left = (start - this.props.line.width / 2) + 'px';
  5107. // reposition dot
  5108. dot.style.left = (start - this.props.dot.width / 2) + 'px';
  5109. };
  5110. /**
  5111. * Reposition the item vertically
  5112. * @Override
  5113. */
  5114. ItemBox.prototype.repositionY = function repositionY () {
  5115. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5116. box = this.dom.box,
  5117. line = this.dom.line,
  5118. dot = this.dom.dot;
  5119. if (orientation == 'top') {
  5120. box.style.top = (this.top || 0) + 'px';
  5121. box.style.bottom = '';
  5122. line.style.top = '0';
  5123. line.style.bottom = '';
  5124. line.style.height = (this.parent.top + this.top + 1) + 'px';
  5125. }
  5126. else { // orientation 'bottom'
  5127. box.style.top = '';
  5128. box.style.bottom = (this.top || 0) + 'px';
  5129. line.style.top = (this.parent.top + this.parent.height - this.top - 1) + 'px';
  5130. line.style.bottom = '0';
  5131. line.style.height = '';
  5132. }
  5133. dot.style.top = (-this.props.dot.height / 2) + 'px';
  5134. };
  5135. /**
  5136. * @constructor ItemPoint
  5137. * @extends Item
  5138. * @param {ItemSet} parent
  5139. * @param {Object} data Object containing parameters start
  5140. * content, className.
  5141. * @param {Object} [options] Options to set initial property values
  5142. * @param {Object} [defaultOptions] default options
  5143. * // TODO: describe available options
  5144. */
  5145. function ItemPoint (parent, data, options, defaultOptions) {
  5146. this.props = {
  5147. dot: {
  5148. top: 0,
  5149. width: 0,
  5150. height: 0
  5151. },
  5152. content: {
  5153. height: 0,
  5154. marginLeft: 0
  5155. }
  5156. };
  5157. // validate data
  5158. if (data) {
  5159. if (data.start == undefined) {
  5160. throw new Error('Property "start" missing in item ' + data);
  5161. }
  5162. }
  5163. Item.call(this, parent, data, options, defaultOptions);
  5164. }
  5165. ItemPoint.prototype = new Item (null, null);
  5166. /**
  5167. * Check whether this item is visible inside given range
  5168. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5169. * @returns {boolean} True if visible
  5170. */
  5171. ItemPoint.prototype.isVisible = function isVisible (range) {
  5172. // determine visibility
  5173. var interval = (range.end - range.start);
  5174. return (this.data.start > range.start - interval) && (this.data.start < range.end);
  5175. }
  5176. /**
  5177. * Repaint the item
  5178. */
  5179. ItemPoint.prototype.repaint = function repaint() {
  5180. var dom = this.dom;
  5181. if (!dom) {
  5182. // create DOM
  5183. this.dom = {};
  5184. dom = this.dom;
  5185. // background box
  5186. dom.point = document.createElement('div');
  5187. // className is updated in repaint()
  5188. // contents box, right from the dot
  5189. dom.content = document.createElement('div');
  5190. dom.content.className = 'content';
  5191. dom.point.appendChild(dom.content);
  5192. // dot at start
  5193. dom.dot = document.createElement('div');
  5194. dom.dot.className = 'dot';
  5195. dom.point.appendChild(dom.dot);
  5196. // attach this item as attribute
  5197. dom.point['timeline-item'] = this;
  5198. }
  5199. // append DOM to parent DOM
  5200. if (!this.parent) {
  5201. throw new Error('Cannot repaint item: no parent attached');
  5202. }
  5203. if (!dom.point.parentNode) {
  5204. var foreground = this.parent.getForeground();
  5205. if (!foreground) {
  5206. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5207. }
  5208. foreground.appendChild(dom.point);
  5209. }
  5210. this.displayed = true;
  5211. // update contents
  5212. if (this.data.content != this.content) {
  5213. this.content = this.data.content;
  5214. if (this.content instanceof Element) {
  5215. dom.content.innerHTML = '';
  5216. dom.content.appendChild(this.content);
  5217. }
  5218. else if (this.data.content != undefined) {
  5219. dom.content.innerHTML = this.content;
  5220. }
  5221. else {
  5222. throw new Error('Property "content" missing in item ' + this.data.id);
  5223. }
  5224. this.dirty = true;
  5225. }
  5226. // update class
  5227. var className = (this.data.className? ' ' + this.data.className : '') +
  5228. (this.selected ? ' selected' : '');
  5229. if (this.className != className) {
  5230. this.className = className;
  5231. dom.point.className = 'item point' + className;
  5232. this.dirty = true;
  5233. }
  5234. // recalculate size
  5235. if (this.dirty) {
  5236. this.width = dom.point.offsetWidth;
  5237. this.height = dom.point.offsetHeight;
  5238. this.props.dot.width = dom.dot.offsetWidth;
  5239. this.props.dot.height = dom.dot.offsetHeight;
  5240. this.props.content.height = dom.content.offsetHeight;
  5241. // resize contents
  5242. dom.content.style.marginLeft = 1.5 * this.props.dot.width + 'px';
  5243. //dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  5244. dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px';
  5245. this.dirty = false;
  5246. }
  5247. this._repaintDeleteButton(dom.point);
  5248. };
  5249. /**
  5250. * Show the item in the DOM (when not already visible). The items DOM will
  5251. * be created when needed.
  5252. */
  5253. ItemPoint.prototype.show = function show() {
  5254. if (!this.displayed) {
  5255. this.repaint();
  5256. }
  5257. };
  5258. /**
  5259. * Hide the item from the DOM (when visible)
  5260. */
  5261. ItemPoint.prototype.hide = function hide() {
  5262. if (this.displayed) {
  5263. if (this.dom.point.parentNode) {
  5264. this.dom.point.parentNode.removeChild(this.dom.point);
  5265. }
  5266. this.top = null;
  5267. this.left = null;
  5268. this.displayed = false;
  5269. }
  5270. };
  5271. /**
  5272. * Reposition the item horizontally
  5273. * @Override
  5274. */
  5275. ItemPoint.prototype.repositionX = function repositionX() {
  5276. var start = this.defaultOptions.toScreen(this.data.start);
  5277. this.left = start - this.props.dot.width / 2;
  5278. // reposition point
  5279. this.dom.point.style.left = this.left + 'px';
  5280. };
  5281. /**
  5282. * Reposition the item vertically
  5283. * @Override
  5284. */
  5285. ItemPoint.prototype.repositionY = function repositionY () {
  5286. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5287. point = this.dom.point;
  5288. if (orientation == 'top') {
  5289. point.style.top = this.top + 'px';
  5290. point.style.bottom = '';
  5291. }
  5292. else {
  5293. point.style.top = '';
  5294. point.style.bottom = this.top + 'px';
  5295. }
  5296. }
  5297. /**
  5298. * @constructor ItemRange
  5299. * @extends Item
  5300. * @param {ItemSet} parent
  5301. * @param {Object} data Object containing parameters start, end
  5302. * content, className.
  5303. * @param {Object} [options] Options to set initial property values
  5304. * @param {Object} [defaultOptions] default options
  5305. * // TODO: describe available options
  5306. */
  5307. function ItemRange (parent, data, options, defaultOptions) {
  5308. this.props = {
  5309. content: {
  5310. width: 0
  5311. }
  5312. };
  5313. // validate data
  5314. if (data) {
  5315. if (data.start == undefined) {
  5316. throw new Error('Property "start" missing in item ' + data.id);
  5317. }
  5318. if (data.end == undefined) {
  5319. throw new Error('Property "end" missing in item ' + data.id);
  5320. }
  5321. }
  5322. Item.call(this, parent, data, options, defaultOptions);
  5323. }
  5324. ItemRange.prototype = new Item (null, null);
  5325. ItemRange.prototype.baseClassName = 'item range';
  5326. /**
  5327. * Check whether this item is visible inside given range
  5328. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5329. * @returns {boolean} True if visible
  5330. */
  5331. ItemRange.prototype.isVisible = function isVisible (range) {
  5332. // determine visibility
  5333. return (this.data.start < range.end) && (this.data.end > range.start);
  5334. };
  5335. /**
  5336. * Repaint the item
  5337. */
  5338. ItemRange.prototype.repaint = function repaint() {
  5339. var dom = this.dom;
  5340. if (!dom) {
  5341. // create DOM
  5342. this.dom = {};
  5343. dom = this.dom;
  5344. // background box
  5345. dom.box = document.createElement('div');
  5346. // className is updated in repaint()
  5347. // contents box
  5348. dom.content = document.createElement('div');
  5349. dom.content.className = 'content';
  5350. dom.box.appendChild(dom.content);
  5351. // attach this item as attribute
  5352. dom.box['timeline-item'] = this;
  5353. }
  5354. // append DOM to parent DOM
  5355. if (!this.parent) {
  5356. throw new Error('Cannot repaint item: no parent attached');
  5357. }
  5358. if (!dom.box.parentNode) {
  5359. var foreground = this.parent.getForeground();
  5360. if (!foreground) {
  5361. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5362. }
  5363. foreground.appendChild(dom.box);
  5364. }
  5365. this.displayed = true;
  5366. // update contents
  5367. if (this.data.content != this.content) {
  5368. this.content = this.data.content;
  5369. if (this.content instanceof Element) {
  5370. dom.content.innerHTML = '';
  5371. dom.content.appendChild(this.content);
  5372. }
  5373. else if (this.data.content != undefined) {
  5374. dom.content.innerHTML = this.content;
  5375. }
  5376. else {
  5377. throw new Error('Property "content" missing in item ' + this.data.id);
  5378. }
  5379. this.dirty = true;
  5380. }
  5381. // update class
  5382. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5383. (this.selected ? ' selected' : '');
  5384. if (this.className != className) {
  5385. this.className = className;
  5386. dom.box.className = this.baseClassName + className;
  5387. this.dirty = true;
  5388. }
  5389. // recalculate size
  5390. if (this.dirty) {
  5391. this.props.content.width = this.dom.content.offsetWidth;
  5392. this.height = this.dom.box.offsetHeight;
  5393. this.dirty = false;
  5394. }
  5395. this._repaintDeleteButton(dom.box);
  5396. this._repaintDragLeft();
  5397. this._repaintDragRight();
  5398. };
  5399. /**
  5400. * Show the item in the DOM (when not already visible). The items DOM will
  5401. * be created when needed.
  5402. */
  5403. ItemRange.prototype.show = function show() {
  5404. if (!this.displayed) {
  5405. this.repaint();
  5406. }
  5407. };
  5408. /**
  5409. * Hide the item from the DOM (when visible)
  5410. * @return {Boolean} changed
  5411. */
  5412. ItemRange.prototype.hide = function hide() {
  5413. if (this.displayed) {
  5414. var box = this.dom.box;
  5415. if (box.parentNode) {
  5416. box.parentNode.removeChild(box);
  5417. }
  5418. this.top = null;
  5419. this.left = null;
  5420. this.displayed = false;
  5421. }
  5422. };
  5423. /**
  5424. * Reposition the item horizontally
  5425. * @Override
  5426. */
  5427. ItemRange.prototype.repositionX = function repositionX() {
  5428. var props = this.props,
  5429. parentWidth = this.parent.width,
  5430. start = this.defaultOptions.toScreen(this.data.start),
  5431. end = this.defaultOptions.toScreen(this.data.end),
  5432. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5433. contentLeft;
  5434. // limit the width of the this, as browsers cannot draw very wide divs
  5435. if (start < -parentWidth) {
  5436. start = -parentWidth;
  5437. }
  5438. if (end > 2 * parentWidth) {
  5439. end = 2 * parentWidth;
  5440. }
  5441. // when range exceeds left of the window, position the contents at the left of the visible area
  5442. if (start < 0) {
  5443. contentLeft = Math.min(-start,
  5444. (end - start - props.content.width - 2 * padding));
  5445. // TODO: remove the need for options.padding. it's terrible.
  5446. }
  5447. else {
  5448. contentLeft = 0;
  5449. }
  5450. this.left = start;
  5451. this.width = Math.max(end - start, 1);
  5452. this.dom.box.style.left = this.left + 'px';
  5453. this.dom.box.style.width = this.width + 'px';
  5454. this.dom.content.style.left = contentLeft + 'px';
  5455. };
  5456. /**
  5457. * Reposition the item vertically
  5458. * @Override
  5459. */
  5460. ItemRange.prototype.repositionY = function repositionY() {
  5461. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5462. box = this.dom.box;
  5463. if (orientation == 'top') {
  5464. box.style.top = this.top + 'px';
  5465. box.style.bottom = '';
  5466. }
  5467. else {
  5468. box.style.top = '';
  5469. box.style.bottom = this.top + 'px';
  5470. }
  5471. };
  5472. /**
  5473. * Repaint a drag area on the left side of the range when the range is selected
  5474. * @private
  5475. */
  5476. ItemRange.prototype._repaintDragLeft = function () {
  5477. if (this.selected && this.options.editable && !this.dom.dragLeft) {
  5478. // create and show drag area
  5479. var dragLeft = document.createElement('div');
  5480. dragLeft.className = 'drag-left';
  5481. dragLeft.dragLeftItem = this;
  5482. // TODO: this should be redundant?
  5483. Hammer(dragLeft, {
  5484. preventDefault: true
  5485. }).on('drag', function () {
  5486. //console.log('drag left')
  5487. });
  5488. this.dom.box.appendChild(dragLeft);
  5489. this.dom.dragLeft = dragLeft;
  5490. }
  5491. else if (!this.selected && this.dom.dragLeft) {
  5492. // delete drag area
  5493. if (this.dom.dragLeft.parentNode) {
  5494. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  5495. }
  5496. this.dom.dragLeft = null;
  5497. }
  5498. };
  5499. /**
  5500. * Repaint a drag area on the right side of the range when the range is selected
  5501. * @private
  5502. */
  5503. ItemRange.prototype._repaintDragRight = function () {
  5504. if (this.selected && this.options.editable && !this.dom.dragRight) {
  5505. // create and show drag area
  5506. var dragRight = document.createElement('div');
  5507. dragRight.className = 'drag-right';
  5508. dragRight.dragRightItem = this;
  5509. // TODO: this should be redundant?
  5510. Hammer(dragRight, {
  5511. preventDefault: true
  5512. }).on('drag', function () {
  5513. //console.log('drag right')
  5514. });
  5515. this.dom.box.appendChild(dragRight);
  5516. this.dom.dragRight = dragRight;
  5517. }
  5518. else if (!this.selected && this.dom.dragRight) {
  5519. // delete drag area
  5520. if (this.dom.dragRight.parentNode) {
  5521. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  5522. }
  5523. this.dom.dragRight = null;
  5524. }
  5525. };
  5526. /**
  5527. * @constructor ItemRangeOverflow
  5528. * @extends ItemRange
  5529. * @param {ItemSet} parent
  5530. * @param {Object} data Object containing parameters start, end
  5531. * content, className.
  5532. * @param {Object} [options] Options to set initial property values
  5533. * @param {Object} [defaultOptions] default options
  5534. * // TODO: describe available options
  5535. */
  5536. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  5537. this.props = {
  5538. content: {
  5539. left: 0,
  5540. width: 0
  5541. }
  5542. };
  5543. ItemRange.call(this, parent, data, options, defaultOptions);
  5544. }
  5545. ItemRangeOverflow.prototype = new ItemRange (null, null);
  5546. ItemRangeOverflow.prototype.baseClassName = 'item rangeoverflow';
  5547. /**
  5548. * Reposition the item horizontally
  5549. * @Override
  5550. */
  5551. ItemRangeOverflow.prototype.repositionX = function repositionX() {
  5552. var parentWidth = this.parent.width,
  5553. start = this.defaultOptions.toScreen(this.data.start),
  5554. end = this.defaultOptions.toScreen(this.data.end),
  5555. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5556. contentLeft;
  5557. // limit the width of the this, as browsers cannot draw very wide divs
  5558. if (start < -parentWidth) {
  5559. start = -parentWidth;
  5560. }
  5561. if (end > 2 * parentWidth) {
  5562. end = 2 * parentWidth;
  5563. }
  5564. // when range exceeds left of the window, position the contents at the left of the visible area
  5565. contentLeft = Math.max(-start, 0);
  5566. this.left = start;
  5567. var boxWidth = Math.max(end - start, 1);
  5568. this.width = (this.props.content.width < boxWidth) ?
  5569. boxWidth :
  5570. start + contentLeft + this.props.content.width;
  5571. this.dom.box.style.left = this.left + 'px';
  5572. this.dom.box.style.width = boxWidth + 'px';
  5573. this.dom.content.style.left = contentLeft + 'px';
  5574. };
  5575. /**
  5576. * @constructor Group
  5577. * @param {Panel} groupPanel
  5578. * @param {Panel} labelPanel
  5579. * @param {Panel} backgroundPanel
  5580. * @param {Panel} axisPanel
  5581. * @param {Number | String} groupId
  5582. * @param {Object} [options] Options to set initial property values
  5583. * // TODO: describe available options
  5584. * @extends Component
  5585. */
  5586. function Group (groupPanel, labelPanel, backgroundPanel, axisPanel, groupId, options) {
  5587. this.id = util.randomUUID();
  5588. this.groupPanel = groupPanel;
  5589. this.labelPanel = labelPanel;
  5590. this.backgroundPanel = backgroundPanel;
  5591. this.axisPanel = axisPanel;
  5592. this.groupId = groupId;
  5593. this.itemSet = null; // ItemSet
  5594. this.options = options || {};
  5595. this.options.top = 0;
  5596. this.props = {
  5597. label: {
  5598. width: 0,
  5599. height: 0
  5600. }
  5601. };
  5602. this.dom = {};
  5603. this.top = 0;
  5604. this.left = 0;
  5605. this.width = 0;
  5606. this.height = 0;
  5607. this._create();
  5608. }
  5609. Group.prototype = new Component();
  5610. // TODO: comment
  5611. Group.prototype.setOptions = Component.prototype.setOptions;
  5612. /**
  5613. * Create DOM elements for the group
  5614. * @private
  5615. */
  5616. Group.prototype._create = function() {
  5617. var label = document.createElement('div');
  5618. label.className = 'vlabel';
  5619. this.dom.label = label;
  5620. var inner = document.createElement('div');
  5621. inner.className = 'inner';
  5622. label.appendChild(inner);
  5623. this.dom.inner = inner;
  5624. };
  5625. /**
  5626. * Set the group data for this group
  5627. * @param {Object} data Group data, can contain properties content and className
  5628. */
  5629. Group.prototype.setData = function setData(data) {
  5630. // update contents
  5631. var content = data && data.content;
  5632. if (content instanceof Element) {
  5633. this.dom.inner.appendChild(content);
  5634. }
  5635. else if (content != undefined) {
  5636. this.dom.inner.innerHTML = content;
  5637. }
  5638. else {
  5639. this.dom.inner.innerHTML = this.groupId;
  5640. }
  5641. // update className
  5642. var className = data && data.className;
  5643. if (className) {
  5644. util.addClassName(this.dom.label, className);
  5645. }
  5646. };
  5647. /**
  5648. * Set item set for the group. The group will create a view on the itemSet,
  5649. * filtered by the groups id.
  5650. * @param {DataSet | DataView} itemsData
  5651. */
  5652. Group.prototype.setItems = function setItems(itemsData) {
  5653. if (this.itemSet) {
  5654. // remove current item set
  5655. this.itemSet.setItems();
  5656. this.itemSet.hide();
  5657. this.groupPanel.frame.removeChild(this.itemSet.getFrame());
  5658. this.itemSet = null;
  5659. }
  5660. if (itemsData) {
  5661. var groupId = this.groupId;
  5662. var me = this;
  5663. var itemSetOptions = util.extend(this.options, {
  5664. height: function () {
  5665. // FIXME: setting height doesn't yet work
  5666. return Math.max(me.props.label.height, me.itemSet.height);
  5667. }
  5668. });
  5669. this.itemSet = new ItemSet(this.backgroundPanel, this.axisPanel, itemSetOptions);
  5670. this.itemSet.on('change', this.emit.bind(this, 'change')); // propagate change event
  5671. this.itemSet.parent = this;
  5672. this.groupPanel.frame.appendChild(this.itemSet.getFrame());
  5673. if (this.range) this.itemSet.setRange(this.range);
  5674. this.view = new DataView(itemsData, {
  5675. filter: function (item) {
  5676. return item.group == groupId;
  5677. }
  5678. });
  5679. this.itemSet.setItems(this.view);
  5680. }
  5681. };
  5682. /**
  5683. * hide the group, detach from DOM if needed
  5684. */
  5685. Group.prototype.show = function show() {
  5686. if (!this.dom.label.parentNode) {
  5687. this.labelPanel.frame.appendChild(this.dom.label);
  5688. }
  5689. var itemSetFrame = this.itemSet && this.itemSet.getFrame();
  5690. if (itemSetFrame) {
  5691. if (itemSetFrame.parentNode) {
  5692. itemSetFrame.parentNode.removeChild(itemSetFrame);
  5693. }
  5694. this.groupPanel.frame.appendChild(itemSetFrame);
  5695. this.itemSet.show();
  5696. }
  5697. };
  5698. /**
  5699. * hide the group, detach from DOM if needed
  5700. */
  5701. Group.prototype.hide = function hide() {
  5702. if (this.dom.label.parentNode) {
  5703. this.dom.label.parentNode.removeChild(this.dom.label);
  5704. }
  5705. if (this.itemSet) {
  5706. this.itemSet.hide();
  5707. }
  5708. var itemSetFrame = this.itemset && this.itemSet.getFrame();
  5709. if (itemSetFrame && itemSetFrame.parentNode) {
  5710. itemSetFrame.parentNode.removeChild(itemSetFrame);
  5711. }
  5712. };
  5713. /**
  5714. * Set range (start and end).
  5715. * @param {Range | Object} range A Range or an object containing start and end.
  5716. */
  5717. Group.prototype.setRange = function (range) {
  5718. this.range = range;
  5719. if (this.itemSet) this.itemSet.setRange(range);
  5720. };
  5721. /**
  5722. * Set selected items by their id. Replaces the current selection.
  5723. * Unknown id's are silently ignored.
  5724. * @param {Array} [ids] An array with zero or more id's of the items to be
  5725. * selected. If ids is an empty array, all items will be
  5726. * unselected.
  5727. */
  5728. Group.prototype.setSelection = function setSelection(ids) {
  5729. if (this.itemSet) this.itemSet.setSelection(ids);
  5730. };
  5731. /**
  5732. * Get the selected items by their id
  5733. * @return {Array} ids The ids of the selected items
  5734. */
  5735. Group.prototype.getSelection = function getSelection() {
  5736. return this.itemSet ? this.itemSet.getSelection() : [];
  5737. };
  5738. /**
  5739. * Repaint the group
  5740. * @return {boolean} Returns true if the component is resized
  5741. */
  5742. Group.prototype.repaint = function repaint() {
  5743. var resized = false;
  5744. this.show();
  5745. if (this.itemSet) {
  5746. resized = this.itemSet.repaint() || resized;
  5747. }
  5748. // calculate inner size of the label
  5749. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  5750. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  5751. this.height = this.itemSet ? this.itemSet.height : 0;
  5752. this.dom.label.style.height = this.height + 'px';
  5753. return resized;
  5754. };
  5755. /**
  5756. * An GroupSet holds a set of groups
  5757. * @param {Panel} contentPanel Panel where the ItemSets will be created
  5758. * @param {Panel} labelPanel Panel where the labels will be created
  5759. * @param {Panel} backgroundPanel Panel where the vertical lines of box
  5760. * items are created
  5761. * @param {Panel} axisPanel Panel on the axis where the dots of box
  5762. * items will be created
  5763. * @param {Object} [options] See GroupSet.setOptions for the available
  5764. * options.
  5765. * @constructor GroupSet
  5766. * @extends Panel
  5767. */
  5768. function GroupSet(contentPanel, labelPanel, backgroundPanel, axisPanel, options) {
  5769. this.id = util.randomUUID();
  5770. this.contentPanel = contentPanel;
  5771. this.labelPanel = labelPanel;
  5772. this.backgroundPanel = backgroundPanel;
  5773. this.axisPanel = axisPanel;
  5774. this.options = options || {};
  5775. this.range = null; // Range or Object {start: number, end: number}
  5776. this.itemsData = null; // DataSet with items
  5777. this.groupsData = null; // DataSet with groups
  5778. this.groups = {}; // map with groups
  5779. this.groupIds = []; // list with ordered group ids
  5780. this.dom = {};
  5781. this.props = {
  5782. labels: {
  5783. width: 0
  5784. }
  5785. };
  5786. // TODO: implement right orientation of the labels (left/right)
  5787. var me = this;
  5788. this.listeners = {
  5789. 'add': function (event, params) {
  5790. me._onAdd(params.items);
  5791. },
  5792. 'update': function (event, params) {
  5793. me._onUpdate(params.items);
  5794. },
  5795. 'remove': function (event, params) {
  5796. me._onRemove(params.items);
  5797. }
  5798. };
  5799. // create HTML DOM
  5800. this._create();
  5801. }
  5802. GroupSet.prototype = new Panel();
  5803. /**
  5804. * Create the HTML DOM elements for the GroupSet
  5805. * @private
  5806. */
  5807. GroupSet.prototype._create = function _create () {
  5808. // TODO: reimplement groupSet DOM elements
  5809. var frame = document.createElement('div');
  5810. frame.className = 'groupset';
  5811. frame['timeline-groupset'] = this;
  5812. this.frame = frame;
  5813. this.labelSet = new Panel({
  5814. className: 'labelset',
  5815. width: '100%',
  5816. height: '100%'
  5817. });
  5818. this.labelPanel.appendChild(this.labelSet);
  5819. };
  5820. /**
  5821. * Get the frame element of component
  5822. * @returns {null} Get frame is not supported by GroupSet
  5823. */
  5824. GroupSet.prototype.getFrame = function getFrame() {
  5825. return this.frame;
  5826. };
  5827. /**
  5828. * Set options for the GroupSet. Existing options will be extended/overwritten.
  5829. * @param {Object} [options] The following options are available:
  5830. * {String | function} groupsOrder
  5831. * TODO: describe options
  5832. */
  5833. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  5834. /**
  5835. * Set range (start and end).
  5836. * @param {Range | Object} range A Range or an object containing start and end.
  5837. */
  5838. GroupSet.prototype.setRange = function (range) {
  5839. this.range = range;
  5840. for (var id in this.groups) {
  5841. if (this.groups.hasOwnProperty(id)) {
  5842. this.groups[id].setRange(range);
  5843. }
  5844. }
  5845. };
  5846. /**
  5847. * Set items
  5848. * @param {vis.DataSet | null} items
  5849. */
  5850. GroupSet.prototype.setItems = function setItems(items) {
  5851. this.itemsData = items;
  5852. for (var id in this.groups) {
  5853. if (this.groups.hasOwnProperty(id)) {
  5854. var group = this.groups[id];
  5855. // TODO: every group will emit a change event, causing a lot of unnecessary repaints. improve this.
  5856. group.setItems(items);
  5857. }
  5858. }
  5859. };
  5860. /**
  5861. * Get items
  5862. * @return {vis.DataSet | null} items
  5863. */
  5864. GroupSet.prototype.getItems = function getItems() {
  5865. return this.itemsData;
  5866. };
  5867. /**
  5868. * Set range (start and end).
  5869. * @param {Range | Object} range A Range or an object containing start and end.
  5870. */
  5871. GroupSet.prototype.setRange = function setRange(range) {
  5872. this.range = range;
  5873. };
  5874. /**
  5875. * Set groups
  5876. * @param {vis.DataSet} groups
  5877. */
  5878. GroupSet.prototype.setGroups = function setGroups(groups) {
  5879. var me = this,
  5880. ids;
  5881. // unsubscribe from current dataset
  5882. if (this.groupsData) {
  5883. util.forEach(this.listeners, function (callback, event) {
  5884. me.groupsData.unsubscribe(event, callback);
  5885. });
  5886. // remove all drawn groups
  5887. ids = this.groupsData.getIds();
  5888. this._onRemove(ids);
  5889. }
  5890. // replace the dataset
  5891. if (!groups) {
  5892. this.groupsData = null;
  5893. }
  5894. else if (groups instanceof DataSet) {
  5895. this.groupsData = groups;
  5896. }
  5897. else {
  5898. this.groupsData = new DataSet({
  5899. convert: {
  5900. start: 'Date',
  5901. end: 'Date'
  5902. }
  5903. });
  5904. this.groupsData.add(groups);
  5905. }
  5906. if (this.groupsData) {
  5907. // subscribe to new dataset
  5908. var id = this.id;
  5909. util.forEach(this.listeners, function (callback, event) {
  5910. me.groupsData.on(event, callback, id);
  5911. });
  5912. // draw all new groups
  5913. ids = this.groupsData.getIds();
  5914. this._onAdd(ids);
  5915. }
  5916. this.emit('change');
  5917. };
  5918. /**
  5919. * Get groups
  5920. * @return {vis.DataSet | null} groups
  5921. */
  5922. GroupSet.prototype.getGroups = function getGroups() {
  5923. return this.groupsData;
  5924. };
  5925. /**
  5926. * Set selected items by their id. Replaces the current selection.
  5927. * Unknown id's are silently ignored.
  5928. * @param {Array} [ids] An array with zero or more id's of the items to be
  5929. * selected. If ids is an empty array, all items will be
  5930. * unselected.
  5931. */
  5932. GroupSet.prototype.setSelection = function setSelection(ids) {
  5933. var selection = [],
  5934. groups = this.groups;
  5935. // iterate over each of the groups
  5936. for (var id in groups) {
  5937. if (groups.hasOwnProperty(id)) {
  5938. var group = groups[id];
  5939. group.setSelection(ids);
  5940. }
  5941. }
  5942. return selection;
  5943. };
  5944. /**
  5945. * Get the selected items by their id
  5946. * @return {Array} ids The ids of the selected items
  5947. */
  5948. GroupSet.prototype.getSelection = function getSelection() {
  5949. var selection = [],
  5950. groups = this.groups;
  5951. // iterate over each of the groups
  5952. for (var id in groups) {
  5953. if (groups.hasOwnProperty(id)) {
  5954. var group = groups[id];
  5955. selection = selection.concat(group.getSelection());
  5956. }
  5957. }
  5958. return selection;
  5959. };
  5960. /**
  5961. * Repaint the component
  5962. * @return {boolean} Returns true if the component was resized since previous repaint
  5963. */
  5964. GroupSet.prototype.repaint = function repaint() {
  5965. var i, id, group,
  5966. asSize = util.option.asSize,
  5967. asString = util.option.asString,
  5968. options = this.options,
  5969. orientation = this.getOption('orientation'),
  5970. frame = this.frame,
  5971. resized = false,
  5972. groups = this.groups;
  5973. // repaint all groups in order
  5974. this.groupIds.forEach(function (id) {
  5975. var groupResized = groups[id].repaint();
  5976. resized = resized || groupResized;
  5977. });
  5978. // reposition the labels and calculate the maximum label width
  5979. var maxWidth = 0;
  5980. for (id in groups) {
  5981. if (groups.hasOwnProperty(id)) {
  5982. group = groups[id];
  5983. maxWidth = Math.max(maxWidth, group.props.label.width);
  5984. }
  5985. }
  5986. resized = util.updateProperty(this.props.labels, 'width', maxWidth) || resized;
  5987. // recalculate the height of the groupset, and recalculate top positions of the groups
  5988. var fixedHeight = (asSize(options.height) != null);
  5989. var height;
  5990. if (!fixedHeight) {
  5991. // height is not specified, calculate the sum of the height of all groups
  5992. height = 0;
  5993. this.groupIds.forEach(function (id) {
  5994. var group = groups[id];
  5995. group.top = height;
  5996. if (group.itemSet) group.itemSet.top = group.top; // TODO: this is an ugly hack
  5997. height += group.height;
  5998. });
  5999. }
  6000. // update classname
  6001. frame.className = 'groupset' + (options.className ? (' ' + asString(options.className)) : '');
  6002. // calculate actual size and position
  6003. this.top = frame.offsetTop;
  6004. this.left = frame.offsetLeft;
  6005. this.width = frame.offsetWidth;
  6006. this.height = height;
  6007. return resized;
  6008. };
  6009. /**
  6010. * Update the groupIds. Requires a repaint afterwards
  6011. * @private
  6012. */
  6013. GroupSet.prototype._updateGroupIds = function () {
  6014. // reorder the groups
  6015. this.groupIds = this.groupsData.getIds({
  6016. order: this.options.groupOrder
  6017. });
  6018. // hide the groups now, they will be shown again in the next repaint
  6019. // in correct order
  6020. var groups = this.groups;
  6021. this.groupIds.forEach(function (id) {
  6022. groups[id].hide();
  6023. });
  6024. };
  6025. /**
  6026. * Get the width of the group labels
  6027. * @return {Number} width
  6028. */
  6029. GroupSet.prototype.getLabelsWidth = function getLabelsWidth() {
  6030. return this.props.labels.width;
  6031. };
  6032. /**
  6033. * Hide the component from the DOM
  6034. */
  6035. GroupSet.prototype.hide = function hide() {
  6036. // hide labelset
  6037. this.labelPanel.removeChild(this.labelSet);
  6038. // hide each of the groups
  6039. for (var groupId in this.groups) {
  6040. if (this.groups.hasOwnProperty(groupId)) {
  6041. this.groups[groupId].hide();
  6042. }
  6043. }
  6044. };
  6045. /**
  6046. * Show the component in the DOM (when not already visible).
  6047. * @return {Boolean} changed
  6048. */
  6049. GroupSet.prototype.show = function show() {
  6050. // show label set
  6051. if (!this.labelPanel.hasChild(this.labelSet)) {
  6052. this.labelPanel.removeChild(this.labelSet);
  6053. }
  6054. // show each of the groups
  6055. for (var groupId in this.groups) {
  6056. if (this.groups.hasOwnProperty(groupId)) {
  6057. this.groups[groupId].show();
  6058. }
  6059. }
  6060. };
  6061. /**
  6062. * Handle updated groups
  6063. * @param {Number[]} ids
  6064. * @private
  6065. */
  6066. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  6067. this._onAdd(ids);
  6068. };
  6069. /**
  6070. * Handle changed groups
  6071. * @param {Number[]} ids
  6072. * @private
  6073. */
  6074. GroupSet.prototype._onAdd = function _onAdd(ids) {
  6075. var me = this;
  6076. ids.forEach(function (id) {
  6077. var group = me.groups[id];
  6078. if (!group) {
  6079. var groupOptions = Object.create(me.options);
  6080. util.extend(groupOptions, {
  6081. height: null
  6082. });
  6083. group = new Group(me, me.labelSet, me.backgroundPanel, me.axisPanel, id, groupOptions);
  6084. group.on('change', me.emit.bind(me, 'change')); // propagate change event
  6085. group.setRange(me.range);
  6086. group.setItems(me.itemsData); // attach items data
  6087. me.groups[id] = group;
  6088. group.parent = me;
  6089. }
  6090. // update group data
  6091. group.setData(me.groupsData.get(id));
  6092. });
  6093. this._updateGroupIds();
  6094. this.emit('change');
  6095. };
  6096. /**
  6097. * Handle removed groups
  6098. * @param {Number[]} ids
  6099. * @private
  6100. */
  6101. GroupSet.prototype._onRemove = function _onRemove(ids) {
  6102. var groups = this.groups;
  6103. ids.forEach(function (id) {
  6104. var group = groups[id];
  6105. if (group) {
  6106. group.setItems(); // detach items data
  6107. group.hide(); // FIXME: for some reason when doing setItems after hide, setItems again makes the label visible
  6108. delete groups[id];
  6109. }
  6110. });
  6111. this._updateGroupIds();
  6112. this.emit('change');
  6113. };
  6114. /**
  6115. * Find the GroupSet from an event target:
  6116. * searches for the attribute 'timeline-groupset' in the event target's element
  6117. * tree, then finds the right group in this groupset
  6118. * @param {Event} event
  6119. * @return {Group | null} group
  6120. */
  6121. GroupSet.groupSetFromTarget = function groupSetFromTarget (event) {
  6122. var target = event.target;
  6123. while (target) {
  6124. if (target.hasOwnProperty('timeline-groupset')) {
  6125. return target['timeline-groupset'];
  6126. }
  6127. target = target.parentNode;
  6128. }
  6129. return null;
  6130. };
  6131. /**
  6132. * Find the Group from an event target:
  6133. * searches for the two elements having attributes 'timeline-groupset' and
  6134. * 'timeline-itemset' in the event target's element, then finds the right group.
  6135. * @param {Event} event
  6136. * @return {Group | null} group
  6137. */
  6138. GroupSet.groupFromTarget = function groupFromTarget (event) {
  6139. // find the groupSet
  6140. var groupSet = GroupSet.groupSetFromTarget(event);
  6141. // find the ItemSet
  6142. var itemSet = ItemSet.itemSetFromTarget(event);
  6143. // find the right group
  6144. if (groupSet && itemSet) {
  6145. for (var groupId in groupSet.groups) {
  6146. if (groupSet.groups.hasOwnProperty(groupId)) {
  6147. var group = groupSet.groups[groupId];
  6148. if (group.itemSet == itemSet) {
  6149. return group;
  6150. }
  6151. }
  6152. }
  6153. }
  6154. return null;
  6155. };
  6156. /**
  6157. * Create a timeline visualization
  6158. * @param {HTMLElement} container
  6159. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6160. * @param {Object} [options] See Timeline.setOptions for the available options.
  6161. * @constructor
  6162. */
  6163. function Timeline (container, items, options) {
  6164. // validate arguments
  6165. if (!container) throw new Error('No container element provided');
  6166. var me = this;
  6167. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6168. this.options = {
  6169. orientation: 'bottom',
  6170. direction: 'horizontal', // 'horizontal' or 'vertical'
  6171. autoResize: true,
  6172. editable: false,
  6173. selectable: true,
  6174. snap: null, // will be specified after timeaxis is created
  6175. min: null,
  6176. max: null,
  6177. zoomMin: 10, // milliseconds
  6178. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6179. // moveable: true, // TODO: option moveable
  6180. // zoomable: true, // TODO: option zoomable
  6181. showMinorLabels: true,
  6182. showMajorLabels: true,
  6183. showCurrentTime: false,
  6184. showCustomTime: false,
  6185. type: 'box',
  6186. align: 'center',
  6187. margin: {
  6188. axis: 20,
  6189. item: 10
  6190. },
  6191. padding: 5,
  6192. onAdd: function (item, callback) {
  6193. callback(item);
  6194. },
  6195. onUpdate: function (item, callback) {
  6196. callback(item);
  6197. },
  6198. onMove: function (item, callback) {
  6199. callback(item);
  6200. },
  6201. onRemove: function (item, callback) {
  6202. callback(item);
  6203. },
  6204. toScreen: me._toScreen.bind(me),
  6205. toTime: me._toTime.bind(me)
  6206. };
  6207. // root panel
  6208. var rootOptions = util.extend(Object.create(this.options), {
  6209. height: function () {
  6210. if (me.options.height) {
  6211. // fixed height
  6212. return me.options.height;
  6213. }
  6214. else {
  6215. // auto height
  6216. // TODO: implement a css based solution to automatically have the right hight
  6217. return (me.timeAxis.height + me.contentPanel.height) + 'px';
  6218. }
  6219. }
  6220. });
  6221. this.rootPanel = new RootPanel(container, rootOptions);
  6222. // single select (or unselect) when tapping an item
  6223. this.rootPanel.on('tap', this._onSelectItem.bind(this));
  6224. // multi select when holding mouse/touch, or on ctrl+click
  6225. this.rootPanel.on('hold', this._onMultiSelectItem.bind(this));
  6226. // add item on doubletap
  6227. this.rootPanel.on('doubletap', this._onAddItem.bind(this));
  6228. // side panel
  6229. var sideOptions = util.extend(Object.create(this.options), {
  6230. top: function () {
  6231. return (sideOptions.orientation == 'top') ? '0' : '';
  6232. },
  6233. bottom: function () {
  6234. return (sideOptions.orientation == 'top') ? '' : '0';
  6235. },
  6236. left: '0',
  6237. right: null,
  6238. height: '100%',
  6239. width: function () {
  6240. if (me.groupSet) {
  6241. return me.groupSet.getLabelsWidth();
  6242. }
  6243. else {
  6244. return 0;
  6245. }
  6246. },
  6247. className: function () {
  6248. return 'side' + (me.groupsData ? '' : ' hidden');
  6249. }
  6250. });
  6251. this.sidePanel = new Panel(sideOptions);
  6252. this.rootPanel.appendChild(this.sidePanel);
  6253. // main panel (contains time axis and itemsets)
  6254. var mainOptions = util.extend(Object.create(this.options), {
  6255. left: function () {
  6256. // we align left to enable a smooth resizing of the window
  6257. return me.sidePanel.width;
  6258. },
  6259. right: null,
  6260. height: '100%',
  6261. width: function () {
  6262. return me.rootPanel.width - me.sidePanel.width;
  6263. },
  6264. className: 'main'
  6265. });
  6266. this.mainPanel = new Panel(mainOptions);
  6267. this.rootPanel.appendChild(this.mainPanel);
  6268. // range
  6269. // TODO: move range inside rootPanel?
  6270. var rangeOptions = Object.create(this.options);
  6271. this.range = new Range(this.rootPanel, this.mainPanel, rangeOptions);
  6272. this.range.setRange(
  6273. now.clone().add('days', -3).valueOf(),
  6274. now.clone().add('days', 4).valueOf()
  6275. );
  6276. this.range.on('rangechange', function (properties) {
  6277. me.rootPanel.repaint();
  6278. me.emit('rangechange', properties);
  6279. });
  6280. this.range.on('rangechanged', function (properties) {
  6281. me.rootPanel.repaint();
  6282. me.emit('rangechanged', properties);
  6283. });
  6284. // panel with time axis
  6285. var timeAxisOptions = util.extend(Object.create(rootOptions), {
  6286. range: this.range,
  6287. left: null,
  6288. top: null,
  6289. width: null,
  6290. height: null
  6291. });
  6292. this.timeAxis = new TimeAxis(timeAxisOptions);
  6293. this.timeAxis.setRange(this.range);
  6294. this.options.snap = this.timeAxis.snap.bind(this.timeAxis);
  6295. this.mainPanel.appendChild(this.timeAxis);
  6296. // content panel (contains itemset(s))
  6297. var contentOptions = util.extend(Object.create(this.options), {
  6298. top: function () {
  6299. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6300. },
  6301. bottom: function () {
  6302. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6303. },
  6304. left: null,
  6305. right: null,
  6306. height: null,
  6307. width: null,
  6308. className: 'content'
  6309. });
  6310. this.contentPanel = new Panel(contentOptions);
  6311. this.mainPanel.appendChild(this.contentPanel);
  6312. // content panel (contains the vertical lines of box items)
  6313. var backgroundOptions = util.extend(Object.create(this.options), {
  6314. top: function () {
  6315. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6316. },
  6317. bottom: function () {
  6318. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6319. },
  6320. left: null,
  6321. right: null,
  6322. height: function () {
  6323. return me.contentPanel.height;
  6324. },
  6325. width: null,
  6326. className: 'background'
  6327. });
  6328. this.backgroundPanel = new Panel(backgroundOptions);
  6329. this.mainPanel.insertBefore(this.backgroundPanel, this.contentPanel);
  6330. // panel with axis holding the dots of item boxes
  6331. var axisPanelOptions = util.extend(Object.create(rootOptions), {
  6332. left: 0,
  6333. top: function () {
  6334. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6335. },
  6336. bottom: function () {
  6337. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6338. },
  6339. width: '100%',
  6340. height: 0,
  6341. className: 'axis'
  6342. });
  6343. this.axisPanel = new Panel(axisPanelOptions);
  6344. this.mainPanel.appendChild(this.axisPanel);
  6345. // content panel (contains itemset(s))
  6346. var sideContentOptions = util.extend(Object.create(this.options), {
  6347. top: function () {
  6348. return (me.options.orientation == 'top') ? (me.timeAxis.height + 'px') : '';
  6349. },
  6350. bottom: function () {
  6351. return (me.options.orientation == 'top') ? '' : (me.timeAxis.height + 'px');
  6352. },
  6353. left: null,
  6354. right: null,
  6355. height: null,
  6356. width: null,
  6357. className: 'side-content'
  6358. });
  6359. this.sideContentPanel = new Panel(sideContentOptions);
  6360. this.sidePanel.appendChild(this.sideContentPanel);
  6361. // current time bar
  6362. // Note: time bar will be attached in this.setOptions when selected
  6363. this.currentTime = new CurrentTime(this.range, rootOptions);
  6364. // custom time bar
  6365. // Note: time bar will be attached in this.setOptions when selected
  6366. this.customTime = new CustomTime(rootOptions);
  6367. this.customTime.on('timechange', function (time) {
  6368. me.emit('timechange', time);
  6369. });
  6370. this.customTime.on('timechanged', function (time) {
  6371. me.emit('timechanged', time);
  6372. });
  6373. this.itemSet = null;
  6374. this.groupSet = null;
  6375. // create groupset
  6376. this.setGroups(null);
  6377. this.itemsData = null; // DataSet
  6378. this.groupsData = null; // DataSet
  6379. // apply options
  6380. if (options) {
  6381. this.setOptions(options);
  6382. }
  6383. // create itemset and groupset
  6384. if (items) {
  6385. this.setItems(items);
  6386. }
  6387. }
  6388. // turn Timeline into an event emitter
  6389. Emitter(Timeline.prototype);
  6390. /**
  6391. * Set options
  6392. * @param {Object} options TODO: describe the available options
  6393. */
  6394. Timeline.prototype.setOptions = function (options) {
  6395. util.extend(this.options, options);
  6396. // force update of range (apply new min/max etc.)
  6397. // both start and end are optional
  6398. this.range.setRange(options.start, options.end);
  6399. if ('editable' in options || 'selectable' in options) {
  6400. if (this.options.selectable) {
  6401. // force update of selection
  6402. this.setSelection(this.getSelection());
  6403. }
  6404. else {
  6405. // remove selection
  6406. this.setSelection([]);
  6407. }
  6408. }
  6409. // validate the callback functions
  6410. var validateCallback = (function (fn) {
  6411. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  6412. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  6413. }
  6414. }).bind(this);
  6415. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  6416. // add/remove the current time bar
  6417. if (this.options.showCurrentTime) {
  6418. if (!this.mainPanel.hasChild(this.currentTime)) {
  6419. this.mainPanel.appendChild(this.currentTime);
  6420. this.currentTime.start();
  6421. }
  6422. }
  6423. else {
  6424. if (this.mainPanel.hasChild(this.currentTime)) {
  6425. this.currentTime.stop();
  6426. this.mainPanel.removeChild(this.currentTime);
  6427. }
  6428. }
  6429. // add/remove the custom time bar
  6430. if (this.options.showCustomTime) {
  6431. if (!this.mainPanel.hasChild(this.customTime)) {
  6432. this.mainPanel.appendChild(this.customTime);
  6433. }
  6434. }
  6435. else {
  6436. if (this.mainPanel.hasChild(this.customTime)) {
  6437. this.mainPanel.removeChild(this.customTime);
  6438. }
  6439. }
  6440. // repaint everything
  6441. this.rootPanel.repaint();
  6442. };
  6443. /**
  6444. * Set a custom time bar
  6445. * @param {Date} time
  6446. */
  6447. Timeline.prototype.setCustomTime = function (time) {
  6448. if (!this.customTime) {
  6449. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6450. }
  6451. this.customTime.setCustomTime(time);
  6452. };
  6453. /**
  6454. * Retrieve the current custom time.
  6455. * @return {Date} customTime
  6456. */
  6457. Timeline.prototype.getCustomTime = function() {
  6458. if (!this.customTime) {
  6459. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6460. }
  6461. return this.customTime.getCustomTime();
  6462. };
  6463. /**
  6464. * Set items
  6465. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  6466. */
  6467. Timeline.prototype.setItems = function(items) {
  6468. var initialLoad = (this.itemsData == null);
  6469. // convert to type DataSet when needed
  6470. var newDataSet;
  6471. if (!items) {
  6472. newDataSet = null;
  6473. }
  6474. else if (items instanceof DataSet) {
  6475. newDataSet = items;
  6476. }
  6477. if (!(items instanceof DataSet)) {
  6478. newDataSet = new DataSet({
  6479. convert: {
  6480. start: 'Date',
  6481. end: 'Date'
  6482. }
  6483. });
  6484. newDataSet.add(items);
  6485. }
  6486. // set items
  6487. this.itemsData = newDataSet;
  6488. (this.itemSet || this.groupSet).setItems(newDataSet);
  6489. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6490. // apply the data range as range
  6491. var dataRange = this.getItemRange();
  6492. // add 5% space on both sides
  6493. var start = dataRange.min;
  6494. var end = dataRange.max;
  6495. if (start != null && end != null) {
  6496. var interval = (end.valueOf() - start.valueOf());
  6497. if (interval <= 0) {
  6498. // prevent an empty interval
  6499. interval = 24 * 60 * 60 * 1000; // 1 day
  6500. }
  6501. start = new Date(start.valueOf() - interval * 0.05);
  6502. end = new Date(end.valueOf() + interval * 0.05);
  6503. }
  6504. // override specified start and/or end date
  6505. if (this.options.start != undefined) {
  6506. start = util.convert(this.options.start, 'Date');
  6507. }
  6508. if (this.options.end != undefined) {
  6509. end = util.convert(this.options.end, 'Date');
  6510. }
  6511. // apply range if there is a min or max available
  6512. if (start != null || end != null) {
  6513. this.range.setRange(start, end);
  6514. }
  6515. }
  6516. };
  6517. /**
  6518. * Set groups
  6519. * @param {vis.DataSet | Array | google.visualization.DataTable} groupSet
  6520. */
  6521. Timeline.prototype.setGroups = function(groupSet) {
  6522. var me = this;
  6523. this.groupsData = groupSet;
  6524. // create options for the itemset or groupset
  6525. var options = util.extend(Object.create(this.options), {
  6526. top: null,
  6527. bottom: null,
  6528. right: null,
  6529. left: null,
  6530. width: null,
  6531. height: null
  6532. });
  6533. if (this.groupsData) {
  6534. // Create a GroupSet
  6535. // remove itemset if existing
  6536. if (this.itemSet) {
  6537. this.itemSet.hide(); // TODO: not so nice having to hide here
  6538. this.contentPanel.removeChild(this.itemSet);
  6539. this.itemSet.setItems(); // disconnect from itemset
  6540. this.itemSet = null;
  6541. }
  6542. // create new GroupSet when needed
  6543. if (!this.groupSet) {
  6544. this.groupSet = new GroupSet(this.contentPanel, this.sideContentPanel, this.backgroundPanel, this.axisPanel, options);
  6545. this.groupSet.on('change', this.rootPanel.repaint.bind(this.rootPanel));
  6546. this.groupSet.setRange(this.range);
  6547. this.groupSet.setItems(this.itemsData);
  6548. this.groupSet.setGroups(this.groupsData);
  6549. this.contentPanel.appendChild(this.groupSet);
  6550. }
  6551. else {
  6552. this.groupSet.setGroups(this.groupsData);
  6553. }
  6554. }
  6555. else {
  6556. // ItemSet
  6557. if (this.groupSet) {
  6558. this.groupSet.hide(); // TODO: not so nice having to hide here
  6559. //this.groupSet.setGroups(); // disconnect from groupset
  6560. this.groupSet.setItems(); // disconnect from itemset
  6561. this.contentPanel.removeChild(this.groupSet);
  6562. this.groupSet = null;
  6563. }
  6564. // create new items
  6565. this.itemSet = new ItemSet(this.backgroundPanel, this.axisPanel, options);
  6566. this.itemSet.setRange(this.range);
  6567. this.itemSet.setItems(this.itemsData);
  6568. this.itemSet.on('change', me.rootPanel.repaint.bind(me.rootPanel));
  6569. this.contentPanel.appendChild(this.itemSet);
  6570. }
  6571. };
  6572. /**
  6573. * Get the data range of the item set.
  6574. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6575. * When no minimum is found, min==null
  6576. * When no maximum is found, max==null
  6577. */
  6578. Timeline.prototype.getItemRange = function getItemRange() {
  6579. // calculate min from start filed
  6580. var itemsData = this.itemsData,
  6581. min = null,
  6582. max = null;
  6583. if (itemsData) {
  6584. // calculate the minimum value of the field 'start'
  6585. var minItem = itemsData.min('start');
  6586. min = minItem ? minItem.start.valueOf() : null;
  6587. // calculate maximum value of fields 'start' and 'end'
  6588. var maxStartItem = itemsData.max('start');
  6589. if (maxStartItem) {
  6590. max = maxStartItem.start.valueOf();
  6591. }
  6592. var maxEndItem = itemsData.max('end');
  6593. if (maxEndItem) {
  6594. if (max == null) {
  6595. max = maxEndItem.end.valueOf();
  6596. }
  6597. else {
  6598. max = Math.max(max, maxEndItem.end.valueOf());
  6599. }
  6600. }
  6601. }
  6602. return {
  6603. min: (min != null) ? new Date(min) : null,
  6604. max: (max != null) ? new Date(max) : null
  6605. };
  6606. };
  6607. /**
  6608. * Set selected items by their id. Replaces the current selection
  6609. * Unknown id's are silently ignored.
  6610. * @param {Array} [ids] An array with zero or more id's of the items to be
  6611. * selected. If ids is an empty array, all items will be
  6612. * unselected.
  6613. */
  6614. Timeline.prototype.setSelection = function setSelection (ids) {
  6615. var itemOrGroupSet = (this.itemSet || this.groupSet);
  6616. if (itemOrGroupSet) itemOrGroupSet.setSelection(ids);
  6617. };
  6618. /**
  6619. * Get the selected items by their id
  6620. * @return {Array} ids The ids of the selected items
  6621. */
  6622. Timeline.prototype.getSelection = function getSelection() {
  6623. var itemOrGroupSet = (this.itemSet || this.groupSet);
  6624. return itemOrGroupSet ? itemOrGroupSet.getSelection() : [];
  6625. };
  6626. /**
  6627. * Set the visible window. Both parameters are optional, you can change only
  6628. * start or only end.
  6629. * @param {Date | Number | String} [start] Start date of visible window
  6630. * @param {Date | Number | String} [end] End date of visible window
  6631. */
  6632. // TODO: implement support for setWindow({start: ..., end: ...})
  6633. // TODO: rename setWindow to setRange?
  6634. Timeline.prototype.setWindow = function setWindow(start, end) {
  6635. this.range.setRange(start, end);
  6636. };
  6637. /**
  6638. * Get the visible window
  6639. * @return {{start: Date, end: Date}} Visible range
  6640. */
  6641. // TODO: rename getWindow to getRange?
  6642. Timeline.prototype.getWindow = function setWindow() {
  6643. var range = this.range.getRange();
  6644. return {
  6645. start: new Date(range.start),
  6646. end: new Date(range.end)
  6647. };
  6648. };
  6649. /**
  6650. * Handle selecting/deselecting an item when tapping it
  6651. * @param {Event} event
  6652. * @private
  6653. */
  6654. // TODO: move this function to ItemSet
  6655. Timeline.prototype._onSelectItem = function (event) {
  6656. if (!this.options.selectable) return;
  6657. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  6658. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  6659. if (ctrlKey || shiftKey) {
  6660. this._onMultiSelectItem(event);
  6661. return;
  6662. }
  6663. var oldSelection = this.getSelection();
  6664. var item = ItemSet.itemFromTarget(event);
  6665. var selection = item ? [item.id] : [];
  6666. this.setSelection(selection);
  6667. var newSelection = this.getSelection();
  6668. // if selection is changed, emit a select event
  6669. if (!util.equalArray(oldSelection, newSelection)) {
  6670. this.emit('select', {
  6671. items: this.getSelection()
  6672. });
  6673. }
  6674. event.stopPropagation();
  6675. };
  6676. /**
  6677. * Handle creation and updates of an item on double tap
  6678. * @param event
  6679. * @private
  6680. */
  6681. Timeline.prototype._onAddItem = function (event) {
  6682. if (!this.options.selectable) return;
  6683. if (!this.options.editable) return;
  6684. var me = this,
  6685. item = ItemSet.itemFromTarget(event);
  6686. if (item) {
  6687. // update item
  6688. // execute async handler to update the item (or cancel it)
  6689. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  6690. this.options.onUpdate(itemData, function (itemData) {
  6691. if (itemData) {
  6692. me.itemsData.update(itemData);
  6693. }
  6694. });
  6695. }
  6696. else {
  6697. // add item
  6698. var xAbs = vis.util.getAbsoluteLeft(this.rootPanel.frame);
  6699. var x = event.gesture.center.pageX - xAbs;
  6700. var newItem = {
  6701. start: this.timeAxis.snap(this._toTime(x)),
  6702. content: 'new item'
  6703. };
  6704. var id = util.randomUUID();
  6705. newItem[this.itemsData.fieldId] = id;
  6706. var group = GroupSet.groupFromTarget(event);
  6707. if (group) {
  6708. newItem.group = group.groupId;
  6709. }
  6710. // execute async handler to customize (or cancel) adding an item
  6711. this.options.onAdd(newItem, function (item) {
  6712. if (item) {
  6713. me.itemsData.add(newItem);
  6714. // TODO: need to trigger a repaint?
  6715. }
  6716. });
  6717. }
  6718. };
  6719. /**
  6720. * Handle selecting/deselecting multiple items when holding an item
  6721. * @param {Event} event
  6722. * @private
  6723. */
  6724. // TODO: move this function to ItemSet
  6725. Timeline.prototype._onMultiSelectItem = function (event) {
  6726. if (!this.options.selectable) return;
  6727. var selection,
  6728. item = ItemSet.itemFromTarget(event);
  6729. if (item) {
  6730. // multi select items
  6731. selection = this.getSelection(); // current selection
  6732. var index = selection.indexOf(item.id);
  6733. if (index == -1) {
  6734. // item is not yet selected -> select it
  6735. selection.push(item.id);
  6736. }
  6737. else {
  6738. // item is already selected -> deselect it
  6739. selection.splice(index, 1);
  6740. }
  6741. this.setSelection(selection);
  6742. this.emit('select', {
  6743. items: this.getSelection()
  6744. });
  6745. event.stopPropagation();
  6746. }
  6747. };
  6748. /**
  6749. * Convert a position on screen (pixels) to a datetime
  6750. * @param {int} x Position on the screen in pixels
  6751. * @return {Date} time The datetime the corresponds with given position x
  6752. * @private
  6753. */
  6754. Timeline.prototype._toTime = function _toTime(x) {
  6755. var conversion = this.range.conversion(this.mainPanel.width);
  6756. return new Date(x / conversion.scale + conversion.offset);
  6757. };
  6758. /**
  6759. * Convert a datetime (Date object) into a position on the screen
  6760. * @param {Date} time A date
  6761. * @return {int} x The position on the screen in pixels which corresponds
  6762. * with the given date.
  6763. * @private
  6764. */
  6765. Timeline.prototype._toScreen = function _toScreen(time) {
  6766. var conversion = this.range.conversion(this.mainPanel.width);
  6767. return (time.valueOf() - conversion.offset) * conversion.scale;
  6768. };
  6769. (function(exports) {
  6770. /**
  6771. * Parse a text source containing data in DOT language into a JSON object.
  6772. * The object contains two lists: one with nodes and one with edges.
  6773. *
  6774. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6775. *
  6776. * @param {String} data Text containing a graph in DOT-notation
  6777. * @return {Object} graph An object containing two parameters:
  6778. * {Object[]} nodes
  6779. * {Object[]} edges
  6780. */
  6781. function parseDOT (data) {
  6782. dot = data;
  6783. return parseGraph();
  6784. }
  6785. // token types enumeration
  6786. var TOKENTYPE = {
  6787. NULL : 0,
  6788. DELIMITER : 1,
  6789. IDENTIFIER: 2,
  6790. UNKNOWN : 3
  6791. };
  6792. // map with all delimiters
  6793. var DELIMITERS = {
  6794. '{': true,
  6795. '}': true,
  6796. '[': true,
  6797. ']': true,
  6798. ';': true,
  6799. '=': true,
  6800. ',': true,
  6801. '->': true,
  6802. '--': true
  6803. };
  6804. var dot = ''; // current dot file
  6805. var index = 0; // current index in dot file
  6806. var c = ''; // current token character in expr
  6807. var token = ''; // current token
  6808. var tokenType = TOKENTYPE.NULL; // type of the token
  6809. /**
  6810. * Get the first character from the dot file.
  6811. * The character is stored into the char c. If the end of the dot file is
  6812. * reached, the function puts an empty string in c.
  6813. */
  6814. function first() {
  6815. index = 0;
  6816. c = dot.charAt(0);
  6817. }
  6818. /**
  6819. * Get the next character from the dot file.
  6820. * The character is stored into the char c. If the end of the dot file is
  6821. * reached, the function puts an empty string in c.
  6822. */
  6823. function next() {
  6824. index++;
  6825. c = dot.charAt(index);
  6826. }
  6827. /**
  6828. * Preview the next character from the dot file.
  6829. * @return {String} cNext
  6830. */
  6831. function nextPreview() {
  6832. return dot.charAt(index + 1);
  6833. }
  6834. /**
  6835. * Test whether given character is alphabetic or numeric
  6836. * @param {String} c
  6837. * @return {Boolean} isAlphaNumeric
  6838. */
  6839. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  6840. function isAlphaNumeric(c) {
  6841. return regexAlphaNumeric.test(c);
  6842. }
  6843. /**
  6844. * Merge all properties of object b into object b
  6845. * @param {Object} a
  6846. * @param {Object} b
  6847. * @return {Object} a
  6848. */
  6849. function merge (a, b) {
  6850. if (!a) {
  6851. a = {};
  6852. }
  6853. if (b) {
  6854. for (var name in b) {
  6855. if (b.hasOwnProperty(name)) {
  6856. a[name] = b[name];
  6857. }
  6858. }
  6859. }
  6860. return a;
  6861. }
  6862. /**
  6863. * Set a value in an object, where the provided parameter name can be a
  6864. * path with nested parameters. For example:
  6865. *
  6866. * var obj = {a: 2};
  6867. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  6868. *
  6869. * @param {Object} obj
  6870. * @param {String} path A parameter name or dot-separated parameter path,
  6871. * like "color.highlight.border".
  6872. * @param {*} value
  6873. */
  6874. function setValue(obj, path, value) {
  6875. var keys = path.split('.');
  6876. var o = obj;
  6877. while (keys.length) {
  6878. var key = keys.shift();
  6879. if (keys.length) {
  6880. // this isn't the end point
  6881. if (!o[key]) {
  6882. o[key] = {};
  6883. }
  6884. o = o[key];
  6885. }
  6886. else {
  6887. // this is the end point
  6888. o[key] = value;
  6889. }
  6890. }
  6891. }
  6892. /**
  6893. * Add a node to a graph object. If there is already a node with
  6894. * the same id, their attributes will be merged.
  6895. * @param {Object} graph
  6896. * @param {Object} node
  6897. */
  6898. function addNode(graph, node) {
  6899. var i, len;
  6900. var current = null;
  6901. // find root graph (in case of subgraph)
  6902. var graphs = [graph]; // list with all graphs from current graph to root graph
  6903. var root = graph;
  6904. while (root.parent) {
  6905. graphs.push(root.parent);
  6906. root = root.parent;
  6907. }
  6908. // find existing node (at root level) by its id
  6909. if (root.nodes) {
  6910. for (i = 0, len = root.nodes.length; i < len; i++) {
  6911. if (node.id === root.nodes[i].id) {
  6912. current = root.nodes[i];
  6913. break;
  6914. }
  6915. }
  6916. }
  6917. if (!current) {
  6918. // this is a new node
  6919. current = {
  6920. id: node.id
  6921. };
  6922. if (graph.node) {
  6923. // clone default attributes
  6924. current.attr = merge(current.attr, graph.node);
  6925. }
  6926. }
  6927. // add node to this (sub)graph and all its parent graphs
  6928. for (i = graphs.length - 1; i >= 0; i--) {
  6929. var g = graphs[i];
  6930. if (!g.nodes) {
  6931. g.nodes = [];
  6932. }
  6933. if (g.nodes.indexOf(current) == -1) {
  6934. g.nodes.push(current);
  6935. }
  6936. }
  6937. // merge attributes
  6938. if (node.attr) {
  6939. current.attr = merge(current.attr, node.attr);
  6940. }
  6941. }
  6942. /**
  6943. * Add an edge to a graph object
  6944. * @param {Object} graph
  6945. * @param {Object} edge
  6946. */
  6947. function addEdge(graph, edge) {
  6948. if (!graph.edges) {
  6949. graph.edges = [];
  6950. }
  6951. graph.edges.push(edge);
  6952. if (graph.edge) {
  6953. var attr = merge({}, graph.edge); // clone default attributes
  6954. edge.attr = merge(attr, edge.attr); // merge attributes
  6955. }
  6956. }
  6957. /**
  6958. * Create an edge to a graph object
  6959. * @param {Object} graph
  6960. * @param {String | Number | Object} from
  6961. * @param {String | Number | Object} to
  6962. * @param {String} type
  6963. * @param {Object | null} attr
  6964. * @return {Object} edge
  6965. */
  6966. function createEdge(graph, from, to, type, attr) {
  6967. var edge = {
  6968. from: from,
  6969. to: to,
  6970. type: type
  6971. };
  6972. if (graph.edge) {
  6973. edge.attr = merge({}, graph.edge); // clone default attributes
  6974. }
  6975. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  6976. return edge;
  6977. }
  6978. /**
  6979. * Get next token in the current dot file.
  6980. * The token and token type are available as token and tokenType
  6981. */
  6982. function getToken() {
  6983. tokenType = TOKENTYPE.NULL;
  6984. token = '';
  6985. // skip over whitespaces
  6986. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  6987. next();
  6988. }
  6989. do {
  6990. var isComment = false;
  6991. // skip comment
  6992. if (c == '#') {
  6993. // find the previous non-space character
  6994. var i = index - 1;
  6995. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  6996. i--;
  6997. }
  6998. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  6999. // the # is at the start of a line, this is indeed a line comment
  7000. while (c != '' && c != '\n') {
  7001. next();
  7002. }
  7003. isComment = true;
  7004. }
  7005. }
  7006. if (c == '/' && nextPreview() == '/') {
  7007. // skip line comment
  7008. while (c != '' && c != '\n') {
  7009. next();
  7010. }
  7011. isComment = true;
  7012. }
  7013. if (c == '/' && nextPreview() == '*') {
  7014. // skip block comment
  7015. while (c != '') {
  7016. if (c == '*' && nextPreview() == '/') {
  7017. // end of block comment found. skip these last two characters
  7018. next();
  7019. next();
  7020. break;
  7021. }
  7022. else {
  7023. next();
  7024. }
  7025. }
  7026. isComment = true;
  7027. }
  7028. // skip over whitespaces
  7029. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7030. next();
  7031. }
  7032. }
  7033. while (isComment);
  7034. // check for end of dot file
  7035. if (c == '') {
  7036. // token is still empty
  7037. tokenType = TOKENTYPE.DELIMITER;
  7038. return;
  7039. }
  7040. // check for delimiters consisting of 2 characters
  7041. var c2 = c + nextPreview();
  7042. if (DELIMITERS[c2]) {
  7043. tokenType = TOKENTYPE.DELIMITER;
  7044. token = c2;
  7045. next();
  7046. next();
  7047. return;
  7048. }
  7049. // check for delimiters consisting of 1 character
  7050. if (DELIMITERS[c]) {
  7051. tokenType = TOKENTYPE.DELIMITER;
  7052. token = c;
  7053. next();
  7054. return;
  7055. }
  7056. // check for an identifier (number or string)
  7057. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7058. if (isAlphaNumeric(c) || c == '-') {
  7059. token += c;
  7060. next();
  7061. while (isAlphaNumeric(c)) {
  7062. token += c;
  7063. next();
  7064. }
  7065. if (token == 'false') {
  7066. token = false; // convert to boolean
  7067. }
  7068. else if (token == 'true') {
  7069. token = true; // convert to boolean
  7070. }
  7071. else if (!isNaN(Number(token))) {
  7072. token = Number(token); // convert to number
  7073. }
  7074. tokenType = TOKENTYPE.IDENTIFIER;
  7075. return;
  7076. }
  7077. // check for a string enclosed by double quotes
  7078. if (c == '"') {
  7079. next();
  7080. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7081. token += c;
  7082. if (c == '"') { // skip the escape character
  7083. next();
  7084. }
  7085. next();
  7086. }
  7087. if (c != '"') {
  7088. throw newSyntaxError('End of string " expected');
  7089. }
  7090. next();
  7091. tokenType = TOKENTYPE.IDENTIFIER;
  7092. return;
  7093. }
  7094. // something unknown is found, wrong characters, a syntax error
  7095. tokenType = TOKENTYPE.UNKNOWN;
  7096. while (c != '') {
  7097. token += c;
  7098. next();
  7099. }
  7100. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7101. }
  7102. /**
  7103. * Parse a graph.
  7104. * @returns {Object} graph
  7105. */
  7106. function parseGraph() {
  7107. var graph = {};
  7108. first();
  7109. getToken();
  7110. // optional strict keyword
  7111. if (token == 'strict') {
  7112. graph.strict = true;
  7113. getToken();
  7114. }
  7115. // graph or digraph keyword
  7116. if (token == 'graph' || token == 'digraph') {
  7117. graph.type = token;
  7118. getToken();
  7119. }
  7120. // optional graph id
  7121. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7122. graph.id = token;
  7123. getToken();
  7124. }
  7125. // open angle bracket
  7126. if (token != '{') {
  7127. throw newSyntaxError('Angle bracket { expected');
  7128. }
  7129. getToken();
  7130. // statements
  7131. parseStatements(graph);
  7132. // close angle bracket
  7133. if (token != '}') {
  7134. throw newSyntaxError('Angle bracket } expected');
  7135. }
  7136. getToken();
  7137. // end of file
  7138. if (token !== '') {
  7139. throw newSyntaxError('End of file expected');
  7140. }
  7141. getToken();
  7142. // remove temporary default properties
  7143. delete graph.node;
  7144. delete graph.edge;
  7145. delete graph.graph;
  7146. return graph;
  7147. }
  7148. /**
  7149. * Parse a list with statements.
  7150. * @param {Object} graph
  7151. */
  7152. function parseStatements (graph) {
  7153. while (token !== '' && token != '}') {
  7154. parseStatement(graph);
  7155. if (token == ';') {
  7156. getToken();
  7157. }
  7158. }
  7159. }
  7160. /**
  7161. * Parse a single statement. Can be a an attribute statement, node
  7162. * statement, a series of node statements and edge statements, or a
  7163. * parameter.
  7164. * @param {Object} graph
  7165. */
  7166. function parseStatement(graph) {
  7167. // parse subgraph
  7168. var subgraph = parseSubgraph(graph);
  7169. if (subgraph) {
  7170. // edge statements
  7171. parseEdge(graph, subgraph);
  7172. return;
  7173. }
  7174. // parse an attribute statement
  7175. var attr = parseAttributeStatement(graph);
  7176. if (attr) {
  7177. return;
  7178. }
  7179. // parse node
  7180. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7181. throw newSyntaxError('Identifier expected');
  7182. }
  7183. var id = token; // id can be a string or a number
  7184. getToken();
  7185. if (token == '=') {
  7186. // id statement
  7187. getToken();
  7188. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7189. throw newSyntaxError('Identifier expected');
  7190. }
  7191. graph[id] = token;
  7192. getToken();
  7193. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7194. }
  7195. else {
  7196. parseNodeStatement(graph, id);
  7197. }
  7198. }
  7199. /**
  7200. * Parse a subgraph
  7201. * @param {Object} graph parent graph object
  7202. * @return {Object | null} subgraph
  7203. */
  7204. function parseSubgraph (graph) {
  7205. var subgraph = null;
  7206. // optional subgraph keyword
  7207. if (token == 'subgraph') {
  7208. subgraph = {};
  7209. subgraph.type = 'subgraph';
  7210. getToken();
  7211. // optional graph id
  7212. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7213. subgraph.id = token;
  7214. getToken();
  7215. }
  7216. }
  7217. // open angle bracket
  7218. if (token == '{') {
  7219. getToken();
  7220. if (!subgraph) {
  7221. subgraph = {};
  7222. }
  7223. subgraph.parent = graph;
  7224. subgraph.node = graph.node;
  7225. subgraph.edge = graph.edge;
  7226. subgraph.graph = graph.graph;
  7227. // statements
  7228. parseStatements(subgraph);
  7229. // close angle bracket
  7230. if (token != '}') {
  7231. throw newSyntaxError('Angle bracket } expected');
  7232. }
  7233. getToken();
  7234. // remove temporary default properties
  7235. delete subgraph.node;
  7236. delete subgraph.edge;
  7237. delete subgraph.graph;
  7238. delete subgraph.parent;
  7239. // register at the parent graph
  7240. if (!graph.subgraphs) {
  7241. graph.subgraphs = [];
  7242. }
  7243. graph.subgraphs.push(subgraph);
  7244. }
  7245. return subgraph;
  7246. }
  7247. /**
  7248. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7249. * Available keywords are 'node', 'edge', 'graph'.
  7250. * The previous list with default attributes will be replaced
  7251. * @param {Object} graph
  7252. * @returns {String | null} keyword Returns the name of the parsed attribute
  7253. * (node, edge, graph), or null if nothing
  7254. * is parsed.
  7255. */
  7256. function parseAttributeStatement (graph) {
  7257. // attribute statements
  7258. if (token == 'node') {
  7259. getToken();
  7260. // node attributes
  7261. graph.node = parseAttributeList();
  7262. return 'node';
  7263. }
  7264. else if (token == 'edge') {
  7265. getToken();
  7266. // edge attributes
  7267. graph.edge = parseAttributeList();
  7268. return 'edge';
  7269. }
  7270. else if (token == 'graph') {
  7271. getToken();
  7272. // graph attributes
  7273. graph.graph = parseAttributeList();
  7274. return 'graph';
  7275. }
  7276. return null;
  7277. }
  7278. /**
  7279. * parse a node statement
  7280. * @param {Object} graph
  7281. * @param {String | Number} id
  7282. */
  7283. function parseNodeStatement(graph, id) {
  7284. // node statement
  7285. var node = {
  7286. id: id
  7287. };
  7288. var attr = parseAttributeList();
  7289. if (attr) {
  7290. node.attr = attr;
  7291. }
  7292. addNode(graph, node);
  7293. // edge statements
  7294. parseEdge(graph, id);
  7295. }
  7296. /**
  7297. * Parse an edge or a series of edges
  7298. * @param {Object} graph
  7299. * @param {String | Number} from Id of the from node
  7300. */
  7301. function parseEdge(graph, from) {
  7302. while (token == '->' || token == '--') {
  7303. var to;
  7304. var type = token;
  7305. getToken();
  7306. var subgraph = parseSubgraph(graph);
  7307. if (subgraph) {
  7308. to = subgraph;
  7309. }
  7310. else {
  7311. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7312. throw newSyntaxError('Identifier or subgraph expected');
  7313. }
  7314. to = token;
  7315. addNode(graph, {
  7316. id: to
  7317. });
  7318. getToken();
  7319. }
  7320. // parse edge attributes
  7321. var attr = parseAttributeList();
  7322. // create edge
  7323. var edge = createEdge(graph, from, to, type, attr);
  7324. addEdge(graph, edge);
  7325. from = to;
  7326. }
  7327. }
  7328. /**
  7329. * Parse a set with attributes,
  7330. * for example [label="1.000", shape=solid]
  7331. * @return {Object | null} attr
  7332. */
  7333. function parseAttributeList() {
  7334. var attr = null;
  7335. while (token == '[') {
  7336. getToken();
  7337. attr = {};
  7338. while (token !== '' && token != ']') {
  7339. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7340. throw newSyntaxError('Attribute name expected');
  7341. }
  7342. var name = token;
  7343. getToken();
  7344. if (token != '=') {
  7345. throw newSyntaxError('Equal sign = expected');
  7346. }
  7347. getToken();
  7348. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7349. throw newSyntaxError('Attribute value expected');
  7350. }
  7351. var value = token;
  7352. setValue(attr, name, value); // name can be a path
  7353. getToken();
  7354. if (token ==',') {
  7355. getToken();
  7356. }
  7357. }
  7358. if (token != ']') {
  7359. throw newSyntaxError('Bracket ] expected');
  7360. }
  7361. getToken();
  7362. }
  7363. return attr;
  7364. }
  7365. /**
  7366. * Create a syntax error with extra information on current token and index.
  7367. * @param {String} message
  7368. * @returns {SyntaxError} err
  7369. */
  7370. function newSyntaxError(message) {
  7371. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7372. }
  7373. /**
  7374. * Chop off text after a maximum length
  7375. * @param {String} text
  7376. * @param {Number} maxLength
  7377. * @returns {String}
  7378. */
  7379. function chop (text, maxLength) {
  7380. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7381. }
  7382. /**
  7383. * Execute a function fn for each pair of elements in two arrays
  7384. * @param {Array | *} array1
  7385. * @param {Array | *} array2
  7386. * @param {function} fn
  7387. */
  7388. function forEach2(array1, array2, fn) {
  7389. if (array1 instanceof Array) {
  7390. array1.forEach(function (elem1) {
  7391. if (array2 instanceof Array) {
  7392. array2.forEach(function (elem2) {
  7393. fn(elem1, elem2);
  7394. });
  7395. }
  7396. else {
  7397. fn(elem1, array2);
  7398. }
  7399. });
  7400. }
  7401. else {
  7402. if (array2 instanceof Array) {
  7403. array2.forEach(function (elem2) {
  7404. fn(array1, elem2);
  7405. });
  7406. }
  7407. else {
  7408. fn(array1, array2);
  7409. }
  7410. }
  7411. }
  7412. /**
  7413. * Convert a string containing a graph in DOT language into a map containing
  7414. * with nodes and edges in the format of graph.
  7415. * @param {String} data Text containing a graph in DOT-notation
  7416. * @return {Object} graphData
  7417. */
  7418. function DOTToGraph (data) {
  7419. // parse the DOT file
  7420. var dotData = parseDOT(data);
  7421. var graphData = {
  7422. nodes: [],
  7423. edges: [],
  7424. options: {}
  7425. };
  7426. // copy the nodes
  7427. if (dotData.nodes) {
  7428. dotData.nodes.forEach(function (dotNode) {
  7429. var graphNode = {
  7430. id: dotNode.id,
  7431. label: String(dotNode.label || dotNode.id)
  7432. };
  7433. merge(graphNode, dotNode.attr);
  7434. if (graphNode.image) {
  7435. graphNode.shape = 'image';
  7436. }
  7437. graphData.nodes.push(graphNode);
  7438. });
  7439. }
  7440. // copy the edges
  7441. if (dotData.edges) {
  7442. /**
  7443. * Convert an edge in DOT format to an edge with VisGraph format
  7444. * @param {Object} dotEdge
  7445. * @returns {Object} graphEdge
  7446. */
  7447. function convertEdge(dotEdge) {
  7448. var graphEdge = {
  7449. from: dotEdge.from,
  7450. to: dotEdge.to
  7451. };
  7452. merge(graphEdge, dotEdge.attr);
  7453. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  7454. return graphEdge;
  7455. }
  7456. dotData.edges.forEach(function (dotEdge) {
  7457. var from, to;
  7458. if (dotEdge.from instanceof Object) {
  7459. from = dotEdge.from.nodes;
  7460. }
  7461. else {
  7462. from = {
  7463. id: dotEdge.from
  7464. }
  7465. }
  7466. if (dotEdge.to instanceof Object) {
  7467. to = dotEdge.to.nodes;
  7468. }
  7469. else {
  7470. to = {
  7471. id: dotEdge.to
  7472. }
  7473. }
  7474. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  7475. dotEdge.from.edges.forEach(function (subEdge) {
  7476. var graphEdge = convertEdge(subEdge);
  7477. graphData.edges.push(graphEdge);
  7478. });
  7479. }
  7480. forEach2(from, to, function (from, to) {
  7481. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  7482. var graphEdge = convertEdge(subEdge);
  7483. graphData.edges.push(graphEdge);
  7484. });
  7485. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  7486. dotEdge.to.edges.forEach(function (subEdge) {
  7487. var graphEdge = convertEdge(subEdge);
  7488. graphData.edges.push(graphEdge);
  7489. });
  7490. }
  7491. });
  7492. }
  7493. // copy the options
  7494. if (dotData.attr) {
  7495. graphData.options = dotData.attr;
  7496. }
  7497. return graphData;
  7498. }
  7499. // exports
  7500. exports.parseDOT = parseDOT;
  7501. exports.DOTToGraph = DOTToGraph;
  7502. })(typeof util !== 'undefined' ? util : exports);
  7503. /**
  7504. * Canvas shapes used by the Graph
  7505. */
  7506. if (typeof CanvasRenderingContext2D !== 'undefined') {
  7507. /**
  7508. * Draw a circle shape
  7509. */
  7510. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  7511. this.beginPath();
  7512. this.arc(x, y, r, 0, 2*Math.PI, false);
  7513. };
  7514. /**
  7515. * Draw a square shape
  7516. * @param {Number} x horizontal center
  7517. * @param {Number} y vertical center
  7518. * @param {Number} r size, width and height of the square
  7519. */
  7520. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  7521. this.beginPath();
  7522. this.rect(x - r, y - r, r * 2, r * 2);
  7523. };
  7524. /**
  7525. * Draw a triangle shape
  7526. * @param {Number} x horizontal center
  7527. * @param {Number} y vertical center
  7528. * @param {Number} r radius, half the length of the sides of the triangle
  7529. */
  7530. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  7531. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7532. this.beginPath();
  7533. var s = r * 2;
  7534. var s2 = s / 2;
  7535. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7536. var h = Math.sqrt(s * s - s2 * s2); // height
  7537. this.moveTo(x, y - (h - ir));
  7538. this.lineTo(x + s2, y + ir);
  7539. this.lineTo(x - s2, y + ir);
  7540. this.lineTo(x, y - (h - ir));
  7541. this.closePath();
  7542. };
  7543. /**
  7544. * Draw a triangle shape in downward orientation
  7545. * @param {Number} x horizontal center
  7546. * @param {Number} y vertical center
  7547. * @param {Number} r radius
  7548. */
  7549. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  7550. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7551. this.beginPath();
  7552. var s = r * 2;
  7553. var s2 = s / 2;
  7554. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7555. var h = Math.sqrt(s * s - s2 * s2); // height
  7556. this.moveTo(x, y + (h - ir));
  7557. this.lineTo(x + s2, y - ir);
  7558. this.lineTo(x - s2, y - ir);
  7559. this.lineTo(x, y + (h - ir));
  7560. this.closePath();
  7561. };
  7562. /**
  7563. * Draw a star shape, a star with 5 points
  7564. * @param {Number} x horizontal center
  7565. * @param {Number} y vertical center
  7566. * @param {Number} r radius, half the length of the sides of the triangle
  7567. */
  7568. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  7569. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  7570. this.beginPath();
  7571. for (var n = 0; n < 10; n++) {
  7572. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  7573. this.lineTo(
  7574. x + radius * Math.sin(n * 2 * Math.PI / 10),
  7575. y - radius * Math.cos(n * 2 * Math.PI / 10)
  7576. );
  7577. }
  7578. this.closePath();
  7579. };
  7580. /**
  7581. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7582. */
  7583. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7584. var r2d = Math.PI/180;
  7585. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7586. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7587. this.beginPath();
  7588. this.moveTo(x+r,y);
  7589. this.lineTo(x+w-r,y);
  7590. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7591. this.lineTo(x+w,y+h-r);
  7592. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7593. this.lineTo(x+r,y+h);
  7594. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7595. this.lineTo(x,y+r);
  7596. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7597. };
  7598. /**
  7599. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7600. */
  7601. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7602. var kappa = .5522848,
  7603. ox = (w / 2) * kappa, // control point offset horizontal
  7604. oy = (h / 2) * kappa, // control point offset vertical
  7605. xe = x + w, // x-end
  7606. ye = y + h, // y-end
  7607. xm = x + w / 2, // x-middle
  7608. ym = y + h / 2; // y-middle
  7609. this.beginPath();
  7610. this.moveTo(x, ym);
  7611. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7612. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7613. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7614. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7615. };
  7616. /**
  7617. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7618. */
  7619. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7620. var f = 1/3;
  7621. var wEllipse = w;
  7622. var hEllipse = h * f;
  7623. var kappa = .5522848,
  7624. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7625. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7626. xe = x + wEllipse, // x-end
  7627. ye = y + hEllipse, // y-end
  7628. xm = x + wEllipse / 2, // x-middle
  7629. ym = y + hEllipse / 2, // y-middle
  7630. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7631. yeb = y + h; // y-end, bottom ellipse
  7632. this.beginPath();
  7633. this.moveTo(xe, ym);
  7634. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7635. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7636. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7637. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7638. this.lineTo(xe, ymb);
  7639. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7640. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7641. this.lineTo(x, ym);
  7642. };
  7643. /**
  7644. * Draw an arrow point (no line)
  7645. */
  7646. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  7647. // tail
  7648. var xt = x - length * Math.cos(angle);
  7649. var yt = y - length * Math.sin(angle);
  7650. // inner tail
  7651. // TODO: allow to customize different shapes
  7652. var xi = x - length * 0.9 * Math.cos(angle);
  7653. var yi = y - length * 0.9 * Math.sin(angle);
  7654. // left
  7655. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  7656. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  7657. // right
  7658. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  7659. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  7660. this.beginPath();
  7661. this.moveTo(x, y);
  7662. this.lineTo(xl, yl);
  7663. this.lineTo(xi, yi);
  7664. this.lineTo(xr, yr);
  7665. this.closePath();
  7666. };
  7667. /**
  7668. * Sets up the dashedLine functionality for drawing
  7669. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  7670. * @author David Jordan
  7671. * @date 2012-08-08
  7672. */
  7673. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  7674. if (!dashArray) dashArray=[10,5];
  7675. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  7676. var dashCount = dashArray.length;
  7677. this.moveTo(x, y);
  7678. var dx = (x2-x), dy = (y2-y);
  7679. var slope = dy/dx;
  7680. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  7681. var dashIndex=0, draw=true;
  7682. while (distRemaining>=0.1){
  7683. var dashLength = dashArray[dashIndex++%dashCount];
  7684. if (dashLength > distRemaining) dashLength = distRemaining;
  7685. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  7686. if (dx<0) xStep = -xStep;
  7687. x += xStep;
  7688. y += slope*xStep;
  7689. this[draw ? 'lineTo' : 'moveTo'](x,y);
  7690. distRemaining -= dashLength;
  7691. draw = !draw;
  7692. }
  7693. };
  7694. // TODO: add diamond shape
  7695. }
  7696. /**
  7697. * @class Node
  7698. * A node. A node can be connected to other nodes via one or multiple edges.
  7699. * @param {object} properties An object containing properties for the node. All
  7700. * properties are optional, except for the id.
  7701. * {number} id Id of the node. Required
  7702. * {string} label Text label for the node
  7703. * {number} x Horizontal position of the node
  7704. * {number} y Vertical position of the node
  7705. * {string} shape Node shape, available:
  7706. * "database", "circle", "ellipse",
  7707. * "box", "image", "text", "dot",
  7708. * "star", "triangle", "triangleDown",
  7709. * "square"
  7710. * {string} image An image url
  7711. * {string} title An title text, can be HTML
  7712. * {anytype} group A group name or number
  7713. * @param {Graph.Images} imagelist A list with images. Only needed
  7714. * when the node has an image
  7715. * @param {Graph.Groups} grouplist A list with groups. Needed for
  7716. * retrieving group properties
  7717. * @param {Object} constants An object with default values for
  7718. * example for the color
  7719. *
  7720. */
  7721. function Node(properties, imagelist, grouplist, constants) {
  7722. this.selected = false;
  7723. this.edges = []; // all edges connected to this node
  7724. this.dynamicEdges = [];
  7725. this.reroutedEdges = {};
  7726. this.group = constants.nodes.group;
  7727. this.fontSize = constants.nodes.fontSize;
  7728. this.fontFace = constants.nodes.fontFace;
  7729. this.fontColor = constants.nodes.fontColor;
  7730. this.fontDrawThreshold = 3;
  7731. this.color = constants.nodes.color;
  7732. // set defaults for the properties
  7733. this.id = undefined;
  7734. this.shape = constants.nodes.shape;
  7735. this.image = constants.nodes.image;
  7736. this.x = null;
  7737. this.y = null;
  7738. this.xFixed = false;
  7739. this.yFixed = false;
  7740. this.horizontalAlignLeft = true; // these are for the navigation controls
  7741. this.verticalAlignTop = true; // these are for the navigation controls
  7742. this.radius = constants.nodes.radius;
  7743. this.baseRadiusValue = constants.nodes.radius;
  7744. this.radiusFixed = false;
  7745. this.radiusMin = constants.nodes.radiusMin;
  7746. this.radiusMax = constants.nodes.radiusMax;
  7747. this.level = -1;
  7748. this.preassignedLevel = false;
  7749. this.imagelist = imagelist;
  7750. this.grouplist = grouplist;
  7751. // physics properties
  7752. this.fx = 0.0; // external force x
  7753. this.fy = 0.0; // external force y
  7754. this.vx = 0.0; // velocity x
  7755. this.vy = 0.0; // velocity y
  7756. this.minForce = constants.minForce;
  7757. this.damping = constants.physics.damping;
  7758. this.mass = 1; // kg
  7759. this.fixedData = {x:null,y:null};
  7760. this.setProperties(properties, constants);
  7761. // creating the variables for clustering
  7762. this.resetCluster();
  7763. this.dynamicEdgesLength = 0;
  7764. this.clusterSession = 0;
  7765. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  7766. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  7767. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  7768. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  7769. this.growthIndicator = 0;
  7770. // variables to tell the node about the graph.
  7771. this.graphScaleInv = 1;
  7772. this.graphScale = 1;
  7773. this.canvasTopLeft = {"x": -300, "y": -300};
  7774. this.canvasBottomRight = {"x": 300, "y": 300};
  7775. this.parentEdgeId = null;
  7776. }
  7777. /**
  7778. * (re)setting the clustering variables and objects
  7779. */
  7780. Node.prototype.resetCluster = function() {
  7781. // clustering variables
  7782. this.formationScale = undefined; // this is used to determine when to open the cluster
  7783. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  7784. this.containedNodes = {};
  7785. this.containedEdges = {};
  7786. this.clusterSessions = [];
  7787. };
  7788. /**
  7789. * Attach a edge to the node
  7790. * @param {Edge} edge
  7791. */
  7792. Node.prototype.attachEdge = function(edge) {
  7793. if (this.edges.indexOf(edge) == -1) {
  7794. this.edges.push(edge);
  7795. }
  7796. if (this.dynamicEdges.indexOf(edge) == -1) {
  7797. this.dynamicEdges.push(edge);
  7798. }
  7799. this.dynamicEdgesLength = this.dynamicEdges.length;
  7800. };
  7801. /**
  7802. * Detach a edge from the node
  7803. * @param {Edge} edge
  7804. */
  7805. Node.prototype.detachEdge = function(edge) {
  7806. var index = this.edges.indexOf(edge);
  7807. if (index != -1) {
  7808. this.edges.splice(index, 1);
  7809. this.dynamicEdges.splice(index, 1);
  7810. }
  7811. this.dynamicEdgesLength = this.dynamicEdges.length;
  7812. };
  7813. /**
  7814. * Set or overwrite properties for the node
  7815. * @param {Object} properties an object with properties
  7816. * @param {Object} constants and object with default, global properties
  7817. */
  7818. Node.prototype.setProperties = function(properties, constants) {
  7819. if (!properties) {
  7820. return;
  7821. }
  7822. this.originalLabel = undefined;
  7823. // basic properties
  7824. if (properties.id !== undefined) {this.id = properties.id;}
  7825. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  7826. if (properties.title !== undefined) {this.title = properties.title;}
  7827. if (properties.group !== undefined) {this.group = properties.group;}
  7828. if (properties.x !== undefined) {this.x = properties.x;}
  7829. if (properties.y !== undefined) {this.y = properties.y;}
  7830. if (properties.value !== undefined) {this.value = properties.value;}
  7831. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  7832. // physics
  7833. if (properties.mass !== undefined) {this.mass = properties.mass;}
  7834. // navigation controls properties
  7835. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  7836. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  7837. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  7838. if (this.id === undefined) {
  7839. throw "Node must have an id";
  7840. }
  7841. // copy group properties
  7842. if (this.group) {
  7843. var groupObj = this.grouplist.get(this.group);
  7844. for (var prop in groupObj) {
  7845. if (groupObj.hasOwnProperty(prop)) {
  7846. this[prop] = groupObj[prop];
  7847. }
  7848. }
  7849. }
  7850. // individual shape properties
  7851. if (properties.shape !== undefined) {this.shape = properties.shape;}
  7852. if (properties.image !== undefined) {this.image = properties.image;}
  7853. if (properties.radius !== undefined) {this.radius = properties.radius;}
  7854. if (properties.color !== undefined) {this.color = util.parseColor(properties.color);}
  7855. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  7856. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  7857. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  7858. if (this.image !== undefined && this.image != "") {
  7859. if (this.imagelist) {
  7860. this.imageObj = this.imagelist.load(this.image);
  7861. }
  7862. else {
  7863. throw "No imagelist provided";
  7864. }
  7865. }
  7866. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX);
  7867. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  7868. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  7869. if (this.shape == 'image') {
  7870. this.radiusMin = constants.nodes.widthMin;
  7871. this.radiusMax = constants.nodes.widthMax;
  7872. }
  7873. // choose draw method depending on the shape
  7874. switch (this.shape) {
  7875. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  7876. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  7877. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  7878. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7879. // TODO: add diamond shape
  7880. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  7881. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  7882. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  7883. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  7884. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  7885. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  7886. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  7887. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7888. }
  7889. // reset the size of the node, this can be changed
  7890. this._reset();
  7891. };
  7892. /**
  7893. * select this node
  7894. */
  7895. Node.prototype.select = function() {
  7896. this.selected = true;
  7897. this._reset();
  7898. };
  7899. /**
  7900. * unselect this node
  7901. */
  7902. Node.prototype.unselect = function() {
  7903. this.selected = false;
  7904. this._reset();
  7905. };
  7906. /**
  7907. * Reset the calculated size of the node, forces it to recalculate its size
  7908. */
  7909. Node.prototype.clearSizeCache = function() {
  7910. this._reset();
  7911. };
  7912. /**
  7913. * Reset the calculated size of the node, forces it to recalculate its size
  7914. * @private
  7915. */
  7916. Node.prototype._reset = function() {
  7917. this.width = undefined;
  7918. this.height = undefined;
  7919. };
  7920. /**
  7921. * get the title of this node.
  7922. * @return {string} title The title of the node, or undefined when no title
  7923. * has been set.
  7924. */
  7925. Node.prototype.getTitle = function() {
  7926. return typeof this.title === "function" ? this.title() : this.title;
  7927. };
  7928. /**
  7929. * Calculate the distance to the border of the Node
  7930. * @param {CanvasRenderingContext2D} ctx
  7931. * @param {Number} angle Angle in radians
  7932. * @returns {number} distance Distance to the border in pixels
  7933. */
  7934. Node.prototype.distanceToBorder = function (ctx, angle) {
  7935. var borderWidth = 1;
  7936. if (!this.width) {
  7937. this.resize(ctx);
  7938. }
  7939. switch (this.shape) {
  7940. case 'circle':
  7941. case 'dot':
  7942. return this.radius + borderWidth;
  7943. case 'ellipse':
  7944. var a = this.width / 2;
  7945. var b = this.height / 2;
  7946. var w = (Math.sin(angle) * a);
  7947. var h = (Math.cos(angle) * b);
  7948. return a * b / Math.sqrt(w * w + h * h);
  7949. // TODO: implement distanceToBorder for database
  7950. // TODO: implement distanceToBorder for triangle
  7951. // TODO: implement distanceToBorder for triangleDown
  7952. case 'box':
  7953. case 'image':
  7954. case 'text':
  7955. default:
  7956. if (this.width) {
  7957. return Math.min(
  7958. Math.abs(this.width / 2 / Math.cos(angle)),
  7959. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  7960. // TODO: reckon with border radius too in case of box
  7961. }
  7962. else {
  7963. return 0;
  7964. }
  7965. }
  7966. // TODO: implement calculation of distance to border for all shapes
  7967. };
  7968. /**
  7969. * Set forces acting on the node
  7970. * @param {number} fx Force in horizontal direction
  7971. * @param {number} fy Force in vertical direction
  7972. */
  7973. Node.prototype._setForce = function(fx, fy) {
  7974. this.fx = fx;
  7975. this.fy = fy;
  7976. };
  7977. /**
  7978. * Add forces acting on the node
  7979. * @param {number} fx Force in horizontal direction
  7980. * @param {number} fy Force in vertical direction
  7981. * @private
  7982. */
  7983. Node.prototype._addForce = function(fx, fy) {
  7984. this.fx += fx;
  7985. this.fy += fy;
  7986. };
  7987. /**
  7988. * Perform one discrete step for the node
  7989. * @param {number} interval Time interval in seconds
  7990. */
  7991. Node.prototype.discreteStep = function(interval) {
  7992. if (!this.xFixed) {
  7993. var dx = this.damping * this.vx; // damping force
  7994. var ax = (this.fx - dx) / this.mass; // acceleration
  7995. this.vx += ax * interval; // velocity
  7996. this.x += this.vx * interval; // position
  7997. }
  7998. if (!this.yFixed) {
  7999. var dy = this.damping * this.vy; // damping force
  8000. var ay = (this.fy - dy) / this.mass; // acceleration
  8001. this.vy += ay * interval; // velocity
  8002. this.y += this.vy * interval; // position
  8003. }
  8004. };
  8005. /**
  8006. * Perform one discrete step for the node
  8007. * @param {number} interval Time interval in seconds
  8008. */
  8009. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8010. if (!this.xFixed) {
  8011. var dx = this.damping * this.vx; // damping force
  8012. var ax = (this.fx - dx) / this.mass; // acceleration
  8013. this.vx += ax * interval; // velocity
  8014. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8015. this.x += this.vx * interval; // position
  8016. }
  8017. else {
  8018. this.fx = 0;
  8019. }
  8020. if (!this.yFixed) {
  8021. var dy = this.damping * this.vy; // damping force
  8022. var ay = (this.fy - dy) / this.mass; // acceleration
  8023. this.vy += ay * interval; // velocity
  8024. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8025. this.y += this.vy * interval; // position
  8026. }
  8027. else {
  8028. this.fy = 0;
  8029. }
  8030. };
  8031. /**
  8032. * Check if this node has a fixed x and y position
  8033. * @return {boolean} true if fixed, false if not
  8034. */
  8035. Node.prototype.isFixed = function() {
  8036. return (this.xFixed && this.yFixed);
  8037. };
  8038. /**
  8039. * Check if this node is moving
  8040. * @param {number} vmin the minimum velocity considered as "moving"
  8041. * @return {boolean} true if moving, false if it has no velocity
  8042. */
  8043. // TODO: replace this method with calculating the kinetic energy
  8044. Node.prototype.isMoving = function(vmin) {
  8045. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8046. };
  8047. /**
  8048. * check if this node is selecte
  8049. * @return {boolean} selected True if node is selected, else false
  8050. */
  8051. Node.prototype.isSelected = function() {
  8052. return this.selected;
  8053. };
  8054. /**
  8055. * Retrieve the value of the node. Can be undefined
  8056. * @return {Number} value
  8057. */
  8058. Node.prototype.getValue = function() {
  8059. return this.value;
  8060. };
  8061. /**
  8062. * Calculate the distance from the nodes location to the given location (x,y)
  8063. * @param {Number} x
  8064. * @param {Number} y
  8065. * @return {Number} value
  8066. */
  8067. Node.prototype.getDistance = function(x, y) {
  8068. var dx = this.x - x,
  8069. dy = this.y - y;
  8070. return Math.sqrt(dx * dx + dy * dy);
  8071. };
  8072. /**
  8073. * Adjust the value range of the node. The node will adjust it's radius
  8074. * based on its value.
  8075. * @param {Number} min
  8076. * @param {Number} max
  8077. */
  8078. Node.prototype.setValueRange = function(min, max) {
  8079. if (!this.radiusFixed && this.value !== undefined) {
  8080. if (max == min) {
  8081. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8082. }
  8083. else {
  8084. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8085. this.radius = (this.value - min) * scale + this.radiusMin;
  8086. }
  8087. }
  8088. this.baseRadiusValue = this.radius;
  8089. };
  8090. /**
  8091. * Draw this node in the given canvas
  8092. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8093. * @param {CanvasRenderingContext2D} ctx
  8094. */
  8095. Node.prototype.draw = function(ctx) {
  8096. throw "Draw method not initialized for node";
  8097. };
  8098. /**
  8099. * Recalculate the size of this node in the given canvas
  8100. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8101. * @param {CanvasRenderingContext2D} ctx
  8102. */
  8103. Node.prototype.resize = function(ctx) {
  8104. throw "Resize method not initialized for node";
  8105. };
  8106. /**
  8107. * Check if this object is overlapping with the provided object
  8108. * @param {Object} obj an object with parameters left, top, right, bottom
  8109. * @return {boolean} True if location is located on node
  8110. */
  8111. Node.prototype.isOverlappingWith = function(obj) {
  8112. return (this.left < obj.right &&
  8113. this.left + this.width > obj.left &&
  8114. this.top < obj.bottom &&
  8115. this.top + this.height > obj.top);
  8116. };
  8117. Node.prototype._resizeImage = function (ctx) {
  8118. // TODO: pre calculate the image size
  8119. if (!this.width || !this.height) { // undefined or 0
  8120. var width, height;
  8121. if (this.value) {
  8122. this.radius = this.baseRadiusValue;
  8123. var scale = this.imageObj.height / this.imageObj.width;
  8124. if (scale !== undefined) {
  8125. width = this.radius || this.imageObj.width;
  8126. height = this.radius * scale || this.imageObj.height;
  8127. }
  8128. else {
  8129. width = 0;
  8130. height = 0;
  8131. }
  8132. }
  8133. else {
  8134. width = this.imageObj.width;
  8135. height = this.imageObj.height;
  8136. }
  8137. this.width = width;
  8138. this.height = height;
  8139. this.growthIndicator = 0;
  8140. if (this.width > 0 && this.height > 0) {
  8141. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8142. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8143. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8144. this.growthIndicator = this.width - width;
  8145. }
  8146. }
  8147. };
  8148. Node.prototype._drawImage = function (ctx) {
  8149. this._resizeImage(ctx);
  8150. this.left = this.x - this.width / 2;
  8151. this.top = this.y - this.height / 2;
  8152. var yLabel;
  8153. if (this.imageObj.width != 0 ) {
  8154. // draw the shade
  8155. if (this.clusterSize > 1) {
  8156. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8157. lineWidth *= this.graphScaleInv;
  8158. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8159. ctx.globalAlpha = 0.5;
  8160. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8161. }
  8162. // draw the image
  8163. ctx.globalAlpha = 1.0;
  8164. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8165. yLabel = this.y + this.height / 2;
  8166. }
  8167. else {
  8168. // image still loading... just draw the label for now
  8169. yLabel = this.y;
  8170. }
  8171. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8172. };
  8173. Node.prototype._resizeBox = function (ctx) {
  8174. if (!this.width) {
  8175. var margin = 5;
  8176. var textSize = this.getTextSize(ctx);
  8177. this.width = textSize.width + 2 * margin;
  8178. this.height = textSize.height + 2 * margin;
  8179. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8180. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8181. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8182. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8183. }
  8184. };
  8185. Node.prototype._drawBox = function (ctx) {
  8186. this._resizeBox(ctx);
  8187. this.left = this.x - this.width / 2;
  8188. this.top = this.y - this.height / 2;
  8189. var clusterLineWidth = 2.5;
  8190. var selectionLineWidth = 2;
  8191. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8192. // draw the outer border
  8193. if (this.clusterSize > 1) {
  8194. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8195. ctx.lineWidth *= this.graphScaleInv;
  8196. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8197. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8198. ctx.stroke();
  8199. }
  8200. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8201. ctx.lineWidth *= this.graphScaleInv;
  8202. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8203. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8204. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8205. ctx.fill();
  8206. ctx.stroke();
  8207. this._label(ctx, this.label, this.x, this.y);
  8208. };
  8209. Node.prototype._resizeDatabase = function (ctx) {
  8210. if (!this.width) {
  8211. var margin = 5;
  8212. var textSize = this.getTextSize(ctx);
  8213. var size = textSize.width + 2 * margin;
  8214. this.width = size;
  8215. this.height = size;
  8216. // scaling used for clustering
  8217. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8218. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8219. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8220. this.growthIndicator = this.width - size;
  8221. }
  8222. };
  8223. Node.prototype._drawDatabase = function (ctx) {
  8224. this._resizeDatabase(ctx);
  8225. this.left = this.x - this.width / 2;
  8226. this.top = this.y - this.height / 2;
  8227. var clusterLineWidth = 2.5;
  8228. var selectionLineWidth = 2;
  8229. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8230. // draw the outer border
  8231. if (this.clusterSize > 1) {
  8232. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8233. ctx.lineWidth *= this.graphScaleInv;
  8234. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8235. 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);
  8236. ctx.stroke();
  8237. }
  8238. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8239. ctx.lineWidth *= this.graphScaleInv;
  8240. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8241. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8242. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8243. ctx.fill();
  8244. ctx.stroke();
  8245. this._label(ctx, this.label, this.x, this.y);
  8246. };
  8247. Node.prototype._resizeCircle = function (ctx) {
  8248. if (!this.width) {
  8249. var margin = 5;
  8250. var textSize = this.getTextSize(ctx);
  8251. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8252. this.radius = diameter / 2;
  8253. this.width = diameter;
  8254. this.height = diameter;
  8255. // scaling used for clustering
  8256. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8257. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8258. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8259. this.growthIndicator = this.radius - 0.5*diameter;
  8260. }
  8261. };
  8262. Node.prototype._drawCircle = function (ctx) {
  8263. this._resizeCircle(ctx);
  8264. this.left = this.x - this.width / 2;
  8265. this.top = this.y - this.height / 2;
  8266. var clusterLineWidth = 2.5;
  8267. var selectionLineWidth = 2;
  8268. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8269. // draw the outer border
  8270. if (this.clusterSize > 1) {
  8271. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8272. ctx.lineWidth *= this.graphScaleInv;
  8273. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8274. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8275. ctx.stroke();
  8276. }
  8277. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8278. ctx.lineWidth *= this.graphScaleInv;
  8279. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8280. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8281. ctx.circle(this.x, this.y, this.radius);
  8282. ctx.fill();
  8283. ctx.stroke();
  8284. this._label(ctx, this.label, this.x, this.y);
  8285. };
  8286. Node.prototype._resizeEllipse = function (ctx) {
  8287. if (!this.width) {
  8288. var textSize = this.getTextSize(ctx);
  8289. this.width = textSize.width * 1.5;
  8290. this.height = textSize.height * 2;
  8291. if (this.width < this.height) {
  8292. this.width = this.height;
  8293. }
  8294. var defaultSize = this.width;
  8295. // scaling used for clustering
  8296. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8297. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8298. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8299. this.growthIndicator = this.width - defaultSize;
  8300. }
  8301. };
  8302. Node.prototype._drawEllipse = function (ctx) {
  8303. this._resizeEllipse(ctx);
  8304. this.left = this.x - this.width / 2;
  8305. this.top = this.y - this.height / 2;
  8306. var clusterLineWidth = 2.5;
  8307. var selectionLineWidth = 2;
  8308. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8309. // draw the outer border
  8310. if (this.clusterSize > 1) {
  8311. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8312. ctx.lineWidth *= this.graphScaleInv;
  8313. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8314. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8315. ctx.stroke();
  8316. }
  8317. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8318. ctx.lineWidth *= this.graphScaleInv;
  8319. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8320. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8321. ctx.ellipse(this.left, this.top, this.width, this.height);
  8322. ctx.fill();
  8323. ctx.stroke();
  8324. this._label(ctx, this.label, this.x, this.y);
  8325. };
  8326. Node.prototype._drawDot = function (ctx) {
  8327. this._drawShape(ctx, 'circle');
  8328. };
  8329. Node.prototype._drawTriangle = function (ctx) {
  8330. this._drawShape(ctx, 'triangle');
  8331. };
  8332. Node.prototype._drawTriangleDown = function (ctx) {
  8333. this._drawShape(ctx, 'triangleDown');
  8334. };
  8335. Node.prototype._drawSquare = function (ctx) {
  8336. this._drawShape(ctx, 'square');
  8337. };
  8338. Node.prototype._drawStar = function (ctx) {
  8339. this._drawShape(ctx, 'star');
  8340. };
  8341. Node.prototype._resizeShape = function (ctx) {
  8342. if (!this.width) {
  8343. this.radius = this.baseRadiusValue;
  8344. var size = 2 * this.radius;
  8345. this.width = size;
  8346. this.height = size;
  8347. // scaling used for clustering
  8348. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8349. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8350. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8351. this.growthIndicator = this.width - size;
  8352. }
  8353. };
  8354. Node.prototype._drawShape = function (ctx, shape) {
  8355. this._resizeShape(ctx);
  8356. this.left = this.x - this.width / 2;
  8357. this.top = this.y - this.height / 2;
  8358. var clusterLineWidth = 2.5;
  8359. var selectionLineWidth = 2;
  8360. var radiusMultiplier = 2;
  8361. // choose draw method depending on the shape
  8362. switch (shape) {
  8363. case 'dot': radiusMultiplier = 2; break;
  8364. case 'square': radiusMultiplier = 2; break;
  8365. case 'triangle': radiusMultiplier = 3; break;
  8366. case 'triangleDown': radiusMultiplier = 3; break;
  8367. case 'star': radiusMultiplier = 4; break;
  8368. }
  8369. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8370. // draw the outer border
  8371. if (this.clusterSize > 1) {
  8372. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8373. ctx.lineWidth *= this.graphScaleInv;
  8374. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8375. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8376. ctx.stroke();
  8377. }
  8378. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8379. ctx.lineWidth *= this.graphScaleInv;
  8380. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8381. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8382. ctx[shape](this.x, this.y, this.radius);
  8383. ctx.fill();
  8384. ctx.stroke();
  8385. if (this.label) {
  8386. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8387. }
  8388. };
  8389. Node.prototype._resizeText = function (ctx) {
  8390. if (!this.width) {
  8391. var margin = 5;
  8392. var textSize = this.getTextSize(ctx);
  8393. this.width = textSize.width + 2 * margin;
  8394. this.height = textSize.height + 2 * margin;
  8395. // scaling used for clustering
  8396. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8397. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8398. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8399. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8400. }
  8401. };
  8402. Node.prototype._drawText = function (ctx) {
  8403. this._resizeText(ctx);
  8404. this.left = this.x - this.width / 2;
  8405. this.top = this.y - this.height / 2;
  8406. this._label(ctx, this.label, this.x, this.y);
  8407. };
  8408. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  8409. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  8410. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8411. ctx.fillStyle = this.fontColor || "black";
  8412. ctx.textAlign = align || "center";
  8413. ctx.textBaseline = baseline || "middle";
  8414. var lines = text.split('\n'),
  8415. lineCount = lines.length,
  8416. fontSize = (this.fontSize + 4),
  8417. yLine = y + (1 - lineCount) / 2 * fontSize;
  8418. for (var i = 0; i < lineCount; i++) {
  8419. ctx.fillText(lines[i], x, yLine);
  8420. yLine += fontSize;
  8421. }
  8422. }
  8423. };
  8424. Node.prototype.getTextSize = function(ctx) {
  8425. if (this.label !== undefined) {
  8426. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8427. var lines = this.label.split('\n'),
  8428. height = (this.fontSize + 4) * lines.length,
  8429. width = 0;
  8430. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  8431. width = Math.max(width, ctx.measureText(lines[i]).width);
  8432. }
  8433. return {"width": width, "height": height};
  8434. }
  8435. else {
  8436. return {"width": 0, "height": 0};
  8437. }
  8438. };
  8439. /**
  8440. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  8441. * there is a safety margin of 0.3 * width;
  8442. *
  8443. * @returns {boolean}
  8444. */
  8445. Node.prototype.inArea = function() {
  8446. if (this.width !== undefined) {
  8447. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  8448. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  8449. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  8450. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  8451. }
  8452. else {
  8453. return true;
  8454. }
  8455. };
  8456. /**
  8457. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  8458. * @returns {boolean}
  8459. */
  8460. Node.prototype.inView = function() {
  8461. return (this.x >= this.canvasTopLeft.x &&
  8462. this.x < this.canvasBottomRight.x &&
  8463. this.y >= this.canvasTopLeft.y &&
  8464. this.y < this.canvasBottomRight.y);
  8465. };
  8466. /**
  8467. * This allows the zoom level of the graph to influence the rendering
  8468. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  8469. *
  8470. * @param scale
  8471. * @param canvasTopLeft
  8472. * @param canvasBottomRight
  8473. */
  8474. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  8475. this.graphScaleInv = 1.0/scale;
  8476. this.graphScale = scale;
  8477. this.canvasTopLeft = canvasTopLeft;
  8478. this.canvasBottomRight = canvasBottomRight;
  8479. };
  8480. /**
  8481. * This allows the zoom level of the graph to influence the rendering
  8482. *
  8483. * @param scale
  8484. */
  8485. Node.prototype.setScale = function(scale) {
  8486. this.graphScaleInv = 1.0/scale;
  8487. this.graphScale = scale;
  8488. };
  8489. /**
  8490. * set the velocity at 0. Is called when this node is contained in another during clustering
  8491. */
  8492. Node.prototype.clearVelocity = function() {
  8493. this.vx = 0;
  8494. this.vy = 0;
  8495. };
  8496. /**
  8497. * Basic preservation of (kinectic) energy
  8498. *
  8499. * @param massBeforeClustering
  8500. */
  8501. Node.prototype.updateVelocity = function(massBeforeClustering) {
  8502. var energyBefore = this.vx * this.vx * massBeforeClustering;
  8503. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8504. this.vx = Math.sqrt(energyBefore/this.mass);
  8505. energyBefore = this.vy * this.vy * massBeforeClustering;
  8506. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8507. this.vy = Math.sqrt(energyBefore/this.mass);
  8508. };
  8509. /**
  8510. * @class Edge
  8511. *
  8512. * A edge connects two nodes
  8513. * @param {Object} properties Object with properties. Must contain
  8514. * At least properties from and to.
  8515. * Available properties: from (number),
  8516. * to (number), label (string, color (string),
  8517. * width (number), style (string),
  8518. * length (number), title (string)
  8519. * @param {Graph} graph A graph object, used to find and edge to
  8520. * nodes.
  8521. * @param {Object} constants An object with default values for
  8522. * example for the color
  8523. */
  8524. function Edge (properties, graph, constants) {
  8525. if (!graph) {
  8526. throw "No graph provided";
  8527. }
  8528. this.graph = graph;
  8529. // initialize constants
  8530. this.widthMin = constants.edges.widthMin;
  8531. this.widthMax = constants.edges.widthMax;
  8532. // initialize variables
  8533. this.id = undefined;
  8534. this.fromId = undefined;
  8535. this.toId = undefined;
  8536. this.style = constants.edges.style;
  8537. this.title = undefined;
  8538. this.width = constants.edges.width;
  8539. this.value = undefined;
  8540. this.length = constants.physics.springLength;
  8541. this.customLength = false;
  8542. this.selected = false;
  8543. this.smooth = constants.smoothCurves;
  8544. this.from = null; // a node
  8545. this.to = null; // a node
  8546. this.via = null; // a temp node
  8547. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  8548. // by storing the original information we can revert to the original connection when the cluser is opened.
  8549. this.originalFromId = [];
  8550. this.originalToId = [];
  8551. this.connected = false;
  8552. // Added to support dashed lines
  8553. // David Jordan
  8554. // 2012-08-08
  8555. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  8556. this.color = {color:constants.edges.color.color,
  8557. highlight:constants.edges.color.highlight};
  8558. this.widthFixed = false;
  8559. this.lengthFixed = false;
  8560. this.setProperties(properties, constants);
  8561. }
  8562. /**
  8563. * Set or overwrite properties for the edge
  8564. * @param {Object} properties an object with properties
  8565. * @param {Object} constants and object with default, global properties
  8566. */
  8567. Edge.prototype.setProperties = function(properties, constants) {
  8568. if (!properties) {
  8569. return;
  8570. }
  8571. if (properties.from !== undefined) {this.fromId = properties.from;}
  8572. if (properties.to !== undefined) {this.toId = properties.to;}
  8573. if (properties.id !== undefined) {this.id = properties.id;}
  8574. if (properties.style !== undefined) {this.style = properties.style;}
  8575. if (properties.label !== undefined) {this.label = properties.label;}
  8576. if (this.label) {
  8577. this.fontSize = constants.edges.fontSize;
  8578. this.fontFace = constants.edges.fontFace;
  8579. this.fontColor = constants.edges.fontColor;
  8580. this.fontFill = constants.edges.fontFill;
  8581. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8582. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8583. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8584. if (properties.fontFill !== undefined) {this.fontFill = properties.fontFill;}
  8585. }
  8586. if (properties.title !== undefined) {this.title = properties.title;}
  8587. if (properties.width !== undefined) {this.width = properties.width;}
  8588. if (properties.value !== undefined) {this.value = properties.value;}
  8589. if (properties.length !== undefined) {this.length = properties.length;
  8590. this.customLength = true;}
  8591. // Added to support dashed lines
  8592. // David Jordan
  8593. // 2012-08-08
  8594. if (properties.dash) {
  8595. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  8596. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  8597. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  8598. }
  8599. if (properties.color !== undefined) {
  8600. if (util.isString(properties.color)) {
  8601. this.color.color = properties.color;
  8602. this.color.highlight = properties.color;
  8603. }
  8604. else {
  8605. if (properties.color.color !== undefined) {this.color.color = properties.color.color;}
  8606. if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;}
  8607. }
  8608. }
  8609. // A node is connected when it has a from and to node.
  8610. this.connect();
  8611. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  8612. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  8613. // set draw method based on style
  8614. switch (this.style) {
  8615. case 'line': this.draw = this._drawLine; break;
  8616. case 'arrow': this.draw = this._drawArrow; break;
  8617. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  8618. case 'dash-line': this.draw = this._drawDashLine; break;
  8619. default: this.draw = this._drawLine; break;
  8620. }
  8621. };
  8622. /**
  8623. * Connect an edge to its nodes
  8624. */
  8625. Edge.prototype.connect = function () {
  8626. this.disconnect();
  8627. this.from = this.graph.nodes[this.fromId] || null;
  8628. this.to = this.graph.nodes[this.toId] || null;
  8629. this.connected = (this.from && this.to);
  8630. if (this.connected) {
  8631. this.from.attachEdge(this);
  8632. this.to.attachEdge(this);
  8633. }
  8634. else {
  8635. if (this.from) {
  8636. this.from.detachEdge(this);
  8637. }
  8638. if (this.to) {
  8639. this.to.detachEdge(this);
  8640. }
  8641. }
  8642. };
  8643. /**
  8644. * Disconnect an edge from its nodes
  8645. */
  8646. Edge.prototype.disconnect = function () {
  8647. if (this.from) {
  8648. this.from.detachEdge(this);
  8649. this.from = null;
  8650. }
  8651. if (this.to) {
  8652. this.to.detachEdge(this);
  8653. this.to = null;
  8654. }
  8655. this.connected = false;
  8656. };
  8657. /**
  8658. * get the title of this edge.
  8659. * @return {string} title The title of the edge, or undefined when no title
  8660. * has been set.
  8661. */
  8662. Edge.prototype.getTitle = function() {
  8663. return typeof this.title === "function" ? this.title() : this.title;
  8664. };
  8665. /**
  8666. * Retrieve the value of the edge. Can be undefined
  8667. * @return {Number} value
  8668. */
  8669. Edge.prototype.getValue = function() {
  8670. return this.value;
  8671. };
  8672. /**
  8673. * Adjust the value range of the edge. The edge will adjust it's width
  8674. * based on its value.
  8675. * @param {Number} min
  8676. * @param {Number} max
  8677. */
  8678. Edge.prototype.setValueRange = function(min, max) {
  8679. if (!this.widthFixed && this.value !== undefined) {
  8680. var scale = (this.widthMax - this.widthMin) / (max - min);
  8681. this.width = (this.value - min) * scale + this.widthMin;
  8682. }
  8683. };
  8684. /**
  8685. * Redraw a edge
  8686. * Draw this edge in the given canvas
  8687. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8688. * @param {CanvasRenderingContext2D} ctx
  8689. */
  8690. Edge.prototype.draw = function(ctx) {
  8691. throw "Method draw not initialized in edge";
  8692. };
  8693. /**
  8694. * Check if this object is overlapping with the provided object
  8695. * @param {Object} obj an object with parameters left, top
  8696. * @return {boolean} True if location is located on the edge
  8697. */
  8698. Edge.prototype.isOverlappingWith = function(obj) {
  8699. if (this.connected) {
  8700. var distMax = 10;
  8701. var xFrom = this.from.x;
  8702. var yFrom = this.from.y;
  8703. var xTo = this.to.x;
  8704. var yTo = this.to.y;
  8705. var xObj = obj.left;
  8706. var yObj = obj.top;
  8707. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  8708. return (dist < distMax);
  8709. }
  8710. else {
  8711. return false
  8712. }
  8713. };
  8714. /**
  8715. * Redraw a edge as a line
  8716. * Draw this edge in the given canvas
  8717. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8718. * @param {CanvasRenderingContext2D} ctx
  8719. * @private
  8720. */
  8721. Edge.prototype._drawLine = function(ctx) {
  8722. // set style
  8723. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  8724. else {ctx.strokeStyle = this.color.color;}
  8725. ctx.lineWidth = this._getLineWidth();
  8726. if (this.from != this.to) {
  8727. // draw line
  8728. this._line(ctx);
  8729. // draw label
  8730. var point;
  8731. if (this.label) {
  8732. if (this.smooth == true) {
  8733. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  8734. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  8735. point = {x:midpointX, y:midpointY};
  8736. }
  8737. else {
  8738. point = this._pointOnLine(0.5);
  8739. }
  8740. this._label(ctx, this.label, point.x, point.y);
  8741. }
  8742. }
  8743. else {
  8744. var x, y;
  8745. var radius = this.length / 4;
  8746. var node = this.from;
  8747. if (!node.width) {
  8748. node.resize(ctx);
  8749. }
  8750. if (node.width > node.height) {
  8751. x = node.x + node.width / 2;
  8752. y = node.y - radius;
  8753. }
  8754. else {
  8755. x = node.x + radius;
  8756. y = node.y - node.height / 2;
  8757. }
  8758. this._circle(ctx, x, y, radius);
  8759. point = this._pointOnCircle(x, y, radius, 0.5);
  8760. this._label(ctx, this.label, point.x, point.y);
  8761. }
  8762. };
  8763. /**
  8764. * Get the line width of the edge. Depends on width and whether one of the
  8765. * connected nodes is selected.
  8766. * @return {Number} width
  8767. * @private
  8768. */
  8769. Edge.prototype._getLineWidth = function() {
  8770. if (this.selected == true) {
  8771. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  8772. }
  8773. else {
  8774. return this.width*this.graphScaleInv;
  8775. }
  8776. };
  8777. /**
  8778. * Draw a line between two nodes
  8779. * @param {CanvasRenderingContext2D} ctx
  8780. * @private
  8781. */
  8782. Edge.prototype._line = function (ctx) {
  8783. // draw a straight line
  8784. ctx.beginPath();
  8785. ctx.moveTo(this.from.x, this.from.y);
  8786. if (this.smooth == true) {
  8787. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  8788. }
  8789. else {
  8790. ctx.lineTo(this.to.x, this.to.y);
  8791. }
  8792. ctx.stroke();
  8793. };
  8794. /**
  8795. * Draw a line from a node to itself, a circle
  8796. * @param {CanvasRenderingContext2D} ctx
  8797. * @param {Number} x
  8798. * @param {Number} y
  8799. * @param {Number} radius
  8800. * @private
  8801. */
  8802. Edge.prototype._circle = function (ctx, x, y, radius) {
  8803. // draw a circle
  8804. ctx.beginPath();
  8805. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  8806. ctx.stroke();
  8807. };
  8808. /**
  8809. * Draw label with white background and with the middle at (x, y)
  8810. * @param {CanvasRenderingContext2D} ctx
  8811. * @param {String} text
  8812. * @param {Number} x
  8813. * @param {Number} y
  8814. * @private
  8815. */
  8816. Edge.prototype._label = function (ctx, text, x, y) {
  8817. if (text) {
  8818. // TODO: cache the calculated size
  8819. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  8820. this.fontSize + "px " + this.fontFace;
  8821. ctx.fillStyle = this.fontFill;
  8822. var width = ctx.measureText(text).width;
  8823. var height = this.fontSize;
  8824. var left = x - width / 2;
  8825. var top = y - height / 2;
  8826. ctx.fillRect(left, top, width, height);
  8827. // draw text
  8828. ctx.fillStyle = this.fontColor || "black";
  8829. ctx.textAlign = "left";
  8830. ctx.textBaseline = "top";
  8831. ctx.fillText(text, left, top);
  8832. }
  8833. };
  8834. /**
  8835. * Redraw a edge as a dashed line
  8836. * Draw this edge in the given canvas
  8837. * @author David Jordan
  8838. * @date 2012-08-08
  8839. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8840. * @param {CanvasRenderingContext2D} ctx
  8841. * @private
  8842. */
  8843. Edge.prototype._drawDashLine = function(ctx) {
  8844. // set style
  8845. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  8846. else {ctx.strokeStyle = this.color.color;}
  8847. ctx.lineWidth = this._getLineWidth();
  8848. // only firefox and chrome support this method, else we use the legacy one.
  8849. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  8850. ctx.beginPath();
  8851. ctx.moveTo(this.from.x, this.from.y);
  8852. // configure the dash pattern
  8853. var pattern = [0];
  8854. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  8855. pattern = [this.dash.length,this.dash.gap];
  8856. }
  8857. else {
  8858. pattern = [5,5];
  8859. }
  8860. // set dash settings for chrome or firefox
  8861. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  8862. ctx.setLineDash(pattern);
  8863. ctx.lineDashOffset = 0;
  8864. } else { //Firefox
  8865. ctx.mozDash = pattern;
  8866. ctx.mozDashOffset = 0;
  8867. }
  8868. // draw the line
  8869. if (this.smooth == true) {
  8870. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  8871. }
  8872. else {
  8873. ctx.lineTo(this.to.x, this.to.y);
  8874. }
  8875. ctx.stroke();
  8876. // restore the dash settings.
  8877. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  8878. ctx.setLineDash([0]);
  8879. ctx.lineDashOffset = 0;
  8880. } else { //Firefox
  8881. ctx.mozDash = [0];
  8882. ctx.mozDashOffset = 0;
  8883. }
  8884. }
  8885. else { // unsupporting smooth lines
  8886. // draw dashed line
  8887. ctx.beginPath();
  8888. ctx.lineCap = 'round';
  8889. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  8890. {
  8891. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8892. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  8893. }
  8894. 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
  8895. {
  8896. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8897. [this.dash.length,this.dash.gap]);
  8898. }
  8899. else //If all else fails draw a line
  8900. {
  8901. ctx.moveTo(this.from.x, this.from.y);
  8902. ctx.lineTo(this.to.x, this.to.y);
  8903. }
  8904. ctx.stroke();
  8905. }
  8906. // draw label
  8907. if (this.label) {
  8908. var point;
  8909. if (this.smooth == true) {
  8910. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  8911. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  8912. point = {x:midpointX, y:midpointY};
  8913. }
  8914. else {
  8915. point = this._pointOnLine(0.5);
  8916. }
  8917. this._label(ctx, this.label, point.x, point.y);
  8918. }
  8919. };
  8920. /**
  8921. * Get a point on a line
  8922. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8923. * @return {Object} point
  8924. * @private
  8925. */
  8926. Edge.prototype._pointOnLine = function (percentage) {
  8927. return {
  8928. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  8929. y: (1 - percentage) * this.from.y + percentage * this.to.y
  8930. }
  8931. };
  8932. /**
  8933. * Get a point on a circle
  8934. * @param {Number} x
  8935. * @param {Number} y
  8936. * @param {Number} radius
  8937. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8938. * @return {Object} point
  8939. * @private
  8940. */
  8941. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  8942. var angle = (percentage - 3/8) * 2 * Math.PI;
  8943. return {
  8944. x: x + radius * Math.cos(angle),
  8945. y: y - radius * Math.sin(angle)
  8946. }
  8947. };
  8948. /**
  8949. * Redraw a edge as a line with an arrow halfway the line
  8950. * Draw this edge in the given canvas
  8951. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8952. * @param {CanvasRenderingContext2D} ctx
  8953. * @private
  8954. */
  8955. Edge.prototype._drawArrowCenter = function(ctx) {
  8956. var point;
  8957. // set style
  8958. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  8959. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  8960. ctx.lineWidth = this._getLineWidth();
  8961. if (this.from != this.to) {
  8962. // draw line
  8963. this._line(ctx);
  8964. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8965. var length = 10 + 5 * this.width; // TODO: make customizable?
  8966. // draw an arrow halfway the line
  8967. if (this.smooth == true) {
  8968. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  8969. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  8970. point = {x:midpointX, y:midpointY};
  8971. }
  8972. else {
  8973. point = this._pointOnLine(0.5);
  8974. }
  8975. ctx.arrow(point.x, point.y, angle, length);
  8976. ctx.fill();
  8977. ctx.stroke();
  8978. // draw label
  8979. if (this.label) {
  8980. this._label(ctx, this.label, point.x, point.y);
  8981. }
  8982. }
  8983. else {
  8984. // draw circle
  8985. var x, y;
  8986. var radius = 0.25 * Math.max(100,this.length);
  8987. var node = this.from;
  8988. if (!node.width) {
  8989. node.resize(ctx);
  8990. }
  8991. if (node.width > node.height) {
  8992. x = node.x + node.width * 0.5;
  8993. y = node.y - radius;
  8994. }
  8995. else {
  8996. x = node.x + radius;
  8997. y = node.y - node.height * 0.5;
  8998. }
  8999. this._circle(ctx, x, y, radius);
  9000. // draw all arrows
  9001. var angle = 0.2 * Math.PI;
  9002. var length = 10 + 5 * this.width; // TODO: make customizable?
  9003. point = this._pointOnCircle(x, y, radius, 0.5);
  9004. ctx.arrow(point.x, point.y, angle, length);
  9005. ctx.fill();
  9006. ctx.stroke();
  9007. // draw label
  9008. if (this.label) {
  9009. point = this._pointOnCircle(x, y, radius, 0.5);
  9010. this._label(ctx, this.label, point.x, point.y);
  9011. }
  9012. }
  9013. };
  9014. /**
  9015. * Redraw a edge as a line with an arrow
  9016. * Draw this edge in the given canvas
  9017. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9018. * @param {CanvasRenderingContext2D} ctx
  9019. * @private
  9020. */
  9021. Edge.prototype._drawArrow = function(ctx) {
  9022. // set style
  9023. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9024. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9025. ctx.lineWidth = this._getLineWidth();
  9026. var angle, length;
  9027. //draw a line
  9028. if (this.from != this.to) {
  9029. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9030. var dx = (this.to.x - this.from.x);
  9031. var dy = (this.to.y - this.from.y);
  9032. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9033. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9034. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9035. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9036. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9037. if (this.smooth == true) {
  9038. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9039. dx = (this.to.x - this.via.x);
  9040. dy = (this.to.y - this.via.y);
  9041. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9042. }
  9043. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9044. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9045. var xTo,yTo;
  9046. if (this.smooth == true) {
  9047. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9048. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9049. }
  9050. else {
  9051. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9052. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9053. }
  9054. ctx.beginPath();
  9055. ctx.moveTo(xFrom,yFrom);
  9056. if (this.smooth == true) {
  9057. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9058. }
  9059. else {
  9060. ctx.lineTo(xTo, yTo);
  9061. }
  9062. ctx.stroke();
  9063. // draw arrow at the end of the line
  9064. length = 10 + 5 * this.width;
  9065. ctx.arrow(xTo, yTo, angle, length);
  9066. ctx.fill();
  9067. ctx.stroke();
  9068. // draw label
  9069. if (this.label) {
  9070. var point;
  9071. if (this.smooth == true) {
  9072. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9073. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9074. point = {x:midpointX, y:midpointY};
  9075. }
  9076. else {
  9077. point = this._pointOnLine(0.5);
  9078. }
  9079. this._label(ctx, this.label, point.x, point.y);
  9080. }
  9081. }
  9082. else {
  9083. // draw circle
  9084. var node = this.from;
  9085. var x, y, arrow;
  9086. var radius = 0.25 * Math.max(100,this.length);
  9087. if (!node.width) {
  9088. node.resize(ctx);
  9089. }
  9090. if (node.width > node.height) {
  9091. x = node.x + node.width * 0.5;
  9092. y = node.y - radius;
  9093. arrow = {
  9094. x: x,
  9095. y: node.y,
  9096. angle: 0.9 * Math.PI
  9097. };
  9098. }
  9099. else {
  9100. x = node.x + radius;
  9101. y = node.y - node.height * 0.5;
  9102. arrow = {
  9103. x: node.x,
  9104. y: y,
  9105. angle: 0.6 * Math.PI
  9106. };
  9107. }
  9108. ctx.beginPath();
  9109. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9110. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9111. ctx.stroke();
  9112. // draw all arrows
  9113. length = 10 + 5 * this.width; // TODO: make customizable?
  9114. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9115. ctx.fill();
  9116. ctx.stroke();
  9117. // draw label
  9118. if (this.label) {
  9119. point = this._pointOnCircle(x, y, radius, 0.5);
  9120. this._label(ctx, this.label, point.x, point.y);
  9121. }
  9122. }
  9123. };
  9124. /**
  9125. * Calculate the distance between a point (x3,y3) and a line segment from
  9126. * (x1,y1) to (x2,y2).
  9127. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9128. * @param {number} x1
  9129. * @param {number} y1
  9130. * @param {number} x2
  9131. * @param {number} y2
  9132. * @param {number} x3
  9133. * @param {number} y3
  9134. * @private
  9135. */
  9136. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9137. if (this.smooth == true) {
  9138. var minDistance = 1e9;
  9139. var i,t,x,y,dx,dy;
  9140. for (i = 0; i < 10; i++) {
  9141. t = 0.1*i;
  9142. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9143. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9144. dx = Math.abs(x3-x);
  9145. dy = Math.abs(y3-y);
  9146. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9147. }
  9148. return minDistance
  9149. }
  9150. else {
  9151. var px = x2-x1,
  9152. py = y2-y1,
  9153. something = px*px + py*py,
  9154. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9155. if (u > 1) {
  9156. u = 1;
  9157. }
  9158. else if (u < 0) {
  9159. u = 0;
  9160. }
  9161. var x = x1 + u * px,
  9162. y = y1 + u * py,
  9163. dx = x - x3,
  9164. dy = y - y3;
  9165. //# Note: If the actual distance does not matter,
  9166. //# if you only want to compare what this function
  9167. //# returns to other results of this function, you
  9168. //# can just return the squared distance instead
  9169. //# (i.e. remove the sqrt) to gain a little performance
  9170. return Math.sqrt(dx*dx + dy*dy);
  9171. }
  9172. };
  9173. /**
  9174. * This allows the zoom level of the graph to influence the rendering
  9175. *
  9176. * @param scale
  9177. */
  9178. Edge.prototype.setScale = function(scale) {
  9179. this.graphScaleInv = 1.0/scale;
  9180. };
  9181. Edge.prototype.select = function() {
  9182. this.selected = true;
  9183. };
  9184. Edge.prototype.unselect = function() {
  9185. this.selected = false;
  9186. };
  9187. Edge.prototype.positionBezierNode = function() {
  9188. if (this.via !== null) {
  9189. this.via.x = 0.5 * (this.from.x + this.to.x);
  9190. this.via.y = 0.5 * (this.from.y + this.to.y);
  9191. }
  9192. };
  9193. /**
  9194. * Popup is a class to create a popup window with some text
  9195. * @param {Element} container The container object.
  9196. * @param {Number} [x]
  9197. * @param {Number} [y]
  9198. * @param {String} [text]
  9199. * @param {Object} [style] An object containing borderColor,
  9200. * backgroundColor, etc.
  9201. */
  9202. function Popup(container, x, y, text, style) {
  9203. if (container) {
  9204. this.container = container;
  9205. }
  9206. else {
  9207. this.container = document.body;
  9208. }
  9209. // x, y and text are optional, see if a style object was passed in their place
  9210. if (style === undefined) {
  9211. if (typeof x === "object") {
  9212. style = x;
  9213. x = undefined;
  9214. } else if (typeof text === "object") {
  9215. style = text;
  9216. text = undefined;
  9217. } else {
  9218. // for backwards compatibility, in case clients other than Graph are creating Popup directly
  9219. style = {
  9220. fontColor: 'black',
  9221. fontSize: 14, // px
  9222. fontFace: 'verdana',
  9223. color: {
  9224. border: '#666',
  9225. background: '#FFFFC6'
  9226. }
  9227. }
  9228. }
  9229. }
  9230. this.x = 0;
  9231. this.y = 0;
  9232. this.padding = 5;
  9233. if (x !== undefined && y !== undefined ) {
  9234. this.setPosition(x, y);
  9235. }
  9236. if (text !== undefined) {
  9237. this.setText(text);
  9238. }
  9239. // create the frame
  9240. this.frame = document.createElement("div");
  9241. var styleAttr = this.frame.style;
  9242. styleAttr.position = "absolute";
  9243. styleAttr.visibility = "hidden";
  9244. styleAttr.border = "1px solid " + style.color.border;
  9245. styleAttr.color = style.fontColor;
  9246. styleAttr.fontSize = style.fontSize + "px";
  9247. styleAttr.fontFamily = style.fontFace;
  9248. styleAttr.padding = this.padding + "px";
  9249. styleAttr.backgroundColor = style.color.background;
  9250. styleAttr.borderRadius = "3px";
  9251. styleAttr.MozBorderRadius = "3px";
  9252. styleAttr.WebkitBorderRadius = "3px";
  9253. styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9254. styleAttr.whiteSpace = "nowrap";
  9255. this.container.appendChild(this.frame);
  9256. }
  9257. /**
  9258. * @param {number} x Horizontal position of the popup window
  9259. * @param {number} y Vertical position of the popup window
  9260. */
  9261. Popup.prototype.setPosition = function(x, y) {
  9262. this.x = parseInt(x);
  9263. this.y = parseInt(y);
  9264. };
  9265. /**
  9266. * Set the text for the popup window. This can be HTML code
  9267. * @param {string} text
  9268. */
  9269. Popup.prototype.setText = function(text) {
  9270. this.frame.innerHTML = text;
  9271. };
  9272. /**
  9273. * Show the popup window
  9274. * @param {boolean} show Optional. Show or hide the window
  9275. */
  9276. Popup.prototype.show = function (show) {
  9277. if (show === undefined) {
  9278. show = true;
  9279. }
  9280. if (show) {
  9281. var height = this.frame.clientHeight;
  9282. var width = this.frame.clientWidth;
  9283. var maxHeight = this.frame.parentNode.clientHeight;
  9284. var maxWidth = this.frame.parentNode.clientWidth;
  9285. var top = (this.y - height);
  9286. if (top + height + this.padding > maxHeight) {
  9287. top = maxHeight - height - this.padding;
  9288. }
  9289. if (top < this.padding) {
  9290. top = this.padding;
  9291. }
  9292. var left = this.x;
  9293. if (left + width + this.padding > maxWidth) {
  9294. left = maxWidth - width - this.padding;
  9295. }
  9296. if (left < this.padding) {
  9297. left = this.padding;
  9298. }
  9299. this.frame.style.left = left + "px";
  9300. this.frame.style.top = top + "px";
  9301. this.frame.style.visibility = "visible";
  9302. }
  9303. else {
  9304. this.hide();
  9305. }
  9306. };
  9307. /**
  9308. * Hide the popup window
  9309. */
  9310. Popup.prototype.hide = function () {
  9311. this.frame.style.visibility = "hidden";
  9312. };
  9313. /**
  9314. * @class Groups
  9315. * This class can store groups and properties specific for groups.
  9316. */
  9317. Groups = function () {
  9318. this.clear();
  9319. this.defaultIndex = 0;
  9320. };
  9321. /**
  9322. * default constants for group colors
  9323. */
  9324. Groups.DEFAULT = [
  9325. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9326. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9327. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9328. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9329. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9330. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9331. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9332. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9333. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9334. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9335. ];
  9336. /**
  9337. * Clear all groups
  9338. */
  9339. Groups.prototype.clear = function () {
  9340. this.groups = {};
  9341. this.groups.length = function()
  9342. {
  9343. var i = 0;
  9344. for ( var p in this ) {
  9345. if (this.hasOwnProperty(p)) {
  9346. i++;
  9347. }
  9348. }
  9349. return i;
  9350. }
  9351. };
  9352. /**
  9353. * get group properties of a groupname. If groupname is not found, a new group
  9354. * is added.
  9355. * @param {*} groupname Can be a number, string, Date, etc.
  9356. * @return {Object} group The created group, containing all group properties
  9357. */
  9358. Groups.prototype.get = function (groupname) {
  9359. var group = this.groups[groupname];
  9360. if (group == undefined) {
  9361. // create new group
  9362. var index = this.defaultIndex % Groups.DEFAULT.length;
  9363. this.defaultIndex++;
  9364. group = {};
  9365. group.color = Groups.DEFAULT[index];
  9366. this.groups[groupname] = group;
  9367. }
  9368. return group;
  9369. };
  9370. /**
  9371. * Add a custom group style
  9372. * @param {String} groupname
  9373. * @param {Object} style An object containing borderColor,
  9374. * backgroundColor, etc.
  9375. * @return {Object} group The created group object
  9376. */
  9377. Groups.prototype.add = function (groupname, style) {
  9378. this.groups[groupname] = style;
  9379. if (style.color) {
  9380. style.color = util.parseColor(style.color);
  9381. }
  9382. return style;
  9383. };
  9384. /**
  9385. * @class Images
  9386. * This class loads images and keeps them stored.
  9387. */
  9388. Images = function () {
  9389. this.images = {};
  9390. this.callback = undefined;
  9391. };
  9392. /**
  9393. * Set an onload callback function. This will be called each time an image
  9394. * is loaded
  9395. * @param {function} callback
  9396. */
  9397. Images.prototype.setOnloadCallback = function(callback) {
  9398. this.callback = callback;
  9399. };
  9400. /**
  9401. *
  9402. * @param {string} url Url of the image
  9403. * @return {Image} img The image object
  9404. */
  9405. Images.prototype.load = function(url) {
  9406. var img = this.images[url];
  9407. if (img == undefined) {
  9408. // create the image
  9409. var images = this;
  9410. img = new Image();
  9411. this.images[url] = img;
  9412. img.onload = function() {
  9413. if (images.callback) {
  9414. images.callback(this);
  9415. }
  9416. };
  9417. img.src = url;
  9418. }
  9419. return img;
  9420. };
  9421. /**
  9422. * Created by Alex on 2/6/14.
  9423. */
  9424. var physicsMixin = {
  9425. /**
  9426. * Toggling barnes Hut calculation on and off.
  9427. *
  9428. * @private
  9429. */
  9430. _toggleBarnesHut: function () {
  9431. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  9432. this._loadSelectedForceSolver();
  9433. this.moving = true;
  9434. this.start();
  9435. },
  9436. /**
  9437. * This loads the node force solver based on the barnes hut or repulsion algorithm
  9438. *
  9439. * @private
  9440. */
  9441. _loadSelectedForceSolver: function () {
  9442. // this overloads the this._calculateNodeForces
  9443. if (this.constants.physics.barnesHut.enabled == true) {
  9444. this._clearMixin(repulsionMixin);
  9445. this._clearMixin(hierarchalRepulsionMixin);
  9446. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  9447. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  9448. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  9449. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  9450. this._loadMixin(barnesHutMixin);
  9451. }
  9452. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  9453. this._clearMixin(barnesHutMixin);
  9454. this._clearMixin(repulsionMixin);
  9455. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  9456. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  9457. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  9458. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  9459. this._loadMixin(hierarchalRepulsionMixin);
  9460. }
  9461. else {
  9462. this._clearMixin(barnesHutMixin);
  9463. this._clearMixin(hierarchalRepulsionMixin);
  9464. this.barnesHutTree = undefined;
  9465. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  9466. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  9467. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  9468. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  9469. this._loadMixin(repulsionMixin);
  9470. }
  9471. },
  9472. /**
  9473. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  9474. * if there is more than one node. If it is just one node, we dont calculate anything.
  9475. *
  9476. * @private
  9477. */
  9478. _initializeForceCalculation: function () {
  9479. // stop calculation if there is only one node
  9480. if (this.nodeIndices.length == 1) {
  9481. this.nodes[this.nodeIndices[0]]._setForce(0, 0);
  9482. }
  9483. else {
  9484. // if there are too many nodes on screen, we cluster without repositioning
  9485. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  9486. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  9487. }
  9488. // we now start the force calculation
  9489. this._calculateForces();
  9490. }
  9491. },
  9492. /**
  9493. * Calculate the external forces acting on the nodes
  9494. * Forces are caused by: edges, repulsing forces between nodes, gravity
  9495. * @private
  9496. */
  9497. _calculateForces: function () {
  9498. // Gravity is required to keep separated groups from floating off
  9499. // the forces are reset to zero in this loop by using _setForce instead
  9500. // of _addForce
  9501. this._calculateGravitationalForces();
  9502. this._calculateNodeForces();
  9503. if (this.constants.smoothCurves == true) {
  9504. this._calculateSpringForcesWithSupport();
  9505. }
  9506. else {
  9507. this._calculateSpringForces();
  9508. }
  9509. },
  9510. /**
  9511. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  9512. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  9513. * This function joins the datanodes and invisible (called support) nodes into one object.
  9514. * We do this so we do not contaminate this.nodes with the support nodes.
  9515. *
  9516. * @private
  9517. */
  9518. _updateCalculationNodes: function () {
  9519. if (this.constants.smoothCurves == true) {
  9520. this.calculationNodes = {};
  9521. this.calculationNodeIndices = [];
  9522. for (var nodeId in this.nodes) {
  9523. if (this.nodes.hasOwnProperty(nodeId)) {
  9524. this.calculationNodes[nodeId] = this.nodes[nodeId];
  9525. }
  9526. }
  9527. var supportNodes = this.sectors['support']['nodes'];
  9528. for (var supportNodeId in supportNodes) {
  9529. if (supportNodes.hasOwnProperty(supportNodeId)) {
  9530. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  9531. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  9532. }
  9533. else {
  9534. supportNodes[supportNodeId]._setForce(0, 0);
  9535. }
  9536. }
  9537. }
  9538. for (var idx in this.calculationNodes) {
  9539. if (this.calculationNodes.hasOwnProperty(idx)) {
  9540. this.calculationNodeIndices.push(idx);
  9541. }
  9542. }
  9543. }
  9544. else {
  9545. this.calculationNodes = this.nodes;
  9546. this.calculationNodeIndices = this.nodeIndices;
  9547. }
  9548. },
  9549. /**
  9550. * this function applies the central gravity effect to keep groups from floating off
  9551. *
  9552. * @private
  9553. */
  9554. _calculateGravitationalForces: function () {
  9555. var dx, dy, distance, node, i;
  9556. var nodes = this.calculationNodes;
  9557. var gravity = this.constants.physics.centralGravity;
  9558. var gravityForce = 0;
  9559. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  9560. node = nodes[this.calculationNodeIndices[i]];
  9561. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  9562. // gravity does not apply when we are in a pocket sector
  9563. if (this._sector() == "default" && gravity != 0) {
  9564. dx = -node.x;
  9565. dy = -node.y;
  9566. distance = Math.sqrt(dx * dx + dy * dy);
  9567. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  9568. node.fx = dx * gravityForce;
  9569. node.fy = dy * gravityForce;
  9570. }
  9571. else {
  9572. node.fx = 0;
  9573. node.fy = 0;
  9574. }
  9575. }
  9576. },
  9577. /**
  9578. * this function calculates the effects of the springs in the case of unsmooth curves.
  9579. *
  9580. * @private
  9581. */
  9582. _calculateSpringForces: function () {
  9583. var edgeLength, edge, edgeId;
  9584. var dx, dy, fx, fy, springForce, length;
  9585. var edges = this.edges;
  9586. // forces caused by the edges, modelled as springs
  9587. for (edgeId in edges) {
  9588. if (edges.hasOwnProperty(edgeId)) {
  9589. edge = edges[edgeId];
  9590. if (edge.connected) {
  9591. // only calculate forces if nodes are in the same sector
  9592. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9593. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9594. // this implies that the edges between big clusters are longer
  9595. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  9596. dx = (edge.from.x - edge.to.x);
  9597. dy = (edge.from.y - edge.to.y);
  9598. length = Math.sqrt(dx * dx + dy * dy);
  9599. if (length == 0) {
  9600. length = 0.01;
  9601. }
  9602. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  9603. fx = dx * springForce;
  9604. fy = dy * springForce;
  9605. edge.from.fx += fx;
  9606. edge.from.fy += fy;
  9607. edge.to.fx -= fx;
  9608. edge.to.fy -= fy;
  9609. }
  9610. }
  9611. }
  9612. }
  9613. },
  9614. /**
  9615. * This function calculates the springforces on the nodes, accounting for the support nodes.
  9616. *
  9617. * @private
  9618. */
  9619. _calculateSpringForcesWithSupport: function () {
  9620. var edgeLength, edge, edgeId, combinedClusterSize;
  9621. var edges = this.edges;
  9622. // forces caused by the edges, modelled as springs
  9623. for (edgeId in edges) {
  9624. if (edges.hasOwnProperty(edgeId)) {
  9625. edge = edges[edgeId];
  9626. if (edge.connected) {
  9627. // only calculate forces if nodes are in the same sector
  9628. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9629. if (edge.via != null) {
  9630. var node1 = edge.to;
  9631. var node2 = edge.via;
  9632. var node3 = edge.from;
  9633. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9634. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  9635. // this implies that the edges between big clusters are longer
  9636. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  9637. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  9638. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  9639. }
  9640. }
  9641. }
  9642. }
  9643. }
  9644. },
  9645. /**
  9646. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  9647. *
  9648. * @param node1
  9649. * @param node2
  9650. * @param edgeLength
  9651. * @private
  9652. */
  9653. _calculateSpringForce: function (node1, node2, edgeLength) {
  9654. var dx, dy, fx, fy, springForce, length;
  9655. dx = (node1.x - node2.x);
  9656. dy = (node1.y - node2.y);
  9657. length = Math.sqrt(dx * dx + dy * dy);
  9658. if (length == 0) {
  9659. length = 0.01;
  9660. }
  9661. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  9662. fx = dx * springForce;
  9663. fy = dy * springForce;
  9664. node1.fx += fx;
  9665. node1.fy += fy;
  9666. node2.fx -= fx;
  9667. node2.fy -= fy;
  9668. },
  9669. /**
  9670. * Load the HTML for the physics config and bind it
  9671. * @private
  9672. */
  9673. _loadPhysicsConfiguration: function () {
  9674. if (this.physicsConfiguration === undefined) {
  9675. this.backupConstants = {};
  9676. util.copyObject(this.constants, this.backupConstants);
  9677. var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"];
  9678. this.physicsConfiguration = document.createElement('div');
  9679. this.physicsConfiguration.className = "PhysicsConfiguration";
  9680. this.physicsConfiguration.innerHTML = '' +
  9681. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  9682. '<tr>' +
  9683. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  9684. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' +
  9685. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  9686. '</tr>' +
  9687. '</table>' +
  9688. '<table id="graph_BH_table" style="display:none">' +
  9689. '<tr><td><b>Barnes Hut</b></td></tr>' +
  9690. '<tr>' +
  9691. '<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>' +
  9692. '</tr>' +
  9693. '<tr>' +
  9694. '<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>' +
  9695. '</tr>' +
  9696. '<tr>' +
  9697. '<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>' +
  9698. '</tr>' +
  9699. '<tr>' +
  9700. '<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>' +
  9701. '</tr>' +
  9702. '<tr>' +
  9703. '<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>' +
  9704. '</tr>' +
  9705. '</table>' +
  9706. '<table id="graph_R_table" style="display:none">' +
  9707. '<tr><td><b>Repulsion</b></td></tr>' +
  9708. '<tr>' +
  9709. '<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>' +
  9710. '</tr>' +
  9711. '<tr>' +
  9712. '<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>' +
  9713. '</tr>' +
  9714. '<tr>' +
  9715. '<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>' +
  9716. '</tr>' +
  9717. '<tr>' +
  9718. '<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>' +
  9719. '</tr>' +
  9720. '<tr>' +
  9721. '<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>' +
  9722. '</tr>' +
  9723. '</table>' +
  9724. '<table id="graph_H_table" style="display:none">' +
  9725. '<tr><td width="150"><b>Hierarchical</b></td></tr>' +
  9726. '<tr>' +
  9727. '<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>' +
  9728. '</tr>' +
  9729. '<tr>' +
  9730. '<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>' +
  9731. '</tr>' +
  9732. '<tr>' +
  9733. '<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>' +
  9734. '</tr>' +
  9735. '<tr>' +
  9736. '<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>' +
  9737. '</tr>' +
  9738. '<tr>' +
  9739. '<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>' +
  9740. '</tr>' +
  9741. '<tr>' +
  9742. '<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>' +
  9743. '</tr>' +
  9744. '<tr>' +
  9745. '<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>' +
  9746. '</tr>' +
  9747. '<tr>' +
  9748. '<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>' +
  9749. '</tr>' +
  9750. '</table>' +
  9751. '<table><tr><td><b>Options:</b></td></tr>' +
  9752. '<tr>' +
  9753. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  9754. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  9755. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  9756. '</tr>' +
  9757. '</table>'
  9758. this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement);
  9759. this.optionsDiv = document.createElement("div");
  9760. this.optionsDiv.style.fontSize = "14px";
  9761. this.optionsDiv.style.fontFamily = "verdana";
  9762. this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement);
  9763. var rangeElement;
  9764. rangeElement = document.getElementById('graph_BH_gc');
  9765. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant");
  9766. rangeElement = document.getElementById('graph_BH_cg');
  9767. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity");
  9768. rangeElement = document.getElementById('graph_BH_sc');
  9769. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant");
  9770. rangeElement = document.getElementById('graph_BH_sl');
  9771. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength");
  9772. rangeElement = document.getElementById('graph_BH_damp');
  9773. rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping");
  9774. rangeElement = document.getElementById('graph_R_nd');
  9775. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance");
  9776. rangeElement = document.getElementById('graph_R_cg');
  9777. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity");
  9778. rangeElement = document.getElementById('graph_R_sc');
  9779. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant");
  9780. rangeElement = document.getElementById('graph_R_sl');
  9781. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength");
  9782. rangeElement = document.getElementById('graph_R_damp');
  9783. rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping");
  9784. rangeElement = document.getElementById('graph_H_nd');
  9785. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
  9786. rangeElement = document.getElementById('graph_H_cg');
  9787. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity");
  9788. rangeElement = document.getElementById('graph_H_sc');
  9789. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant");
  9790. rangeElement = document.getElementById('graph_H_sl');
  9791. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength");
  9792. rangeElement = document.getElementById('graph_H_damp');
  9793. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping");
  9794. rangeElement = document.getElementById('graph_H_direction');
  9795. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction");
  9796. rangeElement = document.getElementById('graph_H_levsep');
  9797. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation");
  9798. rangeElement = document.getElementById('graph_H_nspac');
  9799. rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing");
  9800. var radioButton1 = document.getElementById("graph_physicsMethod1");
  9801. var radioButton2 = document.getElementById("graph_physicsMethod2");
  9802. var radioButton3 = document.getElementById("graph_physicsMethod3");
  9803. radioButton2.checked = true;
  9804. if (this.constants.physics.barnesHut.enabled) {
  9805. radioButton1.checked = true;
  9806. }
  9807. if (this.constants.hierarchicalLayout.enabled) {
  9808. radioButton3.checked = true;
  9809. }
  9810. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  9811. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  9812. var graph_generateOptions = document.getElementById("graph_generateOptions");
  9813. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  9814. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  9815. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  9816. if (this.constants.smoothCurves == true) {
  9817. graph_toggleSmooth.style.background = "#A4FF56";
  9818. }
  9819. else {
  9820. graph_toggleSmooth.style.background = "#FF8532";
  9821. }
  9822. switchConfigurations.apply(this);
  9823. radioButton1.onchange = switchConfigurations.bind(this);
  9824. radioButton2.onchange = switchConfigurations.bind(this);
  9825. radioButton3.onchange = switchConfigurations.bind(this);
  9826. }
  9827. },
  9828. _overWriteGraphConstants: function (constantsVariableName, value) {
  9829. var nameArray = constantsVariableName.split("_");
  9830. if (nameArray.length == 1) {
  9831. this.constants[nameArray[0]] = value;
  9832. }
  9833. else if (nameArray.length == 2) {
  9834. this.constants[nameArray[0]][nameArray[1]] = value;
  9835. }
  9836. else if (nameArray.length == 3) {
  9837. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  9838. }
  9839. }
  9840. };
  9841. function graphToggleSmoothCurves () {
  9842. this.constants.smoothCurves = !this.constants.smoothCurves;
  9843. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  9844. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  9845. else {graph_toggleSmooth.style.background = "#FF8532";}
  9846. this._configureSmoothCurves(false);
  9847. };
  9848. function graphRepositionNodes () {
  9849. for (var nodeId in this.calculationNodes) {
  9850. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  9851. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  9852. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  9853. }
  9854. }
  9855. if (this.constants.hierarchicalLayout.enabled == true) {
  9856. this._setupHierarchicalLayout();
  9857. }
  9858. else {
  9859. this.repositionNodes();
  9860. }
  9861. this.moving = true;
  9862. this.start();
  9863. };
  9864. function graphGenerateOptions () {
  9865. var options = "No options are required, default values used.";
  9866. var optionsSpecific = [];
  9867. var radioButton1 = document.getElementById("graph_physicsMethod1");
  9868. var radioButton2 = document.getElementById("graph_physicsMethod2");
  9869. if (radioButton1.checked == true) {
  9870. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  9871. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  9872. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  9873. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  9874. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  9875. if (optionsSpecific.length != 0) {
  9876. options = "var options = {";
  9877. options += "physics: {barnesHut: {";
  9878. for (var i = 0; i < optionsSpecific.length; i++) {
  9879. options += optionsSpecific[i];
  9880. if (i < optionsSpecific.length - 1) {
  9881. options += ", "
  9882. }
  9883. }
  9884. options += '}}'
  9885. }
  9886. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  9887. if (optionsSpecific.length == 0) {options = "var options = {";}
  9888. else {options += ", "}
  9889. options += "smoothCurves: " + this.constants.smoothCurves;
  9890. }
  9891. if (options != "No options are required, default values used.") {
  9892. options += '};'
  9893. }
  9894. }
  9895. else if (radioButton2.checked == true) {
  9896. options = "var options = {";
  9897. options += "physics: {barnesHut: {enabled: false}";
  9898. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  9899. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  9900. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  9901. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  9902. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  9903. if (optionsSpecific.length != 0) {
  9904. options += ", repulsion: {";
  9905. for (var i = 0; i < optionsSpecific.length; i++) {
  9906. options += optionsSpecific[i];
  9907. if (i < optionsSpecific.length - 1) {
  9908. options += ", "
  9909. }
  9910. }
  9911. options += '}}'
  9912. }
  9913. if (optionsSpecific.length == 0) {options += "}"}
  9914. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  9915. options += ", smoothCurves: " + this.constants.smoothCurves;
  9916. }
  9917. options += '};'
  9918. }
  9919. else {
  9920. options = "var options = {";
  9921. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  9922. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  9923. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  9924. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  9925. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  9926. if (optionsSpecific.length != 0) {
  9927. options += "physics: {hierarchicalRepulsion: {";
  9928. for (var i = 0; i < optionsSpecific.length; i++) {
  9929. options += optionsSpecific[i];
  9930. if (i < optionsSpecific.length - 1) {
  9931. options += ", ";
  9932. }
  9933. }
  9934. options += '}},';
  9935. }
  9936. options += 'hierarchicalLayout: {';
  9937. optionsSpecific = [];
  9938. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  9939. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  9940. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  9941. if (optionsSpecific.length != 0) {
  9942. for (var i = 0; i < optionsSpecific.length; i++) {
  9943. options += optionsSpecific[i];
  9944. if (i < optionsSpecific.length - 1) {
  9945. options += ", "
  9946. }
  9947. }
  9948. options += '}'
  9949. }
  9950. else {
  9951. options += "enabled:true}";
  9952. }
  9953. options += '};'
  9954. }
  9955. this.optionsDiv.innerHTML = options;
  9956. };
  9957. function switchConfigurations () {
  9958. var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"];
  9959. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  9960. var tableId = "graph_" + radioButton + "_table";
  9961. var table = document.getElementById(tableId);
  9962. table.style.display = "block";
  9963. for (var i = 0; i < ids.length; i++) {
  9964. if (ids[i] != tableId) {
  9965. table = document.getElementById(ids[i]);
  9966. table.style.display = "none";
  9967. }
  9968. }
  9969. this._restoreNodes();
  9970. if (radioButton == "R") {
  9971. this.constants.hierarchicalLayout.enabled = false;
  9972. this.constants.physics.hierarchicalRepulsion.enabled = false;
  9973. this.constants.physics.barnesHut.enabled = false;
  9974. }
  9975. else if (radioButton == "H") {
  9976. this.constants.hierarchicalLayout.enabled = true;
  9977. this.constants.physics.hierarchicalRepulsion.enabled = true;
  9978. this.constants.physics.barnesHut.enabled = false;
  9979. this._setupHierarchicalLayout();
  9980. }
  9981. else {
  9982. this.constants.hierarchicalLayout.enabled = false;
  9983. this.constants.physics.hierarchicalRepulsion.enabled = false;
  9984. this.constants.physics.barnesHut.enabled = true;
  9985. }
  9986. this._loadSelectedForceSolver();
  9987. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  9988. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  9989. else {graph_toggleSmooth.style.background = "#FF8532";}
  9990. this.moving = true;
  9991. this.start();
  9992. }
  9993. function showValueOfRange (id,map,constantsVariableName) {
  9994. var valueId = id + "_value";
  9995. var rangeValue = document.getElementById(id).value;
  9996. if (map instanceof Array) {
  9997. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  9998. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  9999. }
  10000. else {
  10001. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  10002. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  10003. }
  10004. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10005. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10006. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10007. this._setupHierarchicalLayout();
  10008. }
  10009. this.moving = true;
  10010. this.start();
  10011. };
  10012. /**
  10013. * Created by Alex on 2/10/14.
  10014. */
  10015. var hierarchalRepulsionMixin = {
  10016. /**
  10017. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10018. * This field is linearly approximated.
  10019. *
  10020. * @private
  10021. */
  10022. _calculateNodeForces: function () {
  10023. var dx, dy, distance, fx, fy, combinedClusterSize,
  10024. repulsingForce, node1, node2, i, j;
  10025. var nodes = this.calculationNodes;
  10026. var nodeIndices = this.calculationNodeIndices;
  10027. // approximation constants
  10028. var b = 5;
  10029. var a_base = 0.5 * -b;
  10030. // repulsing forces between nodes
  10031. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  10032. var minimumDistance = nodeDistance;
  10033. // we loop from i over all but the last entree in the array
  10034. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10035. for (i = 0; i < nodeIndices.length - 1; i++) {
  10036. node1 = nodes[nodeIndices[i]];
  10037. for (j = i + 1; j < nodeIndices.length; j++) {
  10038. node2 = nodes[nodeIndices[j]];
  10039. dx = node2.x - node1.x;
  10040. dy = node2.y - node1.y;
  10041. distance = Math.sqrt(dx * dx + dy * dy);
  10042. var a = a_base / minimumDistance;
  10043. if (distance < 2 * minimumDistance) {
  10044. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10045. // normalize force with
  10046. if (distance == 0) {
  10047. distance = 0.01;
  10048. }
  10049. else {
  10050. repulsingForce = repulsingForce / distance;
  10051. }
  10052. fx = dx * repulsingForce;
  10053. fy = dy * repulsingForce;
  10054. node1.fx -= fx;
  10055. node1.fy -= fy;
  10056. node2.fx += fx;
  10057. node2.fy += fy;
  10058. }
  10059. }
  10060. }
  10061. }
  10062. };
  10063. /**
  10064. * Created by Alex on 2/10/14.
  10065. */
  10066. var barnesHutMixin = {
  10067. /**
  10068. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10069. * The Barnes Hut method is used to speed up this N-body simulation.
  10070. *
  10071. * @private
  10072. */
  10073. _calculateNodeForces : function() {
  10074. if (this.constants.physics.barnesHut.gravitationalConstant != 0) {
  10075. var node;
  10076. var nodes = this.calculationNodes;
  10077. var nodeIndices = this.calculationNodeIndices;
  10078. var nodeCount = nodeIndices.length;
  10079. this._formBarnesHutTree(nodes,nodeIndices);
  10080. var barnesHutTree = this.barnesHutTree;
  10081. // place the nodes one by one recursively
  10082. for (var i = 0; i < nodeCount; i++) {
  10083. node = nodes[nodeIndices[i]];
  10084. // starting with root is irrelevant, it never passes the BarnesHut condition
  10085. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10086. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10087. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10088. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10089. }
  10090. }
  10091. },
  10092. /**
  10093. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10094. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10095. *
  10096. * @param parentBranch
  10097. * @param node
  10098. * @private
  10099. */
  10100. _getForceContribution : function(parentBranch,node) {
  10101. // we get no force contribution from an empty region
  10102. if (parentBranch.childrenCount > 0) {
  10103. var dx,dy,distance;
  10104. // get the distance from the center of mass to the node.
  10105. dx = parentBranch.centerOfMass.x - node.x;
  10106. dy = parentBranch.centerOfMass.y - node.y;
  10107. distance = Math.sqrt(dx * dx + dy * dy);
  10108. // BarnesHut condition
  10109. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10110. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10111. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10112. // duplicate code to reduce function calls to speed up program
  10113. if (distance == 0) {
  10114. distance = 0.1*Math.random();
  10115. dx = distance;
  10116. }
  10117. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10118. var fx = dx * gravityForce;
  10119. var fy = dy * gravityForce;
  10120. node.fx += fx;
  10121. node.fy += fy;
  10122. }
  10123. else {
  10124. // Did not pass the condition, go into children if available
  10125. if (parentBranch.childrenCount == 4) {
  10126. this._getForceContribution(parentBranch.children.NW,node);
  10127. this._getForceContribution(parentBranch.children.NE,node);
  10128. this._getForceContribution(parentBranch.children.SW,node);
  10129. this._getForceContribution(parentBranch.children.SE,node);
  10130. }
  10131. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10132. if (parentBranch.children.data.id != node.id) { // if it is not self
  10133. // duplicate code to reduce function calls to speed up program
  10134. if (distance == 0) {
  10135. distance = 0.5*Math.random();
  10136. dx = distance;
  10137. }
  10138. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10139. var fx = dx * gravityForce;
  10140. var fy = dy * gravityForce;
  10141. node.fx += fx;
  10142. node.fy += fy;
  10143. }
  10144. }
  10145. }
  10146. }
  10147. },
  10148. /**
  10149. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10150. *
  10151. * @param nodes
  10152. * @param nodeIndices
  10153. * @private
  10154. */
  10155. _formBarnesHutTree : function(nodes,nodeIndices) {
  10156. var node;
  10157. var nodeCount = nodeIndices.length;
  10158. var minX = Number.MAX_VALUE,
  10159. minY = Number.MAX_VALUE,
  10160. maxX =-Number.MAX_VALUE,
  10161. maxY =-Number.MAX_VALUE;
  10162. // get the range of the nodes
  10163. for (var i = 0; i < nodeCount; i++) {
  10164. var x = nodes[nodeIndices[i]].x;
  10165. var y = nodes[nodeIndices[i]].y;
  10166. if (x < minX) { minX = x; }
  10167. if (x > maxX) { maxX = x; }
  10168. if (y < minY) { minY = y; }
  10169. if (y > maxY) { maxY = y; }
  10170. }
  10171. // make the range a square
  10172. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10173. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10174. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10175. var minimumTreeSize = 1e-5;
  10176. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10177. var halfRootSize = 0.5 * rootSize;
  10178. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10179. // construct the barnesHutTree
  10180. var barnesHutTree = {root:{
  10181. centerOfMass:{x:0,y:0}, // Center of Mass
  10182. mass:0,
  10183. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10184. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10185. size: rootSize,
  10186. calcSize: 1 / rootSize,
  10187. children: {data:null},
  10188. maxWidth: 0,
  10189. level: 0,
  10190. childrenCount: 4
  10191. }};
  10192. this._splitBranch(barnesHutTree.root);
  10193. // place the nodes one by one recursively
  10194. for (i = 0; i < nodeCount; i++) {
  10195. node = nodes[nodeIndices[i]];
  10196. this._placeInTree(barnesHutTree.root,node);
  10197. }
  10198. // make global
  10199. this.barnesHutTree = barnesHutTree
  10200. },
  10201. _updateBranchMass : function(parentBranch, node) {
  10202. var totalMass = parentBranch.mass + node.mass;
  10203. var totalMassInv = 1/totalMass;
  10204. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10205. parentBranch.centerOfMass.x *= totalMassInv;
  10206. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10207. parentBranch.centerOfMass.y *= totalMassInv;
  10208. parentBranch.mass = totalMass;
  10209. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10210. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10211. },
  10212. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10213. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10214. // update the mass of the branch.
  10215. this._updateBranchMass(parentBranch,node);
  10216. }
  10217. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10218. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10219. this._placeInRegion(parentBranch,node,"NW");
  10220. }
  10221. else { // in SW
  10222. this._placeInRegion(parentBranch,node,"SW");
  10223. }
  10224. }
  10225. else { // in NE or SE
  10226. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10227. this._placeInRegion(parentBranch,node,"NE");
  10228. }
  10229. else { // in SE
  10230. this._placeInRegion(parentBranch,node,"SE");
  10231. }
  10232. }
  10233. },
  10234. _placeInRegion : function(parentBranch,node,region) {
  10235. switch (parentBranch.children[region].childrenCount) {
  10236. case 0: // place node here
  10237. parentBranch.children[region].children.data = node;
  10238. parentBranch.children[region].childrenCount = 1;
  10239. this._updateBranchMass(parentBranch.children[region],node);
  10240. break;
  10241. case 1: // convert into children
  10242. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10243. // we move one node a pixel and we do not put it in the tree.
  10244. if (parentBranch.children[region].children.data.x == node.x &&
  10245. parentBranch.children[region].children.data.y == node.y) {
  10246. node.x += Math.random();
  10247. node.y += Math.random();
  10248. }
  10249. else {
  10250. this._splitBranch(parentBranch.children[region]);
  10251. this._placeInTree(parentBranch.children[region],node);
  10252. }
  10253. break;
  10254. case 4: // place in branch
  10255. this._placeInTree(parentBranch.children[region],node);
  10256. break;
  10257. }
  10258. },
  10259. /**
  10260. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10261. * after the split is complete.
  10262. *
  10263. * @param parentBranch
  10264. * @private
  10265. */
  10266. _splitBranch : function(parentBranch) {
  10267. // if the branch is filled with a node, replace the node in the new subset.
  10268. var containedNode = null;
  10269. if (parentBranch.childrenCount == 1) {
  10270. containedNode = parentBranch.children.data;
  10271. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10272. }
  10273. parentBranch.childrenCount = 4;
  10274. parentBranch.children.data = null;
  10275. this._insertRegion(parentBranch,"NW");
  10276. this._insertRegion(parentBranch,"NE");
  10277. this._insertRegion(parentBranch,"SW");
  10278. this._insertRegion(parentBranch,"SE");
  10279. if (containedNode != null) {
  10280. this._placeInTree(parentBranch,containedNode);
  10281. }
  10282. },
  10283. /**
  10284. * This function subdivides the region into four new segments.
  10285. * Specifically, this inserts a single new segment.
  10286. * It fills the children section of the parentBranch
  10287. *
  10288. * @param parentBranch
  10289. * @param region
  10290. * @param parentRange
  10291. * @private
  10292. */
  10293. _insertRegion : function(parentBranch, region) {
  10294. var minX,maxX,minY,maxY;
  10295. var childSize = 0.5 * parentBranch.size;
  10296. switch (region) {
  10297. case "NW":
  10298. minX = parentBranch.range.minX;
  10299. maxX = parentBranch.range.minX + childSize;
  10300. minY = parentBranch.range.minY;
  10301. maxY = parentBranch.range.minY + childSize;
  10302. break;
  10303. case "NE":
  10304. minX = parentBranch.range.minX + childSize;
  10305. maxX = parentBranch.range.maxX;
  10306. minY = parentBranch.range.minY;
  10307. maxY = parentBranch.range.minY + childSize;
  10308. break;
  10309. case "SW":
  10310. minX = parentBranch.range.minX;
  10311. maxX = parentBranch.range.minX + childSize;
  10312. minY = parentBranch.range.minY + childSize;
  10313. maxY = parentBranch.range.maxY;
  10314. break;
  10315. case "SE":
  10316. minX = parentBranch.range.minX + childSize;
  10317. maxX = parentBranch.range.maxX;
  10318. minY = parentBranch.range.minY + childSize;
  10319. maxY = parentBranch.range.maxY;
  10320. break;
  10321. }
  10322. parentBranch.children[region] = {
  10323. centerOfMass:{x:0,y:0},
  10324. mass:0,
  10325. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10326. size: 0.5 * parentBranch.size,
  10327. calcSize: 2 * parentBranch.calcSize,
  10328. children: {data:null},
  10329. maxWidth: 0,
  10330. level: parentBranch.level+1,
  10331. childrenCount: 0
  10332. };
  10333. },
  10334. /**
  10335. * This function is for debugging purposed, it draws the tree.
  10336. *
  10337. * @param ctx
  10338. * @param color
  10339. * @private
  10340. */
  10341. _drawTree : function(ctx,color) {
  10342. if (this.barnesHutTree !== undefined) {
  10343. ctx.lineWidth = 1;
  10344. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10345. }
  10346. },
  10347. /**
  10348. * This function is for debugging purposes. It draws the branches recursively.
  10349. *
  10350. * @param branch
  10351. * @param ctx
  10352. * @param color
  10353. * @private
  10354. */
  10355. _drawBranch : function(branch,ctx,color) {
  10356. if (color === undefined) {
  10357. color = "#FF0000";
  10358. }
  10359. if (branch.childrenCount == 4) {
  10360. this._drawBranch(branch.children.NW,ctx);
  10361. this._drawBranch(branch.children.NE,ctx);
  10362. this._drawBranch(branch.children.SE,ctx);
  10363. this._drawBranch(branch.children.SW,ctx);
  10364. }
  10365. ctx.strokeStyle = color;
  10366. ctx.beginPath();
  10367. ctx.moveTo(branch.range.minX,branch.range.minY);
  10368. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10369. ctx.stroke();
  10370. ctx.beginPath();
  10371. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10372. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10373. ctx.stroke();
  10374. ctx.beginPath();
  10375. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10376. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10377. ctx.stroke();
  10378. ctx.beginPath();
  10379. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10380. ctx.lineTo(branch.range.minX,branch.range.minY);
  10381. ctx.stroke();
  10382. /*
  10383. if (branch.mass > 0) {
  10384. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  10385. ctx.stroke();
  10386. }
  10387. */
  10388. }
  10389. };
  10390. /**
  10391. * Created by Alex on 2/10/14.
  10392. */
  10393. var repulsionMixin = {
  10394. /**
  10395. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10396. * This field is linearly approximated.
  10397. *
  10398. * @private
  10399. */
  10400. _calculateNodeForces: function () {
  10401. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  10402. repulsingForce, node1, node2, i, j;
  10403. var nodes = this.calculationNodes;
  10404. var nodeIndices = this.calculationNodeIndices;
  10405. // approximation constants
  10406. var a_base = -2 / 3;
  10407. var b = 4 / 3;
  10408. // repulsing forces between nodes
  10409. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10410. var minimumDistance = nodeDistance;
  10411. // we loop from i over all but the last entree in the array
  10412. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10413. for (i = 0; i < nodeIndices.length - 1; i++) {
  10414. node1 = nodes[nodeIndices[i]];
  10415. for (j = i + 1; j < nodeIndices.length; j++) {
  10416. node2 = nodes[nodeIndices[j]];
  10417. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  10418. dx = node2.x - node1.x;
  10419. dy = node2.y - node1.y;
  10420. distance = Math.sqrt(dx * dx + dy * dy);
  10421. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  10422. var a = a_base / minimumDistance;
  10423. if (distance < 2 * minimumDistance) {
  10424. if (distance < 0.5 * minimumDistance) {
  10425. repulsingForce = 1.0;
  10426. }
  10427. else {
  10428. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10429. }
  10430. // amplify the repulsion for clusters.
  10431. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  10432. repulsingForce = repulsingForce / distance;
  10433. fx = dx * repulsingForce;
  10434. fy = dy * repulsingForce;
  10435. node1.fx -= fx;
  10436. node1.fy -= fy;
  10437. node2.fx += fx;
  10438. node2.fy += fy;
  10439. }
  10440. }
  10441. }
  10442. }
  10443. };
  10444. var HierarchicalLayoutMixin = {
  10445. _resetLevels : function() {
  10446. for (var nodeId in this.nodes) {
  10447. if (this.nodes.hasOwnProperty(nodeId)) {
  10448. var node = this.nodes[nodeId];
  10449. if (node.preassignedLevel == false) {
  10450. node.level = -1;
  10451. }
  10452. }
  10453. }
  10454. },
  10455. /**
  10456. * This is the main function to layout the nodes in a hierarchical way.
  10457. * It checks if the node details are supplied correctly
  10458. *
  10459. * @private
  10460. */
  10461. _setupHierarchicalLayout : function() {
  10462. if (this.constants.hierarchicalLayout.enabled == true) {
  10463. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  10464. this.constants.hierarchicalLayout.levelSeparation *= -1;
  10465. }
  10466. else {
  10467. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  10468. }
  10469. // get the size of the largest hubs and check if the user has defined a level for a node.
  10470. var hubsize = 0;
  10471. var node, nodeId;
  10472. var definedLevel = false;
  10473. var undefinedLevel = false;
  10474. for (nodeId in this.nodes) {
  10475. if (this.nodes.hasOwnProperty(nodeId)) {
  10476. node = this.nodes[nodeId];
  10477. if (node.level != -1) {
  10478. definedLevel = true;
  10479. }
  10480. else {
  10481. undefinedLevel = true;
  10482. }
  10483. if (hubsize < node.edges.length) {
  10484. hubsize = node.edges.length;
  10485. }
  10486. }
  10487. }
  10488. // if the user defined some levels but not all, alert and run without hierarchical layout
  10489. if (undefinedLevel == true && definedLevel == true) {
  10490. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");
  10491. this.zoomExtent(true,this.constants.clustering.enabled);
  10492. if (!this.constants.clustering.enabled) {
  10493. this.start();
  10494. }
  10495. }
  10496. else {
  10497. // setup the system to use hierarchical method.
  10498. this._changeConstants();
  10499. // define levels if undefined by the users. Based on hubsize
  10500. if (undefinedLevel == true) {
  10501. this._determineLevels(hubsize);
  10502. }
  10503. // check the distribution of the nodes per level.
  10504. var distribution = this._getDistribution();
  10505. // place the nodes on the canvas. This also stablilizes the system.
  10506. this._placeNodesByHierarchy(distribution);
  10507. // start the simulation.
  10508. this.start();
  10509. }
  10510. }
  10511. },
  10512. /**
  10513. * This function places the nodes on the canvas based on the hierarchial distribution.
  10514. *
  10515. * @param {Object} distribution | obtained by the function this._getDistribution()
  10516. * @private
  10517. */
  10518. _placeNodesByHierarchy : function(distribution) {
  10519. var nodeId, node;
  10520. // start placing all the level 0 nodes first. Then recursively position their branches.
  10521. for (nodeId in distribution[0].nodes) {
  10522. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  10523. node = distribution[0].nodes[nodeId];
  10524. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10525. if (node.xFixed) {
  10526. node.x = distribution[0].minPos;
  10527. node.xFixed = false;
  10528. distribution[0].minPos += distribution[0].nodeSpacing;
  10529. }
  10530. }
  10531. else {
  10532. if (node.yFixed) {
  10533. node.y = distribution[0].minPos;
  10534. node.yFixed = false;
  10535. distribution[0].minPos += distribution[0].nodeSpacing;
  10536. }
  10537. }
  10538. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  10539. }
  10540. }
  10541. // stabilize the system after positioning. This function calls zoomExtent.
  10542. this._stabilize();
  10543. },
  10544. /**
  10545. * This function get the distribution of levels based on hubsize
  10546. *
  10547. * @returns {Object}
  10548. * @private
  10549. */
  10550. _getDistribution : function() {
  10551. var distribution = {};
  10552. var nodeId, node;
  10553. // 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.
  10554. // the fix of X is removed after the x value has been set.
  10555. for (nodeId in this.nodes) {
  10556. if (this.nodes.hasOwnProperty(nodeId)) {
  10557. node = this.nodes[nodeId];
  10558. node.xFixed = true;
  10559. node.yFixed = true;
  10560. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10561. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10562. }
  10563. else {
  10564. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10565. }
  10566. if (!distribution.hasOwnProperty(node.level)) {
  10567. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  10568. }
  10569. distribution[node.level].amount += 1;
  10570. distribution[node.level].nodes[node.id] = node;
  10571. }
  10572. }
  10573. // determine the largest amount of nodes of all levels
  10574. var maxCount = 0;
  10575. for (var level in distribution) {
  10576. if (distribution.hasOwnProperty(level)) {
  10577. if (maxCount < distribution[level].amount) {
  10578. maxCount = distribution[level].amount;
  10579. }
  10580. }
  10581. }
  10582. // set the initial position and spacing of each nodes accordingly
  10583. for (var level in distribution) {
  10584. if (distribution.hasOwnProperty(level)) {
  10585. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  10586. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  10587. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  10588. }
  10589. }
  10590. return distribution;
  10591. },
  10592. /**
  10593. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  10594. *
  10595. * @param hubsize
  10596. * @private
  10597. */
  10598. _determineLevels : function(hubsize) {
  10599. var nodeId, node;
  10600. // determine hubs
  10601. for (nodeId in this.nodes) {
  10602. if (this.nodes.hasOwnProperty(nodeId)) {
  10603. node = this.nodes[nodeId];
  10604. if (node.edges.length == hubsize) {
  10605. node.level = 0;
  10606. }
  10607. }
  10608. }
  10609. // branch from hubs
  10610. for (nodeId in this.nodes) {
  10611. if (this.nodes.hasOwnProperty(nodeId)) {
  10612. node = this.nodes[nodeId];
  10613. if (node.level == 0) {
  10614. this._setLevel(1,node.edges,node.id);
  10615. }
  10616. }
  10617. }
  10618. },
  10619. /**
  10620. * Since hierarchical layout does not support:
  10621. * - smooth curves (based on the physics),
  10622. * - clustering (based on dynamic node counts)
  10623. *
  10624. * We disable both features so there will be no problems.
  10625. *
  10626. * @private
  10627. */
  10628. _changeConstants : function() {
  10629. this.constants.clustering.enabled = false;
  10630. this.constants.physics.barnesHut.enabled = false;
  10631. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10632. this._loadSelectedForceSolver();
  10633. this.constants.smoothCurves = false;
  10634. this._configureSmoothCurves();
  10635. },
  10636. /**
  10637. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  10638. * on a X position that ensures there will be no overlap.
  10639. *
  10640. * @param edges
  10641. * @param parentId
  10642. * @param distribution
  10643. * @param parentLevel
  10644. * @private
  10645. */
  10646. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  10647. for (var i = 0; i < edges.length; i++) {
  10648. var childNode = null;
  10649. if (edges[i].toId == parentId) {
  10650. childNode = edges[i].from;
  10651. }
  10652. else {
  10653. childNode = edges[i].to;
  10654. }
  10655. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  10656. var nodeMoved = false;
  10657. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10658. if (childNode.xFixed && childNode.level > parentLevel) {
  10659. childNode.xFixed = false;
  10660. childNode.x = distribution[childNode.level].minPos;
  10661. nodeMoved = true;
  10662. }
  10663. }
  10664. else {
  10665. if (childNode.yFixed && childNode.level > parentLevel) {
  10666. childNode.yFixed = false;
  10667. childNode.y = distribution[childNode.level].minPos;
  10668. nodeMoved = true;
  10669. }
  10670. }
  10671. if (nodeMoved == true) {
  10672. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  10673. if (childNode.edges.length > 1) {
  10674. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  10675. }
  10676. }
  10677. }
  10678. },
  10679. /**
  10680. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  10681. *
  10682. * @param level
  10683. * @param edges
  10684. * @param parentId
  10685. * @private
  10686. */
  10687. _setLevel : function(level, edges, parentId) {
  10688. for (var i = 0; i < edges.length; i++) {
  10689. var childNode = null;
  10690. if (edges[i].toId == parentId) {
  10691. childNode = edges[i].from;
  10692. }
  10693. else {
  10694. childNode = edges[i].to;
  10695. }
  10696. if (childNode.level == -1 || childNode.level > level) {
  10697. childNode.level = level;
  10698. if (edges.length > 1) {
  10699. this._setLevel(level+1, childNode.edges, childNode.id);
  10700. }
  10701. }
  10702. }
  10703. },
  10704. /**
  10705. * Unfix nodes
  10706. *
  10707. * @private
  10708. */
  10709. _restoreNodes : function() {
  10710. for (nodeId in this.nodes) {
  10711. if (this.nodes.hasOwnProperty(nodeId)) {
  10712. this.nodes[nodeId].xFixed = false;
  10713. this.nodes[nodeId].yFixed = false;
  10714. }
  10715. }
  10716. }
  10717. };
  10718. /**
  10719. * Created by Alex on 2/4/14.
  10720. */
  10721. var manipulationMixin = {
  10722. /**
  10723. * clears the toolbar div element of children
  10724. *
  10725. * @private
  10726. */
  10727. _clearManipulatorBar : function() {
  10728. while (this.manipulationDiv.hasChildNodes()) {
  10729. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  10730. }
  10731. },
  10732. /**
  10733. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  10734. * these functions to their original functionality, we saved them in this.cachedFunctions.
  10735. * This function restores these functions to their original function.
  10736. *
  10737. * @private
  10738. */
  10739. _restoreOverloadedFunctions : function() {
  10740. for (var functionName in this.cachedFunctions) {
  10741. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  10742. this[functionName] = this.cachedFunctions[functionName];
  10743. }
  10744. }
  10745. },
  10746. /**
  10747. * Enable or disable edit-mode.
  10748. *
  10749. * @private
  10750. */
  10751. _toggleEditMode : function() {
  10752. this.editMode = !this.editMode;
  10753. var toolbar = document.getElementById("graph-manipulationDiv");
  10754. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  10755. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  10756. if (this.editMode == true) {
  10757. toolbar.style.display="block";
  10758. closeDiv.style.display="block";
  10759. editModeDiv.style.display="none";
  10760. closeDiv.onclick = this._toggleEditMode.bind(this);
  10761. }
  10762. else {
  10763. toolbar.style.display="none";
  10764. closeDiv.style.display="none";
  10765. editModeDiv.style.display="block";
  10766. closeDiv.onclick = null;
  10767. }
  10768. this._createManipulatorBar()
  10769. },
  10770. /**
  10771. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  10772. *
  10773. * @private
  10774. */
  10775. _createManipulatorBar : function() {
  10776. // remove bound functions
  10777. if (this.boundFunction) {
  10778. this.off('select', this.boundFunction);
  10779. }
  10780. // restore overloaded functions
  10781. this._restoreOverloadedFunctions();
  10782. // resume calculation
  10783. this.freezeSimulation = false;
  10784. // reset global variables
  10785. this.blockConnectingEdgeSelection = false;
  10786. this.forceAppendSelection = false;
  10787. if (this.editMode == true) {
  10788. while (this.manipulationDiv.hasChildNodes()) {
  10789. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  10790. }
  10791. // add the icons to the manipulator div
  10792. this.manipulationDiv.innerHTML = "" +
  10793. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  10794. "<span class='graph-manipulationLabel'>"+this.constants.labels['add'] +"</span></span>" +
  10795. "<div class='graph-seperatorLine'></div>" +
  10796. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  10797. "<span class='graph-manipulationLabel'>"+this.constants.labels['link'] +"</span></span>";
  10798. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  10799. this.manipulationDiv.innerHTML += "" +
  10800. "<div class='graph-seperatorLine'></div>" +
  10801. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  10802. "<span class='graph-manipulationLabel'>"+this.constants.labels['editNode'] +"</span></span>";
  10803. }
  10804. if (this._selectionIsEmpty() == false) {
  10805. this.manipulationDiv.innerHTML += "" +
  10806. "<div class='graph-seperatorLine'></div>" +
  10807. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  10808. "<span class='graph-manipulationLabel'>"+this.constants.labels['del'] +"</span></span>";
  10809. }
  10810. // bind the icons
  10811. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  10812. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  10813. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  10814. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  10815. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  10816. var editButton = document.getElementById("graph-manipulate-editNode");
  10817. editButton.onclick = this._editNode.bind(this);
  10818. }
  10819. if (this._selectionIsEmpty() == false) {
  10820. var deleteButton = document.getElementById("graph-manipulate-delete");
  10821. deleteButton.onclick = this._deleteSelected.bind(this);
  10822. }
  10823. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  10824. closeDiv.onclick = this._toggleEditMode.bind(this);
  10825. this.boundFunction = this._createManipulatorBar.bind(this);
  10826. this.on('select', this.boundFunction);
  10827. }
  10828. else {
  10829. this.editModeDiv.innerHTML = "" +
  10830. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  10831. "<span class='graph-manipulationLabel'>" + this.constants.labels['edit'] + "</span></span>";
  10832. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  10833. editModeButton.onclick = this._toggleEditMode.bind(this);
  10834. }
  10835. },
  10836. /**
  10837. * Create the toolbar for adding Nodes
  10838. *
  10839. * @private
  10840. */
  10841. _createAddNodeToolbar : function() {
  10842. // clear the toolbar
  10843. this._clearManipulatorBar();
  10844. if (this.boundFunction) {
  10845. this.off('select', this.boundFunction);
  10846. }
  10847. // create the toolbar contents
  10848. this.manipulationDiv.innerHTML = "" +
  10849. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  10850. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  10851. "<div class='graph-seperatorLine'></div>" +
  10852. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  10853. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['addDescription'] + "</span></span>";
  10854. // bind the icon
  10855. var backButton = document.getElementById("graph-manipulate-back");
  10856. backButton.onclick = this._createManipulatorBar.bind(this);
  10857. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  10858. this.boundFunction = this._addNode.bind(this);
  10859. this.on('select', this.boundFunction);
  10860. },
  10861. /**
  10862. * create the toolbar to connect nodes
  10863. *
  10864. * @private
  10865. */
  10866. _createAddEdgeToolbar : function() {
  10867. // clear the toolbar
  10868. this._clearManipulatorBar();
  10869. this._unselectAll(true);
  10870. this.freezeSimulation = true;
  10871. if (this.boundFunction) {
  10872. this.off('select', this.boundFunction);
  10873. }
  10874. this._unselectAll();
  10875. this.forceAppendSelection = false;
  10876. this.blockConnectingEdgeSelection = true;
  10877. this.manipulationDiv.innerHTML = "" +
  10878. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  10879. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  10880. "<div class='graph-seperatorLine'></div>" +
  10881. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  10882. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['linkDescription'] + "</span></span>";
  10883. // bind the icon
  10884. var backButton = document.getElementById("graph-manipulate-back");
  10885. backButton.onclick = this._createManipulatorBar.bind(this);
  10886. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  10887. this.boundFunction = this._handleConnect.bind(this);
  10888. this.on('select', this.boundFunction);
  10889. // temporarily overload functions
  10890. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  10891. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  10892. this._handleTouch = this._handleConnect;
  10893. this._handleOnRelease = this._finishConnect;
  10894. // redraw to show the unselect
  10895. this._redraw();
  10896. },
  10897. /**
  10898. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  10899. * to walk the user through the process.
  10900. *
  10901. * @private
  10902. */
  10903. _handleConnect : function(pointer) {
  10904. if (this._getSelectedNodeCount() == 0) {
  10905. var node = this._getNodeAt(pointer);
  10906. if (node != null) {
  10907. if (node.clusterSize > 1) {
  10908. alert("Cannot create edges to a cluster.")
  10909. }
  10910. else {
  10911. this._selectObject(node,false);
  10912. // create a node the temporary line can look at
  10913. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  10914. this.sectors['support']['nodes']['targetNode'].x = node.x;
  10915. this.sectors['support']['nodes']['targetNode'].y = node.y;
  10916. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  10917. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  10918. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  10919. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  10920. // create a temporary edge
  10921. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  10922. this.edges['connectionEdge'].from = node;
  10923. this.edges['connectionEdge'].connected = true;
  10924. this.edges['connectionEdge'].smooth = true;
  10925. this.edges['connectionEdge'].selected = true;
  10926. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  10927. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  10928. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  10929. this._handleOnDrag = function(event) {
  10930. var pointer = this._getPointer(event.gesture.center);
  10931. this.sectors['support']['nodes']['targetNode'].x = this._canvasToX(pointer.x);
  10932. this.sectors['support']['nodes']['targetNode'].y = this._canvasToY(pointer.y);
  10933. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._canvasToX(pointer.x) + this.edges['connectionEdge'].from.x);
  10934. this.sectors['support']['nodes']['targetViaNode'].y = this._canvasToY(pointer.y);
  10935. };
  10936. this.moving = true;
  10937. this.start();
  10938. }
  10939. }
  10940. }
  10941. },
  10942. _finishConnect : function(pointer) {
  10943. if (this._getSelectedNodeCount() == 1) {
  10944. // restore the drag function
  10945. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  10946. delete this.cachedFunctions["_handleOnDrag"];
  10947. // remember the edge id
  10948. var connectFromId = this.edges['connectionEdge'].fromId;
  10949. // remove the temporary nodes and edge
  10950. delete this.edges['connectionEdge'];
  10951. delete this.sectors['support']['nodes']['targetNode'];
  10952. delete this.sectors['support']['nodes']['targetViaNode'];
  10953. var node = this._getNodeAt(pointer);
  10954. if (node != null) {
  10955. if (node.clusterSize > 1) {
  10956. alert("Cannot create edges to a cluster.")
  10957. }
  10958. else {
  10959. this._createEdge(connectFromId,node.id);
  10960. this._createManipulatorBar();
  10961. }
  10962. }
  10963. this._unselectAll();
  10964. }
  10965. },
  10966. /**
  10967. * Adds a node on the specified location
  10968. *
  10969. * @param {Object} pointer
  10970. */
  10971. _addNode : function() {
  10972. if (this._selectionIsEmpty() && this.editMode == true) {
  10973. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  10974. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  10975. if (this.triggerFunctions.add) {
  10976. if (this.triggerFunctions.add.length == 2) {
  10977. var me = this;
  10978. this.triggerFunctions.add(defaultData, function(finalizedData) {
  10979. me.nodesData.add(finalizedData);
  10980. me._createManipulatorBar();
  10981. me.moving = true;
  10982. me.start();
  10983. });
  10984. }
  10985. else {
  10986. alert(this.constants.labels['addError']);
  10987. this._createManipulatorBar();
  10988. this.moving = true;
  10989. this.start();
  10990. }
  10991. }
  10992. else {
  10993. this.nodesData.add(defaultData);
  10994. this._createManipulatorBar();
  10995. this.moving = true;
  10996. this.start();
  10997. }
  10998. }
  10999. },
  11000. /**
  11001. * connect two nodes with a new edge.
  11002. *
  11003. * @private
  11004. */
  11005. _createEdge : function(sourceNodeId,targetNodeId) {
  11006. if (this.editMode == true) {
  11007. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11008. if (this.triggerFunctions.connect) {
  11009. if (this.triggerFunctions.connect.length == 2) {
  11010. var me = this;
  11011. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11012. me.edgesData.add(finalizedData);
  11013. me.moving = true;
  11014. me.start();
  11015. });
  11016. }
  11017. else {
  11018. alert(this.constants.labels["linkError"]);
  11019. this.moving = true;
  11020. this.start();
  11021. }
  11022. }
  11023. else {
  11024. this.edgesData.add(defaultData);
  11025. this.moving = true;
  11026. this.start();
  11027. }
  11028. }
  11029. },
  11030. /**
  11031. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11032. *
  11033. * @private
  11034. */
  11035. _editNode : function() {
  11036. if (this.triggerFunctions.edit && this.editMode == true) {
  11037. var node = this._getSelectedNode();
  11038. var data = {id:node.id,
  11039. label: node.label,
  11040. group: node.group,
  11041. shape: node.shape,
  11042. color: {
  11043. background:node.color.background,
  11044. border:node.color.border,
  11045. highlight: {
  11046. background:node.color.highlight.background,
  11047. border:node.color.highlight.border
  11048. }
  11049. }};
  11050. if (this.triggerFunctions.edit.length == 2) {
  11051. var me = this;
  11052. this.triggerFunctions.edit(data, function (finalizedData) {
  11053. me.nodesData.update(finalizedData);
  11054. me._createManipulatorBar();
  11055. me.moving = true;
  11056. me.start();
  11057. });
  11058. }
  11059. else {
  11060. alert(this.constants.labels["editError"]);
  11061. }
  11062. }
  11063. else {
  11064. alert(this.constants.labels["editBoundError"]);
  11065. }
  11066. },
  11067. /**
  11068. * delete everything in the selection
  11069. *
  11070. * @private
  11071. */
  11072. _deleteSelected : function() {
  11073. if (!this._selectionIsEmpty() && this.editMode == true) {
  11074. if (!this._clusterInSelection()) {
  11075. var selectedNodes = this.getSelectedNodes();
  11076. var selectedEdges = this.getSelectedEdges();
  11077. if (this.triggerFunctions.del) {
  11078. var me = this;
  11079. var data = {nodes: selectedNodes, edges: selectedEdges};
  11080. if (this.triggerFunctions.del.length = 2) {
  11081. this.triggerFunctions.del(data, function (finalizedData) {
  11082. me.edgesData.remove(finalizedData.edges);
  11083. me.nodesData.remove(finalizedData.nodes);
  11084. me._unselectAll();
  11085. me.moving = true;
  11086. me.start();
  11087. });
  11088. }
  11089. else {
  11090. alert(this.constants.labels["deleteError"])
  11091. }
  11092. }
  11093. else {
  11094. this.edgesData.remove(selectedEdges);
  11095. this.nodesData.remove(selectedNodes);
  11096. this._unselectAll();
  11097. this.moving = true;
  11098. this.start();
  11099. }
  11100. }
  11101. else {
  11102. alert(this.constants.labels["deleteClusterError"]);
  11103. }
  11104. }
  11105. }
  11106. };
  11107. /**
  11108. * Creation of the SectorMixin var.
  11109. *
  11110. * This contains all the functions the Graph object can use to employ the sector system.
  11111. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11112. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11113. *
  11114. * Alex de Mulder
  11115. * 21-01-2013
  11116. */
  11117. var SectorMixin = {
  11118. /**
  11119. * This function is only called by the setData function of the Graph object.
  11120. * This loads the global references into the active sector. This initializes the sector.
  11121. *
  11122. * @private
  11123. */
  11124. _putDataInSector : function() {
  11125. this.sectors["active"][this._sector()].nodes = this.nodes;
  11126. this.sectors["active"][this._sector()].edges = this.edges;
  11127. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11128. },
  11129. /**
  11130. * /**
  11131. * This function sets the global references to nodes, edges and nodeIndices back to
  11132. * those of the supplied (active) sector. If a type is defined, do the specific type
  11133. *
  11134. * @param {String} sectorId
  11135. * @param {String} [sectorType] | "active" or "frozen"
  11136. * @private
  11137. */
  11138. _switchToSector : function(sectorId, sectorType) {
  11139. if (sectorType === undefined || sectorType == "active") {
  11140. this._switchToActiveSector(sectorId);
  11141. }
  11142. else {
  11143. this._switchToFrozenSector(sectorId);
  11144. }
  11145. },
  11146. /**
  11147. * This function sets the global references to nodes, edges and nodeIndices back to
  11148. * those of the supplied active sector.
  11149. *
  11150. * @param sectorId
  11151. * @private
  11152. */
  11153. _switchToActiveSector : function(sectorId) {
  11154. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11155. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11156. this.edges = this.sectors["active"][sectorId]["edges"];
  11157. },
  11158. /**
  11159. * This function sets the global references to nodes, edges and nodeIndices back to
  11160. * those of the supplied active sector.
  11161. *
  11162. * @param sectorId
  11163. * @private
  11164. */
  11165. _switchToSupportSector : function() {
  11166. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11167. this.nodes = this.sectors["support"]["nodes"];
  11168. this.edges = this.sectors["support"]["edges"];
  11169. },
  11170. /**
  11171. * This function sets the global references to nodes, edges and nodeIndices back to
  11172. * those of the supplied frozen sector.
  11173. *
  11174. * @param sectorId
  11175. * @private
  11176. */
  11177. _switchToFrozenSector : function(sectorId) {
  11178. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11179. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11180. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11181. },
  11182. /**
  11183. * This function sets the global references to nodes, edges and nodeIndices back to
  11184. * those of the currently active sector.
  11185. *
  11186. * @private
  11187. */
  11188. _loadLatestSector : function() {
  11189. this._switchToSector(this._sector());
  11190. },
  11191. /**
  11192. * This function returns the currently active sector Id
  11193. *
  11194. * @returns {String}
  11195. * @private
  11196. */
  11197. _sector : function() {
  11198. return this.activeSector[this.activeSector.length-1];
  11199. },
  11200. /**
  11201. * This function returns the previously active sector Id
  11202. *
  11203. * @returns {String}
  11204. * @private
  11205. */
  11206. _previousSector : function() {
  11207. if (this.activeSector.length > 1) {
  11208. return this.activeSector[this.activeSector.length-2];
  11209. }
  11210. else {
  11211. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11212. }
  11213. },
  11214. /**
  11215. * We add the active sector at the end of the this.activeSector array
  11216. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11217. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11218. *
  11219. * @param newId
  11220. * @private
  11221. */
  11222. _setActiveSector : function(newId) {
  11223. this.activeSector.push(newId);
  11224. },
  11225. /**
  11226. * We remove the currently active sector id from the active sector stack. This happens when
  11227. * we reactivate the previously active sector
  11228. *
  11229. * @private
  11230. */
  11231. _forgetLastSector : function() {
  11232. this.activeSector.pop();
  11233. },
  11234. /**
  11235. * This function creates a new active sector with the supplied newId. This newId
  11236. * is the expanding node id.
  11237. *
  11238. * @param {String} newId | Id of the new active sector
  11239. * @private
  11240. */
  11241. _createNewSector : function(newId) {
  11242. // create the new sector
  11243. this.sectors["active"][newId] = {"nodes":{},
  11244. "edges":{},
  11245. "nodeIndices":[],
  11246. "formationScale": this.scale,
  11247. "drawingNode": undefined};
  11248. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11249. this.sectors["active"][newId]['drawingNode'] = new Node(
  11250. {id:newId,
  11251. color: {
  11252. background: "#eaefef",
  11253. border: "495c5e"
  11254. }
  11255. },{},{},this.constants);
  11256. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11257. },
  11258. /**
  11259. * This function removes the currently active sector. This is called when we create a new
  11260. * active sector.
  11261. *
  11262. * @param {String} sectorId | Id of the active sector that will be removed
  11263. * @private
  11264. */
  11265. _deleteActiveSector : function(sectorId) {
  11266. delete this.sectors["active"][sectorId];
  11267. },
  11268. /**
  11269. * This function removes the currently active sector. This is called when we reactivate
  11270. * the previously active sector.
  11271. *
  11272. * @param {String} sectorId | Id of the active sector that will be removed
  11273. * @private
  11274. */
  11275. _deleteFrozenSector : function(sectorId) {
  11276. delete this.sectors["frozen"][sectorId];
  11277. },
  11278. /**
  11279. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11280. * We copy the references, then delete the active entree.
  11281. *
  11282. * @param sectorId
  11283. * @private
  11284. */
  11285. _freezeSector : function(sectorId) {
  11286. // we move the set references from the active to the frozen stack.
  11287. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11288. // we have moved the sector data into the frozen set, we now remove it from the active set
  11289. this._deleteActiveSector(sectorId);
  11290. },
  11291. /**
  11292. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11293. * object to the "active" object.
  11294. *
  11295. * @param sectorId
  11296. * @private
  11297. */
  11298. _activateSector : function(sectorId) {
  11299. // we move the set references from the frozen to the active stack.
  11300. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11301. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11302. this._deleteFrozenSector(sectorId);
  11303. },
  11304. /**
  11305. * This function merges the data from the currently active sector with a frozen sector. This is used
  11306. * in the process of reverting back to the previously active sector.
  11307. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11308. * upon the creation of a new active sector.
  11309. *
  11310. * @param sectorId
  11311. * @private
  11312. */
  11313. _mergeThisWithFrozen : function(sectorId) {
  11314. // copy all nodes
  11315. for (var nodeId in this.nodes) {
  11316. if (this.nodes.hasOwnProperty(nodeId)) {
  11317. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11318. }
  11319. }
  11320. // copy all edges (if not fully clustered, else there are no edges)
  11321. for (var edgeId in this.edges) {
  11322. if (this.edges.hasOwnProperty(edgeId)) {
  11323. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11324. }
  11325. }
  11326. // merge the nodeIndices
  11327. for (var i = 0; i < this.nodeIndices.length; i++) {
  11328. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11329. }
  11330. },
  11331. /**
  11332. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11333. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11334. *
  11335. * @private
  11336. */
  11337. _collapseThisToSingleCluster : function() {
  11338. this.clusterToFit(1,false);
  11339. },
  11340. /**
  11341. * We create a new active sector from the node that we want to open.
  11342. *
  11343. * @param node
  11344. * @private
  11345. */
  11346. _addSector : function(node) {
  11347. // this is the currently active sector
  11348. var sector = this._sector();
  11349. // // this should allow me to select nodes from a frozen set.
  11350. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11351. // console.log("the node is part of the active sector");
  11352. // }
  11353. // else {
  11354. // console.log("I dont know what the fuck happened!!");
  11355. // }
  11356. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11357. delete this.nodes[node.id];
  11358. var unqiueIdentifier = util.randomUUID();
  11359. // we fully freeze the currently active sector
  11360. this._freezeSector(sector);
  11361. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11362. this._createNewSector(unqiueIdentifier);
  11363. // we add the active sector to the sectors array to be able to revert these steps later on
  11364. this._setActiveSector(unqiueIdentifier);
  11365. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11366. this._switchToSector(this._sector());
  11367. // finally we add the node we removed from our previous active sector to the new active sector
  11368. this.nodes[node.id] = node;
  11369. },
  11370. /**
  11371. * We close the sector that is currently open and revert back to the one before.
  11372. * If the active sector is the "default" sector, nothing happens.
  11373. *
  11374. * @private
  11375. */
  11376. _collapseSector : function() {
  11377. // the currently active sector
  11378. var sector = this._sector();
  11379. // we cannot collapse the default sector
  11380. if (sector != "default") {
  11381. if ((this.nodeIndices.length == 1) ||
  11382. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11383. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11384. var previousSector = this._previousSector();
  11385. // we collapse the sector back to a single cluster
  11386. this._collapseThisToSingleCluster();
  11387. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  11388. // This previous sector is the one we will reactivate
  11389. this._mergeThisWithFrozen(previousSector);
  11390. // the previously active (frozen) sector now has all the data from the currently active sector.
  11391. // we can now delete the active sector.
  11392. this._deleteActiveSector(sector);
  11393. // we activate the previously active (and currently frozen) sector.
  11394. this._activateSector(previousSector);
  11395. // we load the references from the newly active sector into the global references
  11396. this._switchToSector(previousSector);
  11397. // we forget the previously active sector because we reverted to the one before
  11398. this._forgetLastSector();
  11399. // finally, we update the node index list.
  11400. this._updateNodeIndexList();
  11401. // we refresh the list with calulation nodes and calculation node indices.
  11402. this._updateCalculationNodes();
  11403. }
  11404. }
  11405. },
  11406. /**
  11407. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11408. *
  11409. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11410. * | we dont pass the function itself because then the "this" is the window object
  11411. * | instead of the Graph object
  11412. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11413. * @private
  11414. */
  11415. _doInAllActiveSectors : function(runFunction,argument) {
  11416. if (argument === undefined) {
  11417. for (var sector in this.sectors["active"]) {
  11418. if (this.sectors["active"].hasOwnProperty(sector)) {
  11419. // switch the global references to those of this sector
  11420. this._switchToActiveSector(sector);
  11421. this[runFunction]();
  11422. }
  11423. }
  11424. }
  11425. else {
  11426. for (var sector in this.sectors["active"]) {
  11427. if (this.sectors["active"].hasOwnProperty(sector)) {
  11428. // switch the global references to those of this sector
  11429. this._switchToActiveSector(sector);
  11430. var args = Array.prototype.splice.call(arguments, 1);
  11431. if (args.length > 1) {
  11432. this[runFunction](args[0],args[1]);
  11433. }
  11434. else {
  11435. this[runFunction](argument);
  11436. }
  11437. }
  11438. }
  11439. }
  11440. // we revert the global references back to our active sector
  11441. this._loadLatestSector();
  11442. },
  11443. /**
  11444. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11445. *
  11446. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11447. * | we dont pass the function itself because then the "this" is the window object
  11448. * | instead of the Graph object
  11449. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11450. * @private
  11451. */
  11452. _doInSupportSector : function(runFunction,argument) {
  11453. if (argument === undefined) {
  11454. this._switchToSupportSector();
  11455. this[runFunction]();
  11456. }
  11457. else {
  11458. this._switchToSupportSector();
  11459. var args = Array.prototype.splice.call(arguments, 1);
  11460. if (args.length > 1) {
  11461. this[runFunction](args[0],args[1]);
  11462. }
  11463. else {
  11464. this[runFunction](argument);
  11465. }
  11466. }
  11467. // we revert the global references back to our active sector
  11468. this._loadLatestSector();
  11469. },
  11470. /**
  11471. * This runs a function in all frozen sectors. This is used in the _redraw().
  11472. *
  11473. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11474. * | we don't pass the function itself because then the "this" is the window object
  11475. * | instead of the Graph object
  11476. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11477. * @private
  11478. */
  11479. _doInAllFrozenSectors : function(runFunction,argument) {
  11480. if (argument === undefined) {
  11481. for (var sector in this.sectors["frozen"]) {
  11482. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11483. // switch the global references to those of this sector
  11484. this._switchToFrozenSector(sector);
  11485. this[runFunction]();
  11486. }
  11487. }
  11488. }
  11489. else {
  11490. for (var sector in this.sectors["frozen"]) {
  11491. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11492. // switch the global references to those of this sector
  11493. this._switchToFrozenSector(sector);
  11494. var args = Array.prototype.splice.call(arguments, 1);
  11495. if (args.length > 1) {
  11496. this[runFunction](args[0],args[1]);
  11497. }
  11498. else {
  11499. this[runFunction](argument);
  11500. }
  11501. }
  11502. }
  11503. }
  11504. this._loadLatestSector();
  11505. },
  11506. /**
  11507. * This runs a function in all sectors. This is used in the _redraw().
  11508. *
  11509. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11510. * | we don't pass the function itself because then the "this" is the window object
  11511. * | instead of the Graph object
  11512. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11513. * @private
  11514. */
  11515. _doInAllSectors : function(runFunction,argument) {
  11516. var args = Array.prototype.splice.call(arguments, 1);
  11517. if (argument === undefined) {
  11518. this._doInAllActiveSectors(runFunction);
  11519. this._doInAllFrozenSectors(runFunction);
  11520. }
  11521. else {
  11522. if (args.length > 1) {
  11523. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  11524. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  11525. }
  11526. else {
  11527. this._doInAllActiveSectors(runFunction,argument);
  11528. this._doInAllFrozenSectors(runFunction,argument);
  11529. }
  11530. }
  11531. },
  11532. /**
  11533. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  11534. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  11535. *
  11536. * @private
  11537. */
  11538. _clearNodeIndexList : function() {
  11539. var sector = this._sector();
  11540. this.sectors["active"][sector]["nodeIndices"] = [];
  11541. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  11542. },
  11543. /**
  11544. * Draw the encompassing sector node
  11545. *
  11546. * @param ctx
  11547. * @param sectorType
  11548. * @private
  11549. */
  11550. _drawSectorNodes : function(ctx,sectorType) {
  11551. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11552. for (var sector in this.sectors[sectorType]) {
  11553. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  11554. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  11555. this._switchToSector(sector,sectorType);
  11556. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  11557. for (var nodeId in this.nodes) {
  11558. if (this.nodes.hasOwnProperty(nodeId)) {
  11559. node = this.nodes[nodeId];
  11560. node.resize(ctx);
  11561. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  11562. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  11563. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  11564. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  11565. }
  11566. }
  11567. node = this.sectors[sectorType][sector]["drawingNode"];
  11568. node.x = 0.5 * (maxX + minX);
  11569. node.y = 0.5 * (maxY + minY);
  11570. node.width = 2 * (node.x - minX);
  11571. node.height = 2 * (node.y - minY);
  11572. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  11573. node.setScale(this.scale);
  11574. node._drawCircle(ctx);
  11575. }
  11576. }
  11577. }
  11578. },
  11579. _drawAllSectorNodes : function(ctx) {
  11580. this._drawSectorNodes(ctx,"frozen");
  11581. this._drawSectorNodes(ctx,"active");
  11582. this._loadLatestSector();
  11583. }
  11584. };
  11585. /**
  11586. * Creation of the ClusterMixin var.
  11587. *
  11588. * This contains all the functions the Graph object can use to employ clustering
  11589. *
  11590. * Alex de Mulder
  11591. * 21-01-2013
  11592. */
  11593. var ClusterMixin = {
  11594. /**
  11595. * This is only called in the constructor of the graph object
  11596. *
  11597. */
  11598. startWithClustering : function() {
  11599. // cluster if the data set is big
  11600. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  11601. // updates the lables after clustering
  11602. this.updateLabels();
  11603. // this is called here because if clusterin is disabled, the start and stabilize are called in
  11604. // the setData function.
  11605. if (this.stabilize) {
  11606. this._stabilize();
  11607. }
  11608. this.start();
  11609. },
  11610. /**
  11611. * This function clusters until the initialMaxNodes has been reached
  11612. *
  11613. * @param {Number} maxNumberOfNodes
  11614. * @param {Boolean} reposition
  11615. */
  11616. clusterToFit : function(maxNumberOfNodes, reposition) {
  11617. var numberOfNodes = this.nodeIndices.length;
  11618. var maxLevels = 50;
  11619. var level = 0;
  11620. // we first cluster the hubs, then we pull in the outliers, repeat
  11621. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  11622. if (level % 3 == 0) {
  11623. this.forceAggregateHubs(true);
  11624. this.normalizeClusterLevels();
  11625. }
  11626. else {
  11627. this.increaseClusterLevel(); // this also includes a cluster normalization
  11628. }
  11629. numberOfNodes = this.nodeIndices.length;
  11630. level += 1;
  11631. }
  11632. // after the clustering we reposition the nodes to reduce the initial chaos
  11633. if (level > 0 && reposition == true) {
  11634. this.repositionNodes();
  11635. }
  11636. this._updateCalculationNodes();
  11637. },
  11638. /**
  11639. * This function can be called to open up a specific cluster. It is only called by
  11640. * It will unpack the cluster back one level.
  11641. *
  11642. * @param node | Node object: cluster to open.
  11643. */
  11644. openCluster : function(node) {
  11645. var isMovingBeforeClustering = this.moving;
  11646. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  11647. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  11648. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  11649. this._addSector(node);
  11650. var level = 0;
  11651. // we decluster until we reach a decent number of nodes
  11652. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  11653. this.decreaseClusterLevel();
  11654. level += 1;
  11655. }
  11656. }
  11657. else {
  11658. this._expandClusterNode(node,false,true);
  11659. // update the index list, dynamic edges and labels
  11660. this._updateNodeIndexList();
  11661. this._updateDynamicEdges();
  11662. this._updateCalculationNodes();
  11663. this.updateLabels();
  11664. }
  11665. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11666. if (this.moving != isMovingBeforeClustering) {
  11667. this.start();
  11668. }
  11669. },
  11670. /**
  11671. * This calls the updateClustes with default arguments
  11672. */
  11673. updateClustersDefault : function() {
  11674. if (this.constants.clustering.enabled == true) {
  11675. this.updateClusters(0,false,false);
  11676. }
  11677. },
  11678. /**
  11679. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  11680. * be clustered with their connected node. This can be repeated as many times as needed.
  11681. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  11682. */
  11683. increaseClusterLevel : function() {
  11684. this.updateClusters(-1,false,true);
  11685. },
  11686. /**
  11687. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  11688. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  11689. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  11690. */
  11691. decreaseClusterLevel : function() {
  11692. this.updateClusters(1,false,true);
  11693. },
  11694. /**
  11695. * This is the main clustering function. It clusters and declusters on zoom or forced
  11696. * This function clusters on zoom, it can be called with a predefined zoom direction
  11697. * If out, check if we can form clusters, if in, check if we can open clusters.
  11698. * This function is only called from _zoom()
  11699. *
  11700. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  11701. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  11702. * @param {Boolean} force | enabled or disable forcing
  11703. *
  11704. */
  11705. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  11706. var isMovingBeforeClustering = this.moving;
  11707. var amountOfNodes = this.nodeIndices.length;
  11708. // on zoom out collapse the sector if the scale is at the level the sector was made
  11709. if (this.previousScale > this.scale && zoomDirection == 0) {
  11710. this._collapseSector();
  11711. }
  11712. // check if we zoom in or out
  11713. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  11714. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  11715. // outer nodes determines if it is being clustered
  11716. this._formClusters(force);
  11717. }
  11718. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  11719. if (force == true) {
  11720. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  11721. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  11722. this._openClusters(recursive,force);
  11723. }
  11724. else {
  11725. // if a cluster takes up a set percentage of the active window
  11726. this._openClustersBySize();
  11727. }
  11728. }
  11729. this._updateNodeIndexList();
  11730. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  11731. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  11732. this._aggregateHubs(force);
  11733. this._updateNodeIndexList();
  11734. }
  11735. // we now reduce chains.
  11736. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  11737. this.handleChains();
  11738. this._updateNodeIndexList();
  11739. }
  11740. this.previousScale = this.scale;
  11741. // rest of the update the index list, dynamic edges and labels
  11742. this._updateDynamicEdges();
  11743. this.updateLabels();
  11744. // if a cluster was formed, we increase the clusterSession
  11745. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  11746. this.clusterSession += 1;
  11747. // if clusters have been made, we normalize the cluster level
  11748. this.normalizeClusterLevels();
  11749. }
  11750. if (doNotStart == false || doNotStart === undefined) {
  11751. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11752. if (this.moving != isMovingBeforeClustering) {
  11753. this.start();
  11754. }
  11755. }
  11756. this._updateCalculationNodes();
  11757. },
  11758. /**
  11759. * This function handles the chains. It is called on every updateClusters().
  11760. */
  11761. handleChains : function() {
  11762. // after clustering we check how many chains there are
  11763. var chainPercentage = this._getChainFraction();
  11764. if (chainPercentage > this.constants.clustering.chainThreshold) {
  11765. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  11766. }
  11767. },
  11768. /**
  11769. * this functions starts clustering by hubs
  11770. * The minimum hub threshold is set globally
  11771. *
  11772. * @private
  11773. */
  11774. _aggregateHubs : function(force) {
  11775. this._getHubSize();
  11776. this._formClustersByHub(force,false);
  11777. },
  11778. /**
  11779. * This function is fired by keypress. It forces hubs to form.
  11780. *
  11781. */
  11782. forceAggregateHubs : function(doNotStart) {
  11783. var isMovingBeforeClustering = this.moving;
  11784. var amountOfNodes = this.nodeIndices.length;
  11785. this._aggregateHubs(true);
  11786. // update the index list, dynamic edges and labels
  11787. this._updateNodeIndexList();
  11788. this._updateDynamicEdges();
  11789. this.updateLabels();
  11790. // if a cluster was formed, we increase the clusterSession
  11791. if (this.nodeIndices.length != amountOfNodes) {
  11792. this.clusterSession += 1;
  11793. }
  11794. if (doNotStart == false || doNotStart === undefined) {
  11795. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11796. if (this.moving != isMovingBeforeClustering) {
  11797. this.start();
  11798. }
  11799. }
  11800. },
  11801. /**
  11802. * If a cluster takes up more than a set percentage of the screen, open the cluster
  11803. *
  11804. * @private
  11805. */
  11806. _openClustersBySize : function() {
  11807. for (var nodeId in this.nodes) {
  11808. if (this.nodes.hasOwnProperty(nodeId)) {
  11809. var node = this.nodes[nodeId];
  11810. if (node.inView() == true) {
  11811. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11812. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11813. this.openCluster(node);
  11814. }
  11815. }
  11816. }
  11817. }
  11818. },
  11819. /**
  11820. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  11821. * has to be opened based on the current zoom level.
  11822. *
  11823. * @private
  11824. */
  11825. _openClusters : function(recursive,force) {
  11826. for (var i = 0; i < this.nodeIndices.length; i++) {
  11827. var node = this.nodes[this.nodeIndices[i]];
  11828. this._expandClusterNode(node,recursive,force);
  11829. this._updateCalculationNodes();
  11830. }
  11831. },
  11832. /**
  11833. * This function checks if a node has to be opened. This is done by checking the zoom level.
  11834. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  11835. * This recursive behaviour is optional and can be set by the recursive argument.
  11836. *
  11837. * @param {Node} parentNode | to check for cluster and expand
  11838. * @param {Boolean} recursive | enabled or disable recursive calling
  11839. * @param {Boolean} force | enabled or disable forcing
  11840. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  11841. * @private
  11842. */
  11843. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  11844. // first check if node is a cluster
  11845. if (parentNode.clusterSize > 1) {
  11846. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  11847. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  11848. openAll = true;
  11849. }
  11850. recursive = openAll ? true : recursive;
  11851. // if the last child has been added on a smaller scale than current scale decluster
  11852. if (parentNode.formationScale < this.scale || force == true) {
  11853. // we will check if any of the contained child nodes should be removed from the cluster
  11854. for (var containedNodeId in parentNode.containedNodes) {
  11855. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  11856. var childNode = parentNode.containedNodes[containedNodeId];
  11857. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  11858. // the largest cluster is the one that comes from outside
  11859. if (force == true) {
  11860. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  11861. || openAll) {
  11862. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  11863. }
  11864. }
  11865. else {
  11866. if (this._nodeInActiveArea(parentNode)) {
  11867. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  11868. }
  11869. }
  11870. }
  11871. }
  11872. }
  11873. }
  11874. },
  11875. /**
  11876. * ONLY CALLED FROM _expandClusterNode
  11877. *
  11878. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  11879. * the child node from the parent contained_node object and put it back into the global nodes object.
  11880. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  11881. *
  11882. * @param {Node} parentNode | the parent node
  11883. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  11884. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  11885. * With force and recursive both true, the entire cluster is unpacked
  11886. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  11887. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  11888. * @private
  11889. */
  11890. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  11891. var childNode = parentNode.containedNodes[containedNodeId];
  11892. // if child node has been added on smaller scale than current, kick out
  11893. if (childNode.formationScale < this.scale || force == true) {
  11894. // unselect all selected items
  11895. this._unselectAll();
  11896. // put the child node back in the global nodes object
  11897. this.nodes[containedNodeId] = childNode;
  11898. // release the contained edges from this childNode back into the global edges
  11899. this._releaseContainedEdges(parentNode,childNode);
  11900. // reconnect rerouted edges to the childNode
  11901. this._connectEdgeBackToChild(parentNode,childNode);
  11902. // validate all edges in dynamicEdges
  11903. this._validateEdges(parentNode);
  11904. // undo the changes from the clustering operation on the parent node
  11905. parentNode.mass -= childNode.mass;
  11906. parentNode.clusterSize -= childNode.clusterSize;
  11907. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  11908. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  11909. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  11910. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  11911. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  11912. // remove node from the list
  11913. delete parentNode.containedNodes[containedNodeId];
  11914. // check if there are other childs with this clusterSession in the parent.
  11915. var othersPresent = false;
  11916. for (var childNodeId in parentNode.containedNodes) {
  11917. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  11918. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  11919. othersPresent = true;
  11920. break;
  11921. }
  11922. }
  11923. }
  11924. // if there are no others, remove the cluster session from the list
  11925. if (othersPresent == false) {
  11926. parentNode.clusterSessions.pop();
  11927. }
  11928. this._repositionBezierNodes(childNode);
  11929. // this._repositionBezierNodes(parentNode);
  11930. // remove the clusterSession from the child node
  11931. childNode.clusterSession = 0;
  11932. // recalculate the size of the node on the next time the node is rendered
  11933. parentNode.clearSizeCache();
  11934. // restart the simulation to reorganise all nodes
  11935. this.moving = true;
  11936. }
  11937. // check if a further expansion step is possible if recursivity is enabled
  11938. if (recursive == true) {
  11939. this._expandClusterNode(childNode,recursive,force,openAll);
  11940. }
  11941. },
  11942. /**
  11943. * position the bezier nodes at the center of the edges
  11944. *
  11945. * @param node
  11946. * @private
  11947. */
  11948. _repositionBezierNodes : function(node) {
  11949. for (var i = 0; i < node.dynamicEdges.length; i++) {
  11950. node.dynamicEdges[i].positionBezierNode();
  11951. }
  11952. },
  11953. /**
  11954. * This function checks if any nodes at the end of their trees have edges below a threshold length
  11955. * This function is called only from updateClusters()
  11956. * forceLevelCollapse ignores the length of the edge and collapses one level
  11957. * This means that a node with only one edge will be clustered with its connected node
  11958. *
  11959. * @private
  11960. * @param {Boolean} force
  11961. */
  11962. _formClusters : function(force) {
  11963. if (force == false) {
  11964. this._formClustersByZoom();
  11965. }
  11966. else {
  11967. this._forceClustersByZoom();
  11968. }
  11969. },
  11970. /**
  11971. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  11972. *
  11973. * @private
  11974. */
  11975. _formClustersByZoom : function() {
  11976. var dx,dy,length,
  11977. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  11978. // check if any edges are shorter than minLength and start the clustering
  11979. // the clustering favours the node with the larger mass
  11980. for (var edgeId in this.edges) {
  11981. if (this.edges.hasOwnProperty(edgeId)) {
  11982. var edge = this.edges[edgeId];
  11983. if (edge.connected) {
  11984. if (edge.toId != edge.fromId) {
  11985. dx = (edge.to.x - edge.from.x);
  11986. dy = (edge.to.y - edge.from.y);
  11987. length = Math.sqrt(dx * dx + dy * dy);
  11988. if (length < minLength) {
  11989. // first check which node is larger
  11990. var parentNode = edge.from;
  11991. var childNode = edge.to;
  11992. if (edge.to.mass > edge.from.mass) {
  11993. parentNode = edge.to;
  11994. childNode = edge.from;
  11995. }
  11996. if (childNode.dynamicEdgesLength == 1) {
  11997. this._addToCluster(parentNode,childNode,false);
  11998. }
  11999. else if (parentNode.dynamicEdgesLength == 1) {
  12000. this._addToCluster(childNode,parentNode,false);
  12001. }
  12002. }
  12003. }
  12004. }
  12005. }
  12006. }
  12007. },
  12008. /**
  12009. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12010. * connected node.
  12011. *
  12012. * @private
  12013. */
  12014. _forceClustersByZoom : function() {
  12015. for (var nodeId in this.nodes) {
  12016. // another node could have absorbed this child.
  12017. if (this.nodes.hasOwnProperty(nodeId)) {
  12018. var childNode = this.nodes[nodeId];
  12019. // the edges can be swallowed by another decrease
  12020. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12021. var edge = childNode.dynamicEdges[0];
  12022. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12023. // group to the largest node
  12024. if (childNode.id != parentNode.id) {
  12025. if (parentNode.mass > childNode.mass) {
  12026. this._addToCluster(parentNode,childNode,true);
  12027. }
  12028. else {
  12029. this._addToCluster(childNode,parentNode,true);
  12030. }
  12031. }
  12032. }
  12033. }
  12034. }
  12035. },
  12036. /**
  12037. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12038. * This function clusters a node to its smallest connected neighbour.
  12039. *
  12040. * @param node
  12041. * @private
  12042. */
  12043. _clusterToSmallestNeighbour : function(node) {
  12044. var smallestNeighbour = -1;
  12045. var smallestNeighbourNode = null;
  12046. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12047. if (node.dynamicEdges[i] !== undefined) {
  12048. var neighbour = null;
  12049. if (node.dynamicEdges[i].fromId != node.id) {
  12050. neighbour = node.dynamicEdges[i].from;
  12051. }
  12052. else if (node.dynamicEdges[i].toId != node.id) {
  12053. neighbour = node.dynamicEdges[i].to;
  12054. }
  12055. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12056. smallestNeighbour = neighbour.clusterSessions.length;
  12057. smallestNeighbourNode = neighbour;
  12058. }
  12059. }
  12060. }
  12061. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12062. this._addToCluster(neighbour, node, true);
  12063. }
  12064. },
  12065. /**
  12066. * This function forms clusters from hubs, it loops over all nodes
  12067. *
  12068. * @param {Boolean} force | Disregard zoom level
  12069. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12070. * @private
  12071. */
  12072. _formClustersByHub : function(force, onlyEqual) {
  12073. // we loop over all nodes in the list
  12074. for (var nodeId in this.nodes) {
  12075. // we check if it is still available since it can be used by the clustering in this loop
  12076. if (this.nodes.hasOwnProperty(nodeId)) {
  12077. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12078. }
  12079. }
  12080. },
  12081. /**
  12082. * This function forms a cluster from a specific preselected hub node
  12083. *
  12084. * @param {Node} hubNode | the node we will cluster as a hub
  12085. * @param {Boolean} force | Disregard zoom level
  12086. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12087. * @param {Number} [absorptionSizeOffset] |
  12088. * @private
  12089. */
  12090. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12091. if (absorptionSizeOffset === undefined) {
  12092. absorptionSizeOffset = 0;
  12093. }
  12094. // we decide if the node is a hub
  12095. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12096. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12097. // initialize variables
  12098. var dx,dy,length;
  12099. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12100. var allowCluster = false;
  12101. // we create a list of edges because the dynamicEdges change over the course of this loop
  12102. var edgesIdarray = [];
  12103. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12104. for (var j = 0; j < amountOfInitialEdges; j++) {
  12105. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12106. }
  12107. // if the hub clustering is not forces, we check if one of the edges connected
  12108. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12109. if (force == false) {
  12110. allowCluster = false;
  12111. for (j = 0; j < amountOfInitialEdges; j++) {
  12112. var edge = this.edges[edgesIdarray[j]];
  12113. if (edge !== undefined) {
  12114. if (edge.connected) {
  12115. if (edge.toId != edge.fromId) {
  12116. dx = (edge.to.x - edge.from.x);
  12117. dy = (edge.to.y - edge.from.y);
  12118. length = Math.sqrt(dx * dx + dy * dy);
  12119. if (length < minLength) {
  12120. allowCluster = true;
  12121. break;
  12122. }
  12123. }
  12124. }
  12125. }
  12126. }
  12127. }
  12128. // start the clustering if allowed
  12129. if ((!force && allowCluster) || force) {
  12130. // we loop over all edges INITIALLY connected to this hub
  12131. for (j = 0; j < amountOfInitialEdges; j++) {
  12132. edge = this.edges[edgesIdarray[j]];
  12133. // the edge can be clustered by this function in a previous loop
  12134. if (edge !== undefined) {
  12135. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12136. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12137. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12138. (childNode.id != hubNode.id)) {
  12139. this._addToCluster(hubNode,childNode,force);
  12140. }
  12141. }
  12142. }
  12143. }
  12144. }
  12145. },
  12146. /**
  12147. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12148. *
  12149. * @param {Node} parentNode | this is the node that will house the child node
  12150. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12151. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12152. * @private
  12153. */
  12154. _addToCluster : function(parentNode, childNode, force) {
  12155. // join child node in the parent node
  12156. parentNode.containedNodes[childNode.id] = childNode;
  12157. // manage all the edges connected to the child and parent nodes
  12158. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12159. var edge = childNode.dynamicEdges[i];
  12160. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12161. this._addToContainedEdges(parentNode,childNode,edge);
  12162. }
  12163. else {
  12164. this._connectEdgeToCluster(parentNode,childNode,edge);
  12165. }
  12166. }
  12167. // a contained node has no dynamic edges.
  12168. childNode.dynamicEdges = [];
  12169. // remove circular edges from clusters
  12170. this._containCircularEdgesFromNode(parentNode,childNode);
  12171. // remove the childNode from the global nodes object
  12172. delete this.nodes[childNode.id];
  12173. // update the properties of the child and parent
  12174. var massBefore = parentNode.mass;
  12175. childNode.clusterSession = this.clusterSession;
  12176. parentNode.mass += childNode.mass;
  12177. parentNode.clusterSize += childNode.clusterSize;
  12178. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12179. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12180. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12181. parentNode.clusterSessions.push(this.clusterSession);
  12182. }
  12183. // forced clusters only open from screen size and double tap
  12184. if (force == true) {
  12185. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12186. parentNode.formationScale = 0;
  12187. }
  12188. else {
  12189. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12190. }
  12191. // recalculate the size of the node on the next time the node is rendered
  12192. parentNode.clearSizeCache();
  12193. // set the pop-out scale for the childnode
  12194. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12195. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12196. childNode.clearVelocity();
  12197. // the mass has altered, preservation of energy dictates the velocity to be updated
  12198. parentNode.updateVelocity(massBefore);
  12199. // restart the simulation to reorganise all nodes
  12200. this.moving = true;
  12201. },
  12202. /**
  12203. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12204. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12205. * It has to be called if a level is collapsed. It is called by _formClusters().
  12206. * @private
  12207. */
  12208. _updateDynamicEdges : function() {
  12209. for (var i = 0; i < this.nodeIndices.length; i++) {
  12210. var node = this.nodes[this.nodeIndices[i]];
  12211. node.dynamicEdgesLength = node.dynamicEdges.length;
  12212. // this corrects for multiple edges pointing at the same other node
  12213. var correction = 0;
  12214. if (node.dynamicEdgesLength > 1) {
  12215. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12216. var edgeToId = node.dynamicEdges[j].toId;
  12217. var edgeFromId = node.dynamicEdges[j].fromId;
  12218. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12219. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12220. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12221. correction += 1;
  12222. }
  12223. }
  12224. }
  12225. }
  12226. node.dynamicEdgesLength -= correction;
  12227. }
  12228. },
  12229. /**
  12230. * This adds an edge from the childNode to the contained edges of the parent node
  12231. *
  12232. * @param parentNode | Node object
  12233. * @param childNode | Node object
  12234. * @param edge | Edge object
  12235. * @private
  12236. */
  12237. _addToContainedEdges : function(parentNode, childNode, edge) {
  12238. // create an array object if it does not yet exist for this childNode
  12239. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12240. parentNode.containedEdges[childNode.id] = []
  12241. }
  12242. // add this edge to the list
  12243. parentNode.containedEdges[childNode.id].push(edge);
  12244. // remove the edge from the global edges object
  12245. delete this.edges[edge.id];
  12246. // remove the edge from the parent object
  12247. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12248. if (parentNode.dynamicEdges[i].id == edge.id) {
  12249. parentNode.dynamicEdges.splice(i,1);
  12250. break;
  12251. }
  12252. }
  12253. },
  12254. /**
  12255. * This function connects an edge that was connected to a child node to the parent node.
  12256. * It keeps track of which nodes it has been connected to with the originalId array.
  12257. *
  12258. * @param {Node} parentNode | Node object
  12259. * @param {Node} childNode | Node object
  12260. * @param {Edge} edge | Edge object
  12261. * @private
  12262. */
  12263. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12264. // handle circular edges
  12265. if (edge.toId == edge.fromId) {
  12266. this._addToContainedEdges(parentNode, childNode, edge);
  12267. }
  12268. else {
  12269. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12270. edge.originalToId.push(childNode.id);
  12271. edge.to = parentNode;
  12272. edge.toId = parentNode.id;
  12273. }
  12274. else { // edge connected to other node with the "from" side
  12275. edge.originalFromId.push(childNode.id);
  12276. edge.from = parentNode;
  12277. edge.fromId = parentNode.id;
  12278. }
  12279. this._addToReroutedEdges(parentNode,childNode,edge);
  12280. }
  12281. },
  12282. /**
  12283. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12284. * these edges inside of the cluster.
  12285. *
  12286. * @param parentNode
  12287. * @param childNode
  12288. * @private
  12289. */
  12290. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12291. // manage all the edges connected to the child and parent nodes
  12292. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12293. var edge = parentNode.dynamicEdges[i];
  12294. // handle circular edges
  12295. if (edge.toId == edge.fromId) {
  12296. this._addToContainedEdges(parentNode, childNode, edge);
  12297. }
  12298. }
  12299. },
  12300. /**
  12301. * This adds an edge from the childNode to the rerouted edges of the parent node
  12302. *
  12303. * @param parentNode | Node object
  12304. * @param childNode | Node object
  12305. * @param edge | Edge object
  12306. * @private
  12307. */
  12308. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12309. // create an array object if it does not yet exist for this childNode
  12310. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12311. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12312. parentNode.reroutedEdges[childNode.id] = [];
  12313. }
  12314. parentNode.reroutedEdges[childNode.id].push(edge);
  12315. // this edge becomes part of the dynamicEdges of the cluster node
  12316. parentNode.dynamicEdges.push(edge);
  12317. },
  12318. /**
  12319. * This function connects an edge that was connected to a cluster node back to the child node.
  12320. *
  12321. * @param parentNode | Node object
  12322. * @param childNode | Node object
  12323. * @private
  12324. */
  12325. _connectEdgeBackToChild : function(parentNode, childNode) {
  12326. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12327. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12328. var edge = parentNode.reroutedEdges[childNode.id][i];
  12329. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12330. edge.originalFromId.pop();
  12331. edge.fromId = childNode.id;
  12332. edge.from = childNode;
  12333. }
  12334. else {
  12335. edge.originalToId.pop();
  12336. edge.toId = childNode.id;
  12337. edge.to = childNode;
  12338. }
  12339. // append this edge to the list of edges connecting to the childnode
  12340. childNode.dynamicEdges.push(edge);
  12341. // remove the edge from the parent object
  12342. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12343. if (parentNode.dynamicEdges[j].id == edge.id) {
  12344. parentNode.dynamicEdges.splice(j,1);
  12345. break;
  12346. }
  12347. }
  12348. }
  12349. // remove the entry from the rerouted edges
  12350. delete parentNode.reroutedEdges[childNode.id];
  12351. }
  12352. },
  12353. /**
  12354. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12355. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12356. * parentNode
  12357. *
  12358. * @param parentNode | Node object
  12359. * @private
  12360. */
  12361. _validateEdges : function(parentNode) {
  12362. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12363. var edge = parentNode.dynamicEdges[i];
  12364. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12365. parentNode.dynamicEdges.splice(i,1);
  12366. }
  12367. }
  12368. },
  12369. /**
  12370. * This function released the contained edges back into the global domain and puts them back into the
  12371. * dynamic edges of both parent and child.
  12372. *
  12373. * @param {Node} parentNode |
  12374. * @param {Node} childNode |
  12375. * @private
  12376. */
  12377. _releaseContainedEdges : function(parentNode, childNode) {
  12378. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12379. var edge = parentNode.containedEdges[childNode.id][i];
  12380. // put the edge back in the global edges object
  12381. this.edges[edge.id] = edge;
  12382. // put the edge back in the dynamic edges of the child and parent
  12383. childNode.dynamicEdges.push(edge);
  12384. parentNode.dynamicEdges.push(edge);
  12385. }
  12386. // remove the entry from the contained edges
  12387. delete parentNode.containedEdges[childNode.id];
  12388. },
  12389. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  12390. /**
  12391. * This updates the node labels for all nodes (for debugging purposes)
  12392. */
  12393. updateLabels : function() {
  12394. var nodeId;
  12395. // update node labels
  12396. for (nodeId in this.nodes) {
  12397. if (this.nodes.hasOwnProperty(nodeId)) {
  12398. var node = this.nodes[nodeId];
  12399. if (node.clusterSize > 1) {
  12400. node.label = "[".concat(String(node.clusterSize),"]");
  12401. }
  12402. }
  12403. }
  12404. // update node labels
  12405. for (nodeId in this.nodes) {
  12406. if (this.nodes.hasOwnProperty(nodeId)) {
  12407. node = this.nodes[nodeId];
  12408. if (node.clusterSize == 1) {
  12409. if (node.originalLabel !== undefined) {
  12410. node.label = node.originalLabel;
  12411. }
  12412. else {
  12413. node.label = String(node.id);
  12414. }
  12415. }
  12416. }
  12417. }
  12418. // /* Debug Override */
  12419. // for (nodeId in this.nodes) {
  12420. // if (this.nodes.hasOwnProperty(nodeId)) {
  12421. // node = this.nodes[nodeId];
  12422. // node.label = String(node.level);
  12423. // }
  12424. // }
  12425. },
  12426. /**
  12427. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  12428. * if the rest of the nodes are already a few cluster levels in.
  12429. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  12430. * clustered enough to the clusterToSmallestNeighbours function.
  12431. */
  12432. normalizeClusterLevels : function() {
  12433. var maxLevel = 0;
  12434. var minLevel = 1e9;
  12435. var clusterLevel = 0;
  12436. // we loop over all nodes in the list
  12437. for (var nodeId in this.nodes) {
  12438. if (this.nodes.hasOwnProperty(nodeId)) {
  12439. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  12440. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  12441. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  12442. }
  12443. }
  12444. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  12445. var amountOfNodes = this.nodeIndices.length;
  12446. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  12447. // we loop over all nodes in the list
  12448. for (var nodeId in this.nodes) {
  12449. if (this.nodes.hasOwnProperty(nodeId)) {
  12450. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  12451. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  12452. }
  12453. }
  12454. }
  12455. this._updateNodeIndexList();
  12456. this._updateDynamicEdges();
  12457. // if a cluster was formed, we increase the clusterSession
  12458. if (this.nodeIndices.length != amountOfNodes) {
  12459. this.clusterSession += 1;
  12460. }
  12461. }
  12462. },
  12463. /**
  12464. * This function determines if the cluster we want to decluster is in the active area
  12465. * this means around the zoom center
  12466. *
  12467. * @param {Node} node
  12468. * @returns {boolean}
  12469. * @private
  12470. */
  12471. _nodeInActiveArea : function(node) {
  12472. return (
  12473. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12474. &&
  12475. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12476. )
  12477. },
  12478. /**
  12479. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  12480. * It puts large clusters away from the center and randomizes the order.
  12481. *
  12482. */
  12483. repositionNodes : function() {
  12484. for (var i = 0; i < this.nodeIndices.length; i++) {
  12485. var node = this.nodes[this.nodeIndices[i]];
  12486. if ((node.xFixed == false || node.yFixed == false)) {
  12487. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.mass);
  12488. var angle = 2 * Math.PI * Math.random();
  12489. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  12490. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  12491. this._repositionBezierNodes(node);
  12492. }
  12493. }
  12494. },
  12495. /**
  12496. * We determine how many connections denote an important hub.
  12497. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  12498. *
  12499. * @private
  12500. */
  12501. _getHubSize : function() {
  12502. var average = 0;
  12503. var averageSquared = 0;
  12504. var hubCounter = 0;
  12505. var largestHub = 0;
  12506. for (var i = 0; i < this.nodeIndices.length; i++) {
  12507. var node = this.nodes[this.nodeIndices[i]];
  12508. if (node.dynamicEdgesLength > largestHub) {
  12509. largestHub = node.dynamicEdgesLength;
  12510. }
  12511. average += node.dynamicEdgesLength;
  12512. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  12513. hubCounter += 1;
  12514. }
  12515. average = average / hubCounter;
  12516. averageSquared = averageSquared / hubCounter;
  12517. var variance = averageSquared - Math.pow(average,2);
  12518. var standardDeviation = Math.sqrt(variance);
  12519. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  12520. // always have at least one to cluster
  12521. if (this.hubThreshold > largestHub) {
  12522. this.hubThreshold = largestHub;
  12523. }
  12524. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  12525. // console.log("hubThreshold:",this.hubThreshold);
  12526. },
  12527. /**
  12528. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12529. * with this amount we can cluster specifically on these chains.
  12530. *
  12531. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  12532. * @private
  12533. */
  12534. _reduceAmountOfChains : function(fraction) {
  12535. this.hubThreshold = 2;
  12536. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  12537. for (var nodeId in this.nodes) {
  12538. if (this.nodes.hasOwnProperty(nodeId)) {
  12539. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12540. if (reduceAmount > 0) {
  12541. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  12542. reduceAmount -= 1;
  12543. }
  12544. }
  12545. }
  12546. }
  12547. },
  12548. /**
  12549. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12550. * with this amount we can cluster specifically on these chains.
  12551. *
  12552. * @private
  12553. */
  12554. _getChainFraction : function() {
  12555. var chains = 0;
  12556. var total = 0;
  12557. for (var nodeId in this.nodes) {
  12558. if (this.nodes.hasOwnProperty(nodeId)) {
  12559. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12560. chains += 1;
  12561. }
  12562. total += 1;
  12563. }
  12564. }
  12565. return chains/total;
  12566. }
  12567. };
  12568. var SelectionMixin = {
  12569. /**
  12570. * This function can be called from the _doInAllSectors function
  12571. *
  12572. * @param object
  12573. * @param overlappingNodes
  12574. * @private
  12575. */
  12576. _getNodesOverlappingWith : function(object, overlappingNodes) {
  12577. var nodes = this.nodes;
  12578. for (var nodeId in nodes) {
  12579. if (nodes.hasOwnProperty(nodeId)) {
  12580. if (nodes[nodeId].isOverlappingWith(object)) {
  12581. overlappingNodes.push(nodeId);
  12582. }
  12583. }
  12584. }
  12585. },
  12586. /**
  12587. * retrieve all nodes overlapping with given object
  12588. * @param {Object} object An object with parameters left, top, right, bottom
  12589. * @return {Number[]} An array with id's of the overlapping nodes
  12590. * @private
  12591. */
  12592. _getAllNodesOverlappingWith : function (object) {
  12593. var overlappingNodes = [];
  12594. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  12595. return overlappingNodes;
  12596. },
  12597. /**
  12598. * Return a position object in canvasspace from a single point in screenspace
  12599. *
  12600. * @param pointer
  12601. * @returns {{left: number, top: number, right: number, bottom: number}}
  12602. * @private
  12603. */
  12604. _pointerToPositionObject : function(pointer) {
  12605. var x = this._canvasToX(pointer.x);
  12606. var y = this._canvasToY(pointer.y);
  12607. return {left: x,
  12608. top: y,
  12609. right: x,
  12610. bottom: y};
  12611. },
  12612. /**
  12613. * Get the top node at the a specific point (like a click)
  12614. *
  12615. * @param {{x: Number, y: Number}} pointer
  12616. * @return {Node | null} node
  12617. * @private
  12618. */
  12619. _getNodeAt : function (pointer) {
  12620. // we first check if this is an navigation controls element
  12621. var positionObject = this._pointerToPositionObject(pointer);
  12622. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  12623. // if there are overlapping nodes, select the last one, this is the
  12624. // one which is drawn on top of the others
  12625. if (overlappingNodes.length > 0) {
  12626. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  12627. }
  12628. else {
  12629. return null;
  12630. }
  12631. },
  12632. /**
  12633. * retrieve all edges overlapping with given object, selector is around center
  12634. * @param {Object} object An object with parameters left, top, right, bottom
  12635. * @return {Number[]} An array with id's of the overlapping nodes
  12636. * @private
  12637. */
  12638. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  12639. var edges = this.edges;
  12640. for (var edgeId in edges) {
  12641. if (edges.hasOwnProperty(edgeId)) {
  12642. if (edges[edgeId].isOverlappingWith(object)) {
  12643. overlappingEdges.push(edgeId);
  12644. }
  12645. }
  12646. }
  12647. },
  12648. /**
  12649. * retrieve all nodes overlapping with given object
  12650. * @param {Object} object An object with parameters left, top, right, bottom
  12651. * @return {Number[]} An array with id's of the overlapping nodes
  12652. * @private
  12653. */
  12654. _getAllEdgesOverlappingWith : function (object) {
  12655. var overlappingEdges = [];
  12656. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  12657. return overlappingEdges;
  12658. },
  12659. /**
  12660. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  12661. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  12662. *
  12663. * @param pointer
  12664. * @returns {null}
  12665. * @private
  12666. */
  12667. _getEdgeAt : function(pointer) {
  12668. var positionObject = this._pointerToPositionObject(pointer);
  12669. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  12670. if (overlappingEdges.length > 0) {
  12671. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  12672. }
  12673. else {
  12674. return null;
  12675. }
  12676. },
  12677. /**
  12678. * Add object to the selection array.
  12679. *
  12680. * @param obj
  12681. * @private
  12682. */
  12683. _addToSelection : function(obj) {
  12684. if (obj instanceof Node) {
  12685. this.selectionObj.nodes[obj.id] = obj;
  12686. }
  12687. else {
  12688. this.selectionObj.edges[obj.id] = obj;
  12689. }
  12690. },
  12691. /**
  12692. * Remove a single option from selection.
  12693. *
  12694. * @param {Object} obj
  12695. * @private
  12696. */
  12697. _removeFromSelection : function(obj) {
  12698. if (obj instanceof Node) {
  12699. delete this.selectionObj.nodes[obj.id];
  12700. }
  12701. else {
  12702. delete this.selectionObj.edges[obj.id];
  12703. }
  12704. },
  12705. /**
  12706. * Unselect all. The selectionObj is useful for this.
  12707. *
  12708. * @param {Boolean} [doNotTrigger] | ignore trigger
  12709. * @private
  12710. */
  12711. _unselectAll : function(doNotTrigger) {
  12712. if (doNotTrigger === undefined) {
  12713. doNotTrigger = false;
  12714. }
  12715. for(var nodeId in this.selectionObj.nodes) {
  12716. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12717. this.selectionObj.nodes[nodeId].unselect();
  12718. }
  12719. }
  12720. for(var edgeId in this.selectionObj.edges) {
  12721. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12722. this.selectionObj.edges[edgeId].unselect();;
  12723. }
  12724. }
  12725. this.selectionObj = {nodes:{},edges:{}};
  12726. if (doNotTrigger == false) {
  12727. this.emit('select', this.getSelection());
  12728. }
  12729. },
  12730. /**
  12731. * Unselect all clusters. The selectionObj is useful for this.
  12732. *
  12733. * @param {Boolean} [doNotTrigger] | ignore trigger
  12734. * @private
  12735. */
  12736. _unselectClusters : function(doNotTrigger) {
  12737. if (doNotTrigger === undefined) {
  12738. doNotTrigger = false;
  12739. }
  12740. for (var nodeId in this.selectionObj.nodes) {
  12741. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12742. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  12743. this.selectionObj.nodes[nodeId].unselect();
  12744. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  12745. }
  12746. }
  12747. }
  12748. if (doNotTrigger == false) {
  12749. this.emit('select', this.getSelection());
  12750. }
  12751. },
  12752. /**
  12753. * return the number of selected nodes
  12754. *
  12755. * @returns {number}
  12756. * @private
  12757. */
  12758. _getSelectedNodeCount : function() {
  12759. var count = 0;
  12760. for (var nodeId in this.selectionObj.nodes) {
  12761. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12762. count += 1;
  12763. }
  12764. }
  12765. return count;
  12766. },
  12767. /**
  12768. * return the number of selected nodes
  12769. *
  12770. * @returns {number}
  12771. * @private
  12772. */
  12773. _getSelectedNode : function() {
  12774. for (var nodeId in this.selectionObj.nodes) {
  12775. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12776. return this.selectionObj.nodes[nodeId];
  12777. }
  12778. }
  12779. return null;
  12780. },
  12781. /**
  12782. * return the number of selected edges
  12783. *
  12784. * @returns {number}
  12785. * @private
  12786. */
  12787. _getSelectedEdgeCount : function() {
  12788. var count = 0;
  12789. for (var edgeId in this.selectionObj.edges) {
  12790. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12791. count += 1;
  12792. }
  12793. }
  12794. return count;
  12795. },
  12796. /**
  12797. * return the number of selected objects.
  12798. *
  12799. * @returns {number}
  12800. * @private
  12801. */
  12802. _getSelectedObjectCount : function() {
  12803. var count = 0;
  12804. for(var nodeId in this.selectionObj.nodes) {
  12805. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12806. count += 1;
  12807. }
  12808. }
  12809. for(var edgeId in this.selectionObj.edges) {
  12810. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12811. count += 1;
  12812. }
  12813. }
  12814. return count;
  12815. },
  12816. /**
  12817. * Check if anything is selected
  12818. *
  12819. * @returns {boolean}
  12820. * @private
  12821. */
  12822. _selectionIsEmpty : function() {
  12823. for(var nodeId in this.selectionObj.nodes) {
  12824. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12825. return false;
  12826. }
  12827. }
  12828. for(var edgeId in this.selectionObj.edges) {
  12829. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12830. return false;
  12831. }
  12832. }
  12833. return true;
  12834. },
  12835. /**
  12836. * check if one of the selected nodes is a cluster.
  12837. *
  12838. * @returns {boolean}
  12839. * @private
  12840. */
  12841. _clusterInSelection : function() {
  12842. for(var nodeId in this.selectionObj.nodes) {
  12843. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12844. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  12845. return true;
  12846. }
  12847. }
  12848. }
  12849. return false;
  12850. },
  12851. /**
  12852. * select the edges connected to the node that is being selected
  12853. *
  12854. * @param {Node} node
  12855. * @private
  12856. */
  12857. _selectConnectedEdges : function(node) {
  12858. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12859. var edge = node.dynamicEdges[i];
  12860. edge.select();
  12861. this._addToSelection(edge);
  12862. }
  12863. },
  12864. /**
  12865. * unselect the edges connected to the node that is being selected
  12866. *
  12867. * @param {Node} node
  12868. * @private
  12869. */
  12870. _unselectConnectedEdges : function(node) {
  12871. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12872. var edge = node.dynamicEdges[i];
  12873. edge.unselect();
  12874. this._removeFromSelection(edge);
  12875. }
  12876. },
  12877. /**
  12878. * This is called when someone clicks on a node. either select or deselect it.
  12879. * If there is an existing selection and we don't want to append to it, clear the existing selection
  12880. *
  12881. * @param {Node || Edge} object
  12882. * @param {Boolean} append
  12883. * @param {Boolean} [doNotTrigger] | ignore trigger
  12884. * @private
  12885. */
  12886. _selectObject : function(object, append, doNotTrigger) {
  12887. if (doNotTrigger === undefined) {
  12888. doNotTrigger = false;
  12889. }
  12890. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  12891. this._unselectAll(true);
  12892. }
  12893. if (object.selected == false) {
  12894. object.select();
  12895. this._addToSelection(object);
  12896. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  12897. this._selectConnectedEdges(object);
  12898. }
  12899. }
  12900. else {
  12901. object.unselect();
  12902. this._removeFromSelection(object);
  12903. }
  12904. if (doNotTrigger == false) {
  12905. this.emit('select', this.getSelection());
  12906. }
  12907. },
  12908. /**
  12909. * handles the selection part of the touch, only for navigation controls elements;
  12910. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  12911. * This is the most responsive solution
  12912. *
  12913. * @param {Object} pointer
  12914. * @private
  12915. */
  12916. _handleTouch : function(pointer) {
  12917. },
  12918. /**
  12919. * handles the selection part of the tap;
  12920. *
  12921. * @param {Object} pointer
  12922. * @private
  12923. */
  12924. _handleTap : function(pointer) {
  12925. var node = this._getNodeAt(pointer);
  12926. if (node != null) {
  12927. this._selectObject(node,false);
  12928. }
  12929. else {
  12930. var edge = this._getEdgeAt(pointer);
  12931. if (edge != null) {
  12932. this._selectObject(edge,false);
  12933. }
  12934. else {
  12935. this._unselectAll();
  12936. }
  12937. }
  12938. this.emit("click", this.getSelection());
  12939. this._redraw();
  12940. },
  12941. /**
  12942. * handles the selection part of the double tap and opens a cluster if needed
  12943. *
  12944. * @param {Object} pointer
  12945. * @private
  12946. */
  12947. _handleDoubleTap : function(pointer) {
  12948. var node = this._getNodeAt(pointer);
  12949. if (node != null && node !== undefined) {
  12950. // we reset the areaCenter here so the opening of the node will occur
  12951. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  12952. "y" : this._canvasToY(pointer.y)};
  12953. this.openCluster(node);
  12954. }
  12955. this.emit("doubleClick", this.getSelection());
  12956. },
  12957. /**
  12958. * Handle the onHold selection part
  12959. *
  12960. * @param pointer
  12961. * @private
  12962. */
  12963. _handleOnHold : function(pointer) {
  12964. var node = this._getNodeAt(pointer);
  12965. if (node != null) {
  12966. this._selectObject(node,true);
  12967. }
  12968. else {
  12969. var edge = this._getEdgeAt(pointer);
  12970. if (edge != null) {
  12971. this._selectObject(edge,true);
  12972. }
  12973. }
  12974. this._redraw();
  12975. },
  12976. /**
  12977. * handle the onRelease event. These functions are here for the navigation controls module.
  12978. *
  12979. * @private
  12980. */
  12981. _handleOnRelease : function(pointer) {
  12982. },
  12983. /**
  12984. *
  12985. * retrieve the currently selected objects
  12986. * @return {Number[] | String[]} selection An array with the ids of the
  12987. * selected nodes.
  12988. */
  12989. getSelection : function() {
  12990. var nodeIds = this.getSelectedNodes();
  12991. var edgeIds = this.getSelectedEdges();
  12992. return {nodes:nodeIds, edges:edgeIds};
  12993. },
  12994. /**
  12995. *
  12996. * retrieve the currently selected nodes
  12997. * @return {String} selection An array with the ids of the
  12998. * selected nodes.
  12999. */
  13000. getSelectedNodes : function() {
  13001. var idArray = [];
  13002. for(var nodeId in this.selectionObj.nodes) {
  13003. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13004. idArray.push(nodeId);
  13005. }
  13006. }
  13007. return idArray
  13008. },
  13009. /**
  13010. *
  13011. * retrieve the currently selected edges
  13012. * @return {Array} selection An array with the ids of the
  13013. * selected nodes.
  13014. */
  13015. getSelectedEdges : function() {
  13016. var idArray = [];
  13017. for(var edgeId in this.selectionObj.edges) {
  13018. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13019. idArray.push(edgeId);
  13020. }
  13021. }
  13022. return idArray;
  13023. },
  13024. /**
  13025. * select zero or more nodes
  13026. * @param {Number[] | String[]} selection An array with the ids of the
  13027. * selected nodes.
  13028. */
  13029. setSelection : function(selection) {
  13030. var i, iMax, id;
  13031. if (!selection || (selection.length == undefined))
  13032. throw 'Selection must be an array with ids';
  13033. // first unselect any selected node
  13034. this._unselectAll(true);
  13035. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13036. id = selection[i];
  13037. var node = this.nodes[id];
  13038. if (!node) {
  13039. throw new RangeError('Node with id "' + id + '" not found');
  13040. }
  13041. this._selectObject(node,true,true);
  13042. }
  13043. this.redraw();
  13044. },
  13045. /**
  13046. * Validate the selection: remove ids of nodes which no longer exist
  13047. * @private
  13048. */
  13049. _updateSelection : function () {
  13050. for(var nodeId in this.selectionObj.nodes) {
  13051. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13052. if (!this.nodes.hasOwnProperty(nodeId)) {
  13053. delete this.selectionObj.nodes[nodeId];
  13054. }
  13055. }
  13056. }
  13057. for(var edgeId in this.selectionObj.edges) {
  13058. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13059. if (!this.edges.hasOwnProperty(edgeId)) {
  13060. delete this.selectionObj.edges[edgeId];
  13061. }
  13062. }
  13063. }
  13064. }
  13065. };
  13066. /**
  13067. * Created by Alex on 1/22/14.
  13068. */
  13069. var NavigationMixin = {
  13070. _cleanNavigation : function() {
  13071. // clean up previosu navigation items
  13072. var wrapper = document.getElementById('graph-navigation_wrapper');
  13073. if (wrapper != null) {
  13074. this.containerElement.removeChild(wrapper);
  13075. }
  13076. document.onmouseup = null;
  13077. },
  13078. /**
  13079. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13080. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13081. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13082. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13083. *
  13084. * @private
  13085. */
  13086. _loadNavigationElements : function() {
  13087. this._cleanNavigation();
  13088. this.navigationDivs = {};
  13089. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13090. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  13091. this.navigationDivs['wrapper'] = document.createElement('div');
  13092. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13093. this.navigationDivs['wrapper'].style.position = "absolute";
  13094. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  13095. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  13096. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13097. for (var i = 0; i < navigationDivs.length; i++) {
  13098. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13099. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13100. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13101. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13102. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13103. }
  13104. document.onmouseup = this._stopMovement.bind(this);
  13105. },
  13106. /**
  13107. * this stops all movement induced by the navigation buttons
  13108. *
  13109. * @private
  13110. */
  13111. _stopMovement : function() {
  13112. this._xStopMoving();
  13113. this._yStopMoving();
  13114. this._stopZoom();
  13115. },
  13116. /**
  13117. * stops the actions performed by page up and down etc.
  13118. *
  13119. * @param event
  13120. * @private
  13121. */
  13122. _preventDefault : function(event) {
  13123. if (event !== undefined) {
  13124. if (event.preventDefault) {
  13125. event.preventDefault();
  13126. } else {
  13127. event.returnValue = false;
  13128. }
  13129. }
  13130. },
  13131. /**
  13132. * move the screen up
  13133. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13134. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13135. * To avoid this behaviour, we do the translation in the start loop.
  13136. *
  13137. * @private
  13138. */
  13139. _moveUp : function(event) {
  13140. this.yIncrement = this.constants.keyboard.speed.y;
  13141. this.start(); // if there is no node movement, the calculation wont be done
  13142. this._preventDefault(event);
  13143. if (this.navigationDivs) {
  13144. this.navigationDivs['up'].className += " active";
  13145. }
  13146. },
  13147. /**
  13148. * move the screen down
  13149. * @private
  13150. */
  13151. _moveDown : function(event) {
  13152. this.yIncrement = -this.constants.keyboard.speed.y;
  13153. this.start(); // if there is no node movement, the calculation wont be done
  13154. this._preventDefault(event);
  13155. if (this.navigationDivs) {
  13156. this.navigationDivs['down'].className += " active";
  13157. }
  13158. },
  13159. /**
  13160. * move the screen left
  13161. * @private
  13162. */
  13163. _moveLeft : function(event) {
  13164. this.xIncrement = this.constants.keyboard.speed.x;
  13165. this.start(); // if there is no node movement, the calculation wont be done
  13166. this._preventDefault(event);
  13167. if (this.navigationDivs) {
  13168. this.navigationDivs['left'].className += " active";
  13169. }
  13170. },
  13171. /**
  13172. * move the screen right
  13173. * @private
  13174. */
  13175. _moveRight : function(event) {
  13176. this.xIncrement = -this.constants.keyboard.speed.y;
  13177. this.start(); // if there is no node movement, the calculation wont be done
  13178. this._preventDefault(event);
  13179. if (this.navigationDivs) {
  13180. this.navigationDivs['right'].className += " active";
  13181. }
  13182. },
  13183. /**
  13184. * Zoom in, using the same method as the movement.
  13185. * @private
  13186. */
  13187. _zoomIn : function(event) {
  13188. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13189. this.start(); // if there is no node movement, the calculation wont be done
  13190. this._preventDefault(event);
  13191. if (this.navigationDivs) {
  13192. this.navigationDivs['zoomIn'].className += " active";
  13193. }
  13194. },
  13195. /**
  13196. * Zoom out
  13197. * @private
  13198. */
  13199. _zoomOut : function() {
  13200. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13201. this.start(); // if there is no node movement, the calculation wont be done
  13202. this._preventDefault(event);
  13203. if (this.navigationDivs) {
  13204. this.navigationDivs['zoomOut'].className += " active";
  13205. }
  13206. },
  13207. /**
  13208. * Stop zooming and unhighlight the zoom controls
  13209. * @private
  13210. */
  13211. _stopZoom : function() {
  13212. this.zoomIncrement = 0;
  13213. if (this.navigationDivs) {
  13214. this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active","");
  13215. this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active","");
  13216. }
  13217. },
  13218. /**
  13219. * Stop moving in the Y direction and unHighlight the up and down
  13220. * @private
  13221. */
  13222. _yStopMoving : function() {
  13223. this.yIncrement = 0;
  13224. if (this.navigationDivs) {
  13225. this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active","");
  13226. this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active","");
  13227. }
  13228. },
  13229. /**
  13230. * Stop moving in the X direction and unHighlight left and right.
  13231. * @private
  13232. */
  13233. _xStopMoving : function() {
  13234. this.xIncrement = 0;
  13235. if (this.navigationDivs) {
  13236. this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active","");
  13237. this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active","");
  13238. }
  13239. }
  13240. };
  13241. /**
  13242. * Created by Alex on 2/10/14.
  13243. */
  13244. var graphMixinLoaders = {
  13245. /**
  13246. * Load a mixin into the graph object
  13247. *
  13248. * @param {Object} sourceVariable | this object has to contain functions.
  13249. * @private
  13250. */
  13251. _loadMixin: function (sourceVariable) {
  13252. for (var mixinFunction in sourceVariable) {
  13253. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13254. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13255. }
  13256. }
  13257. },
  13258. /**
  13259. * removes a mixin from the graph object.
  13260. *
  13261. * @param {Object} sourceVariable | this object has to contain functions.
  13262. * @private
  13263. */
  13264. _clearMixin: function (sourceVariable) {
  13265. for (var mixinFunction in sourceVariable) {
  13266. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13267. Graph.prototype[mixinFunction] = undefined;
  13268. }
  13269. }
  13270. },
  13271. /**
  13272. * Mixin the physics system and initialize the parameters required.
  13273. *
  13274. * @private
  13275. */
  13276. _loadPhysicsSystem: function () {
  13277. this._loadMixin(physicsMixin);
  13278. this._loadSelectedForceSolver();
  13279. if (this.constants.configurePhysics == true) {
  13280. this._loadPhysicsConfiguration();
  13281. }
  13282. },
  13283. /**
  13284. * Mixin the cluster system and initialize the parameters required.
  13285. *
  13286. * @private
  13287. */
  13288. _loadClusterSystem: function () {
  13289. this.clusterSession = 0;
  13290. this.hubThreshold = 5;
  13291. this._loadMixin(ClusterMixin);
  13292. },
  13293. /**
  13294. * Mixin the sector system and initialize the parameters required
  13295. *
  13296. * @private
  13297. */
  13298. _loadSectorSystem: function () {
  13299. this.sectors = { },
  13300. this.activeSector = ["default"];
  13301. this.sectors["active"] = { },
  13302. this.sectors["active"]["default"] = {"nodes": {},
  13303. "edges": {},
  13304. "nodeIndices": [],
  13305. "formationScale": 1.0,
  13306. "drawingNode": undefined };
  13307. this.sectors["frozen"] = {},
  13308. this.sectors["support"] = {"nodes": {},
  13309. "edges": {},
  13310. "nodeIndices": [],
  13311. "formationScale": 1.0,
  13312. "drawingNode": undefined };
  13313. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13314. this._loadMixin(SectorMixin);
  13315. },
  13316. /**
  13317. * Mixin the selection system and initialize the parameters required
  13318. *
  13319. * @private
  13320. */
  13321. _loadSelectionSystem: function () {
  13322. this.selectionObj = {nodes: {}, edges: {}};
  13323. this._loadMixin(SelectionMixin);
  13324. },
  13325. /**
  13326. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13327. *
  13328. * @private
  13329. */
  13330. _loadManipulationSystem: function () {
  13331. // reset global variables -- these are used by the selection of nodes and edges.
  13332. this.blockConnectingEdgeSelection = false;
  13333. this.forceAppendSelection = false
  13334. if (this.constants.dataManipulation.enabled == true) {
  13335. // load the manipulator HTML elements. All styling done in css.
  13336. if (this.manipulationDiv === undefined) {
  13337. this.manipulationDiv = document.createElement('div');
  13338. this.manipulationDiv.className = 'graph-manipulationDiv';
  13339. this.manipulationDiv.id = 'graph-manipulationDiv';
  13340. if (this.editMode == true) {
  13341. this.manipulationDiv.style.display = "block";
  13342. }
  13343. else {
  13344. this.manipulationDiv.style.display = "none";
  13345. }
  13346. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13347. }
  13348. if (this.editModeDiv === undefined) {
  13349. this.editModeDiv = document.createElement('div');
  13350. this.editModeDiv.className = 'graph-manipulation-editMode';
  13351. this.editModeDiv.id = 'graph-manipulation-editMode';
  13352. if (this.editMode == true) {
  13353. this.editModeDiv.style.display = "none";
  13354. }
  13355. else {
  13356. this.editModeDiv.style.display = "block";
  13357. }
  13358. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13359. }
  13360. if (this.closeDiv === undefined) {
  13361. this.closeDiv = document.createElement('div');
  13362. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13363. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13364. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13365. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13366. }
  13367. // load the manipulation functions
  13368. this._loadMixin(manipulationMixin);
  13369. // create the manipulator toolbar
  13370. this._createManipulatorBar();
  13371. }
  13372. else {
  13373. if (this.manipulationDiv !== undefined) {
  13374. // removes all the bindings and overloads
  13375. this._createManipulatorBar();
  13376. // remove the manipulation divs
  13377. this.containerElement.removeChild(this.manipulationDiv);
  13378. this.containerElement.removeChild(this.editModeDiv);
  13379. this.containerElement.removeChild(this.closeDiv);
  13380. this.manipulationDiv = undefined;
  13381. this.editModeDiv = undefined;
  13382. this.closeDiv = undefined;
  13383. // remove the mixin functions
  13384. this._clearMixin(manipulationMixin);
  13385. }
  13386. }
  13387. },
  13388. /**
  13389. * Mixin the navigation (User Interface) system and initialize the parameters required
  13390. *
  13391. * @private
  13392. */
  13393. _loadNavigationControls: function () {
  13394. this._loadMixin(NavigationMixin);
  13395. // the clean function removes the button divs, this is done to remove the bindings.
  13396. this._cleanNavigation();
  13397. if (this.constants.navigation.enabled == true) {
  13398. this._loadNavigationElements();
  13399. }
  13400. },
  13401. /**
  13402. * Mixin the hierarchical layout system.
  13403. *
  13404. * @private
  13405. */
  13406. _loadHierarchySystem: function () {
  13407. this._loadMixin(HierarchicalLayoutMixin);
  13408. }
  13409. };
  13410. /**
  13411. * @constructor Graph
  13412. * Create a graph visualization, displaying nodes and edges.
  13413. *
  13414. * @param {Element} container The DOM element in which the Graph will
  13415. * be created. Normally a div element.
  13416. * @param {Object} data An object containing parameters
  13417. * {Array} nodes
  13418. * {Array} edges
  13419. * @param {Object} options Options
  13420. */
  13421. function Graph (container, data, options) {
  13422. this._initializeMixinLoaders();
  13423. // create variables and set default values
  13424. this.containerElement = container;
  13425. this.width = '100%';
  13426. this.height = '100%';
  13427. // render and calculation settings
  13428. this.renderRefreshRate = 60; // hz (fps)
  13429. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  13430. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  13431. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  13432. this.physicsDiscreteStepsize = 0.65; // discrete stepsize of the simulation
  13433. this.stabilize = true; // stabilize before displaying the graph
  13434. this.selectable = true;
  13435. this.initializing = true;
  13436. // these functions are triggered when the dataset is edited
  13437. this.triggerFunctions = {add:null,edit:null,connect:null,del:null};
  13438. // set constant values
  13439. this.constants = {
  13440. nodes: {
  13441. radiusMin: 5,
  13442. radiusMax: 20,
  13443. radius: 5,
  13444. shape: 'ellipse',
  13445. image: undefined,
  13446. widthMin: 16, // px
  13447. widthMax: 64, // px
  13448. fixed: false,
  13449. fontColor: 'black',
  13450. fontSize: 14, // px
  13451. fontFace: 'verdana',
  13452. level: -1,
  13453. color: {
  13454. border: '#2B7CE9',
  13455. background: '#97C2FC',
  13456. highlight: {
  13457. border: '#2B7CE9',
  13458. background: '#D2E5FF'
  13459. }
  13460. },
  13461. borderColor: '#2B7CE9',
  13462. backgroundColor: '#97C2FC',
  13463. highlightColor: '#D2E5FF',
  13464. group: undefined
  13465. },
  13466. edges: {
  13467. widthMin: 1,
  13468. widthMax: 15,
  13469. width: 1,
  13470. style: 'line',
  13471. color: {
  13472. color:'#848484',
  13473. highlight:'#848484'
  13474. },
  13475. fontColor: '#343434',
  13476. fontSize: 14, // px
  13477. fontFace: 'arial',
  13478. fontFill: 'white',
  13479. dash: {
  13480. length: 10,
  13481. gap: 5,
  13482. altLength: undefined
  13483. }
  13484. },
  13485. configurePhysics:false,
  13486. physics: {
  13487. barnesHut: {
  13488. enabled: true,
  13489. theta: 1 / 0.6, // inverted to save time during calculation
  13490. gravitationalConstant: -2000,
  13491. centralGravity: 0.3,
  13492. springLength: 95,
  13493. springConstant: 0.04,
  13494. damping: 0.09
  13495. },
  13496. repulsion: {
  13497. centralGravity: 0.1,
  13498. springLength: 200,
  13499. springConstant: 0.05,
  13500. nodeDistance: 100,
  13501. damping: 0.09
  13502. },
  13503. hierarchicalRepulsion: {
  13504. enabled: false,
  13505. centralGravity: 0.0,
  13506. springLength: 100,
  13507. springConstant: 0.01,
  13508. nodeDistance: 60,
  13509. damping: 0.09
  13510. },
  13511. damping: null,
  13512. centralGravity: null,
  13513. springLength: null,
  13514. springConstant: null
  13515. },
  13516. clustering: { // Per Node in Cluster = PNiC
  13517. enabled: false, // (Boolean) | global on/off switch for clustering.
  13518. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  13519. 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
  13520. 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
  13521. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  13522. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  13523. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  13524. 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.
  13525. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  13526. maxFontSize: 1000,
  13527. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  13528. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  13529. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  13530. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  13531. height: 1, // (px PNiC) | growth of the height per node in cluster.
  13532. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  13533. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  13534. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  13535. clusterLevelDifference: 2
  13536. },
  13537. navigation: {
  13538. enabled: false
  13539. },
  13540. keyboard: {
  13541. enabled: false,
  13542. speed: {x: 10, y: 10, zoom: 0.02}
  13543. },
  13544. dataManipulation: {
  13545. enabled: false,
  13546. initiallyVisible: false
  13547. },
  13548. hierarchicalLayout: {
  13549. enabled:false,
  13550. levelSeparation: 150,
  13551. nodeSpacing: 100,
  13552. direction: "UD" // UD, DU, LR, RL
  13553. },
  13554. freezeForStabilization: false,
  13555. smoothCurves: true,
  13556. maxVelocity: 10,
  13557. minVelocity: 0.1, // px/s
  13558. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  13559. labels:{
  13560. add:"Add Node",
  13561. edit:"Edit",
  13562. link:"Add Link",
  13563. del:"Delete selected",
  13564. editNode:"Edit Node",
  13565. back:"Back",
  13566. addDescription:"Click in an empty space to place a new node.",
  13567. linkDescription:"Click on a node and drag the edge to another node to connect them.",
  13568. addError:"The function for add does not support two arguments (data,callback).",
  13569. linkError:"The function for connect does not support two arguments (data,callback).",
  13570. editError:"The function for edit does not support two arguments (data, callback).",
  13571. editBoundError:"No edit function has been bound to this button.",
  13572. deleteError:"The function for delete does not support two arguments (data, callback).",
  13573. deleteClusterError:"Clusters cannot be deleted."
  13574. },
  13575. tooltip: {
  13576. delay: 300,
  13577. fontColor: 'black',
  13578. fontSize: 14, // px
  13579. fontFace: 'verdana',
  13580. color: {
  13581. border: '#666',
  13582. background: '#FFFFC6'
  13583. }
  13584. }
  13585. };
  13586. this.editMode = this.constants.dataManipulation.initiallyVisible;
  13587. // Node variables
  13588. var graph = this;
  13589. this.groups = new Groups(); // object with groups
  13590. this.images = new Images(); // object with images
  13591. this.images.setOnloadCallback(function () {
  13592. graph._redraw();
  13593. });
  13594. // keyboard navigation variables
  13595. this.xIncrement = 0;
  13596. this.yIncrement = 0;
  13597. this.zoomIncrement = 0;
  13598. // loading all the mixins:
  13599. // load the force calculation functions, grouped under the physics system.
  13600. this._loadPhysicsSystem();
  13601. // create a frame and canvas
  13602. this._create();
  13603. // load the sector system. (mandatory, fully integrated with Graph)
  13604. this._loadSectorSystem();
  13605. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  13606. this._loadClusterSystem();
  13607. // load the selection system. (mandatory, required by Graph)
  13608. this._loadSelectionSystem();
  13609. // load the selection system. (mandatory, required by Graph)
  13610. this._loadHierarchySystem();
  13611. // apply options
  13612. this.setOptions(options);
  13613. // other vars
  13614. this.freezeSimulation = false;// freeze the simulation
  13615. this.cachedFunctions = {};
  13616. // containers for nodes and edges
  13617. this.calculationNodes = {};
  13618. this.calculationNodeIndices = [];
  13619. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  13620. this.nodes = {}; // object with Node objects
  13621. this.edges = {}; // object with Edge objects
  13622. // position and scale variables and objects
  13623. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  13624. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13625. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13626. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  13627. this.scale = 1; // defining the global scale variable in the constructor
  13628. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  13629. // datasets or dataviews
  13630. this.nodesData = null; // A DataSet or DataView
  13631. this.edgesData = null; // A DataSet or DataView
  13632. // create event listeners used to subscribe on the DataSets of the nodes and edges
  13633. this.nodesListeners = {
  13634. 'add': function (event, params) {
  13635. graph._addNodes(params.items);
  13636. graph.start();
  13637. },
  13638. 'update': function (event, params) {
  13639. graph._updateNodes(params.items);
  13640. graph.start();
  13641. },
  13642. 'remove': function (event, params) {
  13643. graph._removeNodes(params.items);
  13644. graph.start();
  13645. }
  13646. };
  13647. this.edgesListeners = {
  13648. 'add': function (event, params) {
  13649. graph._addEdges(params.items);
  13650. graph.start();
  13651. },
  13652. 'update': function (event, params) {
  13653. graph._updateEdges(params.items);
  13654. graph.start();
  13655. },
  13656. 'remove': function (event, params) {
  13657. graph._removeEdges(params.items);
  13658. graph.start();
  13659. }
  13660. };
  13661. // properties for the animation
  13662. this.moving = true;
  13663. this.timer = undefined; // Scheduling function. Is definded in this.start();
  13664. // load data (the disable start variable will be the same as the enabled clustering)
  13665. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  13666. // hierarchical layout
  13667. this.initializing = false;
  13668. if (this.constants.hierarchicalLayout.enabled == true) {
  13669. this._setupHierarchicalLayout();
  13670. }
  13671. else {
  13672. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  13673. if (this.stabilize == false) {
  13674. this.zoomExtent(true,this.constants.clustering.enabled);
  13675. }
  13676. }
  13677. // if clustering is disabled, the simulation will have started in the setData function
  13678. if (this.constants.clustering.enabled) {
  13679. this.startWithClustering();
  13680. }
  13681. }
  13682. // Extend Graph with an Emitter mixin
  13683. Emitter(Graph.prototype);
  13684. /**
  13685. * Get the script path where the vis.js library is located
  13686. *
  13687. * @returns {string | null} path Path or null when not found. Path does not
  13688. * end with a slash.
  13689. * @private
  13690. */
  13691. Graph.prototype._getScriptPath = function() {
  13692. var scripts = document.getElementsByTagName( 'script' );
  13693. // find script named vis.js or vis.min.js
  13694. for (var i = 0; i < scripts.length; i++) {
  13695. var src = scripts[i].src;
  13696. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  13697. if (match) {
  13698. // return path without the script name
  13699. return src.substring(0, src.length - match[0].length);
  13700. }
  13701. }
  13702. return null;
  13703. };
  13704. /**
  13705. * Find the center position of the graph
  13706. * @private
  13707. */
  13708. Graph.prototype._getRange = function() {
  13709. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  13710. for (var nodeId in this.nodes) {
  13711. if (this.nodes.hasOwnProperty(nodeId)) {
  13712. node = this.nodes[nodeId];
  13713. if (minX > (node.x)) {minX = node.x;}
  13714. if (maxX < (node.x)) {maxX = node.x;}
  13715. if (minY > (node.y)) {minY = node.y;}
  13716. if (maxY < (node.y)) {maxY = node.y;}
  13717. }
  13718. }
  13719. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  13720. minY = 0, maxY = 0, minX = 0, maxX = 0;
  13721. }
  13722. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13723. };
  13724. /**
  13725. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13726. * @returns {{x: number, y: number}}
  13727. * @private
  13728. */
  13729. Graph.prototype._findCenter = function(range) {
  13730. return {x: (0.5 * (range.maxX + range.minX)),
  13731. y: (0.5 * (range.maxY + range.minY))};
  13732. };
  13733. /**
  13734. * center the graph
  13735. *
  13736. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13737. */
  13738. Graph.prototype._centerGraph = function(range) {
  13739. var center = this._findCenter(range);
  13740. center.x *= this.scale;
  13741. center.y *= this.scale;
  13742. center.x -= 0.5 * this.frame.canvas.clientWidth;
  13743. center.y -= 0.5 * this.frame.canvas.clientHeight;
  13744. this._setTranslation(-center.x,-center.y); // set at 0,0
  13745. };
  13746. /**
  13747. * This function zooms out to fit all data on screen based on amount of nodes
  13748. *
  13749. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  13750. */
  13751. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  13752. if (initialZoom === undefined) {
  13753. initialZoom = false;
  13754. }
  13755. if (disableStart === undefined) {
  13756. disableStart = false;
  13757. }
  13758. var range = this._getRange();
  13759. var zoomLevel;
  13760. if (initialZoom == true) {
  13761. var numberOfNodes = this.nodeIndices.length;
  13762. if (this.constants.smoothCurves == true) {
  13763. if (this.constants.clustering.enabled == true &&
  13764. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  13765. 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.
  13766. }
  13767. else {
  13768. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13769. }
  13770. }
  13771. else {
  13772. if (this.constants.clustering.enabled == true &&
  13773. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  13774. 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.
  13775. }
  13776. else {
  13777. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13778. }
  13779. }
  13780. // correct for larger canvasses.
  13781. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  13782. zoomLevel *= factor;
  13783. }
  13784. else {
  13785. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  13786. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  13787. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  13788. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  13789. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  13790. }
  13791. if (zoomLevel > 1.0) {
  13792. zoomLevel = 1.0;
  13793. }
  13794. this._setScale(zoomLevel);
  13795. this._centerGraph(range);
  13796. if (disableStart == false) {
  13797. this.moving = true;
  13798. this.start();
  13799. }
  13800. };
  13801. /**
  13802. * Update the this.nodeIndices with the most recent node index list
  13803. * @private
  13804. */
  13805. Graph.prototype._updateNodeIndexList = function() {
  13806. this._clearNodeIndexList();
  13807. for (var idx in this.nodes) {
  13808. if (this.nodes.hasOwnProperty(idx)) {
  13809. this.nodeIndices.push(idx);
  13810. }
  13811. }
  13812. };
  13813. /**
  13814. * Set nodes and edges, and optionally options as well.
  13815. *
  13816. * @param {Object} data Object containing parameters:
  13817. * {Array | DataSet | DataView} [nodes] Array with nodes
  13818. * {Array | DataSet | DataView} [edges] Array with edges
  13819. * {String} [dot] String containing data in DOT format
  13820. * {Options} [options] Object with options
  13821. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  13822. */
  13823. Graph.prototype.setData = function(data, disableStart) {
  13824. if (disableStart === undefined) {
  13825. disableStart = false;
  13826. }
  13827. if (data && data.dot && (data.nodes || data.edges)) {
  13828. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  13829. ' parameter pair "nodes" and "edges", but not both.');
  13830. }
  13831. // set options
  13832. this.setOptions(data && data.options);
  13833. // set all data
  13834. if (data && data.dot) {
  13835. // parse DOT file
  13836. if(data && data.dot) {
  13837. var dotData = vis.util.DOTToGraph(data.dot);
  13838. this.setData(dotData);
  13839. return;
  13840. }
  13841. }
  13842. else {
  13843. this._setNodes(data && data.nodes);
  13844. this._setEdges(data && data.edges);
  13845. }
  13846. this._putDataInSector();
  13847. if (!disableStart) {
  13848. // find a stable position or start animating to a stable position
  13849. if (this.stabilize) {
  13850. this._stabilize();
  13851. }
  13852. this.start();
  13853. }
  13854. };
  13855. /**
  13856. * Set options
  13857. * @param {Object} options
  13858. */
  13859. Graph.prototype.setOptions = function (options) {
  13860. if (options) {
  13861. var prop;
  13862. // retrieve parameter values
  13863. if (options.width !== undefined) {this.width = options.width;}
  13864. if (options.height !== undefined) {this.height = options.height;}
  13865. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  13866. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  13867. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  13868. if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;}
  13869. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  13870. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  13871. if (options.labels !== undefined) {
  13872. for (prop in options.labels) {
  13873. if (options.labels.hasOwnProperty(prop)) {
  13874. this.constants.labels[prop] = options.labels[prop];
  13875. }
  13876. }
  13877. }
  13878. if (options.onAdd) {
  13879. this.triggerFunctions.add = options.onAdd;
  13880. }
  13881. if (options.onEdit) {
  13882. this.triggerFunctions.edit = options.onEdit;
  13883. }
  13884. if (options.onConnect) {
  13885. this.triggerFunctions.connect = options.onConnect;
  13886. }
  13887. if (options.onDelete) {
  13888. this.triggerFunctions.del = options.onDelete;
  13889. }
  13890. if (options.physics) {
  13891. if (options.physics.barnesHut) {
  13892. this.constants.physics.barnesHut.enabled = true;
  13893. for (prop in options.physics.barnesHut) {
  13894. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  13895. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  13896. }
  13897. }
  13898. }
  13899. if (options.physics.repulsion) {
  13900. this.constants.physics.barnesHut.enabled = false;
  13901. for (prop in options.physics.repulsion) {
  13902. if (options.physics.repulsion.hasOwnProperty(prop)) {
  13903. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  13904. }
  13905. }
  13906. }
  13907. }
  13908. if (options.hierarchicalLayout) {
  13909. this.constants.hierarchicalLayout.enabled = true;
  13910. for (prop in options.hierarchicalLayout) {
  13911. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  13912. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  13913. }
  13914. }
  13915. }
  13916. else if (options.hierarchicalLayout !== undefined) {
  13917. this.constants.hierarchicalLayout.enabled = false;
  13918. }
  13919. if (options.clustering) {
  13920. this.constants.clustering.enabled = true;
  13921. for (prop in options.clustering) {
  13922. if (options.clustering.hasOwnProperty(prop)) {
  13923. this.constants.clustering[prop] = options.clustering[prop];
  13924. }
  13925. }
  13926. }
  13927. else if (options.clustering !== undefined) {
  13928. this.constants.clustering.enabled = false;
  13929. }
  13930. if (options.navigation) {
  13931. this.constants.navigation.enabled = true;
  13932. for (prop in options.navigation) {
  13933. if (options.navigation.hasOwnProperty(prop)) {
  13934. this.constants.navigation[prop] = options.navigation[prop];
  13935. }
  13936. }
  13937. }
  13938. else if (options.navigation !== undefined) {
  13939. this.constants.navigation.enabled = false;
  13940. }
  13941. if (options.keyboard) {
  13942. this.constants.keyboard.enabled = true;
  13943. for (prop in options.keyboard) {
  13944. if (options.keyboard.hasOwnProperty(prop)) {
  13945. this.constants.keyboard[prop] = options.keyboard[prop];
  13946. }
  13947. }
  13948. }
  13949. else if (options.keyboard !== undefined) {
  13950. this.constants.keyboard.enabled = false;
  13951. }
  13952. if (options.dataManipulation) {
  13953. this.constants.dataManipulation.enabled = true;
  13954. for (prop in options.dataManipulation) {
  13955. if (options.dataManipulation.hasOwnProperty(prop)) {
  13956. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  13957. }
  13958. }
  13959. }
  13960. else if (options.dataManipulation !== undefined) {
  13961. this.constants.dataManipulation.enabled = false;
  13962. }
  13963. // TODO: work out these options and document them
  13964. if (options.edges) {
  13965. for (prop in options.edges) {
  13966. if (options.edges.hasOwnProperty(prop)) {
  13967. if (typeof options.edges[prop] != "object") {
  13968. this.constants.edges[prop] = options.edges[prop];
  13969. }
  13970. }
  13971. }
  13972. if (options.edges.color !== undefined) {
  13973. if (util.isString(options.edges.color)) {
  13974. this.constants.edges.color = {};
  13975. this.constants.edges.color.color = options.edges.color;
  13976. this.constants.edges.color.highlight = options.edges.color;
  13977. }
  13978. else {
  13979. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  13980. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  13981. }
  13982. }
  13983. if (!options.edges.fontColor) {
  13984. if (options.edges.color !== undefined) {
  13985. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  13986. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  13987. }
  13988. }
  13989. // Added to support dashed lines
  13990. // David Jordan
  13991. // 2012-08-08
  13992. if (options.edges.dash) {
  13993. if (options.edges.dash.length !== undefined) {
  13994. this.constants.edges.dash.length = options.edges.dash.length;
  13995. }
  13996. if (options.edges.dash.gap !== undefined) {
  13997. this.constants.edges.dash.gap = options.edges.dash.gap;
  13998. }
  13999. if (options.edges.dash.altLength !== undefined) {
  14000. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14001. }
  14002. }
  14003. }
  14004. if (options.nodes) {
  14005. for (prop in options.nodes) {
  14006. if (options.nodes.hasOwnProperty(prop)) {
  14007. this.constants.nodes[prop] = options.nodes[prop];
  14008. }
  14009. }
  14010. if (options.nodes.color) {
  14011. this.constants.nodes.color = util.parseColor(options.nodes.color);
  14012. }
  14013. /*
  14014. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14015. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14016. */
  14017. }
  14018. if (options.groups) {
  14019. for (var groupname in options.groups) {
  14020. if (options.groups.hasOwnProperty(groupname)) {
  14021. var group = options.groups[groupname];
  14022. this.groups.add(groupname, group);
  14023. }
  14024. }
  14025. }
  14026. if (options.tooltip) {
  14027. for (prop in options.tooltip) {
  14028. if (options.tooltip.hasOwnProperty(prop)) {
  14029. this.constants.tooltip[prop] = options.tooltip[prop];
  14030. }
  14031. }
  14032. if (options.tooltip.color) {
  14033. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  14034. }
  14035. }
  14036. }
  14037. // (Re)loading the mixins that can be enabled or disabled in the options.
  14038. // load the force calculation functions, grouped under the physics system.
  14039. this._loadPhysicsSystem();
  14040. // load the navigation system.
  14041. this._loadNavigationControls();
  14042. // load the data manipulation system
  14043. this._loadManipulationSystem();
  14044. // configure the smooth curves
  14045. this._configureSmoothCurves();
  14046. // bind keys. If disabled, this will not do anything;
  14047. this._createKeyBinds();
  14048. this.setSize(this.width, this.height);
  14049. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14050. this._setScale(1);
  14051. this._redraw();
  14052. };
  14053. /**
  14054. * Create the main frame for the Graph.
  14055. * This function is executed once when a Graph object is created. The frame
  14056. * contains a canvas, and this canvas contains all objects like the axis and
  14057. * nodes.
  14058. * @private
  14059. */
  14060. Graph.prototype._create = function () {
  14061. // remove all elements from the container element.
  14062. while (this.containerElement.hasChildNodes()) {
  14063. this.containerElement.removeChild(this.containerElement.firstChild);
  14064. }
  14065. this.frame = document.createElement('div');
  14066. this.frame.className = 'graph-frame';
  14067. this.frame.style.position = 'relative';
  14068. this.frame.style.overflow = 'hidden';
  14069. // create the graph canvas (HTML canvas element)
  14070. this.frame.canvas = document.createElement( 'canvas' );
  14071. this.frame.canvas.style.position = 'relative';
  14072. this.frame.appendChild(this.frame.canvas);
  14073. if (!this.frame.canvas.getContext) {
  14074. var noCanvas = document.createElement( 'DIV' );
  14075. noCanvas.style.color = 'red';
  14076. noCanvas.style.fontWeight = 'bold' ;
  14077. noCanvas.style.padding = '10px';
  14078. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14079. this.frame.canvas.appendChild(noCanvas);
  14080. }
  14081. var me = this;
  14082. this.drag = {};
  14083. this.pinch = {};
  14084. this.hammer = Hammer(this.frame.canvas, {
  14085. prevent_default: true
  14086. });
  14087. this.hammer.on('tap', me._onTap.bind(me) );
  14088. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14089. this.hammer.on('hold', me._onHold.bind(me) );
  14090. this.hammer.on('pinch', me._onPinch.bind(me) );
  14091. this.hammer.on('touch', me._onTouch.bind(me) );
  14092. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14093. this.hammer.on('drag', me._onDrag.bind(me) );
  14094. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14095. this.hammer.on('release', me._onRelease.bind(me) );
  14096. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14097. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14098. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14099. // add the frame to the container element
  14100. this.containerElement.appendChild(this.frame);
  14101. };
  14102. /**
  14103. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14104. * @private
  14105. */
  14106. Graph.prototype._createKeyBinds = function() {
  14107. var me = this;
  14108. this.mousetrap = mousetrap;
  14109. this.mousetrap.reset();
  14110. if (this.constants.keyboard.enabled == true) {
  14111. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14112. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14113. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14114. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14115. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14116. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14117. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14118. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14119. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14120. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14121. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14122. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14123. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14124. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14125. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14126. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14127. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14128. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14129. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14130. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14131. }
  14132. if (this.constants.dataManipulation.enabled == true) {
  14133. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14134. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14135. }
  14136. };
  14137. /**
  14138. * Get the pointer location from a touch location
  14139. * @param {{pageX: Number, pageY: Number}} touch
  14140. * @return {{x: Number, y: Number}} pointer
  14141. * @private
  14142. */
  14143. Graph.prototype._getPointer = function (touch) {
  14144. return {
  14145. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14146. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14147. };
  14148. };
  14149. /**
  14150. * On start of a touch gesture, store the pointer
  14151. * @param event
  14152. * @private
  14153. */
  14154. Graph.prototype._onTouch = function (event) {
  14155. this.drag.pointer = this._getPointer(event.gesture.center);
  14156. this.drag.pinched = false;
  14157. this.pinch.scale = this._getScale();
  14158. this._handleTouch(this.drag.pointer);
  14159. };
  14160. /**
  14161. * handle drag start event
  14162. * @private
  14163. */
  14164. Graph.prototype._onDragStart = function () {
  14165. this._handleDragStart();
  14166. };
  14167. /**
  14168. * This function is called by _onDragStart.
  14169. * It is separated out because we can then overload it for the datamanipulation system.
  14170. *
  14171. * @private
  14172. */
  14173. Graph.prototype._handleDragStart = function() {
  14174. var drag = this.drag;
  14175. var node = this._getNodeAt(drag.pointer);
  14176. // note: drag.pointer is set in _onTouch to get the initial touch location
  14177. drag.dragging = true;
  14178. drag.selection = [];
  14179. drag.translation = this._getTranslation();
  14180. drag.nodeId = null;
  14181. if (node != null) {
  14182. drag.nodeId = node.id;
  14183. // select the clicked node if not yet selected
  14184. if (!node.isSelected()) {
  14185. this._selectObject(node,false);
  14186. }
  14187. // create an array with the selected nodes and their original location and status
  14188. for (var objectId in this.selectionObj.nodes) {
  14189. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  14190. var object = this.selectionObj.nodes[objectId];
  14191. var s = {
  14192. id: object.id,
  14193. node: object,
  14194. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14195. x: object.x,
  14196. y: object.y,
  14197. xFixed: object.xFixed,
  14198. yFixed: object.yFixed
  14199. };
  14200. object.xFixed = true;
  14201. object.yFixed = true;
  14202. drag.selection.push(s);
  14203. }
  14204. }
  14205. }
  14206. };
  14207. /**
  14208. * handle drag event
  14209. * @private
  14210. */
  14211. Graph.prototype._onDrag = function (event) {
  14212. this._handleOnDrag(event)
  14213. };
  14214. /**
  14215. * This function is called by _onDrag.
  14216. * It is separated out because we can then overload it for the datamanipulation system.
  14217. *
  14218. * @private
  14219. */
  14220. Graph.prototype._handleOnDrag = function(event) {
  14221. if (this.drag.pinched) {
  14222. return;
  14223. }
  14224. var pointer = this._getPointer(event.gesture.center);
  14225. var me = this,
  14226. drag = this.drag,
  14227. selection = drag.selection;
  14228. if (selection && selection.length) {
  14229. // calculate delta's and new location
  14230. var deltaX = pointer.x - drag.pointer.x,
  14231. deltaY = pointer.y - drag.pointer.y;
  14232. // update position of all selected nodes
  14233. selection.forEach(function (s) {
  14234. var node = s.node;
  14235. if (!s.xFixed) {
  14236. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14237. }
  14238. if (!s.yFixed) {
  14239. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14240. }
  14241. });
  14242. // start _animationStep if not yet running
  14243. if (!this.moving) {
  14244. this.moving = true;
  14245. this.start();
  14246. }
  14247. }
  14248. else {
  14249. // move the graph
  14250. var diffX = pointer.x - this.drag.pointer.x;
  14251. var diffY = pointer.y - this.drag.pointer.y;
  14252. this._setTranslation(
  14253. this.drag.translation.x + diffX,
  14254. this.drag.translation.y + diffY);
  14255. this._redraw();
  14256. this.moved = true;
  14257. }
  14258. };
  14259. /**
  14260. * handle drag start event
  14261. * @private
  14262. */
  14263. Graph.prototype._onDragEnd = function () {
  14264. this.drag.dragging = false;
  14265. var selection = this.drag.selection;
  14266. if (selection) {
  14267. selection.forEach(function (s) {
  14268. // restore original xFixed and yFixed
  14269. s.node.xFixed = s.xFixed;
  14270. s.node.yFixed = s.yFixed;
  14271. });
  14272. }
  14273. };
  14274. /**
  14275. * handle tap/click event: select/unselect a node
  14276. * @private
  14277. */
  14278. Graph.prototype._onTap = function (event) {
  14279. var pointer = this._getPointer(event.gesture.center);
  14280. this.pointerPosition = pointer;
  14281. this._handleTap(pointer);
  14282. };
  14283. /**
  14284. * handle doubletap event
  14285. * @private
  14286. */
  14287. Graph.prototype._onDoubleTap = function (event) {
  14288. var pointer = this._getPointer(event.gesture.center);
  14289. this._handleDoubleTap(pointer);
  14290. };
  14291. /**
  14292. * handle long tap event: multi select nodes
  14293. * @private
  14294. */
  14295. Graph.prototype._onHold = function (event) {
  14296. var pointer = this._getPointer(event.gesture.center);
  14297. this.pointerPosition = pointer;
  14298. this._handleOnHold(pointer);
  14299. };
  14300. /**
  14301. * handle the release of the screen
  14302. *
  14303. * @private
  14304. */
  14305. Graph.prototype._onRelease = function (event) {
  14306. var pointer = this._getPointer(event.gesture.center);
  14307. this._handleOnRelease(pointer);
  14308. };
  14309. /**
  14310. * Handle pinch event
  14311. * @param event
  14312. * @private
  14313. */
  14314. Graph.prototype._onPinch = function (event) {
  14315. var pointer = this._getPointer(event.gesture.center);
  14316. this.drag.pinched = true;
  14317. if (!('scale' in this.pinch)) {
  14318. this.pinch.scale = 1;
  14319. }
  14320. // TODO: enabled moving while pinching?
  14321. var scale = this.pinch.scale * event.gesture.scale;
  14322. this._zoom(scale, pointer)
  14323. };
  14324. /**
  14325. * Zoom the graph in or out
  14326. * @param {Number} scale a number around 1, and between 0.01 and 10
  14327. * @param {{x: Number, y: Number}} pointer Position on screen
  14328. * @return {Number} appliedScale scale is limited within the boundaries
  14329. * @private
  14330. */
  14331. Graph.prototype._zoom = function(scale, pointer) {
  14332. var scaleOld = this._getScale();
  14333. if (scale < 0.00001) {
  14334. scale = 0.00001;
  14335. }
  14336. if (scale > 10) {
  14337. scale = 10;
  14338. }
  14339. // + this.frame.canvas.clientHeight / 2
  14340. var translation = this._getTranslation();
  14341. var scaleFrac = scale / scaleOld;
  14342. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14343. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14344. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  14345. "y" : this._canvasToY(pointer.y)};
  14346. this._setScale(scale);
  14347. this._setTranslation(tx, ty);
  14348. this.updateClustersDefault();
  14349. this._redraw();
  14350. return scale;
  14351. };
  14352. /**
  14353. * Event handler for mouse wheel event, used to zoom the timeline
  14354. * See http://adomas.org/javascript-mouse-wheel/
  14355. * https://github.com/EightMedia/hammer.js/issues/256
  14356. * @param {MouseEvent} event
  14357. * @private
  14358. */
  14359. Graph.prototype._onMouseWheel = function(event) {
  14360. // retrieve delta
  14361. var delta = 0;
  14362. if (event.wheelDelta) { /* IE/Opera. */
  14363. delta = event.wheelDelta/120;
  14364. } else if (event.detail) { /* Mozilla case. */
  14365. // In Mozilla, sign of delta is different than in IE.
  14366. // Also, delta is multiple of 3.
  14367. delta = -event.detail/3;
  14368. }
  14369. // If delta is nonzero, handle it.
  14370. // Basically, delta is now positive if wheel was scrolled up,
  14371. // and negative, if wheel was scrolled down.
  14372. if (delta) {
  14373. // calculate the new scale
  14374. var scale = this._getScale();
  14375. var zoom = delta / 10;
  14376. if (delta < 0) {
  14377. zoom = zoom / (1 - zoom);
  14378. }
  14379. scale *= (1 + zoom);
  14380. // calculate the pointer location
  14381. var gesture = util.fakeGesture(this, event);
  14382. var pointer = this._getPointer(gesture.center);
  14383. // apply the new scale
  14384. this._zoom(scale, pointer);
  14385. }
  14386. // Prevent default actions caused by mouse wheel.
  14387. event.preventDefault();
  14388. };
  14389. /**
  14390. * Mouse move handler for checking whether the title moves over a node with a title.
  14391. * @param {Event} event
  14392. * @private
  14393. */
  14394. Graph.prototype._onMouseMoveTitle = function (event) {
  14395. var gesture = util.fakeGesture(this, event);
  14396. var pointer = this._getPointer(gesture.center);
  14397. // check if the previously selected node is still selected
  14398. if (this.popupNode) {
  14399. this._checkHidePopup(pointer);
  14400. }
  14401. // start a timeout that will check if the mouse is positioned above
  14402. // an element
  14403. var me = this;
  14404. var checkShow = function() {
  14405. me._checkShowPopup(pointer);
  14406. };
  14407. if (this.popupTimer) {
  14408. clearInterval(this.popupTimer); // stop any running calculationTimer
  14409. }
  14410. if (!this.drag.dragging) {
  14411. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  14412. }
  14413. };
  14414. /**
  14415. * Check if there is an element on the given position in the graph
  14416. * (a node or edge). If so, and if this element has a title,
  14417. * show a popup window with its title.
  14418. *
  14419. * @param {{x:Number, y:Number}} pointer
  14420. * @private
  14421. */
  14422. Graph.prototype._checkShowPopup = function (pointer) {
  14423. var obj = {
  14424. left: this._canvasToX(pointer.x),
  14425. top: this._canvasToY(pointer.y),
  14426. right: this._canvasToX(pointer.x),
  14427. bottom: this._canvasToY(pointer.y)
  14428. };
  14429. var id;
  14430. var lastPopupNode = this.popupNode;
  14431. if (this.popupNode == undefined) {
  14432. // search the nodes for overlap, select the top one in case of multiple nodes
  14433. var nodes = this.nodes;
  14434. for (id in nodes) {
  14435. if (nodes.hasOwnProperty(id)) {
  14436. var node = nodes[id];
  14437. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14438. this.popupNode = node;
  14439. break;
  14440. }
  14441. }
  14442. }
  14443. }
  14444. if (this.popupNode === undefined) {
  14445. // search the edges for overlap
  14446. var edges = this.edges;
  14447. for (id in edges) {
  14448. if (edges.hasOwnProperty(id)) {
  14449. var edge = edges[id];
  14450. if (edge.connected && (edge.getTitle() !== undefined) &&
  14451. edge.isOverlappingWith(obj)) {
  14452. this.popupNode = edge;
  14453. break;
  14454. }
  14455. }
  14456. }
  14457. }
  14458. if (this.popupNode) {
  14459. // show popup message window
  14460. if (this.popupNode != lastPopupNode) {
  14461. var me = this;
  14462. if (!me.popup) {
  14463. me.popup = new Popup(me.frame, me.constants.tooltip);
  14464. }
  14465. // adjust a small offset such that the mouse cursor is located in the
  14466. // bottom left location of the popup, and you can easily move over the
  14467. // popup area
  14468. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14469. me.popup.setText(me.popupNode.getTitle());
  14470. me.popup.show();
  14471. }
  14472. }
  14473. else {
  14474. if (this.popup) {
  14475. this.popup.hide();
  14476. }
  14477. }
  14478. };
  14479. /**
  14480. * Check if the popup must be hided, which is the case when the mouse is no
  14481. * longer hovering on the object
  14482. * @param {{x:Number, y:Number}} pointer
  14483. * @private
  14484. */
  14485. Graph.prototype._checkHidePopup = function (pointer) {
  14486. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  14487. this.popupNode = undefined;
  14488. if (this.popup) {
  14489. this.popup.hide();
  14490. }
  14491. }
  14492. };
  14493. /**
  14494. * Set a new size for the graph
  14495. * @param {string} width Width in pixels or percentage (for example '800px'
  14496. * or '50%')
  14497. * @param {string} height Height in pixels or percentage (for example '400px'
  14498. * or '30%')
  14499. */
  14500. Graph.prototype.setSize = function(width, height) {
  14501. this.frame.style.width = width;
  14502. this.frame.style.height = height;
  14503. this.frame.canvas.style.width = '100%';
  14504. this.frame.canvas.style.height = '100%';
  14505. this.frame.canvas.width = this.frame.canvas.clientWidth;
  14506. this.frame.canvas.height = this.frame.canvas.clientHeight;
  14507. if (this.manipulationDiv !== undefined) {
  14508. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  14509. }
  14510. if (this.navigationDivs !== undefined) {
  14511. if (this.navigationDivs['wrapper'] !== undefined) {
  14512. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  14513. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  14514. }
  14515. }
  14516. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  14517. };
  14518. /**
  14519. * Set a data set with nodes for the graph
  14520. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14521. * @private
  14522. */
  14523. Graph.prototype._setNodes = function(nodes) {
  14524. var oldNodesData = this.nodesData;
  14525. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14526. this.nodesData = nodes;
  14527. }
  14528. else if (nodes instanceof Array) {
  14529. this.nodesData = new DataSet();
  14530. this.nodesData.add(nodes);
  14531. }
  14532. else if (!nodes) {
  14533. this.nodesData = new DataSet();
  14534. }
  14535. else {
  14536. throw new TypeError('Array or DataSet expected');
  14537. }
  14538. if (oldNodesData) {
  14539. // unsubscribe from old dataset
  14540. util.forEach(this.nodesListeners, function (callback, event) {
  14541. oldNodesData.off(event, callback);
  14542. });
  14543. }
  14544. // remove drawn nodes
  14545. this.nodes = {};
  14546. if (this.nodesData) {
  14547. // subscribe to new dataset
  14548. var me = this;
  14549. util.forEach(this.nodesListeners, function (callback, event) {
  14550. me.nodesData.on(event, callback);
  14551. });
  14552. // draw all new nodes
  14553. var ids = this.nodesData.getIds();
  14554. this._addNodes(ids);
  14555. }
  14556. this._updateSelection();
  14557. };
  14558. /**
  14559. * Add nodes
  14560. * @param {Number[] | String[]} ids
  14561. * @private
  14562. */
  14563. Graph.prototype._addNodes = function(ids) {
  14564. var id;
  14565. for (var i = 0, len = ids.length; i < len; i++) {
  14566. id = ids[i];
  14567. var data = this.nodesData.get(id);
  14568. var node = new Node(data, this.images, this.groups, this.constants);
  14569. this.nodes[id] = node; // note: this may replace an existing node
  14570. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  14571. var radius = 10 * 0.1*ids.length;
  14572. var angle = 2 * Math.PI * Math.random();
  14573. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  14574. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  14575. }
  14576. this.moving = true;
  14577. }
  14578. this._updateNodeIndexList();
  14579. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14580. this._resetLevels();
  14581. this._setupHierarchicalLayout();
  14582. }
  14583. this._updateCalculationNodes();
  14584. this._reconnectEdges();
  14585. this._updateValueRange(this.nodes);
  14586. this.updateLabels();
  14587. };
  14588. /**
  14589. * Update existing nodes, or create them when not yet existing
  14590. * @param {Number[] | String[]} ids
  14591. * @private
  14592. */
  14593. Graph.prototype._updateNodes = function(ids) {
  14594. var nodes = this.nodes,
  14595. nodesData = this.nodesData;
  14596. for (var i = 0, len = ids.length; i < len; i++) {
  14597. var id = ids[i];
  14598. var node = nodes[id];
  14599. var data = nodesData.get(id);
  14600. if (node) {
  14601. // update node
  14602. node.setProperties(data, this.constants);
  14603. }
  14604. else {
  14605. // create node
  14606. node = new Node(properties, this.images, this.groups, this.constants);
  14607. nodes[id] = node;
  14608. }
  14609. }
  14610. this.moving = true;
  14611. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14612. this._resetLevels();
  14613. this._setupHierarchicalLayout();
  14614. }
  14615. this._updateNodeIndexList();
  14616. this._reconnectEdges();
  14617. this._updateValueRange(nodes);
  14618. };
  14619. /**
  14620. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  14621. * @param {Number[] | String[]} ids
  14622. * @private
  14623. */
  14624. Graph.prototype._removeNodes = function(ids) {
  14625. var nodes = this.nodes;
  14626. for (var i = 0, len = ids.length; i < len; i++) {
  14627. var id = ids[i];
  14628. delete nodes[id];
  14629. }
  14630. this._updateNodeIndexList();
  14631. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14632. this._resetLevels();
  14633. this._setupHierarchicalLayout();
  14634. }
  14635. this._updateCalculationNodes();
  14636. this._reconnectEdges();
  14637. this._updateSelection();
  14638. this._updateValueRange(nodes);
  14639. };
  14640. /**
  14641. * Load edges by reading the data table
  14642. * @param {Array | DataSet | DataView} edges The data containing the edges.
  14643. * @private
  14644. * @private
  14645. */
  14646. Graph.prototype._setEdges = function(edges) {
  14647. var oldEdgesData = this.edgesData;
  14648. if (edges instanceof DataSet || edges instanceof DataView) {
  14649. this.edgesData = edges;
  14650. }
  14651. else if (edges instanceof Array) {
  14652. this.edgesData = new DataSet();
  14653. this.edgesData.add(edges);
  14654. }
  14655. else if (!edges) {
  14656. this.edgesData = new DataSet();
  14657. }
  14658. else {
  14659. throw new TypeError('Array or DataSet expected');
  14660. }
  14661. if (oldEdgesData) {
  14662. // unsubscribe from old dataset
  14663. util.forEach(this.edgesListeners, function (callback, event) {
  14664. oldEdgesData.off(event, callback);
  14665. });
  14666. }
  14667. // remove drawn edges
  14668. this.edges = {};
  14669. if (this.edgesData) {
  14670. // subscribe to new dataset
  14671. var me = this;
  14672. util.forEach(this.edgesListeners, function (callback, event) {
  14673. me.edgesData.on(event, callback);
  14674. });
  14675. // draw all new nodes
  14676. var ids = this.edgesData.getIds();
  14677. this._addEdges(ids);
  14678. }
  14679. this._reconnectEdges();
  14680. };
  14681. /**
  14682. * Add edges
  14683. * @param {Number[] | String[]} ids
  14684. * @private
  14685. */
  14686. Graph.prototype._addEdges = function (ids) {
  14687. var edges = this.edges,
  14688. edgesData = this.edgesData;
  14689. for (var i = 0, len = ids.length; i < len; i++) {
  14690. var id = ids[i];
  14691. var oldEdge = edges[id];
  14692. if (oldEdge) {
  14693. oldEdge.disconnect();
  14694. }
  14695. var data = edgesData.get(id, {"showInternalIds" : true});
  14696. edges[id] = new Edge(data, this, this.constants);
  14697. }
  14698. this.moving = true;
  14699. this._updateValueRange(edges);
  14700. this._createBezierNodes();
  14701. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14702. this._resetLevels();
  14703. this._setupHierarchicalLayout();
  14704. }
  14705. this._updateCalculationNodes();
  14706. };
  14707. /**
  14708. * Update existing edges, or create them when not yet existing
  14709. * @param {Number[] | String[]} ids
  14710. * @private
  14711. */
  14712. Graph.prototype._updateEdges = function (ids) {
  14713. var edges = this.edges,
  14714. edgesData = this.edgesData;
  14715. for (var i = 0, len = ids.length; i < len; i++) {
  14716. var id = ids[i];
  14717. var data = edgesData.get(id);
  14718. var edge = edges[id];
  14719. if (edge) {
  14720. // update edge
  14721. edge.disconnect();
  14722. edge.setProperties(data, this.constants);
  14723. edge.connect();
  14724. }
  14725. else {
  14726. // create edge
  14727. edge = new Edge(data, this, this.constants);
  14728. this.edges[id] = edge;
  14729. }
  14730. }
  14731. this._createBezierNodes();
  14732. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14733. this._resetLevels();
  14734. this._setupHierarchicalLayout();
  14735. }
  14736. this.moving = true;
  14737. this._updateValueRange(edges);
  14738. };
  14739. /**
  14740. * Remove existing edges. Non existing ids will be ignored
  14741. * @param {Number[] | String[]} ids
  14742. * @private
  14743. */
  14744. Graph.prototype._removeEdges = function (ids) {
  14745. var edges = this.edges;
  14746. for (var i = 0, len = ids.length; i < len; i++) {
  14747. var id = ids[i];
  14748. var edge = edges[id];
  14749. if (edge) {
  14750. if (edge.via != null) {
  14751. delete this.sectors['support']['nodes'][edge.via.id];
  14752. }
  14753. edge.disconnect();
  14754. delete edges[id];
  14755. }
  14756. }
  14757. this.moving = true;
  14758. this._updateValueRange(edges);
  14759. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  14760. this._resetLevels();
  14761. this._setupHierarchicalLayout();
  14762. }
  14763. this._updateCalculationNodes();
  14764. };
  14765. /**
  14766. * Reconnect all edges
  14767. * @private
  14768. */
  14769. Graph.prototype._reconnectEdges = function() {
  14770. var id,
  14771. nodes = this.nodes,
  14772. edges = this.edges;
  14773. for (id in nodes) {
  14774. if (nodes.hasOwnProperty(id)) {
  14775. nodes[id].edges = [];
  14776. }
  14777. }
  14778. for (id in edges) {
  14779. if (edges.hasOwnProperty(id)) {
  14780. var edge = edges[id];
  14781. edge.from = null;
  14782. edge.to = null;
  14783. edge.connect();
  14784. }
  14785. }
  14786. };
  14787. /**
  14788. * Update the values of all object in the given array according to the current
  14789. * value range of the objects in the array.
  14790. * @param {Object} obj An object containing a set of Edges or Nodes
  14791. * The objects must have a method getValue() and
  14792. * setValueRange(min, max).
  14793. * @private
  14794. */
  14795. Graph.prototype._updateValueRange = function(obj) {
  14796. var id;
  14797. // determine the range of the objects
  14798. var valueMin = undefined;
  14799. var valueMax = undefined;
  14800. for (id in obj) {
  14801. if (obj.hasOwnProperty(id)) {
  14802. var value = obj[id].getValue();
  14803. if (value !== undefined) {
  14804. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  14805. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  14806. }
  14807. }
  14808. }
  14809. // adjust the range of all objects
  14810. if (valueMin !== undefined && valueMax !== undefined) {
  14811. for (id in obj) {
  14812. if (obj.hasOwnProperty(id)) {
  14813. obj[id].setValueRange(valueMin, valueMax);
  14814. }
  14815. }
  14816. }
  14817. };
  14818. /**
  14819. * Redraw the graph with the current data
  14820. * chart will be resized too.
  14821. */
  14822. Graph.prototype.redraw = function() {
  14823. this.setSize(this.width, this.height);
  14824. this._redraw();
  14825. };
  14826. /**
  14827. * Redraw the graph with the current data
  14828. * @private
  14829. */
  14830. Graph.prototype._redraw = function() {
  14831. var ctx = this.frame.canvas.getContext('2d');
  14832. // clear the canvas
  14833. var w = this.frame.canvas.width;
  14834. var h = this.frame.canvas.height;
  14835. ctx.clearRect(0, 0, w, h);
  14836. // set scaling and translation
  14837. ctx.save();
  14838. ctx.translate(this.translation.x, this.translation.y);
  14839. ctx.scale(this.scale, this.scale);
  14840. this.canvasTopLeft = {
  14841. "x": this._canvasToX(0),
  14842. "y": this._canvasToY(0)
  14843. };
  14844. this.canvasBottomRight = {
  14845. "x": this._canvasToX(this.frame.canvas.clientWidth),
  14846. "y": this._canvasToY(this.frame.canvas.clientHeight)
  14847. };
  14848. this._doInAllSectors("_drawAllSectorNodes",ctx);
  14849. this._doInAllSectors("_drawEdges",ctx);
  14850. this._doInAllSectors("_drawNodes",ctx,false);
  14851. // this._doInSupportSector("_drawNodes",ctx,true);
  14852. // this._drawTree(ctx,"#F00F0F");
  14853. // restore original scaling and translation
  14854. ctx.restore();
  14855. };
  14856. /**
  14857. * Set the translation of the graph
  14858. * @param {Number} offsetX Horizontal offset
  14859. * @param {Number} offsetY Vertical offset
  14860. * @private
  14861. */
  14862. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  14863. if (this.translation === undefined) {
  14864. this.translation = {
  14865. x: 0,
  14866. y: 0
  14867. };
  14868. }
  14869. if (offsetX !== undefined) {
  14870. this.translation.x = offsetX;
  14871. }
  14872. if (offsetY !== undefined) {
  14873. this.translation.y = offsetY;
  14874. }
  14875. };
  14876. /**
  14877. * Get the translation of the graph
  14878. * @return {Object} translation An object with parameters x and y, both a number
  14879. * @private
  14880. */
  14881. Graph.prototype._getTranslation = function() {
  14882. return {
  14883. x: this.translation.x,
  14884. y: this.translation.y
  14885. };
  14886. };
  14887. /**
  14888. * Scale the graph
  14889. * @param {Number} scale Scaling factor 1.0 is unscaled
  14890. * @private
  14891. */
  14892. Graph.prototype._setScale = function(scale) {
  14893. this.scale = scale;
  14894. };
  14895. /**
  14896. * Get the current scale of the graph
  14897. * @return {Number} scale Scaling factor 1.0 is unscaled
  14898. * @private
  14899. */
  14900. Graph.prototype._getScale = function() {
  14901. return this.scale;
  14902. };
  14903. /**
  14904. * Convert a horizontal point on the HTML canvas to the x-value of the model
  14905. * @param {number} x
  14906. * @returns {number}
  14907. * @private
  14908. */
  14909. Graph.prototype._canvasToX = function(x) {
  14910. return (x - this.translation.x) / this.scale;
  14911. };
  14912. /**
  14913. * Convert an x-value in the model to a horizontal point on the HTML canvas
  14914. * @param {number} x
  14915. * @returns {number}
  14916. * @private
  14917. */
  14918. Graph.prototype._xToCanvas = function(x) {
  14919. return x * this.scale + this.translation.x;
  14920. };
  14921. /**
  14922. * Convert a vertical point on the HTML canvas to the y-value of the model
  14923. * @param {number} y
  14924. * @returns {number}
  14925. * @private
  14926. */
  14927. Graph.prototype._canvasToY = function(y) {
  14928. return (y - this.translation.y) / this.scale;
  14929. };
  14930. /**
  14931. * Convert an y-value in the model to a vertical point on the HTML canvas
  14932. * @param {number} y
  14933. * @returns {number}
  14934. * @private
  14935. */
  14936. Graph.prototype._yToCanvas = function(y) {
  14937. return y * this.scale + this.translation.y ;
  14938. };
  14939. /**
  14940. * Redraw all nodes
  14941. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  14942. * @param {CanvasRenderingContext2D} ctx
  14943. * @param {Boolean} [alwaysShow]
  14944. * @private
  14945. */
  14946. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  14947. if (alwaysShow === undefined) {
  14948. alwaysShow = false;
  14949. }
  14950. // first draw the unselected nodes
  14951. var nodes = this.nodes;
  14952. var selected = [];
  14953. for (var id in nodes) {
  14954. if (nodes.hasOwnProperty(id)) {
  14955. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  14956. if (nodes[id].isSelected()) {
  14957. selected.push(id);
  14958. }
  14959. else {
  14960. if (nodes[id].inArea() || alwaysShow) {
  14961. nodes[id].draw(ctx);
  14962. }
  14963. }
  14964. }
  14965. }
  14966. // draw the selected nodes on top
  14967. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  14968. if (nodes[selected[s]].inArea() || alwaysShow) {
  14969. nodes[selected[s]].draw(ctx);
  14970. }
  14971. }
  14972. };
  14973. /**
  14974. * Redraw all edges
  14975. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  14976. * @param {CanvasRenderingContext2D} ctx
  14977. * @private
  14978. */
  14979. Graph.prototype._drawEdges = function(ctx) {
  14980. var edges = this.edges;
  14981. for (var id in edges) {
  14982. if (edges.hasOwnProperty(id)) {
  14983. var edge = edges[id];
  14984. edge.setScale(this.scale);
  14985. if (edge.connected) {
  14986. edges[id].draw(ctx);
  14987. }
  14988. }
  14989. }
  14990. };
  14991. /**
  14992. * Find a stable position for all nodes
  14993. * @private
  14994. */
  14995. Graph.prototype._stabilize = function() {
  14996. if (this.constants.freezeForStabilization == true) {
  14997. this._freezeDefinedNodes();
  14998. }
  14999. // find stable position
  15000. var count = 0;
  15001. while (this.moving && count < this.constants.stabilizationIterations) {
  15002. this._physicsTick();
  15003. count++;
  15004. }
  15005. this.zoomExtent(false,true);
  15006. if (this.constants.freezeForStabilization == true) {
  15007. this._restoreFrozenNodes();
  15008. }
  15009. this.emit("stabilized",{iterations:count});
  15010. };
  15011. Graph.prototype._freezeDefinedNodes = function() {
  15012. var nodes = this.nodes;
  15013. for (var id in nodes) {
  15014. if (nodes.hasOwnProperty(id)) {
  15015. if (nodes[id].x != null && nodes[id].y != null) {
  15016. nodes[id].fixedData.x = nodes[id].xFixed;
  15017. nodes[id].fixedData.y = nodes[id].yFixed;
  15018. nodes[id].xFixed = true;
  15019. nodes[id].yFixed = true;
  15020. }
  15021. }
  15022. }
  15023. };
  15024. Graph.prototype._restoreFrozenNodes = function() {
  15025. var nodes = this.nodes;
  15026. for (var id in nodes) {
  15027. if (nodes.hasOwnProperty(id)) {
  15028. if (nodes[id].fixedData.x != null) {
  15029. nodes[id].xFixed = nodes[id].fixedData.x;
  15030. nodes[id].yFixed = nodes[id].fixedData.y;
  15031. }
  15032. }
  15033. }
  15034. };
  15035. /**
  15036. * Check if any of the nodes is still moving
  15037. * @param {number} vmin the minimum velocity considered as 'moving'
  15038. * @return {boolean} true if moving, false if non of the nodes is moving
  15039. * @private
  15040. */
  15041. Graph.prototype._isMoving = function(vmin) {
  15042. var nodes = this.nodes;
  15043. for (var id in nodes) {
  15044. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15045. return true;
  15046. }
  15047. }
  15048. return false;
  15049. };
  15050. /**
  15051. * /**
  15052. * Perform one discrete step for all nodes
  15053. *
  15054. * @private
  15055. */
  15056. Graph.prototype._discreteStepNodes = function() {
  15057. var interval = this.physicsDiscreteStepsize;
  15058. var nodes = this.nodes;
  15059. var nodeId;
  15060. var nodesPresent = false;
  15061. if (this.constants.maxVelocity > 0) {
  15062. for (nodeId in nodes) {
  15063. if (nodes.hasOwnProperty(nodeId)) {
  15064. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15065. nodesPresent = true;
  15066. }
  15067. }
  15068. }
  15069. else {
  15070. for (nodeId in nodes) {
  15071. if (nodes.hasOwnProperty(nodeId)) {
  15072. nodes[nodeId].discreteStep(interval);
  15073. nodesPresent = true;
  15074. }
  15075. }
  15076. }
  15077. if (nodesPresent == true) {
  15078. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15079. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15080. this.moving = true;
  15081. }
  15082. else {
  15083. this.moving = this._isMoving(vminCorrected);
  15084. }
  15085. }
  15086. };
  15087. Graph.prototype._physicsTick = function() {
  15088. if (!this.freezeSimulation) {
  15089. if (this.moving) {
  15090. this._doInAllActiveSectors("_initializeForceCalculation");
  15091. this._doInAllActiveSectors("_discreteStepNodes");
  15092. if (this.constants.smoothCurves) {
  15093. this._doInSupportSector("_discreteStepNodes");
  15094. }
  15095. this._findCenter(this._getRange())
  15096. }
  15097. }
  15098. };
  15099. /**
  15100. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15101. * It reschedules itself at the beginning of the function
  15102. *
  15103. * @private
  15104. */
  15105. Graph.prototype._animationStep = function() {
  15106. // reset the timer so a new scheduled animation step can be set
  15107. this.timer = undefined;
  15108. // handle the keyboad movement
  15109. this._handleNavigation();
  15110. // this schedules a new animation step
  15111. this.start();
  15112. // start the physics simulation
  15113. var calculationTime = Date.now();
  15114. var maxSteps = 1;
  15115. this._physicsTick();
  15116. var timeRequired = Date.now() - calculationTime;
  15117. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  15118. this._physicsTick();
  15119. timeRequired = Date.now() - calculationTime;
  15120. maxSteps++;
  15121. }
  15122. // start the rendering process
  15123. var renderTime = Date.now();
  15124. this._redraw();
  15125. this.renderTime = Date.now() - renderTime;
  15126. };
  15127. if (typeof window !== 'undefined') {
  15128. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15129. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15130. }
  15131. /**
  15132. * Schedule a animation step with the refreshrate interval.
  15133. */
  15134. Graph.prototype.start = function() {
  15135. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15136. if (!this.timer) {
  15137. var ua = navigator.userAgent.toLowerCase();
  15138. var requiresTimeout = false;
  15139. if (ua.indexOf('msie 9.0') != -1) { // IE 9
  15140. requiresTimeout = true;
  15141. }
  15142. else if (ua.indexOf('safari') != -1) { // safari
  15143. if (ua.indexOf('chrome') <= -1) {
  15144. requiresTimeout = true;
  15145. }
  15146. }
  15147. if (requiresTimeout == true) {
  15148. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15149. }
  15150. else{
  15151. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15152. }
  15153. }
  15154. }
  15155. else {
  15156. this._redraw();
  15157. }
  15158. };
  15159. /**
  15160. * Move the graph according to the keyboard presses.
  15161. *
  15162. * @private
  15163. */
  15164. Graph.prototype._handleNavigation = function() {
  15165. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15166. var translation = this._getTranslation();
  15167. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15168. }
  15169. if (this.zoomIncrement != 0) {
  15170. var center = {
  15171. x: this.frame.canvas.clientWidth / 2,
  15172. y: this.frame.canvas.clientHeight / 2
  15173. };
  15174. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15175. }
  15176. };
  15177. /**
  15178. * Freeze the _animationStep
  15179. */
  15180. Graph.prototype.toggleFreeze = function() {
  15181. if (this.freezeSimulation == false) {
  15182. this.freezeSimulation = true;
  15183. }
  15184. else {
  15185. this.freezeSimulation = false;
  15186. this.start();
  15187. }
  15188. };
  15189. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15190. if (disableStart === undefined) {
  15191. disableStart = true;
  15192. }
  15193. if (this.constants.smoothCurves == true) {
  15194. this._createBezierNodes();
  15195. }
  15196. else {
  15197. // delete the support nodes
  15198. this.sectors['support']['nodes'] = {};
  15199. for (var edgeId in this.edges) {
  15200. if (this.edges.hasOwnProperty(edgeId)) {
  15201. this.edges[edgeId].smooth = false;
  15202. this.edges[edgeId].via = null;
  15203. }
  15204. }
  15205. }
  15206. this._updateCalculationNodes();
  15207. if (!disableStart) {
  15208. this.moving = true;
  15209. this.start();
  15210. }
  15211. };
  15212. Graph.prototype._createBezierNodes = function() {
  15213. if (this.constants.smoothCurves == true) {
  15214. for (var edgeId in this.edges) {
  15215. if (this.edges.hasOwnProperty(edgeId)) {
  15216. var edge = this.edges[edgeId];
  15217. if (edge.via == null) {
  15218. edge.smooth = true;
  15219. var nodeId = "edgeId:".concat(edge.id);
  15220. this.sectors['support']['nodes'][nodeId] = new Node(
  15221. {id:nodeId,
  15222. mass:1,
  15223. shape:'circle',
  15224. image:"",
  15225. internalMultiplier:1
  15226. },{},{},this.constants);
  15227. edge.via = this.sectors['support']['nodes'][nodeId];
  15228. edge.via.parentEdgeId = edge.id;
  15229. edge.positionBezierNode();
  15230. }
  15231. }
  15232. }
  15233. }
  15234. };
  15235. Graph.prototype._initializeMixinLoaders = function () {
  15236. for (var mixinFunction in graphMixinLoaders) {
  15237. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15238. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15239. }
  15240. }
  15241. };
  15242. /**
  15243. * Load the XY positions of the nodes into the dataset.
  15244. */
  15245. Graph.prototype.storePosition = function() {
  15246. var dataArray = [];
  15247. for (var nodeId in this.nodes) {
  15248. if (this.nodes.hasOwnProperty(nodeId)) {
  15249. var node = this.nodes[nodeId];
  15250. var allowedToMoveX = !this.nodes.xFixed;
  15251. var allowedToMoveY = !this.nodes.yFixed;
  15252. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  15253. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15254. }
  15255. }
  15256. }
  15257. this.nodesData.update(dataArray);
  15258. };
  15259. /**
  15260. * vis.js module exports
  15261. */
  15262. var vis = {
  15263. util: util,
  15264. DataSet: DataSet,
  15265. DataView: DataView,
  15266. Range: Range,
  15267. Stack: Stack,
  15268. TimeStep: TimeStep,
  15269. components: {
  15270. items: {
  15271. Item: Item,
  15272. ItemBox: ItemBox,
  15273. ItemPoint: ItemPoint,
  15274. ItemRange: ItemRange
  15275. },
  15276. Component: Component,
  15277. Panel: Panel,
  15278. RootPanel: RootPanel,
  15279. ItemSet: ItemSet,
  15280. TimeAxis: TimeAxis
  15281. },
  15282. graph: {
  15283. Node: Node,
  15284. Edge: Edge,
  15285. Popup: Popup,
  15286. Groups: Groups,
  15287. Images: Images
  15288. },
  15289. Timeline: Timeline,
  15290. Graph: Graph
  15291. };
  15292. /**
  15293. * CommonJS module exports
  15294. */
  15295. if (typeof exports !== 'undefined') {
  15296. exports = vis;
  15297. }
  15298. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15299. module.exports = vis;
  15300. }
  15301. /**
  15302. * AMD module exports
  15303. */
  15304. if (typeof(define) === 'function') {
  15305. define(function () {
  15306. return vis;
  15307. });
  15308. }
  15309. /**
  15310. * Window exports
  15311. */
  15312. if (typeof window !== 'undefined') {
  15313. // attach the module to the window, load as a regular javascript file
  15314. window['vis'] = vis;
  15315. }
  15316. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15317. /**
  15318. * Expose `Emitter`.
  15319. */
  15320. module.exports = Emitter;
  15321. /**
  15322. * Initialize a new `Emitter`.
  15323. *
  15324. * @api public
  15325. */
  15326. function Emitter(obj) {
  15327. if (obj) return mixin(obj);
  15328. };
  15329. /**
  15330. * Mixin the emitter properties.
  15331. *
  15332. * @param {Object} obj
  15333. * @return {Object}
  15334. * @api private
  15335. */
  15336. function mixin(obj) {
  15337. for (var key in Emitter.prototype) {
  15338. obj[key] = Emitter.prototype[key];
  15339. }
  15340. return obj;
  15341. }
  15342. /**
  15343. * Listen on the given `event` with `fn`.
  15344. *
  15345. * @param {String} event
  15346. * @param {Function} fn
  15347. * @return {Emitter}
  15348. * @api public
  15349. */
  15350. Emitter.prototype.on =
  15351. Emitter.prototype.addEventListener = function(event, fn){
  15352. this._callbacks = this._callbacks || {};
  15353. (this._callbacks[event] = this._callbacks[event] || [])
  15354. .push(fn);
  15355. return this;
  15356. };
  15357. /**
  15358. * Adds an `event` listener that will be invoked a single
  15359. * time then automatically removed.
  15360. *
  15361. * @param {String} event
  15362. * @param {Function} fn
  15363. * @return {Emitter}
  15364. * @api public
  15365. */
  15366. Emitter.prototype.once = function(event, fn){
  15367. var self = this;
  15368. this._callbacks = this._callbacks || {};
  15369. function on() {
  15370. self.off(event, on);
  15371. fn.apply(this, arguments);
  15372. }
  15373. on.fn = fn;
  15374. this.on(event, on);
  15375. return this;
  15376. };
  15377. /**
  15378. * Remove the given callback for `event` or all
  15379. * registered callbacks.
  15380. *
  15381. * @param {String} event
  15382. * @param {Function} fn
  15383. * @return {Emitter}
  15384. * @api public
  15385. */
  15386. Emitter.prototype.off =
  15387. Emitter.prototype.removeListener =
  15388. Emitter.prototype.removeAllListeners =
  15389. Emitter.prototype.removeEventListener = function(event, fn){
  15390. this._callbacks = this._callbacks || {};
  15391. // all
  15392. if (0 == arguments.length) {
  15393. this._callbacks = {};
  15394. return this;
  15395. }
  15396. // specific event
  15397. var callbacks = this._callbacks[event];
  15398. if (!callbacks) return this;
  15399. // remove all handlers
  15400. if (1 == arguments.length) {
  15401. delete this._callbacks[event];
  15402. return this;
  15403. }
  15404. // remove specific handler
  15405. var cb;
  15406. for (var i = 0; i < callbacks.length; i++) {
  15407. cb = callbacks[i];
  15408. if (cb === fn || cb.fn === fn) {
  15409. callbacks.splice(i, 1);
  15410. break;
  15411. }
  15412. }
  15413. return this;
  15414. };
  15415. /**
  15416. * Emit `event` with the given args.
  15417. *
  15418. * @param {String} event
  15419. * @param {Mixed} ...
  15420. * @return {Emitter}
  15421. */
  15422. Emitter.prototype.emit = function(event){
  15423. this._callbacks = this._callbacks || {};
  15424. var args = [].slice.call(arguments, 1)
  15425. , callbacks = this._callbacks[event];
  15426. if (callbacks) {
  15427. callbacks = callbacks.slice(0);
  15428. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15429. callbacks[i].apply(this, args);
  15430. }
  15431. }
  15432. return this;
  15433. };
  15434. /**
  15435. * Return array of callbacks for `event`.
  15436. *
  15437. * @param {String} event
  15438. * @return {Array}
  15439. * @api public
  15440. */
  15441. Emitter.prototype.listeners = function(event){
  15442. this._callbacks = this._callbacks || {};
  15443. return this._callbacks[event] || [];
  15444. };
  15445. /**
  15446. * Check if this emitter has `event` handlers.
  15447. *
  15448. * @param {String} event
  15449. * @return {Boolean}
  15450. * @api public
  15451. */
  15452. Emitter.prototype.hasListeners = function(event){
  15453. return !! this.listeners(event).length;
  15454. };
  15455. },{}],3:[function(require,module,exports){
  15456. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15457. * http://eightmedia.github.com/hammer.js
  15458. *
  15459. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  15460. * Licensed under the MIT license */
  15461. (function(window, undefined) {
  15462. 'use strict';
  15463. /**
  15464. * Hammer
  15465. * use this to create instances
  15466. * @param {HTMLElement} element
  15467. * @param {Object} options
  15468. * @returns {Hammer.Instance}
  15469. * @constructor
  15470. */
  15471. var Hammer = function(element, options) {
  15472. return new Hammer.Instance(element, options || {});
  15473. };
  15474. // default settings
  15475. Hammer.defaults = {
  15476. // add styles and attributes to the element to prevent the browser from doing
  15477. // its native behavior. this doesnt prevent the scrolling, but cancels
  15478. // the contextmenu, tap highlighting etc
  15479. // set to false to disable this
  15480. stop_browser_behavior: {
  15481. // this also triggers onselectstart=false for IE
  15482. userSelect: 'none',
  15483. // this makes the element blocking in IE10 >, you could experiment with the value
  15484. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  15485. touchAction: 'none',
  15486. touchCallout: 'none',
  15487. contentZooming: 'none',
  15488. userDrag: 'none',
  15489. tapHighlightColor: 'rgba(0,0,0,0)'
  15490. }
  15491. // more settings are defined per gesture at gestures.js
  15492. };
  15493. // detect touchevents
  15494. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  15495. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  15496. // dont use mouseevents on mobile devices
  15497. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  15498. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  15499. // eventtypes per touchevent (start, move, end)
  15500. // are filled by Hammer.event.determineEventTypes on setup
  15501. Hammer.EVENT_TYPES = {};
  15502. // direction defines
  15503. Hammer.DIRECTION_DOWN = 'down';
  15504. Hammer.DIRECTION_LEFT = 'left';
  15505. Hammer.DIRECTION_UP = 'up';
  15506. Hammer.DIRECTION_RIGHT = 'right';
  15507. // pointer type
  15508. Hammer.POINTER_MOUSE = 'mouse';
  15509. Hammer.POINTER_TOUCH = 'touch';
  15510. Hammer.POINTER_PEN = 'pen';
  15511. // touch event defines
  15512. Hammer.EVENT_START = 'start';
  15513. Hammer.EVENT_MOVE = 'move';
  15514. Hammer.EVENT_END = 'end';
  15515. // hammer document where the base events are added at
  15516. Hammer.DOCUMENT = document;
  15517. // plugins namespace
  15518. Hammer.plugins = {};
  15519. // if the window events are set...
  15520. Hammer.READY = false;
  15521. /**
  15522. * setup events to detect gestures on the document
  15523. */
  15524. function setup() {
  15525. if(Hammer.READY) {
  15526. return;
  15527. }
  15528. // find what eventtypes we add listeners to
  15529. Hammer.event.determineEventTypes();
  15530. // Register all gestures inside Hammer.gestures
  15531. for(var name in Hammer.gestures) {
  15532. if(Hammer.gestures.hasOwnProperty(name)) {
  15533. Hammer.detection.register(Hammer.gestures[name]);
  15534. }
  15535. }
  15536. // Add touch events on the document
  15537. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  15538. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  15539. // Hammer is ready...!
  15540. Hammer.READY = true;
  15541. }
  15542. /**
  15543. * create new hammer instance
  15544. * all methods should return the instance itself, so it is chainable.
  15545. * @param {HTMLElement} element
  15546. * @param {Object} [options={}]
  15547. * @returns {Hammer.Instance}
  15548. * @constructor
  15549. */
  15550. Hammer.Instance = function(element, options) {
  15551. var self = this;
  15552. // setup HammerJS window events and register all gestures
  15553. // this also sets up the default options
  15554. setup();
  15555. this.element = element;
  15556. // start/stop detection option
  15557. this.enabled = true;
  15558. // merge options
  15559. this.options = Hammer.utils.extend(
  15560. Hammer.utils.extend({}, Hammer.defaults),
  15561. options || {});
  15562. // add some css to the element to prevent the browser from doing its native behavoir
  15563. if(this.options.stop_browser_behavior) {
  15564. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  15565. }
  15566. // start detection on touchstart
  15567. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  15568. if(self.enabled) {
  15569. Hammer.detection.startDetect(self, ev);
  15570. }
  15571. });
  15572. // return instance
  15573. return this;
  15574. };
  15575. Hammer.Instance.prototype = {
  15576. /**
  15577. * bind events to the instance
  15578. * @param {String} gesture
  15579. * @param {Function} handler
  15580. * @returns {Hammer.Instance}
  15581. */
  15582. on: function onEvent(gesture, handler){
  15583. var gestures = gesture.split(' ');
  15584. for(var t=0; t<gestures.length; t++) {
  15585. this.element.addEventListener(gestures[t], handler, false);
  15586. }
  15587. return this;
  15588. },
  15589. /**
  15590. * unbind events to the instance
  15591. * @param {String} gesture
  15592. * @param {Function} handler
  15593. * @returns {Hammer.Instance}
  15594. */
  15595. off: function offEvent(gesture, handler){
  15596. var gestures = gesture.split(' ');
  15597. for(var t=0; t<gestures.length; t++) {
  15598. this.element.removeEventListener(gestures[t], handler, false);
  15599. }
  15600. return this;
  15601. },
  15602. /**
  15603. * trigger gesture event
  15604. * @param {String} gesture
  15605. * @param {Object} eventData
  15606. * @returns {Hammer.Instance}
  15607. */
  15608. trigger: function triggerEvent(gesture, eventData){
  15609. // create DOM event
  15610. var event = Hammer.DOCUMENT.createEvent('Event');
  15611. event.initEvent(gesture, true, true);
  15612. event.gesture = eventData;
  15613. // trigger on the target if it is in the instance element,
  15614. // this is for event delegation tricks
  15615. var element = this.element;
  15616. if(Hammer.utils.hasParent(eventData.target, element)) {
  15617. element = eventData.target;
  15618. }
  15619. element.dispatchEvent(event);
  15620. return this;
  15621. },
  15622. /**
  15623. * enable of disable hammer.js detection
  15624. * @param {Boolean} state
  15625. * @returns {Hammer.Instance}
  15626. */
  15627. enable: function enable(state) {
  15628. this.enabled = state;
  15629. return this;
  15630. }
  15631. };
  15632. /**
  15633. * this holds the last move event,
  15634. * used to fix empty touchend issue
  15635. * see the onTouch event for an explanation
  15636. * @type {Object}
  15637. */
  15638. var last_move_event = null;
  15639. /**
  15640. * when the mouse is hold down, this is true
  15641. * @type {Boolean}
  15642. */
  15643. var enable_detect = false;
  15644. /**
  15645. * when touch events have been fired, this is true
  15646. * @type {Boolean}
  15647. */
  15648. var touch_triggered = false;
  15649. Hammer.event = {
  15650. /**
  15651. * simple addEventListener
  15652. * @param {HTMLElement} element
  15653. * @param {String} type
  15654. * @param {Function} handler
  15655. */
  15656. bindDom: function(element, type, handler) {
  15657. var types = type.split(' ');
  15658. for(var t=0; t<types.length; t++) {
  15659. element.addEventListener(types[t], handler, false);
  15660. }
  15661. },
  15662. /**
  15663. * touch events with mouse fallback
  15664. * @param {HTMLElement} element
  15665. * @param {String} eventType like Hammer.EVENT_MOVE
  15666. * @param {Function} handler
  15667. */
  15668. onTouch: function onTouch(element, eventType, handler) {
  15669. var self = this;
  15670. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  15671. var sourceEventType = ev.type.toLowerCase();
  15672. // onmouseup, but when touchend has been fired we do nothing.
  15673. // this is for touchdevices which also fire a mouseup on touchend
  15674. if(sourceEventType.match(/mouse/) && touch_triggered) {
  15675. return;
  15676. }
  15677. // mousebutton must be down or a touch event
  15678. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  15679. sourceEventType.match(/pointerdown/) || // pointerevents touch
  15680. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  15681. ){
  15682. enable_detect = true;
  15683. }
  15684. // we are in a touch event, set the touch triggered bool to true,
  15685. // this for the conflicts that may occur on ios and android
  15686. if(sourceEventType.match(/touch|pointer/)) {
  15687. touch_triggered = true;
  15688. }
  15689. // count the total touches on the screen
  15690. var count_touches = 0;
  15691. // when touch has been triggered in this detection session
  15692. // and we are now handling a mouse event, we stop that to prevent conflicts
  15693. if(enable_detect) {
  15694. // update pointerevent
  15695. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  15696. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15697. }
  15698. // touch
  15699. else if(sourceEventType.match(/touch/)) {
  15700. count_touches = ev.touches.length;
  15701. }
  15702. // mouse
  15703. else if(!touch_triggered) {
  15704. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  15705. }
  15706. // if we are in a end event, but when we remove one touch and
  15707. // we still have enough, set eventType to move
  15708. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  15709. eventType = Hammer.EVENT_MOVE;
  15710. }
  15711. // no touches, force the end event
  15712. else if(!count_touches) {
  15713. eventType = Hammer.EVENT_END;
  15714. }
  15715. // because touchend has no touches, and we often want to use these in our gestures,
  15716. // we send the last move event as our eventData in touchend
  15717. if(!count_touches && last_move_event !== null) {
  15718. ev = last_move_event;
  15719. }
  15720. // store the last move event
  15721. else {
  15722. last_move_event = ev;
  15723. }
  15724. // trigger the handler
  15725. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  15726. // remove pointerevent from list
  15727. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  15728. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15729. }
  15730. }
  15731. //debug(sourceEventType +" "+ eventType);
  15732. // on the end we reset everything
  15733. if(!count_touches) {
  15734. last_move_event = null;
  15735. enable_detect = false;
  15736. touch_triggered = false;
  15737. Hammer.PointerEvent.reset();
  15738. }
  15739. });
  15740. },
  15741. /**
  15742. * we have different events for each device/browser
  15743. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  15744. */
  15745. determineEventTypes: function determineEventTypes() {
  15746. // determine the eventtype we want to set
  15747. var types;
  15748. // pointerEvents magic
  15749. if(Hammer.HAS_POINTEREVENTS) {
  15750. types = Hammer.PointerEvent.getEvents();
  15751. }
  15752. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  15753. else if(Hammer.NO_MOUSEEVENTS) {
  15754. types = [
  15755. 'touchstart',
  15756. 'touchmove',
  15757. 'touchend touchcancel'];
  15758. }
  15759. // for non pointer events browsers and mixed browsers,
  15760. // like chrome on windows8 touch laptop
  15761. else {
  15762. types = [
  15763. 'touchstart mousedown',
  15764. 'touchmove mousemove',
  15765. 'touchend touchcancel mouseup'];
  15766. }
  15767. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  15768. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  15769. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  15770. },
  15771. /**
  15772. * create touchlist depending on the event
  15773. * @param {Object} ev
  15774. * @param {String} eventType used by the fakemultitouch plugin
  15775. */
  15776. getTouchList: function getTouchList(ev/*, eventType*/) {
  15777. // get the fake pointerEvent touchlist
  15778. if(Hammer.HAS_POINTEREVENTS) {
  15779. return Hammer.PointerEvent.getTouchList();
  15780. }
  15781. // get the touchlist
  15782. else if(ev.touches) {
  15783. return ev.touches;
  15784. }
  15785. // make fake touchlist from mouse position
  15786. else {
  15787. return [{
  15788. identifier: 1,
  15789. pageX: ev.pageX,
  15790. pageY: ev.pageY,
  15791. target: ev.target
  15792. }];
  15793. }
  15794. },
  15795. /**
  15796. * collect event data for Hammer js
  15797. * @param {HTMLElement} element
  15798. * @param {String} eventType like Hammer.EVENT_MOVE
  15799. * @param {Object} eventData
  15800. */
  15801. collectEventData: function collectEventData(element, eventType, ev) {
  15802. var touches = this.getTouchList(ev, eventType);
  15803. // find out pointerType
  15804. var pointerType = Hammer.POINTER_TOUCH;
  15805. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  15806. pointerType = Hammer.POINTER_MOUSE;
  15807. }
  15808. return {
  15809. center : Hammer.utils.getCenter(touches),
  15810. timeStamp : new Date().getTime(),
  15811. target : ev.target,
  15812. touches : touches,
  15813. eventType : eventType,
  15814. pointerType : pointerType,
  15815. srcEvent : ev,
  15816. /**
  15817. * prevent the browser default actions
  15818. * mostly used to disable scrolling of the browser
  15819. */
  15820. preventDefault: function() {
  15821. if(this.srcEvent.preventManipulation) {
  15822. this.srcEvent.preventManipulation();
  15823. }
  15824. if(this.srcEvent.preventDefault) {
  15825. this.srcEvent.preventDefault();
  15826. }
  15827. },
  15828. /**
  15829. * stop bubbling the event up to its parents
  15830. */
  15831. stopPropagation: function() {
  15832. this.srcEvent.stopPropagation();
  15833. },
  15834. /**
  15835. * immediately stop gesture detection
  15836. * might be useful after a swipe was detected
  15837. * @return {*}
  15838. */
  15839. stopDetect: function() {
  15840. return Hammer.detection.stopDetect();
  15841. }
  15842. };
  15843. }
  15844. };
  15845. Hammer.PointerEvent = {
  15846. /**
  15847. * holds all pointers
  15848. * @type {Object}
  15849. */
  15850. pointers: {},
  15851. /**
  15852. * get a list of pointers
  15853. * @returns {Array} touchlist
  15854. */
  15855. getTouchList: function() {
  15856. var self = this;
  15857. var touchlist = [];
  15858. // we can use forEach since pointerEvents only is in IE10
  15859. Object.keys(self.pointers).sort().forEach(function(id) {
  15860. touchlist.push(self.pointers[id]);
  15861. });
  15862. return touchlist;
  15863. },
  15864. /**
  15865. * update the position of a pointer
  15866. * @param {String} type Hammer.EVENT_END
  15867. * @param {Object} pointerEvent
  15868. */
  15869. updatePointer: function(type, pointerEvent) {
  15870. if(type == Hammer.EVENT_END) {
  15871. this.pointers = {};
  15872. }
  15873. else {
  15874. pointerEvent.identifier = pointerEvent.pointerId;
  15875. this.pointers[pointerEvent.pointerId] = pointerEvent;
  15876. }
  15877. return Object.keys(this.pointers).length;
  15878. },
  15879. /**
  15880. * check if ev matches pointertype
  15881. * @param {String} pointerType Hammer.POINTER_MOUSE
  15882. * @param {PointerEvent} ev
  15883. */
  15884. matchType: function(pointerType, ev) {
  15885. if(!ev.pointerType) {
  15886. return false;
  15887. }
  15888. var types = {};
  15889. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  15890. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  15891. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  15892. return types[pointerType];
  15893. },
  15894. /**
  15895. * get events
  15896. */
  15897. getEvents: function() {
  15898. return [
  15899. 'pointerdown MSPointerDown',
  15900. 'pointermove MSPointerMove',
  15901. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  15902. ];
  15903. },
  15904. /**
  15905. * reset the list
  15906. */
  15907. reset: function() {
  15908. this.pointers = {};
  15909. }
  15910. };
  15911. Hammer.utils = {
  15912. /**
  15913. * extend method,
  15914. * also used for cloning when dest is an empty object
  15915. * @param {Object} dest
  15916. * @param {Object} src
  15917. * @parm {Boolean} merge do a merge
  15918. * @returns {Object} dest
  15919. */
  15920. extend: function extend(dest, src, merge) {
  15921. for (var key in src) {
  15922. if(dest[key] !== undefined && merge) {
  15923. continue;
  15924. }
  15925. dest[key] = src[key];
  15926. }
  15927. return dest;
  15928. },
  15929. /**
  15930. * find if a node is in the given parent
  15931. * used for event delegation tricks
  15932. * @param {HTMLElement} node
  15933. * @param {HTMLElement} parent
  15934. * @returns {boolean} has_parent
  15935. */
  15936. hasParent: function(node, parent) {
  15937. while(node){
  15938. if(node == parent) {
  15939. return true;
  15940. }
  15941. node = node.parentNode;
  15942. }
  15943. return false;
  15944. },
  15945. /**
  15946. * get the center of all the touches
  15947. * @param {Array} touches
  15948. * @returns {Object} center
  15949. */
  15950. getCenter: function getCenter(touches) {
  15951. var valuesX = [], valuesY = [];
  15952. for(var t= 0,len=touches.length; t<len; t++) {
  15953. valuesX.push(touches[t].pageX);
  15954. valuesY.push(touches[t].pageY);
  15955. }
  15956. return {
  15957. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  15958. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  15959. };
  15960. },
  15961. /**
  15962. * calculate the velocity between two points
  15963. * @param {Number} delta_time
  15964. * @param {Number} delta_x
  15965. * @param {Number} delta_y
  15966. * @returns {Object} velocity
  15967. */
  15968. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  15969. return {
  15970. x: Math.abs(delta_x / delta_time) || 0,
  15971. y: Math.abs(delta_y / delta_time) || 0
  15972. };
  15973. },
  15974. /**
  15975. * calculate the angle between two coordinates
  15976. * @param {Touch} touch1
  15977. * @param {Touch} touch2
  15978. * @returns {Number} angle
  15979. */
  15980. getAngle: function getAngle(touch1, touch2) {
  15981. var y = touch2.pageY - touch1.pageY,
  15982. x = touch2.pageX - touch1.pageX;
  15983. return Math.atan2(y, x) * 180 / Math.PI;
  15984. },
  15985. /**
  15986. * angle to direction define
  15987. * @param {Touch} touch1
  15988. * @param {Touch} touch2
  15989. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  15990. */
  15991. getDirection: function getDirection(touch1, touch2) {
  15992. var x = Math.abs(touch1.pageX - touch2.pageX),
  15993. y = Math.abs(touch1.pageY - touch2.pageY);
  15994. if(x >= y) {
  15995. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  15996. }
  15997. else {
  15998. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  15999. }
  16000. },
  16001. /**
  16002. * calculate the distance between two touches
  16003. * @param {Touch} touch1
  16004. * @param {Touch} touch2
  16005. * @returns {Number} distance
  16006. */
  16007. getDistance: function getDistance(touch1, touch2) {
  16008. var x = touch2.pageX - touch1.pageX,
  16009. y = touch2.pageY - touch1.pageY;
  16010. return Math.sqrt((x*x) + (y*y));
  16011. },
  16012. /**
  16013. * calculate the scale factor between two touchLists (fingers)
  16014. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16015. * @param {Array} start
  16016. * @param {Array} end
  16017. * @returns {Number} scale
  16018. */
  16019. getScale: function getScale(start, end) {
  16020. // need two fingers...
  16021. if(start.length >= 2 && end.length >= 2) {
  16022. return this.getDistance(end[0], end[1]) /
  16023. this.getDistance(start[0], start[1]);
  16024. }
  16025. return 1;
  16026. },
  16027. /**
  16028. * calculate the rotation degrees between two touchLists (fingers)
  16029. * @param {Array} start
  16030. * @param {Array} end
  16031. * @returns {Number} rotation
  16032. */
  16033. getRotation: function getRotation(start, end) {
  16034. // need two fingers
  16035. if(start.length >= 2 && end.length >= 2) {
  16036. return this.getAngle(end[1], end[0]) -
  16037. this.getAngle(start[1], start[0]);
  16038. }
  16039. return 0;
  16040. },
  16041. /**
  16042. * boolean if the direction is vertical
  16043. * @param {String} direction
  16044. * @returns {Boolean} is_vertical
  16045. */
  16046. isVertical: function isVertical(direction) {
  16047. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16048. },
  16049. /**
  16050. * stop browser default behavior with css props
  16051. * @param {HtmlElement} element
  16052. * @param {Object} css_props
  16053. */
  16054. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16055. var prop,
  16056. vendors = ['webkit','khtml','moz','ms','o',''];
  16057. if(!css_props || !element.style) {
  16058. return;
  16059. }
  16060. // with css properties for modern browsers
  16061. for(var i = 0; i < vendors.length; i++) {
  16062. for(var p in css_props) {
  16063. if(css_props.hasOwnProperty(p)) {
  16064. prop = p;
  16065. // vender prefix at the property
  16066. if(vendors[i]) {
  16067. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16068. }
  16069. // set the style
  16070. element.style[prop] = css_props[p];
  16071. }
  16072. }
  16073. }
  16074. // also the disable onselectstart
  16075. if(css_props.userSelect == 'none') {
  16076. element.onselectstart = function() {
  16077. return false;
  16078. };
  16079. }
  16080. }
  16081. };
  16082. Hammer.detection = {
  16083. // contains all registred Hammer.gestures in the correct order
  16084. gestures: [],
  16085. // data of the current Hammer.gesture detection session
  16086. current: null,
  16087. // the previous Hammer.gesture session data
  16088. // is a full clone of the previous gesture.current object
  16089. previous: null,
  16090. // when this becomes true, no gestures are fired
  16091. stopped: false,
  16092. /**
  16093. * start Hammer.gesture detection
  16094. * @param {Hammer.Instance} inst
  16095. * @param {Object} eventData
  16096. */
  16097. startDetect: function startDetect(inst, eventData) {
  16098. // already busy with a Hammer.gesture detection on an element
  16099. if(this.current) {
  16100. return;
  16101. }
  16102. this.stopped = false;
  16103. this.current = {
  16104. inst : inst, // reference to HammerInstance we're working for
  16105. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16106. lastEvent : false, // last eventData
  16107. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16108. };
  16109. this.detect(eventData);
  16110. },
  16111. /**
  16112. * Hammer.gesture detection
  16113. * @param {Object} eventData
  16114. * @param {Object} eventData
  16115. */
  16116. detect: function detect(eventData) {
  16117. if(!this.current || this.stopped) {
  16118. return;
  16119. }
  16120. // extend event data with calculations about scale, distance etc
  16121. eventData = this.extendEventData(eventData);
  16122. // instance options
  16123. var inst_options = this.current.inst.options;
  16124. // call Hammer.gesture handlers
  16125. for(var g=0,len=this.gestures.length; g<len; g++) {
  16126. var gesture = this.gestures[g];
  16127. // only when the instance options have enabled this gesture
  16128. if(!this.stopped && inst_options[gesture.name] !== false) {
  16129. // if a handler returns false, we stop with the detection
  16130. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16131. this.stopDetect();
  16132. break;
  16133. }
  16134. }
  16135. }
  16136. // store as previous event event
  16137. if(this.current) {
  16138. this.current.lastEvent = eventData;
  16139. }
  16140. // endevent, but not the last touch, so dont stop
  16141. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16142. this.stopDetect();
  16143. }
  16144. return eventData;
  16145. },
  16146. /**
  16147. * clear the Hammer.gesture vars
  16148. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16149. * to stop other Hammer.gestures from being fired
  16150. */
  16151. stopDetect: function stopDetect() {
  16152. // clone current data to the store as the previous gesture
  16153. // used for the double tap gesture, since this is an other gesture detect session
  16154. this.previous = Hammer.utils.extend({}, this.current);
  16155. // reset the current
  16156. this.current = null;
  16157. // stopped!
  16158. this.stopped = true;
  16159. },
  16160. /**
  16161. * extend eventData for Hammer.gestures
  16162. * @param {Object} ev
  16163. * @returns {Object} ev
  16164. */
  16165. extendEventData: function extendEventData(ev) {
  16166. var startEv = this.current.startEvent;
  16167. // if the touches change, set the new touches over the startEvent touches
  16168. // this because touchevents don't have all the touches on touchstart, or the
  16169. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16170. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16171. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16172. // extend 1 level deep to get the touchlist with the touch objects
  16173. startEv.touches = [];
  16174. for(var i=0,len=ev.touches.length; i<len; i++) {
  16175. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16176. }
  16177. }
  16178. var delta_time = ev.timeStamp - startEv.timeStamp,
  16179. delta_x = ev.center.pageX - startEv.center.pageX,
  16180. delta_y = ev.center.pageY - startEv.center.pageY,
  16181. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16182. Hammer.utils.extend(ev, {
  16183. deltaTime : delta_time,
  16184. deltaX : delta_x,
  16185. deltaY : delta_y,
  16186. velocityX : velocity.x,
  16187. velocityY : velocity.y,
  16188. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16189. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16190. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16191. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16192. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16193. startEvent : startEv
  16194. });
  16195. return ev;
  16196. },
  16197. /**
  16198. * register new gesture
  16199. * @param {Object} gesture object, see gestures.js for documentation
  16200. * @returns {Array} gestures
  16201. */
  16202. register: function register(gesture) {
  16203. // add an enable gesture options if there is no given
  16204. var options = gesture.defaults || {};
  16205. if(options[gesture.name] === undefined) {
  16206. options[gesture.name] = true;
  16207. }
  16208. // extend Hammer default options with the Hammer.gesture options
  16209. Hammer.utils.extend(Hammer.defaults, options, true);
  16210. // set its index
  16211. gesture.index = gesture.index || 1000;
  16212. // add Hammer.gesture to the list
  16213. this.gestures.push(gesture);
  16214. // sort the list by index
  16215. this.gestures.sort(function(a, b) {
  16216. if (a.index < b.index) {
  16217. return -1;
  16218. }
  16219. if (a.index > b.index) {
  16220. return 1;
  16221. }
  16222. return 0;
  16223. });
  16224. return this.gestures;
  16225. }
  16226. };
  16227. Hammer.gestures = Hammer.gestures || {};
  16228. /**
  16229. * Custom gestures
  16230. * ==============================
  16231. *
  16232. * Gesture object
  16233. * --------------------
  16234. * The object structure of a gesture:
  16235. *
  16236. * { name: 'mygesture',
  16237. * index: 1337,
  16238. * defaults: {
  16239. * mygesture_option: true
  16240. * }
  16241. * handler: function(type, ev, inst) {
  16242. * // trigger gesture event
  16243. * inst.trigger(this.name, ev);
  16244. * }
  16245. * }
  16246. * @param {String} name
  16247. * this should be the name of the gesture, lowercase
  16248. * it is also being used to disable/enable the gesture per instance config.
  16249. *
  16250. * @param {Number} [index=1000]
  16251. * the index of the gesture, where it is going to be in the stack of gestures detection
  16252. * like when you build an gesture that depends on the drag gesture, it is a good
  16253. * idea to place it after the index of the drag gesture.
  16254. *
  16255. * @param {Object} [defaults={}]
  16256. * the default settings of the gesture. these are added to the instance settings,
  16257. * and can be overruled per instance. you can also add the name of the gesture,
  16258. * but this is also added by default (and set to true).
  16259. *
  16260. * @param {Function} handler
  16261. * this handles the gesture detection of your custom gesture and receives the
  16262. * following arguments:
  16263. *
  16264. * @param {Object} eventData
  16265. * event data containing the following properties:
  16266. * timeStamp {Number} time the event occurred
  16267. * target {HTMLElement} target element
  16268. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16269. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16270. * center {Object} center position of the touches. contains pageX and pageY
  16271. * deltaTime {Number} the total time of the touches in the screen
  16272. * deltaX {Number} the delta on x axis we haved moved
  16273. * deltaY {Number} the delta on y axis we haved moved
  16274. * velocityX {Number} the velocity on the x
  16275. * velocityY {Number} the velocity on y
  16276. * angle {Number} the angle we are moving
  16277. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16278. * distance {Number} the distance we haved moved
  16279. * scale {Number} scaling of the touches, needs 2 touches
  16280. * rotation {Number} rotation of the touches, needs 2 touches *
  16281. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16282. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16283. * startEvent {Object} contains the same properties as above,
  16284. * but from the first touch. this is used to calculate
  16285. * distances, deltaTime, scaling etc
  16286. *
  16287. * @param {Hammer.Instance} inst
  16288. * the instance we are doing the detection for. you can get the options from
  16289. * the inst.options object and trigger the gesture event by calling inst.trigger
  16290. *
  16291. *
  16292. * Handle gestures
  16293. * --------------------
  16294. * inside the handler you can get/set Hammer.detection.current. This is the current
  16295. * detection session. It has the following properties
  16296. * @param {String} name
  16297. * contains the name of the gesture we have detected. it has not a real function,
  16298. * only to check in other gestures if something is detected.
  16299. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16300. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16301. *
  16302. * @readonly
  16303. * @param {Hammer.Instance} inst
  16304. * the instance we do the detection for
  16305. *
  16306. * @readonly
  16307. * @param {Object} startEvent
  16308. * contains the properties of the first gesture detection in this session.
  16309. * Used for calculations about timing, distance, etc.
  16310. *
  16311. * @readonly
  16312. * @param {Object} lastEvent
  16313. * contains all the properties of the last gesture detect in this session.
  16314. *
  16315. * after the gesture detection session has been completed (user has released the screen)
  16316. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16317. * this is usefull for gestures like doubletap, where you need to know if the
  16318. * previous gesture was a tap
  16319. *
  16320. * options that have been set by the instance can be received by calling inst.options
  16321. *
  16322. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16323. * The first param is the name of your gesture, the second the event argument
  16324. *
  16325. *
  16326. * Register gestures
  16327. * --------------------
  16328. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16329. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16330. * manually and pass your gesture object as a param
  16331. *
  16332. */
  16333. /**
  16334. * Hold
  16335. * Touch stays at the same place for x time
  16336. * @events hold
  16337. */
  16338. Hammer.gestures.Hold = {
  16339. name: 'hold',
  16340. index: 10,
  16341. defaults: {
  16342. hold_timeout : 500,
  16343. hold_threshold : 1
  16344. },
  16345. timer: null,
  16346. handler: function holdGesture(ev, inst) {
  16347. switch(ev.eventType) {
  16348. case Hammer.EVENT_START:
  16349. // clear any running timers
  16350. clearTimeout(this.timer);
  16351. // set the gesture so we can check in the timeout if it still is
  16352. Hammer.detection.current.name = this.name;
  16353. // set timer and if after the timeout it still is hold,
  16354. // we trigger the hold event
  16355. this.timer = setTimeout(function() {
  16356. if(Hammer.detection.current.name == 'hold') {
  16357. inst.trigger('hold', ev);
  16358. }
  16359. }, inst.options.hold_timeout);
  16360. break;
  16361. // when you move or end we clear the timer
  16362. case Hammer.EVENT_MOVE:
  16363. if(ev.distance > inst.options.hold_threshold) {
  16364. clearTimeout(this.timer);
  16365. }
  16366. break;
  16367. case Hammer.EVENT_END:
  16368. clearTimeout(this.timer);
  16369. break;
  16370. }
  16371. }
  16372. };
  16373. /**
  16374. * Tap/DoubleTap
  16375. * Quick touch at a place or double at the same place
  16376. * @events tap, doubletap
  16377. */
  16378. Hammer.gestures.Tap = {
  16379. name: 'tap',
  16380. index: 100,
  16381. defaults: {
  16382. tap_max_touchtime : 250,
  16383. tap_max_distance : 10,
  16384. tap_always : true,
  16385. doubletap_distance : 20,
  16386. doubletap_interval : 300
  16387. },
  16388. handler: function tapGesture(ev, inst) {
  16389. if(ev.eventType == Hammer.EVENT_END) {
  16390. // previous gesture, for the double tap since these are two different gesture detections
  16391. var prev = Hammer.detection.previous,
  16392. did_doubletap = false;
  16393. // when the touchtime is higher then the max touch time
  16394. // or when the moving distance is too much
  16395. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16396. ev.distance > inst.options.tap_max_distance) {
  16397. return;
  16398. }
  16399. // check if double tap
  16400. if(prev && prev.name == 'tap' &&
  16401. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16402. ev.distance < inst.options.doubletap_distance) {
  16403. inst.trigger('doubletap', ev);
  16404. did_doubletap = true;
  16405. }
  16406. // do a single tap
  16407. if(!did_doubletap || inst.options.tap_always) {
  16408. Hammer.detection.current.name = 'tap';
  16409. inst.trigger(Hammer.detection.current.name, ev);
  16410. }
  16411. }
  16412. }
  16413. };
  16414. /**
  16415. * Swipe
  16416. * triggers swipe events when the end velocity is above the threshold
  16417. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16418. */
  16419. Hammer.gestures.Swipe = {
  16420. name: 'swipe',
  16421. index: 40,
  16422. defaults: {
  16423. // set 0 for unlimited, but this can conflict with transform
  16424. swipe_max_touches : 1,
  16425. swipe_velocity : 0.7
  16426. },
  16427. handler: function swipeGesture(ev, inst) {
  16428. if(ev.eventType == Hammer.EVENT_END) {
  16429. // max touches
  16430. if(inst.options.swipe_max_touches > 0 &&
  16431. ev.touches.length > inst.options.swipe_max_touches) {
  16432. return;
  16433. }
  16434. // when the distance we moved is too small we skip this gesture
  16435. // or we can be already in dragging
  16436. if(ev.velocityX > inst.options.swipe_velocity ||
  16437. ev.velocityY > inst.options.swipe_velocity) {
  16438. // trigger swipe events
  16439. inst.trigger(this.name, ev);
  16440. inst.trigger(this.name + ev.direction, ev);
  16441. }
  16442. }
  16443. }
  16444. };
  16445. /**
  16446. * Drag
  16447. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16448. * moving left and right is a good practice. When all the drag events are blocking
  16449. * you disable scrolling on that area.
  16450. * @events drag, drapleft, dragright, dragup, dragdown
  16451. */
  16452. Hammer.gestures.Drag = {
  16453. name: 'drag',
  16454. index: 50,
  16455. defaults: {
  16456. drag_min_distance : 10,
  16457. // set 0 for unlimited, but this can conflict with transform
  16458. drag_max_touches : 1,
  16459. // prevent default browser behavior when dragging occurs
  16460. // be careful with it, it makes the element a blocking element
  16461. // when you are using the drag gesture, it is a good practice to set this true
  16462. drag_block_horizontal : false,
  16463. drag_block_vertical : false,
  16464. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  16465. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  16466. drag_lock_to_axis : false,
  16467. // drag lock only kicks in when distance > drag_lock_min_distance
  16468. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  16469. drag_lock_min_distance : 25
  16470. },
  16471. triggered: false,
  16472. handler: function dragGesture(ev, inst) {
  16473. // current gesture isnt drag, but dragged is true
  16474. // this means an other gesture is busy. now call dragend
  16475. if(Hammer.detection.current.name != this.name && this.triggered) {
  16476. inst.trigger(this.name +'end', ev);
  16477. this.triggered = false;
  16478. return;
  16479. }
  16480. // max touches
  16481. if(inst.options.drag_max_touches > 0 &&
  16482. ev.touches.length > inst.options.drag_max_touches) {
  16483. return;
  16484. }
  16485. switch(ev.eventType) {
  16486. case Hammer.EVENT_START:
  16487. this.triggered = false;
  16488. break;
  16489. case Hammer.EVENT_MOVE:
  16490. // when the distance we moved is too small we skip this gesture
  16491. // or we can be already in dragging
  16492. if(ev.distance < inst.options.drag_min_distance &&
  16493. Hammer.detection.current.name != this.name) {
  16494. return;
  16495. }
  16496. // we are dragging!
  16497. Hammer.detection.current.name = this.name;
  16498. // lock drag to axis?
  16499. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  16500. ev.drag_locked_to_axis = true;
  16501. }
  16502. var last_direction = Hammer.detection.current.lastEvent.direction;
  16503. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  16504. // keep direction on the axis that the drag gesture started on
  16505. if(Hammer.utils.isVertical(last_direction)) {
  16506. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16507. }
  16508. else {
  16509. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16510. }
  16511. }
  16512. // first time, trigger dragstart event
  16513. if(!this.triggered) {
  16514. inst.trigger(this.name +'start', ev);
  16515. this.triggered = true;
  16516. }
  16517. // trigger normal event
  16518. inst.trigger(this.name, ev);
  16519. // direction event, like dragdown
  16520. inst.trigger(this.name + ev.direction, ev);
  16521. // block the browser events
  16522. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  16523. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  16524. ev.preventDefault();
  16525. }
  16526. break;
  16527. case Hammer.EVENT_END:
  16528. // trigger dragend
  16529. if(this.triggered) {
  16530. inst.trigger(this.name +'end', ev);
  16531. }
  16532. this.triggered = false;
  16533. break;
  16534. }
  16535. }
  16536. };
  16537. /**
  16538. * Transform
  16539. * User want to scale or rotate with 2 fingers
  16540. * @events transform, pinch, pinchin, pinchout, rotate
  16541. */
  16542. Hammer.gestures.Transform = {
  16543. name: 'transform',
  16544. index: 45,
  16545. defaults: {
  16546. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  16547. transform_min_scale : 0.01,
  16548. // rotation in degrees
  16549. transform_min_rotation : 1,
  16550. // prevent default browser behavior when two touches are on the screen
  16551. // but it makes the element a blocking element
  16552. // when you are using the transform gesture, it is a good practice to set this true
  16553. transform_always_block : false
  16554. },
  16555. triggered: false,
  16556. handler: function transformGesture(ev, inst) {
  16557. // current gesture isnt drag, but dragged is true
  16558. // this means an other gesture is busy. now call dragend
  16559. if(Hammer.detection.current.name != this.name && this.triggered) {
  16560. inst.trigger(this.name +'end', ev);
  16561. this.triggered = false;
  16562. return;
  16563. }
  16564. // atleast multitouch
  16565. if(ev.touches.length < 2) {
  16566. return;
  16567. }
  16568. // prevent default when two fingers are on the screen
  16569. if(inst.options.transform_always_block) {
  16570. ev.preventDefault();
  16571. }
  16572. switch(ev.eventType) {
  16573. case Hammer.EVENT_START:
  16574. this.triggered = false;
  16575. break;
  16576. case Hammer.EVENT_MOVE:
  16577. var scale_threshold = Math.abs(1-ev.scale);
  16578. var rotation_threshold = Math.abs(ev.rotation);
  16579. // when the distance we moved is too small we skip this gesture
  16580. // or we can be already in dragging
  16581. if(scale_threshold < inst.options.transform_min_scale &&
  16582. rotation_threshold < inst.options.transform_min_rotation) {
  16583. return;
  16584. }
  16585. // we are transforming!
  16586. Hammer.detection.current.name = this.name;
  16587. // first time, trigger dragstart event
  16588. if(!this.triggered) {
  16589. inst.trigger(this.name +'start', ev);
  16590. this.triggered = true;
  16591. }
  16592. inst.trigger(this.name, ev); // basic transform event
  16593. // trigger rotate event
  16594. if(rotation_threshold > inst.options.transform_min_rotation) {
  16595. inst.trigger('rotate', ev);
  16596. }
  16597. // trigger pinch event
  16598. if(scale_threshold > inst.options.transform_min_scale) {
  16599. inst.trigger('pinch', ev);
  16600. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  16601. }
  16602. break;
  16603. case Hammer.EVENT_END:
  16604. // trigger dragend
  16605. if(this.triggered) {
  16606. inst.trigger(this.name +'end', ev);
  16607. }
  16608. this.triggered = false;
  16609. break;
  16610. }
  16611. }
  16612. };
  16613. /**
  16614. * Touch
  16615. * Called as first, tells the user has touched the screen
  16616. * @events touch
  16617. */
  16618. Hammer.gestures.Touch = {
  16619. name: 'touch',
  16620. index: -Infinity,
  16621. defaults: {
  16622. // call preventDefault at touchstart, and makes the element blocking by
  16623. // disabling the scrolling of the page, but it improves gestures like
  16624. // transforming and dragging.
  16625. // be careful with using this, it can be very annoying for users to be stuck
  16626. // on the page
  16627. prevent_default: false,
  16628. // disable mouse events, so only touch (or pen!) input triggers events
  16629. prevent_mouseevents: false
  16630. },
  16631. handler: function touchGesture(ev, inst) {
  16632. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  16633. ev.stopDetect();
  16634. return;
  16635. }
  16636. if(inst.options.prevent_default) {
  16637. ev.preventDefault();
  16638. }
  16639. if(ev.eventType == Hammer.EVENT_START) {
  16640. inst.trigger(this.name, ev);
  16641. }
  16642. }
  16643. };
  16644. /**
  16645. * Release
  16646. * Called as last, tells the user has released the screen
  16647. * @events release
  16648. */
  16649. Hammer.gestures.Release = {
  16650. name: 'release',
  16651. index: Infinity,
  16652. handler: function releaseGesture(ev, inst) {
  16653. if(ev.eventType == Hammer.EVENT_END) {
  16654. inst.trigger(this.name, ev);
  16655. }
  16656. }
  16657. };
  16658. // node export
  16659. if(typeof module === 'object' && typeof module.exports === 'object'){
  16660. module.exports = Hammer;
  16661. }
  16662. // just window export
  16663. else {
  16664. window.Hammer = Hammer;
  16665. // requireJS module definition
  16666. if(typeof window.define === 'function' && window.define.amd) {
  16667. window.define('hammer', [], function() {
  16668. return Hammer;
  16669. });
  16670. }
  16671. }
  16672. })(this);
  16673. },{}],4:[function(require,module,exports){
  16674. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};//! moment.js
  16675. //! version : 2.6.0
  16676. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  16677. //! license : MIT
  16678. //! momentjs.com
  16679. (function (undefined) {
  16680. /************************************
  16681. Constants
  16682. ************************************/
  16683. var moment,
  16684. VERSION = "2.6.0",
  16685. // the global-scope this is NOT the global object in Node.js
  16686. globalScope = typeof global !== 'undefined' ? global : this,
  16687. oldGlobalMoment,
  16688. round = Math.round,
  16689. i,
  16690. YEAR = 0,
  16691. MONTH = 1,
  16692. DATE = 2,
  16693. HOUR = 3,
  16694. MINUTE = 4,
  16695. SECOND = 5,
  16696. MILLISECOND = 6,
  16697. // internal storage for language config files
  16698. languages = {},
  16699. // moment internal properties
  16700. momentProperties = {
  16701. _isAMomentObject: null,
  16702. _i : null,
  16703. _f : null,
  16704. _l : null,
  16705. _strict : null,
  16706. _isUTC : null,
  16707. _offset : null, // optional. Combine with _isUTC
  16708. _pf : null,
  16709. _lang : null // optional
  16710. },
  16711. // check for nodeJS
  16712. hasModule = (typeof module !== 'undefined' && module.exports),
  16713. // ASP.NET json date format regex
  16714. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  16715. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  16716. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  16717. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  16718. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  16719. // format tokens
  16720. 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,
  16721. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  16722. // parsing token regexes
  16723. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  16724. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  16725. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  16726. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  16727. parseTokenDigits = /\d+/, // nonzero number of digits
  16728. 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.
  16729. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  16730. parseTokenT = /T/i, // T (ISO separator)
  16731. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  16732. parseTokenOrdinal = /\d{1,2}/,
  16733. //strict parsing regexes
  16734. parseTokenOneDigit = /\d/, // 0 - 9
  16735. parseTokenTwoDigits = /\d\d/, // 00 - 99
  16736. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  16737. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  16738. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  16739. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  16740. // iso 8601 regex
  16741. // 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)
  16742. 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)?)?$/,
  16743. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  16744. isoDates = [
  16745. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  16746. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  16747. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  16748. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  16749. ['YYYY-DDD', /\d{4}-\d{3}/]
  16750. ],
  16751. // iso time formats and regexes
  16752. isoTimes = [
  16753. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
  16754. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  16755. ['HH:mm', /(T| )\d\d:\d\d/],
  16756. ['HH', /(T| )\d\d/]
  16757. ],
  16758. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  16759. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  16760. // getter and setter names
  16761. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  16762. unitMillisecondFactors = {
  16763. 'Milliseconds' : 1,
  16764. 'Seconds' : 1e3,
  16765. 'Minutes' : 6e4,
  16766. 'Hours' : 36e5,
  16767. 'Days' : 864e5,
  16768. 'Months' : 2592e6,
  16769. 'Years' : 31536e6
  16770. },
  16771. unitAliases = {
  16772. ms : 'millisecond',
  16773. s : 'second',
  16774. m : 'minute',
  16775. h : 'hour',
  16776. d : 'day',
  16777. D : 'date',
  16778. w : 'week',
  16779. W : 'isoWeek',
  16780. M : 'month',
  16781. Q : 'quarter',
  16782. y : 'year',
  16783. DDD : 'dayOfYear',
  16784. e : 'weekday',
  16785. E : 'isoWeekday',
  16786. gg: 'weekYear',
  16787. GG: 'isoWeekYear'
  16788. },
  16789. camelFunctions = {
  16790. dayofyear : 'dayOfYear',
  16791. isoweekday : 'isoWeekday',
  16792. isoweek : 'isoWeek',
  16793. weekyear : 'weekYear',
  16794. isoweekyear : 'isoWeekYear'
  16795. },
  16796. // format function strings
  16797. formatFunctions = {},
  16798. // tokens to ordinalize and pad
  16799. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  16800. paddedTokens = 'M D H h m s w W'.split(' '),
  16801. formatTokenFunctions = {
  16802. M : function () {
  16803. return this.month() + 1;
  16804. },
  16805. MMM : function (format) {
  16806. return this.lang().monthsShort(this, format);
  16807. },
  16808. MMMM : function (format) {
  16809. return this.lang().months(this, format);
  16810. },
  16811. D : function () {
  16812. return this.date();
  16813. },
  16814. DDD : function () {
  16815. return this.dayOfYear();
  16816. },
  16817. d : function () {
  16818. return this.day();
  16819. },
  16820. dd : function (format) {
  16821. return this.lang().weekdaysMin(this, format);
  16822. },
  16823. ddd : function (format) {
  16824. return this.lang().weekdaysShort(this, format);
  16825. },
  16826. dddd : function (format) {
  16827. return this.lang().weekdays(this, format);
  16828. },
  16829. w : function () {
  16830. return this.week();
  16831. },
  16832. W : function () {
  16833. return this.isoWeek();
  16834. },
  16835. YY : function () {
  16836. return leftZeroFill(this.year() % 100, 2);
  16837. },
  16838. YYYY : function () {
  16839. return leftZeroFill(this.year(), 4);
  16840. },
  16841. YYYYY : function () {
  16842. return leftZeroFill(this.year(), 5);
  16843. },
  16844. YYYYYY : function () {
  16845. var y = this.year(), sign = y >= 0 ? '+' : '-';
  16846. return sign + leftZeroFill(Math.abs(y), 6);
  16847. },
  16848. gg : function () {
  16849. return leftZeroFill(this.weekYear() % 100, 2);
  16850. },
  16851. gggg : function () {
  16852. return leftZeroFill(this.weekYear(), 4);
  16853. },
  16854. ggggg : function () {
  16855. return leftZeroFill(this.weekYear(), 5);
  16856. },
  16857. GG : function () {
  16858. return leftZeroFill(this.isoWeekYear() % 100, 2);
  16859. },
  16860. GGGG : function () {
  16861. return leftZeroFill(this.isoWeekYear(), 4);
  16862. },
  16863. GGGGG : function () {
  16864. return leftZeroFill(this.isoWeekYear(), 5);
  16865. },
  16866. e : function () {
  16867. return this.weekday();
  16868. },
  16869. E : function () {
  16870. return this.isoWeekday();
  16871. },
  16872. a : function () {
  16873. return this.lang().meridiem(this.hours(), this.minutes(), true);
  16874. },
  16875. A : function () {
  16876. return this.lang().meridiem(this.hours(), this.minutes(), false);
  16877. },
  16878. H : function () {
  16879. return this.hours();
  16880. },
  16881. h : function () {
  16882. return this.hours() % 12 || 12;
  16883. },
  16884. m : function () {
  16885. return this.minutes();
  16886. },
  16887. s : function () {
  16888. return this.seconds();
  16889. },
  16890. S : function () {
  16891. return toInt(this.milliseconds() / 100);
  16892. },
  16893. SS : function () {
  16894. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  16895. },
  16896. SSS : function () {
  16897. return leftZeroFill(this.milliseconds(), 3);
  16898. },
  16899. SSSS : function () {
  16900. return leftZeroFill(this.milliseconds(), 3);
  16901. },
  16902. Z : function () {
  16903. var a = -this.zone(),
  16904. b = "+";
  16905. if (a < 0) {
  16906. a = -a;
  16907. b = "-";
  16908. }
  16909. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  16910. },
  16911. ZZ : function () {
  16912. var a = -this.zone(),
  16913. b = "+";
  16914. if (a < 0) {
  16915. a = -a;
  16916. b = "-";
  16917. }
  16918. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  16919. },
  16920. z : function () {
  16921. return this.zoneAbbr();
  16922. },
  16923. zz : function () {
  16924. return this.zoneName();
  16925. },
  16926. X : function () {
  16927. return this.unix();
  16928. },
  16929. Q : function () {
  16930. return this.quarter();
  16931. }
  16932. },
  16933. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  16934. function defaultParsingFlags() {
  16935. // We need to deep clone this object, and es5 standard is not very
  16936. // helpful.
  16937. return {
  16938. empty : false,
  16939. unusedTokens : [],
  16940. unusedInput : [],
  16941. overflow : -2,
  16942. charsLeftOver : 0,
  16943. nullInput : false,
  16944. invalidMonth : null,
  16945. invalidFormat : false,
  16946. userInvalidated : false,
  16947. iso: false
  16948. };
  16949. }
  16950. function deprecate(msg, fn) {
  16951. var firstTime = true;
  16952. function printMsg() {
  16953. if (moment.suppressDeprecationWarnings === false &&
  16954. typeof console !== 'undefined' && console.warn) {
  16955. console.warn("Deprecation warning: " + msg);
  16956. }
  16957. }
  16958. return extend(function () {
  16959. if (firstTime) {
  16960. printMsg();
  16961. firstTime = false;
  16962. }
  16963. return fn.apply(this, arguments);
  16964. }, fn);
  16965. }
  16966. function padToken(func, count) {
  16967. return function (a) {
  16968. return leftZeroFill(func.call(this, a), count);
  16969. };
  16970. }
  16971. function ordinalizeToken(func, period) {
  16972. return function (a) {
  16973. return this.lang().ordinal(func.call(this, a), period);
  16974. };
  16975. }
  16976. while (ordinalizeTokens.length) {
  16977. i = ordinalizeTokens.pop();
  16978. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  16979. }
  16980. while (paddedTokens.length) {
  16981. i = paddedTokens.pop();
  16982. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  16983. }
  16984. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  16985. /************************************
  16986. Constructors
  16987. ************************************/
  16988. function Language() {
  16989. }
  16990. // Moment prototype object
  16991. function Moment(config) {
  16992. checkOverflow(config);
  16993. extend(this, config);
  16994. }
  16995. // Duration Constructor
  16996. function Duration(duration) {
  16997. var normalizedInput = normalizeObjectUnits(duration),
  16998. years = normalizedInput.year || 0,
  16999. quarters = normalizedInput.quarter || 0,
  17000. months = normalizedInput.month || 0,
  17001. weeks = normalizedInput.week || 0,
  17002. days = normalizedInput.day || 0,
  17003. hours = normalizedInput.hour || 0,
  17004. minutes = normalizedInput.minute || 0,
  17005. seconds = normalizedInput.second || 0,
  17006. milliseconds = normalizedInput.millisecond || 0;
  17007. // representation for dateAddRemove
  17008. this._milliseconds = +milliseconds +
  17009. seconds * 1e3 + // 1000
  17010. minutes * 6e4 + // 1000 * 60
  17011. hours * 36e5; // 1000 * 60 * 60
  17012. // Because of dateAddRemove treats 24 hours as different from a
  17013. // day when working around DST, we need to store them separately
  17014. this._days = +days +
  17015. weeks * 7;
  17016. // It is impossible translate months into days without knowing
  17017. // which months you are are talking about, so we have to store
  17018. // it separately.
  17019. this._months = +months +
  17020. quarters * 3 +
  17021. years * 12;
  17022. this._data = {};
  17023. this._bubble();
  17024. }
  17025. /************************************
  17026. Helpers
  17027. ************************************/
  17028. function extend(a, b) {
  17029. for (var i in b) {
  17030. if (b.hasOwnProperty(i)) {
  17031. a[i] = b[i];
  17032. }
  17033. }
  17034. if (b.hasOwnProperty("toString")) {
  17035. a.toString = b.toString;
  17036. }
  17037. if (b.hasOwnProperty("valueOf")) {
  17038. a.valueOf = b.valueOf;
  17039. }
  17040. return a;
  17041. }
  17042. function cloneMoment(m) {
  17043. var result = {}, i;
  17044. for (i in m) {
  17045. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17046. result[i] = m[i];
  17047. }
  17048. }
  17049. return result;
  17050. }
  17051. function absRound(number) {
  17052. if (number < 0) {
  17053. return Math.ceil(number);
  17054. } else {
  17055. return Math.floor(number);
  17056. }
  17057. }
  17058. // left zero fill a number
  17059. // see http://jsperf.com/left-zero-filling for performance comparison
  17060. function leftZeroFill(number, targetLength, forceSign) {
  17061. var output = '' + Math.abs(number),
  17062. sign = number >= 0;
  17063. while (output.length < targetLength) {
  17064. output = '0' + output;
  17065. }
  17066. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17067. }
  17068. // helper function for _.addTime and _.subtractTime
  17069. function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
  17070. var milliseconds = duration._milliseconds,
  17071. days = duration._days,
  17072. months = duration._months;
  17073. updateOffset = updateOffset == null ? true : updateOffset;
  17074. if (milliseconds) {
  17075. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17076. }
  17077. if (days) {
  17078. rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
  17079. }
  17080. if (months) {
  17081. rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
  17082. }
  17083. if (updateOffset) {
  17084. moment.updateOffset(mom, days || months);
  17085. }
  17086. }
  17087. // check if is an array
  17088. function isArray(input) {
  17089. return Object.prototype.toString.call(input) === '[object Array]';
  17090. }
  17091. function isDate(input) {
  17092. return Object.prototype.toString.call(input) === '[object Date]' ||
  17093. input instanceof Date;
  17094. }
  17095. // compare two arrays, return the number of differences
  17096. function compareArrays(array1, array2, dontConvert) {
  17097. var len = Math.min(array1.length, array2.length),
  17098. lengthDiff = Math.abs(array1.length - array2.length),
  17099. diffs = 0,
  17100. i;
  17101. for (i = 0; i < len; i++) {
  17102. if ((dontConvert && array1[i] !== array2[i]) ||
  17103. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17104. diffs++;
  17105. }
  17106. }
  17107. return diffs + lengthDiff;
  17108. }
  17109. function normalizeUnits(units) {
  17110. if (units) {
  17111. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17112. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17113. }
  17114. return units;
  17115. }
  17116. function normalizeObjectUnits(inputObject) {
  17117. var normalizedInput = {},
  17118. normalizedProp,
  17119. prop;
  17120. for (prop in inputObject) {
  17121. if (inputObject.hasOwnProperty(prop)) {
  17122. normalizedProp = normalizeUnits(prop);
  17123. if (normalizedProp) {
  17124. normalizedInput[normalizedProp] = inputObject[prop];
  17125. }
  17126. }
  17127. }
  17128. return normalizedInput;
  17129. }
  17130. function makeList(field) {
  17131. var count, setter;
  17132. if (field.indexOf('week') === 0) {
  17133. count = 7;
  17134. setter = 'day';
  17135. }
  17136. else if (field.indexOf('month') === 0) {
  17137. count = 12;
  17138. setter = 'month';
  17139. }
  17140. else {
  17141. return;
  17142. }
  17143. moment[field] = function (format, index) {
  17144. var i, getter,
  17145. method = moment.fn._lang[field],
  17146. results = [];
  17147. if (typeof format === 'number') {
  17148. index = format;
  17149. format = undefined;
  17150. }
  17151. getter = function (i) {
  17152. var m = moment().utc().set(setter, i);
  17153. return method.call(moment.fn._lang, m, format || '');
  17154. };
  17155. if (index != null) {
  17156. return getter(index);
  17157. }
  17158. else {
  17159. for (i = 0; i < count; i++) {
  17160. results.push(getter(i));
  17161. }
  17162. return results;
  17163. }
  17164. };
  17165. }
  17166. function toInt(argumentForCoercion) {
  17167. var coercedNumber = +argumentForCoercion,
  17168. value = 0;
  17169. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17170. if (coercedNumber >= 0) {
  17171. value = Math.floor(coercedNumber);
  17172. } else {
  17173. value = Math.ceil(coercedNumber);
  17174. }
  17175. }
  17176. return value;
  17177. }
  17178. function daysInMonth(year, month) {
  17179. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17180. }
  17181. function weeksInYear(year, dow, doy) {
  17182. return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
  17183. }
  17184. function daysInYear(year) {
  17185. return isLeapYear(year) ? 366 : 365;
  17186. }
  17187. function isLeapYear(year) {
  17188. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17189. }
  17190. function checkOverflow(m) {
  17191. var overflow;
  17192. if (m._a && m._pf.overflow === -2) {
  17193. overflow =
  17194. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17195. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17196. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17197. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17198. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17199. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17200. -1;
  17201. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17202. overflow = DATE;
  17203. }
  17204. m._pf.overflow = overflow;
  17205. }
  17206. }
  17207. function isValid(m) {
  17208. if (m._isValid == null) {
  17209. m._isValid = !isNaN(m._d.getTime()) &&
  17210. m._pf.overflow < 0 &&
  17211. !m._pf.empty &&
  17212. !m._pf.invalidMonth &&
  17213. !m._pf.nullInput &&
  17214. !m._pf.invalidFormat &&
  17215. !m._pf.userInvalidated;
  17216. if (m._strict) {
  17217. m._isValid = m._isValid &&
  17218. m._pf.charsLeftOver === 0 &&
  17219. m._pf.unusedTokens.length === 0;
  17220. }
  17221. }
  17222. return m._isValid;
  17223. }
  17224. function normalizeLanguage(key) {
  17225. return key ? key.toLowerCase().replace('_', '-') : key;
  17226. }
  17227. // Return a moment from input, that is local/utc/zone equivalent to model.
  17228. function makeAs(input, model) {
  17229. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17230. moment(input).local();
  17231. }
  17232. /************************************
  17233. Languages
  17234. ************************************/
  17235. extend(Language.prototype, {
  17236. set : function (config) {
  17237. var prop, i;
  17238. for (i in config) {
  17239. prop = config[i];
  17240. if (typeof prop === 'function') {
  17241. this[i] = prop;
  17242. } else {
  17243. this['_' + i] = prop;
  17244. }
  17245. }
  17246. },
  17247. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17248. months : function (m) {
  17249. return this._months[m.month()];
  17250. },
  17251. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17252. monthsShort : function (m) {
  17253. return this._monthsShort[m.month()];
  17254. },
  17255. monthsParse : function (monthName) {
  17256. var i, mom, regex;
  17257. if (!this._monthsParse) {
  17258. this._monthsParse = [];
  17259. }
  17260. for (i = 0; i < 12; i++) {
  17261. // make the regex if we don't have it already
  17262. if (!this._monthsParse[i]) {
  17263. mom = moment.utc([2000, i]);
  17264. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17265. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17266. }
  17267. // test the regex
  17268. if (this._monthsParse[i].test(monthName)) {
  17269. return i;
  17270. }
  17271. }
  17272. },
  17273. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17274. weekdays : function (m) {
  17275. return this._weekdays[m.day()];
  17276. },
  17277. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17278. weekdaysShort : function (m) {
  17279. return this._weekdaysShort[m.day()];
  17280. },
  17281. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17282. weekdaysMin : function (m) {
  17283. return this._weekdaysMin[m.day()];
  17284. },
  17285. weekdaysParse : function (weekdayName) {
  17286. var i, mom, regex;
  17287. if (!this._weekdaysParse) {
  17288. this._weekdaysParse = [];
  17289. }
  17290. for (i = 0; i < 7; i++) {
  17291. // make the regex if we don't have it already
  17292. if (!this._weekdaysParse[i]) {
  17293. mom = moment([2000, 1]).day(i);
  17294. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17295. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17296. }
  17297. // test the regex
  17298. if (this._weekdaysParse[i].test(weekdayName)) {
  17299. return i;
  17300. }
  17301. }
  17302. },
  17303. _longDateFormat : {
  17304. LT : "h:mm A",
  17305. L : "MM/DD/YYYY",
  17306. LL : "MMMM D YYYY",
  17307. LLL : "MMMM D YYYY LT",
  17308. LLLL : "dddd, MMMM D YYYY LT"
  17309. },
  17310. longDateFormat : function (key) {
  17311. var output = this._longDateFormat[key];
  17312. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17313. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17314. return val.slice(1);
  17315. });
  17316. this._longDateFormat[key] = output;
  17317. }
  17318. return output;
  17319. },
  17320. isPM : function (input) {
  17321. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17322. // Using charAt should be more compatible.
  17323. return ((input + '').toLowerCase().charAt(0) === 'p');
  17324. },
  17325. _meridiemParse : /[ap]\.?m?\.?/i,
  17326. meridiem : function (hours, minutes, isLower) {
  17327. if (hours > 11) {
  17328. return isLower ? 'pm' : 'PM';
  17329. } else {
  17330. return isLower ? 'am' : 'AM';
  17331. }
  17332. },
  17333. _calendar : {
  17334. sameDay : '[Today at] LT',
  17335. nextDay : '[Tomorrow at] LT',
  17336. nextWeek : 'dddd [at] LT',
  17337. lastDay : '[Yesterday at] LT',
  17338. lastWeek : '[Last] dddd [at] LT',
  17339. sameElse : 'L'
  17340. },
  17341. calendar : function (key, mom) {
  17342. var output = this._calendar[key];
  17343. return typeof output === 'function' ? output.apply(mom) : output;
  17344. },
  17345. _relativeTime : {
  17346. future : "in %s",
  17347. past : "%s ago",
  17348. s : "a few seconds",
  17349. m : "a minute",
  17350. mm : "%d minutes",
  17351. h : "an hour",
  17352. hh : "%d hours",
  17353. d : "a day",
  17354. dd : "%d days",
  17355. M : "a month",
  17356. MM : "%d months",
  17357. y : "a year",
  17358. yy : "%d years"
  17359. },
  17360. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17361. var output = this._relativeTime[string];
  17362. return (typeof output === 'function') ?
  17363. output(number, withoutSuffix, string, isFuture) :
  17364. output.replace(/%d/i, number);
  17365. },
  17366. pastFuture : function (diff, output) {
  17367. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17368. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17369. },
  17370. ordinal : function (number) {
  17371. return this._ordinal.replace("%d", number);
  17372. },
  17373. _ordinal : "%d",
  17374. preparse : function (string) {
  17375. return string;
  17376. },
  17377. postformat : function (string) {
  17378. return string;
  17379. },
  17380. week : function (mom) {
  17381. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17382. },
  17383. _week : {
  17384. dow : 0, // Sunday is the first day of the week.
  17385. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17386. },
  17387. _invalidDate: 'Invalid date',
  17388. invalidDate: function () {
  17389. return this._invalidDate;
  17390. }
  17391. });
  17392. // Loads a language definition into the `languages` cache. The function
  17393. // takes a key and optionally values. If not in the browser and no values
  17394. // are provided, it will load the language file module. As a convenience,
  17395. // this function also returns the language values.
  17396. function loadLang(key, values) {
  17397. values.abbr = key;
  17398. if (!languages[key]) {
  17399. languages[key] = new Language();
  17400. }
  17401. languages[key].set(values);
  17402. return languages[key];
  17403. }
  17404. // Remove a language from the `languages` cache. Mostly useful in tests.
  17405. function unloadLang(key) {
  17406. delete languages[key];
  17407. }
  17408. // Determines which language definition to use and returns it.
  17409. //
  17410. // With no parameters, it will return the global language. If you
  17411. // pass in a language key, such as 'en', it will return the
  17412. // definition for 'en', so long as 'en' has already been loaded using
  17413. // moment.lang.
  17414. function getLangDefinition(key) {
  17415. var i = 0, j, lang, next, split,
  17416. get = function (k) {
  17417. if (!languages[k] && hasModule) {
  17418. try {
  17419. require('./lang/' + k);
  17420. } catch (e) { }
  17421. }
  17422. return languages[k];
  17423. };
  17424. if (!key) {
  17425. return moment.fn._lang;
  17426. }
  17427. if (!isArray(key)) {
  17428. //short-circuit everything else
  17429. lang = get(key);
  17430. if (lang) {
  17431. return lang;
  17432. }
  17433. key = [key];
  17434. }
  17435. //pick the language from the array
  17436. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17437. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17438. while (i < key.length) {
  17439. split = normalizeLanguage(key[i]).split('-');
  17440. j = split.length;
  17441. next = normalizeLanguage(key[i + 1]);
  17442. next = next ? next.split('-') : null;
  17443. while (j > 0) {
  17444. lang = get(split.slice(0, j).join('-'));
  17445. if (lang) {
  17446. return lang;
  17447. }
  17448. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17449. //the next array item is better than a shallower substring of this one
  17450. break;
  17451. }
  17452. j--;
  17453. }
  17454. i++;
  17455. }
  17456. return moment.fn._lang;
  17457. }
  17458. /************************************
  17459. Formatting
  17460. ************************************/
  17461. function removeFormattingTokens(input) {
  17462. if (input.match(/\[[\s\S]/)) {
  17463. return input.replace(/^\[|\]$/g, "");
  17464. }
  17465. return input.replace(/\\/g, "");
  17466. }
  17467. function makeFormatFunction(format) {
  17468. var array = format.match(formattingTokens), i, length;
  17469. for (i = 0, length = array.length; i < length; i++) {
  17470. if (formatTokenFunctions[array[i]]) {
  17471. array[i] = formatTokenFunctions[array[i]];
  17472. } else {
  17473. array[i] = removeFormattingTokens(array[i]);
  17474. }
  17475. }
  17476. return function (mom) {
  17477. var output = "";
  17478. for (i = 0; i < length; i++) {
  17479. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  17480. }
  17481. return output;
  17482. };
  17483. }
  17484. // format date using native date object
  17485. function formatMoment(m, format) {
  17486. if (!m.isValid()) {
  17487. return m.lang().invalidDate();
  17488. }
  17489. format = expandFormat(format, m.lang());
  17490. if (!formatFunctions[format]) {
  17491. formatFunctions[format] = makeFormatFunction(format);
  17492. }
  17493. return formatFunctions[format](m);
  17494. }
  17495. function expandFormat(format, lang) {
  17496. var i = 5;
  17497. function replaceLongDateFormatTokens(input) {
  17498. return lang.longDateFormat(input) || input;
  17499. }
  17500. localFormattingTokens.lastIndex = 0;
  17501. while (i >= 0 && localFormattingTokens.test(format)) {
  17502. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  17503. localFormattingTokens.lastIndex = 0;
  17504. i -= 1;
  17505. }
  17506. return format;
  17507. }
  17508. /************************************
  17509. Parsing
  17510. ************************************/
  17511. // get the regex to find the next token
  17512. function getParseRegexForToken(token, config) {
  17513. var a, strict = config._strict;
  17514. switch (token) {
  17515. case 'Q':
  17516. return parseTokenOneDigit;
  17517. case 'DDDD':
  17518. return parseTokenThreeDigits;
  17519. case 'YYYY':
  17520. case 'GGGG':
  17521. case 'gggg':
  17522. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  17523. case 'Y':
  17524. case 'G':
  17525. case 'g':
  17526. return parseTokenSignedNumber;
  17527. case 'YYYYYY':
  17528. case 'YYYYY':
  17529. case 'GGGGG':
  17530. case 'ggggg':
  17531. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  17532. case 'S':
  17533. if (strict) { return parseTokenOneDigit; }
  17534. /* falls through */
  17535. case 'SS':
  17536. if (strict) { return parseTokenTwoDigits; }
  17537. /* falls through */
  17538. case 'SSS':
  17539. if (strict) { return parseTokenThreeDigits; }
  17540. /* falls through */
  17541. case 'DDD':
  17542. return parseTokenOneToThreeDigits;
  17543. case 'MMM':
  17544. case 'MMMM':
  17545. case 'dd':
  17546. case 'ddd':
  17547. case 'dddd':
  17548. return parseTokenWord;
  17549. case 'a':
  17550. case 'A':
  17551. return getLangDefinition(config._l)._meridiemParse;
  17552. case 'X':
  17553. return parseTokenTimestampMs;
  17554. case 'Z':
  17555. case 'ZZ':
  17556. return parseTokenTimezone;
  17557. case 'T':
  17558. return parseTokenT;
  17559. case 'SSSS':
  17560. return parseTokenDigits;
  17561. case 'MM':
  17562. case 'DD':
  17563. case 'YY':
  17564. case 'GG':
  17565. case 'gg':
  17566. case 'HH':
  17567. case 'hh':
  17568. case 'mm':
  17569. case 'ss':
  17570. case 'ww':
  17571. case 'WW':
  17572. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  17573. case 'M':
  17574. case 'D':
  17575. case 'd':
  17576. case 'H':
  17577. case 'h':
  17578. case 'm':
  17579. case 's':
  17580. case 'w':
  17581. case 'W':
  17582. case 'e':
  17583. case 'E':
  17584. return parseTokenOneOrTwoDigits;
  17585. case 'Do':
  17586. return parseTokenOrdinal;
  17587. default :
  17588. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  17589. return a;
  17590. }
  17591. }
  17592. function timezoneMinutesFromString(string) {
  17593. string = string || "";
  17594. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  17595. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  17596. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  17597. minutes = +(parts[1] * 60) + toInt(parts[2]);
  17598. return parts[0] === '+' ? -minutes : minutes;
  17599. }
  17600. // function to convert string input to date
  17601. function addTimeToArrayFromToken(token, input, config) {
  17602. var a, datePartArray = config._a;
  17603. switch (token) {
  17604. // QUARTER
  17605. case 'Q':
  17606. if (input != null) {
  17607. datePartArray[MONTH] = (toInt(input) - 1) * 3;
  17608. }
  17609. break;
  17610. // MONTH
  17611. case 'M' : // fall through to MM
  17612. case 'MM' :
  17613. if (input != null) {
  17614. datePartArray[MONTH] = toInt(input) - 1;
  17615. }
  17616. break;
  17617. case 'MMM' : // fall through to MMMM
  17618. case 'MMMM' :
  17619. a = getLangDefinition(config._l).monthsParse(input);
  17620. // if we didn't find a month name, mark the date as invalid.
  17621. if (a != null) {
  17622. datePartArray[MONTH] = a;
  17623. } else {
  17624. config._pf.invalidMonth = input;
  17625. }
  17626. break;
  17627. // DAY OF MONTH
  17628. case 'D' : // fall through to DD
  17629. case 'DD' :
  17630. if (input != null) {
  17631. datePartArray[DATE] = toInt(input);
  17632. }
  17633. break;
  17634. case 'Do' :
  17635. if (input != null) {
  17636. datePartArray[DATE] = toInt(parseInt(input, 10));
  17637. }
  17638. break;
  17639. // DAY OF YEAR
  17640. case 'DDD' : // fall through to DDDD
  17641. case 'DDDD' :
  17642. if (input != null) {
  17643. config._dayOfYear = toInt(input);
  17644. }
  17645. break;
  17646. // YEAR
  17647. case 'YY' :
  17648. datePartArray[YEAR] = moment.parseTwoDigitYear(input);
  17649. break;
  17650. case 'YYYY' :
  17651. case 'YYYYY' :
  17652. case 'YYYYYY' :
  17653. datePartArray[YEAR] = toInt(input);
  17654. break;
  17655. // AM / PM
  17656. case 'a' : // fall through to A
  17657. case 'A' :
  17658. config._isPm = getLangDefinition(config._l).isPM(input);
  17659. break;
  17660. // 24 HOUR
  17661. case 'H' : // fall through to hh
  17662. case 'HH' : // fall through to hh
  17663. case 'h' : // fall through to hh
  17664. case 'hh' :
  17665. datePartArray[HOUR] = toInt(input);
  17666. break;
  17667. // MINUTE
  17668. case 'm' : // fall through to mm
  17669. case 'mm' :
  17670. datePartArray[MINUTE] = toInt(input);
  17671. break;
  17672. // SECOND
  17673. case 's' : // fall through to ss
  17674. case 'ss' :
  17675. datePartArray[SECOND] = toInt(input);
  17676. break;
  17677. // MILLISECOND
  17678. case 'S' :
  17679. case 'SS' :
  17680. case 'SSS' :
  17681. case 'SSSS' :
  17682. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  17683. break;
  17684. // UNIX TIMESTAMP WITH MS
  17685. case 'X':
  17686. config._d = new Date(parseFloat(input) * 1000);
  17687. break;
  17688. // TIMEZONE
  17689. case 'Z' : // fall through to ZZ
  17690. case 'ZZ' :
  17691. config._useUTC = true;
  17692. config._tzm = timezoneMinutesFromString(input);
  17693. break;
  17694. case 'w':
  17695. case 'ww':
  17696. case 'W':
  17697. case 'WW':
  17698. case 'd':
  17699. case 'dd':
  17700. case 'ddd':
  17701. case 'dddd':
  17702. case 'e':
  17703. case 'E':
  17704. token = token.substr(0, 1);
  17705. /* falls through */
  17706. case 'gg':
  17707. case 'gggg':
  17708. case 'GG':
  17709. case 'GGGG':
  17710. case 'GGGGG':
  17711. token = token.substr(0, 2);
  17712. if (input) {
  17713. config._w = config._w || {};
  17714. config._w[token] = input;
  17715. }
  17716. break;
  17717. }
  17718. }
  17719. // convert an array to a date.
  17720. // the array should mirror the parameters below
  17721. // note: all values past the year are optional and will default to the lowest possible value.
  17722. // [year, month, day , hour, minute, second, millisecond]
  17723. function dateFromConfig(config) {
  17724. var i, date, input = [], currentDate,
  17725. yearToUse, fixYear, w, temp, lang, weekday, week;
  17726. if (config._d) {
  17727. return;
  17728. }
  17729. currentDate = currentDateArray(config);
  17730. //compute day of the year from weeks and weekdays
  17731. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  17732. fixYear = function (val) {
  17733. var intVal = parseInt(val, 10);
  17734. return val ?
  17735. (val.length < 3 ? (intVal > 68 ? 1900 + intVal : 2000 + intVal) : intVal) :
  17736. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  17737. };
  17738. w = config._w;
  17739. if (w.GG != null || w.W != null || w.E != null) {
  17740. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  17741. }
  17742. else {
  17743. lang = getLangDefinition(config._l);
  17744. weekday = w.d != null ? parseWeekday(w.d, lang) :
  17745. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  17746. week = parseInt(w.w, 10) || 1;
  17747. //if we're parsing 'd', then the low day numbers may be next week
  17748. if (w.d != null && weekday < lang._week.dow) {
  17749. week++;
  17750. }
  17751. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  17752. }
  17753. config._a[YEAR] = temp.year;
  17754. config._dayOfYear = temp.dayOfYear;
  17755. }
  17756. //if the day of the year is set, figure out what it is
  17757. if (config._dayOfYear) {
  17758. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  17759. if (config._dayOfYear > daysInYear(yearToUse)) {
  17760. config._pf._overflowDayOfYear = true;
  17761. }
  17762. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  17763. config._a[MONTH] = date.getUTCMonth();
  17764. config._a[DATE] = date.getUTCDate();
  17765. }
  17766. // Default to current date.
  17767. // * if no year, month, day of month are given, default to today
  17768. // * if day of month is given, default month and year
  17769. // * if month is given, default only year
  17770. // * if year is given, don't default anything
  17771. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  17772. config._a[i] = input[i] = currentDate[i];
  17773. }
  17774. // Zero out whatever was not defaulted, including time
  17775. for (; i < 7; i++) {
  17776. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  17777. }
  17778. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  17779. input[HOUR] += toInt((config._tzm || 0) / 60);
  17780. input[MINUTE] += toInt((config._tzm || 0) % 60);
  17781. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  17782. }
  17783. function dateFromObject(config) {
  17784. var normalizedInput;
  17785. if (config._d) {
  17786. return;
  17787. }
  17788. normalizedInput = normalizeObjectUnits(config._i);
  17789. config._a = [
  17790. normalizedInput.year,
  17791. normalizedInput.month,
  17792. normalizedInput.day,
  17793. normalizedInput.hour,
  17794. normalizedInput.minute,
  17795. normalizedInput.second,
  17796. normalizedInput.millisecond
  17797. ];
  17798. dateFromConfig(config);
  17799. }
  17800. function currentDateArray(config) {
  17801. var now = new Date();
  17802. if (config._useUTC) {
  17803. return [
  17804. now.getUTCFullYear(),
  17805. now.getUTCMonth(),
  17806. now.getUTCDate()
  17807. ];
  17808. } else {
  17809. return [now.getFullYear(), now.getMonth(), now.getDate()];
  17810. }
  17811. }
  17812. // date from string and format string
  17813. function makeDateFromStringAndFormat(config) {
  17814. config._a = [];
  17815. config._pf.empty = true;
  17816. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  17817. var lang = getLangDefinition(config._l),
  17818. string = '' + config._i,
  17819. i, parsedInput, tokens, token, skipped,
  17820. stringLength = string.length,
  17821. totalParsedInputLength = 0;
  17822. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  17823. for (i = 0; i < tokens.length; i++) {
  17824. token = tokens[i];
  17825. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  17826. if (parsedInput) {
  17827. skipped = string.substr(0, string.indexOf(parsedInput));
  17828. if (skipped.length > 0) {
  17829. config._pf.unusedInput.push(skipped);
  17830. }
  17831. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  17832. totalParsedInputLength += parsedInput.length;
  17833. }
  17834. // don't parse if it's not a known token
  17835. if (formatTokenFunctions[token]) {
  17836. if (parsedInput) {
  17837. config._pf.empty = false;
  17838. }
  17839. else {
  17840. config._pf.unusedTokens.push(token);
  17841. }
  17842. addTimeToArrayFromToken(token, parsedInput, config);
  17843. }
  17844. else if (config._strict && !parsedInput) {
  17845. config._pf.unusedTokens.push(token);
  17846. }
  17847. }
  17848. // add remaining unparsed input length to the string
  17849. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  17850. if (string.length > 0) {
  17851. config._pf.unusedInput.push(string);
  17852. }
  17853. // handle am pm
  17854. if (config._isPm && config._a[HOUR] < 12) {
  17855. config._a[HOUR] += 12;
  17856. }
  17857. // if is 12 am, change hours to 0
  17858. if (config._isPm === false && config._a[HOUR] === 12) {
  17859. config._a[HOUR] = 0;
  17860. }
  17861. dateFromConfig(config);
  17862. checkOverflow(config);
  17863. }
  17864. function unescapeFormat(s) {
  17865. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  17866. return p1 || p2 || p3 || p4;
  17867. });
  17868. }
  17869. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  17870. function regexpEscape(s) {
  17871. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  17872. }
  17873. // date from string and array of format strings
  17874. function makeDateFromStringAndArray(config) {
  17875. var tempConfig,
  17876. bestMoment,
  17877. scoreToBeat,
  17878. i,
  17879. currentScore;
  17880. if (config._f.length === 0) {
  17881. config._pf.invalidFormat = true;
  17882. config._d = new Date(NaN);
  17883. return;
  17884. }
  17885. for (i = 0; i < config._f.length; i++) {
  17886. currentScore = 0;
  17887. tempConfig = extend({}, config);
  17888. tempConfig._pf = defaultParsingFlags();
  17889. tempConfig._f = config._f[i];
  17890. makeDateFromStringAndFormat(tempConfig);
  17891. if (!isValid(tempConfig)) {
  17892. continue;
  17893. }
  17894. // if there is any input that was not parsed add a penalty for that format
  17895. currentScore += tempConfig._pf.charsLeftOver;
  17896. //or tokens
  17897. currentScore += tempConfig._pf.unusedTokens.length * 10;
  17898. tempConfig._pf.score = currentScore;
  17899. if (scoreToBeat == null || currentScore < scoreToBeat) {
  17900. scoreToBeat = currentScore;
  17901. bestMoment = tempConfig;
  17902. }
  17903. }
  17904. extend(config, bestMoment || tempConfig);
  17905. }
  17906. // date from iso format
  17907. function makeDateFromString(config) {
  17908. var i, l,
  17909. string = config._i,
  17910. match = isoRegex.exec(string);
  17911. if (match) {
  17912. config._pf.iso = true;
  17913. for (i = 0, l = isoDates.length; i < l; i++) {
  17914. if (isoDates[i][1].exec(string)) {
  17915. // match[5] should be "T" or undefined
  17916. config._f = isoDates[i][0] + (match[6] || " ");
  17917. break;
  17918. }
  17919. }
  17920. for (i = 0, l = isoTimes.length; i < l; i++) {
  17921. if (isoTimes[i][1].exec(string)) {
  17922. config._f += isoTimes[i][0];
  17923. break;
  17924. }
  17925. }
  17926. if (string.match(parseTokenTimezone)) {
  17927. config._f += "Z";
  17928. }
  17929. makeDateFromStringAndFormat(config);
  17930. }
  17931. else {
  17932. moment.createFromInputFallback(config);
  17933. }
  17934. }
  17935. function makeDateFromInput(config) {
  17936. var input = config._i,
  17937. matched = aspNetJsonRegex.exec(input);
  17938. if (input === undefined) {
  17939. config._d = new Date();
  17940. } else if (matched) {
  17941. config._d = new Date(+matched[1]);
  17942. } else if (typeof input === 'string') {
  17943. makeDateFromString(config);
  17944. } else if (isArray(input)) {
  17945. config._a = input.slice(0);
  17946. dateFromConfig(config);
  17947. } else if (isDate(input)) {
  17948. config._d = new Date(+input);
  17949. } else if (typeof(input) === 'object') {
  17950. dateFromObject(config);
  17951. } else if (typeof(input) === 'number') {
  17952. // from milliseconds
  17953. config._d = new Date(input);
  17954. } else {
  17955. moment.createFromInputFallback(config);
  17956. }
  17957. }
  17958. function makeDate(y, m, d, h, M, s, ms) {
  17959. //can't just apply() to create a date:
  17960. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  17961. var date = new Date(y, m, d, h, M, s, ms);
  17962. //the date constructor doesn't accept years < 1970
  17963. if (y < 1970) {
  17964. date.setFullYear(y);
  17965. }
  17966. return date;
  17967. }
  17968. function makeUTCDate(y) {
  17969. var date = new Date(Date.UTC.apply(null, arguments));
  17970. if (y < 1970) {
  17971. date.setUTCFullYear(y);
  17972. }
  17973. return date;
  17974. }
  17975. function parseWeekday(input, language) {
  17976. if (typeof input === 'string') {
  17977. if (!isNaN(input)) {
  17978. input = parseInt(input, 10);
  17979. }
  17980. else {
  17981. input = language.weekdaysParse(input);
  17982. if (typeof input !== 'number') {
  17983. return null;
  17984. }
  17985. }
  17986. }
  17987. return input;
  17988. }
  17989. /************************************
  17990. Relative Time
  17991. ************************************/
  17992. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  17993. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  17994. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  17995. }
  17996. function relativeTime(milliseconds, withoutSuffix, lang) {
  17997. var seconds = round(Math.abs(milliseconds) / 1000),
  17998. minutes = round(seconds / 60),
  17999. hours = round(minutes / 60),
  18000. days = round(hours / 24),
  18001. years = round(days / 365),
  18002. args = seconds < 45 && ['s', seconds] ||
  18003. minutes === 1 && ['m'] ||
  18004. minutes < 45 && ['mm', minutes] ||
  18005. hours === 1 && ['h'] ||
  18006. hours < 22 && ['hh', hours] ||
  18007. days === 1 && ['d'] ||
  18008. days <= 25 && ['dd', days] ||
  18009. days <= 45 && ['M'] ||
  18010. days < 345 && ['MM', round(days / 30)] ||
  18011. years === 1 && ['y'] || ['yy', years];
  18012. args[2] = withoutSuffix;
  18013. args[3] = milliseconds > 0;
  18014. args[4] = lang;
  18015. return substituteTimeAgo.apply({}, args);
  18016. }
  18017. /************************************
  18018. Week of Year
  18019. ************************************/
  18020. // firstDayOfWeek 0 = sun, 6 = sat
  18021. // the day of the week that starts the week
  18022. // (usually sunday or monday)
  18023. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18024. // the first week is the week that contains the first
  18025. // of this day of the week
  18026. // (eg. ISO weeks use thursday (4))
  18027. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18028. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18029. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18030. adjustedMoment;
  18031. if (daysToDayOfWeek > end) {
  18032. daysToDayOfWeek -= 7;
  18033. }
  18034. if (daysToDayOfWeek < end - 7) {
  18035. daysToDayOfWeek += 7;
  18036. }
  18037. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18038. return {
  18039. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18040. year: adjustedMoment.year()
  18041. };
  18042. }
  18043. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18044. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18045. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18046. weekday = weekday != null ? weekday : firstDayOfWeek;
  18047. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18048. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18049. return {
  18050. year: dayOfYear > 0 ? year : year - 1,
  18051. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18052. };
  18053. }
  18054. /************************************
  18055. Top Level Functions
  18056. ************************************/
  18057. function makeMoment(config) {
  18058. var input = config._i,
  18059. format = config._f;
  18060. if (input === null || (format === undefined && input === '')) {
  18061. return moment.invalid({nullInput: true});
  18062. }
  18063. if (typeof input === 'string') {
  18064. config._i = input = getLangDefinition().preparse(input);
  18065. }
  18066. if (moment.isMoment(input)) {
  18067. config = cloneMoment(input);
  18068. config._d = new Date(+input._d);
  18069. } else if (format) {
  18070. if (isArray(format)) {
  18071. makeDateFromStringAndArray(config);
  18072. } else {
  18073. makeDateFromStringAndFormat(config);
  18074. }
  18075. } else {
  18076. makeDateFromInput(config);
  18077. }
  18078. return new Moment(config);
  18079. }
  18080. moment = function (input, format, lang, strict) {
  18081. var c;
  18082. if (typeof(lang) === "boolean") {
  18083. strict = lang;
  18084. lang = undefined;
  18085. }
  18086. // object construction must be done this way.
  18087. // https://github.com/moment/moment/issues/1423
  18088. c = {};
  18089. c._isAMomentObject = true;
  18090. c._i = input;
  18091. c._f = format;
  18092. c._l = lang;
  18093. c._strict = strict;
  18094. c._isUTC = false;
  18095. c._pf = defaultParsingFlags();
  18096. return makeMoment(c);
  18097. };
  18098. moment.suppressDeprecationWarnings = false;
  18099. moment.createFromInputFallback = deprecate(
  18100. "moment construction falls back to js Date. This is " +
  18101. "discouraged and will be removed in upcoming major " +
  18102. "release. Please refer to " +
  18103. "https://github.com/moment/moment/issues/1407 for more info.",
  18104. function (config) {
  18105. config._d = new Date(config._i);
  18106. });
  18107. // creating with utc
  18108. moment.utc = function (input, format, lang, strict) {
  18109. var c;
  18110. if (typeof(lang) === "boolean") {
  18111. strict = lang;
  18112. lang = undefined;
  18113. }
  18114. // object construction must be done this way.
  18115. // https://github.com/moment/moment/issues/1423
  18116. c = {};
  18117. c._isAMomentObject = true;
  18118. c._useUTC = true;
  18119. c._isUTC = true;
  18120. c._l = lang;
  18121. c._i = input;
  18122. c._f = format;
  18123. c._strict = strict;
  18124. c._pf = defaultParsingFlags();
  18125. return makeMoment(c).utc();
  18126. };
  18127. // creating with unix timestamp (in seconds)
  18128. moment.unix = function (input) {
  18129. return moment(input * 1000);
  18130. };
  18131. // duration
  18132. moment.duration = function (input, key) {
  18133. var duration = input,
  18134. // matching against regexp is expensive, do it on demand
  18135. match = null,
  18136. sign,
  18137. ret,
  18138. parseIso;
  18139. if (moment.isDuration(input)) {
  18140. duration = {
  18141. ms: input._milliseconds,
  18142. d: input._days,
  18143. M: input._months
  18144. };
  18145. } else if (typeof input === 'number') {
  18146. duration = {};
  18147. if (key) {
  18148. duration[key] = input;
  18149. } else {
  18150. duration.milliseconds = input;
  18151. }
  18152. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18153. sign = (match[1] === "-") ? -1 : 1;
  18154. duration = {
  18155. y: 0,
  18156. d: toInt(match[DATE]) * sign,
  18157. h: toInt(match[HOUR]) * sign,
  18158. m: toInt(match[MINUTE]) * sign,
  18159. s: toInt(match[SECOND]) * sign,
  18160. ms: toInt(match[MILLISECOND]) * sign
  18161. };
  18162. } else if (!!(match = isoDurationRegex.exec(input))) {
  18163. sign = (match[1] === "-") ? -1 : 1;
  18164. parseIso = function (inp) {
  18165. // We'd normally use ~~inp for this, but unfortunately it also
  18166. // converts floats to ints.
  18167. // inp may be undefined, so careful calling replace on it.
  18168. var res = inp && parseFloat(inp.replace(',', '.'));
  18169. // apply sign while we're at it
  18170. return (isNaN(res) ? 0 : res) * sign;
  18171. };
  18172. duration = {
  18173. y: parseIso(match[2]),
  18174. M: parseIso(match[3]),
  18175. d: parseIso(match[4]),
  18176. h: parseIso(match[5]),
  18177. m: parseIso(match[6]),
  18178. s: parseIso(match[7]),
  18179. w: parseIso(match[8])
  18180. };
  18181. }
  18182. ret = new Duration(duration);
  18183. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18184. ret._lang = input._lang;
  18185. }
  18186. return ret;
  18187. };
  18188. // version number
  18189. moment.version = VERSION;
  18190. // default format
  18191. moment.defaultFormat = isoFormat;
  18192. // Plugins that add properties should also add the key here (null value),
  18193. // so we can properly clone ourselves.
  18194. moment.momentProperties = momentProperties;
  18195. // This function will be called whenever a moment is mutated.
  18196. // It is intended to keep the offset in sync with the timezone.
  18197. moment.updateOffset = function () {};
  18198. // This function will load languages and then set the global language. If
  18199. // no arguments are passed in, it will simply return the current global
  18200. // language key.
  18201. moment.lang = function (key, values) {
  18202. var r;
  18203. if (!key) {
  18204. return moment.fn._lang._abbr;
  18205. }
  18206. if (values) {
  18207. loadLang(normalizeLanguage(key), values);
  18208. } else if (values === null) {
  18209. unloadLang(key);
  18210. key = 'en';
  18211. } else if (!languages[key]) {
  18212. getLangDefinition(key);
  18213. }
  18214. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18215. return r._abbr;
  18216. };
  18217. // returns language data
  18218. moment.langData = function (key) {
  18219. if (key && key._lang && key._lang._abbr) {
  18220. key = key._lang._abbr;
  18221. }
  18222. return getLangDefinition(key);
  18223. };
  18224. // compare moment object
  18225. moment.isMoment = function (obj) {
  18226. return obj instanceof Moment ||
  18227. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18228. };
  18229. // for typechecking Duration objects
  18230. moment.isDuration = function (obj) {
  18231. return obj instanceof Duration;
  18232. };
  18233. for (i = lists.length - 1; i >= 0; --i) {
  18234. makeList(lists[i]);
  18235. }
  18236. moment.normalizeUnits = function (units) {
  18237. return normalizeUnits(units);
  18238. };
  18239. moment.invalid = function (flags) {
  18240. var m = moment.utc(NaN);
  18241. if (flags != null) {
  18242. extend(m._pf, flags);
  18243. }
  18244. else {
  18245. m._pf.userInvalidated = true;
  18246. }
  18247. return m;
  18248. };
  18249. moment.parseZone = function () {
  18250. return moment.apply(null, arguments).parseZone();
  18251. };
  18252. moment.parseTwoDigitYear = function (input) {
  18253. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  18254. };
  18255. /************************************
  18256. Moment Prototype
  18257. ************************************/
  18258. extend(moment.fn = Moment.prototype, {
  18259. clone : function () {
  18260. return moment(this);
  18261. },
  18262. valueOf : function () {
  18263. return +this._d + ((this._offset || 0) * 60000);
  18264. },
  18265. unix : function () {
  18266. return Math.floor(+this / 1000);
  18267. },
  18268. toString : function () {
  18269. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18270. },
  18271. toDate : function () {
  18272. return this._offset ? new Date(+this) : this._d;
  18273. },
  18274. toISOString : function () {
  18275. var m = moment(this).utc();
  18276. if (0 < m.year() && m.year() <= 9999) {
  18277. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18278. } else {
  18279. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18280. }
  18281. },
  18282. toArray : function () {
  18283. var m = this;
  18284. return [
  18285. m.year(),
  18286. m.month(),
  18287. m.date(),
  18288. m.hours(),
  18289. m.minutes(),
  18290. m.seconds(),
  18291. m.milliseconds()
  18292. ];
  18293. },
  18294. isValid : function () {
  18295. return isValid(this);
  18296. },
  18297. isDSTShifted : function () {
  18298. if (this._a) {
  18299. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18300. }
  18301. return false;
  18302. },
  18303. parsingFlags : function () {
  18304. return extend({}, this._pf);
  18305. },
  18306. invalidAt: function () {
  18307. return this._pf.overflow;
  18308. },
  18309. utc : function () {
  18310. return this.zone(0);
  18311. },
  18312. local : function () {
  18313. this.zone(0);
  18314. this._isUTC = false;
  18315. return this;
  18316. },
  18317. format : function (inputString) {
  18318. var output = formatMoment(this, inputString || moment.defaultFormat);
  18319. return this.lang().postformat(output);
  18320. },
  18321. add : function (input, val) {
  18322. var dur;
  18323. // switch args to support add('s', 1) and add(1, 's')
  18324. if (typeof input === 'string') {
  18325. dur = moment.duration(+val, input);
  18326. } else {
  18327. dur = moment.duration(input, val);
  18328. }
  18329. addOrSubtractDurationFromMoment(this, dur, 1);
  18330. return this;
  18331. },
  18332. subtract : function (input, val) {
  18333. var dur;
  18334. // switch args to support subtract('s', 1) and subtract(1, 's')
  18335. if (typeof input === 'string') {
  18336. dur = moment.duration(+val, input);
  18337. } else {
  18338. dur = moment.duration(input, val);
  18339. }
  18340. addOrSubtractDurationFromMoment(this, dur, -1);
  18341. return this;
  18342. },
  18343. diff : function (input, units, asFloat) {
  18344. var that = makeAs(input, this),
  18345. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18346. diff, output;
  18347. units = normalizeUnits(units);
  18348. if (units === 'year' || units === 'month') {
  18349. // average number of days in the months in the given dates
  18350. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18351. // difference in months
  18352. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18353. // adjust by taking difference in days, average number of days
  18354. // and dst in the given months.
  18355. output += ((this - moment(this).startOf('month')) -
  18356. (that - moment(that).startOf('month'))) / diff;
  18357. // same as above but with zones, to negate all dst
  18358. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18359. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18360. if (units === 'year') {
  18361. output = output / 12;
  18362. }
  18363. } else {
  18364. diff = (this - that);
  18365. output = units === 'second' ? diff / 1e3 : // 1000
  18366. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18367. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18368. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18369. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18370. diff;
  18371. }
  18372. return asFloat ? output : absRound(output);
  18373. },
  18374. from : function (time, withoutSuffix) {
  18375. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18376. },
  18377. fromNow : function (withoutSuffix) {
  18378. return this.from(moment(), withoutSuffix);
  18379. },
  18380. calendar : function () {
  18381. // We want to compare the start of today, vs this.
  18382. // Getting start-of-today depends on whether we're zone'd or not.
  18383. var sod = makeAs(moment(), this).startOf('day'),
  18384. diff = this.diff(sod, 'days', true),
  18385. format = diff < -6 ? 'sameElse' :
  18386. diff < -1 ? 'lastWeek' :
  18387. diff < 0 ? 'lastDay' :
  18388. diff < 1 ? 'sameDay' :
  18389. diff < 2 ? 'nextDay' :
  18390. diff < 7 ? 'nextWeek' : 'sameElse';
  18391. return this.format(this.lang().calendar(format, this));
  18392. },
  18393. isLeapYear : function () {
  18394. return isLeapYear(this.year());
  18395. },
  18396. isDST : function () {
  18397. return (this.zone() < this.clone().month(0).zone() ||
  18398. this.zone() < this.clone().month(5).zone());
  18399. },
  18400. day : function (input) {
  18401. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18402. if (input != null) {
  18403. input = parseWeekday(input, this.lang());
  18404. return this.add({ d : input - day });
  18405. } else {
  18406. return day;
  18407. }
  18408. },
  18409. month : makeAccessor('Month', true),
  18410. startOf: function (units) {
  18411. units = normalizeUnits(units);
  18412. // the following switch intentionally omits break keywords
  18413. // to utilize falling through the cases.
  18414. switch (units) {
  18415. case 'year':
  18416. this.month(0);
  18417. /* falls through */
  18418. case 'quarter':
  18419. case 'month':
  18420. this.date(1);
  18421. /* falls through */
  18422. case 'week':
  18423. case 'isoWeek':
  18424. case 'day':
  18425. this.hours(0);
  18426. /* falls through */
  18427. case 'hour':
  18428. this.minutes(0);
  18429. /* falls through */
  18430. case 'minute':
  18431. this.seconds(0);
  18432. /* falls through */
  18433. case 'second':
  18434. this.milliseconds(0);
  18435. /* falls through */
  18436. }
  18437. // weeks are a special case
  18438. if (units === 'week') {
  18439. this.weekday(0);
  18440. } else if (units === 'isoWeek') {
  18441. this.isoWeekday(1);
  18442. }
  18443. // quarters are also special
  18444. if (units === 'quarter') {
  18445. this.month(Math.floor(this.month() / 3) * 3);
  18446. }
  18447. return this;
  18448. },
  18449. endOf: function (units) {
  18450. units = normalizeUnits(units);
  18451. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18452. },
  18453. isAfter: function (input, units) {
  18454. units = typeof units !== 'undefined' ? units : 'millisecond';
  18455. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18456. },
  18457. isBefore: function (input, units) {
  18458. units = typeof units !== 'undefined' ? units : 'millisecond';
  18459. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18460. },
  18461. isSame: function (input, units) {
  18462. units = units || 'ms';
  18463. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18464. },
  18465. min: function (other) {
  18466. other = moment.apply(null, arguments);
  18467. return other < this ? this : other;
  18468. },
  18469. max: function (other) {
  18470. other = moment.apply(null, arguments);
  18471. return other > this ? this : other;
  18472. },
  18473. // keepTime = true means only change the timezone, without affecting
  18474. // the local hour. So 5:31:26 +0300 --[zone(2, true)]--> 5:31:26 +0200
  18475. // It is possible that 5:31:26 doesn't exist int zone +0200, so we
  18476. // adjust the time as needed, to be valid.
  18477. //
  18478. // Keeping the time actually adds/subtracts (one hour)
  18479. // from the actual represented time. That is why we call updateOffset
  18480. // a second time. In case it wants us to change the offset again
  18481. // _changeInProgress == true case, then we have to adjust, because
  18482. // there is no such time in the given timezone.
  18483. zone : function (input, keepTime) {
  18484. var offset = this._offset || 0;
  18485. if (input != null) {
  18486. if (typeof input === "string") {
  18487. input = timezoneMinutesFromString(input);
  18488. }
  18489. if (Math.abs(input) < 16) {
  18490. input = input * 60;
  18491. }
  18492. this._offset = input;
  18493. this._isUTC = true;
  18494. if (offset !== input) {
  18495. if (!keepTime || this._changeInProgress) {
  18496. addOrSubtractDurationFromMoment(this,
  18497. moment.duration(offset - input, 'm'), 1, false);
  18498. } else if (!this._changeInProgress) {
  18499. this._changeInProgress = true;
  18500. moment.updateOffset(this, true);
  18501. this._changeInProgress = null;
  18502. }
  18503. }
  18504. } else {
  18505. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18506. }
  18507. return this;
  18508. },
  18509. zoneAbbr : function () {
  18510. return this._isUTC ? "UTC" : "";
  18511. },
  18512. zoneName : function () {
  18513. return this._isUTC ? "Coordinated Universal Time" : "";
  18514. },
  18515. parseZone : function () {
  18516. if (this._tzm) {
  18517. this.zone(this._tzm);
  18518. } else if (typeof this._i === 'string') {
  18519. this.zone(this._i);
  18520. }
  18521. return this;
  18522. },
  18523. hasAlignedHourOffset : function (input) {
  18524. if (!input) {
  18525. input = 0;
  18526. }
  18527. else {
  18528. input = moment(input).zone();
  18529. }
  18530. return (this.zone() - input) % 60 === 0;
  18531. },
  18532. daysInMonth : function () {
  18533. return daysInMonth(this.year(), this.month());
  18534. },
  18535. dayOfYear : function (input) {
  18536. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  18537. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  18538. },
  18539. quarter : function (input) {
  18540. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  18541. },
  18542. weekYear : function (input) {
  18543. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  18544. return input == null ? year : this.add("y", (input - year));
  18545. },
  18546. isoWeekYear : function (input) {
  18547. var year = weekOfYear(this, 1, 4).year;
  18548. return input == null ? year : this.add("y", (input - year));
  18549. },
  18550. week : function (input) {
  18551. var week = this.lang().week(this);
  18552. return input == null ? week : this.add("d", (input - week) * 7);
  18553. },
  18554. isoWeek : function (input) {
  18555. var week = weekOfYear(this, 1, 4).week;
  18556. return input == null ? week : this.add("d", (input - week) * 7);
  18557. },
  18558. weekday : function (input) {
  18559. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  18560. return input == null ? weekday : this.add("d", input - weekday);
  18561. },
  18562. isoWeekday : function (input) {
  18563. // behaves the same as moment#day except
  18564. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  18565. // as a setter, sunday should belong to the previous week.
  18566. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  18567. },
  18568. isoWeeksInYear : function () {
  18569. return weeksInYear(this.year(), 1, 4);
  18570. },
  18571. weeksInYear : function () {
  18572. var weekInfo = this._lang._week;
  18573. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  18574. },
  18575. get : function (units) {
  18576. units = normalizeUnits(units);
  18577. return this[units]();
  18578. },
  18579. set : function (units, value) {
  18580. units = normalizeUnits(units);
  18581. if (typeof this[units] === 'function') {
  18582. this[units](value);
  18583. }
  18584. return this;
  18585. },
  18586. // If passed a language key, it will set the language for this
  18587. // instance. Otherwise, it will return the language configuration
  18588. // variables for this instance.
  18589. lang : function (key) {
  18590. if (key === undefined) {
  18591. return this._lang;
  18592. } else {
  18593. this._lang = getLangDefinition(key);
  18594. return this;
  18595. }
  18596. }
  18597. });
  18598. function rawMonthSetter(mom, value) {
  18599. var dayOfMonth;
  18600. // TODO: Move this out of here!
  18601. if (typeof value === 'string') {
  18602. value = mom.lang().monthsParse(value);
  18603. // TODO: Another silent failure?
  18604. if (typeof value !== 'number') {
  18605. return mom;
  18606. }
  18607. }
  18608. dayOfMonth = Math.min(mom.date(),
  18609. daysInMonth(mom.year(), value));
  18610. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  18611. return mom;
  18612. }
  18613. function rawGetter(mom, unit) {
  18614. return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
  18615. }
  18616. function rawSetter(mom, unit, value) {
  18617. if (unit === 'Month') {
  18618. return rawMonthSetter(mom, value);
  18619. } else {
  18620. return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  18621. }
  18622. }
  18623. function makeAccessor(unit, keepTime) {
  18624. return function (value) {
  18625. if (value != null) {
  18626. rawSetter(this, unit, value);
  18627. moment.updateOffset(this, keepTime);
  18628. return this;
  18629. } else {
  18630. return rawGetter(this, unit);
  18631. }
  18632. };
  18633. }
  18634. moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
  18635. moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
  18636. moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
  18637. // Setting the hour should keep the time, because the user explicitly
  18638. // specified which hour he wants. So trying to maintain the same hour (in
  18639. // a new timezone) makes sense. Adding/subtracting hours does not follow
  18640. // this rule.
  18641. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
  18642. // moment.fn.month is defined separately
  18643. moment.fn.date = makeAccessor('Date', true);
  18644. moment.fn.dates = deprecate("dates accessor is deprecated. Use date instead.", makeAccessor('Date', true));
  18645. moment.fn.year = makeAccessor('FullYear', true);
  18646. moment.fn.years = deprecate("years accessor is deprecated. Use year instead.", makeAccessor('FullYear', true));
  18647. // add plural methods
  18648. moment.fn.days = moment.fn.day;
  18649. moment.fn.months = moment.fn.month;
  18650. moment.fn.weeks = moment.fn.week;
  18651. moment.fn.isoWeeks = moment.fn.isoWeek;
  18652. moment.fn.quarters = moment.fn.quarter;
  18653. // add aliased format methods
  18654. moment.fn.toJSON = moment.fn.toISOString;
  18655. /************************************
  18656. Duration Prototype
  18657. ************************************/
  18658. extend(moment.duration.fn = Duration.prototype, {
  18659. _bubble : function () {
  18660. var milliseconds = this._milliseconds,
  18661. days = this._days,
  18662. months = this._months,
  18663. data = this._data,
  18664. seconds, minutes, hours, years;
  18665. // The following code bubbles up values, see the tests for
  18666. // examples of what that means.
  18667. data.milliseconds = milliseconds % 1000;
  18668. seconds = absRound(milliseconds / 1000);
  18669. data.seconds = seconds % 60;
  18670. minutes = absRound(seconds / 60);
  18671. data.minutes = minutes % 60;
  18672. hours = absRound(minutes / 60);
  18673. data.hours = hours % 24;
  18674. days += absRound(hours / 24);
  18675. data.days = days % 30;
  18676. months += absRound(days / 30);
  18677. data.months = months % 12;
  18678. years = absRound(months / 12);
  18679. data.years = years;
  18680. },
  18681. weeks : function () {
  18682. return absRound(this.days() / 7);
  18683. },
  18684. valueOf : function () {
  18685. return this._milliseconds +
  18686. this._days * 864e5 +
  18687. (this._months % 12) * 2592e6 +
  18688. toInt(this._months / 12) * 31536e6;
  18689. },
  18690. humanize : function (withSuffix) {
  18691. var difference = +this,
  18692. output = relativeTime(difference, !withSuffix, this.lang());
  18693. if (withSuffix) {
  18694. output = this.lang().pastFuture(difference, output);
  18695. }
  18696. return this.lang().postformat(output);
  18697. },
  18698. add : function (input, val) {
  18699. // supports only 2.0-style add(1, 's') or add(moment)
  18700. var dur = moment.duration(input, val);
  18701. this._milliseconds += dur._milliseconds;
  18702. this._days += dur._days;
  18703. this._months += dur._months;
  18704. this._bubble();
  18705. return this;
  18706. },
  18707. subtract : function (input, val) {
  18708. var dur = moment.duration(input, val);
  18709. this._milliseconds -= dur._milliseconds;
  18710. this._days -= dur._days;
  18711. this._months -= dur._months;
  18712. this._bubble();
  18713. return this;
  18714. },
  18715. get : function (units) {
  18716. units = normalizeUnits(units);
  18717. return this[units.toLowerCase() + 's']();
  18718. },
  18719. as : function (units) {
  18720. units = normalizeUnits(units);
  18721. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  18722. },
  18723. lang : moment.fn.lang,
  18724. toIsoString : function () {
  18725. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  18726. var years = Math.abs(this.years()),
  18727. months = Math.abs(this.months()),
  18728. days = Math.abs(this.days()),
  18729. hours = Math.abs(this.hours()),
  18730. minutes = Math.abs(this.minutes()),
  18731. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  18732. if (!this.asSeconds()) {
  18733. // this is the same as C#'s (Noda) and python (isodate)...
  18734. // but not other JS (goog.date)
  18735. return 'P0D';
  18736. }
  18737. return (this.asSeconds() < 0 ? '-' : '') +
  18738. 'P' +
  18739. (years ? years + 'Y' : '') +
  18740. (months ? months + 'M' : '') +
  18741. (days ? days + 'D' : '') +
  18742. ((hours || minutes || seconds) ? 'T' : '') +
  18743. (hours ? hours + 'H' : '') +
  18744. (minutes ? minutes + 'M' : '') +
  18745. (seconds ? seconds + 'S' : '');
  18746. }
  18747. });
  18748. function makeDurationGetter(name) {
  18749. moment.duration.fn[name] = function () {
  18750. return this._data[name];
  18751. };
  18752. }
  18753. function makeDurationAsGetter(name, factor) {
  18754. moment.duration.fn['as' + name] = function () {
  18755. return +this / factor;
  18756. };
  18757. }
  18758. for (i in unitMillisecondFactors) {
  18759. if (unitMillisecondFactors.hasOwnProperty(i)) {
  18760. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  18761. makeDurationGetter(i.toLowerCase());
  18762. }
  18763. }
  18764. makeDurationAsGetter('Weeks', 6048e5);
  18765. moment.duration.fn.asMonths = function () {
  18766. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  18767. };
  18768. /************************************
  18769. Default Lang
  18770. ************************************/
  18771. // Set default language, other languages will inherit from English.
  18772. moment.lang('en', {
  18773. ordinal : function (number) {
  18774. var b = number % 10,
  18775. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  18776. (b === 1) ? 'st' :
  18777. (b === 2) ? 'nd' :
  18778. (b === 3) ? 'rd' : 'th';
  18779. return number + output;
  18780. }
  18781. });
  18782. /* EMBED_LANGUAGES */
  18783. /************************************
  18784. Exposing Moment
  18785. ************************************/
  18786. function makeGlobal(shouldDeprecate) {
  18787. /*global ender:false */
  18788. if (typeof ender !== 'undefined') {
  18789. return;
  18790. }
  18791. oldGlobalMoment = globalScope.moment;
  18792. if (shouldDeprecate) {
  18793. globalScope.moment = deprecate(
  18794. "Accessing Moment through the global scope is " +
  18795. "deprecated, and will be removed in an upcoming " +
  18796. "release.",
  18797. moment);
  18798. } else {
  18799. globalScope.moment = moment;
  18800. }
  18801. }
  18802. // CommonJS module is defined
  18803. if (hasModule) {
  18804. module.exports = moment;
  18805. } else if (typeof define === "function" && define.amd) {
  18806. define("moment", function (require, exports, module) {
  18807. if (module.config && module.config() && module.config().noGlobal === true) {
  18808. // release the global variable
  18809. globalScope.moment = oldGlobalMoment;
  18810. }
  18811. return moment;
  18812. });
  18813. makeGlobal(true);
  18814. } else {
  18815. makeGlobal();
  18816. }
  18817. }).call(this);
  18818. },{}],5:[function(require,module,exports){
  18819. /**
  18820. * Copyright 2012 Craig Campbell
  18821. *
  18822. * Licensed under the Apache License, Version 2.0 (the "License");
  18823. * you may not use this file except in compliance with the License.
  18824. * You may obtain a copy of the License at
  18825. *
  18826. * http://www.apache.org/licenses/LICENSE-2.0
  18827. *
  18828. * Unless required by applicable law or agreed to in writing, software
  18829. * distributed under the License is distributed on an "AS IS" BASIS,
  18830. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18831. * See the License for the specific language governing permissions and
  18832. * limitations under the License.
  18833. *
  18834. * Mousetrap is a simple keyboard shortcut library for Javascript with
  18835. * no external dependencies
  18836. *
  18837. * @version 1.1.2
  18838. * @url craig.is/killing/mice
  18839. */
  18840. /**
  18841. * mapping of special keycodes to their corresponding keys
  18842. *
  18843. * everything in this dictionary cannot use keypress events
  18844. * so it has to be here to map to the correct keycodes for
  18845. * keyup/keydown events
  18846. *
  18847. * @type {Object}
  18848. */
  18849. var _MAP = {
  18850. 8: 'backspace',
  18851. 9: 'tab',
  18852. 13: 'enter',
  18853. 16: 'shift',
  18854. 17: 'ctrl',
  18855. 18: 'alt',
  18856. 20: 'capslock',
  18857. 27: 'esc',
  18858. 32: 'space',
  18859. 33: 'pageup',
  18860. 34: 'pagedown',
  18861. 35: 'end',
  18862. 36: 'home',
  18863. 37: 'left',
  18864. 38: 'up',
  18865. 39: 'right',
  18866. 40: 'down',
  18867. 45: 'ins',
  18868. 46: 'del',
  18869. 91: 'meta',
  18870. 93: 'meta',
  18871. 224: 'meta'
  18872. },
  18873. /**
  18874. * mapping for special characters so they can support
  18875. *
  18876. * this dictionary is only used incase you want to bind a
  18877. * keyup or keydown event to one of these keys
  18878. *
  18879. * @type {Object}
  18880. */
  18881. _KEYCODE_MAP = {
  18882. 106: '*',
  18883. 107: '+',
  18884. 109: '-',
  18885. 110: '.',
  18886. 111 : '/',
  18887. 186: ';',
  18888. 187: '=',
  18889. 188: ',',
  18890. 189: '-',
  18891. 190: '.',
  18892. 191: '/',
  18893. 192: '`',
  18894. 219: '[',
  18895. 220: '\\',
  18896. 221: ']',
  18897. 222: '\''
  18898. },
  18899. /**
  18900. * this is a mapping of keys that require shift on a US keypad
  18901. * back to the non shift equivelents
  18902. *
  18903. * this is so you can use keyup events with these keys
  18904. *
  18905. * note that this will only work reliably on US keyboards
  18906. *
  18907. * @type {Object}
  18908. */
  18909. _SHIFT_MAP = {
  18910. '~': '`',
  18911. '!': '1',
  18912. '@': '2',
  18913. '#': '3',
  18914. '$': '4',
  18915. '%': '5',
  18916. '^': '6',
  18917. '&': '7',
  18918. '*': '8',
  18919. '(': '9',
  18920. ')': '0',
  18921. '_': '-',
  18922. '+': '=',
  18923. ':': ';',
  18924. '\"': '\'',
  18925. '<': ',',
  18926. '>': '.',
  18927. '?': '/',
  18928. '|': '\\'
  18929. },
  18930. /**
  18931. * this is a list of special strings you can use to map
  18932. * to modifier keys when you specify your keyboard shortcuts
  18933. *
  18934. * @type {Object}
  18935. */
  18936. _SPECIAL_ALIASES = {
  18937. 'option': 'alt',
  18938. 'command': 'meta',
  18939. 'return': 'enter',
  18940. 'escape': 'esc'
  18941. },
  18942. /**
  18943. * variable to store the flipped version of _MAP from above
  18944. * needed to check if we should use keypress or not when no action
  18945. * is specified
  18946. *
  18947. * @type {Object|undefined}
  18948. */
  18949. _REVERSE_MAP,
  18950. /**
  18951. * a list of all the callbacks setup via Mousetrap.bind()
  18952. *
  18953. * @type {Object}
  18954. */
  18955. _callbacks = {},
  18956. /**
  18957. * direct map of string combinations to callbacks used for trigger()
  18958. *
  18959. * @type {Object}
  18960. */
  18961. _direct_map = {},
  18962. /**
  18963. * keeps track of what level each sequence is at since multiple
  18964. * sequences can start out with the same sequence
  18965. *
  18966. * @type {Object}
  18967. */
  18968. _sequence_levels = {},
  18969. /**
  18970. * variable to store the setTimeout call
  18971. *
  18972. * @type {null|number}
  18973. */
  18974. _reset_timer,
  18975. /**
  18976. * temporary state where we will ignore the next keyup
  18977. *
  18978. * @type {boolean|string}
  18979. */
  18980. _ignore_next_keyup = false,
  18981. /**
  18982. * are we currently inside of a sequence?
  18983. * type of action ("keyup" or "keydown" or "keypress") or false
  18984. *
  18985. * @type {boolean|string}
  18986. */
  18987. _inside_sequence = false;
  18988. /**
  18989. * loop through the f keys, f1 to f19 and add them to the map
  18990. * programatically
  18991. */
  18992. for (var i = 1; i < 20; ++i) {
  18993. _MAP[111 + i] = 'f' + i;
  18994. }
  18995. /**
  18996. * loop through to map numbers on the numeric keypad
  18997. */
  18998. for (i = 0; i <= 9; ++i) {
  18999. _MAP[i + 96] = i;
  19000. }
  19001. /**
  19002. * cross browser add event method
  19003. *
  19004. * @param {Element|HTMLDocument} object
  19005. * @param {string} type
  19006. * @param {Function} callback
  19007. * @returns void
  19008. */
  19009. function _addEvent(object, type, callback) {
  19010. if (object.addEventListener) {
  19011. return object.addEventListener(type, callback, false);
  19012. }
  19013. object.attachEvent('on' + type, callback);
  19014. }
  19015. /**
  19016. * takes the event and returns the key character
  19017. *
  19018. * @param {Event} e
  19019. * @return {string}
  19020. */
  19021. function _characterFromEvent(e) {
  19022. // for keypress events we should return the character as is
  19023. if (e.type == 'keypress') {
  19024. return String.fromCharCode(e.which);
  19025. }
  19026. // for non keypress events the special maps are needed
  19027. if (_MAP[e.which]) {
  19028. return _MAP[e.which];
  19029. }
  19030. if (_KEYCODE_MAP[e.which]) {
  19031. return _KEYCODE_MAP[e.which];
  19032. }
  19033. // if it is not in the special map
  19034. return String.fromCharCode(e.which).toLowerCase();
  19035. }
  19036. /**
  19037. * should we stop this event before firing off callbacks
  19038. *
  19039. * @param {Event} e
  19040. * @return {boolean}
  19041. */
  19042. function _stop(e) {
  19043. var element = e.target || e.srcElement,
  19044. tag_name = element.tagName;
  19045. // if the element has the class "mousetrap" then no need to stop
  19046. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19047. return false;
  19048. }
  19049. // stop for input, select, and textarea
  19050. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19051. }
  19052. /**
  19053. * checks if two arrays are equal
  19054. *
  19055. * @param {Array} modifiers1
  19056. * @param {Array} modifiers2
  19057. * @returns {boolean}
  19058. */
  19059. function _modifiersMatch(modifiers1, modifiers2) {
  19060. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19061. }
  19062. /**
  19063. * resets all sequence counters except for the ones passed in
  19064. *
  19065. * @param {Object} do_not_reset
  19066. * @returns void
  19067. */
  19068. function _resetSequences(do_not_reset) {
  19069. do_not_reset = do_not_reset || {};
  19070. var active_sequences = false,
  19071. key;
  19072. for (key in _sequence_levels) {
  19073. if (do_not_reset[key]) {
  19074. active_sequences = true;
  19075. continue;
  19076. }
  19077. _sequence_levels[key] = 0;
  19078. }
  19079. if (!active_sequences) {
  19080. _inside_sequence = false;
  19081. }
  19082. }
  19083. /**
  19084. * finds all callbacks that match based on the keycode, modifiers,
  19085. * and action
  19086. *
  19087. * @param {string} character
  19088. * @param {Array} modifiers
  19089. * @param {string} action
  19090. * @param {boolean=} remove - should we remove any matches
  19091. * @param {string=} combination
  19092. * @returns {Array}
  19093. */
  19094. function _getMatches(character, modifiers, action, remove, combination) {
  19095. var i,
  19096. callback,
  19097. matches = [];
  19098. // if there are no events related to this keycode
  19099. if (!_callbacks[character]) {
  19100. return [];
  19101. }
  19102. // if a modifier key is coming up on its own we should allow it
  19103. if (action == 'keyup' && _isModifier(character)) {
  19104. modifiers = [character];
  19105. }
  19106. // loop through all callbacks for the key that was pressed
  19107. // and see if any of them match
  19108. for (i = 0; i < _callbacks[character].length; ++i) {
  19109. callback = _callbacks[character][i];
  19110. // if this is a sequence but it is not at the right level
  19111. // then move onto the next match
  19112. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19113. continue;
  19114. }
  19115. // if the action we are looking for doesn't match the action we got
  19116. // then we should keep going
  19117. if (action != callback.action) {
  19118. continue;
  19119. }
  19120. // if this is a keypress event that means that we need to only
  19121. // look at the character, otherwise check the modifiers as
  19122. // well
  19123. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19124. // remove is used so if you change your mind and call bind a
  19125. // second time with a new function the first one is overwritten
  19126. if (remove && callback.combo == combination) {
  19127. _callbacks[character].splice(i, 1);
  19128. }
  19129. matches.push(callback);
  19130. }
  19131. }
  19132. return matches;
  19133. }
  19134. /**
  19135. * takes a key event and figures out what the modifiers are
  19136. *
  19137. * @param {Event} e
  19138. * @returns {Array}
  19139. */
  19140. function _eventModifiers(e) {
  19141. var modifiers = [];
  19142. if (e.shiftKey) {
  19143. modifiers.push('shift');
  19144. }
  19145. if (e.altKey) {
  19146. modifiers.push('alt');
  19147. }
  19148. if (e.ctrlKey) {
  19149. modifiers.push('ctrl');
  19150. }
  19151. if (e.metaKey) {
  19152. modifiers.push('meta');
  19153. }
  19154. return modifiers;
  19155. }
  19156. /**
  19157. * actually calls the callback function
  19158. *
  19159. * if your callback function returns false this will use the jquery
  19160. * convention - prevent default and stop propogation on the event
  19161. *
  19162. * @param {Function} callback
  19163. * @param {Event} e
  19164. * @returns void
  19165. */
  19166. function _fireCallback(callback, e) {
  19167. if (callback(e) === false) {
  19168. if (e.preventDefault) {
  19169. e.preventDefault();
  19170. }
  19171. if (e.stopPropagation) {
  19172. e.stopPropagation();
  19173. }
  19174. e.returnValue = false;
  19175. e.cancelBubble = true;
  19176. }
  19177. }
  19178. /**
  19179. * handles a character key event
  19180. *
  19181. * @param {string} character
  19182. * @param {Event} e
  19183. * @returns void
  19184. */
  19185. function _handleCharacter(character, e) {
  19186. // if this event should not happen stop here
  19187. if (_stop(e)) {
  19188. return;
  19189. }
  19190. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19191. i,
  19192. do_not_reset = {},
  19193. processed_sequence_callback = false;
  19194. // loop through matching callbacks for this key event
  19195. for (i = 0; i < callbacks.length; ++i) {
  19196. // fire for all sequence callbacks
  19197. // this is because if for example you have multiple sequences
  19198. // bound such as "g i" and "g t" they both need to fire the
  19199. // callback for matching g cause otherwise you can only ever
  19200. // match the first one
  19201. if (callbacks[i].seq) {
  19202. processed_sequence_callback = true;
  19203. // keep a list of which sequences were matches for later
  19204. do_not_reset[callbacks[i].seq] = 1;
  19205. _fireCallback(callbacks[i].callback, e);
  19206. continue;
  19207. }
  19208. // if there were no sequence matches but we are still here
  19209. // that means this is a regular match so we should fire that
  19210. if (!processed_sequence_callback && !_inside_sequence) {
  19211. _fireCallback(callbacks[i].callback, e);
  19212. }
  19213. }
  19214. // if you are inside of a sequence and the key you are pressing
  19215. // is not a modifier key then we should reset all sequences
  19216. // that were not matched by this key event
  19217. if (e.type == _inside_sequence && !_isModifier(character)) {
  19218. _resetSequences(do_not_reset);
  19219. }
  19220. }
  19221. /**
  19222. * handles a keydown event
  19223. *
  19224. * @param {Event} e
  19225. * @returns void
  19226. */
  19227. function _handleKey(e) {
  19228. // normalize e.which for key events
  19229. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19230. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19231. var character = _characterFromEvent(e);
  19232. // no character found then stop
  19233. if (!character) {
  19234. return;
  19235. }
  19236. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19237. _ignore_next_keyup = false;
  19238. return;
  19239. }
  19240. _handleCharacter(character, e);
  19241. }
  19242. /**
  19243. * determines if the keycode specified is a modifier key or not
  19244. *
  19245. * @param {string} key
  19246. * @returns {boolean}
  19247. */
  19248. function _isModifier(key) {
  19249. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19250. }
  19251. /**
  19252. * called to set a 1 second timeout on the specified sequence
  19253. *
  19254. * this is so after each key press in the sequence you have 1 second
  19255. * to press the next key before you have to start over
  19256. *
  19257. * @returns void
  19258. */
  19259. function _resetSequenceTimer() {
  19260. clearTimeout(_reset_timer);
  19261. _reset_timer = setTimeout(_resetSequences, 1000);
  19262. }
  19263. /**
  19264. * reverses the map lookup so that we can look for specific keys
  19265. * to see what can and can't use keypress
  19266. *
  19267. * @return {Object}
  19268. */
  19269. function _getReverseMap() {
  19270. if (!_REVERSE_MAP) {
  19271. _REVERSE_MAP = {};
  19272. for (var key in _MAP) {
  19273. // pull out the numeric keypad from here cause keypress should
  19274. // be able to detect the keys from the character
  19275. if (key > 95 && key < 112) {
  19276. continue;
  19277. }
  19278. if (_MAP.hasOwnProperty(key)) {
  19279. _REVERSE_MAP[_MAP[key]] = key;
  19280. }
  19281. }
  19282. }
  19283. return _REVERSE_MAP;
  19284. }
  19285. /**
  19286. * picks the best action based on the key combination
  19287. *
  19288. * @param {string} key - character for key
  19289. * @param {Array} modifiers
  19290. * @param {string=} action passed in
  19291. */
  19292. function _pickBestAction(key, modifiers, action) {
  19293. // if no action was picked in we should try to pick the one
  19294. // that we think would work best for this key
  19295. if (!action) {
  19296. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19297. }
  19298. // modifier keys don't work as expected with keypress,
  19299. // switch to keydown
  19300. if (action == 'keypress' && modifiers.length) {
  19301. action = 'keydown';
  19302. }
  19303. return action;
  19304. }
  19305. /**
  19306. * binds a key sequence to an event
  19307. *
  19308. * @param {string} combo - combo specified in bind call
  19309. * @param {Array} keys
  19310. * @param {Function} callback
  19311. * @param {string=} action
  19312. * @returns void
  19313. */
  19314. function _bindSequence(combo, keys, callback, action) {
  19315. // start off by adding a sequence level record for this combination
  19316. // and setting the level to 0
  19317. _sequence_levels[combo] = 0;
  19318. // if there is no action pick the best one for the first key
  19319. // in the sequence
  19320. if (!action) {
  19321. action = _pickBestAction(keys[0], []);
  19322. }
  19323. /**
  19324. * callback to increase the sequence level for this sequence and reset
  19325. * all other sequences that were active
  19326. *
  19327. * @param {Event} e
  19328. * @returns void
  19329. */
  19330. var _increaseSequence = function(e) {
  19331. _inside_sequence = action;
  19332. ++_sequence_levels[combo];
  19333. _resetSequenceTimer();
  19334. },
  19335. /**
  19336. * wraps the specified callback inside of another function in order
  19337. * to reset all sequence counters as soon as this sequence is done
  19338. *
  19339. * @param {Event} e
  19340. * @returns void
  19341. */
  19342. _callbackAndReset = function(e) {
  19343. _fireCallback(callback, e);
  19344. // we should ignore the next key up if the action is key down
  19345. // or keypress. this is so if you finish a sequence and
  19346. // release the key the final key will not trigger a keyup
  19347. if (action !== 'keyup') {
  19348. _ignore_next_keyup = _characterFromEvent(e);
  19349. }
  19350. // weird race condition if a sequence ends with the key
  19351. // another sequence begins with
  19352. setTimeout(_resetSequences, 10);
  19353. },
  19354. i;
  19355. // loop through keys one at a time and bind the appropriate callback
  19356. // function. for any key leading up to the final one it should
  19357. // increase the sequence. after the final, it should reset all sequences
  19358. for (i = 0; i < keys.length; ++i) {
  19359. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19360. }
  19361. }
  19362. /**
  19363. * binds a single keyboard combination
  19364. *
  19365. * @param {string} combination
  19366. * @param {Function} callback
  19367. * @param {string=} action
  19368. * @param {string=} sequence_name - name of sequence if part of sequence
  19369. * @param {number=} level - what part of the sequence the command is
  19370. * @returns void
  19371. */
  19372. function _bindSingle(combination, callback, action, sequence_name, level) {
  19373. // make sure multiple spaces in a row become a single space
  19374. combination = combination.replace(/\s+/g, ' ');
  19375. var sequence = combination.split(' '),
  19376. i,
  19377. key,
  19378. keys,
  19379. modifiers = [];
  19380. // if this pattern is a sequence of keys then run through this method
  19381. // to reprocess each pattern one key at a time
  19382. if (sequence.length > 1) {
  19383. return _bindSequence(combination, sequence, callback, action);
  19384. }
  19385. // take the keys from this pattern and figure out what the actual
  19386. // pattern is all about
  19387. keys = combination === '+' ? ['+'] : combination.split('+');
  19388. for (i = 0; i < keys.length; ++i) {
  19389. key = keys[i];
  19390. // normalize key names
  19391. if (_SPECIAL_ALIASES[key]) {
  19392. key = _SPECIAL_ALIASES[key];
  19393. }
  19394. // if this is not a keypress event then we should
  19395. // be smart about using shift keys
  19396. // this will only work for US keyboards however
  19397. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19398. key = _SHIFT_MAP[key];
  19399. modifiers.push('shift');
  19400. }
  19401. // if this key is a modifier then add it to the list of modifiers
  19402. if (_isModifier(key)) {
  19403. modifiers.push(key);
  19404. }
  19405. }
  19406. // depending on what the key combination is
  19407. // we will try to pick the best event for it
  19408. action = _pickBestAction(key, modifiers, action);
  19409. // make sure to initialize array if this is the first time
  19410. // a callback is added for this key
  19411. if (!_callbacks[key]) {
  19412. _callbacks[key] = [];
  19413. }
  19414. // remove an existing match if there is one
  19415. _getMatches(key, modifiers, action, !sequence_name, combination);
  19416. // add this call back to the array
  19417. // if it is a sequence put it at the beginning
  19418. // if not put it at the end
  19419. //
  19420. // this is important because the way these are processed expects
  19421. // the sequence ones to come first
  19422. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19423. callback: callback,
  19424. modifiers: modifiers,
  19425. action: action,
  19426. seq: sequence_name,
  19427. level: level,
  19428. combo: combination
  19429. });
  19430. }
  19431. /**
  19432. * binds multiple combinations to the same callback
  19433. *
  19434. * @param {Array} combinations
  19435. * @param {Function} callback
  19436. * @param {string|undefined} action
  19437. * @returns void
  19438. */
  19439. function _bindMultiple(combinations, callback, action) {
  19440. for (var i = 0; i < combinations.length; ++i) {
  19441. _bindSingle(combinations[i], callback, action);
  19442. }
  19443. }
  19444. // start!
  19445. _addEvent(document, 'keypress', _handleKey);
  19446. _addEvent(document, 'keydown', _handleKey);
  19447. _addEvent(document, 'keyup', _handleKey);
  19448. var mousetrap = {
  19449. /**
  19450. * binds an event to mousetrap
  19451. *
  19452. * can be a single key, a combination of keys separated with +,
  19453. * a comma separated list of keys, an array of keys, or
  19454. * a sequence of keys separated by spaces
  19455. *
  19456. * be sure to list the modifier keys first to make sure that the
  19457. * correct key ends up getting bound (the last key in the pattern)
  19458. *
  19459. * @param {string|Array} keys
  19460. * @param {Function} callback
  19461. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19462. * @returns void
  19463. */
  19464. bind: function(keys, callback, action) {
  19465. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19466. _direct_map[keys + ':' + action] = callback;
  19467. return this;
  19468. },
  19469. /**
  19470. * unbinds an event to mousetrap
  19471. *
  19472. * the unbinding sets the callback function of the specified key combo
  19473. * to an empty function and deletes the corresponding key in the
  19474. * _direct_map dict.
  19475. *
  19476. * the keycombo+action has to be exactly the same as
  19477. * it was defined in the bind method
  19478. *
  19479. * TODO: actually remove this from the _callbacks dictionary instead
  19480. * of binding an empty function
  19481. *
  19482. * @param {string|Array} keys
  19483. * @param {string} action
  19484. * @returns void
  19485. */
  19486. unbind: function(keys, action) {
  19487. if (_direct_map[keys + ':' + action]) {
  19488. delete _direct_map[keys + ':' + action];
  19489. this.bind(keys, function() {}, action);
  19490. }
  19491. return this;
  19492. },
  19493. /**
  19494. * triggers an event that has already been bound
  19495. *
  19496. * @param {string} keys
  19497. * @param {string=} action
  19498. * @returns void
  19499. */
  19500. trigger: function(keys, action) {
  19501. _direct_map[keys + ':' + action]();
  19502. return this;
  19503. },
  19504. /**
  19505. * resets the library back to its initial state. this is useful
  19506. * if you want to clear out the current keyboard shortcuts and bind
  19507. * new ones - for example if you switch to another page
  19508. *
  19509. * @returns void
  19510. */
  19511. reset: function() {
  19512. _callbacks = {};
  19513. _direct_map = {};
  19514. return this;
  19515. }
  19516. };
  19517. module.exports = mousetrap;
  19518. },{}]},{},[1])
  19519. (1)
  19520. });