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.

22921 lines
671 KiB

  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.7.2
  8. * @date 2014-04-09
  9. *
  10. * @license
  11. * Copyright (C) 2011-2014 Almende B.V, http://almende.com
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  14. * use this file except in compliance with the License. You may obtain a copy
  15. * of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  22. * License for the specific language governing permissions and limitations under
  23. * the License.
  24. */
  25. !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.vis=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  26. /**
  27. * vis.js module imports
  28. */
  29. // Try to load dependencies from the global window object.
  30. // If not available there, load via require.
  31. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment');
  32. var Emitter = require('emitter-component');
  33. var Hammer;
  34. if (typeof window !== 'undefined') {
  35. // load hammer.js only when running in a browser (where window is available)
  36. Hammer = window['Hammer'] || require('hammerjs');
  37. }
  38. else {
  39. Hammer = function () {
  40. throw Error('hammer.js is only available in a browser, not in node.js.');
  41. }
  42. }
  43. var mousetrap;
  44. if (typeof window !== 'undefined') {
  45. // load mousetrap.js only when running in a browser (where window is available)
  46. mousetrap = window['mousetrap'] || require('mousetrap');
  47. }
  48. else {
  49. mousetrap = function () {
  50. throw Error('mouseTrap is only available in a browser, not in node.js.');
  51. }
  52. }
  53. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  54. // it here in that case.
  55. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  56. if(!Array.prototype.indexOf) {
  57. Array.prototype.indexOf = function(obj){
  58. for(var i = 0; i < this.length; i++){
  59. if(this[i] == obj){
  60. return i;
  61. }
  62. }
  63. return -1;
  64. };
  65. try {
  66. console.log("Warning: Ancient browser detected. Please update your browser");
  67. }
  68. catch (err) {
  69. }
  70. }
  71. // Internet Explorer 8 and older does not support Array.forEach, so we define
  72. // it here in that case.
  73. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  74. if (!Array.prototype.forEach) {
  75. Array.prototype.forEach = function(fn, scope) {
  76. for(var i = 0, len = this.length; i < len; ++i) {
  77. fn.call(scope || this, this[i], i, this);
  78. }
  79. }
  80. }
  81. // Internet Explorer 8 and older does not support Array.map, so we define it
  82. // here in that case.
  83. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  84. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  85. // Reference: http://es5.github.com/#x15.4.4.19
  86. if (!Array.prototype.map) {
  87. Array.prototype.map = function(callback, thisArg) {
  88. var T, A, k;
  89. if (this == null) {
  90. throw new TypeError(" this is null or not defined");
  91. }
  92. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  93. var O = Object(this);
  94. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  95. // 3. Let len be ToUint32(lenValue).
  96. var len = O.length >>> 0;
  97. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  98. // See: http://es5.github.com/#x9.11
  99. if (typeof callback !== "function") {
  100. throw new TypeError(callback + " is not a function");
  101. }
  102. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  103. if (thisArg) {
  104. T = thisArg;
  105. }
  106. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  107. // the standard built-in constructor with that name and len is the value of len.
  108. A = new Array(len);
  109. // 7. Let k be 0
  110. k = 0;
  111. // 8. Repeat, while k < len
  112. while(k < len) {
  113. var kValue, mappedValue;
  114. // a. Let Pk be ToString(k).
  115. // This is implicit for LHS operands of the in operator
  116. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  117. // This step can be combined with c
  118. // c. If kPresent is true, then
  119. if (k in O) {
  120. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  121. kValue = O[ k ];
  122. // ii. Let mappedValue be the result of calling the Call internal method of callback
  123. // with T as the this value and argument list containing kValue, k, and O.
  124. mappedValue = callback.call(T, kValue, k, O);
  125. // iii. Call the DefineOwnProperty internal method of A with arguments
  126. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  127. // and false.
  128. // In browsers that support Object.defineProperty, use the following:
  129. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  130. // For best browser support, use the following:
  131. A[ k ] = mappedValue;
  132. }
  133. // d. Increase k by 1.
  134. k++;
  135. }
  136. // 9. return A
  137. return A;
  138. };
  139. }
  140. // Internet Explorer 8 and older does not support Array.filter, so we define it
  141. // here in that case.
  142. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  143. if (!Array.prototype.filter) {
  144. Array.prototype.filter = function(fun /*, thisp */) {
  145. "use strict";
  146. if (this == null) {
  147. throw new TypeError();
  148. }
  149. var t = Object(this);
  150. var len = t.length >>> 0;
  151. if (typeof fun != "function") {
  152. throw new TypeError();
  153. }
  154. var res = [];
  155. var thisp = arguments[1];
  156. for (var i = 0; i < len; i++) {
  157. if (i in t) {
  158. var val = t[i]; // in case fun mutates this
  159. if (fun.call(thisp, val, i, t))
  160. res.push(val);
  161. }
  162. }
  163. return res;
  164. };
  165. }
  166. // Internet Explorer 8 and older does not support Object.keys, so we define it
  167. // here in that case.
  168. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  169. if (!Object.keys) {
  170. Object.keys = (function () {
  171. var hasOwnProperty = Object.prototype.hasOwnProperty,
  172. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  173. dontEnums = [
  174. 'toString',
  175. 'toLocaleString',
  176. 'valueOf',
  177. 'hasOwnProperty',
  178. 'isPrototypeOf',
  179. 'propertyIsEnumerable',
  180. 'constructor'
  181. ],
  182. dontEnumsLength = dontEnums.length;
  183. return function (obj) {
  184. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  185. throw new TypeError('Object.keys called on non-object');
  186. }
  187. var result = [];
  188. for (var prop in obj) {
  189. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  190. }
  191. if (hasDontEnumBug) {
  192. for (var i=0; i < dontEnumsLength; i++) {
  193. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  194. }
  195. }
  196. return result;
  197. }
  198. })()
  199. }
  200. // Internet Explorer 8 and older does not support Array.isArray,
  201. // so we define it here in that case.
  202. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  203. if(!Array.isArray) {
  204. Array.isArray = function (vArg) {
  205. return Object.prototype.toString.call(vArg) === "[object Array]";
  206. };
  207. }
  208. // Internet Explorer 8 and older does not support Function.bind,
  209. // so we define it here in that case.
  210. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  211. if (!Function.prototype.bind) {
  212. Function.prototype.bind = function (oThis) {
  213. if (typeof this !== "function") {
  214. // closest thing possible to the ECMAScript 5 internal IsCallable function
  215. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  216. }
  217. var aArgs = Array.prototype.slice.call(arguments, 1),
  218. fToBind = this,
  219. fNOP = function () {},
  220. fBound = function () {
  221. return fToBind.apply(this instanceof fNOP && oThis
  222. ? this
  223. : oThis,
  224. aArgs.concat(Array.prototype.slice.call(arguments)));
  225. };
  226. fNOP.prototype = this.prototype;
  227. fBound.prototype = new fNOP();
  228. return fBound;
  229. };
  230. }
  231. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  232. if (!Object.create) {
  233. Object.create = function (o) {
  234. if (arguments.length > 1) {
  235. throw new Error('Object.create implementation only accepts the first parameter.');
  236. }
  237. function F() {}
  238. F.prototype = o;
  239. return new F();
  240. };
  241. }
  242. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  243. if (!Function.prototype.bind) {
  244. Function.prototype.bind = function (oThis) {
  245. if (typeof this !== "function") {
  246. // closest thing possible to the ECMAScript 5 internal IsCallable function
  247. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  248. }
  249. var aArgs = Array.prototype.slice.call(arguments, 1),
  250. fToBind = this,
  251. fNOP = function () {},
  252. fBound = function () {
  253. return fToBind.apply(this instanceof fNOP && oThis
  254. ? this
  255. : oThis,
  256. aArgs.concat(Array.prototype.slice.call(arguments)));
  257. };
  258. fNOP.prototype = this.prototype;
  259. fBound.prototype = new fNOP();
  260. return fBound;
  261. };
  262. }
  263. /**
  264. * utility functions
  265. */
  266. var util = {};
  267. /**
  268. * Test whether given object is a number
  269. * @param {*} object
  270. * @return {Boolean} isNumber
  271. */
  272. util.isNumber = function isNumber(object) {
  273. return (object instanceof Number || typeof object == 'number');
  274. };
  275. /**
  276. * Test whether given object is a string
  277. * @param {*} object
  278. * @return {Boolean} isString
  279. */
  280. util.isString = function isString(object) {
  281. return (object instanceof String || typeof object == 'string');
  282. };
  283. /**
  284. * Test whether given object is a Date, or a String containing a Date
  285. * @param {Date | String} object
  286. * @return {Boolean} isDate
  287. */
  288. util.isDate = function isDate(object) {
  289. if (object instanceof Date) {
  290. return true;
  291. }
  292. else if (util.isString(object)) {
  293. // test whether this string contains a date
  294. var match = ASPDateRegex.exec(object);
  295. if (match) {
  296. return true;
  297. }
  298. else if (!isNaN(Date.parse(object))) {
  299. return true;
  300. }
  301. }
  302. return false;
  303. };
  304. /**
  305. * Test whether given object is an instance of google.visualization.DataTable
  306. * @param {*} object
  307. * @return {Boolean} isDataTable
  308. */
  309. util.isDataTable = function isDataTable(object) {
  310. return (typeof (google) !== 'undefined') &&
  311. (google.visualization) &&
  312. (google.visualization.DataTable) &&
  313. (object instanceof google.visualization.DataTable);
  314. };
  315. /**
  316. * Create a semi UUID
  317. * source: http://stackoverflow.com/a/105074/1262753
  318. * @return {String} uuid
  319. */
  320. util.randomUUID = function randomUUID () {
  321. var S4 = function () {
  322. return Math.floor(
  323. Math.random() * 0x10000 /* 65536 */
  324. ).toString(16);
  325. };
  326. return (
  327. S4() + S4() + '-' +
  328. S4() + '-' +
  329. S4() + '-' +
  330. S4() + '-' +
  331. S4() + S4() + S4()
  332. );
  333. };
  334. /**
  335. * Extend object a with the properties of object b or a series of objects
  336. * Only properties with defined values are copied
  337. * @param {Object} a
  338. * @param {... Object} b
  339. * @return {Object} a
  340. */
  341. util.extend = function (a, b) {
  342. for (var i = 1, len = arguments.length; i < len; i++) {
  343. var other = arguments[i];
  344. for (var prop in other) {
  345. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  346. a[prop] = other[prop];
  347. }
  348. }
  349. }
  350. return a;
  351. };
  352. /**
  353. * Convert an object to another type
  354. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  355. * @param {String | undefined} type Name of the type. Available types:
  356. * 'Boolean', 'Number', 'String',
  357. * 'Date', 'Moment', ISODate', 'ASPDate'.
  358. * @return {*} object
  359. * @throws Error
  360. */
  361. util.convert = function convert(object, type) {
  362. var match;
  363. if (object === undefined) {
  364. return undefined;
  365. }
  366. if (object === null) {
  367. return null;
  368. }
  369. if (!type) {
  370. return object;
  371. }
  372. if (!(typeof type === 'string') && !(type instanceof String)) {
  373. throw new Error('Type must be a string');
  374. }
  375. //noinspection FallthroughInSwitchStatementJS
  376. switch (type) {
  377. case 'boolean':
  378. case 'Boolean':
  379. return Boolean(object);
  380. case 'number':
  381. case 'Number':
  382. return Number(object.valueOf());
  383. case 'string':
  384. case 'String':
  385. return String(object);
  386. case 'Date':
  387. if (util.isNumber(object)) {
  388. return new Date(object);
  389. }
  390. if (object instanceof Date) {
  391. return new Date(object.valueOf());
  392. }
  393. else if (moment.isMoment(object)) {
  394. return new Date(object.valueOf());
  395. }
  396. if (util.isString(object)) {
  397. match = ASPDateRegex.exec(object);
  398. if (match) {
  399. // object is an ASP date
  400. return new Date(Number(match[1])); // parse number
  401. }
  402. else {
  403. return moment(object).toDate(); // parse string
  404. }
  405. }
  406. else {
  407. throw new Error(
  408. 'Cannot convert object of type ' + util.getType(object) +
  409. ' to type Date');
  410. }
  411. case 'Moment':
  412. if (util.isNumber(object)) {
  413. return moment(object);
  414. }
  415. if (object instanceof Date) {
  416. return moment(object.valueOf());
  417. }
  418. else if (moment.isMoment(object)) {
  419. return moment(object);
  420. }
  421. if (util.isString(object)) {
  422. match = ASPDateRegex.exec(object);
  423. if (match) {
  424. // object is an ASP date
  425. return moment(Number(match[1])); // parse number
  426. }
  427. else {
  428. return moment(object); // parse string
  429. }
  430. }
  431. else {
  432. throw new Error(
  433. 'Cannot convert object of type ' + util.getType(object) +
  434. ' to type Date');
  435. }
  436. case 'ISODate':
  437. if (util.isNumber(object)) {
  438. return new Date(object);
  439. }
  440. else if (object instanceof Date) {
  441. return object.toISOString();
  442. }
  443. else if (moment.isMoment(object)) {
  444. return object.toDate().toISOString();
  445. }
  446. else if (util.isString(object)) {
  447. match = ASPDateRegex.exec(object);
  448. if (match) {
  449. // object is an ASP date
  450. return new Date(Number(match[1])).toISOString(); // parse number
  451. }
  452. else {
  453. return new Date(object).toISOString(); // parse string
  454. }
  455. }
  456. else {
  457. throw new Error(
  458. 'Cannot convert object of type ' + util.getType(object) +
  459. ' to type ISODate');
  460. }
  461. case 'ASPDate':
  462. if (util.isNumber(object)) {
  463. return '/Date(' + object + ')/';
  464. }
  465. else if (object instanceof Date) {
  466. return '/Date(' + object.valueOf() + ')/';
  467. }
  468. else if (util.isString(object)) {
  469. match = ASPDateRegex.exec(object);
  470. var value;
  471. if (match) {
  472. // object is an ASP date
  473. value = new Date(Number(match[1])).valueOf(); // parse number
  474. }
  475. else {
  476. value = new Date(object).valueOf(); // parse string
  477. }
  478. return '/Date(' + value + ')/';
  479. }
  480. else {
  481. throw new Error(
  482. 'Cannot convert object of type ' + util.getType(object) +
  483. ' to type ASPDate');
  484. }
  485. default:
  486. throw new Error('Cannot convert object of type ' + util.getType(object) +
  487. ' to type "' + type + '"');
  488. }
  489. };
  490. // parse ASP.Net Date pattern,
  491. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  492. // code from http://momentjs.com/
  493. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  494. /**
  495. * Get the type of an object, for example util.getType([]) returns 'Array'
  496. * @param {*} object
  497. * @return {String} type
  498. */
  499. util.getType = function getType(object) {
  500. var type = typeof object;
  501. if (type == 'object') {
  502. if (object == null) {
  503. return 'null';
  504. }
  505. if (object instanceof Boolean) {
  506. return 'Boolean';
  507. }
  508. if (object instanceof Number) {
  509. return 'Number';
  510. }
  511. if (object instanceof String) {
  512. return 'String';
  513. }
  514. if (object instanceof Array) {
  515. return 'Array';
  516. }
  517. if (object instanceof Date) {
  518. return 'Date';
  519. }
  520. return 'Object';
  521. }
  522. else if (type == 'number') {
  523. return 'Number';
  524. }
  525. else if (type == 'boolean') {
  526. return 'Boolean';
  527. }
  528. else if (type == 'string') {
  529. return 'String';
  530. }
  531. return type;
  532. };
  533. /**
  534. * Retrieve the absolute left value of a DOM element
  535. * @param {Element} elem A dom element, for example a div
  536. * @return {number} left The absolute left position of this element
  537. * in the browser page.
  538. */
  539. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  540. var doc = document.documentElement;
  541. var body = document.body;
  542. var left = elem.offsetLeft;
  543. var e = elem.offsetParent;
  544. while (e != null && e != body && e != doc) {
  545. left += e.offsetLeft;
  546. left -= e.scrollLeft;
  547. e = e.offsetParent;
  548. }
  549. return left;
  550. };
  551. /**
  552. * Retrieve the absolute top value of a DOM element
  553. * @param {Element} elem A dom element, for example a div
  554. * @return {number} top The absolute top position of this element
  555. * in the browser page.
  556. */
  557. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  558. var doc = document.documentElement;
  559. var body = document.body;
  560. var top = elem.offsetTop;
  561. var e = elem.offsetParent;
  562. while (e != null && e != body && e != doc) {
  563. top += e.offsetTop;
  564. top -= e.scrollTop;
  565. e = e.offsetParent;
  566. }
  567. return top;
  568. };
  569. /**
  570. * Get the absolute, vertical mouse position from an event.
  571. * @param {Event} event
  572. * @return {Number} pageY
  573. */
  574. util.getPageY = function getPageY (event) {
  575. if ('pageY' in event) {
  576. return event.pageY;
  577. }
  578. else {
  579. var clientY;
  580. if (('targetTouches' in event) && event.targetTouches.length) {
  581. clientY = event.targetTouches[0].clientY;
  582. }
  583. else {
  584. clientY = event.clientY;
  585. }
  586. var doc = document.documentElement;
  587. var body = document.body;
  588. return clientY +
  589. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  590. ( doc && doc.clientTop || body && body.clientTop || 0 );
  591. }
  592. };
  593. /**
  594. * Get the absolute, horizontal mouse position from an event.
  595. * @param {Event} event
  596. * @return {Number} pageX
  597. */
  598. util.getPageX = function getPageX (event) {
  599. if ('pageY' in event) {
  600. return event.pageX;
  601. }
  602. else {
  603. var clientX;
  604. if (('targetTouches' in event) && event.targetTouches.length) {
  605. clientX = event.targetTouches[0].clientX;
  606. }
  607. else {
  608. clientX = event.clientX;
  609. }
  610. var doc = document.documentElement;
  611. var body = document.body;
  612. return clientX +
  613. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  614. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  615. }
  616. };
  617. /**
  618. * add a className to the given elements style
  619. * @param {Element} elem
  620. * @param {String} className
  621. */
  622. util.addClassName = function addClassName(elem, className) {
  623. var classes = elem.className.split(' ');
  624. if (classes.indexOf(className) == -1) {
  625. classes.push(className); // add the class to the array
  626. elem.className = classes.join(' ');
  627. }
  628. };
  629. /**
  630. * add a className to the given elements style
  631. * @param {Element} elem
  632. * @param {String} className
  633. */
  634. util.removeClassName = function removeClassname(elem, className) {
  635. var classes = elem.className.split(' ');
  636. var index = classes.indexOf(className);
  637. if (index != -1) {
  638. classes.splice(index, 1); // remove the class from the array
  639. elem.className = classes.join(' ');
  640. }
  641. };
  642. /**
  643. * For each method for both arrays and objects.
  644. * In case of an array, the built-in Array.forEach() is applied.
  645. * In case of an Object, the method loops over all properties of the object.
  646. * @param {Object | Array} object An Object or Array
  647. * @param {function} callback Callback method, called for each item in
  648. * the object or array with three parameters:
  649. * callback(value, index, object)
  650. */
  651. util.forEach = function forEach (object, callback) {
  652. var i,
  653. len;
  654. if (object instanceof Array) {
  655. // array
  656. for (i = 0, len = object.length; i < len; i++) {
  657. callback(object[i], i, object);
  658. }
  659. }
  660. else {
  661. // object
  662. for (i in object) {
  663. if (object.hasOwnProperty(i)) {
  664. callback(object[i], i, object);
  665. }
  666. }
  667. }
  668. };
  669. /**
  670. * Update a property in an object
  671. * @param {Object} object
  672. * @param {String} key
  673. * @param {*} value
  674. * @return {Boolean} changed
  675. */
  676. util.updateProperty = function updateProp (object, key, value) {
  677. if (object[key] !== value) {
  678. object[key] = value;
  679. return true;
  680. }
  681. else {
  682. return false;
  683. }
  684. };
  685. /**
  686. * Add and event listener. Works for all browsers
  687. * @param {Element} element An html element
  688. * @param {string} action The action, for example "click",
  689. * without the prefix "on"
  690. * @param {function} listener The callback function to be executed
  691. * @param {boolean} [useCapture]
  692. */
  693. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  694. if (element.addEventListener) {
  695. if (useCapture === undefined)
  696. useCapture = false;
  697. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  698. action = "DOMMouseScroll"; // For Firefox
  699. }
  700. element.addEventListener(action, listener, useCapture);
  701. } else {
  702. element.attachEvent("on" + action, listener); // IE browsers
  703. }
  704. };
  705. /**
  706. * Remove an event listener from an element
  707. * @param {Element} element An html dom element
  708. * @param {string} action The name of the event, for example "mousedown"
  709. * @param {function} listener The listener function
  710. * @param {boolean} [useCapture]
  711. */
  712. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  713. if (element.removeEventListener) {
  714. // non-IE browsers
  715. if (useCapture === undefined)
  716. useCapture = false;
  717. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  718. action = "DOMMouseScroll"; // For Firefox
  719. }
  720. element.removeEventListener(action, listener, useCapture);
  721. } else {
  722. // IE browsers
  723. element.detachEvent("on" + action, listener);
  724. }
  725. };
  726. /**
  727. * Get HTML element which is the target of the event
  728. * @param {Event} event
  729. * @return {Element} target element
  730. */
  731. util.getTarget = function getTarget(event) {
  732. // code from http://www.quirksmode.org/js/events_properties.html
  733. if (!event) {
  734. event = window.event;
  735. }
  736. var target;
  737. if (event.target) {
  738. target = event.target;
  739. }
  740. else if (event.srcElement) {
  741. target = event.srcElement;
  742. }
  743. if (target.nodeType != undefined && target.nodeType == 3) {
  744. // defeat Safari bug
  745. target = target.parentNode;
  746. }
  747. return target;
  748. };
  749. /**
  750. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  751. * @param {Element} element
  752. * @param {Event} event
  753. */
  754. util.fakeGesture = function fakeGesture (element, event) {
  755. var eventType = null;
  756. // for hammer.js 1.0.5
  757. var gesture = Hammer.event.collectEventData(this, eventType, event);
  758. // for hammer.js 1.0.6
  759. //var touches = Hammer.event.getTouchList(event, eventType);
  760. // var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  761. // on IE in standards mode, no touches are recognized by hammer.js,
  762. // resulting in NaN values for center.pageX and center.pageY
  763. if (isNaN(gesture.center.pageX)) {
  764. gesture.center.pageX = event.pageX;
  765. }
  766. if (isNaN(gesture.center.pageY)) {
  767. gesture.center.pageY = event.pageY;
  768. }
  769. return gesture;
  770. };
  771. util.option = {};
  772. /**
  773. * Convert a value into a boolean
  774. * @param {Boolean | function | undefined} value
  775. * @param {Boolean} [defaultValue]
  776. * @returns {Boolean} bool
  777. */
  778. util.option.asBoolean = function (value, defaultValue) {
  779. if (typeof value == 'function') {
  780. value = value();
  781. }
  782. if (value != null) {
  783. return (value != false);
  784. }
  785. return defaultValue || null;
  786. };
  787. /**
  788. * Convert a value into a number
  789. * @param {Boolean | function | undefined} value
  790. * @param {Number} [defaultValue]
  791. * @returns {Number} number
  792. */
  793. util.option.asNumber = function (value, defaultValue) {
  794. if (typeof value == 'function') {
  795. value = value();
  796. }
  797. if (value != null) {
  798. return Number(value) || defaultValue || null;
  799. }
  800. return defaultValue || null;
  801. };
  802. /**
  803. * Convert a value into a string
  804. * @param {String | function | undefined} value
  805. * @param {String} [defaultValue]
  806. * @returns {String} str
  807. */
  808. util.option.asString = function (value, defaultValue) {
  809. if (typeof value == 'function') {
  810. value = value();
  811. }
  812. if (value != null) {
  813. return String(value);
  814. }
  815. return defaultValue || null;
  816. };
  817. /**
  818. * Convert a size or location into a string with pixels or a percentage
  819. * @param {String | Number | function | undefined} value
  820. * @param {String} [defaultValue]
  821. * @returns {String} size
  822. */
  823. util.option.asSize = function (value, defaultValue) {
  824. if (typeof value == 'function') {
  825. value = value();
  826. }
  827. if (util.isString(value)) {
  828. return value;
  829. }
  830. else if (util.isNumber(value)) {
  831. return value + 'px';
  832. }
  833. else {
  834. return defaultValue || null;
  835. }
  836. };
  837. /**
  838. * Convert a value into a DOM element
  839. * @param {HTMLElement | function | undefined} value
  840. * @param {HTMLElement} [defaultValue]
  841. * @returns {HTMLElement | null} dom
  842. */
  843. util.option.asElement = function (value, defaultValue) {
  844. if (typeof value == 'function') {
  845. value = value();
  846. }
  847. return value || defaultValue || null;
  848. };
  849. util.GiveDec = function GiveDec(Hex)
  850. {
  851. if(Hex == "A")
  852. Value = 10;
  853. else
  854. if(Hex == "B")
  855. Value = 11;
  856. else
  857. if(Hex == "C")
  858. Value = 12;
  859. else
  860. if(Hex == "D")
  861. Value = 13;
  862. else
  863. if(Hex == "E")
  864. Value = 14;
  865. else
  866. if(Hex == "F")
  867. Value = 15;
  868. else
  869. Value = eval(Hex)
  870. return Value;
  871. }
  872. util.GiveHex = function GiveHex(Dec)
  873. {
  874. if(Dec == 10)
  875. Value = "A";
  876. else
  877. if(Dec == 11)
  878. Value = "B";
  879. else
  880. if(Dec == 12)
  881. Value = "C";
  882. else
  883. if(Dec == 13)
  884. Value = "D";
  885. else
  886. if(Dec == 14)
  887. Value = "E";
  888. else
  889. if(Dec == 15)
  890. Value = "F";
  891. else
  892. Value = "" + Dec;
  893. return Value;
  894. }
  895. /**
  896. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  897. *
  898. * @param {String} hex
  899. * @returns {{r: *, g: *, b: *}}
  900. */
  901. util.hexToRGB = function hexToRGB(hex) {
  902. hex = hex.replace("#","").toUpperCase();
  903. var a = util.GiveDec(hex.substring(0, 1));
  904. var b = util.GiveDec(hex.substring(1, 2));
  905. var c = util.GiveDec(hex.substring(2, 3));
  906. var d = util.GiveDec(hex.substring(3, 4));
  907. var e = util.GiveDec(hex.substring(4, 5));
  908. var f = util.GiveDec(hex.substring(5, 6));
  909. var r = (a * 16) + b;
  910. var g = (c * 16) + d;
  911. var b = (e * 16) + f;
  912. return {r:r,g:g,b:b};
  913. };
  914. util.RGBToHex = function RGBToHex(red,green,blue) {
  915. var a = util.GiveHex(Math.floor(red / 16));
  916. var b = util.GiveHex(red % 16);
  917. var c = util.GiveHex(Math.floor(green / 16));
  918. var d = util.GiveHex(green % 16);
  919. var e = util.GiveHex(Math.floor(blue / 16));
  920. var f = util.GiveHex(blue % 16);
  921. var hex = a + b + c + d + e + f;
  922. return "#" + hex;
  923. };
  924. /**
  925. * http://www.javascripter.net/faq/rgb2hsv.htm
  926. *
  927. * @param red
  928. * @param green
  929. * @param blue
  930. * @returns {*}
  931. * @constructor
  932. */
  933. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  934. red=red/255; green=green/255; blue=blue/255;
  935. var minRGB = Math.min(red,Math.min(green,blue));
  936. var maxRGB = Math.max(red,Math.max(green,blue));
  937. // Black-gray-white
  938. if (minRGB == maxRGB) {
  939. return {h:0,s:0,v:minRGB};
  940. }
  941. // Colors other than black-gray-white:
  942. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  943. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  944. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  945. var saturation = (maxRGB - minRGB)/maxRGB;
  946. var value = maxRGB;
  947. return {h:hue,s:saturation,v:value};
  948. };
  949. /**
  950. * https://gist.github.com/mjijackson/5311256
  951. * @param hue
  952. * @param saturation
  953. * @param value
  954. * @returns {{r: number, g: number, b: number}}
  955. * @constructor
  956. */
  957. util.HSVToRGB = function HSVToRGB(h, s, v) {
  958. var r, g, b;
  959. var i = Math.floor(h * 6);
  960. var f = h * 6 - i;
  961. var p = v * (1 - s);
  962. var q = v * (1 - f * s);
  963. var t = v * (1 - (1 - f) * s);
  964. switch (i % 6) {
  965. case 0: r = v, g = t, b = p; break;
  966. case 1: r = q, g = v, b = p; break;
  967. case 2: r = p, g = v, b = t; break;
  968. case 3: r = p, g = q, b = v; break;
  969. case 4: r = t, g = p, b = v; break;
  970. case 5: r = v, g = p, b = q; break;
  971. }
  972. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  973. };
  974. util.HSVToHex = function HSVToHex(h,s,v) {
  975. var rgb = util.HSVToRGB(h,s,v);
  976. return util.RGBToHex(rgb.r,rgb.g,rgb.b);
  977. }
  978. util.hexToHSV = function hexToHSV(hex) {
  979. var rgb = util.hexToRGB(hex);
  980. return util.RGBToHSV(rgb.r,rgb.g,rgb.b);
  981. }
  982. util.isValidHex = function isValidHex(hex) {
  983. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  984. return isOk;
  985. }
  986. util.copyObject = function copyObject(objectFrom,objectTo) {
  987. for (var i in objectFrom) {
  988. if (objectFrom.hasOwnProperty(i)) {
  989. if (typeof objectFrom[i] == "object") {
  990. objectTo[i] = {};
  991. util.copyObject(objectFrom[i],objectTo[i]);
  992. }
  993. else {
  994. objectTo[i] = objectFrom[i];
  995. }
  996. }
  997. }
  998. }
  999. /**
  1000. * DataSet
  1001. *
  1002. * Usage:
  1003. * var dataSet = new DataSet({
  1004. * fieldId: '_id',
  1005. * convert: {
  1006. * // ...
  1007. * }
  1008. * });
  1009. *
  1010. * dataSet.add(item);
  1011. * dataSet.add(data);
  1012. * dataSet.update(item);
  1013. * dataSet.update(data);
  1014. * dataSet.remove(id);
  1015. * dataSet.remove(ids);
  1016. * var data = dataSet.get();
  1017. * var data = dataSet.get(id);
  1018. * var data = dataSet.get(ids);
  1019. * var data = dataSet.get(ids, options, data);
  1020. * dataSet.clear();
  1021. *
  1022. * A data set can:
  1023. * - add/remove/update data
  1024. * - gives triggers upon changes in the data
  1025. * - can import/export data in various data formats
  1026. *
  1027. * @param {Object} [options] Available options:
  1028. * {String} fieldId Field name of the id in the
  1029. * items, 'id' by default.
  1030. * {Object.<String, String} convert
  1031. * A map with field names as key,
  1032. * and the field type as value.
  1033. * @constructor DataSet
  1034. */
  1035. // TODO: add a DataSet constructor DataSet(data, options)
  1036. function DataSet (options) {
  1037. this.id = util.randomUUID();
  1038. this.options = options || {};
  1039. this.data = {}; // map with data indexed by id
  1040. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1041. this.convert = {}; // field types by field name
  1042. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1043. if (this.options.convert) {
  1044. for (var field in this.options.convert) {
  1045. if (this.options.convert.hasOwnProperty(field)) {
  1046. var value = this.options.convert[field];
  1047. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1048. this.convert[field] = 'Date';
  1049. }
  1050. else {
  1051. this.convert[field] = value;
  1052. }
  1053. }
  1054. }
  1055. }
  1056. // event subscribers
  1057. this.subscribers = {};
  1058. this.internalIds = {}; // internally generated id's
  1059. }
  1060. /**
  1061. * Subscribe to an event, add an event listener
  1062. * @param {String} event Event name. Available events: 'put', 'update',
  1063. * 'remove'
  1064. * @param {function} callback Callback method. Called with three parameters:
  1065. * {String} event
  1066. * {Object | null} params
  1067. * {String | Number} senderId
  1068. */
  1069. DataSet.prototype.on = function on (event, callback) {
  1070. var subscribers = this.subscribers[event];
  1071. if (!subscribers) {
  1072. subscribers = [];
  1073. this.subscribers[event] = subscribers;
  1074. }
  1075. subscribers.push({
  1076. callback: callback
  1077. });
  1078. };
  1079. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1080. DataSet.prototype.subscribe = DataSet.prototype.on;
  1081. /**
  1082. * Unsubscribe from an event, remove an event listener
  1083. * @param {String} event
  1084. * @param {function} callback
  1085. */
  1086. DataSet.prototype.off = function off(event, callback) {
  1087. var subscribers = this.subscribers[event];
  1088. if (subscribers) {
  1089. this.subscribers[event] = subscribers.filter(function (listener) {
  1090. return (listener.callback != callback);
  1091. });
  1092. }
  1093. };
  1094. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1095. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1096. /**
  1097. * Trigger an event
  1098. * @param {String} event
  1099. * @param {Object | null} params
  1100. * @param {String} [senderId] Optional id of the sender.
  1101. * @private
  1102. */
  1103. DataSet.prototype._trigger = function (event, params, senderId) {
  1104. if (event == '*') {
  1105. throw new Error('Cannot trigger event *');
  1106. }
  1107. var subscribers = [];
  1108. if (event in this.subscribers) {
  1109. subscribers = subscribers.concat(this.subscribers[event]);
  1110. }
  1111. if ('*' in this.subscribers) {
  1112. subscribers = subscribers.concat(this.subscribers['*']);
  1113. }
  1114. for (var i = 0; i < subscribers.length; i++) {
  1115. var subscriber = subscribers[i];
  1116. if (subscriber.callback) {
  1117. subscriber.callback(event, params, senderId || null);
  1118. }
  1119. }
  1120. };
  1121. /**
  1122. * Add data.
  1123. * Adding an item will fail when there already is an item with the same id.
  1124. * @param {Object | Array | DataTable} data
  1125. * @param {String} [senderId] Optional sender id
  1126. * @return {Array} addedIds Array with the ids of the added items
  1127. */
  1128. DataSet.prototype.add = function (data, senderId) {
  1129. var addedIds = [],
  1130. id,
  1131. me = this;
  1132. if (data instanceof Array) {
  1133. // Array
  1134. for (var i = 0, len = data.length; i < len; i++) {
  1135. id = me._addItem(data[i]);
  1136. addedIds.push(id);
  1137. }
  1138. }
  1139. else if (util.isDataTable(data)) {
  1140. // Google DataTable
  1141. var columns = this._getColumnNames(data);
  1142. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1143. var item = {};
  1144. for (var col = 0, cols = columns.length; col < cols; col++) {
  1145. var field = columns[col];
  1146. item[field] = data.getValue(row, col);
  1147. }
  1148. id = me._addItem(item);
  1149. addedIds.push(id);
  1150. }
  1151. }
  1152. else if (data instanceof Object) {
  1153. // Single item
  1154. id = me._addItem(data);
  1155. addedIds.push(id);
  1156. }
  1157. else {
  1158. throw new Error('Unknown dataType');
  1159. }
  1160. if (addedIds.length) {
  1161. this._trigger('add', {items: addedIds}, senderId);
  1162. }
  1163. return addedIds;
  1164. };
  1165. /**
  1166. * Update existing items. When an item does not exist, it will be created
  1167. * @param {Object | Array | DataTable} data
  1168. * @param {String} [senderId] Optional sender id
  1169. * @return {Array} updatedIds The ids of the added or updated items
  1170. */
  1171. DataSet.prototype.update = function (data, senderId) {
  1172. var addedIds = [],
  1173. updatedIds = [],
  1174. me = this,
  1175. fieldId = me.fieldId;
  1176. var addOrUpdate = function (item) {
  1177. var id = item[fieldId];
  1178. if (me.data[id]) {
  1179. // update item
  1180. id = me._updateItem(item);
  1181. updatedIds.push(id);
  1182. }
  1183. else {
  1184. // add new item
  1185. id = me._addItem(item);
  1186. addedIds.push(id);
  1187. }
  1188. };
  1189. if (data instanceof Array) {
  1190. // Array
  1191. for (var i = 0, len = data.length; i < len; i++) {
  1192. addOrUpdate(data[i]);
  1193. }
  1194. }
  1195. else if (util.isDataTable(data)) {
  1196. // Google DataTable
  1197. var columns = this._getColumnNames(data);
  1198. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1199. var item = {};
  1200. for (var col = 0, cols = columns.length; col < cols; col++) {
  1201. var field = columns[col];
  1202. item[field] = data.getValue(row, col);
  1203. }
  1204. addOrUpdate(item);
  1205. }
  1206. }
  1207. else if (data instanceof Object) {
  1208. // Single item
  1209. addOrUpdate(data);
  1210. }
  1211. else {
  1212. throw new Error('Unknown dataType');
  1213. }
  1214. if (addedIds.length) {
  1215. this._trigger('add', {items: addedIds}, senderId);
  1216. }
  1217. if (updatedIds.length) {
  1218. this._trigger('update', {items: updatedIds}, senderId);
  1219. }
  1220. return addedIds.concat(updatedIds);
  1221. };
  1222. /**
  1223. * Get a data item or multiple items.
  1224. *
  1225. * Usage:
  1226. *
  1227. * get()
  1228. * get(options: Object)
  1229. * get(options: Object, data: Array | DataTable)
  1230. *
  1231. * get(id: Number | String)
  1232. * get(id: Number | String, options: Object)
  1233. * get(id: Number | String, options: Object, data: Array | DataTable)
  1234. *
  1235. * get(ids: Number[] | String[])
  1236. * get(ids: Number[] | String[], options: Object)
  1237. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1238. *
  1239. * Where:
  1240. *
  1241. * {Number | String} id The id of an item
  1242. * {Number[] | String{}} ids An array with ids of items
  1243. * {Object} options An Object with options. Available options:
  1244. * {String} [type] Type of data to be returned. Can
  1245. * be 'DataTable' or 'Array' (default)
  1246. * {Object.<String, String>} [convert]
  1247. * {String[]} [fields] field names to be returned
  1248. * {function} [filter] filter items
  1249. * {String | function} [order] Order the items by
  1250. * a field name or custom sort function.
  1251. * {Array | DataTable} [data] If provided, items will be appended to this
  1252. * array or table. Required in case of Google
  1253. * DataTable.
  1254. *
  1255. * @throws Error
  1256. */
  1257. DataSet.prototype.get = function (args) {
  1258. var me = this;
  1259. var globalShowInternalIds = this.showInternalIds;
  1260. // parse the arguments
  1261. var id, ids, options, data;
  1262. var firstType = util.getType(arguments[0]);
  1263. if (firstType == 'String' || firstType == 'Number') {
  1264. // get(id [, options] [, data])
  1265. id = arguments[0];
  1266. options = arguments[1];
  1267. data = arguments[2];
  1268. }
  1269. else if (firstType == 'Array') {
  1270. // get(ids [, options] [, data])
  1271. ids = arguments[0];
  1272. options = arguments[1];
  1273. data = arguments[2];
  1274. }
  1275. else {
  1276. // get([, options] [, data])
  1277. options = arguments[0];
  1278. data = arguments[1];
  1279. }
  1280. // determine the return type
  1281. var type;
  1282. if (options && options.type) {
  1283. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1284. if (data && (type != util.getType(data))) {
  1285. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1286. 'does not correspond with specified options.type (' + options.type + ')');
  1287. }
  1288. if (type == 'DataTable' && !util.isDataTable(data)) {
  1289. throw new Error('Parameter "data" must be a DataTable ' +
  1290. 'when options.type is "DataTable"');
  1291. }
  1292. }
  1293. else if (data) {
  1294. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1295. }
  1296. else {
  1297. type = 'Array';
  1298. }
  1299. // we allow the setting of this value for a single get request.
  1300. if (options != undefined) {
  1301. if (options.showInternalIds != undefined) {
  1302. this.showInternalIds = options.showInternalIds;
  1303. }
  1304. }
  1305. // build options
  1306. var convert = options && options.convert || this.options.convert;
  1307. var filter = options && options.filter;
  1308. var items = [], item, itemId, i, len;
  1309. // convert items
  1310. if (id != undefined) {
  1311. // return a single item
  1312. item = me._getItem(id, convert);
  1313. if (filter && !filter(item)) {
  1314. item = null;
  1315. }
  1316. }
  1317. else if (ids != undefined) {
  1318. // return a subset of items
  1319. for (i = 0, len = ids.length; i < len; i++) {
  1320. item = me._getItem(ids[i], convert);
  1321. if (!filter || filter(item)) {
  1322. items.push(item);
  1323. }
  1324. }
  1325. }
  1326. else {
  1327. // return all items
  1328. for (itemId in this.data) {
  1329. if (this.data.hasOwnProperty(itemId)) {
  1330. item = me._getItem(itemId, convert);
  1331. if (!filter || filter(item)) {
  1332. items.push(item);
  1333. }
  1334. }
  1335. }
  1336. }
  1337. // restore the global value of showInternalIds
  1338. this.showInternalIds = globalShowInternalIds;
  1339. // order the results
  1340. if (options && options.order && id == undefined) {
  1341. this._sort(items, options.order);
  1342. }
  1343. // filter fields of the items
  1344. if (options && options.fields) {
  1345. var fields = options.fields;
  1346. if (id != undefined) {
  1347. item = this._filterFields(item, fields);
  1348. }
  1349. else {
  1350. for (i = 0, len = items.length; i < len; i++) {
  1351. items[i] = this._filterFields(items[i], fields);
  1352. }
  1353. }
  1354. }
  1355. // return the results
  1356. if (type == 'DataTable') {
  1357. var columns = this._getColumnNames(data);
  1358. if (id != undefined) {
  1359. // append a single item to the data table
  1360. me._appendRow(data, columns, item);
  1361. }
  1362. else {
  1363. // copy the items to the provided data table
  1364. for (i = 0, len = items.length; i < len; i++) {
  1365. me._appendRow(data, columns, items[i]);
  1366. }
  1367. }
  1368. return data;
  1369. }
  1370. else {
  1371. // return an array
  1372. if (id != undefined) {
  1373. // a single item
  1374. return item;
  1375. }
  1376. else {
  1377. // multiple items
  1378. if (data) {
  1379. // copy the items to the provided array
  1380. for (i = 0, len = items.length; i < len; i++) {
  1381. data.push(items[i]);
  1382. }
  1383. return data;
  1384. }
  1385. else {
  1386. // just return our array
  1387. return items;
  1388. }
  1389. }
  1390. }
  1391. };
  1392. /**
  1393. * Get ids of all items or from a filtered set of items.
  1394. * @param {Object} [options] An Object with options. Available options:
  1395. * {function} [filter] filter items
  1396. * {String | function} [order] Order the items by
  1397. * a field name or custom sort function.
  1398. * @return {Array} ids
  1399. */
  1400. DataSet.prototype.getIds = function (options) {
  1401. var data = this.data,
  1402. filter = options && options.filter,
  1403. order = options && options.order,
  1404. convert = options && options.convert || this.options.convert,
  1405. i,
  1406. len,
  1407. id,
  1408. item,
  1409. items,
  1410. ids = [];
  1411. if (filter) {
  1412. // get filtered items
  1413. if (order) {
  1414. // create ordered list
  1415. items = [];
  1416. for (id in data) {
  1417. if (data.hasOwnProperty(id)) {
  1418. item = this._getItem(id, convert);
  1419. if (filter(item)) {
  1420. items.push(item);
  1421. }
  1422. }
  1423. }
  1424. this._sort(items, order);
  1425. for (i = 0, len = items.length; i < len; i++) {
  1426. ids[i] = items[i][this.fieldId];
  1427. }
  1428. }
  1429. else {
  1430. // create unordered list
  1431. for (id in data) {
  1432. if (data.hasOwnProperty(id)) {
  1433. item = this._getItem(id, convert);
  1434. if (filter(item)) {
  1435. ids.push(item[this.fieldId]);
  1436. }
  1437. }
  1438. }
  1439. }
  1440. }
  1441. else {
  1442. // get all items
  1443. if (order) {
  1444. // create an ordered list
  1445. items = [];
  1446. for (id in data) {
  1447. if (data.hasOwnProperty(id)) {
  1448. items.push(data[id]);
  1449. }
  1450. }
  1451. this._sort(items, order);
  1452. for (i = 0, len = items.length; i < len; i++) {
  1453. ids[i] = items[i][this.fieldId];
  1454. }
  1455. }
  1456. else {
  1457. // create unordered list
  1458. for (id in data) {
  1459. if (data.hasOwnProperty(id)) {
  1460. item = data[id];
  1461. ids.push(item[this.fieldId]);
  1462. }
  1463. }
  1464. }
  1465. }
  1466. return ids;
  1467. };
  1468. /**
  1469. * Execute a callback function for every item in the dataset.
  1470. * The order of the items is not determined.
  1471. * @param {function} callback
  1472. * @param {Object} [options] Available options:
  1473. * {Object.<String, String>} [convert]
  1474. * {String[]} [fields] filter fields
  1475. * {function} [filter] filter items
  1476. * {String | function} [order] Order the items by
  1477. * a field name or custom sort function.
  1478. */
  1479. DataSet.prototype.forEach = function (callback, options) {
  1480. var filter = options && options.filter,
  1481. convert = options && options.convert || this.options.convert,
  1482. data = this.data,
  1483. item,
  1484. id;
  1485. if (options && options.order) {
  1486. // execute forEach on ordered list
  1487. var items = this.get(options);
  1488. for (var i = 0, len = items.length; i < len; i++) {
  1489. item = items[i];
  1490. id = item[this.fieldId];
  1491. callback(item, id);
  1492. }
  1493. }
  1494. else {
  1495. // unordered
  1496. for (id in data) {
  1497. if (data.hasOwnProperty(id)) {
  1498. item = this._getItem(id, convert);
  1499. if (!filter || filter(item)) {
  1500. callback(item, id);
  1501. }
  1502. }
  1503. }
  1504. }
  1505. };
  1506. /**
  1507. * Map every item in the dataset.
  1508. * @param {function} callback
  1509. * @param {Object} [options] Available options:
  1510. * {Object.<String, String>} [convert]
  1511. * {String[]} [fields] filter fields
  1512. * {function} [filter] filter items
  1513. * {String | function} [order] Order the items by
  1514. * a field name or custom sort function.
  1515. * @return {Object[]} mappedItems
  1516. */
  1517. DataSet.prototype.map = function (callback, options) {
  1518. var filter = options && options.filter,
  1519. convert = options && options.convert || this.options.convert,
  1520. mappedItems = [],
  1521. data = this.data,
  1522. item;
  1523. // convert and filter items
  1524. for (var id in data) {
  1525. if (data.hasOwnProperty(id)) {
  1526. item = this._getItem(id, convert);
  1527. if (!filter || filter(item)) {
  1528. mappedItems.push(callback(item, id));
  1529. }
  1530. }
  1531. }
  1532. // order items
  1533. if (options && options.order) {
  1534. this._sort(mappedItems, options.order);
  1535. }
  1536. return mappedItems;
  1537. };
  1538. /**
  1539. * Filter the fields of an item
  1540. * @param {Object} item
  1541. * @param {String[]} fields Field names
  1542. * @return {Object} filteredItem
  1543. * @private
  1544. */
  1545. DataSet.prototype._filterFields = function (item, fields) {
  1546. var filteredItem = {};
  1547. for (var field in item) {
  1548. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1549. filteredItem[field] = item[field];
  1550. }
  1551. }
  1552. return filteredItem;
  1553. };
  1554. /**
  1555. * Sort the provided array with items
  1556. * @param {Object[]} items
  1557. * @param {String | function} order A field name or custom sort function.
  1558. * @private
  1559. */
  1560. DataSet.prototype._sort = function (items, order) {
  1561. if (util.isString(order)) {
  1562. // order by provided field name
  1563. var name = order; // field name
  1564. items.sort(function (a, b) {
  1565. var av = a[name];
  1566. var bv = b[name];
  1567. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1568. });
  1569. }
  1570. else if (typeof order === 'function') {
  1571. // order by sort function
  1572. items.sort(order);
  1573. }
  1574. // TODO: extend order by an Object {field:String, direction:String}
  1575. // where direction can be 'asc' or 'desc'
  1576. else {
  1577. throw new TypeError('Order must be a function or a string');
  1578. }
  1579. };
  1580. /**
  1581. * Remove an object by pointer or by id
  1582. * @param {String | Number | Object | Array} id Object or id, or an array with
  1583. * objects or ids to be removed
  1584. * @param {String} [senderId] Optional sender id
  1585. * @return {Array} removedIds
  1586. */
  1587. DataSet.prototype.remove = function (id, senderId) {
  1588. var removedIds = [],
  1589. i, len, removedId;
  1590. if (id instanceof Array) {
  1591. for (i = 0, len = id.length; i < len; i++) {
  1592. removedId = this._remove(id[i]);
  1593. if (removedId != null) {
  1594. removedIds.push(removedId);
  1595. }
  1596. }
  1597. }
  1598. else {
  1599. removedId = this._remove(id);
  1600. if (removedId != null) {
  1601. removedIds.push(removedId);
  1602. }
  1603. }
  1604. if (removedIds.length) {
  1605. this._trigger('remove', {items: removedIds}, senderId);
  1606. }
  1607. return removedIds;
  1608. };
  1609. /**
  1610. * Remove an item by its id
  1611. * @param {Number | String | Object} id id or item
  1612. * @returns {Number | String | null} id
  1613. * @private
  1614. */
  1615. DataSet.prototype._remove = function (id) {
  1616. if (util.isNumber(id) || util.isString(id)) {
  1617. if (this.data[id]) {
  1618. delete this.data[id];
  1619. delete this.internalIds[id];
  1620. return id;
  1621. }
  1622. }
  1623. else if (id instanceof Object) {
  1624. var itemId = id[this.fieldId];
  1625. if (itemId && this.data[itemId]) {
  1626. delete this.data[itemId];
  1627. delete this.internalIds[itemId];
  1628. return itemId;
  1629. }
  1630. }
  1631. return null;
  1632. };
  1633. /**
  1634. * Clear the data
  1635. * @param {String} [senderId] Optional sender id
  1636. * @return {Array} removedIds The ids of all removed items
  1637. */
  1638. DataSet.prototype.clear = function (senderId) {
  1639. var ids = Object.keys(this.data);
  1640. this.data = {};
  1641. this.internalIds = {};
  1642. this._trigger('remove', {items: ids}, senderId);
  1643. return ids;
  1644. };
  1645. /**
  1646. * Find the item with maximum value of a specified field
  1647. * @param {String} field
  1648. * @return {Object | null} item Item containing max value, or null if no items
  1649. */
  1650. DataSet.prototype.max = function (field) {
  1651. var data = this.data,
  1652. max = null,
  1653. maxField = null;
  1654. for (var id in data) {
  1655. if (data.hasOwnProperty(id)) {
  1656. var item = data[id];
  1657. var itemField = item[field];
  1658. if (itemField != null && (!max || itemField > maxField)) {
  1659. max = item;
  1660. maxField = itemField;
  1661. }
  1662. }
  1663. }
  1664. return max;
  1665. };
  1666. /**
  1667. * Find the item with minimum value of a specified field
  1668. * @param {String} field
  1669. * @return {Object | null} item Item containing max value, or null if no items
  1670. */
  1671. DataSet.prototype.min = function (field) {
  1672. var data = this.data,
  1673. min = null,
  1674. minField = null;
  1675. for (var id in data) {
  1676. if (data.hasOwnProperty(id)) {
  1677. var item = data[id];
  1678. var itemField = item[field];
  1679. if (itemField != null && (!min || itemField < minField)) {
  1680. min = item;
  1681. minField = itemField;
  1682. }
  1683. }
  1684. }
  1685. return min;
  1686. };
  1687. /**
  1688. * Find all distinct values of a specified field
  1689. * @param {String} field
  1690. * @return {Array} values Array containing all distinct values. If the data
  1691. * items do not contain the specified field, an array
  1692. * containing a single value undefined is returned.
  1693. * The returned array is unordered.
  1694. */
  1695. DataSet.prototype.distinct = function (field) {
  1696. var data = this.data,
  1697. values = [],
  1698. fieldType = this.options.convert[field],
  1699. count = 0;
  1700. for (var prop in data) {
  1701. if (data.hasOwnProperty(prop)) {
  1702. var item = data[prop];
  1703. var value = util.convert(item[field], fieldType);
  1704. var exists = false;
  1705. for (var i = 0; i < count; i++) {
  1706. if (values[i] == value) {
  1707. exists = true;
  1708. break;
  1709. }
  1710. }
  1711. if (!exists) {
  1712. values[count] = value;
  1713. count++;
  1714. }
  1715. }
  1716. }
  1717. return values;
  1718. };
  1719. /**
  1720. * Add a single item. Will fail when an item with the same id already exists.
  1721. * @param {Object} item
  1722. * @return {String} id
  1723. * @private
  1724. */
  1725. DataSet.prototype._addItem = function (item) {
  1726. var id = item[this.fieldId];
  1727. if (id != undefined) {
  1728. // check whether this id is already taken
  1729. if (this.data[id]) {
  1730. // item already exists
  1731. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1732. }
  1733. }
  1734. else {
  1735. // generate an id
  1736. id = util.randomUUID();
  1737. item[this.fieldId] = id;
  1738. this.internalIds[id] = item;
  1739. }
  1740. var d = {};
  1741. for (var field in item) {
  1742. if (item.hasOwnProperty(field)) {
  1743. var fieldType = this.convert[field]; // type may be undefined
  1744. d[field] = util.convert(item[field], fieldType);
  1745. }
  1746. }
  1747. this.data[id] = d;
  1748. return id;
  1749. };
  1750. /**
  1751. * Get an item. Fields can be converted to a specific type
  1752. * @param {String} id
  1753. * @param {Object.<String, String>} [convert] field types to convert
  1754. * @return {Object | null} item
  1755. * @private
  1756. */
  1757. DataSet.prototype._getItem = function (id, convert) {
  1758. var field, value;
  1759. // get the item from the dataset
  1760. var raw = this.data[id];
  1761. if (!raw) {
  1762. return null;
  1763. }
  1764. // convert the items field types
  1765. var converted = {},
  1766. fieldId = this.fieldId,
  1767. internalIds = this.internalIds;
  1768. if (convert) {
  1769. for (field in raw) {
  1770. if (raw.hasOwnProperty(field)) {
  1771. value = raw[field];
  1772. // output all fields, except internal ids
  1773. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1774. converted[field] = util.convert(value, convert[field]);
  1775. }
  1776. }
  1777. }
  1778. }
  1779. else {
  1780. // no field types specified, no converting needed
  1781. for (field in raw) {
  1782. if (raw.hasOwnProperty(field)) {
  1783. value = raw[field];
  1784. // output all fields, except internal ids
  1785. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1786. converted[field] = value;
  1787. }
  1788. }
  1789. }
  1790. }
  1791. return converted;
  1792. };
  1793. /**
  1794. * Update a single item: merge with existing item.
  1795. * Will fail when the item has no id, or when there does not exist an item
  1796. * with the same id.
  1797. * @param {Object} item
  1798. * @return {String} id
  1799. * @private
  1800. */
  1801. DataSet.prototype._updateItem = function (item) {
  1802. var id = item[this.fieldId];
  1803. if (id == undefined) {
  1804. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1805. }
  1806. var d = this.data[id];
  1807. if (!d) {
  1808. // item doesn't exist
  1809. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1810. }
  1811. // merge with current item
  1812. for (var field in item) {
  1813. if (item.hasOwnProperty(field)) {
  1814. var fieldType = this.convert[field]; // type may be undefined
  1815. d[field] = util.convert(item[field], fieldType);
  1816. }
  1817. }
  1818. return id;
  1819. };
  1820. /**
  1821. * check if an id is an internal or external id
  1822. * @param id
  1823. * @returns {boolean}
  1824. * @private
  1825. */
  1826. DataSet.prototype.isInternalId = function(id) {
  1827. return (id in this.internalIds);
  1828. };
  1829. /**
  1830. * Get an array with the column names of a Google DataTable
  1831. * @param {DataTable} dataTable
  1832. * @return {String[]} columnNames
  1833. * @private
  1834. */
  1835. DataSet.prototype._getColumnNames = function (dataTable) {
  1836. var columns = [];
  1837. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1838. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1839. }
  1840. return columns;
  1841. };
  1842. /**
  1843. * Append an item as a row to the dataTable
  1844. * @param dataTable
  1845. * @param columns
  1846. * @param item
  1847. * @private
  1848. */
  1849. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1850. var row = dataTable.addRow();
  1851. for (var col = 0, cols = columns.length; col < cols; col++) {
  1852. var field = columns[col];
  1853. dataTable.setValue(row, col, item[field]);
  1854. }
  1855. };
  1856. /**
  1857. * DataView
  1858. *
  1859. * a dataview offers a filtered view on a dataset or an other dataview.
  1860. *
  1861. * @param {DataSet | DataView} data
  1862. * @param {Object} [options] Available options: see method get
  1863. *
  1864. * @constructor DataView
  1865. */
  1866. function DataView (data, options) {
  1867. this.id = util.randomUUID();
  1868. this.data = null;
  1869. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1870. this.options = options || {};
  1871. this.fieldId = 'id'; // name of the field containing id
  1872. this.subscribers = {}; // event subscribers
  1873. var me = this;
  1874. this.listener = function () {
  1875. me._onEvent.apply(me, arguments);
  1876. };
  1877. this.setData(data);
  1878. }
  1879. // TODO: implement a function .config() to dynamically update things like configured filter
  1880. // and trigger changes accordingly
  1881. /**
  1882. * Set a data source for the view
  1883. * @param {DataSet | DataView} data
  1884. */
  1885. DataView.prototype.setData = function (data) {
  1886. var ids, dataItems, i, len;
  1887. if (this.data) {
  1888. // unsubscribe from current dataset
  1889. if (this.data.unsubscribe) {
  1890. this.data.unsubscribe('*', this.listener);
  1891. }
  1892. // trigger a remove of all items in memory
  1893. ids = [];
  1894. for (var id in this.ids) {
  1895. if (this.ids.hasOwnProperty(id)) {
  1896. ids.push(id);
  1897. }
  1898. }
  1899. this.ids = {};
  1900. this._trigger('remove', {items: ids});
  1901. }
  1902. this.data = data;
  1903. if (this.data) {
  1904. // update fieldId
  1905. this.fieldId = this.options.fieldId ||
  1906. (this.data && this.data.options && this.data.options.fieldId) ||
  1907. 'id';
  1908. // trigger an add of all added items
  1909. ids = this.data.getIds({filter: this.options && this.options.filter});
  1910. for (i = 0, len = ids.length; i < len; i++) {
  1911. id = ids[i];
  1912. this.ids[id] = true;
  1913. }
  1914. this._trigger('add', {items: ids});
  1915. // subscribe to new dataset
  1916. if (this.data.on) {
  1917. this.data.on('*', this.listener);
  1918. }
  1919. }
  1920. };
  1921. /**
  1922. * Get data from the data view
  1923. *
  1924. * Usage:
  1925. *
  1926. * get()
  1927. * get(options: Object)
  1928. * get(options: Object, data: Array | DataTable)
  1929. *
  1930. * get(id: Number)
  1931. * get(id: Number, options: Object)
  1932. * get(id: Number, options: Object, data: Array | DataTable)
  1933. *
  1934. * get(ids: Number[])
  1935. * get(ids: Number[], options: Object)
  1936. * get(ids: Number[], options: Object, data: Array | DataTable)
  1937. *
  1938. * Where:
  1939. *
  1940. * {Number | String} id The id of an item
  1941. * {Number[] | String{}} ids An array with ids of items
  1942. * {Object} options An Object with options. Available options:
  1943. * {String} [type] Type of data to be returned. Can
  1944. * be 'DataTable' or 'Array' (default)
  1945. * {Object.<String, String>} [convert]
  1946. * {String[]} [fields] field names to be returned
  1947. * {function} [filter] filter items
  1948. * {String | function} [order] Order the items by
  1949. * a field name or custom sort function.
  1950. * {Array | DataTable} [data] If provided, items will be appended to this
  1951. * array or table. Required in case of Google
  1952. * DataTable.
  1953. * @param args
  1954. */
  1955. DataView.prototype.get = function (args) {
  1956. var me = this;
  1957. // parse the arguments
  1958. var ids, options, data;
  1959. var firstType = util.getType(arguments[0]);
  1960. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  1961. // get(id(s) [, options] [, data])
  1962. ids = arguments[0]; // can be a single id or an array with ids
  1963. options = arguments[1];
  1964. data = arguments[2];
  1965. }
  1966. else {
  1967. // get([, options] [, data])
  1968. options = arguments[0];
  1969. data = arguments[1];
  1970. }
  1971. // extend the options with the default options and provided options
  1972. var viewOptions = util.extend({}, this.options, options);
  1973. // create a combined filter method when needed
  1974. if (this.options.filter && options && options.filter) {
  1975. viewOptions.filter = function (item) {
  1976. return me.options.filter(item) && options.filter(item);
  1977. }
  1978. }
  1979. // build up the call to the linked data set
  1980. var getArguments = [];
  1981. if (ids != undefined) {
  1982. getArguments.push(ids);
  1983. }
  1984. getArguments.push(viewOptions);
  1985. getArguments.push(data);
  1986. return this.data && this.data.get.apply(this.data, getArguments);
  1987. };
  1988. /**
  1989. * Get ids of all items or from a filtered set of items.
  1990. * @param {Object} [options] An Object with options. Available options:
  1991. * {function} [filter] filter items
  1992. * {String | function} [order] Order the items by
  1993. * a field name or custom sort function.
  1994. * @return {Array} ids
  1995. */
  1996. DataView.prototype.getIds = function (options) {
  1997. var ids;
  1998. if (this.data) {
  1999. var defaultFilter = this.options.filter;
  2000. var filter;
  2001. if (options && options.filter) {
  2002. if (defaultFilter) {
  2003. filter = function (item) {
  2004. return defaultFilter(item) && options.filter(item);
  2005. }
  2006. }
  2007. else {
  2008. filter = options.filter;
  2009. }
  2010. }
  2011. else {
  2012. filter = defaultFilter;
  2013. }
  2014. ids = this.data.getIds({
  2015. filter: filter,
  2016. order: options && options.order
  2017. });
  2018. }
  2019. else {
  2020. ids = [];
  2021. }
  2022. return ids;
  2023. };
  2024. /**
  2025. * Event listener. Will propagate all events from the connected data set to
  2026. * the subscribers of the DataView, but will filter the items and only trigger
  2027. * when there are changes in the filtered data set.
  2028. * @param {String} event
  2029. * @param {Object | null} params
  2030. * @param {String} senderId
  2031. * @private
  2032. */
  2033. DataView.prototype._onEvent = function (event, params, senderId) {
  2034. var i, len, id, item,
  2035. ids = params && params.items,
  2036. data = this.data,
  2037. added = [],
  2038. updated = [],
  2039. removed = [];
  2040. if (ids && data) {
  2041. switch (event) {
  2042. case 'add':
  2043. // filter the ids of the added items
  2044. for (i = 0, len = ids.length; i < len; i++) {
  2045. id = ids[i];
  2046. item = this.get(id);
  2047. if (item) {
  2048. this.ids[id] = true;
  2049. added.push(id);
  2050. }
  2051. }
  2052. break;
  2053. case 'update':
  2054. // determine the event from the views viewpoint: an updated
  2055. // item can be added, updated, or removed from this view.
  2056. for (i = 0, len = ids.length; i < len; i++) {
  2057. id = ids[i];
  2058. item = this.get(id);
  2059. if (item) {
  2060. if (this.ids[id]) {
  2061. updated.push(id);
  2062. }
  2063. else {
  2064. this.ids[id] = true;
  2065. added.push(id);
  2066. }
  2067. }
  2068. else {
  2069. if (this.ids[id]) {
  2070. delete this.ids[id];
  2071. removed.push(id);
  2072. }
  2073. else {
  2074. // nothing interesting for me :-(
  2075. }
  2076. }
  2077. }
  2078. break;
  2079. case 'remove':
  2080. // filter the ids of the removed items
  2081. for (i = 0, len = ids.length; i < len; i++) {
  2082. id = ids[i];
  2083. if (this.ids[id]) {
  2084. delete this.ids[id];
  2085. removed.push(id);
  2086. }
  2087. }
  2088. break;
  2089. }
  2090. if (added.length) {
  2091. this._trigger('add', {items: added}, senderId);
  2092. }
  2093. if (updated.length) {
  2094. this._trigger('update', {items: updated}, senderId);
  2095. }
  2096. if (removed.length) {
  2097. this._trigger('remove', {items: removed}, senderId);
  2098. }
  2099. }
  2100. };
  2101. // copy subscription functionality from DataSet
  2102. DataView.prototype.on = DataSet.prototype.on;
  2103. DataView.prototype.off = DataSet.prototype.off;
  2104. DataView.prototype._trigger = DataSet.prototype._trigger;
  2105. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2106. DataView.prototype.subscribe = DataView.prototype.on;
  2107. DataView.prototype.unsubscribe = DataView.prototype.off;
  2108. /**
  2109. * @constructor TimeStep
  2110. * The class TimeStep is an iterator for dates. You provide a start date and an
  2111. * end date. The class itself determines the best scale (step size) based on the
  2112. * provided start Date, end Date, and minimumStep.
  2113. *
  2114. * If minimumStep is provided, the step size is chosen as close as possible
  2115. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2116. * provided, the scale is set to 1 DAY.
  2117. * The minimumStep should correspond with the onscreen size of about 6 characters
  2118. *
  2119. * Alternatively, you can set a scale by hand.
  2120. * After creation, you can initialize the class by executing first(). Then you
  2121. * can iterate from the start date to the end date via next(). You can check if
  2122. * the end date is reached with the function hasNext(). After each step, you can
  2123. * retrieve the current date via getCurrent().
  2124. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2125. * days, to years.
  2126. *
  2127. * Version: 1.2
  2128. *
  2129. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2130. * or new Date(2010, 9, 21, 23, 45, 00)
  2131. * @param {Date} [end] The end date
  2132. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2133. */
  2134. TimeStep = function(start, end, minimumStep) {
  2135. // variables
  2136. this.current = new Date();
  2137. this._start = new Date();
  2138. this._end = new Date();
  2139. this.autoScale = true;
  2140. this.scale = TimeStep.SCALE.DAY;
  2141. this.step = 1;
  2142. // initialize the range
  2143. this.setRange(start, end, minimumStep);
  2144. };
  2145. /// enum scale
  2146. TimeStep.SCALE = {
  2147. MILLISECOND: 1,
  2148. SECOND: 2,
  2149. MINUTE: 3,
  2150. HOUR: 4,
  2151. DAY: 5,
  2152. WEEKDAY: 6,
  2153. MONTH: 7,
  2154. YEAR: 8
  2155. };
  2156. /**
  2157. * Set a new range
  2158. * If minimumStep is provided, the step size is chosen as close as possible
  2159. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2160. * provided, the scale is set to 1 DAY.
  2161. * The minimumStep should correspond with the onscreen size of about 6 characters
  2162. * @param {Date} [start] The start date and time.
  2163. * @param {Date} [end] The end date and time.
  2164. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2165. */
  2166. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2167. if (!(start instanceof Date) || !(end instanceof Date)) {
  2168. throw "No legal start or end date in method setRange";
  2169. }
  2170. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2171. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2172. if (this.autoScale) {
  2173. this.setMinimumStep(minimumStep);
  2174. }
  2175. };
  2176. /**
  2177. * Set the range iterator to the start date.
  2178. */
  2179. TimeStep.prototype.first = function() {
  2180. this.current = new Date(this._start.valueOf());
  2181. this.roundToMinor();
  2182. };
  2183. /**
  2184. * Round the current date to the first minor date value
  2185. * This must be executed once when the current date is set to start Date
  2186. */
  2187. TimeStep.prototype.roundToMinor = function() {
  2188. // round to floor
  2189. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2190. //noinspection FallthroughInSwitchStatementJS
  2191. switch (this.scale) {
  2192. case TimeStep.SCALE.YEAR:
  2193. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2194. this.current.setMonth(0);
  2195. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2196. case TimeStep.SCALE.DAY: // intentional fall through
  2197. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2198. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2199. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2200. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2201. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2202. }
  2203. if (this.step != 1) {
  2204. // round down to the first minor value that is a multiple of the current step size
  2205. switch (this.scale) {
  2206. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2207. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2208. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2209. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2210. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2211. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2212. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2213. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2214. default: break;
  2215. }
  2216. }
  2217. };
  2218. /**
  2219. * Check if the there is a next step
  2220. * @return {boolean} true if the current date has not passed the end date
  2221. */
  2222. TimeStep.prototype.hasNext = function () {
  2223. return (this.current.valueOf() <= this._end.valueOf());
  2224. };
  2225. /**
  2226. * Do the next step
  2227. */
  2228. TimeStep.prototype.next = function() {
  2229. var prev = this.current.valueOf();
  2230. // Two cases, needed to prevent issues with switching daylight savings
  2231. // (end of March and end of October)
  2232. if (this.current.getMonth() < 6) {
  2233. switch (this.scale) {
  2234. case TimeStep.SCALE.MILLISECOND:
  2235. this.current = new Date(this.current.valueOf() + this.step); break;
  2236. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2237. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2238. case TimeStep.SCALE.HOUR:
  2239. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2240. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2241. var h = this.current.getHours();
  2242. this.current.setHours(h - (h % this.step));
  2243. break;
  2244. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2245. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2246. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2247. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2248. default: break;
  2249. }
  2250. }
  2251. else {
  2252. switch (this.scale) {
  2253. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2254. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2255. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2256. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2257. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2258. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2259. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2260. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2261. default: break;
  2262. }
  2263. }
  2264. if (this.step != 1) {
  2265. // round down to the correct major value
  2266. switch (this.scale) {
  2267. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2268. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2269. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2270. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2271. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2272. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2273. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2274. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2275. default: break;
  2276. }
  2277. }
  2278. // safety mechanism: if current time is still unchanged, move to the end
  2279. if (this.current.valueOf() == prev) {
  2280. this.current = new Date(this._end.valueOf());
  2281. }
  2282. };
  2283. /**
  2284. * Get the current datetime
  2285. * @return {Date} current The current date
  2286. */
  2287. TimeStep.prototype.getCurrent = function() {
  2288. return this.current;
  2289. };
  2290. /**
  2291. * Set a custom scale. Autoscaling will be disabled.
  2292. * For example setScale(SCALE.MINUTES, 5) will result
  2293. * in minor steps of 5 minutes, and major steps of an hour.
  2294. *
  2295. * @param {TimeStep.SCALE} newScale
  2296. * A scale. Choose from SCALE.MILLISECOND,
  2297. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2298. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2299. * SCALE.YEAR.
  2300. * @param {Number} newStep A step size, by default 1. Choose for
  2301. * example 1, 2, 5, or 10.
  2302. */
  2303. TimeStep.prototype.setScale = function(newScale, newStep) {
  2304. this.scale = newScale;
  2305. if (newStep > 0) {
  2306. this.step = newStep;
  2307. }
  2308. this.autoScale = false;
  2309. };
  2310. /**
  2311. * Enable or disable autoscaling
  2312. * @param {boolean} enable If true, autoascaling is set true
  2313. */
  2314. TimeStep.prototype.setAutoScale = function (enable) {
  2315. this.autoScale = enable;
  2316. };
  2317. /**
  2318. * Automatically determine the scale that bests fits the provided minimum step
  2319. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2320. */
  2321. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2322. if (minimumStep == undefined) {
  2323. return;
  2324. }
  2325. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2326. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2327. var stepDay = (1000 * 60 * 60 * 24);
  2328. var stepHour = (1000 * 60 * 60);
  2329. var stepMinute = (1000 * 60);
  2330. var stepSecond = (1000);
  2331. var stepMillisecond= (1);
  2332. // find the smallest step that is larger than the provided minimumStep
  2333. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2334. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2335. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2336. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2337. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2338. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2339. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2340. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2341. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2342. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2343. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2344. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2345. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2346. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2347. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2348. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2349. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2350. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2351. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2352. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2353. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2354. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2355. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2356. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2357. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2358. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2359. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2360. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2361. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2362. };
  2363. /**
  2364. * Snap a date to a rounded value.
  2365. * The snap intervals are dependent on the current scale and step.
  2366. * @param {Date} date the date to be snapped.
  2367. * @return {Date} snappedDate
  2368. */
  2369. TimeStep.prototype.snap = function(date) {
  2370. var clone = new Date(date.valueOf());
  2371. if (this.scale == TimeStep.SCALE.YEAR) {
  2372. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2373. clone.setFullYear(Math.round(year / this.step) * this.step);
  2374. clone.setMonth(0);
  2375. clone.setDate(0);
  2376. clone.setHours(0);
  2377. clone.setMinutes(0);
  2378. clone.setSeconds(0);
  2379. clone.setMilliseconds(0);
  2380. }
  2381. else if (this.scale == TimeStep.SCALE.MONTH) {
  2382. if (clone.getDate() > 15) {
  2383. clone.setDate(1);
  2384. clone.setMonth(clone.getMonth() + 1);
  2385. // important: first set Date to 1, after that change the month.
  2386. }
  2387. else {
  2388. clone.setDate(1);
  2389. }
  2390. clone.setHours(0);
  2391. clone.setMinutes(0);
  2392. clone.setSeconds(0);
  2393. clone.setMilliseconds(0);
  2394. }
  2395. else if (this.scale == TimeStep.SCALE.DAY ||
  2396. this.scale == TimeStep.SCALE.WEEKDAY) {
  2397. //noinspection FallthroughInSwitchStatementJS
  2398. switch (this.step) {
  2399. case 5:
  2400. case 2:
  2401. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2402. default:
  2403. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2404. }
  2405. clone.setMinutes(0);
  2406. clone.setSeconds(0);
  2407. clone.setMilliseconds(0);
  2408. }
  2409. else if (this.scale == TimeStep.SCALE.HOUR) {
  2410. switch (this.step) {
  2411. case 4:
  2412. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2413. default:
  2414. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2415. }
  2416. clone.setSeconds(0);
  2417. clone.setMilliseconds(0);
  2418. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2419. //noinspection FallthroughInSwitchStatementJS
  2420. switch (this.step) {
  2421. case 15:
  2422. case 10:
  2423. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2424. clone.setSeconds(0);
  2425. break;
  2426. case 5:
  2427. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2428. default:
  2429. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2430. }
  2431. clone.setMilliseconds(0);
  2432. }
  2433. else if (this.scale == TimeStep.SCALE.SECOND) {
  2434. //noinspection FallthroughInSwitchStatementJS
  2435. switch (this.step) {
  2436. case 15:
  2437. case 10:
  2438. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2439. clone.setMilliseconds(0);
  2440. break;
  2441. case 5:
  2442. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2443. default:
  2444. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2445. }
  2446. }
  2447. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2448. var step = this.step > 5 ? this.step / 2 : 1;
  2449. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2450. }
  2451. return clone;
  2452. };
  2453. /**
  2454. * Check if the current value is a major value (for example when the step
  2455. * is DAY, a major value is each first day of the MONTH)
  2456. * @return {boolean} true if current date is major, else false.
  2457. */
  2458. TimeStep.prototype.isMajor = function() {
  2459. switch (this.scale) {
  2460. case TimeStep.SCALE.MILLISECOND:
  2461. return (this.current.getMilliseconds() == 0);
  2462. case TimeStep.SCALE.SECOND:
  2463. return (this.current.getSeconds() == 0);
  2464. case TimeStep.SCALE.MINUTE:
  2465. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2466. // Note: this is no bug. Major label is equal for both minute and hour scale
  2467. case TimeStep.SCALE.HOUR:
  2468. return (this.current.getHours() == 0);
  2469. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2470. case TimeStep.SCALE.DAY:
  2471. return (this.current.getDate() == 1);
  2472. case TimeStep.SCALE.MONTH:
  2473. return (this.current.getMonth() == 0);
  2474. case TimeStep.SCALE.YEAR:
  2475. return false;
  2476. default:
  2477. return false;
  2478. }
  2479. };
  2480. /**
  2481. * Returns formatted text for the minor axislabel, depending on the current
  2482. * date and the scale. For example when scale is MINUTE, the current time is
  2483. * formatted as "hh:mm".
  2484. * @param {Date} [date] custom date. if not provided, current date is taken
  2485. */
  2486. TimeStep.prototype.getLabelMinor = function(date) {
  2487. if (date == undefined) {
  2488. date = this.current;
  2489. }
  2490. switch (this.scale) {
  2491. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2492. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2493. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2494. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2495. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2496. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2497. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2498. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2499. default: return '';
  2500. }
  2501. };
  2502. /**
  2503. * Returns formatted text for the major axis label, depending on the current
  2504. * date and the scale. For example when scale is MINUTE, the major scale is
  2505. * hours, and the hour will be formatted as "hh".
  2506. * @param {Date} [date] custom date. if not provided, current date is taken
  2507. */
  2508. TimeStep.prototype.getLabelMajor = function(date) {
  2509. if (date == undefined) {
  2510. date = this.current;
  2511. }
  2512. //noinspection FallthroughInSwitchStatementJS
  2513. switch (this.scale) {
  2514. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2515. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2516. case TimeStep.SCALE.MINUTE:
  2517. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2518. case TimeStep.SCALE.WEEKDAY:
  2519. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2520. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2521. case TimeStep.SCALE.YEAR: return '';
  2522. default: return '';
  2523. }
  2524. };
  2525. /**
  2526. * @constructor Stack
  2527. * Stacks items on top of each other.
  2528. * @param {ItemSet} itemset
  2529. * @param {Object} [options]
  2530. */
  2531. function Stack (itemset, options) {
  2532. this.itemset = itemset;
  2533. this.options = options || {};
  2534. this.defaultOptions = {
  2535. order: function (a, b) {
  2536. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  2537. // Order: ranges over non-ranges, ranged ordered by width, and
  2538. // lastly ordered by start.
  2539. if (a instanceof ItemRange) {
  2540. if (b instanceof ItemRange) {
  2541. var aInt = (a.data.end - a.data.start);
  2542. var bInt = (b.data.end - b.data.start);
  2543. return (aInt - bInt) || (a.data.start - b.data.start);
  2544. }
  2545. else {
  2546. return -1;
  2547. }
  2548. }
  2549. else {
  2550. if (b instanceof ItemRange) {
  2551. return 1;
  2552. }
  2553. else {
  2554. return (a.data.start - b.data.start);
  2555. }
  2556. }
  2557. },
  2558. margin: {
  2559. item: 10
  2560. }
  2561. };
  2562. this.ordered = []; // ordered items
  2563. }
  2564. /**
  2565. * Set options for the stack
  2566. * @param {Object} options Available options:
  2567. * {ItemSet} itemset
  2568. * {Number} margin
  2569. * {function} order Stacking order
  2570. */
  2571. Stack.prototype.setOptions = function setOptions (options) {
  2572. util.extend(this.options, options);
  2573. // TODO: register on data changes at the connected itemset, and update the changed part only and immediately
  2574. };
  2575. /**
  2576. * Stack the items such that they don't overlap. The items will have a minimal
  2577. * distance equal to options.margin.item.
  2578. */
  2579. Stack.prototype.update = function update() {
  2580. this._order();
  2581. this._stack();
  2582. };
  2583. /**
  2584. * Order the items. If a custom order function has been provided via the options,
  2585. * then this will be used.
  2586. * @private
  2587. */
  2588. Stack.prototype._order = function _order () {
  2589. var items = this.itemset.items;
  2590. if (!items) {
  2591. throw new Error('Cannot stack items: ItemSet does not contain items');
  2592. }
  2593. // TODO: store the sorted items, to have less work later on
  2594. var ordered = [];
  2595. var index = 0;
  2596. // items is a map (no array)
  2597. util.forEach(items, function (item) {
  2598. if (item.visible) {
  2599. ordered[index] = item;
  2600. index++;
  2601. }
  2602. });
  2603. //if a customer stack order function exists, use it.
  2604. var order = this.options.order || this.defaultOptions.order;
  2605. if (!(typeof order === 'function')) {
  2606. throw new Error('Option order must be a function');
  2607. }
  2608. ordered.sort(order);
  2609. this.ordered = ordered;
  2610. };
  2611. /**
  2612. * Adjust vertical positions of the events such that they don't overlap each
  2613. * other.
  2614. * @private
  2615. */
  2616. Stack.prototype._stack = function _stack () {
  2617. var i,
  2618. iMax,
  2619. ordered = this.ordered,
  2620. options = this.options,
  2621. orientation = options.orientation || this.defaultOptions.orientation,
  2622. axisOnTop = (orientation == 'top'),
  2623. margin;
  2624. if (options.margin && options.margin.item !== undefined) {
  2625. margin = options.margin.item;
  2626. }
  2627. else {
  2628. margin = this.defaultOptions.margin.item
  2629. }
  2630. // calculate new, non-overlapping positions
  2631. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  2632. var item = ordered[i];
  2633. var collidingItem = null;
  2634. do {
  2635. // TODO: optimize checking for overlap. when there is a gap without items,
  2636. // you only need to check for items from the next item on, not from zero
  2637. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  2638. if (collidingItem != null) {
  2639. // There is a collision. Reposition the event above the colliding element
  2640. if (axisOnTop) {
  2641. item.top = collidingItem.top + collidingItem.height + margin;
  2642. }
  2643. else {
  2644. item.top = collidingItem.top - item.height - margin;
  2645. }
  2646. }
  2647. } while (collidingItem);
  2648. }
  2649. };
  2650. /**
  2651. * Check if the destiny position of given item overlaps with any
  2652. * of the other items from index itemStart to itemEnd.
  2653. * @param {Array} items Array with items
  2654. * @param {int} itemIndex Number of the item to be checked for overlap
  2655. * @param {int} itemStart First item to be checked.
  2656. * @param {int} itemEnd Last item to be checked.
  2657. * @return {Object | null} colliding item, or undefined when no collisions
  2658. * @param {Number} margin A minimum required margin.
  2659. * If margin is provided, the two items will be
  2660. * marked colliding when they overlap or
  2661. * when the margin between the two is smaller than
  2662. * the requested margin.
  2663. */
  2664. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  2665. itemStart, itemEnd, margin) {
  2666. var collision = this.collision;
  2667. // we loop from end to start, as we suppose that the chance of a
  2668. // collision is larger for items at the end, so check these first.
  2669. var a = items[itemIndex];
  2670. for (var i = itemEnd; i >= itemStart; i--) {
  2671. var b = items[i];
  2672. if (collision(a, b, margin)) {
  2673. if (i != itemIndex) {
  2674. return b;
  2675. }
  2676. }
  2677. }
  2678. return null;
  2679. };
  2680. /**
  2681. * Test if the two provided items collide
  2682. * The items must have parameters left, width, top, and height.
  2683. * @param {Component} a The first item
  2684. * @param {Component} b The second item
  2685. * @param {Number} margin A minimum required margin.
  2686. * If margin is provided, the two items will be
  2687. * marked colliding when they overlap or
  2688. * when the margin between the two is smaller than
  2689. * the requested margin.
  2690. * @return {boolean} true if a and b collide, else false
  2691. */
  2692. Stack.prototype.collision = function collision (a, b, margin) {
  2693. return ((a.left - margin) < (b.left + b.width) &&
  2694. (a.left + a.width + margin) > b.left &&
  2695. (a.top - margin) < (b.top + b.height) &&
  2696. (a.top + a.height + margin) > b.top);
  2697. };
  2698. /**
  2699. * @constructor Range
  2700. * A Range controls a numeric range with a start and end value.
  2701. * The Range adjusts the range based on mouse events or programmatic changes,
  2702. * and triggers events when the range is changing or has been changed.
  2703. * @param {Object} [options] See description at Range.setOptions
  2704. * @extends Controller
  2705. */
  2706. function Range(options) {
  2707. this.id = util.randomUUID();
  2708. this.start = null; // Number
  2709. this.end = null; // Number
  2710. this.options = options || {};
  2711. this.setOptions(options);
  2712. }
  2713. // extend the Range prototype with an event emitter mixin
  2714. Emitter(Range.prototype);
  2715. /**
  2716. * Set options for the range controller
  2717. * @param {Object} options Available options:
  2718. * {Number} min Minimum value for start
  2719. * {Number} max Maximum value for end
  2720. * {Number} zoomMin Set a minimum value for
  2721. * (end - start).
  2722. * {Number} zoomMax Set a maximum value for
  2723. * (end - start).
  2724. */
  2725. Range.prototype.setOptions = function (options) {
  2726. util.extend(this.options, options);
  2727. // re-apply range with new limitations
  2728. if (this.start !== null && this.end !== null) {
  2729. this.setRange(this.start, this.end);
  2730. }
  2731. };
  2732. /**
  2733. * Test whether direction has a valid value
  2734. * @param {String} direction 'horizontal' or 'vertical'
  2735. */
  2736. function validateDirection (direction) {
  2737. if (direction != 'horizontal' && direction != 'vertical') {
  2738. throw new TypeError('Unknown direction "' + direction + '". ' +
  2739. 'Choose "horizontal" or "vertical".');
  2740. }
  2741. }
  2742. /**
  2743. * Add listeners for mouse and touch events to the component
  2744. * @param {Controller} controller
  2745. * @param {Component} component Should be a rootpanel
  2746. * @param {String} event Available events: 'move', 'zoom'
  2747. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2748. */
  2749. Range.prototype.subscribe = function (controller, component, event, direction) {
  2750. var me = this;
  2751. if (event == 'move') {
  2752. // drag start listener
  2753. controller.on('dragstart', function (event) {
  2754. me._onDragStart(event, component);
  2755. });
  2756. // drag listener
  2757. controller.on('drag', function (event) {
  2758. me._onDrag(event, component, direction);
  2759. });
  2760. // drag end listener
  2761. controller.on('dragend', function (event) {
  2762. me._onDragEnd(event, component);
  2763. });
  2764. // ignore dragging when holding
  2765. controller.on('hold', function (event) {
  2766. me._onHold();
  2767. });
  2768. }
  2769. else if (event == 'zoom') {
  2770. // mouse wheel
  2771. function mousewheel (event) {
  2772. me._onMouseWheel(event, component, direction);
  2773. }
  2774. controller.on('mousewheel', mousewheel);
  2775. controller.on('DOMMouseScroll', mousewheel); // For FF
  2776. // pinch
  2777. controller.on('touch', function (event) {
  2778. me._onTouch(event);
  2779. });
  2780. controller.on('pinch', function (event) {
  2781. me._onPinch(event, component, direction);
  2782. });
  2783. }
  2784. else {
  2785. throw new TypeError('Unknown event "' + event + '". ' +
  2786. 'Choose "move" or "zoom".');
  2787. }
  2788. };
  2789. /**
  2790. * Set a new start and end range
  2791. * @param {Number} [start]
  2792. * @param {Number} [end]
  2793. */
  2794. Range.prototype.setRange = function(start, end) {
  2795. var changed = this._applyRange(start, end);
  2796. if (changed) {
  2797. var params = {
  2798. start: this.start,
  2799. end: this.end
  2800. };
  2801. this.emit('rangechange', params);
  2802. this.emit('rangechanged', params);
  2803. }
  2804. };
  2805. /**
  2806. * Set a new start and end range. This method is the same as setRange, but
  2807. * does not trigger a range change and range changed event, and it returns
  2808. * true when the range is changed
  2809. * @param {Number} [start]
  2810. * @param {Number} [end]
  2811. * @return {Boolean} changed
  2812. * @private
  2813. */
  2814. Range.prototype._applyRange = function(start, end) {
  2815. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2816. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2817. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2818. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2819. diff;
  2820. // check for valid number
  2821. if (isNaN(newStart) || newStart === null) {
  2822. throw new Error('Invalid start "' + start + '"');
  2823. }
  2824. if (isNaN(newEnd) || newEnd === null) {
  2825. throw new Error('Invalid end "' + end + '"');
  2826. }
  2827. // prevent start < end
  2828. if (newEnd < newStart) {
  2829. newEnd = newStart;
  2830. }
  2831. // prevent start < min
  2832. if (min !== null) {
  2833. if (newStart < min) {
  2834. diff = (min - newStart);
  2835. newStart += diff;
  2836. newEnd += diff;
  2837. // prevent end > max
  2838. if (max != null) {
  2839. if (newEnd > max) {
  2840. newEnd = max;
  2841. }
  2842. }
  2843. }
  2844. }
  2845. // prevent end > max
  2846. if (max !== null) {
  2847. if (newEnd > max) {
  2848. diff = (newEnd - max);
  2849. newStart -= diff;
  2850. newEnd -= diff;
  2851. // prevent start < min
  2852. if (min != null) {
  2853. if (newStart < min) {
  2854. newStart = min;
  2855. }
  2856. }
  2857. }
  2858. }
  2859. // prevent (end-start) < zoomMin
  2860. if (this.options.zoomMin !== null) {
  2861. var zoomMin = parseFloat(this.options.zoomMin);
  2862. if (zoomMin < 0) {
  2863. zoomMin = 0;
  2864. }
  2865. if ((newEnd - newStart) < zoomMin) {
  2866. if ((this.end - this.start) === zoomMin) {
  2867. // ignore this action, we are already zoomed to the minimum
  2868. newStart = this.start;
  2869. newEnd = this.end;
  2870. }
  2871. else {
  2872. // zoom to the minimum
  2873. diff = (zoomMin - (newEnd - newStart));
  2874. newStart -= diff / 2;
  2875. newEnd += diff / 2;
  2876. }
  2877. }
  2878. }
  2879. // prevent (end-start) > zoomMax
  2880. if (this.options.zoomMax !== null) {
  2881. var zoomMax = parseFloat(this.options.zoomMax);
  2882. if (zoomMax < 0) {
  2883. zoomMax = 0;
  2884. }
  2885. if ((newEnd - newStart) > zoomMax) {
  2886. if ((this.end - this.start) === zoomMax) {
  2887. // ignore this action, we are already zoomed to the maximum
  2888. newStart = this.start;
  2889. newEnd = this.end;
  2890. }
  2891. else {
  2892. // zoom to the maximum
  2893. diff = ((newEnd - newStart) - zoomMax);
  2894. newStart += diff / 2;
  2895. newEnd -= diff / 2;
  2896. }
  2897. }
  2898. }
  2899. var changed = (this.start != newStart || this.end != newEnd);
  2900. this.start = newStart;
  2901. this.end = newEnd;
  2902. return changed;
  2903. };
  2904. /**
  2905. * Retrieve the current range.
  2906. * @return {Object} An object with start and end properties
  2907. */
  2908. Range.prototype.getRange = function() {
  2909. return {
  2910. start: this.start,
  2911. end: this.end
  2912. };
  2913. };
  2914. /**
  2915. * Calculate the conversion offset and scale for current range, based on
  2916. * the provided width
  2917. * @param {Number} width
  2918. * @returns {{offset: number, scale: number}} conversion
  2919. */
  2920. Range.prototype.conversion = function (width) {
  2921. return Range.conversion(this.start, this.end, width);
  2922. };
  2923. /**
  2924. * Static method to calculate the conversion offset and scale for a range,
  2925. * based on the provided start, end, and width
  2926. * @param {Number} start
  2927. * @param {Number} end
  2928. * @param {Number} width
  2929. * @returns {{offset: number, scale: number}} conversion
  2930. */
  2931. Range.conversion = function (start, end, width) {
  2932. if (width != 0 && (end - start != 0)) {
  2933. return {
  2934. offset: start,
  2935. scale: width / (end - start)
  2936. }
  2937. }
  2938. else {
  2939. return {
  2940. offset: 0,
  2941. scale: 1
  2942. };
  2943. }
  2944. };
  2945. // global (private) object to store drag params
  2946. var touchParams = {};
  2947. /**
  2948. * Start dragging horizontally or vertically
  2949. * @param {Event} event
  2950. * @param {Object} component
  2951. * @private
  2952. */
  2953. Range.prototype._onDragStart = function(event, component) {
  2954. // refuse to drag when we where pinching to prevent the timeline make a jump
  2955. // when releasing the fingers in opposite order from the touch screen
  2956. if (touchParams.ignore) return;
  2957. // TODO: reckon with option movable
  2958. touchParams.start = this.start;
  2959. touchParams.end = this.end;
  2960. var frame = component.frame;
  2961. if (frame) {
  2962. frame.style.cursor = 'move';
  2963. }
  2964. };
  2965. /**
  2966. * Perform dragging operating.
  2967. * @param {Event} event
  2968. * @param {Component} component
  2969. * @param {String} direction 'horizontal' or 'vertical'
  2970. * @private
  2971. */
  2972. Range.prototype._onDrag = function (event, component, direction) {
  2973. validateDirection(direction);
  2974. // TODO: reckon with option movable
  2975. // refuse to drag when we where pinching to prevent the timeline make a jump
  2976. // when releasing the fingers in opposite order from the touch screen
  2977. if (touchParams.ignore) return;
  2978. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  2979. interval = (touchParams.end - touchParams.start),
  2980. width = (direction == 'horizontal') ? component.width : component.height,
  2981. diffRange = -delta / width * interval;
  2982. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  2983. this.emit('rangechange', {
  2984. start: this.start,
  2985. end: this.end
  2986. });
  2987. };
  2988. /**
  2989. * Stop dragging operating.
  2990. * @param {event} event
  2991. * @param {Component} component
  2992. * @private
  2993. */
  2994. Range.prototype._onDragEnd = function (event, component) {
  2995. // refuse to drag when we where pinching to prevent the timeline make a jump
  2996. // when releasing the fingers in opposite order from the touch screen
  2997. if (touchParams.ignore) return;
  2998. // TODO: reckon with option movable
  2999. if (component.frame) {
  3000. component.frame.style.cursor = 'auto';
  3001. }
  3002. // fire a rangechanged event
  3003. this.emit('rangechanged', {
  3004. start: this.start,
  3005. end: this.end
  3006. });
  3007. };
  3008. /**
  3009. * Event handler for mouse wheel event, used to zoom
  3010. * Code from http://adomas.org/javascript-mouse-wheel/
  3011. * @param {Event} event
  3012. * @param {Component} component
  3013. * @param {String} direction 'horizontal' or 'vertical'
  3014. * @private
  3015. */
  3016. Range.prototype._onMouseWheel = function(event, component, direction) {
  3017. validateDirection(direction);
  3018. // TODO: reckon with option zoomable
  3019. // retrieve delta
  3020. var delta = 0;
  3021. if (event.wheelDelta) { /* IE/Opera. */
  3022. delta = event.wheelDelta / 120;
  3023. } else if (event.detail) { /* Mozilla case. */
  3024. // In Mozilla, sign of delta is different than in IE.
  3025. // Also, delta is multiple of 3.
  3026. delta = -event.detail / 3;
  3027. }
  3028. // If delta is nonzero, handle it.
  3029. // Basically, delta is now positive if wheel was scrolled up,
  3030. // and negative, if wheel was scrolled down.
  3031. if (delta) {
  3032. // perform the zoom action. Delta is normally 1 or -1
  3033. // adjust a negative delta such that zooming in with delta 0.1
  3034. // equals zooming out with a delta -0.1
  3035. var scale;
  3036. if (delta < 0) {
  3037. scale = 1 - (delta / 5);
  3038. }
  3039. else {
  3040. scale = 1 / (1 + (delta / 5)) ;
  3041. }
  3042. // calculate center, the date to zoom around
  3043. var gesture = util.fakeGesture(this, event),
  3044. pointer = getPointer(gesture.center, component.frame),
  3045. pointerDate = this._pointerToDate(component, direction, pointer);
  3046. this.zoom(scale, pointerDate);
  3047. }
  3048. // Prevent default actions caused by mouse wheel
  3049. // (else the page and timeline both zoom and scroll)
  3050. event.preventDefault();
  3051. };
  3052. /**
  3053. * Start of a touch gesture
  3054. * @private
  3055. */
  3056. Range.prototype._onTouch = function (event) {
  3057. touchParams.start = this.start;
  3058. touchParams.end = this.end;
  3059. touchParams.ignore = false;
  3060. touchParams.center = null;
  3061. // don't move the range when dragging a selected event
  3062. // TODO: it's not so neat to have to know about the state of the ItemSet
  3063. var item = ItemSet.itemFromTarget(event);
  3064. if (item && item.selected && this.options.editable) {
  3065. touchParams.ignore = true;
  3066. }
  3067. };
  3068. /**
  3069. * On start of a hold gesture
  3070. * @private
  3071. */
  3072. Range.prototype._onHold = function () {
  3073. touchParams.ignore = true;
  3074. };
  3075. /**
  3076. * Handle pinch event
  3077. * @param {Event} event
  3078. * @param {Component} component
  3079. * @param {String} direction 'horizontal' or 'vertical'
  3080. * @private
  3081. */
  3082. Range.prototype._onPinch = function (event, component, direction) {
  3083. touchParams.ignore = true;
  3084. // TODO: reckon with option zoomable
  3085. if (event.gesture.touches.length > 1) {
  3086. if (!touchParams.center) {
  3087. touchParams.center = getPointer(event.gesture.center, component.frame);
  3088. }
  3089. var scale = 1 / event.gesture.scale,
  3090. initDate = this._pointerToDate(component, direction, touchParams.center),
  3091. center = getPointer(event.gesture.center, component.frame),
  3092. date = this._pointerToDate(component, direction, center),
  3093. delta = date - initDate; // TODO: utilize delta
  3094. // calculate new start and end
  3095. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3096. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3097. // apply new range
  3098. this.setRange(newStart, newEnd);
  3099. }
  3100. };
  3101. /**
  3102. * Helper function to calculate the center date for zooming
  3103. * @param {Component} component
  3104. * @param {{x: Number, y: Number}} pointer
  3105. * @param {String} direction 'horizontal' or 'vertical'
  3106. * @return {number} date
  3107. * @private
  3108. */
  3109. Range.prototype._pointerToDate = function (component, direction, pointer) {
  3110. var conversion;
  3111. if (direction == 'horizontal') {
  3112. var width = component.width;
  3113. conversion = this.conversion(width);
  3114. return pointer.x / conversion.scale + conversion.offset;
  3115. }
  3116. else {
  3117. var height = component.height;
  3118. conversion = this.conversion(height);
  3119. return pointer.y / conversion.scale + conversion.offset;
  3120. }
  3121. };
  3122. /**
  3123. * Get the pointer location relative to the location of the dom element
  3124. * @param {{pageX: Number, pageY: Number}} touch
  3125. * @param {Element} element HTML DOM element
  3126. * @return {{x: Number, y: Number}} pointer
  3127. * @private
  3128. */
  3129. function getPointer (touch, element) {
  3130. return {
  3131. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3132. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3133. };
  3134. }
  3135. /**
  3136. * Zoom the range the given scale in or out. Start and end date will
  3137. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3138. * date around which to zoom.
  3139. * For example, try scale = 0.9 or 1.1
  3140. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3141. * values below 1 will zoom in.
  3142. * @param {Number} [center] Value representing a date around which will
  3143. * be zoomed.
  3144. */
  3145. Range.prototype.zoom = function(scale, center) {
  3146. // if centerDate is not provided, take it half between start Date and end Date
  3147. if (center == null) {
  3148. center = (this.start + this.end) / 2;
  3149. }
  3150. // calculate new start and end
  3151. var newStart = center + (this.start - center) * scale;
  3152. var newEnd = center + (this.end - center) * scale;
  3153. this.setRange(newStart, newEnd);
  3154. };
  3155. /**
  3156. * Move the range with a given delta to the left or right. Start and end
  3157. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3158. * @param {Number} delta Moving amount. Positive value will move right,
  3159. * negative value will move left
  3160. */
  3161. Range.prototype.move = function(delta) {
  3162. // zoom start Date and end Date relative to the centerDate
  3163. var diff = (this.end - this.start);
  3164. // apply new values
  3165. var newStart = this.start + diff * delta;
  3166. var newEnd = this.end + diff * delta;
  3167. // TODO: reckon with min and max range
  3168. this.start = newStart;
  3169. this.end = newEnd;
  3170. };
  3171. /**
  3172. * Move the range to a new center point
  3173. * @param {Number} moveTo New center point of the range
  3174. */
  3175. Range.prototype.moveTo = function(moveTo) {
  3176. var center = (this.start + this.end) / 2;
  3177. var diff = center - moveTo;
  3178. // calculate new start and end
  3179. var newStart = this.start - diff;
  3180. var newEnd = this.end - diff;
  3181. this.setRange(newStart, newEnd);
  3182. };
  3183. /**
  3184. * @constructor Controller
  3185. *
  3186. * A Controller controls the reflows and repaints of all components,
  3187. * and is used as an event bus for all components.
  3188. */
  3189. function Controller () {
  3190. var me = this;
  3191. this.id = util.randomUUID();
  3192. this.components = {};
  3193. /**
  3194. * Listen for a 'request-reflow' event. The controller will schedule a reflow
  3195. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3196. * is false.
  3197. */
  3198. var reflowTimer = null;
  3199. this.on('request-reflow', function requestReflow(force) {
  3200. if (force) {
  3201. me.reflow();
  3202. }
  3203. else {
  3204. if (!reflowTimer) {
  3205. reflowTimer = setTimeout(function () {
  3206. reflowTimer = null;
  3207. me.reflow();
  3208. }, 0);
  3209. }
  3210. }
  3211. });
  3212. /**
  3213. * Request a repaint. The controller will schedule a repaint
  3214. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3215. * is false.
  3216. */
  3217. var repaintTimer = null;
  3218. this.on('request-repaint', function requestRepaint(force) {
  3219. if (force) {
  3220. me.repaint();
  3221. }
  3222. else {
  3223. if (!repaintTimer) {
  3224. repaintTimer = setTimeout(function () {
  3225. repaintTimer = null;
  3226. me.repaint();
  3227. }, 0);
  3228. }
  3229. }
  3230. });
  3231. }
  3232. // Extend controller with Emitter mixin
  3233. Emitter(Controller.prototype);
  3234. /**
  3235. * Add a component to the controller
  3236. * @param {Component} component
  3237. */
  3238. Controller.prototype.add = function add(component) {
  3239. // validate the component
  3240. if (component.id == undefined) {
  3241. throw new Error('Component has no field id');
  3242. }
  3243. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3244. throw new TypeError('Component must be an instance of ' +
  3245. 'prototype Component or Controller');
  3246. }
  3247. // add the component
  3248. component.setController(this);
  3249. this.components[component.id] = component;
  3250. };
  3251. /**
  3252. * Remove a component from the controller
  3253. * @param {Component | String} component
  3254. */
  3255. Controller.prototype.remove = function remove(component) {
  3256. var id;
  3257. for (id in this.components) {
  3258. if (this.components.hasOwnProperty(id)) {
  3259. if (id == component || this.components[id] === component) {
  3260. break;
  3261. }
  3262. }
  3263. }
  3264. if (id) {
  3265. // unregister the controller (gives the component the ability to unregister
  3266. // event listeners and clean up other stuff)
  3267. this.components[id].setController(null);
  3268. delete this.components[id];
  3269. }
  3270. };
  3271. /**
  3272. * Repaint all components
  3273. */
  3274. Controller.prototype.repaint = function repaint() {
  3275. var changed = false;
  3276. // cancel any running repaint request
  3277. if (this.repaintTimer) {
  3278. clearTimeout(this.repaintTimer);
  3279. this.repaintTimer = undefined;
  3280. }
  3281. var done = {};
  3282. function repaint(component, id) {
  3283. if (!(id in done)) {
  3284. // first repaint the components on which this component is dependent
  3285. if (component.depends) {
  3286. component.depends.forEach(function (dep) {
  3287. repaint(dep, dep.id);
  3288. });
  3289. }
  3290. if (component.parent) {
  3291. repaint(component.parent, component.parent.id);
  3292. }
  3293. // repaint the component itself and mark as done
  3294. changed = component.repaint() || changed;
  3295. done[id] = true;
  3296. }
  3297. }
  3298. util.forEach(this.components, repaint);
  3299. this.emit('repaint');
  3300. // immediately reflow when needed
  3301. if (changed) {
  3302. this.reflow();
  3303. }
  3304. // TODO: limit the number of nested reflows/repaints, prevent loop
  3305. };
  3306. /**
  3307. * Reflow all components
  3308. */
  3309. Controller.prototype.reflow = function reflow() {
  3310. var resized = false;
  3311. // cancel any running repaint request
  3312. if (this.reflowTimer) {
  3313. clearTimeout(this.reflowTimer);
  3314. this.reflowTimer = undefined;
  3315. }
  3316. var done = {};
  3317. function reflow(component, id) {
  3318. if (!(id in done)) {
  3319. // first reflow the components on which this component is dependent
  3320. if (component.depends) {
  3321. component.depends.forEach(function (dep) {
  3322. reflow(dep, dep.id);
  3323. });
  3324. }
  3325. if (component.parent) {
  3326. reflow(component.parent, component.parent.id);
  3327. }
  3328. // reflow the component itself and mark as done
  3329. resized = component.reflow() || resized;
  3330. done[id] = true;
  3331. }
  3332. }
  3333. util.forEach(this.components, reflow);
  3334. this.emit('reflow');
  3335. // immediately repaint when needed
  3336. if (resized) {
  3337. this.repaint();
  3338. }
  3339. // TODO: limit the number of nested reflows/repaints, prevent loop
  3340. };
  3341. /**
  3342. * Prototype for visual components
  3343. */
  3344. function Component () {
  3345. this.id = null;
  3346. this.parent = null;
  3347. this.depends = null;
  3348. this.controller = null;
  3349. this.options = null;
  3350. this.frame = null; // main DOM element
  3351. this.top = 0;
  3352. this.left = 0;
  3353. this.width = 0;
  3354. this.height = 0;
  3355. }
  3356. /**
  3357. * Set parameters for the frame. Parameters will be merged in current parameter
  3358. * set.
  3359. * @param {Object} options Available parameters:
  3360. * {String | function} [className]
  3361. * {String | Number | function} [left]
  3362. * {String | Number | function} [top]
  3363. * {String | Number | function} [width]
  3364. * {String | Number | function} [height]
  3365. */
  3366. Component.prototype.setOptions = function setOptions(options) {
  3367. if (options) {
  3368. util.extend(this.options, options);
  3369. if (this.controller) {
  3370. this.requestRepaint();
  3371. this.requestReflow();
  3372. }
  3373. }
  3374. };
  3375. /**
  3376. * Get an option value by name
  3377. * The function will first check this.options object, and else will check
  3378. * this.defaultOptions.
  3379. * @param {String} name
  3380. * @return {*} value
  3381. */
  3382. Component.prototype.getOption = function getOption(name) {
  3383. var value;
  3384. if (this.options) {
  3385. value = this.options[name];
  3386. }
  3387. if (value === undefined && this.defaultOptions) {
  3388. value = this.defaultOptions[name];
  3389. }
  3390. return value;
  3391. };
  3392. /**
  3393. * Set controller for this component, or remove current controller by passing
  3394. * null as parameter value.
  3395. * @param {Controller | null} controller
  3396. */
  3397. Component.prototype.setController = function setController (controller) {
  3398. this.controller = controller || null;
  3399. };
  3400. /**
  3401. * Get controller of this component
  3402. * @return {Controller} controller
  3403. */
  3404. Component.prototype.getController = function getController () {
  3405. return this.controller;
  3406. };
  3407. /**
  3408. * Get the container element of the component, which can be used by a child to
  3409. * add its own widgets. Not all components do have a container for childs, in
  3410. * that case null is returned.
  3411. * @returns {HTMLElement | null} container
  3412. */
  3413. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3414. Component.prototype.getContainer = function getContainer() {
  3415. // should be implemented by the component
  3416. return null;
  3417. };
  3418. /**
  3419. * Get the frame element of the component, the outer HTML DOM element.
  3420. * @returns {HTMLElement | null} frame
  3421. */
  3422. Component.prototype.getFrame = function getFrame() {
  3423. return this.frame;
  3424. };
  3425. /**
  3426. * Repaint the component
  3427. * @return {Boolean} changed
  3428. */
  3429. Component.prototype.repaint = function repaint() {
  3430. // should be implemented by the component
  3431. return false;
  3432. };
  3433. /**
  3434. * Reflow the component
  3435. * @return {Boolean} resized
  3436. */
  3437. Component.prototype.reflow = function reflow() {
  3438. // should be implemented by the component
  3439. return false;
  3440. };
  3441. /**
  3442. * Hide the component from the DOM
  3443. * @return {Boolean} changed
  3444. */
  3445. Component.prototype.hide = function hide() {
  3446. if (this.frame && this.frame.parentNode) {
  3447. this.frame.parentNode.removeChild(this.frame);
  3448. return true;
  3449. }
  3450. else {
  3451. return false;
  3452. }
  3453. };
  3454. /**
  3455. * Show the component in the DOM (when not already visible).
  3456. * A repaint will be executed when the component is not visible
  3457. * @return {Boolean} changed
  3458. */
  3459. Component.prototype.show = function show() {
  3460. if (!this.frame || !this.frame.parentNode) {
  3461. return this.repaint();
  3462. }
  3463. else {
  3464. return false;
  3465. }
  3466. };
  3467. /**
  3468. * Request a repaint. The controller will schedule a repaint
  3469. */
  3470. Component.prototype.requestRepaint = function requestRepaint() {
  3471. if (this.controller) {
  3472. this.controller.emit('request-repaint');
  3473. }
  3474. else {
  3475. throw new Error('Cannot request a repaint: no controller configured');
  3476. // TODO: just do a repaint when no parent is configured?
  3477. }
  3478. };
  3479. /**
  3480. * Request a reflow. The controller will schedule a reflow
  3481. */
  3482. Component.prototype.requestReflow = function requestReflow() {
  3483. if (this.controller) {
  3484. this.controller.emit('request-reflow');
  3485. }
  3486. else {
  3487. throw new Error('Cannot request a reflow: no controller configured');
  3488. // TODO: just do a reflow when no parent is configured?
  3489. }
  3490. };
  3491. /**
  3492. * A panel can contain components
  3493. * @param {Component} [parent]
  3494. * @param {Component[]} [depends] Components on which this components depends
  3495. * (except for the parent)
  3496. * @param {Object} [options] Available parameters:
  3497. * {String | Number | function} [left]
  3498. * {String | Number | function} [top]
  3499. * {String | Number | function} [width]
  3500. * {String | Number | function} [height]
  3501. * {String | function} [className]
  3502. * @constructor Panel
  3503. * @extends Component
  3504. */
  3505. function Panel(parent, depends, options) {
  3506. this.id = util.randomUUID();
  3507. this.parent = parent;
  3508. this.depends = depends;
  3509. this.options = options || {};
  3510. }
  3511. Panel.prototype = new Component();
  3512. /**
  3513. * Set options. Will extend the current options.
  3514. * @param {Object} [options] Available parameters:
  3515. * {String | function} [className]
  3516. * {String | Number | function} [left]
  3517. * {String | Number | function} [top]
  3518. * {String | Number | function} [width]
  3519. * {String | Number | function} [height]
  3520. */
  3521. Panel.prototype.setOptions = Component.prototype.setOptions;
  3522. /**
  3523. * Get the container element of the panel, which can be used by a child to
  3524. * add its own widgets.
  3525. * @returns {HTMLElement} container
  3526. */
  3527. Panel.prototype.getContainer = function () {
  3528. return this.frame;
  3529. };
  3530. /**
  3531. * Repaint the component
  3532. * @return {Boolean} changed
  3533. */
  3534. Panel.prototype.repaint = function () {
  3535. var changed = 0,
  3536. update = util.updateProperty,
  3537. asSize = util.option.asSize,
  3538. options = this.options,
  3539. frame = this.frame;
  3540. if (!frame) {
  3541. frame = document.createElement('div');
  3542. frame.className = 'vpanel';
  3543. var className = options.className;
  3544. if (className) {
  3545. if (typeof className == 'function') {
  3546. util.addClassName(frame, String(className()));
  3547. }
  3548. else {
  3549. util.addClassName(frame, String(className));
  3550. }
  3551. }
  3552. this.frame = frame;
  3553. changed += 1;
  3554. }
  3555. if (!frame.parentNode) {
  3556. if (!this.parent) {
  3557. throw new Error('Cannot repaint panel: no parent attached');
  3558. }
  3559. var parentContainer = this.parent.getContainer();
  3560. if (!parentContainer) {
  3561. throw new Error('Cannot repaint panel: parent has no container element');
  3562. }
  3563. parentContainer.appendChild(frame);
  3564. changed += 1;
  3565. }
  3566. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3567. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3568. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3569. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3570. return (changed > 0);
  3571. };
  3572. /**
  3573. * Reflow the component
  3574. * @return {Boolean} resized
  3575. */
  3576. Panel.prototype.reflow = function () {
  3577. var changed = 0,
  3578. update = util.updateProperty,
  3579. frame = this.frame;
  3580. if (frame) {
  3581. changed += update(this, 'top', frame.offsetTop);
  3582. changed += update(this, 'left', frame.offsetLeft);
  3583. changed += update(this, 'width', frame.offsetWidth);
  3584. changed += update(this, 'height', frame.offsetHeight);
  3585. }
  3586. else {
  3587. changed += 1;
  3588. }
  3589. return (changed > 0);
  3590. };
  3591. /**
  3592. * A root panel can hold components. The root panel must be initialized with
  3593. * a DOM element as container.
  3594. * @param {HTMLElement} container
  3595. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3596. * @constructor RootPanel
  3597. * @extends Panel
  3598. */
  3599. function RootPanel(container, options) {
  3600. this.id = util.randomUUID();
  3601. this.container = container;
  3602. // create functions to be used as DOM event listeners
  3603. var me = this;
  3604. this.hammer = null;
  3605. // create listeners for all interesting events, these events will be emitted
  3606. // via the controller
  3607. var events = [
  3608. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3609. 'dragstart', 'drag', 'dragend',
  3610. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3611. ];
  3612. this.listeners = {};
  3613. events.forEach(function (event) {
  3614. me.listeners[event] = function () {
  3615. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3616. me.controller.emit.apply(me.controller, args);
  3617. };
  3618. });
  3619. this.options = options || {};
  3620. this.defaultOptions = {
  3621. autoResize: true
  3622. };
  3623. }
  3624. RootPanel.prototype = new Panel();
  3625. /**
  3626. * Set options. Will extend the current options.
  3627. * @param {Object} [options] Available parameters:
  3628. * {String | function} [className]
  3629. * {String | Number | function} [left]
  3630. * {String | Number | function} [top]
  3631. * {String | Number | function} [width]
  3632. * {String | Number | function} [height]
  3633. * {Boolean | function} [autoResize]
  3634. */
  3635. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3636. /**
  3637. * Repaint the component
  3638. * @return {Boolean} changed
  3639. */
  3640. RootPanel.prototype.repaint = function () {
  3641. var changed = 0,
  3642. update = util.updateProperty,
  3643. asSize = util.option.asSize,
  3644. options = this.options,
  3645. frame = this.frame;
  3646. if (!frame) {
  3647. frame = document.createElement('div');
  3648. this.frame = frame;
  3649. this._registerListeners();
  3650. changed += 1;
  3651. }
  3652. if (!frame.parentNode) {
  3653. if (!this.container) {
  3654. throw new Error('Cannot repaint root panel: no container attached');
  3655. }
  3656. this.container.appendChild(frame);
  3657. changed += 1;
  3658. }
  3659. frame.className = 'vis timeline rootpanel ' + options.orientation +
  3660. (options.editable ? ' editable' : '');
  3661. var className = options.className;
  3662. if (className) {
  3663. util.addClassName(frame, util.option.asString(className));
  3664. }
  3665. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3666. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3667. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3668. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3669. this._updateWatch();
  3670. return (changed > 0);
  3671. };
  3672. /**
  3673. * Reflow the component
  3674. * @return {Boolean} resized
  3675. */
  3676. RootPanel.prototype.reflow = function () {
  3677. var changed = 0,
  3678. update = util.updateProperty,
  3679. frame = this.frame;
  3680. if (frame) {
  3681. changed += update(this, 'top', frame.offsetTop);
  3682. changed += update(this, 'left', frame.offsetLeft);
  3683. changed += update(this, 'width', frame.offsetWidth);
  3684. changed += update(this, 'height', frame.offsetHeight);
  3685. }
  3686. else {
  3687. changed += 1;
  3688. }
  3689. return (changed > 0);
  3690. };
  3691. /**
  3692. * Update watching for resize, depending on the current option
  3693. * @private
  3694. */
  3695. RootPanel.prototype._updateWatch = function () {
  3696. var autoResize = this.getOption('autoResize');
  3697. if (autoResize) {
  3698. this._watch();
  3699. }
  3700. else {
  3701. this._unwatch();
  3702. }
  3703. };
  3704. /**
  3705. * Watch for changes in the size of the frame. On resize, the Panel will
  3706. * automatically redraw itself.
  3707. * @private
  3708. */
  3709. RootPanel.prototype._watch = function () {
  3710. var me = this;
  3711. this._unwatch();
  3712. var checkSize = function () {
  3713. var autoResize = me.getOption('autoResize');
  3714. if (!autoResize) {
  3715. // stop watching when the option autoResize is changed to false
  3716. me._unwatch();
  3717. return;
  3718. }
  3719. if (me.frame) {
  3720. // check whether the frame is resized
  3721. if ((me.frame.clientWidth != me.width) ||
  3722. (me.frame.clientHeight != me.height)) {
  3723. me.requestReflow();
  3724. }
  3725. }
  3726. };
  3727. // TODO: automatically cleanup the event listener when the frame is deleted
  3728. util.addEventListener(window, 'resize', checkSize);
  3729. this.watchTimer = setInterval(checkSize, 1000);
  3730. };
  3731. /**
  3732. * Stop watching for a resize of the frame.
  3733. * @private
  3734. */
  3735. RootPanel.prototype._unwatch = function () {
  3736. if (this.watchTimer) {
  3737. clearInterval(this.watchTimer);
  3738. this.watchTimer = undefined;
  3739. }
  3740. // TODO: remove event listener on window.resize
  3741. };
  3742. /**
  3743. * Set controller for this component, or remove current controller by passing
  3744. * null as parameter value.
  3745. * @param {Controller | null} controller
  3746. */
  3747. RootPanel.prototype.setController = function setController (controller) {
  3748. this.controller = controller || null;
  3749. if (this.controller) {
  3750. this._registerListeners();
  3751. }
  3752. else {
  3753. this._unregisterListeners();
  3754. }
  3755. };
  3756. /**
  3757. * Register event emitters emitted by the rootpanel
  3758. * @private
  3759. */
  3760. RootPanel.prototype._registerListeners = function () {
  3761. if (this.frame && this.controller && !this.hammer) {
  3762. this.hammer = Hammer(this.frame, {
  3763. prevent_default: true
  3764. });
  3765. for (var event in this.listeners) {
  3766. if (this.listeners.hasOwnProperty(event)) {
  3767. this.hammer.on(event, this.listeners[event]);
  3768. }
  3769. }
  3770. }
  3771. };
  3772. /**
  3773. * Unregister event emitters from the rootpanel
  3774. * @private
  3775. */
  3776. RootPanel.prototype._unregisterListeners = function () {
  3777. if (this.hammer) {
  3778. for (var event in this.listeners) {
  3779. if (this.listeners.hasOwnProperty(event)) {
  3780. this.hammer.off(event, this.listeners[event]);
  3781. }
  3782. }
  3783. this.hammer = null;
  3784. }
  3785. };
  3786. /**
  3787. * A horizontal time axis
  3788. * @param {Component} parent
  3789. * @param {Component[]} [depends] Components on which this components depends
  3790. * (except for the parent)
  3791. * @param {Object} [options] See TimeAxis.setOptions for the available
  3792. * options.
  3793. * @constructor TimeAxis
  3794. * @extends Component
  3795. */
  3796. function TimeAxis (parent, depends, options) {
  3797. this.id = util.randomUUID();
  3798. this.parent = parent;
  3799. this.depends = depends;
  3800. this.dom = {
  3801. majorLines: [],
  3802. majorTexts: [],
  3803. minorLines: [],
  3804. minorTexts: [],
  3805. redundant: {
  3806. majorLines: [],
  3807. majorTexts: [],
  3808. minorLines: [],
  3809. minorTexts: []
  3810. }
  3811. };
  3812. this.props = {
  3813. range: {
  3814. start: 0,
  3815. end: 0,
  3816. minimumStep: 0
  3817. },
  3818. lineTop: 0
  3819. };
  3820. this.options = options || {};
  3821. this.defaultOptions = {
  3822. orientation: 'bottom', // supported: 'top', 'bottom'
  3823. // TODO: implement timeaxis orientations 'left' and 'right'
  3824. showMinorLabels: true,
  3825. showMajorLabels: true
  3826. };
  3827. this.conversion = null;
  3828. this.range = null;
  3829. }
  3830. TimeAxis.prototype = new Component();
  3831. // TODO: comment options
  3832. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3833. /**
  3834. * Set a range (start and end)
  3835. * @param {Range | Object} range A Range or an object containing start and end.
  3836. */
  3837. TimeAxis.prototype.setRange = function (range) {
  3838. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3839. throw new TypeError('Range must be an instance of Range, ' +
  3840. 'or an object containing start and end.');
  3841. }
  3842. this.range = range;
  3843. };
  3844. /**
  3845. * Convert a position on screen (pixels) to a datetime
  3846. * @param {int} x Position on the screen in pixels
  3847. * @return {Date} time The datetime the corresponds with given position x
  3848. */
  3849. TimeAxis.prototype.toTime = function(x) {
  3850. var conversion = this.conversion;
  3851. return new Date(x / conversion.scale + conversion.offset);
  3852. };
  3853. /**
  3854. * Convert a datetime (Date object) into a position on the screen
  3855. * @param {Date} time A date
  3856. * @return {int} x The position on the screen in pixels which corresponds
  3857. * with the given date.
  3858. * @private
  3859. */
  3860. TimeAxis.prototype.toScreen = function(time) {
  3861. var conversion = this.conversion;
  3862. return (time.valueOf() - conversion.offset) * conversion.scale;
  3863. };
  3864. /**
  3865. * Repaint the component
  3866. * @return {Boolean} changed
  3867. */
  3868. TimeAxis.prototype.repaint = function () {
  3869. var changed = 0,
  3870. update = util.updateProperty,
  3871. asSize = util.option.asSize,
  3872. options = this.options,
  3873. orientation = this.getOption('orientation'),
  3874. props = this.props,
  3875. step = this.step;
  3876. var frame = this.frame;
  3877. if (!frame) {
  3878. frame = document.createElement('div');
  3879. this.frame = frame;
  3880. changed += 1;
  3881. }
  3882. frame.className = 'axis';
  3883. // TODO: custom className?
  3884. if (!frame.parentNode) {
  3885. if (!this.parent) {
  3886. throw new Error('Cannot repaint time axis: no parent attached');
  3887. }
  3888. var parentContainer = this.parent.getContainer();
  3889. if (!parentContainer) {
  3890. throw new Error('Cannot repaint time axis: parent has no container element');
  3891. }
  3892. parentContainer.appendChild(frame);
  3893. changed += 1;
  3894. }
  3895. var parent = frame.parentNode;
  3896. if (parent) {
  3897. var beforeChild = frame.nextSibling;
  3898. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3899. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3900. (this.props.parentHeight - this.height) + 'px' :
  3901. '0px';
  3902. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3903. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3904. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3905. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3906. // get characters width and height
  3907. this._repaintMeasureChars();
  3908. if (this.step) {
  3909. this._repaintStart();
  3910. step.first();
  3911. var xFirstMajorLabel = undefined;
  3912. var max = 0;
  3913. while (step.hasNext() && max < 1000) {
  3914. max++;
  3915. var cur = step.getCurrent(),
  3916. x = this.toScreen(cur),
  3917. isMajor = step.isMajor();
  3918. // TODO: lines must have a width, such that we can create css backgrounds
  3919. if (this.getOption('showMinorLabels')) {
  3920. this._repaintMinorText(x, step.getLabelMinor());
  3921. }
  3922. if (isMajor && this.getOption('showMajorLabels')) {
  3923. if (x > 0) {
  3924. if (xFirstMajorLabel == undefined) {
  3925. xFirstMajorLabel = x;
  3926. }
  3927. this._repaintMajorText(x, step.getLabelMajor());
  3928. }
  3929. this._repaintMajorLine(x);
  3930. }
  3931. else {
  3932. this._repaintMinorLine(x);
  3933. }
  3934. step.next();
  3935. }
  3936. // create a major label on the left when needed
  3937. if (this.getOption('showMajorLabels')) {
  3938. var leftTime = this.toTime(0),
  3939. leftText = step.getLabelMajor(leftTime),
  3940. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3941. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3942. this._repaintMajorText(0, leftText);
  3943. }
  3944. }
  3945. this._repaintEnd();
  3946. }
  3947. this._repaintLine();
  3948. // put frame online again
  3949. if (beforeChild) {
  3950. parent.insertBefore(frame, beforeChild);
  3951. }
  3952. else {
  3953. parent.appendChild(frame)
  3954. }
  3955. }
  3956. return (changed > 0);
  3957. };
  3958. /**
  3959. * Start a repaint. Move all DOM elements to a redundant list, where they
  3960. * can be picked for re-use, or can be cleaned up in the end
  3961. * @private
  3962. */
  3963. TimeAxis.prototype._repaintStart = function () {
  3964. var dom = this.dom,
  3965. redundant = dom.redundant;
  3966. redundant.majorLines = dom.majorLines;
  3967. redundant.majorTexts = dom.majorTexts;
  3968. redundant.minorLines = dom.minorLines;
  3969. redundant.minorTexts = dom.minorTexts;
  3970. dom.majorLines = [];
  3971. dom.majorTexts = [];
  3972. dom.minorLines = [];
  3973. dom.minorTexts = [];
  3974. };
  3975. /**
  3976. * End a repaint. Cleanup leftover DOM elements in the redundant list
  3977. * @private
  3978. */
  3979. TimeAxis.prototype._repaintEnd = function () {
  3980. util.forEach(this.dom.redundant, function (arr) {
  3981. while (arr.length) {
  3982. var elem = arr.pop();
  3983. if (elem && elem.parentNode) {
  3984. elem.parentNode.removeChild(elem);
  3985. }
  3986. }
  3987. });
  3988. };
  3989. /**
  3990. * Create a minor label for the axis at position x
  3991. * @param {Number} x
  3992. * @param {String} text
  3993. * @private
  3994. */
  3995. TimeAxis.prototype._repaintMinorText = function (x, text) {
  3996. // reuse redundant label
  3997. var label = this.dom.redundant.minorTexts.shift();
  3998. if (!label) {
  3999. // create new label
  4000. var content = document.createTextNode('');
  4001. label = document.createElement('div');
  4002. label.appendChild(content);
  4003. label.className = 'text minor';
  4004. this.frame.appendChild(label);
  4005. }
  4006. this.dom.minorTexts.push(label);
  4007. label.childNodes[0].nodeValue = text;
  4008. label.style.left = x + 'px';
  4009. label.style.top = this.props.minorLabelTop + 'px';
  4010. //label.title = title; // TODO: this is a heavy operation
  4011. };
  4012. /**
  4013. * Create a Major label for the axis at position x
  4014. * @param {Number} x
  4015. * @param {String} text
  4016. * @private
  4017. */
  4018. TimeAxis.prototype._repaintMajorText = function (x, text) {
  4019. // reuse redundant label
  4020. var label = this.dom.redundant.majorTexts.shift();
  4021. if (!label) {
  4022. // create label
  4023. var content = document.createTextNode(text);
  4024. label = document.createElement('div');
  4025. label.className = 'text major';
  4026. label.appendChild(content);
  4027. this.frame.appendChild(label);
  4028. }
  4029. this.dom.majorTexts.push(label);
  4030. label.childNodes[0].nodeValue = text;
  4031. label.style.top = this.props.majorLabelTop + 'px';
  4032. label.style.left = x + 'px';
  4033. //label.title = title; // TODO: this is a heavy operation
  4034. };
  4035. /**
  4036. * Create a minor line for the axis at position x
  4037. * @param {Number} x
  4038. * @private
  4039. */
  4040. TimeAxis.prototype._repaintMinorLine = function (x) {
  4041. // reuse redundant line
  4042. var line = this.dom.redundant.minorLines.shift();
  4043. if (!line) {
  4044. // create vertical line
  4045. line = document.createElement('div');
  4046. line.className = 'grid vertical minor';
  4047. this.frame.appendChild(line);
  4048. }
  4049. this.dom.minorLines.push(line);
  4050. var props = this.props;
  4051. line.style.top = props.minorLineTop + 'px';
  4052. line.style.height = props.minorLineHeight + 'px';
  4053. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  4054. };
  4055. /**
  4056. * Create a Major line for the axis at position x
  4057. * @param {Number} x
  4058. * @private
  4059. */
  4060. TimeAxis.prototype._repaintMajorLine = function (x) {
  4061. // reuse redundant line
  4062. var line = this.dom.redundant.majorLines.shift();
  4063. if (!line) {
  4064. // create vertical line
  4065. line = document.createElement('DIV');
  4066. line.className = 'grid vertical major';
  4067. this.frame.appendChild(line);
  4068. }
  4069. this.dom.majorLines.push(line);
  4070. var props = this.props;
  4071. line.style.top = props.majorLineTop + 'px';
  4072. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4073. line.style.height = props.majorLineHeight + 'px';
  4074. };
  4075. /**
  4076. * Repaint the horizontal line for the axis
  4077. * @private
  4078. */
  4079. TimeAxis.prototype._repaintLine = function() {
  4080. var line = this.dom.line,
  4081. frame = this.frame,
  4082. options = this.options;
  4083. // line before all axis elements
  4084. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4085. if (line) {
  4086. // put this line at the end of all childs
  4087. frame.removeChild(line);
  4088. frame.appendChild(line);
  4089. }
  4090. else {
  4091. // create the axis line
  4092. line = document.createElement('div');
  4093. line.className = 'grid horizontal major';
  4094. frame.appendChild(line);
  4095. this.dom.line = line;
  4096. }
  4097. line.style.top = this.props.lineTop + 'px';
  4098. }
  4099. else {
  4100. if (line && line.parentElement) {
  4101. frame.removeChild(line.line);
  4102. delete this.dom.line;
  4103. }
  4104. }
  4105. };
  4106. /**
  4107. * Create characters used to determine the size of text on the axis
  4108. * @private
  4109. */
  4110. TimeAxis.prototype._repaintMeasureChars = function () {
  4111. // calculate the width and height of a single character
  4112. // this is used to calculate the step size, and also the positioning of the
  4113. // axis
  4114. var dom = this.dom,
  4115. text;
  4116. if (!dom.measureCharMinor) {
  4117. text = document.createTextNode('0');
  4118. var measureCharMinor = document.createElement('DIV');
  4119. measureCharMinor.className = 'text minor measure';
  4120. measureCharMinor.appendChild(text);
  4121. this.frame.appendChild(measureCharMinor);
  4122. dom.measureCharMinor = measureCharMinor;
  4123. }
  4124. if (!dom.measureCharMajor) {
  4125. text = document.createTextNode('0');
  4126. var measureCharMajor = document.createElement('DIV');
  4127. measureCharMajor.className = 'text major measure';
  4128. measureCharMajor.appendChild(text);
  4129. this.frame.appendChild(measureCharMajor);
  4130. dom.measureCharMajor = measureCharMajor;
  4131. }
  4132. };
  4133. /**
  4134. * Reflow the component
  4135. * @return {Boolean} resized
  4136. */
  4137. TimeAxis.prototype.reflow = function () {
  4138. var changed = 0,
  4139. update = util.updateProperty,
  4140. frame = this.frame,
  4141. range = this.range;
  4142. if (!range) {
  4143. throw new Error('Cannot repaint time axis: no range configured');
  4144. }
  4145. if (frame) {
  4146. changed += update(this, 'top', frame.offsetTop);
  4147. changed += update(this, 'left', frame.offsetLeft);
  4148. // calculate size of a character
  4149. var props = this.props,
  4150. showMinorLabels = this.getOption('showMinorLabels'),
  4151. showMajorLabels = this.getOption('showMajorLabels'),
  4152. measureCharMinor = this.dom.measureCharMinor,
  4153. measureCharMajor = this.dom.measureCharMajor;
  4154. if (measureCharMinor) {
  4155. props.minorCharHeight = measureCharMinor.clientHeight;
  4156. props.minorCharWidth = measureCharMinor.clientWidth;
  4157. }
  4158. if (measureCharMajor) {
  4159. props.majorCharHeight = measureCharMajor.clientHeight;
  4160. props.majorCharWidth = measureCharMajor.clientWidth;
  4161. }
  4162. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4163. if (parentHeight != props.parentHeight) {
  4164. props.parentHeight = parentHeight;
  4165. changed += 1;
  4166. }
  4167. switch (this.getOption('orientation')) {
  4168. case 'bottom':
  4169. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4170. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4171. props.minorLabelTop = 0;
  4172. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4173. props.minorLineTop = -this.top;
  4174. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4175. props.minorLineWidth = 1; // TODO: really calculate width
  4176. props.majorLineTop = -this.top;
  4177. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4178. props.majorLineWidth = 1; // TODO: really calculate width
  4179. props.lineTop = 0;
  4180. break;
  4181. case 'top':
  4182. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4183. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4184. props.majorLabelTop = 0;
  4185. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4186. props.minorLineTop = props.minorLabelTop;
  4187. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4188. props.minorLineWidth = 1; // TODO: really calculate width
  4189. props.majorLineTop = 0;
  4190. props.majorLineHeight = Math.max(parentHeight - this.top);
  4191. props.majorLineWidth = 1; // TODO: really calculate width
  4192. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4193. break;
  4194. default:
  4195. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4196. }
  4197. var height = props.minorLabelHeight + props.majorLabelHeight;
  4198. changed += update(this, 'width', frame.offsetWidth);
  4199. changed += update(this, 'height', height);
  4200. // calculate range and step
  4201. this._updateConversion();
  4202. var start = util.convert(range.start, 'Number'),
  4203. end = util.convert(range.end, 'Number'),
  4204. minimumStep = this.toTime((props.minorCharWidth || 10) * 5).valueOf()
  4205. -this.toTime(0).valueOf();
  4206. this.step = new TimeStep(new Date(start), new Date(end), minimumStep);
  4207. changed += update(props.range, 'start', start);
  4208. changed += update(props.range, 'end', end);
  4209. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4210. }
  4211. return (changed > 0);
  4212. };
  4213. /**
  4214. * Calculate the scale and offset to convert a position on screen to the
  4215. * corresponding date and vice versa.
  4216. * After the method _updateConversion is executed once, the methods toTime
  4217. * and toScreen can be used.
  4218. * @private
  4219. */
  4220. TimeAxis.prototype._updateConversion = function() {
  4221. var range = this.range;
  4222. if (!range) {
  4223. throw new Error('No range configured');
  4224. }
  4225. if (range.conversion) {
  4226. this.conversion = range.conversion(this.width);
  4227. }
  4228. else {
  4229. this.conversion = Range.conversion(range.start, range.end, this.width);
  4230. }
  4231. };
  4232. /**
  4233. * Snap a date to a rounded value.
  4234. * The snap intervals are dependent on the current scale and step.
  4235. * @param {Date} date the date to be snapped.
  4236. * @return {Date} snappedDate
  4237. */
  4238. TimeAxis.prototype.snap = function snap (date) {
  4239. return this.step.snap(date);
  4240. };
  4241. /**
  4242. * A current time bar
  4243. * @param {Component} parent
  4244. * @param {Component[]} [depends] Components on which this components depends
  4245. * (except for the parent)
  4246. * @param {Object} [options] Available parameters:
  4247. * {Boolean} [showCurrentTime]
  4248. * @constructor CurrentTime
  4249. * @extends Component
  4250. */
  4251. function CurrentTime (parent, depends, options) {
  4252. this.id = util.randomUUID();
  4253. this.parent = parent;
  4254. this.depends = depends;
  4255. this.options = options || {};
  4256. this.defaultOptions = {
  4257. showCurrentTime: false
  4258. };
  4259. }
  4260. CurrentTime.prototype = new Component();
  4261. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  4262. /**
  4263. * Get the container element of the bar, which can be used by a child to
  4264. * add its own widgets.
  4265. * @returns {HTMLElement} container
  4266. */
  4267. CurrentTime.prototype.getContainer = function () {
  4268. return this.frame;
  4269. };
  4270. /**
  4271. * Repaint the component
  4272. * @return {Boolean} changed
  4273. */
  4274. CurrentTime.prototype.repaint = function () {
  4275. var bar = this.frame,
  4276. parent = this.parent,
  4277. parentContainer = parent.parent.getContainer();
  4278. if (!parent) {
  4279. throw new Error('Cannot repaint bar: no parent attached');
  4280. }
  4281. if (!parentContainer) {
  4282. throw new Error('Cannot repaint bar: parent has no container element');
  4283. }
  4284. if (!this.getOption('showCurrentTime')) {
  4285. if (bar) {
  4286. parentContainer.removeChild(bar);
  4287. delete this.frame;
  4288. }
  4289. return false;
  4290. }
  4291. if (!bar) {
  4292. bar = document.createElement('div');
  4293. bar.className = 'currenttime';
  4294. bar.style.position = 'absolute';
  4295. bar.style.top = '0px';
  4296. bar.style.height = '100%';
  4297. parentContainer.appendChild(bar);
  4298. this.frame = bar;
  4299. }
  4300. if (!parent.conversion) {
  4301. parent._updateConversion();
  4302. }
  4303. var now = new Date();
  4304. var x = parent.toScreen(now);
  4305. bar.style.left = x + 'px';
  4306. bar.title = 'Current time: ' + now;
  4307. // start a timer to adjust for the new time
  4308. if (this.currentTimeTimer !== undefined) {
  4309. clearTimeout(this.currentTimeTimer);
  4310. delete this.currentTimeTimer;
  4311. }
  4312. var timeline = this;
  4313. var interval = 1 / parent.conversion.scale / 2;
  4314. if (interval < 30) {
  4315. interval = 30;
  4316. }
  4317. this.currentTimeTimer = setTimeout(function() {
  4318. timeline.repaint();
  4319. }, interval);
  4320. return false;
  4321. };
  4322. /**
  4323. * A custom time bar
  4324. * @param {Component} parent
  4325. * @param {Component[]} [depends] Components on which this components depends
  4326. * (except for the parent)
  4327. * @param {Object} [options] Available parameters:
  4328. * {Boolean} [showCustomTime]
  4329. * @constructor CustomTime
  4330. * @extends Component
  4331. */
  4332. function CustomTime (parent, depends, options) {
  4333. this.id = util.randomUUID();
  4334. this.parent = parent;
  4335. this.depends = depends;
  4336. this.options = options || {};
  4337. this.defaultOptions = {
  4338. showCustomTime: false
  4339. };
  4340. this.customTime = new Date();
  4341. this.eventParams = {}; // stores state parameters while dragging the bar
  4342. }
  4343. CustomTime.prototype = new Component();
  4344. Emitter(CustomTime.prototype);
  4345. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4346. /**
  4347. * Get the container element of the bar, which can be used by a child to
  4348. * add its own widgets.
  4349. * @returns {HTMLElement} container
  4350. */
  4351. CustomTime.prototype.getContainer = function () {
  4352. return this.frame;
  4353. };
  4354. /**
  4355. * Repaint the component
  4356. * @return {Boolean} changed
  4357. */
  4358. CustomTime.prototype.repaint = function () {
  4359. var bar = this.frame,
  4360. parent = this.parent;
  4361. if (!parent) {
  4362. throw new Error('Cannot repaint bar: no parent attached');
  4363. }
  4364. var parentContainer = parent.parent.getContainer();
  4365. if (!parentContainer) {
  4366. throw new Error('Cannot repaint bar: parent has no container element');
  4367. }
  4368. if (!this.getOption('showCustomTime')) {
  4369. if (bar) {
  4370. parentContainer.removeChild(bar);
  4371. delete this.frame;
  4372. }
  4373. return false;
  4374. }
  4375. if (!bar) {
  4376. bar = document.createElement('div');
  4377. bar.className = 'customtime';
  4378. bar.style.position = 'absolute';
  4379. bar.style.top = '0px';
  4380. bar.style.height = '100%';
  4381. parentContainer.appendChild(bar);
  4382. var drag = document.createElement('div');
  4383. drag.style.position = 'relative';
  4384. drag.style.top = '0px';
  4385. drag.style.left = '-10px';
  4386. drag.style.height = '100%';
  4387. drag.style.width = '20px';
  4388. bar.appendChild(drag);
  4389. this.frame = bar;
  4390. // attach event listeners
  4391. this.hammer = Hammer(bar, {
  4392. prevent_default: true
  4393. });
  4394. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4395. this.hammer.on('drag', this._onDrag.bind(this));
  4396. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4397. }
  4398. if (!parent.conversion) {
  4399. parent._updateConversion();
  4400. }
  4401. var x = parent.toScreen(this.customTime);
  4402. bar.style.left = x + 'px';
  4403. bar.title = 'Time: ' + this.customTime;
  4404. return false;
  4405. };
  4406. /**
  4407. * Set custom time.
  4408. * @param {Date} time
  4409. */
  4410. CustomTime.prototype.setCustomTime = function(time) {
  4411. this.customTime = new Date(time.valueOf());
  4412. this.repaint();
  4413. };
  4414. /**
  4415. * Retrieve the current custom time.
  4416. * @return {Date} customTime
  4417. */
  4418. CustomTime.prototype.getCustomTime = function() {
  4419. return new Date(this.customTime.valueOf());
  4420. };
  4421. /**
  4422. * Start moving horizontally
  4423. * @param {Event} event
  4424. * @private
  4425. */
  4426. CustomTime.prototype._onDragStart = function(event) {
  4427. this.eventParams.customTime = this.customTime;
  4428. event.stopPropagation();
  4429. event.preventDefault();
  4430. };
  4431. /**
  4432. * Perform moving operating.
  4433. * @param {Event} event
  4434. * @private
  4435. */
  4436. CustomTime.prototype._onDrag = function (event) {
  4437. var deltaX = event.gesture.deltaX,
  4438. x = this.parent.toScreen(this.eventParams.customTime) + deltaX,
  4439. time = this.parent.toTime(x);
  4440. this.setCustomTime(time);
  4441. // fire a timechange event
  4442. if (this.controller) {
  4443. this.controller.emit('timechange', {
  4444. time: this.customTime
  4445. })
  4446. }
  4447. event.stopPropagation();
  4448. event.preventDefault();
  4449. };
  4450. /**
  4451. * Stop moving operating.
  4452. * @param {event} event
  4453. * @private
  4454. */
  4455. CustomTime.prototype._onDragEnd = function (event) {
  4456. // fire a timechanged event
  4457. if (this.controller) {
  4458. this.controller.emit('timechanged', {
  4459. time: this.customTime
  4460. })
  4461. }
  4462. event.stopPropagation();
  4463. event.preventDefault();
  4464. };
  4465. /**
  4466. * An ItemSet holds a set of items and ranges which can be displayed in a
  4467. * range. The width is determined by the parent of the ItemSet, and the height
  4468. * is determined by the size of the items.
  4469. * @param {Component} parent
  4470. * @param {Component[]} [depends] Components on which this components depends
  4471. * (except for the parent)
  4472. * @param {Object} [options] See ItemSet.setOptions for the available
  4473. * options.
  4474. * @constructor ItemSet
  4475. * @extends Panel
  4476. */
  4477. // TODO: improve performance by replacing all Array.forEach with a for loop
  4478. function ItemSet(parent, depends, options) {
  4479. this.id = util.randomUUID();
  4480. this.parent = parent;
  4481. this.depends = depends;
  4482. // event listeners
  4483. this.eventListeners = {
  4484. dragstart: this._onDragStart.bind(this),
  4485. drag: this._onDrag.bind(this),
  4486. dragend: this._onDragEnd.bind(this)
  4487. };
  4488. // one options object is shared by this itemset and all its items
  4489. this.options = options || {};
  4490. this.defaultOptions = {
  4491. type: 'box',
  4492. align: 'center',
  4493. orientation: 'bottom',
  4494. margin: {
  4495. axis: 20,
  4496. item: 10
  4497. },
  4498. padding: 5
  4499. };
  4500. this.dom = {};
  4501. var me = this;
  4502. this.itemsData = null; // DataSet
  4503. this.range = null; // Range or Object {start: number, end: number}
  4504. // data change listeners
  4505. this.listeners = {
  4506. 'add': function (event, params, senderId) {
  4507. if (senderId != me.id) {
  4508. me._onAdd(params.items);
  4509. }
  4510. },
  4511. 'update': function (event, params, senderId) {
  4512. if (senderId != me.id) {
  4513. me._onUpdate(params.items);
  4514. }
  4515. },
  4516. 'remove': function (event, params, senderId) {
  4517. if (senderId != me.id) {
  4518. me._onRemove(params.items);
  4519. }
  4520. }
  4521. };
  4522. this.items = {}; // object with an Item for every data item
  4523. this.selection = []; // list with the ids of all selected nodes
  4524. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4525. this.stack = new Stack(this, Object.create(this.options));
  4526. this.conversion = null;
  4527. this.touchParams = {}; // stores properties while dragging
  4528. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4529. }
  4530. ItemSet.prototype = new Panel();
  4531. // available item types will be registered here
  4532. ItemSet.types = {
  4533. box: ItemBox,
  4534. range: ItemRange,
  4535. rangeoverflow: ItemRangeOverflow,
  4536. point: ItemPoint
  4537. };
  4538. /**
  4539. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4540. * @param {Object} [options] The following options are available:
  4541. * {String | function} [className]
  4542. * class name for the itemset
  4543. * {String} [type]
  4544. * Default type for the items. Choose from 'box'
  4545. * (default), 'point', or 'range'. The default
  4546. * Style can be overwritten by individual items.
  4547. * {String} align
  4548. * Alignment for the items, only applicable for
  4549. * ItemBox. Choose 'center' (default), 'left', or
  4550. * 'right'.
  4551. * {String} orientation
  4552. * Orientation of the item set. Choose 'top' or
  4553. * 'bottom' (default).
  4554. * {Number} margin.axis
  4555. * Margin between the axis and the items in pixels.
  4556. * Default is 20.
  4557. * {Number} margin.item
  4558. * Margin between items in pixels. Default is 10.
  4559. * {Number} padding
  4560. * Padding of the contents of an item in pixels.
  4561. * Must correspond with the items css. Default is 5.
  4562. * {Function} snap
  4563. * Function to let items snap to nice dates when
  4564. * dragging items.
  4565. */
  4566. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4567. /**
  4568. * Set controller for this component
  4569. * @param {Controller | null} controller
  4570. */
  4571. ItemSet.prototype.setController = function setController (controller) {
  4572. var event;
  4573. // unregister old event listeners
  4574. if (this.controller) {
  4575. for (event in this.eventListeners) {
  4576. if (this.eventListeners.hasOwnProperty(event)) {
  4577. this.controller.off(event, this.eventListeners[event]);
  4578. }
  4579. }
  4580. }
  4581. this.controller = controller || null;
  4582. // register new event listeners
  4583. if (this.controller) {
  4584. for (event in this.eventListeners) {
  4585. if (this.eventListeners.hasOwnProperty(event)) {
  4586. this.controller.on(event, this.eventListeners[event]);
  4587. }
  4588. }
  4589. }
  4590. };
  4591. // attach event listeners for dragging items to the controller
  4592. (function (me) {
  4593. var _controller = null;
  4594. var _onDragStart = null;
  4595. var _onDrag = null;
  4596. var _onDragEnd = null;
  4597. Object.defineProperty(me, 'controller', {
  4598. get: function () {
  4599. return _controller;
  4600. },
  4601. set: function (controller) {
  4602. }
  4603. });
  4604. }) (this);
  4605. /**
  4606. * Set range (start and end).
  4607. * @param {Range | Object} range A Range or an object containing start and end.
  4608. */
  4609. ItemSet.prototype.setRange = function setRange(range) {
  4610. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4611. throw new TypeError('Range must be an instance of Range, ' +
  4612. 'or an object containing start and end.');
  4613. }
  4614. this.range = range;
  4615. };
  4616. /**
  4617. * Set selected items by their id. Replaces the current selection
  4618. * Unknown id's are silently ignored.
  4619. * @param {Array} [ids] An array with zero or more id's of the items to be
  4620. * selected. If ids is an empty array, all items will be
  4621. * unselected.
  4622. */
  4623. ItemSet.prototype.setSelection = function setSelection(ids) {
  4624. var i, ii, id, item, selection;
  4625. if (ids) {
  4626. if (!Array.isArray(ids)) {
  4627. throw new TypeError('Array expected');
  4628. }
  4629. // unselect currently selected items
  4630. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4631. id = this.selection[i];
  4632. item = this.items[id];
  4633. if (item) item.unselect();
  4634. }
  4635. // select items
  4636. this.selection = [];
  4637. for (i = 0, ii = ids.length; i < ii; i++) {
  4638. id = ids[i];
  4639. item = this.items[id];
  4640. if (item) {
  4641. this.selection.push(id);
  4642. item.select();
  4643. }
  4644. }
  4645. if (this.controller) {
  4646. this.requestRepaint();
  4647. }
  4648. }
  4649. };
  4650. /**
  4651. * Get the selected items by their id
  4652. * @return {Array} ids The ids of the selected items
  4653. */
  4654. ItemSet.prototype.getSelection = function getSelection() {
  4655. return this.selection.concat([]);
  4656. };
  4657. /**
  4658. * Deselect a selected item
  4659. * @param {String | Number} id
  4660. * @private
  4661. */
  4662. ItemSet.prototype._deselect = function _deselect(id) {
  4663. var selection = this.selection;
  4664. for (var i = 0, ii = selection.length; i < ii; i++) {
  4665. if (selection[i] == id) { // non-strict comparison!
  4666. selection.splice(i, 1);
  4667. break;
  4668. }
  4669. }
  4670. };
  4671. /**
  4672. * Repaint the component
  4673. * @return {Boolean} changed
  4674. */
  4675. ItemSet.prototype.repaint = function repaint() {
  4676. var changed = 0,
  4677. update = util.updateProperty,
  4678. asSize = util.option.asSize,
  4679. options = this.options,
  4680. orientation = this.getOption('orientation'),
  4681. defaultOptions = this.defaultOptions,
  4682. frame = this.frame;
  4683. if (!frame) {
  4684. frame = document.createElement('div');
  4685. frame.className = 'itemset';
  4686. frame['timeline-itemset'] = this;
  4687. var className = options.className;
  4688. if (className) {
  4689. util.addClassName(frame, util.option.asString(className));
  4690. }
  4691. // create background panel
  4692. var background = document.createElement('div');
  4693. background.className = 'background';
  4694. frame.appendChild(background);
  4695. this.dom.background = background;
  4696. // create foreground panel
  4697. var foreground = document.createElement('div');
  4698. foreground.className = 'foreground';
  4699. frame.appendChild(foreground);
  4700. this.dom.foreground = foreground;
  4701. // create axis panel
  4702. var axis = document.createElement('div');
  4703. axis.className = 'itemset-axis';
  4704. //frame.appendChild(axis);
  4705. this.dom.axis = axis;
  4706. this.frame = frame;
  4707. changed += 1;
  4708. }
  4709. if (!this.parent) {
  4710. throw new Error('Cannot repaint itemset: no parent attached');
  4711. }
  4712. var parentContainer = this.parent.getContainer();
  4713. if (!parentContainer) {
  4714. throw new Error('Cannot repaint itemset: parent has no container element');
  4715. }
  4716. if (!frame.parentNode) {
  4717. parentContainer.appendChild(frame);
  4718. changed += 1;
  4719. }
  4720. if (!this.dom.axis.parentNode) {
  4721. parentContainer.appendChild(this.dom.axis);
  4722. changed += 1;
  4723. }
  4724. // reposition frame
  4725. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4726. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4727. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4728. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4729. // reposition axis
  4730. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4731. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4732. if (orientation == 'bottom') {
  4733. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4734. }
  4735. else { // orientation == 'top'
  4736. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4737. }
  4738. this._updateConversion();
  4739. var me = this,
  4740. queue = this.queue,
  4741. itemsData = this.itemsData,
  4742. items = this.items,
  4743. dataOptions = {
  4744. // TODO: cleanup
  4745. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  4746. };
  4747. // show/hide added/changed/removed items
  4748. for (var id in queue) {
  4749. if (queue.hasOwnProperty(id)) {
  4750. var entry = queue[id],
  4751. item = items[id],
  4752. action = entry.action;
  4753. //noinspection FallthroughInSwitchStatementJS
  4754. switch (action) {
  4755. case 'add':
  4756. case 'update':
  4757. var itemData = itemsData && itemsData.get(id, dataOptions);
  4758. if (itemData) {
  4759. var type = itemData.type ||
  4760. (itemData.start && itemData.end && 'range') ||
  4761. options.type ||
  4762. 'box';
  4763. var constructor = ItemSet.types[type];
  4764. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4765. if (item) {
  4766. // update item
  4767. if (!constructor || !(item instanceof constructor)) {
  4768. // item type has changed, hide and delete the item
  4769. changed += item.hide();
  4770. item = null;
  4771. }
  4772. else {
  4773. item.data = itemData; // TODO: create a method item.setData ?
  4774. changed++;
  4775. }
  4776. }
  4777. if (!item) {
  4778. // create item
  4779. if (constructor) {
  4780. item = new constructor(me, itemData, options, defaultOptions);
  4781. item.id = entry.id; // we take entry.id, as id itself is stringified
  4782. changed++;
  4783. }
  4784. else {
  4785. throw new TypeError('Unknown item type "' + type + '"');
  4786. }
  4787. }
  4788. // force a repaint (not only a reposition)
  4789. item.repaint();
  4790. items[id] = item;
  4791. }
  4792. // update queue
  4793. delete queue[id];
  4794. break;
  4795. case 'remove':
  4796. if (item) {
  4797. // remove the item from the set selected items
  4798. if (item.selected) {
  4799. me._deselect(id);
  4800. }
  4801. // remove DOM of the item
  4802. changed += item.hide();
  4803. }
  4804. // update lists
  4805. delete items[id];
  4806. delete queue[id];
  4807. break;
  4808. default:
  4809. console.log('Error: unknown action "' + action + '"');
  4810. }
  4811. }
  4812. }
  4813. // reposition all items. Show items only when in the visible area
  4814. util.forEach(this.items, function (item) {
  4815. if (item.visible) {
  4816. changed += item.show();
  4817. item.reposition();
  4818. }
  4819. else {
  4820. changed += item.hide();
  4821. }
  4822. });
  4823. return (changed > 0);
  4824. };
  4825. /**
  4826. * Get the foreground container element
  4827. * @return {HTMLElement} foreground
  4828. */
  4829. ItemSet.prototype.getForeground = function getForeground() {
  4830. return this.dom.foreground;
  4831. };
  4832. /**
  4833. * Get the background container element
  4834. * @return {HTMLElement} background
  4835. */
  4836. ItemSet.prototype.getBackground = function getBackground() {
  4837. return this.dom.background;
  4838. };
  4839. /**
  4840. * Get the axis container element
  4841. * @return {HTMLElement} axis
  4842. */
  4843. ItemSet.prototype.getAxis = function getAxis() {
  4844. return this.dom.axis;
  4845. };
  4846. /**
  4847. * Reflow the component
  4848. * @return {Boolean} resized
  4849. */
  4850. ItemSet.prototype.reflow = function reflow () {
  4851. var changed = 0,
  4852. options = this.options,
  4853. marginAxis = (options.margin && 'axis' in options.margin) ? options.margin.axis : this.defaultOptions.margin.axis,
  4854. marginItem = (options.margin && 'item' in options.margin) ? options.margin.item : this.defaultOptions.margin.item,
  4855. update = util.updateProperty,
  4856. asNumber = util.option.asNumber,
  4857. asSize = util.option.asSize,
  4858. frame = this.frame;
  4859. if (frame) {
  4860. this._updateConversion();
  4861. util.forEach(this.items, function (item) {
  4862. changed += item.reflow();
  4863. });
  4864. // TODO: stack.update should be triggered via an event, in stack itself
  4865. // TODO: only update the stack when there are changed items
  4866. this.stack.update();
  4867. var maxHeight = asNumber(options.maxHeight);
  4868. var fixedHeight = (asSize(options.height) != null);
  4869. var height;
  4870. if (fixedHeight) {
  4871. height = frame.offsetHeight;
  4872. }
  4873. else {
  4874. // height is not specified, determine the height from the height and positioned items
  4875. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4876. if (visibleItems.length) {
  4877. var min = visibleItems[0].top;
  4878. var max = visibleItems[0].top + visibleItems[0].height;
  4879. util.forEach(visibleItems, function (item) {
  4880. min = Math.min(min, item.top);
  4881. max = Math.max(max, (item.top + item.height));
  4882. });
  4883. height = (max - min) + marginAxis + marginItem;
  4884. }
  4885. else {
  4886. height = marginAxis + marginItem;
  4887. }
  4888. }
  4889. if (maxHeight != null) {
  4890. height = Math.min(height, maxHeight);
  4891. }
  4892. changed += update(this, 'height', height);
  4893. // calculate height from items
  4894. changed += update(this, 'top', frame.offsetTop);
  4895. changed += update(this, 'left', frame.offsetLeft);
  4896. changed += update(this, 'width', frame.offsetWidth);
  4897. }
  4898. else {
  4899. changed += 1;
  4900. }
  4901. return (changed > 0);
  4902. };
  4903. /**
  4904. * Hide this component from the DOM
  4905. * @return {Boolean} changed
  4906. */
  4907. ItemSet.prototype.hide = function hide() {
  4908. var changed = false;
  4909. // remove the DOM
  4910. if (this.frame && this.frame.parentNode) {
  4911. this.frame.parentNode.removeChild(this.frame);
  4912. changed = true;
  4913. }
  4914. if (this.dom.axis && this.dom.axis.parentNode) {
  4915. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4916. changed = true;
  4917. }
  4918. return changed;
  4919. };
  4920. /**
  4921. * Set items
  4922. * @param {vis.DataSet | null} items
  4923. */
  4924. ItemSet.prototype.setItems = function setItems(items) {
  4925. var me = this,
  4926. ids,
  4927. oldItemsData = this.itemsData;
  4928. // replace the dataset
  4929. if (!items) {
  4930. this.itemsData = null;
  4931. }
  4932. else if (items instanceof DataSet || items instanceof DataView) {
  4933. this.itemsData = items;
  4934. }
  4935. else {
  4936. throw new TypeError('Data must be an instance of DataSet');
  4937. }
  4938. if (oldItemsData) {
  4939. // unsubscribe from old dataset
  4940. util.forEach(this.listeners, function (callback, event) {
  4941. oldItemsData.unsubscribe(event, callback);
  4942. });
  4943. // remove all drawn items
  4944. ids = oldItemsData.getIds();
  4945. this._onRemove(ids);
  4946. }
  4947. if (this.itemsData) {
  4948. // subscribe to new dataset
  4949. var id = this.id;
  4950. util.forEach(this.listeners, function (callback, event) {
  4951. me.itemsData.on(event, callback, id);
  4952. });
  4953. // draw all new items
  4954. ids = this.itemsData.getIds();
  4955. this._onAdd(ids);
  4956. }
  4957. };
  4958. /**
  4959. * Get the current items items
  4960. * @returns {vis.DataSet | null}
  4961. */
  4962. ItemSet.prototype.getItems = function getItems() {
  4963. return this.itemsData;
  4964. };
  4965. /**
  4966. * Remove an item by its id
  4967. * @param {String | Number} id
  4968. */
  4969. ItemSet.prototype.removeItem = function removeItem (id) {
  4970. var item = this.itemsData.get(id),
  4971. dataset = this._myDataSet();
  4972. if (item) {
  4973. // confirm deletion
  4974. this.options.onRemove(item, function (item) {
  4975. if (item) {
  4976. dataset.remove(item);
  4977. }
  4978. });
  4979. }
  4980. };
  4981. /**
  4982. * Handle updated items
  4983. * @param {Number[]} ids
  4984. * @private
  4985. */
  4986. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4987. this._toQueue('update', ids);
  4988. };
  4989. /**
  4990. * Handle changed items
  4991. * @param {Number[]} ids
  4992. * @private
  4993. */
  4994. ItemSet.prototype._onAdd = function _onAdd(ids) {
  4995. this._toQueue('add', ids);
  4996. };
  4997. /**
  4998. * Handle removed items
  4999. * @param {Number[]} ids
  5000. * @private
  5001. */
  5002. ItemSet.prototype._onRemove = function _onRemove(ids) {
  5003. this._toQueue('remove', ids);
  5004. };
  5005. /**
  5006. * Put items in the queue to be added/updated/remove
  5007. * @param {String} action can be 'add', 'update', 'remove'
  5008. * @param {Number[]} ids
  5009. */
  5010. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  5011. var queue = this.queue;
  5012. ids.forEach(function (id) {
  5013. queue[id] = {
  5014. id: id,
  5015. action: action
  5016. };
  5017. });
  5018. if (this.controller) {
  5019. //this.requestReflow();
  5020. this.requestRepaint();
  5021. }
  5022. };
  5023. /**
  5024. * Calculate the scale and offset to convert a position on screen to the
  5025. * corresponding date and vice versa.
  5026. * After the method _updateConversion is executed once, the methods toTime
  5027. * and toScreen can be used.
  5028. * @private
  5029. */
  5030. ItemSet.prototype._updateConversion = function _updateConversion() {
  5031. var range = this.range;
  5032. if (!range) {
  5033. throw new Error('No range configured');
  5034. }
  5035. if (range.conversion) {
  5036. this.conversion = range.conversion(this.width);
  5037. }
  5038. else {
  5039. this.conversion = Range.conversion(range.start, range.end, this.width);
  5040. }
  5041. };
  5042. /**
  5043. * Convert a position on screen (pixels) to a datetime
  5044. * Before this method can be used, the method _updateConversion must be
  5045. * executed once.
  5046. * @param {int} x Position on the screen in pixels
  5047. * @return {Date} time The datetime the corresponds with given position x
  5048. */
  5049. ItemSet.prototype.toTime = function toTime(x) {
  5050. var conversion = this.conversion;
  5051. return new Date(x / conversion.scale + conversion.offset);
  5052. };
  5053. /**
  5054. * Convert a datetime (Date object) into a position on the screen
  5055. * Before this method can be used, the method _updateConversion must be
  5056. * executed once.
  5057. * @param {Date} time A date
  5058. * @return {int} x The position on the screen in pixels which corresponds
  5059. * with the given date.
  5060. */
  5061. ItemSet.prototype.toScreen = function toScreen(time) {
  5062. var conversion = this.conversion;
  5063. return (time.valueOf() - conversion.offset) * conversion.scale;
  5064. };
  5065. /**
  5066. * Start dragging the selected events
  5067. * @param {Event} event
  5068. * @private
  5069. */
  5070. ItemSet.prototype._onDragStart = function (event) {
  5071. if (!this.options.editable) {
  5072. return;
  5073. }
  5074. var item = ItemSet.itemFromTarget(event),
  5075. me = this;
  5076. if (item && item.selected) {
  5077. var dragLeftItem = event.target.dragLeftItem;
  5078. var dragRightItem = event.target.dragRightItem;
  5079. if (dragLeftItem) {
  5080. this.touchParams.itemProps = [{
  5081. item: dragLeftItem,
  5082. start: item.data.start.valueOf()
  5083. }];
  5084. }
  5085. else if (dragRightItem) {
  5086. this.touchParams.itemProps = [{
  5087. item: dragRightItem,
  5088. end: item.data.end.valueOf()
  5089. }];
  5090. }
  5091. else {
  5092. this.touchParams.itemProps = this.getSelection().map(function (id) {
  5093. var item = me.items[id];
  5094. var props = {
  5095. item: item
  5096. };
  5097. if ('start' in item.data) {
  5098. props.start = item.data.start.valueOf()
  5099. }
  5100. if ('end' in item.data) {
  5101. props.end = item.data.end.valueOf()
  5102. }
  5103. return props;
  5104. });
  5105. }
  5106. event.stopPropagation();
  5107. }
  5108. };
  5109. /**
  5110. * Drag selected items
  5111. * @param {Event} event
  5112. * @private
  5113. */
  5114. ItemSet.prototype._onDrag = function (event) {
  5115. if (this.touchParams.itemProps) {
  5116. var snap = this.options.snap || null,
  5117. deltaX = event.gesture.deltaX,
  5118. offset = deltaX / this.conversion.scale;
  5119. // move
  5120. this.touchParams.itemProps.forEach(function (props) {
  5121. if ('start' in props) {
  5122. var start = new Date(props.start + offset);
  5123. props.item.data.start = snap ? snap(start) : start;
  5124. }
  5125. if ('end' in props) {
  5126. var end = new Date(props.end + offset);
  5127. props.item.data.end = snap ? snap(end) : end;
  5128. }
  5129. });
  5130. // TODO: implement onMoving handler
  5131. // TODO: implement dragging from one group to another
  5132. this.requestReflow();
  5133. event.stopPropagation();
  5134. }
  5135. };
  5136. /**
  5137. * End of dragging selected items
  5138. * @param {Event} event
  5139. * @private
  5140. */
  5141. ItemSet.prototype._onDragEnd = function (event) {
  5142. if (this.touchParams.itemProps) {
  5143. // prepare a change set for the changed items
  5144. var changes = [],
  5145. me = this,
  5146. dataset = this._myDataSet(),
  5147. type;
  5148. this.touchParams.itemProps.forEach(function (props) {
  5149. var id = props.item.id,
  5150. item = me.itemsData.get(id);
  5151. var changed = false;
  5152. if ('start' in props.item.data) {
  5153. changed = (props.start != props.item.data.start.valueOf());
  5154. item.start = util.convert(props.item.data.start, dataset.convert['start']);
  5155. }
  5156. if ('end' in props.item.data) {
  5157. changed = changed || (props.end != props.item.data.end.valueOf());
  5158. item.end = util.convert(props.item.data.end, dataset.convert['end']);
  5159. }
  5160. // only apply changes when start or end is actually changed
  5161. if (changed) {
  5162. me.options.onMove(item, function (item) {
  5163. if (item) {
  5164. // apply changes
  5165. changes.push(item);
  5166. }
  5167. else {
  5168. // restore original values
  5169. if ('start' in props) props.item.data.start = props.start;
  5170. if ('end' in props) props.item.data.end = props.end;
  5171. me.requestReflow();
  5172. }
  5173. });
  5174. }
  5175. });
  5176. this.touchParams.itemProps = null;
  5177. // apply the changes to the data (if there are changes)
  5178. if (changes.length) {
  5179. dataset.update(changes);
  5180. }
  5181. event.stopPropagation();
  5182. }
  5183. };
  5184. /**
  5185. * Find an item from an event target:
  5186. * searches for the attribute 'timeline-item' in the event target's element tree
  5187. * @param {Event} event
  5188. * @return {Item | null} item
  5189. */
  5190. ItemSet.itemFromTarget = function itemFromTarget (event) {
  5191. var target = event.target;
  5192. while (target) {
  5193. if (target.hasOwnProperty('timeline-item')) {
  5194. return target['timeline-item'];
  5195. }
  5196. target = target.parentNode;
  5197. }
  5198. return null;
  5199. };
  5200. /**
  5201. * Find the ItemSet from an event target:
  5202. * searches for the attribute 'timeline-itemset' in the event target's element tree
  5203. * @param {Event} event
  5204. * @return {ItemSet | null} item
  5205. */
  5206. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  5207. var target = event.target;
  5208. while (target) {
  5209. if (target.hasOwnProperty('timeline-itemset')) {
  5210. return target['timeline-itemset'];
  5211. }
  5212. target = target.parentNode;
  5213. }
  5214. return null;
  5215. };
  5216. /**
  5217. * Find the DataSet to which this ItemSet is connected
  5218. * @returns {null | DataSet} dataset
  5219. * @private
  5220. */
  5221. ItemSet.prototype._myDataSet = function _myDataSet() {
  5222. // find the root DataSet
  5223. var dataset = this.itemsData;
  5224. while (dataset instanceof DataView) {
  5225. dataset = dataset.data;
  5226. }
  5227. return dataset;
  5228. };
  5229. /**
  5230. * @constructor Item
  5231. * @param {ItemSet} parent
  5232. * @param {Object} data Object containing (optional) parameters type,
  5233. * start, end, content, group, className.
  5234. * @param {Object} [options] Options to set initial property values
  5235. * @param {Object} [defaultOptions] default options
  5236. * // TODO: describe available options
  5237. */
  5238. function Item (parent, data, options, defaultOptions) {
  5239. this.parent = parent;
  5240. this.data = data;
  5241. this.dom = null;
  5242. this.options = options || {};
  5243. this.defaultOptions = defaultOptions || {};
  5244. this.selected = false;
  5245. this.visible = false;
  5246. this.top = 0;
  5247. this.left = 0;
  5248. this.width = 0;
  5249. this.height = 0;
  5250. this.offset = 0;
  5251. }
  5252. /**
  5253. * Select current item
  5254. */
  5255. Item.prototype.select = function select() {
  5256. this.selected = true;
  5257. if (this.visible) this.repaint();
  5258. };
  5259. /**
  5260. * Unselect current item
  5261. */
  5262. Item.prototype.unselect = function unselect() {
  5263. this.selected = false;
  5264. if (this.visible) this.repaint();
  5265. };
  5266. /**
  5267. * Show the Item in the DOM (when not already visible)
  5268. * @return {Boolean} changed
  5269. */
  5270. Item.prototype.show = function show() {
  5271. return false;
  5272. };
  5273. /**
  5274. * Hide the Item from the DOM (when visible)
  5275. * @return {Boolean} changed
  5276. */
  5277. Item.prototype.hide = function hide() {
  5278. return false;
  5279. };
  5280. /**
  5281. * Repaint the item
  5282. * @return {Boolean} changed
  5283. */
  5284. Item.prototype.repaint = function repaint() {
  5285. // should be implemented by the item
  5286. return false;
  5287. };
  5288. /**
  5289. * Reflow the item
  5290. * @return {Boolean} resized
  5291. */
  5292. Item.prototype.reflow = function reflow() {
  5293. // should be implemented by the item
  5294. return false;
  5295. };
  5296. /**
  5297. * Give the item a display offset in pixels
  5298. * @param {Number} offset Offset on screen in pixels
  5299. */
  5300. Item.prototype.setOffset = function setOffset(offset) {
  5301. this.offset = offset;
  5302. };
  5303. /**
  5304. * Repaint a delete button on the top right of the item when the item is selected
  5305. * @param {HTMLElement} anchor
  5306. * @private
  5307. */
  5308. Item.prototype._repaintDeleteButton = function (anchor) {
  5309. if (this.selected && this.options.editable && !this.dom.deleteButton) {
  5310. // create and show button
  5311. var parent = this.parent;
  5312. var id = this.id;
  5313. var deleteButton = document.createElement('div');
  5314. deleteButton.className = 'delete';
  5315. deleteButton.title = 'Delete this item';
  5316. Hammer(deleteButton, {
  5317. preventDefault: true
  5318. }).on('tap', function (event) {
  5319. parent.removeItem(id);
  5320. event.stopPropagation();
  5321. });
  5322. anchor.appendChild(deleteButton);
  5323. this.dom.deleteButton = deleteButton;
  5324. }
  5325. else if (!this.selected && this.dom.deleteButton) {
  5326. // remove button
  5327. if (this.dom.deleteButton.parentNode) {
  5328. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5329. }
  5330. this.dom.deleteButton = null;
  5331. }
  5332. };
  5333. /**
  5334. * @constructor ItemBox
  5335. * @extends Item
  5336. * @param {ItemSet} parent
  5337. * @param {Object} data Object containing parameters start
  5338. * content, className.
  5339. * @param {Object} [options] Options to set initial property values
  5340. * @param {Object} [defaultOptions] default options
  5341. * // TODO: describe available options
  5342. */
  5343. function ItemBox (parent, data, options, defaultOptions) {
  5344. this.props = {
  5345. dot: {
  5346. left: 0,
  5347. top: 0,
  5348. width: 0,
  5349. height: 0
  5350. },
  5351. line: {
  5352. top: 0,
  5353. left: 0,
  5354. width: 0,
  5355. height: 0
  5356. }
  5357. };
  5358. Item.call(this, parent, data, options, defaultOptions);
  5359. }
  5360. ItemBox.prototype = new Item (null, null);
  5361. /**
  5362. * Repaint the item
  5363. * @return {Boolean} changed
  5364. */
  5365. ItemBox.prototype.repaint = function repaint() {
  5366. // TODO: make an efficient repaint
  5367. var changed = false;
  5368. var dom = this.dom;
  5369. if (!dom) {
  5370. this._create();
  5371. dom = this.dom;
  5372. changed = true;
  5373. }
  5374. if (dom) {
  5375. if (!this.parent) {
  5376. throw new Error('Cannot repaint item: no parent attached');
  5377. }
  5378. if (!dom.box.parentNode) {
  5379. var foreground = this.parent.getForeground();
  5380. if (!foreground) {
  5381. throw new Error('Cannot repaint time axis: ' +
  5382. 'parent has no foreground container element');
  5383. }
  5384. foreground.appendChild(dom.box);
  5385. changed = true;
  5386. }
  5387. if (!dom.line.parentNode) {
  5388. var background = this.parent.getBackground();
  5389. if (!background) {
  5390. throw new Error('Cannot repaint time axis: ' +
  5391. 'parent has no background container element');
  5392. }
  5393. background.appendChild(dom.line);
  5394. changed = true;
  5395. }
  5396. if (!dom.dot.parentNode) {
  5397. var axis = this.parent.getAxis();
  5398. if (!background) {
  5399. throw new Error('Cannot repaint time axis: ' +
  5400. 'parent has no axis container element');
  5401. }
  5402. axis.appendChild(dom.dot);
  5403. changed = true;
  5404. }
  5405. this._repaintDeleteButton(dom.box);
  5406. // update contents
  5407. if (this.data.content != this.content) {
  5408. this.content = this.data.content;
  5409. if (this.content instanceof Element) {
  5410. dom.content.innerHTML = '';
  5411. dom.content.appendChild(this.content);
  5412. }
  5413. else if (this.data.content != undefined) {
  5414. dom.content.innerHTML = this.content;
  5415. }
  5416. else {
  5417. throw new Error('Property "content" missing in item ' + this.data.id);
  5418. }
  5419. changed = true;
  5420. }
  5421. // update class
  5422. var className = (this.data.className? ' ' + this.data.className : '') +
  5423. (this.selected ? ' selected' : '');
  5424. if (this.className != className) {
  5425. this.className = className;
  5426. dom.box.className = 'item box' + className;
  5427. dom.line.className = 'item line' + className;
  5428. dom.dot.className = 'item dot' + className;
  5429. changed = true;
  5430. }
  5431. }
  5432. return changed;
  5433. };
  5434. /**
  5435. * Show the item in the DOM (when not already visible). The items DOM will
  5436. * be created when needed.
  5437. * @return {Boolean} changed
  5438. */
  5439. ItemBox.prototype.show = function show() {
  5440. if (!this.dom || !this.dom.box.parentNode) {
  5441. return this.repaint();
  5442. }
  5443. else {
  5444. return false;
  5445. }
  5446. };
  5447. /**
  5448. * Hide the item from the DOM (when visible)
  5449. * @return {Boolean} changed
  5450. */
  5451. ItemBox.prototype.hide = function hide() {
  5452. var changed = false,
  5453. dom = this.dom;
  5454. if (dom) {
  5455. if (dom.box.parentNode) {
  5456. dom.box.parentNode.removeChild(dom.box);
  5457. changed = true;
  5458. }
  5459. if (dom.line.parentNode) {
  5460. dom.line.parentNode.removeChild(dom.line);
  5461. }
  5462. if (dom.dot.parentNode) {
  5463. dom.dot.parentNode.removeChild(dom.dot);
  5464. }
  5465. }
  5466. return changed;
  5467. };
  5468. /**
  5469. * Reflow the item: calculate its actual size and position from the DOM
  5470. * @return {boolean} resized returns true if the axis is resized
  5471. * @override
  5472. */
  5473. ItemBox.prototype.reflow = function reflow() {
  5474. var changed = 0,
  5475. update,
  5476. dom,
  5477. props,
  5478. options,
  5479. margin,
  5480. start,
  5481. align,
  5482. orientation,
  5483. top,
  5484. left,
  5485. data,
  5486. range;
  5487. if (this.data.start == undefined) {
  5488. throw new Error('Property "start" missing in item ' + this.data.id);
  5489. }
  5490. data = this.data;
  5491. range = this.parent && this.parent.range;
  5492. if (data && range) {
  5493. // TODO: account for the width of the item
  5494. var interval = (range.end - range.start);
  5495. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  5496. }
  5497. else {
  5498. this.visible = false;
  5499. }
  5500. if (this.visible) {
  5501. dom = this.dom;
  5502. if (dom) {
  5503. update = util.updateProperty;
  5504. props = this.props;
  5505. options = this.options;
  5506. start = this.parent.toScreen(this.data.start) + this.offset;
  5507. align = options.align || this.defaultOptions.align;
  5508. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5509. orientation = options.orientation || this.defaultOptions.orientation;
  5510. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5511. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5512. changed += update(props.line, 'width', dom.line.offsetWidth);
  5513. changed += update(props.line, 'height', dom.line.offsetHeight);
  5514. changed += update(props.line, 'top', dom.line.offsetTop);
  5515. changed += update(this, 'width', dom.box.offsetWidth);
  5516. changed += update(this, 'height', dom.box.offsetHeight);
  5517. if (align == 'right') {
  5518. left = start - this.width;
  5519. }
  5520. else if (align == 'left') {
  5521. left = start;
  5522. }
  5523. else {
  5524. // default or 'center'
  5525. left = start - this.width / 2;
  5526. }
  5527. changed += update(this, 'left', left);
  5528. changed += update(props.line, 'left', start - props.line.width / 2);
  5529. changed += update(props.dot, 'left', start - props.dot.width / 2);
  5530. changed += update(props.dot, 'top', -props.dot.height / 2);
  5531. if (orientation == 'top') {
  5532. top = margin;
  5533. changed += update(this, 'top', top);
  5534. }
  5535. else {
  5536. // default or 'bottom'
  5537. var parentHeight = this.parent.height;
  5538. top = parentHeight - this.height - margin;
  5539. changed += update(this, 'top', top);
  5540. }
  5541. }
  5542. else {
  5543. changed += 1;
  5544. }
  5545. }
  5546. return (changed > 0);
  5547. };
  5548. /**
  5549. * Create an items DOM
  5550. * @private
  5551. */
  5552. ItemBox.prototype._create = function _create() {
  5553. var dom = this.dom;
  5554. if (!dom) {
  5555. this.dom = dom = {};
  5556. // create the box
  5557. dom.box = document.createElement('DIV');
  5558. // className is updated in repaint()
  5559. // contents box (inside the background box). used for making margins
  5560. dom.content = document.createElement('DIV');
  5561. dom.content.className = 'content';
  5562. dom.box.appendChild(dom.content);
  5563. // line to axis
  5564. dom.line = document.createElement('DIV');
  5565. dom.line.className = 'line';
  5566. // dot on axis
  5567. dom.dot = document.createElement('DIV');
  5568. dom.dot.className = 'dot';
  5569. // attach this item as attribute
  5570. dom.box['timeline-item'] = this;
  5571. }
  5572. };
  5573. /**
  5574. * Reposition the item, recalculate its left, top, and width, using the current
  5575. * range and size of the items itemset
  5576. * @override
  5577. */
  5578. ItemBox.prototype.reposition = function reposition() {
  5579. var dom = this.dom,
  5580. props = this.props,
  5581. orientation = this.options.orientation || this.defaultOptions.orientation;
  5582. if (dom) {
  5583. var box = dom.box,
  5584. line = dom.line,
  5585. dot = dom.dot;
  5586. box.style.left = this.left + 'px';
  5587. box.style.top = this.top + 'px';
  5588. line.style.left = props.line.left + 'px';
  5589. if (orientation == 'top') {
  5590. line.style.top = 0 + 'px';
  5591. line.style.height = this.top + 'px';
  5592. }
  5593. else {
  5594. // orientation 'bottom'
  5595. line.style.top = (this.top + this.height) + 'px';
  5596. line.style.height = Math.max(this.parent.height - this.top - this.height +
  5597. this.props.dot.height / 2, 0) + 'px';
  5598. }
  5599. dot.style.left = props.dot.left + 'px';
  5600. dot.style.top = props.dot.top + 'px';
  5601. }
  5602. };
  5603. /**
  5604. * @constructor ItemPoint
  5605. * @extends Item
  5606. * @param {ItemSet} parent
  5607. * @param {Object} data Object containing parameters start
  5608. * content, className.
  5609. * @param {Object} [options] Options to set initial property values
  5610. * @param {Object} [defaultOptions] default options
  5611. * // TODO: describe available options
  5612. */
  5613. function ItemPoint (parent, data, options, defaultOptions) {
  5614. this.props = {
  5615. dot: {
  5616. top: 0,
  5617. width: 0,
  5618. height: 0
  5619. },
  5620. content: {
  5621. height: 0,
  5622. marginLeft: 0
  5623. }
  5624. };
  5625. Item.call(this, parent, data, options, defaultOptions);
  5626. }
  5627. ItemPoint.prototype = new Item (null, null);
  5628. /**
  5629. * Repaint the item
  5630. * @return {Boolean} changed
  5631. */
  5632. ItemPoint.prototype.repaint = function repaint() {
  5633. // TODO: make an efficient repaint
  5634. var changed = false;
  5635. var dom = this.dom;
  5636. if (!dom) {
  5637. this._create();
  5638. dom = this.dom;
  5639. changed = true;
  5640. }
  5641. if (dom) {
  5642. if (!this.parent) {
  5643. throw new Error('Cannot repaint item: no parent attached');
  5644. }
  5645. var foreground = this.parent.getForeground();
  5646. if (!foreground) {
  5647. throw new Error('Cannot repaint time axis: ' +
  5648. 'parent has no foreground container element');
  5649. }
  5650. if (!dom.point.parentNode) {
  5651. foreground.appendChild(dom.point);
  5652. foreground.appendChild(dom.point);
  5653. changed = true;
  5654. }
  5655. // update contents
  5656. if (this.data.content != this.content) {
  5657. this.content = this.data.content;
  5658. if (this.content instanceof Element) {
  5659. dom.content.innerHTML = '';
  5660. dom.content.appendChild(this.content);
  5661. }
  5662. else if (this.data.content != undefined) {
  5663. dom.content.innerHTML = this.content;
  5664. }
  5665. else {
  5666. throw new Error('Property "content" missing in item ' + this.data.id);
  5667. }
  5668. changed = true;
  5669. }
  5670. this._repaintDeleteButton(dom.point);
  5671. // update class
  5672. var className = (this.data.className? ' ' + this.data.className : '') +
  5673. (this.selected ? ' selected' : '');
  5674. if (this.className != className) {
  5675. this.className = className;
  5676. dom.point.className = 'item point' + className;
  5677. changed = true;
  5678. }
  5679. }
  5680. return changed;
  5681. };
  5682. /**
  5683. * Show the item in the DOM (when not already visible). The items DOM will
  5684. * be created when needed.
  5685. * @return {Boolean} changed
  5686. */
  5687. ItemPoint.prototype.show = function show() {
  5688. if (!this.dom || !this.dom.point.parentNode) {
  5689. return this.repaint();
  5690. }
  5691. else {
  5692. return false;
  5693. }
  5694. };
  5695. /**
  5696. * Hide the item from the DOM (when visible)
  5697. * @return {Boolean} changed
  5698. */
  5699. ItemPoint.prototype.hide = function hide() {
  5700. var changed = false,
  5701. dom = this.dom;
  5702. if (dom) {
  5703. if (dom.point.parentNode) {
  5704. dom.point.parentNode.removeChild(dom.point);
  5705. changed = true;
  5706. }
  5707. }
  5708. return changed;
  5709. };
  5710. /**
  5711. * Reflow the item: calculate its actual size from the DOM
  5712. * @return {boolean} resized returns true if the axis is resized
  5713. * @override
  5714. */
  5715. ItemPoint.prototype.reflow = function reflow() {
  5716. var changed = 0,
  5717. update,
  5718. dom,
  5719. props,
  5720. options,
  5721. margin,
  5722. orientation,
  5723. start,
  5724. top,
  5725. data,
  5726. range;
  5727. if (this.data.start == undefined) {
  5728. throw new Error('Property "start" missing in item ' + this.data.id);
  5729. }
  5730. data = this.data;
  5731. range = this.parent && this.parent.range;
  5732. if (data && range) {
  5733. // TODO: account for the width of the item
  5734. var interval = (range.end - range.start);
  5735. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  5736. }
  5737. else {
  5738. this.visible = false;
  5739. }
  5740. if (this.visible) {
  5741. dom = this.dom;
  5742. if (dom) {
  5743. update = util.updateProperty;
  5744. props = this.props;
  5745. options = this.options;
  5746. orientation = options.orientation || this.defaultOptions.orientation;
  5747. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5748. start = this.parent.toScreen(this.data.start) + this.offset;
  5749. changed += update(this, 'width', dom.point.offsetWidth);
  5750. changed += update(this, 'height', dom.point.offsetHeight);
  5751. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5752. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5753. changed += update(props.content, 'height', dom.content.offsetHeight);
  5754. if (orientation == 'top') {
  5755. top = margin;
  5756. }
  5757. else {
  5758. // default or 'bottom'
  5759. var parentHeight = this.parent.height;
  5760. top = Math.max(parentHeight - this.height - margin, 0);
  5761. }
  5762. changed += update(this, 'top', top);
  5763. changed += update(this, 'left', start - props.dot.width / 2);
  5764. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5765. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5766. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5767. }
  5768. else {
  5769. changed += 1;
  5770. }
  5771. }
  5772. return (changed > 0);
  5773. };
  5774. /**
  5775. * Create an items DOM
  5776. * @private
  5777. */
  5778. ItemPoint.prototype._create = function _create() {
  5779. var dom = this.dom;
  5780. if (!dom) {
  5781. this.dom = dom = {};
  5782. // background box
  5783. dom.point = document.createElement('div');
  5784. // className is updated in repaint()
  5785. // contents box, right from the dot
  5786. dom.content = document.createElement('div');
  5787. dom.content.className = 'content';
  5788. dom.point.appendChild(dom.content);
  5789. // dot at start
  5790. dom.dot = document.createElement('div');
  5791. dom.dot.className = 'dot';
  5792. dom.point.appendChild(dom.dot);
  5793. // attach this item as attribute
  5794. dom.point['timeline-item'] = this;
  5795. }
  5796. };
  5797. /**
  5798. * Reposition the item, recalculate its left, top, and width, using the current
  5799. * range and size of the items itemset
  5800. * @override
  5801. */
  5802. ItemPoint.prototype.reposition = function reposition() {
  5803. var dom = this.dom,
  5804. props = this.props;
  5805. if (dom) {
  5806. dom.point.style.top = this.top + 'px';
  5807. dom.point.style.left = this.left + 'px';
  5808. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5809. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5810. dom.dot.style.top = props.dot.top + 'px';
  5811. }
  5812. };
  5813. /**
  5814. * @constructor ItemRange
  5815. * @extends Item
  5816. * @param {ItemSet} parent
  5817. * @param {Object} data Object containing parameters start, end
  5818. * content, className.
  5819. * @param {Object} [options] Options to set initial property values
  5820. * @param {Object} [defaultOptions] default options
  5821. * // TODO: describe available options
  5822. */
  5823. function ItemRange (parent, data, options, defaultOptions) {
  5824. this.props = {
  5825. content: {
  5826. left: 0,
  5827. width: 0
  5828. }
  5829. };
  5830. Item.call(this, parent, data, options, defaultOptions);
  5831. }
  5832. ItemRange.prototype = new Item (null, null);
  5833. /**
  5834. * Repaint the item
  5835. * @return {Boolean} changed
  5836. */
  5837. ItemRange.prototype.repaint = function repaint() {
  5838. // TODO: make an efficient repaint
  5839. var changed = false;
  5840. var dom = this.dom;
  5841. if (!dom) {
  5842. this._create();
  5843. dom = this.dom;
  5844. changed = true;
  5845. }
  5846. if (dom) {
  5847. if (!this.parent) {
  5848. throw new Error('Cannot repaint item: no parent attached');
  5849. }
  5850. var foreground = this.parent.getForeground();
  5851. if (!foreground) {
  5852. throw new Error('Cannot repaint time axis: ' +
  5853. 'parent has no foreground container element');
  5854. }
  5855. if (!dom.box.parentNode) {
  5856. foreground.appendChild(dom.box);
  5857. changed = true;
  5858. }
  5859. // update content
  5860. if (this.data.content != this.content) {
  5861. this.content = this.data.content;
  5862. if (this.content instanceof Element) {
  5863. dom.content.innerHTML = '';
  5864. dom.content.appendChild(this.content);
  5865. }
  5866. else if (this.data.content != undefined) {
  5867. dom.content.innerHTML = this.content;
  5868. }
  5869. else {
  5870. throw new Error('Property "content" missing in item ' + this.data.id);
  5871. }
  5872. changed = true;
  5873. }
  5874. this._repaintDeleteButton(dom.box);
  5875. this._repaintDragLeft();
  5876. this._repaintDragRight();
  5877. // update class
  5878. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5879. (this.selected ? ' selected' : '');
  5880. if (this.className != className) {
  5881. this.className = className;
  5882. dom.box.className = 'item range' + className;
  5883. changed = true;
  5884. }
  5885. }
  5886. return changed;
  5887. };
  5888. /**
  5889. * Show the item in the DOM (when not already visible). The items DOM will
  5890. * be created when needed.
  5891. * @return {Boolean} changed
  5892. */
  5893. ItemRange.prototype.show = function show() {
  5894. if (!this.dom || !this.dom.box.parentNode) {
  5895. return this.repaint();
  5896. }
  5897. else {
  5898. return false;
  5899. }
  5900. };
  5901. /**
  5902. * Hide the item from the DOM (when visible)
  5903. * @return {Boolean} changed
  5904. */
  5905. ItemRange.prototype.hide = function hide() {
  5906. var changed = false,
  5907. dom = this.dom;
  5908. if (dom) {
  5909. if (dom.box.parentNode) {
  5910. dom.box.parentNode.removeChild(dom.box);
  5911. changed = true;
  5912. }
  5913. }
  5914. return changed;
  5915. };
  5916. /**
  5917. * Reflow the item: calculate its actual size from the DOM
  5918. * @return {boolean} resized returns true if the axis is resized
  5919. * @override
  5920. */
  5921. ItemRange.prototype.reflow = function reflow() {
  5922. var changed = 0,
  5923. dom,
  5924. props,
  5925. options,
  5926. margin,
  5927. padding,
  5928. parent,
  5929. start,
  5930. end,
  5931. data,
  5932. range,
  5933. update,
  5934. box,
  5935. parentWidth,
  5936. contentLeft,
  5937. orientation,
  5938. top;
  5939. if (this.data.start == undefined) {
  5940. throw new Error('Property "start" missing in item ' + this.data.id);
  5941. }
  5942. if (this.data.end == undefined) {
  5943. throw new Error('Property "end" missing in item ' + this.data.id);
  5944. }
  5945. data = this.data;
  5946. range = this.parent && this.parent.range;
  5947. if (data && range) {
  5948. // TODO: account for the width of the item. Take some margin
  5949. this.visible = (data.start < range.end) && (data.end > range.start);
  5950. }
  5951. else {
  5952. this.visible = false;
  5953. }
  5954. if (this.visible) {
  5955. dom = this.dom;
  5956. if (dom) {
  5957. props = this.props;
  5958. options = this.options;
  5959. parent = this.parent;
  5960. start = parent.toScreen(this.data.start) + this.offset;
  5961. end = parent.toScreen(this.data.end) + this.offset;
  5962. update = util.updateProperty;
  5963. box = dom.box;
  5964. parentWidth = parent.width;
  5965. orientation = options.orientation || this.defaultOptions.orientation;
  5966. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5967. padding = options.padding || this.defaultOptions.padding;
  5968. changed += update(props.content, 'width', dom.content.offsetWidth);
  5969. changed += update(this, 'height', box.offsetHeight);
  5970. // limit the width of the this, as browsers cannot draw very wide divs
  5971. if (start < -parentWidth) {
  5972. start = -parentWidth;
  5973. }
  5974. if (end > 2 * parentWidth) {
  5975. end = 2 * parentWidth;
  5976. }
  5977. // when range exceeds left of the window, position the contents at the left of the visible area
  5978. if (start < 0) {
  5979. contentLeft = Math.min(-start,
  5980. (end - start - props.content.width - 2 * padding));
  5981. // TODO: remove the need for options.padding. it's terrible.
  5982. }
  5983. else {
  5984. contentLeft = 0;
  5985. }
  5986. changed += update(props.content, 'left', contentLeft);
  5987. if (orientation == 'top') {
  5988. top = margin;
  5989. changed += update(this, 'top', top);
  5990. }
  5991. else {
  5992. // default or 'bottom'
  5993. top = parent.height - this.height - margin;
  5994. changed += update(this, 'top', top);
  5995. }
  5996. changed += update(this, 'left', start);
  5997. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  5998. }
  5999. else {
  6000. changed += 1;
  6001. }
  6002. }
  6003. return (changed > 0);
  6004. };
  6005. /**
  6006. * Create an items DOM
  6007. * @private
  6008. */
  6009. ItemRange.prototype._create = function _create() {
  6010. var dom = this.dom;
  6011. if (!dom) {
  6012. this.dom = dom = {};
  6013. // background box
  6014. dom.box = document.createElement('div');
  6015. // className is updated in repaint()
  6016. // contents box
  6017. dom.content = document.createElement('div');
  6018. dom.content.className = 'content';
  6019. dom.box.appendChild(dom.content);
  6020. // attach this item as attribute
  6021. dom.box['timeline-item'] = this;
  6022. }
  6023. };
  6024. /**
  6025. * Reposition the item, recalculate its left, top, and width, using the current
  6026. * range and size of the items itemset
  6027. * @override
  6028. */
  6029. ItemRange.prototype.reposition = function reposition() {
  6030. var dom = this.dom,
  6031. props = this.props;
  6032. if (dom) {
  6033. dom.box.style.top = this.top + 'px';
  6034. dom.box.style.left = this.left + 'px';
  6035. dom.box.style.width = this.width + 'px';
  6036. dom.content.style.left = props.content.left + 'px';
  6037. }
  6038. };
  6039. /**
  6040. * Repaint a drag area on the left side of the range when the range is selected
  6041. * @private
  6042. */
  6043. ItemRange.prototype._repaintDragLeft = function () {
  6044. if (this.selected && this.options.editable && !this.dom.dragLeft) {
  6045. // create and show drag area
  6046. var dragLeft = document.createElement('div');
  6047. dragLeft.className = 'drag-left';
  6048. dragLeft.dragLeftItem = this;
  6049. // TODO: this should be redundant?
  6050. Hammer(dragLeft, {
  6051. preventDefault: true
  6052. }).on('drag', function () {
  6053. //console.log('drag left')
  6054. });
  6055. this.dom.box.appendChild(dragLeft);
  6056. this.dom.dragLeft = dragLeft;
  6057. }
  6058. else if (!this.selected && this.dom.dragLeft) {
  6059. // delete drag area
  6060. if (this.dom.dragLeft.parentNode) {
  6061. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  6062. }
  6063. this.dom.dragLeft = null;
  6064. }
  6065. };
  6066. /**
  6067. * Repaint a drag area on the right side of the range when the range is selected
  6068. * @private
  6069. */
  6070. ItemRange.prototype._repaintDragRight = function () {
  6071. if (this.selected && this.options.editable && !this.dom.dragRight) {
  6072. // create and show drag area
  6073. var dragRight = document.createElement('div');
  6074. dragRight.className = 'drag-right';
  6075. dragRight.dragRightItem = this;
  6076. // TODO: this should be redundant?
  6077. Hammer(dragRight, {
  6078. preventDefault: true
  6079. }).on('drag', function () {
  6080. //console.log('drag right')
  6081. });
  6082. this.dom.box.appendChild(dragRight);
  6083. this.dom.dragRight = dragRight;
  6084. }
  6085. else if (!this.selected && this.dom.dragRight) {
  6086. // delete drag area
  6087. if (this.dom.dragRight.parentNode) {
  6088. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  6089. }
  6090. this.dom.dragRight = null;
  6091. }
  6092. };
  6093. /**
  6094. * @constructor ItemRangeOverflow
  6095. * @extends ItemRange
  6096. * @param {ItemSet} parent
  6097. * @param {Object} data Object containing parameters start, end
  6098. * content, className.
  6099. * @param {Object} [options] Options to set initial property values
  6100. * @param {Object} [defaultOptions] default options
  6101. * // TODO: describe available options
  6102. */
  6103. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  6104. this.props = {
  6105. content: {
  6106. left: 0,
  6107. width: 0
  6108. }
  6109. };
  6110. // define a private property _width, which is the with of the range box
  6111. // adhering to the ranges start and end date. The property width has a
  6112. // getter which returns the max of border width and content width
  6113. this._width = 0;
  6114. Object.defineProperty(this, 'width', {
  6115. get: function () {
  6116. return (this.props.content && this._width < this.props.content.width) ?
  6117. this.props.content.width :
  6118. this._width;
  6119. },
  6120. set: function (width) {
  6121. this._width = width;
  6122. }
  6123. });
  6124. ItemRange.call(this, parent, data, options, defaultOptions);
  6125. }
  6126. ItemRangeOverflow.prototype = new ItemRange (null, null);
  6127. /**
  6128. * Repaint the item
  6129. * @return {Boolean} changed
  6130. */
  6131. ItemRangeOverflow.prototype.repaint = function repaint() {
  6132. // TODO: make an efficient repaint
  6133. var changed = false;
  6134. var dom = this.dom;
  6135. if (!dom) {
  6136. this._create();
  6137. dom = this.dom;
  6138. changed = true;
  6139. }
  6140. if (dom) {
  6141. if (!this.parent) {
  6142. throw new Error('Cannot repaint item: no parent attached');
  6143. }
  6144. var foreground = this.parent.getForeground();
  6145. if (!foreground) {
  6146. throw new Error('Cannot repaint time axis: ' +
  6147. 'parent has no foreground container element');
  6148. }
  6149. if (!dom.box.parentNode) {
  6150. foreground.appendChild(dom.box);
  6151. changed = true;
  6152. }
  6153. // update content
  6154. if (this.data.content != this.content) {
  6155. this.content = this.data.content;
  6156. if (this.content instanceof Element) {
  6157. dom.content.innerHTML = '';
  6158. dom.content.appendChild(this.content);
  6159. }
  6160. else if (this.data.content != undefined) {
  6161. dom.content.innerHTML = this.content;
  6162. }
  6163. else {
  6164. throw new Error('Property "content" missing in item ' + this.id);
  6165. }
  6166. changed = true;
  6167. }
  6168. this._repaintDeleteButton(dom.box);
  6169. this._repaintDragLeft();
  6170. this._repaintDragRight();
  6171. // update class
  6172. var className = (this.data.className? ' ' + this.data.className : '') +
  6173. (this.selected ? ' selected' : '');
  6174. if (this.className != className) {
  6175. this.className = className;
  6176. dom.box.className = 'item rangeoverflow' + className;
  6177. changed = true;
  6178. }
  6179. }
  6180. return changed;
  6181. };
  6182. /**
  6183. * Reposition the item, recalculate its left, top, and width, using the current
  6184. * range and size of the items itemset
  6185. * @override
  6186. */
  6187. ItemRangeOverflow.prototype.reposition = function reposition() {
  6188. var dom = this.dom,
  6189. props = this.props;
  6190. if (dom) {
  6191. dom.box.style.top = this.top + 'px';
  6192. dom.box.style.left = this.left + 'px';
  6193. dom.box.style.width = this._width + 'px';
  6194. dom.content.style.left = props.content.left + 'px';
  6195. }
  6196. };
  6197. /**
  6198. * @constructor Group
  6199. * @param {GroupSet} parent
  6200. * @param {Number | String} groupId
  6201. * @param {Object} [options] Options to set initial property values
  6202. * // TODO: describe available options
  6203. * @extends Component
  6204. */
  6205. function Group (parent, groupId, options) {
  6206. this.id = util.randomUUID();
  6207. this.parent = parent;
  6208. this.groupId = groupId;
  6209. this.itemset = null; // ItemSet
  6210. this.options = options || {};
  6211. this.options.top = 0;
  6212. this.props = {
  6213. label: {
  6214. width: 0,
  6215. height: 0
  6216. }
  6217. };
  6218. this.top = 0;
  6219. this.left = 0;
  6220. this.width = 0;
  6221. this.height = 0;
  6222. }
  6223. Group.prototype = new Component();
  6224. // TODO: comment
  6225. Group.prototype.setOptions = Component.prototype.setOptions;
  6226. /**
  6227. * Get the container element of the panel, which can be used by a child to
  6228. * add its own widgets.
  6229. * @returns {HTMLElement} container
  6230. */
  6231. Group.prototype.getContainer = function () {
  6232. return this.parent.getContainer();
  6233. };
  6234. /**
  6235. * Set item set for the group. The group will create a view on the itemset,
  6236. * filtered by the groups id.
  6237. * @param {DataSet | DataView} items
  6238. */
  6239. Group.prototype.setItems = function setItems(items) {
  6240. if (this.itemset) {
  6241. // remove current item set
  6242. this.itemset.hide();
  6243. this.itemset.setItems();
  6244. this.parent.controller.remove(this.itemset);
  6245. this.itemset = null;
  6246. }
  6247. if (items) {
  6248. var groupId = this.groupId;
  6249. var itemsetOptions = Object.create(this.options);
  6250. this.itemset = new ItemSet(this, null, itemsetOptions);
  6251. this.itemset.setRange(this.parent.range);
  6252. this.view = new DataView(items, {
  6253. filter: function (item) {
  6254. return item.group == groupId;
  6255. }
  6256. });
  6257. this.itemset.setItems(this.view);
  6258. this.parent.controller.add(this.itemset);
  6259. }
  6260. };
  6261. /**
  6262. * Set selected items by their id. Replaces the current selection.
  6263. * Unknown id's are silently ignored.
  6264. * @param {Array} [ids] An array with zero or more id's of the items to be
  6265. * selected. If ids is an empty array, all items will be
  6266. * unselected.
  6267. */
  6268. Group.prototype.setSelection = function setSelection(ids) {
  6269. if (this.itemset) this.itemset.setSelection(ids);
  6270. };
  6271. /**
  6272. * Get the selected items by their id
  6273. * @return {Array} ids The ids of the selected items
  6274. */
  6275. Group.prototype.getSelection = function getSelection() {
  6276. return this.itemset ? this.itemset.getSelection() : [];
  6277. };
  6278. /**
  6279. * Repaint the item
  6280. * @return {Boolean} changed
  6281. */
  6282. Group.prototype.repaint = function repaint() {
  6283. return false;
  6284. };
  6285. /**
  6286. * Reflow the item
  6287. * @return {Boolean} resized
  6288. */
  6289. Group.prototype.reflow = function reflow() {
  6290. var changed = 0,
  6291. update = util.updateProperty;
  6292. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  6293. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  6294. // TODO: reckon with the height of the group label
  6295. if (this.label) {
  6296. var inner = this.label.firstChild;
  6297. changed += update(this.props.label, 'width', inner.clientWidth);
  6298. changed += update(this.props.label, 'height', inner.clientHeight);
  6299. }
  6300. else {
  6301. changed += update(this.props.label, 'width', 0);
  6302. changed += update(this.props.label, 'height', 0);
  6303. }
  6304. return (changed > 0);
  6305. };
  6306. /**
  6307. * An GroupSet holds a set of groups
  6308. * @param {Component} parent
  6309. * @param {Component[]} [depends] Components on which this components depends
  6310. * (except for the parent)
  6311. * @param {Object} [options] See GroupSet.setOptions for the available
  6312. * options.
  6313. * @constructor GroupSet
  6314. * @extends Panel
  6315. */
  6316. function GroupSet(parent, depends, options) {
  6317. this.id = util.randomUUID();
  6318. this.parent = parent;
  6319. this.depends = depends;
  6320. this.options = options || {};
  6321. this.range = null; // Range or Object {start: number, end: number}
  6322. this.itemsData = null; // DataSet with items
  6323. this.groupsData = null; // DataSet with groups
  6324. this.groups = {}; // map with groups
  6325. this.dom = {};
  6326. this.props = {
  6327. labels: {
  6328. width: 0
  6329. }
  6330. };
  6331. // TODO: implement right orientation of the labels
  6332. // changes in groups are queued key/value map containing id/action
  6333. this.queue = {};
  6334. var me = this;
  6335. this.listeners = {
  6336. 'add': function (event, params) {
  6337. me._onAdd(params.items);
  6338. },
  6339. 'update': function (event, params) {
  6340. me._onUpdate(params.items);
  6341. },
  6342. 'remove': function (event, params) {
  6343. me._onRemove(params.items);
  6344. }
  6345. };
  6346. }
  6347. GroupSet.prototype = new Panel();
  6348. /**
  6349. * Set options for the GroupSet. Existing options will be extended/overwritten.
  6350. * @param {Object} [options] The following options are available:
  6351. * {String | function} groupsOrder
  6352. * TODO: describe options
  6353. */
  6354. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  6355. GroupSet.prototype.setRange = function (range) {
  6356. // TODO: implement setRange
  6357. };
  6358. /**
  6359. * Set items
  6360. * @param {vis.DataSet | null} items
  6361. */
  6362. GroupSet.prototype.setItems = function setItems(items) {
  6363. this.itemsData = items;
  6364. for (var id in this.groups) {
  6365. if (this.groups.hasOwnProperty(id)) {
  6366. var group = this.groups[id];
  6367. group.setItems(items);
  6368. }
  6369. }
  6370. };
  6371. /**
  6372. * Get items
  6373. * @return {vis.DataSet | null} items
  6374. */
  6375. GroupSet.prototype.getItems = function getItems() {
  6376. return this.itemsData;
  6377. };
  6378. /**
  6379. * Set range (start and end).
  6380. * @param {Range | Object} range A Range or an object containing start and end.
  6381. */
  6382. GroupSet.prototype.setRange = function setRange(range) {
  6383. this.range = range;
  6384. };
  6385. /**
  6386. * Set groups
  6387. * @param {vis.DataSet} groups
  6388. */
  6389. GroupSet.prototype.setGroups = function setGroups(groups) {
  6390. var me = this,
  6391. ids;
  6392. // unsubscribe from current dataset
  6393. if (this.groupsData) {
  6394. util.forEach(this.listeners, function (callback, event) {
  6395. me.groupsData.unsubscribe(event, callback);
  6396. });
  6397. // remove all drawn groups
  6398. ids = this.groupsData.getIds();
  6399. this._onRemove(ids);
  6400. }
  6401. // replace the dataset
  6402. if (!groups) {
  6403. this.groupsData = null;
  6404. }
  6405. else if (groups instanceof DataSet) {
  6406. this.groupsData = groups;
  6407. }
  6408. else {
  6409. this.groupsData = new DataSet({
  6410. convert: {
  6411. start: 'Date',
  6412. end: 'Date'
  6413. }
  6414. });
  6415. this.groupsData.add(groups);
  6416. }
  6417. if (this.groupsData) {
  6418. // subscribe to new dataset
  6419. var id = this.id;
  6420. util.forEach(this.listeners, function (callback, event) {
  6421. me.groupsData.on(event, callback, id);
  6422. });
  6423. // draw all new groups
  6424. ids = this.groupsData.getIds();
  6425. this._onAdd(ids);
  6426. }
  6427. };
  6428. /**
  6429. * Get groups
  6430. * @return {vis.DataSet | null} groups
  6431. */
  6432. GroupSet.prototype.getGroups = function getGroups() {
  6433. return this.groupsData;
  6434. };
  6435. /**
  6436. * Set selected items by their id. Replaces the current selection.
  6437. * Unknown id's are silently ignored.
  6438. * @param {Array} [ids] An array with zero or more id's of the items to be
  6439. * selected. If ids is an empty array, all items will be
  6440. * unselected.
  6441. */
  6442. GroupSet.prototype.setSelection = function setSelection(ids) {
  6443. var selection = [],
  6444. groups = this.groups;
  6445. // iterate over each of the groups
  6446. for (var id in groups) {
  6447. if (groups.hasOwnProperty(id)) {
  6448. var group = groups[id];
  6449. group.setSelection(ids);
  6450. }
  6451. }
  6452. return selection;
  6453. };
  6454. /**
  6455. * Get the selected items by their id
  6456. * @return {Array} ids The ids of the selected items
  6457. */
  6458. GroupSet.prototype.getSelection = function getSelection() {
  6459. var selection = [],
  6460. groups = this.groups;
  6461. // iterate over each of the groups
  6462. for (var id in groups) {
  6463. if (groups.hasOwnProperty(id)) {
  6464. var group = groups[id];
  6465. selection = selection.concat(group.getSelection());
  6466. }
  6467. }
  6468. return selection;
  6469. };
  6470. /**
  6471. * Repaint the component
  6472. * @return {Boolean} changed
  6473. */
  6474. GroupSet.prototype.repaint = function repaint() {
  6475. var changed = 0,
  6476. i, id, group, label,
  6477. update = util.updateProperty,
  6478. asSize = util.option.asSize,
  6479. asElement = util.option.asElement,
  6480. options = this.options,
  6481. frame = this.dom.frame,
  6482. labels = this.dom.labels,
  6483. labelSet = this.dom.labelSet;
  6484. // create frame
  6485. if (!this.parent) {
  6486. throw new Error('Cannot repaint groupset: no parent attached');
  6487. }
  6488. var parentContainer = this.parent.getContainer();
  6489. if (!parentContainer) {
  6490. throw new Error('Cannot repaint groupset: parent has no container element');
  6491. }
  6492. if (!frame) {
  6493. frame = document.createElement('div');
  6494. frame.className = 'groupset';
  6495. frame['timeline-groupset'] = this;
  6496. this.dom.frame = frame;
  6497. var className = options.className;
  6498. if (className) {
  6499. util.addClassName(frame, util.option.asString(className));
  6500. }
  6501. changed += 1;
  6502. }
  6503. if (!frame.parentNode) {
  6504. parentContainer.appendChild(frame);
  6505. changed += 1;
  6506. }
  6507. // create labels
  6508. var labelContainer = asElement(options.labelContainer);
  6509. if (!labelContainer) {
  6510. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  6511. }
  6512. if (!labels) {
  6513. labels = document.createElement('div');
  6514. labels.className = 'labels';
  6515. this.dom.labels = labels;
  6516. }
  6517. if (!labelSet) {
  6518. labelSet = document.createElement('div');
  6519. labelSet.className = 'label-set';
  6520. labels.appendChild(labelSet);
  6521. this.dom.labelSet = labelSet;
  6522. }
  6523. if (!labels.parentNode || labels.parentNode != labelContainer) {
  6524. if (labels.parentNode) {
  6525. labels.parentNode.removeChild(labels.parentNode);
  6526. }
  6527. labelContainer.appendChild(labels);
  6528. }
  6529. // reposition frame
  6530. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  6531. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6532. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6533. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6534. // reposition labels
  6535. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  6536. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  6537. var me = this,
  6538. queue = this.queue,
  6539. groups = this.groups,
  6540. groupsData = this.groupsData;
  6541. // show/hide added/changed/removed groups
  6542. var ids = Object.keys(queue);
  6543. if (ids.length) {
  6544. ids.forEach(function (id) {
  6545. var action = queue[id];
  6546. var group = groups[id];
  6547. //noinspection FallthroughInSwitchStatementJS
  6548. switch (action) {
  6549. case 'add':
  6550. case 'update':
  6551. if (!group) {
  6552. var groupOptions = Object.create(me.options);
  6553. util.extend(groupOptions, {
  6554. height: null,
  6555. maxHeight: null
  6556. });
  6557. group = new Group(me, id, groupOptions);
  6558. group.setItems(me.itemsData); // attach items data
  6559. groups[id] = group;
  6560. me.controller.add(group);
  6561. }
  6562. // TODO: update group data
  6563. group.data = groupsData.get(id);
  6564. delete queue[id];
  6565. break;
  6566. case 'remove':
  6567. if (group) {
  6568. group.setItems(); // detach items data
  6569. delete groups[id];
  6570. me.controller.remove(group);
  6571. }
  6572. // update lists
  6573. delete queue[id];
  6574. break;
  6575. default:
  6576. console.log('Error: unknown action "' + action + '"');
  6577. }
  6578. });
  6579. // the groupset depends on each of the groups
  6580. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  6581. // TODO: apply dependencies of the groupset
  6582. // update the top positions of the groups in the correct order
  6583. var orderedGroups = this.groupsData.getIds({
  6584. order: this.options.groupOrder
  6585. });
  6586. for (i = 0; i < orderedGroups.length; i++) {
  6587. (function (group, prevGroup) {
  6588. var top = 0;
  6589. if (prevGroup) {
  6590. top = function () {
  6591. // TODO: top must reckon with options.maxHeight
  6592. return prevGroup.top + prevGroup.height;
  6593. }
  6594. }
  6595. group.setOptions({
  6596. top: top
  6597. });
  6598. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  6599. }
  6600. // (re)create the labels
  6601. while (labelSet.firstChild) {
  6602. labelSet.removeChild(labelSet.firstChild);
  6603. }
  6604. for (i = 0; i < orderedGroups.length; i++) {
  6605. id = orderedGroups[i];
  6606. label = this._createLabel(id);
  6607. labelSet.appendChild(label);
  6608. }
  6609. changed++;
  6610. }
  6611. // reposition the labels
  6612. // TODO: labels are not displayed correctly when orientation=='top'
  6613. // TODO: width of labelPanel is not immediately updated on a change in groups
  6614. for (id in groups) {
  6615. if (groups.hasOwnProperty(id)) {
  6616. group = groups[id];
  6617. label = group.label;
  6618. if (label) {
  6619. label.style.top = group.top + 'px';
  6620. label.style.height = group.height + 'px';
  6621. }
  6622. }
  6623. }
  6624. return (changed > 0);
  6625. };
  6626. /**
  6627. * Create a label for group with given id
  6628. * @param {Number} id
  6629. * @return {Element} label
  6630. * @private
  6631. */
  6632. GroupSet.prototype._createLabel = function(id) {
  6633. var group = this.groups[id];
  6634. var label = document.createElement('div');
  6635. label.className = 'vlabel';
  6636. var inner = document.createElement('div');
  6637. inner.className = 'inner';
  6638. label.appendChild(inner);
  6639. var content = group.data && group.data.content;
  6640. if (content instanceof Element) {
  6641. inner.appendChild(content);
  6642. }
  6643. else if (content != undefined) {
  6644. inner.innerHTML = content;
  6645. }
  6646. var className = group.data && group.data.className;
  6647. if (className) {
  6648. util.addClassName(label, className);
  6649. }
  6650. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  6651. return label;
  6652. };
  6653. /**
  6654. * Get container element
  6655. * @return {HTMLElement} container
  6656. */
  6657. GroupSet.prototype.getContainer = function getContainer() {
  6658. return this.dom.frame;
  6659. };
  6660. /**
  6661. * Get the width of the group labels
  6662. * @return {Number} width
  6663. */
  6664. GroupSet.prototype.getLabelsWidth = function getContainer() {
  6665. return this.props.labels.width;
  6666. };
  6667. /**
  6668. * Reflow the component
  6669. * @return {Boolean} resized
  6670. */
  6671. GroupSet.prototype.reflow = function reflow() {
  6672. var changed = 0,
  6673. id, group,
  6674. options = this.options,
  6675. update = util.updateProperty,
  6676. asNumber = util.option.asNumber,
  6677. asSize = util.option.asSize,
  6678. frame = this.dom.frame;
  6679. if (frame) {
  6680. var maxHeight = asNumber(options.maxHeight);
  6681. var fixedHeight = (asSize(options.height) != null);
  6682. var height;
  6683. if (fixedHeight) {
  6684. height = frame.offsetHeight;
  6685. }
  6686. else {
  6687. // height is not specified, calculate the sum of the height of all groups
  6688. height = 0;
  6689. for (id in this.groups) {
  6690. if (this.groups.hasOwnProperty(id)) {
  6691. group = this.groups[id];
  6692. height += group.height;
  6693. }
  6694. }
  6695. }
  6696. if (maxHeight != null) {
  6697. height = Math.min(height, maxHeight);
  6698. }
  6699. changed += update(this, 'height', height);
  6700. changed += update(this, 'top', frame.offsetTop);
  6701. changed += update(this, 'left', frame.offsetLeft);
  6702. changed += update(this, 'width', frame.offsetWidth);
  6703. }
  6704. // calculate the maximum width of the labels
  6705. var width = 0;
  6706. for (id in this.groups) {
  6707. if (this.groups.hasOwnProperty(id)) {
  6708. group = this.groups[id];
  6709. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  6710. width = Math.max(width, labelWidth);
  6711. }
  6712. }
  6713. changed += update(this.props.labels, 'width', width);
  6714. return (changed > 0);
  6715. };
  6716. /**
  6717. * Hide the component from the DOM
  6718. * @return {Boolean} changed
  6719. */
  6720. GroupSet.prototype.hide = function hide() {
  6721. if (this.dom.frame && this.dom.frame.parentNode) {
  6722. this.dom.frame.parentNode.removeChild(this.dom.frame);
  6723. return true;
  6724. }
  6725. else {
  6726. return false;
  6727. }
  6728. };
  6729. /**
  6730. * Show the component in the DOM (when not already visible).
  6731. * A repaint will be executed when the component is not visible
  6732. * @return {Boolean} changed
  6733. */
  6734. GroupSet.prototype.show = function show() {
  6735. if (!this.dom.frame || !this.dom.frame.parentNode) {
  6736. return this.repaint();
  6737. }
  6738. else {
  6739. return false;
  6740. }
  6741. };
  6742. /**
  6743. * Handle updated groups
  6744. * @param {Number[]} ids
  6745. * @private
  6746. */
  6747. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  6748. this._toQueue(ids, 'update');
  6749. };
  6750. /**
  6751. * Handle changed groups
  6752. * @param {Number[]} ids
  6753. * @private
  6754. */
  6755. GroupSet.prototype._onAdd = function _onAdd(ids) {
  6756. this._toQueue(ids, 'add');
  6757. };
  6758. /**
  6759. * Handle removed groups
  6760. * @param {Number[]} ids
  6761. * @private
  6762. */
  6763. GroupSet.prototype._onRemove = function _onRemove(ids) {
  6764. this._toQueue(ids, 'remove');
  6765. };
  6766. /**
  6767. * Put groups in the queue to be added/updated/remove
  6768. * @param {Number[]} ids
  6769. * @param {String} action can be 'add', 'update', 'remove'
  6770. */
  6771. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  6772. var queue = this.queue;
  6773. ids.forEach(function (id) {
  6774. queue[id] = action;
  6775. });
  6776. if (this.controller) {
  6777. //this.requestReflow();
  6778. this.requestRepaint();
  6779. }
  6780. };
  6781. /**
  6782. * Find the Group from an event target:
  6783. * searches for the attribute 'timeline-groupset' in the event target's element
  6784. * tree, then finds the right group in this groupset
  6785. * @param {Event} event
  6786. * @return {Group | null} group
  6787. */
  6788. GroupSet.groupFromTarget = function groupFromTarget (event) {
  6789. var groupset,
  6790. target = event.target;
  6791. while (target) {
  6792. if (target.hasOwnProperty('timeline-groupset')) {
  6793. groupset = target['timeline-groupset'];
  6794. break;
  6795. }
  6796. target = target.parentNode;
  6797. }
  6798. if (groupset) {
  6799. for (var groupId in groupset.groups) {
  6800. if (groupset.groups.hasOwnProperty(groupId)) {
  6801. var group = groupset.groups[groupId];
  6802. if (group.itemset && ItemSet.itemSetFromTarget(event) == group.itemset) {
  6803. return group;
  6804. }
  6805. }
  6806. }
  6807. }
  6808. return null;
  6809. };
  6810. /**
  6811. * Create a timeline visualization
  6812. * @param {HTMLElement} container
  6813. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6814. * @param {Object} [options] See Timeline.setOptions for the available options.
  6815. * @constructor
  6816. */
  6817. function Timeline (container, items, options) {
  6818. var me = this;
  6819. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6820. this.options = {
  6821. orientation: 'bottom',
  6822. autoResize: true,
  6823. editable: false,
  6824. selectable: true,
  6825. snap: null, // will be specified after timeaxis is created
  6826. min: null,
  6827. max: null,
  6828. zoomMin: 10, // milliseconds
  6829. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6830. // moveable: true, // TODO: option moveable
  6831. // zoomable: true, // TODO: option zoomable
  6832. showMinorLabels: true,
  6833. showMajorLabels: true,
  6834. showCurrentTime: false,
  6835. showCustomTime: false,
  6836. onAdd: function (item, callback) {
  6837. callback(item);
  6838. },
  6839. onUpdate: function (item, callback) {
  6840. callback(item);
  6841. },
  6842. onMove: function (item, callback) {
  6843. callback(item);
  6844. },
  6845. onRemove: function (item, callback) {
  6846. callback(item);
  6847. }
  6848. };
  6849. // controller
  6850. this.controller = new Controller();
  6851. // root panel
  6852. if (!container) {
  6853. throw new Error('No container element provided');
  6854. }
  6855. var rootOptions = Object.create(this.options);
  6856. rootOptions.height = function () {
  6857. // TODO: change to height
  6858. if (me.options.height) {
  6859. // fixed height
  6860. return me.options.height;
  6861. }
  6862. else {
  6863. // auto height
  6864. return (me.timeaxis.height + me.content.height) + 'px';
  6865. }
  6866. };
  6867. this.rootPanel = new RootPanel(container, rootOptions);
  6868. this.controller.add(this.rootPanel);
  6869. // single select (or unselect) when tapping an item
  6870. this.controller.on('tap', this._onSelectItem.bind(this));
  6871. // multi select when holding mouse/touch, or on ctrl+click
  6872. this.controller.on('hold', this._onMultiSelectItem.bind(this));
  6873. // add item on doubletap
  6874. this.controller.on('doubletap', this._onAddItem.bind(this));
  6875. // item panel
  6876. var itemOptions = Object.create(this.options);
  6877. itemOptions.left = function () {
  6878. return me.labelPanel.width;
  6879. };
  6880. itemOptions.width = function () {
  6881. return me.rootPanel.width - me.labelPanel.width;
  6882. };
  6883. itemOptions.top = null;
  6884. itemOptions.height = null;
  6885. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  6886. this.controller.add(this.itemPanel);
  6887. // label panel
  6888. var labelOptions = Object.create(this.options);
  6889. labelOptions.top = null;
  6890. labelOptions.left = null;
  6891. labelOptions.height = null;
  6892. labelOptions.width = function () {
  6893. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  6894. return me.content.getLabelsWidth();
  6895. }
  6896. else {
  6897. return 0;
  6898. }
  6899. };
  6900. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  6901. this.controller.add(this.labelPanel);
  6902. // range
  6903. var rangeOptions = Object.create(this.options);
  6904. this.range = new Range(rangeOptions);
  6905. this.range.setRange(
  6906. now.clone().add('days', -3).valueOf(),
  6907. now.clone().add('days', 4).valueOf()
  6908. );
  6909. this.range.subscribe(this.controller, this.rootPanel, 'move', 'horizontal');
  6910. this.range.subscribe(this.controller, this.rootPanel, 'zoom', 'horizontal');
  6911. this.range.on('rangechange', function (properties) {
  6912. var force = true;
  6913. me.controller.emit('rangechange', properties);
  6914. me.controller.emit('request-reflow', force);
  6915. });
  6916. this.range.on('rangechanged', function (properties) {
  6917. var force = true;
  6918. me.controller.emit('rangechanged', properties);
  6919. me.controller.emit('request-reflow', force);
  6920. });
  6921. // time axis
  6922. var timeaxisOptions = Object.create(rootOptions);
  6923. timeaxisOptions.range = this.range;
  6924. timeaxisOptions.left = null;
  6925. timeaxisOptions.top = null;
  6926. timeaxisOptions.width = '100%';
  6927. timeaxisOptions.height = null;
  6928. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6929. this.timeaxis.setRange(this.range);
  6930. this.controller.add(this.timeaxis);
  6931. this.options.snap = this.timeaxis.snap.bind(this.timeaxis);
  6932. // current time bar
  6933. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  6934. this.controller.add(this.currenttime);
  6935. // custom time bar
  6936. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  6937. this.controller.add(this.customtime);
  6938. // create groupset
  6939. this.setGroups(null);
  6940. this.itemsData = null; // DataSet
  6941. this.groupsData = null; // DataSet
  6942. // apply options
  6943. if (options) {
  6944. this.setOptions(options);
  6945. }
  6946. // create itemset and groupset
  6947. if (items) {
  6948. this.setItems(items);
  6949. }
  6950. }
  6951. /**
  6952. * Add an event listener to the timeline
  6953. * @param {String} event Available events: select, rangechange, rangechanged,
  6954. * timechange, timechanged
  6955. * @param {function} callback
  6956. */
  6957. Timeline.prototype.on = function on (event, callback) {
  6958. this.controller.on(event, callback);
  6959. };
  6960. /**
  6961. * Add an event listener from the timeline
  6962. * @param {String} event
  6963. * @param {function} callback
  6964. */
  6965. Timeline.prototype.off = function off (event, callback) {
  6966. this.controller.off(event, callback);
  6967. };
  6968. /**
  6969. * Set options
  6970. * @param {Object} options TODO: describe the available options
  6971. */
  6972. Timeline.prototype.setOptions = function (options) {
  6973. util.extend(this.options, options);
  6974. // force update of range (apply new min/max etc.)
  6975. // both start and end are optional
  6976. this.range.setRange(options.start, options.end);
  6977. if ('editable' in options || 'selectable' in options) {
  6978. if (this.options.selectable) {
  6979. // force update of selection
  6980. this.setSelection(this.getSelection());
  6981. }
  6982. else {
  6983. // remove selection
  6984. this.setSelection([]);
  6985. }
  6986. }
  6987. // validate the callback functions
  6988. var validateCallback = (function (fn) {
  6989. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  6990. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  6991. }
  6992. }).bind(this);
  6993. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  6994. this.controller.reflow();
  6995. this.controller.repaint();
  6996. };
  6997. /**
  6998. * Set a custom time bar
  6999. * @param {Date} time
  7000. */
  7001. Timeline.prototype.setCustomTime = function (time) {
  7002. if (!this.customtime) {
  7003. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  7004. }
  7005. this.customtime.setCustomTime(time);
  7006. };
  7007. /**
  7008. * Retrieve the current custom time.
  7009. * @return {Date} customTime
  7010. */
  7011. Timeline.prototype.getCustomTime = function() {
  7012. if (!this.customtime) {
  7013. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  7014. }
  7015. return this.customtime.getCustomTime();
  7016. };
  7017. /**
  7018. * Set items
  7019. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  7020. */
  7021. Timeline.prototype.setItems = function(items) {
  7022. var initialLoad = (this.itemsData == null);
  7023. // convert to type DataSet when needed
  7024. var newDataSet;
  7025. if (!items) {
  7026. newDataSet = null;
  7027. }
  7028. else if (items instanceof DataSet) {
  7029. newDataSet = items;
  7030. }
  7031. if (!(items instanceof DataSet)) {
  7032. newDataSet = new DataSet({
  7033. convert: {
  7034. start: 'Date',
  7035. end: 'Date'
  7036. }
  7037. });
  7038. newDataSet.add(items);
  7039. }
  7040. // set items
  7041. this.itemsData = newDataSet;
  7042. this.content.setItems(newDataSet);
  7043. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  7044. // apply the data range as range
  7045. var dataRange = this.getItemRange();
  7046. // add 5% space on both sides
  7047. var start = dataRange.min;
  7048. var end = dataRange.max;
  7049. if (start != null && end != null) {
  7050. var interval = (end.valueOf() - start.valueOf());
  7051. if (interval <= 0) {
  7052. // prevent an empty interval
  7053. interval = 24 * 60 * 60 * 1000; // 1 day
  7054. }
  7055. start = new Date(start.valueOf() - interval * 0.05);
  7056. end = new Date(end.valueOf() + interval * 0.05);
  7057. }
  7058. // override specified start and/or end date
  7059. if (this.options.start != undefined) {
  7060. start = util.convert(this.options.start, 'Date');
  7061. }
  7062. if (this.options.end != undefined) {
  7063. end = util.convert(this.options.end, 'Date');
  7064. }
  7065. // apply range if there is a min or max available
  7066. if (start != null || end != null) {
  7067. this.range.setRange(start, end);
  7068. }
  7069. }
  7070. };
  7071. /**
  7072. * Set groups
  7073. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  7074. */
  7075. Timeline.prototype.setGroups = function(groups) {
  7076. var me = this;
  7077. this.groupsData = groups;
  7078. // switch content type between ItemSet or GroupSet when needed
  7079. var Type = this.groupsData ? GroupSet : ItemSet;
  7080. if (!(this.content instanceof Type)) {
  7081. // remove old content set
  7082. if (this.content) {
  7083. this.content.hide();
  7084. if (this.content.setItems) {
  7085. this.content.setItems(); // disconnect from items
  7086. }
  7087. if (this.content.setGroups) {
  7088. this.content.setGroups(); // disconnect from groups
  7089. }
  7090. this.controller.remove(this.content);
  7091. }
  7092. // create new content set
  7093. var options = Object.create(this.options);
  7094. util.extend(options, {
  7095. top: function () {
  7096. if (me.options.orientation == 'top') {
  7097. return me.timeaxis.height;
  7098. }
  7099. else {
  7100. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  7101. }
  7102. },
  7103. left: null,
  7104. width: '100%',
  7105. height: function () {
  7106. if (me.options.height) {
  7107. // fixed height
  7108. return me.itemPanel.height - me.timeaxis.height;
  7109. }
  7110. else {
  7111. // auto height
  7112. return null;
  7113. }
  7114. },
  7115. maxHeight: function () {
  7116. // TODO: change maxHeight to be a css string like '100%' or '300px'
  7117. if (me.options.maxHeight) {
  7118. if (!util.isNumber(me.options.maxHeight)) {
  7119. throw new TypeError('Number expected for property maxHeight');
  7120. }
  7121. return me.options.maxHeight - me.timeaxis.height;
  7122. }
  7123. else {
  7124. return null;
  7125. }
  7126. },
  7127. labelContainer: function () {
  7128. return me.labelPanel.getContainer();
  7129. }
  7130. });
  7131. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  7132. if (this.content.setRange) {
  7133. this.content.setRange(this.range);
  7134. }
  7135. if (this.content.setItems) {
  7136. this.content.setItems(this.itemsData);
  7137. }
  7138. if (this.content.setGroups) {
  7139. this.content.setGroups(this.groupsData);
  7140. }
  7141. this.controller.add(this.content);
  7142. }
  7143. };
  7144. /**
  7145. * Get the data range of the item set.
  7146. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  7147. * When no minimum is found, min==null
  7148. * When no maximum is found, max==null
  7149. */
  7150. Timeline.prototype.getItemRange = function getItemRange() {
  7151. // calculate min from start filed
  7152. var itemsData = this.itemsData,
  7153. min = null,
  7154. max = null;
  7155. if (itemsData) {
  7156. // calculate the minimum value of the field 'start'
  7157. var minItem = itemsData.min('start');
  7158. min = minItem ? minItem.start.valueOf() : null;
  7159. // calculate maximum value of fields 'start' and 'end'
  7160. var maxStartItem = itemsData.max('start');
  7161. if (maxStartItem) {
  7162. max = maxStartItem.start.valueOf();
  7163. }
  7164. var maxEndItem = itemsData.max('end');
  7165. if (maxEndItem) {
  7166. if (max == null) {
  7167. max = maxEndItem.end.valueOf();
  7168. }
  7169. else {
  7170. max = Math.max(max, maxEndItem.end.valueOf());
  7171. }
  7172. }
  7173. }
  7174. return {
  7175. min: (min != null) ? new Date(min) : null,
  7176. max: (max != null) ? new Date(max) : null
  7177. };
  7178. };
  7179. /**
  7180. * Set selected items by their id. Replaces the current selection
  7181. * Unknown id's are silently ignored.
  7182. * @param {Array} [ids] An array with zero or more id's of the items to be
  7183. * selected. If ids is an empty array, all items will be
  7184. * unselected.
  7185. */
  7186. Timeline.prototype.setSelection = function setSelection (ids) {
  7187. if (this.content) this.content.setSelection(ids);
  7188. };
  7189. /**
  7190. * Get the selected items by their id
  7191. * @return {Array} ids The ids of the selected items
  7192. */
  7193. Timeline.prototype.getSelection = function getSelection() {
  7194. return this.content ? this.content.getSelection() : [];
  7195. };
  7196. /**
  7197. * Set the visible window. Both parameters are optional, you can change only
  7198. * start or only end.
  7199. * @param {Date | Number | String} [start] Start date of visible window
  7200. * @param {Date | Number | String} [end] End date of visible window
  7201. */
  7202. Timeline.prototype.setWindow = function setWindow(start, end) {
  7203. this.range.setRange(start, end);
  7204. };
  7205. /**
  7206. * Get the visible window
  7207. * @return {{start: Date, end: Date}} Visible range
  7208. */
  7209. Timeline.prototype.getWindow = function setWindow() {
  7210. var range = this.range.getRange();
  7211. return {
  7212. start: new Date(range.start),
  7213. end: new Date(range.end)
  7214. };
  7215. };
  7216. /**
  7217. * Handle selecting/deselecting an item when tapping it
  7218. * @param {Event} event
  7219. * @private
  7220. */
  7221. // TODO: move this function to ItemSet
  7222. Timeline.prototype._onSelectItem = function (event) {
  7223. if (!this.options.selectable) return;
  7224. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  7225. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  7226. if (ctrlKey || shiftKey) {
  7227. this._onMultiSelectItem(event);
  7228. return;
  7229. }
  7230. var item = ItemSet.itemFromTarget(event);
  7231. var selection = item ? [item.id] : [];
  7232. this.setSelection(selection);
  7233. this.controller.emit('select', {
  7234. items: this.getSelection()
  7235. });
  7236. event.stopPropagation();
  7237. };
  7238. /**
  7239. * Handle creation and updates of an item on double tap
  7240. * @param event
  7241. * @private
  7242. */
  7243. Timeline.prototype._onAddItem = function (event) {
  7244. if (!this.options.selectable) return;
  7245. if (!this.options.editable) return;
  7246. var me = this,
  7247. item = ItemSet.itemFromTarget(event);
  7248. if (item) {
  7249. // update item
  7250. // execute async handler to update the item (or cancel it)
  7251. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  7252. this.options.onUpdate(itemData, function (itemData) {
  7253. if (itemData) {
  7254. me.itemsData.update(itemData);
  7255. }
  7256. });
  7257. }
  7258. else {
  7259. // add item
  7260. var xAbs = vis.util.getAbsoluteLeft(this.rootPanel.frame);
  7261. var x = event.gesture.center.pageX - xAbs;
  7262. var newItem = {
  7263. start: this.timeaxis.snap(this._toTime(x)),
  7264. content: 'new item'
  7265. };
  7266. var id = util.randomUUID();
  7267. newItem[this.itemsData.fieldId] = id;
  7268. var group = GroupSet.groupFromTarget(event);
  7269. if (group) {
  7270. newItem.group = group.groupId;
  7271. }
  7272. // execute async handler to customize (or cancel) adding an item
  7273. this.options.onAdd(newItem, function (item) {
  7274. if (item) {
  7275. me.itemsData.add(newItem);
  7276. // select the created item after it is repainted
  7277. me.controller.once('repaint', function () {
  7278. me.setSelection([id]);
  7279. me.controller.emit('select', {
  7280. items: me.getSelection()
  7281. });
  7282. }.bind(me));
  7283. }
  7284. });
  7285. }
  7286. };
  7287. /**
  7288. * Handle selecting/deselecting multiple items when holding an item
  7289. * @param {Event} event
  7290. * @private
  7291. */
  7292. // TODO: move this function to ItemSet
  7293. Timeline.prototype._onMultiSelectItem = function (event) {
  7294. if (!this.options.selectable) return;
  7295. var selection,
  7296. item = ItemSet.itemFromTarget(event);
  7297. if (item) {
  7298. // multi select items
  7299. selection = this.getSelection(); // current selection
  7300. var index = selection.indexOf(item.id);
  7301. if (index == -1) {
  7302. // item is not yet selected -> select it
  7303. selection.push(item.id);
  7304. }
  7305. else {
  7306. // item is already selected -> deselect it
  7307. selection.splice(index, 1);
  7308. }
  7309. this.setSelection(selection);
  7310. this.controller.emit('select', {
  7311. items: this.getSelection()
  7312. });
  7313. event.stopPropagation();
  7314. }
  7315. };
  7316. /**
  7317. * Convert a position on screen (pixels) to a datetime
  7318. * @param {int} x Position on the screen in pixels
  7319. * @return {Date} time The datetime the corresponds with given position x
  7320. * @private
  7321. */
  7322. Timeline.prototype._toTime = function _toTime(x) {
  7323. var conversion = this.range.conversion(this.content.width);
  7324. return new Date(x / conversion.scale + conversion.offset);
  7325. };
  7326. /**
  7327. * Convert a datetime (Date object) into a position on the screen
  7328. * @param {Date} time A date
  7329. * @return {int} x The position on the screen in pixels which corresponds
  7330. * with the given date.
  7331. * @private
  7332. */
  7333. Timeline.prototype._toScreen = function _toScreen(time) {
  7334. var conversion = this.range.conversion(this.content.width);
  7335. return (time.valueOf() - conversion.offset) * conversion.scale;
  7336. };
  7337. (function(exports) {
  7338. /**
  7339. * Parse a text source containing data in DOT language into a JSON object.
  7340. * The object contains two lists: one with nodes and one with edges.
  7341. *
  7342. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  7343. *
  7344. * @param {String} data Text containing a graph in DOT-notation
  7345. * @return {Object} graph An object containing two parameters:
  7346. * {Object[]} nodes
  7347. * {Object[]} edges
  7348. */
  7349. function parseDOT (data) {
  7350. dot = data;
  7351. return parseGraph();
  7352. }
  7353. // token types enumeration
  7354. var TOKENTYPE = {
  7355. NULL : 0,
  7356. DELIMITER : 1,
  7357. IDENTIFIER: 2,
  7358. UNKNOWN : 3
  7359. };
  7360. // map with all delimiters
  7361. var DELIMITERS = {
  7362. '{': true,
  7363. '}': true,
  7364. '[': true,
  7365. ']': true,
  7366. ';': true,
  7367. '=': true,
  7368. ',': true,
  7369. '->': true,
  7370. '--': true
  7371. };
  7372. var dot = ''; // current dot file
  7373. var index = 0; // current index in dot file
  7374. var c = ''; // current token character in expr
  7375. var token = ''; // current token
  7376. var tokenType = TOKENTYPE.NULL; // type of the token
  7377. /**
  7378. * Get the first character from the dot file.
  7379. * The character is stored into the char c. If the end of the dot file is
  7380. * reached, the function puts an empty string in c.
  7381. */
  7382. function first() {
  7383. index = 0;
  7384. c = dot.charAt(0);
  7385. }
  7386. /**
  7387. * Get the next character from the dot file.
  7388. * The character is stored into the char c. If the end of the dot file is
  7389. * reached, the function puts an empty string in c.
  7390. */
  7391. function next() {
  7392. index++;
  7393. c = dot.charAt(index);
  7394. }
  7395. /**
  7396. * Preview the next character from the dot file.
  7397. * @return {String} cNext
  7398. */
  7399. function nextPreview() {
  7400. return dot.charAt(index + 1);
  7401. }
  7402. /**
  7403. * Test whether given character is alphabetic or numeric
  7404. * @param {String} c
  7405. * @return {Boolean} isAlphaNumeric
  7406. */
  7407. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  7408. function isAlphaNumeric(c) {
  7409. return regexAlphaNumeric.test(c);
  7410. }
  7411. /**
  7412. * Merge all properties of object b into object b
  7413. * @param {Object} a
  7414. * @param {Object} b
  7415. * @return {Object} a
  7416. */
  7417. function merge (a, b) {
  7418. if (!a) {
  7419. a = {};
  7420. }
  7421. if (b) {
  7422. for (var name in b) {
  7423. if (b.hasOwnProperty(name)) {
  7424. a[name] = b[name];
  7425. }
  7426. }
  7427. }
  7428. return a;
  7429. }
  7430. /**
  7431. * Set a value in an object, where the provided parameter name can be a
  7432. * path with nested parameters. For example:
  7433. *
  7434. * var obj = {a: 2};
  7435. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  7436. *
  7437. * @param {Object} obj
  7438. * @param {String} path A parameter name or dot-separated parameter path,
  7439. * like "color.highlight.border".
  7440. * @param {*} value
  7441. */
  7442. function setValue(obj, path, value) {
  7443. var keys = path.split('.');
  7444. var o = obj;
  7445. while (keys.length) {
  7446. var key = keys.shift();
  7447. if (keys.length) {
  7448. // this isn't the end point
  7449. if (!o[key]) {
  7450. o[key] = {};
  7451. }
  7452. o = o[key];
  7453. }
  7454. else {
  7455. // this is the end point
  7456. o[key] = value;
  7457. }
  7458. }
  7459. }
  7460. /**
  7461. * Add a node to a graph object. If there is already a node with
  7462. * the same id, their attributes will be merged.
  7463. * @param {Object} graph
  7464. * @param {Object} node
  7465. */
  7466. function addNode(graph, node) {
  7467. var i, len;
  7468. var current = null;
  7469. // find root graph (in case of subgraph)
  7470. var graphs = [graph]; // list with all graphs from current graph to root graph
  7471. var root = graph;
  7472. while (root.parent) {
  7473. graphs.push(root.parent);
  7474. root = root.parent;
  7475. }
  7476. // find existing node (at root level) by its id
  7477. if (root.nodes) {
  7478. for (i = 0, len = root.nodes.length; i < len; i++) {
  7479. if (node.id === root.nodes[i].id) {
  7480. current = root.nodes[i];
  7481. break;
  7482. }
  7483. }
  7484. }
  7485. if (!current) {
  7486. // this is a new node
  7487. current = {
  7488. id: node.id
  7489. };
  7490. if (graph.node) {
  7491. // clone default attributes
  7492. current.attr = merge(current.attr, graph.node);
  7493. }
  7494. }
  7495. // add node to this (sub)graph and all its parent graphs
  7496. for (i = graphs.length - 1; i >= 0; i--) {
  7497. var g = graphs[i];
  7498. if (!g.nodes) {
  7499. g.nodes = [];
  7500. }
  7501. if (g.nodes.indexOf(current) == -1) {
  7502. g.nodes.push(current);
  7503. }
  7504. }
  7505. // merge attributes
  7506. if (node.attr) {
  7507. current.attr = merge(current.attr, node.attr);
  7508. }
  7509. }
  7510. /**
  7511. * Add an edge to a graph object
  7512. * @param {Object} graph
  7513. * @param {Object} edge
  7514. */
  7515. function addEdge(graph, edge) {
  7516. if (!graph.edges) {
  7517. graph.edges = [];
  7518. }
  7519. graph.edges.push(edge);
  7520. if (graph.edge) {
  7521. var attr = merge({}, graph.edge); // clone default attributes
  7522. edge.attr = merge(attr, edge.attr); // merge attributes
  7523. }
  7524. }
  7525. /**
  7526. * Create an edge to a graph object
  7527. * @param {Object} graph
  7528. * @param {String | Number | Object} from
  7529. * @param {String | Number | Object} to
  7530. * @param {String} type
  7531. * @param {Object | null} attr
  7532. * @return {Object} edge
  7533. */
  7534. function createEdge(graph, from, to, type, attr) {
  7535. var edge = {
  7536. from: from,
  7537. to: to,
  7538. type: type
  7539. };
  7540. if (graph.edge) {
  7541. edge.attr = merge({}, graph.edge); // clone default attributes
  7542. }
  7543. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7544. return edge;
  7545. }
  7546. /**
  7547. * Get next token in the current dot file.
  7548. * The token and token type are available as token and tokenType
  7549. */
  7550. function getToken() {
  7551. tokenType = TOKENTYPE.NULL;
  7552. token = '';
  7553. // skip over whitespaces
  7554. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7555. next();
  7556. }
  7557. do {
  7558. var isComment = false;
  7559. // skip comment
  7560. if (c == '#') {
  7561. // find the previous non-space character
  7562. var i = index - 1;
  7563. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7564. i--;
  7565. }
  7566. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7567. // the # is at the start of a line, this is indeed a line comment
  7568. while (c != '' && c != '\n') {
  7569. next();
  7570. }
  7571. isComment = true;
  7572. }
  7573. }
  7574. if (c == '/' && nextPreview() == '/') {
  7575. // skip line comment
  7576. while (c != '' && c != '\n') {
  7577. next();
  7578. }
  7579. isComment = true;
  7580. }
  7581. if (c == '/' && nextPreview() == '*') {
  7582. // skip block comment
  7583. while (c != '') {
  7584. if (c == '*' && nextPreview() == '/') {
  7585. // end of block comment found. skip these last two characters
  7586. next();
  7587. next();
  7588. break;
  7589. }
  7590. else {
  7591. next();
  7592. }
  7593. }
  7594. isComment = true;
  7595. }
  7596. // skip over whitespaces
  7597. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7598. next();
  7599. }
  7600. }
  7601. while (isComment);
  7602. // check for end of dot file
  7603. if (c == '') {
  7604. // token is still empty
  7605. tokenType = TOKENTYPE.DELIMITER;
  7606. return;
  7607. }
  7608. // check for delimiters consisting of 2 characters
  7609. var c2 = c + nextPreview();
  7610. if (DELIMITERS[c2]) {
  7611. tokenType = TOKENTYPE.DELIMITER;
  7612. token = c2;
  7613. next();
  7614. next();
  7615. return;
  7616. }
  7617. // check for delimiters consisting of 1 character
  7618. if (DELIMITERS[c]) {
  7619. tokenType = TOKENTYPE.DELIMITER;
  7620. token = c;
  7621. next();
  7622. return;
  7623. }
  7624. // check for an identifier (number or string)
  7625. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7626. if (isAlphaNumeric(c) || c == '-') {
  7627. token += c;
  7628. next();
  7629. while (isAlphaNumeric(c)) {
  7630. token += c;
  7631. next();
  7632. }
  7633. if (token == 'false') {
  7634. token = false; // convert to boolean
  7635. }
  7636. else if (token == 'true') {
  7637. token = true; // convert to boolean
  7638. }
  7639. else if (!isNaN(Number(token))) {
  7640. token = Number(token); // convert to number
  7641. }
  7642. tokenType = TOKENTYPE.IDENTIFIER;
  7643. return;
  7644. }
  7645. // check for a string enclosed by double quotes
  7646. if (c == '"') {
  7647. next();
  7648. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7649. token += c;
  7650. if (c == '"') { // skip the escape character
  7651. next();
  7652. }
  7653. next();
  7654. }
  7655. if (c != '"') {
  7656. throw newSyntaxError('End of string " expected');
  7657. }
  7658. next();
  7659. tokenType = TOKENTYPE.IDENTIFIER;
  7660. return;
  7661. }
  7662. // something unknown is found, wrong characters, a syntax error
  7663. tokenType = TOKENTYPE.UNKNOWN;
  7664. while (c != '') {
  7665. token += c;
  7666. next();
  7667. }
  7668. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7669. }
  7670. /**
  7671. * Parse a graph.
  7672. * @returns {Object} graph
  7673. */
  7674. function parseGraph() {
  7675. var graph = {};
  7676. first();
  7677. getToken();
  7678. // optional strict keyword
  7679. if (token == 'strict') {
  7680. graph.strict = true;
  7681. getToken();
  7682. }
  7683. // graph or digraph keyword
  7684. if (token == 'graph' || token == 'digraph') {
  7685. graph.type = token;
  7686. getToken();
  7687. }
  7688. // optional graph id
  7689. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7690. graph.id = token;
  7691. getToken();
  7692. }
  7693. // open angle bracket
  7694. if (token != '{') {
  7695. throw newSyntaxError('Angle bracket { expected');
  7696. }
  7697. getToken();
  7698. // statements
  7699. parseStatements(graph);
  7700. // close angle bracket
  7701. if (token != '}') {
  7702. throw newSyntaxError('Angle bracket } expected');
  7703. }
  7704. getToken();
  7705. // end of file
  7706. if (token !== '') {
  7707. throw newSyntaxError('End of file expected');
  7708. }
  7709. getToken();
  7710. // remove temporary default properties
  7711. delete graph.node;
  7712. delete graph.edge;
  7713. delete graph.graph;
  7714. return graph;
  7715. }
  7716. /**
  7717. * Parse a list with statements.
  7718. * @param {Object} graph
  7719. */
  7720. function parseStatements (graph) {
  7721. while (token !== '' && token != '}') {
  7722. parseStatement(graph);
  7723. if (token == ';') {
  7724. getToken();
  7725. }
  7726. }
  7727. }
  7728. /**
  7729. * Parse a single statement. Can be a an attribute statement, node
  7730. * statement, a series of node statements and edge statements, or a
  7731. * parameter.
  7732. * @param {Object} graph
  7733. */
  7734. function parseStatement(graph) {
  7735. // parse subgraph
  7736. var subgraph = parseSubgraph(graph);
  7737. if (subgraph) {
  7738. // edge statements
  7739. parseEdge(graph, subgraph);
  7740. return;
  7741. }
  7742. // parse an attribute statement
  7743. var attr = parseAttributeStatement(graph);
  7744. if (attr) {
  7745. return;
  7746. }
  7747. // parse node
  7748. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7749. throw newSyntaxError('Identifier expected');
  7750. }
  7751. var id = token; // id can be a string or a number
  7752. getToken();
  7753. if (token == '=') {
  7754. // id statement
  7755. getToken();
  7756. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7757. throw newSyntaxError('Identifier expected');
  7758. }
  7759. graph[id] = token;
  7760. getToken();
  7761. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7762. }
  7763. else {
  7764. parseNodeStatement(graph, id);
  7765. }
  7766. }
  7767. /**
  7768. * Parse a subgraph
  7769. * @param {Object} graph parent graph object
  7770. * @return {Object | null} subgraph
  7771. */
  7772. function parseSubgraph (graph) {
  7773. var subgraph = null;
  7774. // optional subgraph keyword
  7775. if (token == 'subgraph') {
  7776. subgraph = {};
  7777. subgraph.type = 'subgraph';
  7778. getToken();
  7779. // optional graph id
  7780. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7781. subgraph.id = token;
  7782. getToken();
  7783. }
  7784. }
  7785. // open angle bracket
  7786. if (token == '{') {
  7787. getToken();
  7788. if (!subgraph) {
  7789. subgraph = {};
  7790. }
  7791. subgraph.parent = graph;
  7792. subgraph.node = graph.node;
  7793. subgraph.edge = graph.edge;
  7794. subgraph.graph = graph.graph;
  7795. // statements
  7796. parseStatements(subgraph);
  7797. // close angle bracket
  7798. if (token != '}') {
  7799. throw newSyntaxError('Angle bracket } expected');
  7800. }
  7801. getToken();
  7802. // remove temporary default properties
  7803. delete subgraph.node;
  7804. delete subgraph.edge;
  7805. delete subgraph.graph;
  7806. delete subgraph.parent;
  7807. // register at the parent graph
  7808. if (!graph.subgraphs) {
  7809. graph.subgraphs = [];
  7810. }
  7811. graph.subgraphs.push(subgraph);
  7812. }
  7813. return subgraph;
  7814. }
  7815. /**
  7816. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7817. * Available keywords are 'node', 'edge', 'graph'.
  7818. * The previous list with default attributes will be replaced
  7819. * @param {Object} graph
  7820. * @returns {String | null} keyword Returns the name of the parsed attribute
  7821. * (node, edge, graph), or null if nothing
  7822. * is parsed.
  7823. */
  7824. function parseAttributeStatement (graph) {
  7825. // attribute statements
  7826. if (token == 'node') {
  7827. getToken();
  7828. // node attributes
  7829. graph.node = parseAttributeList();
  7830. return 'node';
  7831. }
  7832. else if (token == 'edge') {
  7833. getToken();
  7834. // edge attributes
  7835. graph.edge = parseAttributeList();
  7836. return 'edge';
  7837. }
  7838. else if (token == 'graph') {
  7839. getToken();
  7840. // graph attributes
  7841. graph.graph = parseAttributeList();
  7842. return 'graph';
  7843. }
  7844. return null;
  7845. }
  7846. /**
  7847. * parse a node statement
  7848. * @param {Object} graph
  7849. * @param {String | Number} id
  7850. */
  7851. function parseNodeStatement(graph, id) {
  7852. // node statement
  7853. var node = {
  7854. id: id
  7855. };
  7856. var attr = parseAttributeList();
  7857. if (attr) {
  7858. node.attr = attr;
  7859. }
  7860. addNode(graph, node);
  7861. // edge statements
  7862. parseEdge(graph, id);
  7863. }
  7864. /**
  7865. * Parse an edge or a series of edges
  7866. * @param {Object} graph
  7867. * @param {String | Number} from Id of the from node
  7868. */
  7869. function parseEdge(graph, from) {
  7870. while (token == '->' || token == '--') {
  7871. var to;
  7872. var type = token;
  7873. getToken();
  7874. var subgraph = parseSubgraph(graph);
  7875. if (subgraph) {
  7876. to = subgraph;
  7877. }
  7878. else {
  7879. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7880. throw newSyntaxError('Identifier or subgraph expected');
  7881. }
  7882. to = token;
  7883. addNode(graph, {
  7884. id: to
  7885. });
  7886. getToken();
  7887. }
  7888. // parse edge attributes
  7889. var attr = parseAttributeList();
  7890. // create edge
  7891. var edge = createEdge(graph, from, to, type, attr);
  7892. addEdge(graph, edge);
  7893. from = to;
  7894. }
  7895. }
  7896. /**
  7897. * Parse a set with attributes,
  7898. * for example [label="1.000", shape=solid]
  7899. * @return {Object | null} attr
  7900. */
  7901. function parseAttributeList() {
  7902. var attr = null;
  7903. while (token == '[') {
  7904. getToken();
  7905. attr = {};
  7906. while (token !== '' && token != ']') {
  7907. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7908. throw newSyntaxError('Attribute name expected');
  7909. }
  7910. var name = token;
  7911. getToken();
  7912. if (token != '=') {
  7913. throw newSyntaxError('Equal sign = expected');
  7914. }
  7915. getToken();
  7916. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7917. throw newSyntaxError('Attribute value expected');
  7918. }
  7919. var value = token;
  7920. setValue(attr, name, value); // name can be a path
  7921. getToken();
  7922. if (token ==',') {
  7923. getToken();
  7924. }
  7925. }
  7926. if (token != ']') {
  7927. throw newSyntaxError('Bracket ] expected');
  7928. }
  7929. getToken();
  7930. }
  7931. return attr;
  7932. }
  7933. /**
  7934. * Create a syntax error with extra information on current token and index.
  7935. * @param {String} message
  7936. * @returns {SyntaxError} err
  7937. */
  7938. function newSyntaxError(message) {
  7939. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7940. }
  7941. /**
  7942. * Chop off text after a maximum length
  7943. * @param {String} text
  7944. * @param {Number} maxLength
  7945. * @returns {String}
  7946. */
  7947. function chop (text, maxLength) {
  7948. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7949. }
  7950. /**
  7951. * Execute a function fn for each pair of elements in two arrays
  7952. * @param {Array | *} array1
  7953. * @param {Array | *} array2
  7954. * @param {function} fn
  7955. */
  7956. function forEach2(array1, array2, fn) {
  7957. if (array1 instanceof Array) {
  7958. array1.forEach(function (elem1) {
  7959. if (array2 instanceof Array) {
  7960. array2.forEach(function (elem2) {
  7961. fn(elem1, elem2);
  7962. });
  7963. }
  7964. else {
  7965. fn(elem1, array2);
  7966. }
  7967. });
  7968. }
  7969. else {
  7970. if (array2 instanceof Array) {
  7971. array2.forEach(function (elem2) {
  7972. fn(array1, elem2);
  7973. });
  7974. }
  7975. else {
  7976. fn(array1, array2);
  7977. }
  7978. }
  7979. }
  7980. /**
  7981. * Convert a string containing a graph in DOT language into a map containing
  7982. * with nodes and edges in the format of graph.
  7983. * @param {String} data Text containing a graph in DOT-notation
  7984. * @return {Object} graphData
  7985. */
  7986. function DOTToGraph (data) {
  7987. // parse the DOT file
  7988. var dotData = parseDOT(data);
  7989. var graphData = {
  7990. nodes: [],
  7991. edges: [],
  7992. options: {}
  7993. };
  7994. // copy the nodes
  7995. if (dotData.nodes) {
  7996. dotData.nodes.forEach(function (dotNode) {
  7997. var graphNode = {
  7998. id: dotNode.id,
  7999. label: String(dotNode.label || dotNode.id)
  8000. };
  8001. merge(graphNode, dotNode.attr);
  8002. if (graphNode.image) {
  8003. graphNode.shape = 'image';
  8004. }
  8005. graphData.nodes.push(graphNode);
  8006. });
  8007. }
  8008. // copy the edges
  8009. if (dotData.edges) {
  8010. /**
  8011. * Convert an edge in DOT format to an edge with VisGraph format
  8012. * @param {Object} dotEdge
  8013. * @returns {Object} graphEdge
  8014. */
  8015. function convertEdge(dotEdge) {
  8016. var graphEdge = {
  8017. from: dotEdge.from,
  8018. to: dotEdge.to
  8019. };
  8020. merge(graphEdge, dotEdge.attr);
  8021. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  8022. return graphEdge;
  8023. }
  8024. dotData.edges.forEach(function (dotEdge) {
  8025. var from, to;
  8026. if (dotEdge.from instanceof Object) {
  8027. from = dotEdge.from.nodes;
  8028. }
  8029. else {
  8030. from = {
  8031. id: dotEdge.from
  8032. }
  8033. }
  8034. if (dotEdge.to instanceof Object) {
  8035. to = dotEdge.to.nodes;
  8036. }
  8037. else {
  8038. to = {
  8039. id: dotEdge.to
  8040. }
  8041. }
  8042. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  8043. dotEdge.from.edges.forEach(function (subEdge) {
  8044. var graphEdge = convertEdge(subEdge);
  8045. graphData.edges.push(graphEdge);
  8046. });
  8047. }
  8048. forEach2(from, to, function (from, to) {
  8049. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  8050. var graphEdge = convertEdge(subEdge);
  8051. graphData.edges.push(graphEdge);
  8052. });
  8053. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  8054. dotEdge.to.edges.forEach(function (subEdge) {
  8055. var graphEdge = convertEdge(subEdge);
  8056. graphData.edges.push(graphEdge);
  8057. });
  8058. }
  8059. });
  8060. }
  8061. // copy the options
  8062. if (dotData.attr) {
  8063. graphData.options = dotData.attr;
  8064. }
  8065. return graphData;
  8066. }
  8067. // exports
  8068. exports.parseDOT = parseDOT;
  8069. exports.DOTToGraph = DOTToGraph;
  8070. })(typeof util !== 'undefined' ? util : exports);
  8071. /**
  8072. * Canvas shapes used by the Graph
  8073. */
  8074. if (typeof CanvasRenderingContext2D !== 'undefined') {
  8075. /**
  8076. * Draw a circle shape
  8077. */
  8078. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  8079. this.beginPath();
  8080. this.arc(x, y, r, 0, 2*Math.PI, false);
  8081. };
  8082. /**
  8083. * Draw a square shape
  8084. * @param {Number} x horizontal center
  8085. * @param {Number} y vertical center
  8086. * @param {Number} r size, width and height of the square
  8087. */
  8088. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  8089. this.beginPath();
  8090. this.rect(x - r, y - r, r * 2, r * 2);
  8091. };
  8092. /**
  8093. * Draw a triangle shape
  8094. * @param {Number} x horizontal center
  8095. * @param {Number} y vertical center
  8096. * @param {Number} r radius, half the length of the sides of the triangle
  8097. */
  8098. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  8099. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8100. this.beginPath();
  8101. var s = r * 2;
  8102. var s2 = s / 2;
  8103. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8104. var h = Math.sqrt(s * s - s2 * s2); // height
  8105. this.moveTo(x, y - (h - ir));
  8106. this.lineTo(x + s2, y + ir);
  8107. this.lineTo(x - s2, y + ir);
  8108. this.lineTo(x, y - (h - ir));
  8109. this.closePath();
  8110. };
  8111. /**
  8112. * Draw a triangle shape in downward orientation
  8113. * @param {Number} x horizontal center
  8114. * @param {Number} y vertical center
  8115. * @param {Number} r radius
  8116. */
  8117. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  8118. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8119. this.beginPath();
  8120. var s = r * 2;
  8121. var s2 = s / 2;
  8122. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8123. var h = Math.sqrt(s * s - s2 * s2); // height
  8124. this.moveTo(x, y + (h - ir));
  8125. this.lineTo(x + s2, y - ir);
  8126. this.lineTo(x - s2, y - ir);
  8127. this.lineTo(x, y + (h - ir));
  8128. this.closePath();
  8129. };
  8130. /**
  8131. * Draw a star shape, a star with 5 points
  8132. * @param {Number} x horizontal center
  8133. * @param {Number} y vertical center
  8134. * @param {Number} r radius, half the length of the sides of the triangle
  8135. */
  8136. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  8137. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  8138. this.beginPath();
  8139. for (var n = 0; n < 10; n++) {
  8140. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  8141. this.lineTo(
  8142. x + radius * Math.sin(n * 2 * Math.PI / 10),
  8143. y - radius * Math.cos(n * 2 * Math.PI / 10)
  8144. );
  8145. }
  8146. this.closePath();
  8147. };
  8148. /**
  8149. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  8150. */
  8151. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  8152. var r2d = Math.PI/180;
  8153. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  8154. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  8155. this.beginPath();
  8156. this.moveTo(x+r,y);
  8157. this.lineTo(x+w-r,y);
  8158. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  8159. this.lineTo(x+w,y+h-r);
  8160. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  8161. this.lineTo(x+r,y+h);
  8162. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  8163. this.lineTo(x,y+r);
  8164. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  8165. };
  8166. /**
  8167. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8168. */
  8169. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  8170. var kappa = .5522848,
  8171. ox = (w / 2) * kappa, // control point offset horizontal
  8172. oy = (h / 2) * kappa, // control point offset vertical
  8173. xe = x + w, // x-end
  8174. ye = y + h, // y-end
  8175. xm = x + w / 2, // x-middle
  8176. ym = y + h / 2; // y-middle
  8177. this.beginPath();
  8178. this.moveTo(x, ym);
  8179. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8180. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8181. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8182. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8183. };
  8184. /**
  8185. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8186. */
  8187. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  8188. var f = 1/3;
  8189. var wEllipse = w;
  8190. var hEllipse = h * f;
  8191. var kappa = .5522848,
  8192. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  8193. oy = (hEllipse / 2) * kappa, // control point offset vertical
  8194. xe = x + wEllipse, // x-end
  8195. ye = y + hEllipse, // y-end
  8196. xm = x + wEllipse / 2, // x-middle
  8197. ym = y + hEllipse / 2, // y-middle
  8198. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  8199. yeb = y + h; // y-end, bottom ellipse
  8200. this.beginPath();
  8201. this.moveTo(xe, ym);
  8202. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8203. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8204. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8205. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8206. this.lineTo(xe, ymb);
  8207. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  8208. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  8209. this.lineTo(x, ym);
  8210. };
  8211. /**
  8212. * Draw an arrow point (no line)
  8213. */
  8214. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  8215. // tail
  8216. var xt = x - length * Math.cos(angle);
  8217. var yt = y - length * Math.sin(angle);
  8218. // inner tail
  8219. // TODO: allow to customize different shapes
  8220. var xi = x - length * 0.9 * Math.cos(angle);
  8221. var yi = y - length * 0.9 * Math.sin(angle);
  8222. // left
  8223. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  8224. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  8225. // right
  8226. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  8227. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  8228. this.beginPath();
  8229. this.moveTo(x, y);
  8230. this.lineTo(xl, yl);
  8231. this.lineTo(xi, yi);
  8232. this.lineTo(xr, yr);
  8233. this.closePath();
  8234. };
  8235. /**
  8236. * Sets up the dashedLine functionality for drawing
  8237. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  8238. * @author David Jordan
  8239. * @date 2012-08-08
  8240. */
  8241. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  8242. if (!dashArray) dashArray=[10,5];
  8243. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  8244. var dashCount = dashArray.length;
  8245. this.moveTo(x, y);
  8246. var dx = (x2-x), dy = (y2-y);
  8247. var slope = dy/dx;
  8248. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  8249. var dashIndex=0, draw=true;
  8250. while (distRemaining>=0.1){
  8251. var dashLength = dashArray[dashIndex++%dashCount];
  8252. if (dashLength > distRemaining) dashLength = distRemaining;
  8253. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  8254. if (dx<0) xStep = -xStep;
  8255. x += xStep;
  8256. y += slope*xStep;
  8257. this[draw ? 'lineTo' : 'moveTo'](x,y);
  8258. distRemaining -= dashLength;
  8259. draw = !draw;
  8260. }
  8261. };
  8262. // TODO: add diamond shape
  8263. }
  8264. /**
  8265. * @class Node
  8266. * A node. A node can be connected to other nodes via one or multiple edges.
  8267. * @param {object} properties An object containing properties for the node. All
  8268. * properties are optional, except for the id.
  8269. * {number} id Id of the node. Required
  8270. * {string} label Text label for the node
  8271. * {number} x Horizontal position of the node
  8272. * {number} y Vertical position of the node
  8273. * {string} shape Node shape, available:
  8274. * "database", "circle", "ellipse",
  8275. * "box", "image", "text", "dot",
  8276. * "star", "triangle", "triangleDown",
  8277. * "square"
  8278. * {string} image An image url
  8279. * {string} title An title text, can be HTML
  8280. * {anytype} group A group name or number
  8281. * @param {Graph.Images} imagelist A list with images. Only needed
  8282. * when the node has an image
  8283. * @param {Graph.Groups} grouplist A list with groups. Needed for
  8284. * retrieving group properties
  8285. * @param {Object} constants An object with default values for
  8286. * example for the color
  8287. *
  8288. */
  8289. function Node(properties, imagelist, grouplist, constants) {
  8290. this.selected = false;
  8291. this.edges = []; // all edges connected to this node
  8292. this.dynamicEdges = [];
  8293. this.reroutedEdges = {};
  8294. this.group = constants.nodes.group;
  8295. this.fontSize = constants.nodes.fontSize;
  8296. this.fontFace = constants.nodes.fontFace;
  8297. this.fontColor = constants.nodes.fontColor;
  8298. this.fontDrawThreshold = 3;
  8299. this.color = constants.nodes.color;
  8300. // set defaults for the properties
  8301. this.id = undefined;
  8302. this.shape = constants.nodes.shape;
  8303. this.image = constants.nodes.image;
  8304. this.x = null;
  8305. this.y = null;
  8306. this.xFixed = false;
  8307. this.yFixed = false;
  8308. this.horizontalAlignLeft = true; // these are for the navigation controls
  8309. this.verticalAlignTop = true; // these are for the navigation controls
  8310. this.radius = constants.nodes.radius;
  8311. this.baseRadiusValue = constants.nodes.radius;
  8312. this.radiusFixed = false;
  8313. this.radiusMin = constants.nodes.radiusMin;
  8314. this.radiusMax = constants.nodes.radiusMax;
  8315. this.level = -1;
  8316. this.preassignedLevel = false;
  8317. this.imagelist = imagelist;
  8318. this.grouplist = grouplist;
  8319. // physics properties
  8320. this.fx = 0.0; // external force x
  8321. this.fy = 0.0; // external force y
  8322. this.vx = 0.0; // velocity x
  8323. this.vy = 0.0; // velocity y
  8324. this.minForce = constants.minForce;
  8325. this.damping = constants.physics.damping;
  8326. this.mass = 1; // kg
  8327. this.fixedData = {x:null,y:null};
  8328. this.setProperties(properties, constants);
  8329. // creating the variables for clustering
  8330. this.resetCluster();
  8331. this.dynamicEdgesLength = 0;
  8332. this.clusterSession = 0;
  8333. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  8334. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  8335. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  8336. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  8337. this.growthIndicator = 0;
  8338. // variables to tell the node about the graph.
  8339. this.graphScaleInv = 1;
  8340. this.graphScale = 1;
  8341. this.canvasTopLeft = {"x": -300, "y": -300};
  8342. this.canvasBottomRight = {"x": 300, "y": 300};
  8343. this.parentEdgeId = null;
  8344. }
  8345. /**
  8346. * (re)setting the clustering variables and objects
  8347. */
  8348. Node.prototype.resetCluster = function() {
  8349. // clustering variables
  8350. this.formationScale = undefined; // this is used to determine when to open the cluster
  8351. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  8352. this.containedNodes = {};
  8353. this.containedEdges = {};
  8354. this.clusterSessions = [];
  8355. };
  8356. /**
  8357. * Attach a edge to the node
  8358. * @param {Edge} edge
  8359. */
  8360. Node.prototype.attachEdge = function(edge) {
  8361. if (this.edges.indexOf(edge) == -1) {
  8362. this.edges.push(edge);
  8363. }
  8364. if (this.dynamicEdges.indexOf(edge) == -1) {
  8365. this.dynamicEdges.push(edge);
  8366. }
  8367. this.dynamicEdgesLength = this.dynamicEdges.length;
  8368. };
  8369. /**
  8370. * Detach a edge from the node
  8371. * @param {Edge} edge
  8372. */
  8373. Node.prototype.detachEdge = function(edge) {
  8374. var index = this.edges.indexOf(edge);
  8375. if (index != -1) {
  8376. this.edges.splice(index, 1);
  8377. this.dynamicEdges.splice(index, 1);
  8378. }
  8379. this.dynamicEdgesLength = this.dynamicEdges.length;
  8380. };
  8381. /**
  8382. * Set or overwrite properties for the node
  8383. * @param {Object} properties an object with properties
  8384. * @param {Object} constants and object with default, global properties
  8385. */
  8386. Node.prototype.setProperties = function(properties, constants) {
  8387. if (!properties) {
  8388. return;
  8389. }
  8390. this.originalLabel = undefined;
  8391. // basic properties
  8392. if (properties.id !== undefined) {this.id = properties.id;}
  8393. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  8394. if (properties.title !== undefined) {this.title = properties.title;}
  8395. if (properties.group !== undefined) {this.group = properties.group;}
  8396. if (properties.x !== undefined) {this.x = properties.x;}
  8397. if (properties.y !== undefined) {this.y = properties.y;}
  8398. if (properties.value !== undefined) {this.value = properties.value;}
  8399. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  8400. // physics
  8401. if (properties.mass !== undefined) {this.mass = properties.mass;}
  8402. // navigation controls properties
  8403. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  8404. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  8405. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  8406. if (this.id === undefined) {
  8407. throw "Node must have an id";
  8408. }
  8409. // copy group properties
  8410. if (this.group) {
  8411. var groupObj = this.grouplist.get(this.group);
  8412. for (var prop in groupObj) {
  8413. if (groupObj.hasOwnProperty(prop)) {
  8414. this[prop] = groupObj[prop];
  8415. }
  8416. }
  8417. }
  8418. // individual shape properties
  8419. if (properties.shape !== undefined) {this.shape = properties.shape;}
  8420. if (properties.image !== undefined) {this.image = properties.image;}
  8421. if (properties.radius !== undefined) {this.radius = properties.radius;}
  8422. if (properties.color !== undefined) {this.color = Node.parseColor(properties.color);}
  8423. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8424. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8425. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8426. if (this.image !== undefined && this.image != "") {
  8427. if (this.imagelist) {
  8428. this.imageObj = this.imagelist.load(this.image);
  8429. }
  8430. else {
  8431. throw "No imagelist provided";
  8432. }
  8433. }
  8434. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX);
  8435. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  8436. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  8437. if (this.shape == 'image') {
  8438. this.radiusMin = constants.nodes.widthMin;
  8439. this.radiusMax = constants.nodes.widthMax;
  8440. }
  8441. // choose draw method depending on the shape
  8442. switch (this.shape) {
  8443. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  8444. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  8445. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  8446. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8447. // TODO: add diamond shape
  8448. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  8449. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  8450. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  8451. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  8452. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  8453. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  8454. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  8455. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8456. }
  8457. // reset the size of the node, this can be changed
  8458. this._reset();
  8459. };
  8460. /**
  8461. * Parse a color property into an object with border, background, and
  8462. * hightlight colors
  8463. * @param {Object | String} color
  8464. * @return {Object} colorObject
  8465. */
  8466. Node.parseColor = function(color) {
  8467. var c;
  8468. if (util.isString(color)) {
  8469. if (util.isValidHex(color)) {
  8470. var hsv = util.hexToHSV(color);
  8471. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  8472. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  8473. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  8474. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  8475. c = {
  8476. background: color,
  8477. border:darkerColorHex,
  8478. highlight: {
  8479. background:lighterColorHex,
  8480. border:darkerColorHex
  8481. }
  8482. };
  8483. }
  8484. else {
  8485. c = {
  8486. background:color,
  8487. border:color,
  8488. highlight: {
  8489. background:color,
  8490. border:color
  8491. }
  8492. };
  8493. }
  8494. }
  8495. else {
  8496. c = {};
  8497. c.background = color.background || 'white';
  8498. c.border = color.border || c.background;
  8499. if (util.isString(color.highlight)) {
  8500. c.highlight = {
  8501. border: color.highlight,
  8502. background: color.highlight
  8503. }
  8504. }
  8505. else {
  8506. c.highlight = {};
  8507. c.highlight.background = color.highlight && color.highlight.background || c.background;
  8508. c.highlight.border = color.highlight && color.highlight.border || c.border;
  8509. }
  8510. }
  8511. return c;
  8512. };
  8513. /**
  8514. * select this node
  8515. */
  8516. Node.prototype.select = function() {
  8517. this.selected = true;
  8518. this._reset();
  8519. };
  8520. /**
  8521. * unselect this node
  8522. */
  8523. Node.prototype.unselect = function() {
  8524. this.selected = false;
  8525. this._reset();
  8526. };
  8527. /**
  8528. * Reset the calculated size of the node, forces it to recalculate its size
  8529. */
  8530. Node.prototype.clearSizeCache = function() {
  8531. this._reset();
  8532. };
  8533. /**
  8534. * Reset the calculated size of the node, forces it to recalculate its size
  8535. * @private
  8536. */
  8537. Node.prototype._reset = function() {
  8538. this.width = undefined;
  8539. this.height = undefined;
  8540. };
  8541. /**
  8542. * get the title of this node.
  8543. * @return {string} title The title of the node, or undefined when no title
  8544. * has been set.
  8545. */
  8546. Node.prototype.getTitle = function() {
  8547. return this.title;
  8548. };
  8549. /**
  8550. * Calculate the distance to the border of the Node
  8551. * @param {CanvasRenderingContext2D} ctx
  8552. * @param {Number} angle Angle in radians
  8553. * @returns {number} distance Distance to the border in pixels
  8554. */
  8555. Node.prototype.distanceToBorder = function (ctx, angle) {
  8556. var borderWidth = 1;
  8557. if (!this.width) {
  8558. this.resize(ctx);
  8559. }
  8560. switch (this.shape) {
  8561. case 'circle':
  8562. case 'dot':
  8563. return this.radius + borderWidth;
  8564. case 'ellipse':
  8565. var a = this.width / 2;
  8566. var b = this.height / 2;
  8567. var w = (Math.sin(angle) * a);
  8568. var h = (Math.cos(angle) * b);
  8569. return a * b / Math.sqrt(w * w + h * h);
  8570. // TODO: implement distanceToBorder for database
  8571. // TODO: implement distanceToBorder for triangle
  8572. // TODO: implement distanceToBorder for triangleDown
  8573. case 'box':
  8574. case 'image':
  8575. case 'text':
  8576. default:
  8577. if (this.width) {
  8578. return Math.min(
  8579. Math.abs(this.width / 2 / Math.cos(angle)),
  8580. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8581. // TODO: reckon with border radius too in case of box
  8582. }
  8583. else {
  8584. return 0;
  8585. }
  8586. }
  8587. // TODO: implement calculation of distance to border for all shapes
  8588. };
  8589. /**
  8590. * Set forces acting on the node
  8591. * @param {number} fx Force in horizontal direction
  8592. * @param {number} fy Force in vertical direction
  8593. */
  8594. Node.prototype._setForce = function(fx, fy) {
  8595. this.fx = fx;
  8596. this.fy = fy;
  8597. };
  8598. /**
  8599. * Add forces acting on the node
  8600. * @param {number} fx Force in horizontal direction
  8601. * @param {number} fy Force in vertical direction
  8602. * @private
  8603. */
  8604. Node.prototype._addForce = function(fx, fy) {
  8605. this.fx += fx;
  8606. this.fy += fy;
  8607. };
  8608. /**
  8609. * Perform one discrete step for the node
  8610. * @param {number} interval Time interval in seconds
  8611. */
  8612. Node.prototype.discreteStep = function(interval) {
  8613. if (!this.xFixed) {
  8614. var dx = this.damping * this.vx; // damping force
  8615. var ax = (this.fx - dx) / this.mass; // acceleration
  8616. this.vx += ax * interval; // velocity
  8617. this.x += this.vx * interval; // position
  8618. }
  8619. if (!this.yFixed) {
  8620. var dy = this.damping * this.vy; // damping force
  8621. var ay = (this.fy - dy) / this.mass; // acceleration
  8622. this.vy += ay * interval; // velocity
  8623. this.y += this.vy * interval; // position
  8624. }
  8625. };
  8626. /**
  8627. * Perform one discrete step for the node
  8628. * @param {number} interval Time interval in seconds
  8629. */
  8630. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8631. if (!this.xFixed) {
  8632. var dx = this.damping * this.vx; // damping force
  8633. var ax = (this.fx - dx) / this.mass; // acceleration
  8634. this.vx += ax * interval; // velocity
  8635. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8636. this.x += this.vx * interval; // position
  8637. }
  8638. else {
  8639. this.fx = 0;
  8640. }
  8641. if (!this.yFixed) {
  8642. var dy = this.damping * this.vy; // damping force
  8643. var ay = (this.fy - dy) / this.mass; // acceleration
  8644. this.vy += ay * interval; // velocity
  8645. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8646. this.y += this.vy * interval; // position
  8647. }
  8648. else {
  8649. this.fy = 0;
  8650. }
  8651. };
  8652. /**
  8653. * Check if this node has a fixed x and y position
  8654. * @return {boolean} true if fixed, false if not
  8655. */
  8656. Node.prototype.isFixed = function() {
  8657. return (this.xFixed && this.yFixed);
  8658. };
  8659. /**
  8660. * Check if this node is moving
  8661. * @param {number} vmin the minimum velocity considered as "moving"
  8662. * @return {boolean} true if moving, false if it has no velocity
  8663. */
  8664. // TODO: replace this method with calculating the kinetic energy
  8665. Node.prototype.isMoving = function(vmin) {
  8666. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8667. };
  8668. /**
  8669. * check if this node is selecte
  8670. * @return {boolean} selected True if node is selected, else false
  8671. */
  8672. Node.prototype.isSelected = function() {
  8673. return this.selected;
  8674. };
  8675. /**
  8676. * Retrieve the value of the node. Can be undefined
  8677. * @return {Number} value
  8678. */
  8679. Node.prototype.getValue = function() {
  8680. return this.value;
  8681. };
  8682. /**
  8683. * Calculate the distance from the nodes location to the given location (x,y)
  8684. * @param {Number} x
  8685. * @param {Number} y
  8686. * @return {Number} value
  8687. */
  8688. Node.prototype.getDistance = function(x, y) {
  8689. var dx = this.x - x,
  8690. dy = this.y - y;
  8691. return Math.sqrt(dx * dx + dy * dy);
  8692. };
  8693. /**
  8694. * Adjust the value range of the node. The node will adjust it's radius
  8695. * based on its value.
  8696. * @param {Number} min
  8697. * @param {Number} max
  8698. */
  8699. Node.prototype.setValueRange = function(min, max) {
  8700. if (!this.radiusFixed && this.value !== undefined) {
  8701. if (max == min) {
  8702. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8703. }
  8704. else {
  8705. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8706. this.radius = (this.value - min) * scale + this.radiusMin;
  8707. }
  8708. }
  8709. this.baseRadiusValue = this.radius;
  8710. };
  8711. /**
  8712. * Draw this node in the given canvas
  8713. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8714. * @param {CanvasRenderingContext2D} ctx
  8715. */
  8716. Node.prototype.draw = function(ctx) {
  8717. throw "Draw method not initialized for node";
  8718. };
  8719. /**
  8720. * Recalculate the size of this node in the given canvas
  8721. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8722. * @param {CanvasRenderingContext2D} ctx
  8723. */
  8724. Node.prototype.resize = function(ctx) {
  8725. throw "Resize method not initialized for node";
  8726. };
  8727. /**
  8728. * Check if this object is overlapping with the provided object
  8729. * @param {Object} obj an object with parameters left, top, right, bottom
  8730. * @return {boolean} True if location is located on node
  8731. */
  8732. Node.prototype.isOverlappingWith = function(obj) {
  8733. return (this.left < obj.right &&
  8734. this.left + this.width > obj.left &&
  8735. this.top < obj.bottom &&
  8736. this.top + this.height > obj.top);
  8737. };
  8738. Node.prototype._resizeImage = function (ctx) {
  8739. // TODO: pre calculate the image size
  8740. if (!this.width || !this.height) { // undefined or 0
  8741. var width, height;
  8742. if (this.value) {
  8743. this.radius = this.baseRadiusValue;
  8744. var scale = this.imageObj.height / this.imageObj.width;
  8745. if (scale !== undefined) {
  8746. width = this.radius || this.imageObj.width;
  8747. height = this.radius * scale || this.imageObj.height;
  8748. }
  8749. else {
  8750. width = 0;
  8751. height = 0;
  8752. }
  8753. }
  8754. else {
  8755. width = this.imageObj.width;
  8756. height = this.imageObj.height;
  8757. }
  8758. this.width = width;
  8759. this.height = height;
  8760. this.growthIndicator = 0;
  8761. if (this.width > 0 && this.height > 0) {
  8762. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8763. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8764. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8765. this.growthIndicator = this.width - width;
  8766. }
  8767. }
  8768. };
  8769. Node.prototype._drawImage = function (ctx) {
  8770. this._resizeImage(ctx);
  8771. this.left = this.x - this.width / 2;
  8772. this.top = this.y - this.height / 2;
  8773. var yLabel;
  8774. if (this.imageObj.width != 0 ) {
  8775. // draw the shade
  8776. if (this.clusterSize > 1) {
  8777. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8778. lineWidth *= this.graphScaleInv;
  8779. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8780. ctx.globalAlpha = 0.5;
  8781. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8782. }
  8783. // draw the image
  8784. ctx.globalAlpha = 1.0;
  8785. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8786. yLabel = this.y + this.height / 2;
  8787. }
  8788. else {
  8789. // image still loading... just draw the label for now
  8790. yLabel = this.y;
  8791. }
  8792. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8793. };
  8794. Node.prototype._resizeBox = function (ctx) {
  8795. if (!this.width) {
  8796. var margin = 5;
  8797. var textSize = this.getTextSize(ctx);
  8798. this.width = textSize.width + 2 * margin;
  8799. this.height = textSize.height + 2 * margin;
  8800. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8801. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8802. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8803. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8804. }
  8805. };
  8806. Node.prototype._drawBox = function (ctx) {
  8807. this._resizeBox(ctx);
  8808. this.left = this.x - this.width / 2;
  8809. this.top = this.y - this.height / 2;
  8810. var clusterLineWidth = 2.5;
  8811. var selectionLineWidth = 2;
  8812. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8813. // draw the outer border
  8814. if (this.clusterSize > 1) {
  8815. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8816. ctx.lineWidth *= this.graphScaleInv;
  8817. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8818. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8819. ctx.stroke();
  8820. }
  8821. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8822. ctx.lineWidth *= this.graphScaleInv;
  8823. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8824. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8825. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8826. ctx.fill();
  8827. ctx.stroke();
  8828. this._label(ctx, this.label, this.x, this.y);
  8829. };
  8830. Node.prototype._resizeDatabase = function (ctx) {
  8831. if (!this.width) {
  8832. var margin = 5;
  8833. var textSize = this.getTextSize(ctx);
  8834. var size = textSize.width + 2 * margin;
  8835. this.width = size;
  8836. this.height = size;
  8837. // scaling used for clustering
  8838. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8839. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8840. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8841. this.growthIndicator = this.width - size;
  8842. }
  8843. };
  8844. Node.prototype._drawDatabase = function (ctx) {
  8845. this._resizeDatabase(ctx);
  8846. this.left = this.x - this.width / 2;
  8847. this.top = this.y - this.height / 2;
  8848. var clusterLineWidth = 2.5;
  8849. var selectionLineWidth = 2;
  8850. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8851. // draw the outer border
  8852. if (this.clusterSize > 1) {
  8853. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8854. ctx.lineWidth *= this.graphScaleInv;
  8855. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8856. 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);
  8857. ctx.stroke();
  8858. }
  8859. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8860. ctx.lineWidth *= this.graphScaleInv;
  8861. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8862. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8863. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8864. ctx.fill();
  8865. ctx.stroke();
  8866. this._label(ctx, this.label, this.x, this.y);
  8867. };
  8868. Node.prototype._resizeCircle = function (ctx) {
  8869. if (!this.width) {
  8870. var margin = 5;
  8871. var textSize = this.getTextSize(ctx);
  8872. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8873. this.radius = diameter / 2;
  8874. this.width = diameter;
  8875. this.height = diameter;
  8876. // scaling used for clustering
  8877. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8878. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8879. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8880. this.growthIndicator = this.radius - 0.5*diameter;
  8881. }
  8882. };
  8883. Node.prototype._drawCircle = function (ctx) {
  8884. this._resizeCircle(ctx);
  8885. this.left = this.x - this.width / 2;
  8886. this.top = this.y - this.height / 2;
  8887. var clusterLineWidth = 2.5;
  8888. var selectionLineWidth = 2;
  8889. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8890. // draw the outer border
  8891. if (this.clusterSize > 1) {
  8892. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8893. ctx.lineWidth *= this.graphScaleInv;
  8894. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8895. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8896. ctx.stroke();
  8897. }
  8898. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8899. ctx.lineWidth *= this.graphScaleInv;
  8900. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8901. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8902. ctx.circle(this.x, this.y, this.radius);
  8903. ctx.fill();
  8904. ctx.stroke();
  8905. this._label(ctx, this.label, this.x, this.y);
  8906. };
  8907. Node.prototype._resizeEllipse = function (ctx) {
  8908. if (!this.width) {
  8909. var textSize = this.getTextSize(ctx);
  8910. this.width = textSize.width * 1.5;
  8911. this.height = textSize.height * 2;
  8912. if (this.width < this.height) {
  8913. this.width = this.height;
  8914. }
  8915. var defaultSize = this.width;
  8916. // scaling used for clustering
  8917. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8918. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8919. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8920. this.growthIndicator = this.width - defaultSize;
  8921. }
  8922. };
  8923. Node.prototype._drawEllipse = function (ctx) {
  8924. this._resizeEllipse(ctx);
  8925. this.left = this.x - this.width / 2;
  8926. this.top = this.y - this.height / 2;
  8927. var clusterLineWidth = 2.5;
  8928. var selectionLineWidth = 2;
  8929. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8930. // draw the outer border
  8931. if (this.clusterSize > 1) {
  8932. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8933. ctx.lineWidth *= this.graphScaleInv;
  8934. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8935. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8936. ctx.stroke();
  8937. }
  8938. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8939. ctx.lineWidth *= this.graphScaleInv;
  8940. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8941. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8942. ctx.ellipse(this.left, this.top, this.width, this.height);
  8943. ctx.fill();
  8944. ctx.stroke();
  8945. this._label(ctx, this.label, this.x, this.y);
  8946. };
  8947. Node.prototype._drawDot = function (ctx) {
  8948. this._drawShape(ctx, 'circle');
  8949. };
  8950. Node.prototype._drawTriangle = function (ctx) {
  8951. this._drawShape(ctx, 'triangle');
  8952. };
  8953. Node.prototype._drawTriangleDown = function (ctx) {
  8954. this._drawShape(ctx, 'triangleDown');
  8955. };
  8956. Node.prototype._drawSquare = function (ctx) {
  8957. this._drawShape(ctx, 'square');
  8958. };
  8959. Node.prototype._drawStar = function (ctx) {
  8960. this._drawShape(ctx, 'star');
  8961. };
  8962. Node.prototype._resizeShape = function (ctx) {
  8963. if (!this.width) {
  8964. this.radius = this.baseRadiusValue;
  8965. var size = 2 * this.radius;
  8966. this.width = size;
  8967. this.height = size;
  8968. // scaling used for clustering
  8969. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8970. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8971. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8972. this.growthIndicator = this.width - size;
  8973. }
  8974. };
  8975. Node.prototype._drawShape = function (ctx, shape) {
  8976. this._resizeShape(ctx);
  8977. this.left = this.x - this.width / 2;
  8978. this.top = this.y - this.height / 2;
  8979. var clusterLineWidth = 2.5;
  8980. var selectionLineWidth = 2;
  8981. var radiusMultiplier = 2;
  8982. // choose draw method depending on the shape
  8983. switch (shape) {
  8984. case 'dot': radiusMultiplier = 2; break;
  8985. case 'square': radiusMultiplier = 2; break;
  8986. case 'triangle': radiusMultiplier = 3; break;
  8987. case 'triangleDown': radiusMultiplier = 3; break;
  8988. case 'star': radiusMultiplier = 4; break;
  8989. }
  8990. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8991. // draw the outer border
  8992. if (this.clusterSize > 1) {
  8993. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8994. ctx.lineWidth *= this.graphScaleInv;
  8995. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8996. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8997. ctx.stroke();
  8998. }
  8999. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  9000. ctx.lineWidth *= this.graphScaleInv;
  9001. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  9002. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  9003. ctx[shape](this.x, this.y, this.radius);
  9004. ctx.fill();
  9005. ctx.stroke();
  9006. if (this.label) {
  9007. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  9008. }
  9009. };
  9010. Node.prototype._resizeText = function (ctx) {
  9011. if (!this.width) {
  9012. var margin = 5;
  9013. var textSize = this.getTextSize(ctx);
  9014. this.width = textSize.width + 2 * margin;
  9015. this.height = textSize.height + 2 * margin;
  9016. // scaling used for clustering
  9017. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  9018. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  9019. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  9020. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  9021. }
  9022. };
  9023. Node.prototype._drawText = function (ctx) {
  9024. this._resizeText(ctx);
  9025. this.left = this.x - this.width / 2;
  9026. this.top = this.y - this.height / 2;
  9027. this._label(ctx, this.label, this.x, this.y);
  9028. };
  9029. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  9030. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  9031. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9032. ctx.fillStyle = this.fontColor || "black";
  9033. ctx.textAlign = align || "center";
  9034. ctx.textBaseline = baseline || "middle";
  9035. var lines = text.split('\n'),
  9036. lineCount = lines.length,
  9037. fontSize = (this.fontSize + 4),
  9038. yLine = y + (1 - lineCount) / 2 * fontSize;
  9039. for (var i = 0; i < lineCount; i++) {
  9040. ctx.fillText(lines[i], x, yLine);
  9041. yLine += fontSize;
  9042. }
  9043. }
  9044. };
  9045. Node.prototype.getTextSize = function(ctx) {
  9046. if (this.label !== undefined) {
  9047. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9048. var lines = this.label.split('\n'),
  9049. height = (this.fontSize + 4) * lines.length,
  9050. width = 0;
  9051. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  9052. width = Math.max(width, ctx.measureText(lines[i]).width);
  9053. }
  9054. return {"width": width, "height": height};
  9055. }
  9056. else {
  9057. return {"width": 0, "height": 0};
  9058. }
  9059. };
  9060. /**
  9061. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  9062. * there is a safety margin of 0.3 * width;
  9063. *
  9064. * @returns {boolean}
  9065. */
  9066. Node.prototype.inArea = function() {
  9067. if (this.width !== undefined) {
  9068. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  9069. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  9070. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  9071. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  9072. }
  9073. else {
  9074. return true;
  9075. }
  9076. };
  9077. /**
  9078. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  9079. * @returns {boolean}
  9080. */
  9081. Node.prototype.inView = function() {
  9082. return (this.x >= this.canvasTopLeft.x &&
  9083. this.x < this.canvasBottomRight.x &&
  9084. this.y >= this.canvasTopLeft.y &&
  9085. this.y < this.canvasBottomRight.y);
  9086. };
  9087. /**
  9088. * This allows the zoom level of the graph to influence the rendering
  9089. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  9090. *
  9091. * @param scale
  9092. * @param canvasTopLeft
  9093. * @param canvasBottomRight
  9094. */
  9095. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  9096. this.graphScaleInv = 1.0/scale;
  9097. this.graphScale = scale;
  9098. this.canvasTopLeft = canvasTopLeft;
  9099. this.canvasBottomRight = canvasBottomRight;
  9100. };
  9101. /**
  9102. * This allows the zoom level of the graph to influence the rendering
  9103. *
  9104. * @param scale
  9105. */
  9106. Node.prototype.setScale = function(scale) {
  9107. this.graphScaleInv = 1.0/scale;
  9108. this.graphScale = scale;
  9109. };
  9110. /**
  9111. * set the velocity at 0. Is called when this node is contained in another during clustering
  9112. */
  9113. Node.prototype.clearVelocity = function() {
  9114. this.vx = 0;
  9115. this.vy = 0;
  9116. };
  9117. /**
  9118. * Basic preservation of (kinectic) energy
  9119. *
  9120. * @param massBeforeClustering
  9121. */
  9122. Node.prototype.updateVelocity = function(massBeforeClustering) {
  9123. var energyBefore = this.vx * this.vx * massBeforeClustering;
  9124. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9125. this.vx = Math.sqrt(energyBefore/this.mass);
  9126. energyBefore = this.vy * this.vy * massBeforeClustering;
  9127. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9128. this.vy = Math.sqrt(energyBefore/this.mass);
  9129. };
  9130. /**
  9131. * @class Edge
  9132. *
  9133. * A edge connects two nodes
  9134. * @param {Object} properties Object with properties. Must contain
  9135. * At least properties from and to.
  9136. * Available properties: from (number),
  9137. * to (number), label (string, color (string),
  9138. * width (number), style (string),
  9139. * length (number), title (string)
  9140. * @param {Graph} graph A graph object, used to find and edge to
  9141. * nodes.
  9142. * @param {Object} constants An object with default values for
  9143. * example for the color
  9144. */
  9145. function Edge (properties, graph, constants) {
  9146. if (!graph) {
  9147. throw "No graph provided";
  9148. }
  9149. this.graph = graph;
  9150. // initialize constants
  9151. this.widthMin = constants.edges.widthMin;
  9152. this.widthMax = constants.edges.widthMax;
  9153. // initialize variables
  9154. this.id = undefined;
  9155. this.fromId = undefined;
  9156. this.toId = undefined;
  9157. this.style = constants.edges.style;
  9158. this.title = undefined;
  9159. this.width = constants.edges.width;
  9160. this.value = undefined;
  9161. this.length = constants.physics.springLength;
  9162. this.customLength = false;
  9163. this.selected = false;
  9164. this.smooth = constants.smoothCurves;
  9165. this.from = null; // a node
  9166. this.to = null; // a node
  9167. this.via = null; // a temp node
  9168. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  9169. // by storing the original information we can revert to the original connection when the cluser is opened.
  9170. this.originalFromId = [];
  9171. this.originalToId = [];
  9172. this.connected = false;
  9173. // Added to support dashed lines
  9174. // David Jordan
  9175. // 2012-08-08
  9176. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  9177. this.color = {color:constants.edges.color.color,
  9178. highlight:constants.edges.color.highlight};
  9179. this.widthFixed = false;
  9180. this.lengthFixed = false;
  9181. this.setProperties(properties, constants);
  9182. }
  9183. /**
  9184. * Set or overwrite properties for the edge
  9185. * @param {Object} properties an object with properties
  9186. * @param {Object} constants and object with default, global properties
  9187. */
  9188. Edge.prototype.setProperties = function(properties, constants) {
  9189. if (!properties) {
  9190. return;
  9191. }
  9192. if (properties.from !== undefined) {this.fromId = properties.from;}
  9193. if (properties.to !== undefined) {this.toId = properties.to;}
  9194. if (properties.id !== undefined) {this.id = properties.id;}
  9195. if (properties.style !== undefined) {this.style = properties.style;}
  9196. if (properties.label !== undefined) {this.label = properties.label;}
  9197. if (this.label) {
  9198. this.fontSize = constants.edges.fontSize;
  9199. this.fontFace = constants.edges.fontFace;
  9200. this.fontColor = constants.edges.fontColor;
  9201. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  9202. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  9203. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  9204. }
  9205. if (properties.title !== undefined) {this.title = properties.title;}
  9206. if (properties.width !== undefined) {this.width = properties.width;}
  9207. if (properties.value !== undefined) {this.value = properties.value;}
  9208. if (properties.length !== undefined) {this.length = properties.length;
  9209. this.customLength = true;}
  9210. // Added to support dashed lines
  9211. // David Jordan
  9212. // 2012-08-08
  9213. if (properties.dash) {
  9214. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  9215. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  9216. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  9217. }
  9218. if (properties.color !== undefined) {
  9219. if (util.isString(properties.color)) {
  9220. this.color.color = properties.color;
  9221. this.color.highlight = properties.color;
  9222. }
  9223. else {
  9224. if (properties.color.color !== undefined) {this.color.color = properties.color.color;}
  9225. if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;}
  9226. }
  9227. }
  9228. // A node is connected when it has a from and to node.
  9229. this.connect();
  9230. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  9231. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  9232. // set draw method based on style
  9233. switch (this.style) {
  9234. case 'line': this.draw = this._drawLine; break;
  9235. case 'arrow': this.draw = this._drawArrow; break;
  9236. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  9237. case 'dash-line': this.draw = this._drawDashLine; break;
  9238. default: this.draw = this._drawLine; break;
  9239. }
  9240. };
  9241. /**
  9242. * Connect an edge to its nodes
  9243. */
  9244. Edge.prototype.connect = function () {
  9245. this.disconnect();
  9246. this.from = this.graph.nodes[this.fromId] || null;
  9247. this.to = this.graph.nodes[this.toId] || null;
  9248. this.connected = (this.from && this.to);
  9249. if (this.connected) {
  9250. this.from.attachEdge(this);
  9251. this.to.attachEdge(this);
  9252. }
  9253. else {
  9254. if (this.from) {
  9255. this.from.detachEdge(this);
  9256. }
  9257. if (this.to) {
  9258. this.to.detachEdge(this);
  9259. }
  9260. }
  9261. };
  9262. /**
  9263. * Disconnect an edge from its nodes
  9264. */
  9265. Edge.prototype.disconnect = function () {
  9266. if (this.from) {
  9267. this.from.detachEdge(this);
  9268. this.from = null;
  9269. }
  9270. if (this.to) {
  9271. this.to.detachEdge(this);
  9272. this.to = null;
  9273. }
  9274. this.connected = false;
  9275. };
  9276. /**
  9277. * get the title of this edge.
  9278. * @return {string} title The title of the edge, or undefined when no title
  9279. * has been set.
  9280. */
  9281. Edge.prototype.getTitle = function() {
  9282. return this.title;
  9283. };
  9284. /**
  9285. * Retrieve the value of the edge. Can be undefined
  9286. * @return {Number} value
  9287. */
  9288. Edge.prototype.getValue = function() {
  9289. return this.value;
  9290. };
  9291. /**
  9292. * Adjust the value range of the edge. The edge will adjust it's width
  9293. * based on its value.
  9294. * @param {Number} min
  9295. * @param {Number} max
  9296. */
  9297. Edge.prototype.setValueRange = function(min, max) {
  9298. if (!this.widthFixed && this.value !== undefined) {
  9299. var scale = (this.widthMax - this.widthMin) / (max - min);
  9300. this.width = (this.value - min) * scale + this.widthMin;
  9301. }
  9302. };
  9303. /**
  9304. * Redraw a edge
  9305. * Draw this edge in the given canvas
  9306. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9307. * @param {CanvasRenderingContext2D} ctx
  9308. */
  9309. Edge.prototype.draw = function(ctx) {
  9310. throw "Method draw not initialized in edge";
  9311. };
  9312. /**
  9313. * Check if this object is overlapping with the provided object
  9314. * @param {Object} obj an object with parameters left, top
  9315. * @return {boolean} True if location is located on the edge
  9316. */
  9317. Edge.prototype.isOverlappingWith = function(obj) {
  9318. if (this.connected) {
  9319. var distMax = 10;
  9320. var xFrom = this.from.x;
  9321. var yFrom = this.from.y;
  9322. var xTo = this.to.x;
  9323. var yTo = this.to.y;
  9324. var xObj = obj.left;
  9325. var yObj = obj.top;
  9326. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  9327. return (dist < distMax);
  9328. }
  9329. else {
  9330. return false
  9331. }
  9332. };
  9333. /**
  9334. * Redraw a edge as a line
  9335. * Draw this edge in the given canvas
  9336. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9337. * @param {CanvasRenderingContext2D} ctx
  9338. * @private
  9339. */
  9340. Edge.prototype._drawLine = function(ctx) {
  9341. // set style
  9342. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9343. else {ctx.strokeStyle = this.color.color;}
  9344. ctx.lineWidth = this._getLineWidth();
  9345. if (this.from != this.to) {
  9346. // draw line
  9347. this._line(ctx);
  9348. // draw label
  9349. var point;
  9350. if (this.label) {
  9351. if (this.smooth == true) {
  9352. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9353. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9354. point = {x:midpointX, y:midpointY};
  9355. }
  9356. else {
  9357. point = this._pointOnLine(0.5);
  9358. }
  9359. this._label(ctx, this.label, point.x, point.y);
  9360. }
  9361. }
  9362. else {
  9363. var x, y;
  9364. var radius = this.length / 4;
  9365. var node = this.from;
  9366. if (!node.width) {
  9367. node.resize(ctx);
  9368. }
  9369. if (node.width > node.height) {
  9370. x = node.x + node.width / 2;
  9371. y = node.y - radius;
  9372. }
  9373. else {
  9374. x = node.x + radius;
  9375. y = node.y - node.height / 2;
  9376. }
  9377. this._circle(ctx, x, y, radius);
  9378. point = this._pointOnCircle(x, y, radius, 0.5);
  9379. this._label(ctx, this.label, point.x, point.y);
  9380. }
  9381. };
  9382. /**
  9383. * Get the line width of the edge. Depends on width and whether one of the
  9384. * connected nodes is selected.
  9385. * @return {Number} width
  9386. * @private
  9387. */
  9388. Edge.prototype._getLineWidth = function() {
  9389. if (this.selected == true) {
  9390. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  9391. }
  9392. else {
  9393. return this.width*this.graphScaleInv;
  9394. }
  9395. };
  9396. /**
  9397. * Draw a line between two nodes
  9398. * @param {CanvasRenderingContext2D} ctx
  9399. * @private
  9400. */
  9401. Edge.prototype._line = function (ctx) {
  9402. // draw a straight line
  9403. ctx.beginPath();
  9404. ctx.moveTo(this.from.x, this.from.y);
  9405. if (this.smooth == true) {
  9406. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9407. }
  9408. else {
  9409. ctx.lineTo(this.to.x, this.to.y);
  9410. }
  9411. ctx.stroke();
  9412. };
  9413. /**
  9414. * Draw a line from a node to itself, a circle
  9415. * @param {CanvasRenderingContext2D} ctx
  9416. * @param {Number} x
  9417. * @param {Number} y
  9418. * @param {Number} radius
  9419. * @private
  9420. */
  9421. Edge.prototype._circle = function (ctx, x, y, radius) {
  9422. // draw a circle
  9423. ctx.beginPath();
  9424. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9425. ctx.stroke();
  9426. };
  9427. /**
  9428. * Draw label with white background and with the middle at (x, y)
  9429. * @param {CanvasRenderingContext2D} ctx
  9430. * @param {String} text
  9431. * @param {Number} x
  9432. * @param {Number} y
  9433. * @private
  9434. */
  9435. Edge.prototype._label = function (ctx, text, x, y) {
  9436. if (text) {
  9437. // TODO: cache the calculated size
  9438. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  9439. this.fontSize + "px " + this.fontFace;
  9440. ctx.fillStyle = 'white';
  9441. var width = ctx.measureText(text).width;
  9442. var height = this.fontSize;
  9443. var left = x - width / 2;
  9444. var top = y - height / 2;
  9445. ctx.fillRect(left, top, width, height);
  9446. // draw text
  9447. ctx.fillStyle = this.fontColor || "black";
  9448. ctx.textAlign = "left";
  9449. ctx.textBaseline = "top";
  9450. ctx.fillText(text, left, top);
  9451. }
  9452. };
  9453. /**
  9454. * Redraw a edge as a dashed line
  9455. * Draw this edge in the given canvas
  9456. * @author David Jordan
  9457. * @date 2012-08-08
  9458. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9459. * @param {CanvasRenderingContext2D} ctx
  9460. * @private
  9461. */
  9462. Edge.prototype._drawDashLine = function(ctx) {
  9463. // set style
  9464. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9465. else {ctx.strokeStyle = this.color.color;}
  9466. ctx.lineWidth = this._getLineWidth();
  9467. // only firefox and chrome support this method, else we use the legacy one.
  9468. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  9469. ctx.beginPath();
  9470. ctx.moveTo(this.from.x, this.from.y);
  9471. // configure the dash pattern
  9472. var pattern = [0];
  9473. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  9474. pattern = [this.dash.length,this.dash.gap];
  9475. }
  9476. else {
  9477. pattern = [5,5];
  9478. }
  9479. // set dash settings for chrome or firefox
  9480. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9481. ctx.setLineDash(pattern);
  9482. ctx.lineDashOffset = 0;
  9483. } else { //Firefox
  9484. ctx.mozDash = pattern;
  9485. ctx.mozDashOffset = 0;
  9486. }
  9487. // draw the line
  9488. if (this.smooth == true) {
  9489. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9490. }
  9491. else {
  9492. ctx.lineTo(this.to.x, this.to.y);
  9493. }
  9494. ctx.stroke();
  9495. // restore the dash settings.
  9496. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9497. ctx.setLineDash([0]);
  9498. ctx.lineDashOffset = 0;
  9499. } else { //Firefox
  9500. ctx.mozDash = [0];
  9501. ctx.mozDashOffset = 0;
  9502. }
  9503. }
  9504. else { // unsupporting smooth lines
  9505. // draw dashed line
  9506. ctx.beginPath();
  9507. ctx.lineCap = 'round';
  9508. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9509. {
  9510. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9511. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9512. }
  9513. 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
  9514. {
  9515. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9516. [this.dash.length,this.dash.gap]);
  9517. }
  9518. else //If all else fails draw a line
  9519. {
  9520. ctx.moveTo(this.from.x, this.from.y);
  9521. ctx.lineTo(this.to.x, this.to.y);
  9522. }
  9523. ctx.stroke();
  9524. }
  9525. // draw label
  9526. if (this.label) {
  9527. var point;
  9528. if (this.smooth == true) {
  9529. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9530. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9531. point = {x:midpointX, y:midpointY};
  9532. }
  9533. else {
  9534. point = this._pointOnLine(0.5);
  9535. }
  9536. this._label(ctx, this.label, point.x, point.y);
  9537. }
  9538. };
  9539. /**
  9540. * Get a point on a line
  9541. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9542. * @return {Object} point
  9543. * @private
  9544. */
  9545. Edge.prototype._pointOnLine = function (percentage) {
  9546. return {
  9547. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9548. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9549. }
  9550. };
  9551. /**
  9552. * Get a point on a circle
  9553. * @param {Number} x
  9554. * @param {Number} y
  9555. * @param {Number} radius
  9556. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9557. * @return {Object} point
  9558. * @private
  9559. */
  9560. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9561. var angle = (percentage - 3/8) * 2 * Math.PI;
  9562. return {
  9563. x: x + radius * Math.cos(angle),
  9564. y: y - radius * Math.sin(angle)
  9565. }
  9566. };
  9567. /**
  9568. * Redraw a edge as a line with an arrow halfway the line
  9569. * Draw this edge in the given canvas
  9570. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9571. * @param {CanvasRenderingContext2D} ctx
  9572. * @private
  9573. */
  9574. Edge.prototype._drawArrowCenter = function(ctx) {
  9575. var point;
  9576. // set style
  9577. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9578. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9579. ctx.lineWidth = this._getLineWidth();
  9580. if (this.from != this.to) {
  9581. // draw line
  9582. this._line(ctx);
  9583. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9584. var length = 10 + 5 * this.width; // TODO: make customizable?
  9585. // draw an arrow halfway the line
  9586. if (this.smooth == true) {
  9587. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9588. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9589. point = {x:midpointX, y:midpointY};
  9590. }
  9591. else {
  9592. point = this._pointOnLine(0.5);
  9593. }
  9594. ctx.arrow(point.x, point.y, angle, length);
  9595. ctx.fill();
  9596. ctx.stroke();
  9597. // draw label
  9598. if (this.label) {
  9599. this._label(ctx, this.label, point.x, point.y);
  9600. }
  9601. }
  9602. else {
  9603. // draw circle
  9604. var x, y;
  9605. var radius = 0.25 * Math.max(100,this.length);
  9606. var node = this.from;
  9607. if (!node.width) {
  9608. node.resize(ctx);
  9609. }
  9610. if (node.width > node.height) {
  9611. x = node.x + node.width * 0.5;
  9612. y = node.y - radius;
  9613. }
  9614. else {
  9615. x = node.x + radius;
  9616. y = node.y - node.height * 0.5;
  9617. }
  9618. this._circle(ctx, x, y, radius);
  9619. // draw all arrows
  9620. var angle = 0.2 * Math.PI;
  9621. var length = 10 + 5 * this.width; // TODO: make customizable?
  9622. point = this._pointOnCircle(x, y, radius, 0.5);
  9623. ctx.arrow(point.x, point.y, angle, length);
  9624. ctx.fill();
  9625. ctx.stroke();
  9626. // draw label
  9627. if (this.label) {
  9628. point = this._pointOnCircle(x, y, radius, 0.5);
  9629. this._label(ctx, this.label, point.x, point.y);
  9630. }
  9631. }
  9632. };
  9633. /**
  9634. * Redraw a edge as a line with an arrow
  9635. * Draw this edge in the given canvas
  9636. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9637. * @param {CanvasRenderingContext2D} ctx
  9638. * @private
  9639. */
  9640. Edge.prototype._drawArrow = function(ctx) {
  9641. // set style
  9642. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9643. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9644. ctx.lineWidth = this._getLineWidth();
  9645. var angle, length;
  9646. //draw a line
  9647. if (this.from != this.to) {
  9648. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9649. var dx = (this.to.x - this.from.x);
  9650. var dy = (this.to.y - this.from.y);
  9651. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9652. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9653. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9654. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9655. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9656. if (this.smooth == true) {
  9657. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9658. dx = (this.to.x - this.via.x);
  9659. dy = (this.to.y - this.via.y);
  9660. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9661. }
  9662. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9663. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9664. var xTo,yTo;
  9665. if (this.smooth == true) {
  9666. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9667. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9668. }
  9669. else {
  9670. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9671. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9672. }
  9673. ctx.beginPath();
  9674. ctx.moveTo(xFrom,yFrom);
  9675. if (this.smooth == true) {
  9676. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9677. }
  9678. else {
  9679. ctx.lineTo(xTo, yTo);
  9680. }
  9681. ctx.stroke();
  9682. // draw arrow at the end of the line
  9683. length = 10 + 5 * this.width;
  9684. ctx.arrow(xTo, yTo, angle, length);
  9685. ctx.fill();
  9686. ctx.stroke();
  9687. // draw label
  9688. if (this.label) {
  9689. var point;
  9690. if (this.smooth == true) {
  9691. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9692. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9693. point = {x:midpointX, y:midpointY};
  9694. }
  9695. else {
  9696. point = this._pointOnLine(0.5);
  9697. }
  9698. this._label(ctx, this.label, point.x, point.y);
  9699. }
  9700. }
  9701. else {
  9702. // draw circle
  9703. var node = this.from;
  9704. var x, y, arrow;
  9705. var radius = 0.25 * Math.max(100,this.length);
  9706. if (!node.width) {
  9707. node.resize(ctx);
  9708. }
  9709. if (node.width > node.height) {
  9710. x = node.x + node.width * 0.5;
  9711. y = node.y - radius;
  9712. arrow = {
  9713. x: x,
  9714. y: node.y,
  9715. angle: 0.9 * Math.PI
  9716. };
  9717. }
  9718. else {
  9719. x = node.x + radius;
  9720. y = node.y - node.height * 0.5;
  9721. arrow = {
  9722. x: node.x,
  9723. y: y,
  9724. angle: 0.6 * Math.PI
  9725. };
  9726. }
  9727. ctx.beginPath();
  9728. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9729. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9730. ctx.stroke();
  9731. // draw all arrows
  9732. length = 10 + 5 * this.width; // TODO: make customizable?
  9733. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9734. ctx.fill();
  9735. ctx.stroke();
  9736. // draw label
  9737. if (this.label) {
  9738. point = this._pointOnCircle(x, y, radius, 0.5);
  9739. this._label(ctx, this.label, point.x, point.y);
  9740. }
  9741. }
  9742. };
  9743. /**
  9744. * Calculate the distance between a point (x3,y3) and a line segment from
  9745. * (x1,y1) to (x2,y2).
  9746. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9747. * @param {number} x1
  9748. * @param {number} y1
  9749. * @param {number} x2
  9750. * @param {number} y2
  9751. * @param {number} x3
  9752. * @param {number} y3
  9753. * @private
  9754. */
  9755. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9756. if (this.smooth == true) {
  9757. var minDistance = 1e9;
  9758. var i,t,x,y,dx,dy;
  9759. for (i = 0; i < 10; i++) {
  9760. t = 0.1*i;
  9761. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9762. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9763. dx = Math.abs(x3-x);
  9764. dy = Math.abs(y3-y);
  9765. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9766. }
  9767. return minDistance
  9768. }
  9769. else {
  9770. var px = x2-x1,
  9771. py = y2-y1,
  9772. something = px*px + py*py,
  9773. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9774. if (u > 1) {
  9775. u = 1;
  9776. }
  9777. else if (u < 0) {
  9778. u = 0;
  9779. }
  9780. var x = x1 + u * px,
  9781. y = y1 + u * py,
  9782. dx = x - x3,
  9783. dy = y - y3;
  9784. //# Note: If the actual distance does not matter,
  9785. //# if you only want to compare what this function
  9786. //# returns to other results of this function, you
  9787. //# can just return the squared distance instead
  9788. //# (i.e. remove the sqrt) to gain a little performance
  9789. return Math.sqrt(dx*dx + dy*dy);
  9790. }
  9791. };
  9792. /**
  9793. * This allows the zoom level of the graph to influence the rendering
  9794. *
  9795. * @param scale
  9796. */
  9797. Edge.prototype.setScale = function(scale) {
  9798. this.graphScaleInv = 1.0/scale;
  9799. };
  9800. Edge.prototype.select = function() {
  9801. this.selected = true;
  9802. };
  9803. Edge.prototype.unselect = function() {
  9804. this.selected = false;
  9805. };
  9806. Edge.prototype.positionBezierNode = function() {
  9807. if (this.via !== null) {
  9808. this.via.x = 0.5 * (this.from.x + this.to.x);
  9809. this.via.y = 0.5 * (this.from.y + this.to.y);
  9810. }
  9811. };
  9812. /**
  9813. * Popup is a class to create a popup window with some text
  9814. * @param {Element} container The container object.
  9815. * @param {Number} [x]
  9816. * @param {Number} [y]
  9817. * @param {String} [text]
  9818. */
  9819. function Popup(container, x, y, text) {
  9820. if (container) {
  9821. this.container = container;
  9822. }
  9823. else {
  9824. this.container = document.body;
  9825. }
  9826. this.x = 0;
  9827. this.y = 0;
  9828. this.padding = 5;
  9829. if (x !== undefined && y !== undefined ) {
  9830. this.setPosition(x, y);
  9831. }
  9832. if (text !== undefined) {
  9833. this.setText(text);
  9834. }
  9835. // create the frame
  9836. this.frame = document.createElement("div");
  9837. var style = this.frame.style;
  9838. style.position = "absolute";
  9839. style.visibility = "hidden";
  9840. style.border = "1px solid #666";
  9841. style.color = "black";
  9842. style.padding = this.padding + "px";
  9843. style.backgroundColor = "#FFFFC6";
  9844. style.borderRadius = "3px";
  9845. style.MozBorderRadius = "3px";
  9846. style.WebkitBorderRadius = "3px";
  9847. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9848. style.whiteSpace = "nowrap";
  9849. this.container.appendChild(this.frame);
  9850. }
  9851. /**
  9852. * @param {number} x Horizontal position of the popup window
  9853. * @param {number} y Vertical position of the popup window
  9854. */
  9855. Popup.prototype.setPosition = function(x, y) {
  9856. this.x = parseInt(x);
  9857. this.y = parseInt(y);
  9858. };
  9859. /**
  9860. * Set the text for the popup window. This can be HTML code
  9861. * @param {string} text
  9862. */
  9863. Popup.prototype.setText = function(text) {
  9864. this.frame.innerHTML = text;
  9865. };
  9866. /**
  9867. * Show the popup window
  9868. * @param {boolean} show Optional. Show or hide the window
  9869. */
  9870. Popup.prototype.show = function (show) {
  9871. if (show === undefined) {
  9872. show = true;
  9873. }
  9874. if (show) {
  9875. var height = this.frame.clientHeight;
  9876. var width = this.frame.clientWidth;
  9877. var maxHeight = this.frame.parentNode.clientHeight;
  9878. var maxWidth = this.frame.parentNode.clientWidth;
  9879. var top = (this.y - height);
  9880. if (top + height + this.padding > maxHeight) {
  9881. top = maxHeight - height - this.padding;
  9882. }
  9883. if (top < this.padding) {
  9884. top = this.padding;
  9885. }
  9886. var left = this.x;
  9887. if (left + width + this.padding > maxWidth) {
  9888. left = maxWidth - width - this.padding;
  9889. }
  9890. if (left < this.padding) {
  9891. left = this.padding;
  9892. }
  9893. this.frame.style.left = left + "px";
  9894. this.frame.style.top = top + "px";
  9895. this.frame.style.visibility = "visible";
  9896. }
  9897. else {
  9898. this.hide();
  9899. }
  9900. };
  9901. /**
  9902. * Hide the popup window
  9903. */
  9904. Popup.prototype.hide = function () {
  9905. this.frame.style.visibility = "hidden";
  9906. };
  9907. /**
  9908. * @class Groups
  9909. * This class can store groups and properties specific for groups.
  9910. */
  9911. Groups = function () {
  9912. this.clear();
  9913. this.defaultIndex = 0;
  9914. };
  9915. /**
  9916. * default constants for group colors
  9917. */
  9918. Groups.DEFAULT = [
  9919. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9920. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9921. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9922. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9923. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9924. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9925. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9926. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9927. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9928. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9929. ];
  9930. /**
  9931. * Clear all groups
  9932. */
  9933. Groups.prototype.clear = function () {
  9934. this.groups = {};
  9935. this.groups.length = function()
  9936. {
  9937. var i = 0;
  9938. for ( var p in this ) {
  9939. if (this.hasOwnProperty(p)) {
  9940. i++;
  9941. }
  9942. }
  9943. return i;
  9944. }
  9945. };
  9946. /**
  9947. * get group properties of a groupname. If groupname is not found, a new group
  9948. * is added.
  9949. * @param {*} groupname Can be a number, string, Date, etc.
  9950. * @return {Object} group The created group, containing all group properties
  9951. */
  9952. Groups.prototype.get = function (groupname) {
  9953. var group = this.groups[groupname];
  9954. if (group == undefined) {
  9955. // create new group
  9956. var index = this.defaultIndex % Groups.DEFAULT.length;
  9957. this.defaultIndex++;
  9958. group = {};
  9959. group.color = Groups.DEFAULT[index];
  9960. this.groups[groupname] = group;
  9961. }
  9962. return group;
  9963. };
  9964. /**
  9965. * Add a custom group style
  9966. * @param {String} groupname
  9967. * @param {Object} style An object containing borderColor,
  9968. * backgroundColor, etc.
  9969. * @return {Object} group The created group object
  9970. */
  9971. Groups.prototype.add = function (groupname, style) {
  9972. this.groups[groupname] = style;
  9973. if (style.color) {
  9974. style.color = Node.parseColor(style.color);
  9975. }
  9976. return style;
  9977. };
  9978. /**
  9979. * @class Images
  9980. * This class loads images and keeps them stored.
  9981. */
  9982. Images = function () {
  9983. this.images = {};
  9984. this.callback = undefined;
  9985. };
  9986. /**
  9987. * Set an onload callback function. This will be called each time an image
  9988. * is loaded
  9989. * @param {function} callback
  9990. */
  9991. Images.prototype.setOnloadCallback = function(callback) {
  9992. this.callback = callback;
  9993. };
  9994. /**
  9995. *
  9996. * @param {string} url Url of the image
  9997. * @return {Image} img The image object
  9998. */
  9999. Images.prototype.load = function(url) {
  10000. var img = this.images[url];
  10001. if (img == undefined) {
  10002. // create the image
  10003. var images = this;
  10004. img = new Image();
  10005. this.images[url] = img;
  10006. img.onload = function() {
  10007. if (images.callback) {
  10008. images.callback(this);
  10009. }
  10010. };
  10011. img.src = url;
  10012. }
  10013. return img;
  10014. };
  10015. /**
  10016. * Created by Alex on 2/6/14.
  10017. */
  10018. var physicsMixin = {
  10019. /**
  10020. * Toggling barnes Hut calculation on and off.
  10021. *
  10022. * @private
  10023. */
  10024. _toggleBarnesHut : function() {
  10025. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  10026. this._loadSelectedForceSolver();
  10027. this.moving = true;
  10028. this.start();
  10029. },
  10030. /**
  10031. * This loads the node force solver based on the barnes hut or repulsion algorithm
  10032. *
  10033. * @private
  10034. */
  10035. _loadSelectedForceSolver : function() {
  10036. // this overloads the this._calculateNodeForces
  10037. if (this.constants.physics.barnesHut.enabled == true) {
  10038. this._clearMixin(repulsionMixin);
  10039. this._clearMixin(hierarchalRepulsionMixin);
  10040. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  10041. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  10042. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  10043. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  10044. this._loadMixin(barnesHutMixin);
  10045. }
  10046. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  10047. this._clearMixin(barnesHutMixin);
  10048. this._clearMixin(repulsionMixin);
  10049. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  10050. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  10051. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  10052. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  10053. this._loadMixin(hierarchalRepulsionMixin);
  10054. }
  10055. else {
  10056. this._clearMixin(barnesHutMixin);
  10057. this._clearMixin(hierarchalRepulsionMixin);
  10058. this.barnesHutTree = undefined;
  10059. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  10060. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  10061. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  10062. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  10063. this._loadMixin(repulsionMixin);
  10064. }
  10065. },
  10066. /**
  10067. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  10068. * if there is more than one node. If it is just one node, we dont calculate anything.
  10069. *
  10070. * @private
  10071. */
  10072. _initializeForceCalculation : function() {
  10073. // stop calculation if there is only one node
  10074. if (this.nodeIndices.length == 1) {
  10075. this.nodes[this.nodeIndices[0]]._setForce(0,0);
  10076. }
  10077. else {
  10078. // if there are too many nodes on screen, we cluster without repositioning
  10079. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  10080. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  10081. }
  10082. // we now start the force calculation
  10083. this._calculateForces();
  10084. }
  10085. },
  10086. /**
  10087. * Calculate the external forces acting on the nodes
  10088. * Forces are caused by: edges, repulsing forces between nodes, gravity
  10089. * @private
  10090. */
  10091. _calculateForces : function() {
  10092. // Gravity is required to keep separated groups from floating off
  10093. // the forces are reset to zero in this loop by using _setForce instead
  10094. // of _addForce
  10095. this._calculateGravitationalForces();
  10096. this._calculateNodeForces();
  10097. if (this.constants.smoothCurves == true) {
  10098. this._calculateSpringForcesWithSupport();
  10099. }
  10100. else {
  10101. this._calculateSpringForces();
  10102. }
  10103. },
  10104. /**
  10105. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  10106. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  10107. * This function joins the datanodes and invisible (called support) nodes into one object.
  10108. * We do this so we do not contaminate this.nodes with the support nodes.
  10109. *
  10110. * @private
  10111. */
  10112. _updateCalculationNodes : function() {
  10113. if (this.constants.smoothCurves == true) {
  10114. this.calculationNodes = {};
  10115. this.calculationNodeIndices = [];
  10116. for (var nodeId in this.nodes) {
  10117. if (this.nodes.hasOwnProperty(nodeId)) {
  10118. this.calculationNodes[nodeId] = this.nodes[nodeId];
  10119. }
  10120. }
  10121. var supportNodes = this.sectors['support']['nodes'];
  10122. for (var supportNodeId in supportNodes) {
  10123. if (supportNodes.hasOwnProperty(supportNodeId)) {
  10124. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  10125. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  10126. }
  10127. else {
  10128. supportNodes[supportNodeId]._setForce(0,0);
  10129. }
  10130. }
  10131. }
  10132. for (var idx in this.calculationNodes) {
  10133. if (this.calculationNodes.hasOwnProperty(idx)) {
  10134. this.calculationNodeIndices.push(idx);
  10135. }
  10136. }
  10137. }
  10138. else {
  10139. this.calculationNodes = this.nodes;
  10140. this.calculationNodeIndices = this.nodeIndices;
  10141. }
  10142. },
  10143. /**
  10144. * this function applies the central gravity effect to keep groups from floating off
  10145. *
  10146. * @private
  10147. */
  10148. _calculateGravitationalForces : function() {
  10149. var dx, dy, distance, node, i;
  10150. var nodes = this.calculationNodes;
  10151. var gravity = this.constants.physics.centralGravity;
  10152. var gravityForce = 0;
  10153. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  10154. node = nodes[this.calculationNodeIndices[i]];
  10155. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  10156. // gravity does not apply when we are in a pocket sector
  10157. if (this._sector() == "default" && gravity != 0) {
  10158. dx = -node.x;
  10159. dy = -node.y;
  10160. distance = Math.sqrt(dx*dx + dy*dy);
  10161. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  10162. node.fx = dx * gravityForce;
  10163. node.fy = dy * gravityForce;
  10164. }
  10165. else {
  10166. node.fx = 0;
  10167. node.fy = 0;
  10168. }
  10169. }
  10170. },
  10171. /**
  10172. * this function calculates the effects of the springs in the case of unsmooth curves.
  10173. *
  10174. * @private
  10175. */
  10176. _calculateSpringForces : function() {
  10177. var edgeLength, edge, edgeId;
  10178. var dx, dy, fx, fy, springForce, length;
  10179. var edges = this.edges;
  10180. // forces caused by the edges, modelled as springs
  10181. for (edgeId in edges) {
  10182. if (edges.hasOwnProperty(edgeId)) {
  10183. edge = edges[edgeId];
  10184. if (edge.connected) {
  10185. // only calculate forces if nodes are in the same sector
  10186. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10187. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  10188. // this implies that the edges between big clusters are longer
  10189. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  10190. dx = (edge.from.x - edge.to.x);
  10191. dy = (edge.from.y - edge.to.y);
  10192. length = Math.sqrt(dx * dx + dy * dy);
  10193. if (length == 0) {
  10194. length = 0.01;
  10195. }
  10196. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10197. fx = dx * springForce;
  10198. fy = dy * springForce;
  10199. edge.from.fx += fx;
  10200. edge.from.fy += fy;
  10201. edge.to.fx -= fx;
  10202. edge.to.fy -= fy;
  10203. }
  10204. }
  10205. }
  10206. }
  10207. },
  10208. /**
  10209. * This function calculates the springforces on the nodes, accounting for the support nodes.
  10210. *
  10211. * @private
  10212. */
  10213. _calculateSpringForcesWithSupport : function() {
  10214. var edgeLength, edge, edgeId, combinedClusterSize;
  10215. var edges = this.edges;
  10216. // forces caused by the edges, modelled as springs
  10217. for (edgeId in edges) {
  10218. if (edges.hasOwnProperty(edgeId)) {
  10219. edge = edges[edgeId];
  10220. if (edge.connected) {
  10221. // only calculate forces if nodes are in the same sector
  10222. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10223. if (edge.via != null) {
  10224. var node1 = edge.to;
  10225. var node2 = edge.via;
  10226. var node3 = edge.from;
  10227. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  10228. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  10229. // this implies that the edges between big clusters are longer
  10230. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  10231. this._calculateSpringForce(node1,node2,0.5*edgeLength);
  10232. this._calculateSpringForce(node2,node3,0.5*edgeLength);
  10233. }
  10234. }
  10235. }
  10236. }
  10237. }
  10238. },
  10239. /**
  10240. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  10241. *
  10242. * @param node1
  10243. * @param node2
  10244. * @param edgeLength
  10245. * @private
  10246. */
  10247. _calculateSpringForce : function(node1,node2,edgeLength) {
  10248. var dx, dy, fx, fy, springForce, length;
  10249. dx = (node1.x - node2.x);
  10250. dy = (node1.y - node2.y);
  10251. length = Math.sqrt(dx * dx + dy * dy);
  10252. if (length == 0) {
  10253. length = 0.01;
  10254. }
  10255. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10256. fx = dx * springForce;
  10257. fy = dy * springForce;
  10258. node1.fx += fx;
  10259. node1.fy += fy;
  10260. node2.fx -= fx;
  10261. node2.fy -= fy;
  10262. },
  10263. /**
  10264. * Load the HTML for the physics config and bind it
  10265. * @private
  10266. */
  10267. _loadPhysicsConfiguration : function() {
  10268. if (this.physicsConfiguration === undefined) {
  10269. this.backupConstants = {};
  10270. util.copyObject(this.constants,this.backupConstants);
  10271. var hierarchicalLayoutDirections = ["LR","RL","UD","DU"];
  10272. this.physicsConfiguration = document.createElement('div');
  10273. this.physicsConfiguration.className = "PhysicsConfiguration";
  10274. this.physicsConfiguration.innerHTML = '' +
  10275. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  10276. '<tr>' +
  10277. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  10278. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>'+
  10279. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  10280. '</tr>'+
  10281. '</table>' +
  10282. '<table id="graph_BH_table" style="display:none">'+
  10283. '<tr><td><b>Barnes Hut</b></td></tr>'+
  10284. '<tr>'+
  10285. '<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>'+
  10286. '</tr>'+
  10287. '<tr>'+
  10288. '<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>'+
  10289. '</tr>'+
  10290. '<tr>'+
  10291. '<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>'+
  10292. '</tr>'+
  10293. '<tr>'+
  10294. '<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>'+
  10295. '</tr>'+
  10296. '<tr>'+
  10297. '<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>'+
  10298. '</tr>'+
  10299. '</table>'+
  10300. '<table id="graph_R_table" style="display:none">'+
  10301. '<tr><td><b>Repulsion</b></td></tr>'+
  10302. '<tr>'+
  10303. '<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>'+
  10304. '</tr>'+
  10305. '<tr>'+
  10306. '<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>'+
  10307. '</tr>'+
  10308. '<tr>'+
  10309. '<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>'+
  10310. '</tr>'+
  10311. '<tr>'+
  10312. '<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>'+
  10313. '</tr>'+
  10314. '<tr>'+
  10315. '<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>'+
  10316. '</tr>'+
  10317. '</table>'+
  10318. '<table id="graph_H_table" style="display:none">'+
  10319. '<tr><td width="150"><b>Hierarchical</b></td></tr>'+
  10320. '<tr>'+
  10321. '<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>'+
  10322. '</tr>'+
  10323. '<tr>'+
  10324. '<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>'+
  10325. '</tr>'+
  10326. '<tr>'+
  10327. '<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>'+
  10328. '</tr>'+
  10329. '<tr>'+
  10330. '<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>'+
  10331. '</tr>'+
  10332. '<tr>'+
  10333. '<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>'+
  10334. '</tr>'+
  10335. '<tr>'+
  10336. '<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>'+
  10337. '</tr>'+
  10338. '<tr>'+
  10339. '<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>'+
  10340. '</tr>'+
  10341. '<tr>'+
  10342. '<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>'+
  10343. '</tr>'+
  10344. '</table>' +
  10345. '<table><tr><td><b>Options:</b></td></tr>' +
  10346. '<tr>' +
  10347. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  10348. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  10349. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  10350. '</tr>'+
  10351. '</table>'
  10352. this.containerElement.parentElement.insertBefore(this.physicsConfiguration,this.containerElement);
  10353. this.optionsDiv = document.createElement("div");
  10354. this.optionsDiv.style.fontSize = "14px";
  10355. this.optionsDiv.style.fontFamily = "verdana";
  10356. this.containerElement.parentElement.insertBefore(this.optionsDiv,this.containerElement);
  10357. var rangeElement;
  10358. rangeElement = document.getElementById('graph_BH_gc');
  10359. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_gc',-1,"physics_barnesHut_gravitationalConstant");
  10360. rangeElement = document.getElementById('graph_BH_cg');
  10361. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_cg',1,"physics_centralGravity");
  10362. rangeElement = document.getElementById('graph_BH_sc');
  10363. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_sc',1,"physics_springConstant");
  10364. rangeElement = document.getElementById('graph_BH_sl');
  10365. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_sl',1,"physics_springLength");
  10366. rangeElement = document.getElementById('graph_BH_damp');
  10367. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_damp',1,"physics_damping");
  10368. rangeElement = document.getElementById('graph_R_nd');
  10369. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_nd',1,"physics_repulsion_nodeDistance");
  10370. rangeElement = document.getElementById('graph_R_cg');
  10371. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_cg',1,"physics_centralGravity");
  10372. rangeElement = document.getElementById('graph_R_sc');
  10373. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_sc',1,"physics_springConstant");
  10374. rangeElement = document.getElementById('graph_R_sl');
  10375. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_sl',1,"physics_springLength");
  10376. rangeElement = document.getElementById('graph_R_damp');
  10377. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_damp',1,"physics_damping");
  10378. rangeElement = document.getElementById('graph_H_nd');
  10379. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_nd',1,"physics_hierarchicalRepulsion_nodeDistance");
  10380. rangeElement = document.getElementById('graph_H_cg');
  10381. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_cg',1,"physics_centralGravity");
  10382. rangeElement = document.getElementById('graph_H_sc');
  10383. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_sc',1,"physics_springConstant");
  10384. rangeElement = document.getElementById('graph_H_sl');
  10385. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_sl',1,"physics_springLength");
  10386. rangeElement = document.getElementById('graph_H_damp');
  10387. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_damp',1,"physics_damping");
  10388. rangeElement = document.getElementById('graph_H_direction');
  10389. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_direction',hierarchicalLayoutDirections,"hierarchicalLayout_direction");
  10390. rangeElement = document.getElementById('graph_H_levsep');
  10391. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_levsep',1,"hierarchicalLayout_levelSeparation");
  10392. rangeElement = document.getElementById('graph_H_nspac');
  10393. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_nspac',1,"hierarchicalLayout_nodeSpacing");
  10394. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10395. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10396. var radioButton3 = document.getElementById("graph_physicsMethod3");
  10397. radioButton2.checked = true;
  10398. if (this.constants.physics.barnesHut.enabled) {
  10399. radioButton1.checked = true;
  10400. }
  10401. if (this.constants.hierarchicalLayout.enabled) {
  10402. radioButton3.checked = true;
  10403. }
  10404. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10405. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  10406. var graph_generateOptions = document.getElementById("graph_generateOptions");
  10407. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  10408. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  10409. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  10410. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10411. else {graph_toggleSmooth.style.background = "#FF8532";}
  10412. switchConfigurations.apply(this);
  10413. radioButton1.onchange = switchConfigurations.bind(this);
  10414. radioButton2.onchange = switchConfigurations.bind(this);
  10415. radioButton3.onchange = switchConfigurations.bind(this);
  10416. }
  10417. },
  10418. _overWriteGraphConstants : function(constantsVariableName, value) {
  10419. var nameArray = constantsVariableName.split("_");
  10420. if (nameArray.length == 1) {
  10421. this.constants[nameArray[0]] = value;
  10422. }
  10423. else if (nameArray.length == 2) {
  10424. this.constants[nameArray[0]][nameArray[1]] = value;
  10425. }
  10426. else if (nameArray.length == 3) {
  10427. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  10428. }
  10429. }
  10430. }
  10431. function graphToggleSmoothCurves () {
  10432. this.constants.smoothCurves = !this.constants.smoothCurves;
  10433. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10434. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10435. else {graph_toggleSmooth.style.background = "#FF8532";}
  10436. this._configureSmoothCurves(false);
  10437. };
  10438. function graphRepositionNodes () {
  10439. for (var nodeId in this.calculationNodes) {
  10440. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  10441. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  10442. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  10443. }
  10444. }
  10445. if (this.constants.hierarchicalLayout.enabled == true) {
  10446. this._setupHierarchicalLayout();
  10447. }
  10448. else {
  10449. this.repositionNodes();
  10450. }
  10451. this.moving = true;
  10452. this.start();
  10453. };
  10454. function graphGenerateOptions () {
  10455. var options = "No options are required, default values used."
  10456. var optionsSpecific = [];
  10457. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10458. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10459. if (radioButton1.checked == true) {
  10460. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  10461. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10462. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10463. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10464. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10465. if (optionsSpecific.length != 0) {
  10466. options = "var options = {"
  10467. options += "physics: {barnesHut: {"
  10468. for (var i = 0; i < optionsSpecific.length; i++) {
  10469. options += optionsSpecific[i];
  10470. if (i < optionsSpecific.length - 1) {
  10471. options += ", "
  10472. }
  10473. }
  10474. options += '}}'
  10475. }
  10476. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10477. if (optionsSpecific.length == 0) {options = "var options = {";}
  10478. else {options += ", "}
  10479. options += "smoothCurves: " + this.constants.smoothCurves;
  10480. }
  10481. if (options != "No options are required, default values used.") {
  10482. options += '};'
  10483. }
  10484. }
  10485. else if (radioButton2.checked == true) {
  10486. options = "var options = {"
  10487. options += "physics: {barnesHut: {enabled: false}";
  10488. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  10489. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10490. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10491. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10492. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10493. if (optionsSpecific.length != 0) {
  10494. options += ", repulsion: {"
  10495. for (var i = 0; i < optionsSpecific.length; i++) {
  10496. options += optionsSpecific[i];
  10497. if (i < optionsSpecific.length - 1) {
  10498. options += ", "
  10499. }
  10500. }
  10501. options += '}}'
  10502. }
  10503. if (optionsSpecific.length == 0) {options += "}"}
  10504. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10505. options += ", smoothCurves: " + this.constants.smoothCurves;
  10506. }
  10507. options += '};'
  10508. }
  10509. else {
  10510. options = "var options = {"
  10511. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  10512. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10513. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10514. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10515. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10516. if (optionsSpecific.length != 0) {
  10517. options += "physics: {hierarchicalRepulsion: {"
  10518. for (var i = 0; i < optionsSpecific.length; i++) {
  10519. options += optionsSpecific[i];
  10520. if (i < optionsSpecific.length - 1) {
  10521. options += ", ";
  10522. }
  10523. }
  10524. options += '}},';
  10525. }
  10526. options += 'hierarchicalLayout: {';
  10527. optionsSpecific = [];
  10528. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  10529. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  10530. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  10531. if (optionsSpecific.length != 0) {
  10532. for (var i = 0; i < optionsSpecific.length; i++) {
  10533. options += optionsSpecific[i];
  10534. if (i < optionsSpecific.length - 1) {
  10535. options += ", "
  10536. }
  10537. }
  10538. options += '}'
  10539. }
  10540. else {
  10541. options += "enabled:true}";
  10542. }
  10543. options += '};'
  10544. }
  10545. this.optionsDiv.innerHTML = options;
  10546. };
  10547. function switchConfigurations () {
  10548. var ids = ["graph_BH_table","graph_R_table","graph_H_table"]
  10549. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  10550. var tableId = "graph_" + radioButton + "_table";
  10551. var table = document.getElementById(tableId);
  10552. table.style.display = "block";
  10553. for (var i = 0; i < ids.length; i++) {
  10554. if (ids[i] != tableId) {
  10555. table = document.getElementById(ids[i]);
  10556. table.style.display = "none";
  10557. }
  10558. }
  10559. this._restoreNodes();
  10560. if (radioButton == "R") {
  10561. this.constants.hierarchicalLayout.enabled = false;
  10562. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10563. this.constants.physics.barnesHut.enabled = false;
  10564. }
  10565. else if (radioButton == "H") {
  10566. this.constants.hierarchicalLayout.enabled = true;
  10567. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10568. this.constants.physics.barnesHut.enabled = false;
  10569. this._setupHierarchicalLayout();
  10570. }
  10571. else {
  10572. this.constants.hierarchicalLayout.enabled = false;
  10573. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10574. this.constants.physics.barnesHut.enabled = true;
  10575. }
  10576. this._loadSelectedForceSolver();
  10577. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10578. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10579. else {graph_toggleSmooth.style.background = "#FF8532";}
  10580. this.moving = true;
  10581. this.start();
  10582. }
  10583. function showValueOfRange (id,map,constantsVariableName) {
  10584. var valueId = id + "_value";
  10585. var rangeValue = document.getElementById(id).value;
  10586. if (map instanceof Array) {
  10587. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  10588. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  10589. }
  10590. else {
  10591. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  10592. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  10593. }
  10594. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10595. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10596. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10597. this._setupHierarchicalLayout();
  10598. }
  10599. this.moving = true;
  10600. this.start();
  10601. };
  10602. /**
  10603. * Created by Alex on 2/10/14.
  10604. */
  10605. var hierarchalRepulsionMixin = {
  10606. /**
  10607. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10608. * This field is linearly approximated.
  10609. *
  10610. * @private
  10611. */
  10612. _calculateNodeForces : function() {
  10613. var dx, dy, distance, fx, fy, combinedClusterSize,
  10614. repulsingForce, node1, node2, i, j;
  10615. var nodes = this.calculationNodes;
  10616. var nodeIndices = this.calculationNodeIndices;
  10617. // approximation constants
  10618. var b = 5;
  10619. var a_base = 0.5*-b;
  10620. // repulsing forces between nodes
  10621. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  10622. var minimumDistance = nodeDistance;
  10623. // we loop from i over all but the last entree in the array
  10624. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10625. for (i = 0; i < nodeIndices.length-1; i++) {
  10626. node1 = nodes[nodeIndices[i]];
  10627. for (j = i+1; j < nodeIndices.length; j++) {
  10628. node2 = nodes[nodeIndices[j]];
  10629. dx = node2.x - node1.x;
  10630. dy = node2.y - node1.y;
  10631. distance = Math.sqrt(dx * dx + dy * dy);
  10632. var a = a_base / minimumDistance;
  10633. if (distance < 2*minimumDistance) {
  10634. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10635. // normalize force with
  10636. if (distance == 0) {
  10637. distance = 0.01;
  10638. }
  10639. else {
  10640. repulsingForce = repulsingForce/distance;
  10641. }
  10642. fx = dx * repulsingForce;
  10643. fy = dy * repulsingForce;
  10644. node1.fx -= fx;
  10645. node1.fy -= fy;
  10646. node2.fx += fx;
  10647. node2.fy += fy;
  10648. }
  10649. }
  10650. }
  10651. }
  10652. }
  10653. /**
  10654. * Created by Alex on 2/10/14.
  10655. */
  10656. var barnesHutMixin = {
  10657. /**
  10658. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10659. * The Barnes Hut method is used to speed up this N-body simulation.
  10660. *
  10661. * @private
  10662. */
  10663. _calculateNodeForces : function() {
  10664. var node;
  10665. var nodes = this.calculationNodes;
  10666. var nodeIndices = this.calculationNodeIndices;
  10667. var nodeCount = nodeIndices.length;
  10668. this._formBarnesHutTree(nodes,nodeIndices);
  10669. var barnesHutTree = this.barnesHutTree;
  10670. // place the nodes one by one recursively
  10671. for (var i = 0; i < nodeCount; i++) {
  10672. node = nodes[nodeIndices[i]];
  10673. // starting with root is irrelevant, it never passes the BarnesHut condition
  10674. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10675. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10676. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10677. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10678. }
  10679. },
  10680. /**
  10681. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10682. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10683. *
  10684. * @param parentBranch
  10685. * @param node
  10686. * @private
  10687. */
  10688. _getForceContribution : function(parentBranch,node) {
  10689. // we get no force contribution from an empty region
  10690. if (parentBranch.childrenCount > 0) {
  10691. var dx,dy,distance;
  10692. // get the distance from the center of mass to the node.
  10693. dx = parentBranch.centerOfMass.x - node.x;
  10694. dy = parentBranch.centerOfMass.y - node.y;
  10695. distance = Math.sqrt(dx * dx + dy * dy);
  10696. // BarnesHut condition
  10697. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10698. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10699. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10700. // duplicate code to reduce function calls to speed up program
  10701. if (distance == 0) {
  10702. distance = 0.1*Math.random();
  10703. dx = distance;
  10704. }
  10705. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10706. var fx = dx * gravityForce;
  10707. var fy = dy * gravityForce;
  10708. node.fx += fx;
  10709. node.fy += fy;
  10710. }
  10711. else {
  10712. // Did not pass the condition, go into children if available
  10713. if (parentBranch.childrenCount == 4) {
  10714. this._getForceContribution(parentBranch.children.NW,node);
  10715. this._getForceContribution(parentBranch.children.NE,node);
  10716. this._getForceContribution(parentBranch.children.SW,node);
  10717. this._getForceContribution(parentBranch.children.SE,node);
  10718. }
  10719. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10720. if (parentBranch.children.data.id != node.id) { // if it is not self
  10721. // duplicate code to reduce function calls to speed up program
  10722. if (distance == 0) {
  10723. distance = 0.5*Math.random();
  10724. dx = distance;
  10725. }
  10726. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10727. var fx = dx * gravityForce;
  10728. var fy = dy * gravityForce;
  10729. node.fx += fx;
  10730. node.fy += fy;
  10731. }
  10732. }
  10733. }
  10734. }
  10735. },
  10736. /**
  10737. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10738. *
  10739. * @param nodes
  10740. * @param nodeIndices
  10741. * @private
  10742. */
  10743. _formBarnesHutTree : function(nodes,nodeIndices) {
  10744. var node;
  10745. var nodeCount = nodeIndices.length;
  10746. var minX = Number.MAX_VALUE,
  10747. minY = Number.MAX_VALUE,
  10748. maxX =-Number.MAX_VALUE,
  10749. maxY =-Number.MAX_VALUE;
  10750. // get the range of the nodes
  10751. for (var i = 0; i < nodeCount; i++) {
  10752. var x = nodes[nodeIndices[i]].x;
  10753. var y = nodes[nodeIndices[i]].y;
  10754. if (x < minX) { minX = x; }
  10755. if (x > maxX) { maxX = x; }
  10756. if (y < minY) { minY = y; }
  10757. if (y > maxY) { maxY = y; }
  10758. }
  10759. // make the range a square
  10760. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10761. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10762. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10763. var minimumTreeSize = 1e-5;
  10764. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10765. var halfRootSize = 0.5 * rootSize;
  10766. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10767. // construct the barnesHutTree
  10768. var barnesHutTree = {root:{
  10769. centerOfMass:{x:0,y:0}, // Center of Mass
  10770. mass:0,
  10771. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10772. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10773. size: rootSize,
  10774. calcSize: 1 / rootSize,
  10775. children: {data:null},
  10776. maxWidth: 0,
  10777. level: 0,
  10778. childrenCount: 4
  10779. }};
  10780. this._splitBranch(barnesHutTree.root);
  10781. // place the nodes one by one recursively
  10782. for (i = 0; i < nodeCount; i++) {
  10783. node = nodes[nodeIndices[i]];
  10784. this._placeInTree(barnesHutTree.root,node);
  10785. }
  10786. // make global
  10787. this.barnesHutTree = barnesHutTree
  10788. },
  10789. _updateBranchMass : function(parentBranch, node) {
  10790. var totalMass = parentBranch.mass + node.mass;
  10791. var totalMassInv = 1/totalMass;
  10792. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10793. parentBranch.centerOfMass.x *= totalMassInv;
  10794. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10795. parentBranch.centerOfMass.y *= totalMassInv;
  10796. parentBranch.mass = totalMass;
  10797. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10798. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10799. },
  10800. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10801. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10802. // update the mass of the branch.
  10803. this._updateBranchMass(parentBranch,node);
  10804. }
  10805. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10806. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10807. this._placeInRegion(parentBranch,node,"NW");
  10808. }
  10809. else { // in SW
  10810. this._placeInRegion(parentBranch,node,"SW");
  10811. }
  10812. }
  10813. else { // in NE or SE
  10814. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10815. this._placeInRegion(parentBranch,node,"NE");
  10816. }
  10817. else { // in SE
  10818. this._placeInRegion(parentBranch,node,"SE");
  10819. }
  10820. }
  10821. },
  10822. _placeInRegion : function(parentBranch,node,region) {
  10823. switch (parentBranch.children[region].childrenCount) {
  10824. case 0: // place node here
  10825. parentBranch.children[region].children.data = node;
  10826. parentBranch.children[region].childrenCount = 1;
  10827. this._updateBranchMass(parentBranch.children[region],node);
  10828. break;
  10829. case 1: // convert into children
  10830. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10831. // we move one node a pixel and we do not put it in the tree.
  10832. if (parentBranch.children[region].children.data.x == node.x &&
  10833. parentBranch.children[region].children.data.y == node.y) {
  10834. node.x += Math.random();
  10835. node.y += Math.random();
  10836. }
  10837. else {
  10838. this._splitBranch(parentBranch.children[region]);
  10839. this._placeInTree(parentBranch.children[region],node);
  10840. }
  10841. break;
  10842. case 4: // place in branch
  10843. this._placeInTree(parentBranch.children[region],node);
  10844. break;
  10845. }
  10846. },
  10847. /**
  10848. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10849. * after the split is complete.
  10850. *
  10851. * @param parentBranch
  10852. * @private
  10853. */
  10854. _splitBranch : function(parentBranch) {
  10855. // if the branch is filled with a node, replace the node in the new subset.
  10856. var containedNode = null;
  10857. if (parentBranch.childrenCount == 1) {
  10858. containedNode = parentBranch.children.data;
  10859. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10860. }
  10861. parentBranch.childrenCount = 4;
  10862. parentBranch.children.data = null;
  10863. this._insertRegion(parentBranch,"NW");
  10864. this._insertRegion(parentBranch,"NE");
  10865. this._insertRegion(parentBranch,"SW");
  10866. this._insertRegion(parentBranch,"SE");
  10867. if (containedNode != null) {
  10868. this._placeInTree(parentBranch,containedNode);
  10869. }
  10870. },
  10871. /**
  10872. * This function subdivides the region into four new segments.
  10873. * Specifically, this inserts a single new segment.
  10874. * It fills the children section of the parentBranch
  10875. *
  10876. * @param parentBranch
  10877. * @param region
  10878. * @param parentRange
  10879. * @private
  10880. */
  10881. _insertRegion : function(parentBranch, region) {
  10882. var minX,maxX,minY,maxY;
  10883. var childSize = 0.5 * parentBranch.size;
  10884. switch (region) {
  10885. case "NW":
  10886. minX = parentBranch.range.minX;
  10887. maxX = parentBranch.range.minX + childSize;
  10888. minY = parentBranch.range.minY;
  10889. maxY = parentBranch.range.minY + childSize;
  10890. break;
  10891. case "NE":
  10892. minX = parentBranch.range.minX + childSize;
  10893. maxX = parentBranch.range.maxX;
  10894. minY = parentBranch.range.minY;
  10895. maxY = parentBranch.range.minY + childSize;
  10896. break;
  10897. case "SW":
  10898. minX = parentBranch.range.minX;
  10899. maxX = parentBranch.range.minX + childSize;
  10900. minY = parentBranch.range.minY + childSize;
  10901. maxY = parentBranch.range.maxY;
  10902. break;
  10903. case "SE":
  10904. minX = parentBranch.range.minX + childSize;
  10905. maxX = parentBranch.range.maxX;
  10906. minY = parentBranch.range.minY + childSize;
  10907. maxY = parentBranch.range.maxY;
  10908. break;
  10909. }
  10910. parentBranch.children[region] = {
  10911. centerOfMass:{x:0,y:0},
  10912. mass:0,
  10913. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10914. size: 0.5 * parentBranch.size,
  10915. calcSize: 2 * parentBranch.calcSize,
  10916. children: {data:null},
  10917. maxWidth: 0,
  10918. level: parentBranch.level+1,
  10919. childrenCount: 0
  10920. };
  10921. },
  10922. /**
  10923. * This function is for debugging purposed, it draws the tree.
  10924. *
  10925. * @param ctx
  10926. * @param color
  10927. * @private
  10928. */
  10929. _drawTree : function(ctx,color) {
  10930. if (this.barnesHutTree !== undefined) {
  10931. ctx.lineWidth = 1;
  10932. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10933. }
  10934. },
  10935. /**
  10936. * This function is for debugging purposes. It draws the branches recursively.
  10937. *
  10938. * @param branch
  10939. * @param ctx
  10940. * @param color
  10941. * @private
  10942. */
  10943. _drawBranch : function(branch,ctx,color) {
  10944. if (color === undefined) {
  10945. color = "#FF0000";
  10946. }
  10947. if (branch.childrenCount == 4) {
  10948. this._drawBranch(branch.children.NW,ctx);
  10949. this._drawBranch(branch.children.NE,ctx);
  10950. this._drawBranch(branch.children.SE,ctx);
  10951. this._drawBranch(branch.children.SW,ctx);
  10952. }
  10953. ctx.strokeStyle = color;
  10954. ctx.beginPath();
  10955. ctx.moveTo(branch.range.minX,branch.range.minY);
  10956. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10957. ctx.stroke();
  10958. ctx.beginPath();
  10959. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10960. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10961. ctx.stroke();
  10962. ctx.beginPath();
  10963. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10964. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10965. ctx.stroke();
  10966. ctx.beginPath();
  10967. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10968. ctx.lineTo(branch.range.minX,branch.range.minY);
  10969. ctx.stroke();
  10970. /*
  10971. if (branch.mass > 0) {
  10972. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  10973. ctx.stroke();
  10974. }
  10975. */
  10976. }
  10977. };
  10978. /**
  10979. * Created by Alex on 2/10/14.
  10980. */
  10981. var repulsionMixin = {
  10982. /**
  10983. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10984. * This field is linearly approximated.
  10985. *
  10986. * @private
  10987. */
  10988. _calculateNodeForces : function() {
  10989. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  10990. repulsingForce, node1, node2, i, j;
  10991. var nodes = this.calculationNodes;
  10992. var nodeIndices = this.calculationNodeIndices;
  10993. // approximation constants
  10994. var a_base = -2/3;
  10995. var b = 4/3;
  10996. // repulsing forces between nodes
  10997. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10998. var minimumDistance = nodeDistance;
  10999. // we loop from i over all but the last entree in the array
  11000. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  11001. for (i = 0; i < nodeIndices.length-1; i++) {
  11002. node1 = nodes[nodeIndices[i]];
  11003. for (j = i+1; j < nodeIndices.length; j++) {
  11004. node2 = nodes[nodeIndices[j]];
  11005. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  11006. dx = node2.x - node1.x;
  11007. dy = node2.y - node1.y;
  11008. distance = Math.sqrt(dx * dx + dy * dy);
  11009. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  11010. var a = a_base / minimumDistance;
  11011. if (distance < 2*minimumDistance) {
  11012. if (distance < 0.5*minimumDistance) {
  11013. repulsingForce = 1.0;
  11014. }
  11015. else {
  11016. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  11017. }
  11018. // amplify the repulsion for clusters.
  11019. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  11020. repulsingForce = repulsingForce/distance;
  11021. fx = dx * repulsingForce;
  11022. fy = dy * repulsingForce;
  11023. node1.fx -= fx;
  11024. node1.fy -= fy;
  11025. node2.fx += fx;
  11026. node2.fy += fy;
  11027. }
  11028. }
  11029. }
  11030. }
  11031. }
  11032. var HierarchicalLayoutMixin = {
  11033. _resetLevels : function() {
  11034. for (var nodeId in this.nodes) {
  11035. if (this.nodes.hasOwnProperty(nodeId)) {
  11036. var node = this.nodes[nodeId];
  11037. if (node.preassignedLevel == false) {
  11038. node.level = -1;
  11039. }
  11040. }
  11041. }
  11042. },
  11043. /**
  11044. * This is the main function to layout the nodes in a hierarchical way.
  11045. * It checks if the node details are supplied correctly
  11046. *
  11047. * @private
  11048. */
  11049. _setupHierarchicalLayout : function() {
  11050. if (this.constants.hierarchicalLayout.enabled == true) {
  11051. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  11052. this.constants.hierarchicalLayout.levelSeparation *= -1;
  11053. }
  11054. else {
  11055. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  11056. }
  11057. // get the size of the largest hubs and check if the user has defined a level for a node.
  11058. var hubsize = 0;
  11059. var node, nodeId;
  11060. var definedLevel = false;
  11061. var undefinedLevel = false;
  11062. for (nodeId in this.nodes) {
  11063. if (this.nodes.hasOwnProperty(nodeId)) {
  11064. node = this.nodes[nodeId];
  11065. if (node.level != -1) {
  11066. definedLevel = true;
  11067. }
  11068. else {
  11069. undefinedLevel = true;
  11070. }
  11071. if (hubsize < node.edges.length) {
  11072. hubsize = node.edges.length;
  11073. }
  11074. }
  11075. }
  11076. // if the user defined some levels but not all, alert and run without hierarchical layout
  11077. if (undefinedLevel == true && definedLevel == true) {
  11078. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.")
  11079. this.zoomExtent(true,this.constants.clustering.enabled);
  11080. if (!this.constants.clustering.enabled) {
  11081. this.start();
  11082. }
  11083. }
  11084. else {
  11085. // setup the system to use hierarchical method.
  11086. this._changeConstants();
  11087. // define levels if undefined by the users. Based on hubsize
  11088. if (undefinedLevel == true) {
  11089. this._determineLevels(hubsize);
  11090. }
  11091. // check the distribution of the nodes per level.
  11092. var distribution = this._getDistribution();
  11093. // place the nodes on the canvas. This also stablilizes the system.
  11094. this._placeNodesByHierarchy(distribution);
  11095. // start the simulation.
  11096. this.start();
  11097. }
  11098. }
  11099. },
  11100. /**
  11101. * This function places the nodes on the canvas based on the hierarchial distribution.
  11102. *
  11103. * @param {Object} distribution | obtained by the function this._getDistribution()
  11104. * @private
  11105. */
  11106. _placeNodesByHierarchy : function(distribution) {
  11107. var nodeId, node;
  11108. // start placing all the level 0 nodes first. Then recursively position their branches.
  11109. for (nodeId in distribution[0].nodes) {
  11110. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  11111. node = distribution[0].nodes[nodeId];
  11112. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11113. if (node.xFixed) {
  11114. node.x = distribution[0].minPos;
  11115. node.xFixed = false;
  11116. distribution[0].minPos += distribution[0].nodeSpacing;
  11117. }
  11118. }
  11119. else {
  11120. if (node.yFixed) {
  11121. node.y = distribution[0].minPos;
  11122. node.yFixed = false;
  11123. distribution[0].minPos += distribution[0].nodeSpacing;
  11124. }
  11125. }
  11126. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  11127. }
  11128. }
  11129. // stabilize the system after positioning. This function calls zoomExtent.
  11130. this._stabilize();
  11131. },
  11132. /**
  11133. * This function get the distribution of levels based on hubsize
  11134. *
  11135. * @returns {Object}
  11136. * @private
  11137. */
  11138. _getDistribution : function() {
  11139. var distribution = {};
  11140. var nodeId, node;
  11141. // 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.
  11142. // the fix of X is removed after the x value has been set.
  11143. for (nodeId in this.nodes) {
  11144. if (this.nodes.hasOwnProperty(nodeId)) {
  11145. node = this.nodes[nodeId];
  11146. node.xFixed = true;
  11147. node.yFixed = true;
  11148. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11149. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  11150. }
  11151. else {
  11152. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  11153. }
  11154. if (!distribution.hasOwnProperty(node.level)) {
  11155. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  11156. }
  11157. distribution[node.level].amount += 1;
  11158. distribution[node.level].nodes[node.id] = node;
  11159. }
  11160. }
  11161. // determine the largest amount of nodes of all levels
  11162. var maxCount = 0;
  11163. for (var level in distribution) {
  11164. if (distribution.hasOwnProperty(level)) {
  11165. if (maxCount < distribution[level].amount) {
  11166. maxCount = distribution[level].amount;
  11167. }
  11168. }
  11169. }
  11170. // set the initial position and spacing of each nodes accordingly
  11171. for (var level in distribution) {
  11172. if (distribution.hasOwnProperty(level)) {
  11173. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  11174. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  11175. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  11176. }
  11177. }
  11178. return distribution;
  11179. },
  11180. /**
  11181. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  11182. *
  11183. * @param hubsize
  11184. * @private
  11185. */
  11186. _determineLevels : function(hubsize) {
  11187. var nodeId, node;
  11188. // determine hubs
  11189. for (nodeId in this.nodes) {
  11190. if (this.nodes.hasOwnProperty(nodeId)) {
  11191. node = this.nodes[nodeId];
  11192. if (node.edges.length == hubsize) {
  11193. node.level = 0;
  11194. }
  11195. }
  11196. }
  11197. // branch from hubs
  11198. for (nodeId in this.nodes) {
  11199. if (this.nodes.hasOwnProperty(nodeId)) {
  11200. node = this.nodes[nodeId];
  11201. if (node.level == 0) {
  11202. this._setLevel(1,node.edges,node.id);
  11203. }
  11204. }
  11205. }
  11206. },
  11207. /**
  11208. * Since hierarchical layout does not support:
  11209. * - smooth curves (based on the physics),
  11210. * - clustering (based on dynamic node counts)
  11211. *
  11212. * We disable both features so there will be no problems.
  11213. *
  11214. * @private
  11215. */
  11216. _changeConstants : function() {
  11217. this.constants.clustering.enabled = false;
  11218. this.constants.physics.barnesHut.enabled = false;
  11219. this.constants.physics.hierarchicalRepulsion.enabled = true;
  11220. this._loadSelectedForceSolver();
  11221. this.constants.smoothCurves = false;
  11222. this._configureSmoothCurves();
  11223. },
  11224. /**
  11225. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  11226. * on a X position that ensures there will be no overlap.
  11227. *
  11228. * @param edges
  11229. * @param parentId
  11230. * @param distribution
  11231. * @param parentLevel
  11232. * @private
  11233. */
  11234. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  11235. for (var i = 0; i < edges.length; i++) {
  11236. var childNode = null;
  11237. if (edges[i].toId == parentId) {
  11238. childNode = edges[i].from;
  11239. }
  11240. else {
  11241. childNode = edges[i].to;
  11242. }
  11243. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  11244. var nodeMoved = false;
  11245. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11246. if (childNode.xFixed && childNode.level > parentLevel) {
  11247. childNode.xFixed = false;
  11248. childNode.x = distribution[childNode.level].minPos;
  11249. nodeMoved = true;
  11250. }
  11251. }
  11252. else {
  11253. if (childNode.yFixed && childNode.level > parentLevel) {
  11254. childNode.yFixed = false;
  11255. childNode.y = distribution[childNode.level].minPos;
  11256. nodeMoved = true;
  11257. }
  11258. }
  11259. if (nodeMoved == true) {
  11260. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  11261. if (childNode.edges.length > 1) {
  11262. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  11263. }
  11264. }
  11265. }
  11266. },
  11267. /**
  11268. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  11269. *
  11270. * @param level
  11271. * @param edges
  11272. * @param parentId
  11273. * @private
  11274. */
  11275. _setLevel : function(level, edges, parentId) {
  11276. for (var i = 0; i < edges.length; i++) {
  11277. var childNode = null;
  11278. if (edges[i].toId == parentId) {
  11279. childNode = edges[i].from;
  11280. }
  11281. else {
  11282. childNode = edges[i].to;
  11283. }
  11284. if (childNode.level == -1 || childNode.level > level) {
  11285. childNode.level = level;
  11286. if (edges.length > 1) {
  11287. this._setLevel(level+1, childNode.edges, childNode.id);
  11288. }
  11289. }
  11290. }
  11291. },
  11292. /**
  11293. * Unfix nodes
  11294. *
  11295. * @private
  11296. */
  11297. _restoreNodes : function() {
  11298. for (nodeId in this.nodes) {
  11299. if (this.nodes.hasOwnProperty(nodeId)) {
  11300. this.nodes[nodeId].xFixed = false;
  11301. this.nodes[nodeId].yFixed = false;
  11302. }
  11303. }
  11304. }
  11305. };
  11306. /**
  11307. * Created by Alex on 2/4/14.
  11308. */
  11309. var manipulationMixin = {
  11310. /**
  11311. * clears the toolbar div element of children
  11312. *
  11313. * @private
  11314. */
  11315. _clearManipulatorBar : function() {
  11316. while (this.manipulationDiv.hasChildNodes()) {
  11317. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11318. }
  11319. },
  11320. /**
  11321. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  11322. * these functions to their original functionality, we saved them in this.cachedFunctions.
  11323. * This function restores these functions to their original function.
  11324. *
  11325. * @private
  11326. */
  11327. _restoreOverloadedFunctions : function() {
  11328. for (var functionName in this.cachedFunctions) {
  11329. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  11330. this[functionName] = this.cachedFunctions[functionName];
  11331. }
  11332. }
  11333. },
  11334. /**
  11335. * Enable or disable edit-mode.
  11336. *
  11337. * @private
  11338. */
  11339. _toggleEditMode : function() {
  11340. this.editMode = !this.editMode;
  11341. var toolbar = document.getElementById("graph-manipulationDiv");
  11342. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11343. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  11344. if (this.editMode == true) {
  11345. toolbar.style.display="block";
  11346. closeDiv.style.display="block";
  11347. editModeDiv.style.display="none";
  11348. closeDiv.onclick = this._toggleEditMode.bind(this);
  11349. }
  11350. else {
  11351. toolbar.style.display="none";
  11352. closeDiv.style.display="none";
  11353. editModeDiv.style.display="block";
  11354. closeDiv.onclick = null;
  11355. }
  11356. this._createManipulatorBar()
  11357. },
  11358. /**
  11359. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  11360. *
  11361. * @private
  11362. */
  11363. _createManipulatorBar : function() {
  11364. // remove bound functions
  11365. if (this.boundFunction) {
  11366. this.off('select', this.boundFunction);
  11367. }
  11368. // restore overloaded functions
  11369. this._restoreOverloadedFunctions();
  11370. // resume calculation
  11371. this.freezeSimulation = false;
  11372. // reset global variables
  11373. this.blockConnectingEdgeSelection = false;
  11374. this.forceAppendSelection = false
  11375. if (this.editMode == true) {
  11376. while (this.manipulationDiv.hasChildNodes()) {
  11377. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11378. }
  11379. // add the icons to the manipulator div
  11380. this.manipulationDiv.innerHTML = "" +
  11381. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  11382. "<span class='graph-manipulationLabel'>Add Node</span></span>" +
  11383. "<div class='graph-seperatorLine'></div>" +
  11384. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  11385. "<span class='graph-manipulationLabel'>Add Link</span></span>";
  11386. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11387. this.manipulationDiv.innerHTML += "" +
  11388. "<div class='graph-seperatorLine'></div>" +
  11389. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  11390. "<span class='graph-manipulationLabel'>Edit Node</span></span>";
  11391. }
  11392. if (this._selectionIsEmpty() == false) {
  11393. this.manipulationDiv.innerHTML += "" +
  11394. "<div class='graph-seperatorLine'></div>" +
  11395. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  11396. "<span class='graph-manipulationLabel'>Delete selected</span></span>";
  11397. }
  11398. // bind the icons
  11399. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  11400. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  11401. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  11402. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  11403. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11404. var editButton = document.getElementById("graph-manipulate-editNode");
  11405. editButton.onclick = this._editNode.bind(this);
  11406. }
  11407. if (this._selectionIsEmpty() == false) {
  11408. var deleteButton = document.getElementById("graph-manipulate-delete");
  11409. deleteButton.onclick = this._deleteSelected.bind(this);
  11410. }
  11411. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11412. closeDiv.onclick = this._toggleEditMode.bind(this);
  11413. this.boundFunction = this._createManipulatorBar.bind(this);
  11414. this.on('select', this.boundFunction);
  11415. }
  11416. else {
  11417. this.editModeDiv.innerHTML = "" +
  11418. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  11419. "<span class='graph-manipulationLabel'>Edit</span></span>"
  11420. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  11421. editModeButton.onclick = this._toggleEditMode.bind(this);
  11422. }
  11423. },
  11424. /**
  11425. * Create the toolbar for adding Nodes
  11426. *
  11427. * @private
  11428. */
  11429. _createAddNodeToolbar : function() {
  11430. // clear the toolbar
  11431. this._clearManipulatorBar();
  11432. if (this.boundFunction) {
  11433. this.off('select', this.boundFunction);
  11434. }
  11435. // create the toolbar contents
  11436. this.manipulationDiv.innerHTML = "" +
  11437. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11438. "<span class='graph-manipulationLabel'>Back</span></span>" +
  11439. "<div class='graph-seperatorLine'></div>" +
  11440. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11441. "<span class='graph-manipulationLabel'>Click in an empty space to place a new node</span></span>";
  11442. // bind the icon
  11443. var backButton = document.getElementById("graph-manipulate-back");
  11444. backButton.onclick = this._createManipulatorBar.bind(this);
  11445. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11446. this.boundFunction = this._addNode.bind(this);
  11447. this.on('select', this.boundFunction);
  11448. },
  11449. /**
  11450. * create the toolbar to connect nodes
  11451. *
  11452. * @private
  11453. */
  11454. _createAddEdgeToolbar : function() {
  11455. // clear the toolbar
  11456. this._clearManipulatorBar();
  11457. this._unselectAll(true);
  11458. this.freezeSimulation = true;
  11459. if (this.boundFunction) {
  11460. this.off('select', this.boundFunction);
  11461. }
  11462. this._unselectAll();
  11463. this.forceAppendSelection = false;
  11464. this.blockConnectingEdgeSelection = true;
  11465. this.manipulationDiv.innerHTML = "" +
  11466. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11467. "<span class='graph-manipulationLabel'>Back</span></span>" +
  11468. "<div class='graph-seperatorLine'></div>" +
  11469. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11470. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>Click on a node and drag the edge to another node to connect them.</span></span>";
  11471. // bind the icon
  11472. var backButton = document.getElementById("graph-manipulate-back");
  11473. backButton.onclick = this._createManipulatorBar.bind(this);
  11474. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11475. this.boundFunction = this._handleConnect.bind(this);
  11476. this.on('select', this.boundFunction);
  11477. // temporarily overload functions
  11478. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  11479. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  11480. this._handleTouch = this._handleConnect;
  11481. this._handleOnRelease = this._finishConnect;
  11482. // redraw to show the unselect
  11483. this._redraw();
  11484. },
  11485. /**
  11486. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11487. * to walk the user through the process.
  11488. *
  11489. * @private
  11490. */
  11491. _handleConnect : function(pointer) {
  11492. if (this._getSelectedNodeCount() == 0) {
  11493. var node = this._getNodeAt(pointer);
  11494. if (node != null) {
  11495. if (node.clusterSize > 1) {
  11496. alert("Cannot create edges to a cluster.")
  11497. }
  11498. else {
  11499. this._selectObject(node,false);
  11500. // create a node the temporary line can look at
  11501. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11502. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11503. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11504. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11505. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11506. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11507. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11508. // create a temporary edge
  11509. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11510. this.edges['connectionEdge'].from = node;
  11511. this.edges['connectionEdge'].connected = true;
  11512. this.edges['connectionEdge'].smooth = true;
  11513. this.edges['connectionEdge'].selected = true;
  11514. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11515. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11516. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11517. this._handleOnDrag = function(event) {
  11518. var pointer = this._getPointer(event.gesture.center);
  11519. this.sectors['support']['nodes']['targetNode'].x = this._canvasToX(pointer.x);
  11520. this.sectors['support']['nodes']['targetNode'].y = this._canvasToY(pointer.y);
  11521. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._canvasToX(pointer.x) + this.edges['connectionEdge'].from.x);
  11522. this.sectors['support']['nodes']['targetViaNode'].y = this._canvasToY(pointer.y);
  11523. };
  11524. this.moving = true;
  11525. this.start();
  11526. }
  11527. }
  11528. }
  11529. },
  11530. _finishConnect : function(pointer) {
  11531. if (this._getSelectedNodeCount() == 1) {
  11532. // restore the drag function
  11533. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11534. delete this.cachedFunctions["_handleOnDrag"];
  11535. // remember the edge id
  11536. var connectFromId = this.edges['connectionEdge'].fromId;
  11537. // remove the temporary nodes and edge
  11538. delete this.edges['connectionEdge']
  11539. delete this.sectors['support']['nodes']['targetNode'];
  11540. delete this.sectors['support']['nodes']['targetViaNode'];
  11541. var node = this._getNodeAt(pointer);
  11542. if (node != null) {
  11543. if (node.clusterSize > 1) {
  11544. alert("Cannot create edges to a cluster.")
  11545. }
  11546. else {
  11547. this._createEdge(connectFromId,node.id);
  11548. this._createManipulatorBar();
  11549. }
  11550. }
  11551. this._unselectAll();
  11552. }
  11553. },
  11554. /**
  11555. * Adds a node on the specified location
  11556. *
  11557. * @param {Object} pointer
  11558. */
  11559. _addNode : function() {
  11560. if (this._selectionIsEmpty() && this.editMode == true) {
  11561. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11562. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  11563. if (this.triggerFunctions.add) {
  11564. if (this.triggerFunctions.add.length == 2) {
  11565. var me = this;
  11566. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11567. me.nodesData.add(finalizedData);
  11568. me._createManipulatorBar();
  11569. me.moving = true;
  11570. me.start();
  11571. });
  11572. }
  11573. else {
  11574. alert("The function for add does not support two arguments (data,callback).");
  11575. this._createManipulatorBar();
  11576. this.moving = true;
  11577. this.start();
  11578. }
  11579. }
  11580. else {
  11581. this.nodesData.add(defaultData);
  11582. this._createManipulatorBar();
  11583. this.moving = true;
  11584. this.start();
  11585. }
  11586. }
  11587. },
  11588. /**
  11589. * connect two nodes with a new edge.
  11590. *
  11591. * @private
  11592. */
  11593. _createEdge : function(sourceNodeId,targetNodeId) {
  11594. if (this.editMode == true) {
  11595. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11596. if (this.triggerFunctions.connect) {
  11597. if (this.triggerFunctions.connect.length == 2) {
  11598. var me = this;
  11599. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11600. me.edgesData.add(finalizedData)
  11601. me.moving = true;
  11602. me.start();
  11603. });
  11604. }
  11605. else {
  11606. alert("The function for connect does not support two arguments (data,callback).");
  11607. this.moving = true;
  11608. this.start();
  11609. }
  11610. }
  11611. else {
  11612. this.edgesData.add(defaultData)
  11613. this.moving = true;
  11614. this.start();
  11615. }
  11616. }
  11617. },
  11618. /**
  11619. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11620. *
  11621. * @private
  11622. */
  11623. _editNode : function() {
  11624. if (this.triggerFunctions.edit && this.editMode == true) {
  11625. var node = this._getSelectedNode();
  11626. var data = {id:node.id,
  11627. label: node.label,
  11628. group: node.group,
  11629. shape: node.shape,
  11630. color: {
  11631. background:node.color.background,
  11632. border:node.color.border,
  11633. highlight: {
  11634. background:node.color.highlight.background,
  11635. border:node.color.highlight.border
  11636. }
  11637. }};
  11638. if (this.triggerFunctions.edit.length == 2) {
  11639. var me = this;
  11640. this.triggerFunctions.edit(data, function (finalizedData) {
  11641. me.nodesData.update(finalizedData);
  11642. me._createManipulatorBar();
  11643. me.moving = true;
  11644. me.start();
  11645. });
  11646. }
  11647. else {
  11648. alert("The function for edit does not support two arguments (data, callback).")
  11649. }
  11650. }
  11651. else {
  11652. alert("No edit function has been bound to this button.")
  11653. }
  11654. },
  11655. /**
  11656. * delete everything in the selection
  11657. *
  11658. * @private
  11659. */
  11660. _deleteSelected : function() {
  11661. if (!this._selectionIsEmpty() && this.editMode == true) {
  11662. if (!this._clusterInSelection()) {
  11663. var selectedNodes = this.getSelectedNodes();
  11664. var selectedEdges = this.getSelectedEdges();
  11665. if (this.triggerFunctions.delete) {
  11666. var me = this;
  11667. var data = {nodes: selectedNodes, edges: selectedEdges};
  11668. if (this.triggerFunctions.delete.length = 2) {
  11669. this.triggerFunctions.delete(data, function (finalizedData) {
  11670. me.edgesData.remove(finalizedData.edges);
  11671. me.nodesData.remove(finalizedData.nodes);
  11672. this._unselectAll();
  11673. me.moving = true;
  11674. me.start();
  11675. });
  11676. }
  11677. else {
  11678. alert("The function for edit does not support two arguments (data, callback).")
  11679. }
  11680. }
  11681. else {
  11682. this.edgesData.remove(selectedEdges);
  11683. this.nodesData.remove(selectedNodes);
  11684. this._unselectAll();
  11685. this.moving = true;
  11686. this.start();
  11687. }
  11688. }
  11689. else {
  11690. alert("Clusters cannot be deleted.");
  11691. }
  11692. }
  11693. }
  11694. };
  11695. /**
  11696. * Creation of the SectorMixin var.
  11697. *
  11698. * This contains all the functions the Graph object can use to employ the sector system.
  11699. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11700. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11701. *
  11702. * Alex de Mulder
  11703. * 21-01-2013
  11704. */
  11705. var SectorMixin = {
  11706. /**
  11707. * This function is only called by the setData function of the Graph object.
  11708. * This loads the global references into the active sector. This initializes the sector.
  11709. *
  11710. * @private
  11711. */
  11712. _putDataInSector : function() {
  11713. this.sectors["active"][this._sector()].nodes = this.nodes;
  11714. this.sectors["active"][this._sector()].edges = this.edges;
  11715. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11716. },
  11717. /**
  11718. * /**
  11719. * This function sets the global references to nodes, edges and nodeIndices back to
  11720. * those of the supplied (active) sector. If a type is defined, do the specific type
  11721. *
  11722. * @param {String} sectorId
  11723. * @param {String} [sectorType] | "active" or "frozen"
  11724. * @private
  11725. */
  11726. _switchToSector : function(sectorId, sectorType) {
  11727. if (sectorType === undefined || sectorType == "active") {
  11728. this._switchToActiveSector(sectorId);
  11729. }
  11730. else {
  11731. this._switchToFrozenSector(sectorId);
  11732. }
  11733. },
  11734. /**
  11735. * This function sets the global references to nodes, edges and nodeIndices back to
  11736. * those of the supplied active sector.
  11737. *
  11738. * @param sectorId
  11739. * @private
  11740. */
  11741. _switchToActiveSector : function(sectorId) {
  11742. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11743. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11744. this.edges = this.sectors["active"][sectorId]["edges"];
  11745. },
  11746. /**
  11747. * This function sets the global references to nodes, edges and nodeIndices back to
  11748. * those of the supplied active sector.
  11749. *
  11750. * @param sectorId
  11751. * @private
  11752. */
  11753. _switchToSupportSector : function() {
  11754. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11755. this.nodes = this.sectors["support"]["nodes"];
  11756. this.edges = this.sectors["support"]["edges"];
  11757. },
  11758. /**
  11759. * This function sets the global references to nodes, edges and nodeIndices back to
  11760. * those of the supplied frozen sector.
  11761. *
  11762. * @param sectorId
  11763. * @private
  11764. */
  11765. _switchToFrozenSector : function(sectorId) {
  11766. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11767. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11768. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11769. },
  11770. /**
  11771. * This function sets the global references to nodes, edges and nodeIndices back to
  11772. * those of the currently active sector.
  11773. *
  11774. * @private
  11775. */
  11776. _loadLatestSector : function() {
  11777. this._switchToSector(this._sector());
  11778. },
  11779. /**
  11780. * This function returns the currently active sector Id
  11781. *
  11782. * @returns {String}
  11783. * @private
  11784. */
  11785. _sector : function() {
  11786. return this.activeSector[this.activeSector.length-1];
  11787. },
  11788. /**
  11789. * This function returns the previously active sector Id
  11790. *
  11791. * @returns {String}
  11792. * @private
  11793. */
  11794. _previousSector : function() {
  11795. if (this.activeSector.length > 1) {
  11796. return this.activeSector[this.activeSector.length-2];
  11797. }
  11798. else {
  11799. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11800. }
  11801. },
  11802. /**
  11803. * We add the active sector at the end of the this.activeSector array
  11804. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11805. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11806. *
  11807. * @param newId
  11808. * @private
  11809. */
  11810. _setActiveSector : function(newId) {
  11811. this.activeSector.push(newId);
  11812. },
  11813. /**
  11814. * We remove the currently active sector id from the active sector stack. This happens when
  11815. * we reactivate the previously active sector
  11816. *
  11817. * @private
  11818. */
  11819. _forgetLastSector : function() {
  11820. this.activeSector.pop();
  11821. },
  11822. /**
  11823. * This function creates a new active sector with the supplied newId. This newId
  11824. * is the expanding node id.
  11825. *
  11826. * @param {String} newId | Id of the new active sector
  11827. * @private
  11828. */
  11829. _createNewSector : function(newId) {
  11830. // create the new sector
  11831. this.sectors["active"][newId] = {"nodes":{},
  11832. "edges":{},
  11833. "nodeIndices":[],
  11834. "formationScale": this.scale,
  11835. "drawingNode": undefined};
  11836. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11837. this.sectors["active"][newId]['drawingNode'] = new Node(
  11838. {id:newId,
  11839. color: {
  11840. background: "#eaefef",
  11841. border: "495c5e"
  11842. }
  11843. },{},{},this.constants);
  11844. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11845. },
  11846. /**
  11847. * This function removes the currently active sector. This is called when we create a new
  11848. * active sector.
  11849. *
  11850. * @param {String} sectorId | Id of the active sector that will be removed
  11851. * @private
  11852. */
  11853. _deleteActiveSector : function(sectorId) {
  11854. delete this.sectors["active"][sectorId];
  11855. },
  11856. /**
  11857. * This function removes the currently active sector. This is called when we reactivate
  11858. * the previously active sector.
  11859. *
  11860. * @param {String} sectorId | Id of the active sector that will be removed
  11861. * @private
  11862. */
  11863. _deleteFrozenSector : function(sectorId) {
  11864. delete this.sectors["frozen"][sectorId];
  11865. },
  11866. /**
  11867. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11868. * We copy the references, then delete the active entree.
  11869. *
  11870. * @param sectorId
  11871. * @private
  11872. */
  11873. _freezeSector : function(sectorId) {
  11874. // we move the set references from the active to the frozen stack.
  11875. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11876. // we have moved the sector data into the frozen set, we now remove it from the active set
  11877. this._deleteActiveSector(sectorId);
  11878. },
  11879. /**
  11880. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11881. * object to the "active" object.
  11882. *
  11883. * @param sectorId
  11884. * @private
  11885. */
  11886. _activateSector : function(sectorId) {
  11887. // we move the set references from the frozen to the active stack.
  11888. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11889. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11890. this._deleteFrozenSector(sectorId);
  11891. },
  11892. /**
  11893. * This function merges the data from the currently active sector with a frozen sector. This is used
  11894. * in the process of reverting back to the previously active sector.
  11895. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11896. * upon the creation of a new active sector.
  11897. *
  11898. * @param sectorId
  11899. * @private
  11900. */
  11901. _mergeThisWithFrozen : function(sectorId) {
  11902. // copy all nodes
  11903. for (var nodeId in this.nodes) {
  11904. if (this.nodes.hasOwnProperty(nodeId)) {
  11905. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11906. }
  11907. }
  11908. // copy all edges (if not fully clustered, else there are no edges)
  11909. for (var edgeId in this.edges) {
  11910. if (this.edges.hasOwnProperty(edgeId)) {
  11911. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11912. }
  11913. }
  11914. // merge the nodeIndices
  11915. for (var i = 0; i < this.nodeIndices.length; i++) {
  11916. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11917. }
  11918. },
  11919. /**
  11920. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11921. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11922. *
  11923. * @private
  11924. */
  11925. _collapseThisToSingleCluster : function() {
  11926. this.clusterToFit(1,false);
  11927. },
  11928. /**
  11929. * We create a new active sector from the node that we want to open.
  11930. *
  11931. * @param node
  11932. * @private
  11933. */
  11934. _addSector : function(node) {
  11935. // this is the currently active sector
  11936. var sector = this._sector();
  11937. // // this should allow me to select nodes from a frozen set.
  11938. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11939. // console.log("the node is part of the active sector");
  11940. // }
  11941. // else {
  11942. // console.log("I dont know what the fuck happened!!");
  11943. // }
  11944. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11945. delete this.nodes[node.id];
  11946. var unqiueIdentifier = util.randomUUID();
  11947. // we fully freeze the currently active sector
  11948. this._freezeSector(sector);
  11949. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11950. this._createNewSector(unqiueIdentifier);
  11951. // we add the active sector to the sectors array to be able to revert these steps later on
  11952. this._setActiveSector(unqiueIdentifier);
  11953. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11954. this._switchToSector(this._sector());
  11955. // finally we add the node we removed from our previous active sector to the new active sector
  11956. this.nodes[node.id] = node;
  11957. },
  11958. /**
  11959. * We close the sector that is currently open and revert back to the one before.
  11960. * If the active sector is the "default" sector, nothing happens.
  11961. *
  11962. * @private
  11963. */
  11964. _collapseSector : function() {
  11965. // the currently active sector
  11966. var sector = this._sector();
  11967. // we cannot collapse the default sector
  11968. if (sector != "default") {
  11969. if ((this.nodeIndices.length == 1) ||
  11970. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11971. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11972. var previousSector = this._previousSector();
  11973. // we collapse the sector back to a single cluster
  11974. this._collapseThisToSingleCluster();
  11975. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  11976. // This previous sector is the one we will reactivate
  11977. this._mergeThisWithFrozen(previousSector);
  11978. // the previously active (frozen) sector now has all the data from the currently active sector.
  11979. // we can now delete the active sector.
  11980. this._deleteActiveSector(sector);
  11981. // we activate the previously active (and currently frozen) sector.
  11982. this._activateSector(previousSector);
  11983. // we load the references from the newly active sector into the global references
  11984. this._switchToSector(previousSector);
  11985. // we forget the previously active sector because we reverted to the one before
  11986. this._forgetLastSector();
  11987. // finally, we update the node index list.
  11988. this._updateNodeIndexList();
  11989. // we refresh the list with calulation nodes and calculation node indices.
  11990. this._updateCalculationNodes();
  11991. }
  11992. }
  11993. },
  11994. /**
  11995. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11996. *
  11997. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11998. * | we dont pass the function itself because then the "this" is the window object
  11999. * | instead of the Graph object
  12000. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12001. * @private
  12002. */
  12003. _doInAllActiveSectors : function(runFunction,argument) {
  12004. if (argument === undefined) {
  12005. for (var sector in this.sectors["active"]) {
  12006. if (this.sectors["active"].hasOwnProperty(sector)) {
  12007. // switch the global references to those of this sector
  12008. this._switchToActiveSector(sector);
  12009. this[runFunction]();
  12010. }
  12011. }
  12012. }
  12013. else {
  12014. for (var sector in this.sectors["active"]) {
  12015. if (this.sectors["active"].hasOwnProperty(sector)) {
  12016. // switch the global references to those of this sector
  12017. this._switchToActiveSector(sector);
  12018. var args = Array.prototype.splice.call(arguments, 1);
  12019. if (args.length > 1) {
  12020. this[runFunction](args[0],args[1]);
  12021. }
  12022. else {
  12023. this[runFunction](argument);
  12024. }
  12025. }
  12026. }
  12027. }
  12028. // we revert the global references back to our active sector
  12029. this._loadLatestSector();
  12030. },
  12031. /**
  12032. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  12033. *
  12034. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  12035. * | we dont pass the function itself because then the "this" is the window object
  12036. * | instead of the Graph object
  12037. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12038. * @private
  12039. */
  12040. _doInSupportSector : function(runFunction,argument) {
  12041. if (argument === undefined) {
  12042. this._switchToSupportSector();
  12043. this[runFunction]();
  12044. }
  12045. else {
  12046. this._switchToSupportSector();
  12047. var args = Array.prototype.splice.call(arguments, 1);
  12048. if (args.length > 1) {
  12049. this[runFunction](args[0],args[1]);
  12050. }
  12051. else {
  12052. this[runFunction](argument);
  12053. }
  12054. }
  12055. // we revert the global references back to our active sector
  12056. this._loadLatestSector();
  12057. },
  12058. /**
  12059. * This runs a function in all frozen sectors. This is used in the _redraw().
  12060. *
  12061. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  12062. * | we don't pass the function itself because then the "this" is the window object
  12063. * | instead of the Graph object
  12064. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12065. * @private
  12066. */
  12067. _doInAllFrozenSectors : function(runFunction,argument) {
  12068. if (argument === undefined) {
  12069. for (var sector in this.sectors["frozen"]) {
  12070. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  12071. // switch the global references to those of this sector
  12072. this._switchToFrozenSector(sector);
  12073. this[runFunction]();
  12074. }
  12075. }
  12076. }
  12077. else {
  12078. for (var sector in this.sectors["frozen"]) {
  12079. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  12080. // switch the global references to those of this sector
  12081. this._switchToFrozenSector(sector);
  12082. var args = Array.prototype.splice.call(arguments, 1);
  12083. if (args.length > 1) {
  12084. this[runFunction](args[0],args[1]);
  12085. }
  12086. else {
  12087. this[runFunction](argument);
  12088. }
  12089. }
  12090. }
  12091. }
  12092. this._loadLatestSector();
  12093. },
  12094. /**
  12095. * This runs a function in all sectors. This is used in the _redraw().
  12096. *
  12097. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  12098. * | we don't pass the function itself because then the "this" is the window object
  12099. * | instead of the Graph object
  12100. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12101. * @private
  12102. */
  12103. _doInAllSectors : function(runFunction,argument) {
  12104. var args = Array.prototype.splice.call(arguments, 1);
  12105. if (argument === undefined) {
  12106. this._doInAllActiveSectors(runFunction);
  12107. this._doInAllFrozenSectors(runFunction);
  12108. }
  12109. else {
  12110. if (args.length > 1) {
  12111. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  12112. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  12113. }
  12114. else {
  12115. this._doInAllActiveSectors(runFunction,argument);
  12116. this._doInAllFrozenSectors(runFunction,argument);
  12117. }
  12118. }
  12119. },
  12120. /**
  12121. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  12122. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  12123. *
  12124. * @private
  12125. */
  12126. _clearNodeIndexList : function() {
  12127. var sector = this._sector();
  12128. this.sectors["active"][sector]["nodeIndices"] = [];
  12129. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  12130. },
  12131. /**
  12132. * Draw the encompassing sector node
  12133. *
  12134. * @param ctx
  12135. * @param sectorType
  12136. * @private
  12137. */
  12138. _drawSectorNodes : function(ctx,sectorType) {
  12139. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  12140. for (var sector in this.sectors[sectorType]) {
  12141. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  12142. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  12143. this._switchToSector(sector,sectorType);
  12144. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  12145. for (var nodeId in this.nodes) {
  12146. if (this.nodes.hasOwnProperty(nodeId)) {
  12147. node = this.nodes[nodeId];
  12148. node.resize(ctx);
  12149. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  12150. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  12151. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  12152. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  12153. }
  12154. }
  12155. node = this.sectors[sectorType][sector]["drawingNode"];
  12156. node.x = 0.5 * (maxX + minX);
  12157. node.y = 0.5 * (maxY + minY);
  12158. node.width = 2 * (node.x - minX);
  12159. node.height = 2 * (node.y - minY);
  12160. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  12161. node.setScale(this.scale);
  12162. node._drawCircle(ctx);
  12163. }
  12164. }
  12165. }
  12166. },
  12167. _drawAllSectorNodes : function(ctx) {
  12168. this._drawSectorNodes(ctx,"frozen");
  12169. this._drawSectorNodes(ctx,"active");
  12170. this._loadLatestSector();
  12171. }
  12172. };
  12173. /**
  12174. * Creation of the ClusterMixin var.
  12175. *
  12176. * This contains all the functions the Graph object can use to employ clustering
  12177. *
  12178. * Alex de Mulder
  12179. * 21-01-2013
  12180. */
  12181. var ClusterMixin = {
  12182. /**
  12183. * This is only called in the constructor of the graph object
  12184. *
  12185. */
  12186. startWithClustering : function() {
  12187. // cluster if the data set is big
  12188. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  12189. // updates the lables after clustering
  12190. this.updateLabels();
  12191. // this is called here because if clusterin is disabled, the start and stabilize are called in
  12192. // the setData function.
  12193. if (this.stabilize) {
  12194. this._stabilize();
  12195. }
  12196. this.start();
  12197. },
  12198. /**
  12199. * This function clusters until the initialMaxNodes has been reached
  12200. *
  12201. * @param {Number} maxNumberOfNodes
  12202. * @param {Boolean} reposition
  12203. */
  12204. clusterToFit : function(maxNumberOfNodes, reposition) {
  12205. var numberOfNodes = this.nodeIndices.length;
  12206. var maxLevels = 50;
  12207. var level = 0;
  12208. // we first cluster the hubs, then we pull in the outliers, repeat
  12209. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  12210. if (level % 3 == 0) {
  12211. this.forceAggregateHubs(true);
  12212. this.normalizeClusterLevels();
  12213. }
  12214. else {
  12215. this.increaseClusterLevel(); // this also includes a cluster normalization
  12216. }
  12217. numberOfNodes = this.nodeIndices.length;
  12218. level += 1;
  12219. }
  12220. // after the clustering we reposition the nodes to reduce the initial chaos
  12221. if (level > 0 && reposition == true) {
  12222. this.repositionNodes();
  12223. }
  12224. this._updateCalculationNodes();
  12225. },
  12226. /**
  12227. * This function can be called to open up a specific cluster. It is only called by
  12228. * It will unpack the cluster back one level.
  12229. *
  12230. * @param node | Node object: cluster to open.
  12231. */
  12232. openCluster : function(node) {
  12233. var isMovingBeforeClustering = this.moving;
  12234. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  12235. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  12236. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  12237. this._addSector(node);
  12238. var level = 0;
  12239. // we decluster until we reach a decent number of nodes
  12240. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  12241. this.decreaseClusterLevel();
  12242. level += 1;
  12243. }
  12244. }
  12245. else {
  12246. this._expandClusterNode(node,false,true);
  12247. // update the index list, dynamic edges and labels
  12248. this._updateNodeIndexList();
  12249. this._updateDynamicEdges();
  12250. this._updateCalculationNodes();
  12251. this.updateLabels();
  12252. }
  12253. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12254. if (this.moving != isMovingBeforeClustering) {
  12255. this.start();
  12256. }
  12257. },
  12258. /**
  12259. * This calls the updateClustes with default arguments
  12260. */
  12261. updateClustersDefault : function() {
  12262. if (this.constants.clustering.enabled == true) {
  12263. this.updateClusters(0,false,false);
  12264. }
  12265. },
  12266. /**
  12267. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  12268. * be clustered with their connected node. This can be repeated as many times as needed.
  12269. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  12270. */
  12271. increaseClusterLevel : function() {
  12272. this.updateClusters(-1,false,true);
  12273. },
  12274. /**
  12275. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  12276. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  12277. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  12278. */
  12279. decreaseClusterLevel : function() {
  12280. this.updateClusters(1,false,true);
  12281. },
  12282. /**
  12283. * This is the main clustering function. It clusters and declusters on zoom or forced
  12284. * This function clusters on zoom, it can be called with a predefined zoom direction
  12285. * If out, check if we can form clusters, if in, check if we can open clusters.
  12286. * This function is only called from _zoom()
  12287. *
  12288. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  12289. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  12290. * @param {Boolean} force | enabled or disable forcing
  12291. *
  12292. */
  12293. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  12294. var isMovingBeforeClustering = this.moving;
  12295. var amountOfNodes = this.nodeIndices.length;
  12296. // on zoom out collapse the sector if the scale is at the level the sector was made
  12297. if (this.previousScale > this.scale && zoomDirection == 0) {
  12298. this._collapseSector();
  12299. }
  12300. // check if we zoom in or out
  12301. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12302. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  12303. // outer nodes determines if it is being clustered
  12304. this._formClusters(force);
  12305. }
  12306. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  12307. if (force == true) {
  12308. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  12309. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  12310. this._openClusters(recursive,force);
  12311. }
  12312. else {
  12313. // if a cluster takes up a set percentage of the active window
  12314. this._openClustersBySize();
  12315. }
  12316. }
  12317. this._updateNodeIndexList();
  12318. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  12319. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  12320. this._aggregateHubs(force);
  12321. this._updateNodeIndexList();
  12322. }
  12323. // we now reduce chains.
  12324. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12325. this.handleChains();
  12326. this._updateNodeIndexList();
  12327. }
  12328. this.previousScale = this.scale;
  12329. // rest of the update the index list, dynamic edges and labels
  12330. this._updateDynamicEdges();
  12331. this.updateLabels();
  12332. // if a cluster was formed, we increase the clusterSession
  12333. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  12334. this.clusterSession += 1;
  12335. // if clusters have been made, we normalize the cluster level
  12336. this.normalizeClusterLevels();
  12337. }
  12338. if (doNotStart == false || doNotStart === undefined) {
  12339. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12340. if (this.moving != isMovingBeforeClustering) {
  12341. this.start();
  12342. }
  12343. }
  12344. this._updateCalculationNodes();
  12345. },
  12346. /**
  12347. * This function handles the chains. It is called on every updateClusters().
  12348. */
  12349. handleChains : function() {
  12350. // after clustering we check how many chains there are
  12351. var chainPercentage = this._getChainFraction();
  12352. if (chainPercentage > this.constants.clustering.chainThreshold) {
  12353. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  12354. }
  12355. },
  12356. /**
  12357. * this functions starts clustering by hubs
  12358. * The minimum hub threshold is set globally
  12359. *
  12360. * @private
  12361. */
  12362. _aggregateHubs : function(force) {
  12363. this._getHubSize();
  12364. this._formClustersByHub(force,false);
  12365. },
  12366. /**
  12367. * This function is fired by keypress. It forces hubs to form.
  12368. *
  12369. */
  12370. forceAggregateHubs : function(doNotStart) {
  12371. var isMovingBeforeClustering = this.moving;
  12372. var amountOfNodes = this.nodeIndices.length;
  12373. this._aggregateHubs(true);
  12374. // update the index list, dynamic edges and labels
  12375. this._updateNodeIndexList();
  12376. this._updateDynamicEdges();
  12377. this.updateLabels();
  12378. // if a cluster was formed, we increase the clusterSession
  12379. if (this.nodeIndices.length != amountOfNodes) {
  12380. this.clusterSession += 1;
  12381. }
  12382. if (doNotStart == false || doNotStart === undefined) {
  12383. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12384. if (this.moving != isMovingBeforeClustering) {
  12385. this.start();
  12386. }
  12387. }
  12388. },
  12389. /**
  12390. * If a cluster takes up more than a set percentage of the screen, open the cluster
  12391. *
  12392. * @private
  12393. */
  12394. _openClustersBySize : function() {
  12395. for (var nodeId in this.nodes) {
  12396. if (this.nodes.hasOwnProperty(nodeId)) {
  12397. var node = this.nodes[nodeId];
  12398. if (node.inView() == true) {
  12399. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  12400. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  12401. this.openCluster(node);
  12402. }
  12403. }
  12404. }
  12405. }
  12406. },
  12407. /**
  12408. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  12409. * has to be opened based on the current zoom level.
  12410. *
  12411. * @private
  12412. */
  12413. _openClusters : function(recursive,force) {
  12414. for (var i = 0; i < this.nodeIndices.length; i++) {
  12415. var node = this.nodes[this.nodeIndices[i]];
  12416. this._expandClusterNode(node,recursive,force);
  12417. this._updateCalculationNodes();
  12418. }
  12419. },
  12420. /**
  12421. * This function checks if a node has to be opened. This is done by checking the zoom level.
  12422. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  12423. * This recursive behaviour is optional and can be set by the recursive argument.
  12424. *
  12425. * @param {Node} parentNode | to check for cluster and expand
  12426. * @param {Boolean} recursive | enabled or disable recursive calling
  12427. * @param {Boolean} force | enabled or disable forcing
  12428. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  12429. * @private
  12430. */
  12431. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  12432. // first check if node is a cluster
  12433. if (parentNode.clusterSize > 1) {
  12434. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  12435. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  12436. openAll = true;
  12437. }
  12438. recursive = openAll ? true : recursive;
  12439. // if the last child has been added on a smaller scale than current scale decluster
  12440. if (parentNode.formationScale < this.scale || force == true) {
  12441. // we will check if any of the contained child nodes should be removed from the cluster
  12442. for (var containedNodeId in parentNode.containedNodes) {
  12443. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  12444. var childNode = parentNode.containedNodes[containedNodeId];
  12445. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  12446. // the largest cluster is the one that comes from outside
  12447. if (force == true) {
  12448. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  12449. || openAll) {
  12450. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12451. }
  12452. }
  12453. else {
  12454. if (this._nodeInActiveArea(parentNode)) {
  12455. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12456. }
  12457. }
  12458. }
  12459. }
  12460. }
  12461. }
  12462. },
  12463. /**
  12464. * ONLY CALLED FROM _expandClusterNode
  12465. *
  12466. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  12467. * the child node from the parent contained_node object and put it back into the global nodes object.
  12468. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  12469. *
  12470. * @param {Node} parentNode | the parent node
  12471. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  12472. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  12473. * With force and recursive both true, the entire cluster is unpacked
  12474. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  12475. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  12476. * @private
  12477. */
  12478. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  12479. var childNode = parentNode.containedNodes[containedNodeId];
  12480. // if child node has been added on smaller scale than current, kick out
  12481. if (childNode.formationScale < this.scale || force == true) {
  12482. // unselect all selected items
  12483. this._unselectAll();
  12484. // put the child node back in the global nodes object
  12485. this.nodes[containedNodeId] = childNode;
  12486. // release the contained edges from this childNode back into the global edges
  12487. this._releaseContainedEdges(parentNode,childNode);
  12488. // reconnect rerouted edges to the childNode
  12489. this._connectEdgeBackToChild(parentNode,childNode);
  12490. // validate all edges in dynamicEdges
  12491. this._validateEdges(parentNode);
  12492. // undo the changes from the clustering operation on the parent node
  12493. parentNode.mass -= childNode.mass;
  12494. parentNode.clusterSize -= childNode.clusterSize;
  12495. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12496. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12497. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12498. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12499. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12500. // remove node from the list
  12501. delete parentNode.containedNodes[containedNodeId];
  12502. // check if there are other childs with this clusterSession in the parent.
  12503. var othersPresent = false;
  12504. for (var childNodeId in parentNode.containedNodes) {
  12505. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12506. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12507. othersPresent = true;
  12508. break;
  12509. }
  12510. }
  12511. }
  12512. // if there are no others, remove the cluster session from the list
  12513. if (othersPresent == false) {
  12514. parentNode.clusterSessions.pop();
  12515. }
  12516. this._repositionBezierNodes(childNode);
  12517. // this._repositionBezierNodes(parentNode);
  12518. // remove the clusterSession from the child node
  12519. childNode.clusterSession = 0;
  12520. // recalculate the size of the node on the next time the node is rendered
  12521. parentNode.clearSizeCache();
  12522. // restart the simulation to reorganise all nodes
  12523. this.moving = true;
  12524. }
  12525. // check if a further expansion step is possible if recursivity is enabled
  12526. if (recursive == true) {
  12527. this._expandClusterNode(childNode,recursive,force,openAll);
  12528. }
  12529. },
  12530. /**
  12531. * position the bezier nodes at the center of the edges
  12532. *
  12533. * @param node
  12534. * @private
  12535. */
  12536. _repositionBezierNodes : function(node) {
  12537. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12538. node.dynamicEdges[i].positionBezierNode();
  12539. }
  12540. },
  12541. /**
  12542. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12543. * This function is called only from updateClusters()
  12544. * forceLevelCollapse ignores the length of the edge and collapses one level
  12545. * This means that a node with only one edge will be clustered with its connected node
  12546. *
  12547. * @private
  12548. * @param {Boolean} force
  12549. */
  12550. _formClusters : function(force) {
  12551. if (force == false) {
  12552. this._formClustersByZoom();
  12553. }
  12554. else {
  12555. this._forceClustersByZoom();
  12556. }
  12557. },
  12558. /**
  12559. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12560. *
  12561. * @private
  12562. */
  12563. _formClustersByZoom : function() {
  12564. var dx,dy,length,
  12565. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12566. // check if any edges are shorter than minLength and start the clustering
  12567. // the clustering favours the node with the larger mass
  12568. for (var edgeId in this.edges) {
  12569. if (this.edges.hasOwnProperty(edgeId)) {
  12570. var edge = this.edges[edgeId];
  12571. if (edge.connected) {
  12572. if (edge.toId != edge.fromId) {
  12573. dx = (edge.to.x - edge.from.x);
  12574. dy = (edge.to.y - edge.from.y);
  12575. length = Math.sqrt(dx * dx + dy * dy);
  12576. if (length < minLength) {
  12577. // first check which node is larger
  12578. var parentNode = edge.from;
  12579. var childNode = edge.to;
  12580. if (edge.to.mass > edge.from.mass) {
  12581. parentNode = edge.to;
  12582. childNode = edge.from;
  12583. }
  12584. if (childNode.dynamicEdgesLength == 1) {
  12585. this._addToCluster(parentNode,childNode,false);
  12586. }
  12587. else if (parentNode.dynamicEdgesLength == 1) {
  12588. this._addToCluster(childNode,parentNode,false);
  12589. }
  12590. }
  12591. }
  12592. }
  12593. }
  12594. }
  12595. },
  12596. /**
  12597. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12598. * connected node.
  12599. *
  12600. * @private
  12601. */
  12602. _forceClustersByZoom : function() {
  12603. for (var nodeId in this.nodes) {
  12604. // another node could have absorbed this child.
  12605. if (this.nodes.hasOwnProperty(nodeId)) {
  12606. var childNode = this.nodes[nodeId];
  12607. // the edges can be swallowed by another decrease
  12608. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12609. var edge = childNode.dynamicEdges[0];
  12610. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12611. // group to the largest node
  12612. if (childNode.id != parentNode.id) {
  12613. if (parentNode.mass > childNode.mass) {
  12614. this._addToCluster(parentNode,childNode,true);
  12615. }
  12616. else {
  12617. this._addToCluster(childNode,parentNode,true);
  12618. }
  12619. }
  12620. }
  12621. }
  12622. }
  12623. },
  12624. /**
  12625. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12626. * This function clusters a node to its smallest connected neighbour.
  12627. *
  12628. * @param node
  12629. * @private
  12630. */
  12631. _clusterToSmallestNeighbour : function(node) {
  12632. var smallestNeighbour = -1;
  12633. var smallestNeighbourNode = null;
  12634. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12635. if (node.dynamicEdges[i] !== undefined) {
  12636. var neighbour = null;
  12637. if (node.dynamicEdges[i].fromId != node.id) {
  12638. neighbour = node.dynamicEdges[i].from;
  12639. }
  12640. else if (node.dynamicEdges[i].toId != node.id) {
  12641. neighbour = node.dynamicEdges[i].to;
  12642. }
  12643. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12644. smallestNeighbour = neighbour.clusterSessions.length;
  12645. smallestNeighbourNode = neighbour;
  12646. }
  12647. }
  12648. }
  12649. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12650. this._addToCluster(neighbour, node, true);
  12651. }
  12652. },
  12653. /**
  12654. * This function forms clusters from hubs, it loops over all nodes
  12655. *
  12656. * @param {Boolean} force | Disregard zoom level
  12657. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12658. * @private
  12659. */
  12660. _formClustersByHub : function(force, onlyEqual) {
  12661. // we loop over all nodes in the list
  12662. for (var nodeId in this.nodes) {
  12663. // we check if it is still available since it can be used by the clustering in this loop
  12664. if (this.nodes.hasOwnProperty(nodeId)) {
  12665. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12666. }
  12667. }
  12668. },
  12669. /**
  12670. * This function forms a cluster from a specific preselected hub node
  12671. *
  12672. * @param {Node} hubNode | the node we will cluster as a hub
  12673. * @param {Boolean} force | Disregard zoom level
  12674. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12675. * @param {Number} [absorptionSizeOffset] |
  12676. * @private
  12677. */
  12678. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12679. if (absorptionSizeOffset === undefined) {
  12680. absorptionSizeOffset = 0;
  12681. }
  12682. // we decide if the node is a hub
  12683. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12684. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12685. // initialize variables
  12686. var dx,dy,length;
  12687. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12688. var allowCluster = false;
  12689. // we create a list of edges because the dynamicEdges change over the course of this loop
  12690. var edgesIdarray = [];
  12691. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12692. for (var j = 0; j < amountOfInitialEdges; j++) {
  12693. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12694. }
  12695. // if the hub clustering is not forces, we check if one of the edges connected
  12696. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12697. if (force == false) {
  12698. allowCluster = false;
  12699. for (j = 0; j < amountOfInitialEdges; j++) {
  12700. var edge = this.edges[edgesIdarray[j]];
  12701. if (edge !== undefined) {
  12702. if (edge.connected) {
  12703. if (edge.toId != edge.fromId) {
  12704. dx = (edge.to.x - edge.from.x);
  12705. dy = (edge.to.y - edge.from.y);
  12706. length = Math.sqrt(dx * dx + dy * dy);
  12707. if (length < minLength) {
  12708. allowCluster = true;
  12709. break;
  12710. }
  12711. }
  12712. }
  12713. }
  12714. }
  12715. }
  12716. // start the clustering if allowed
  12717. if ((!force && allowCluster) || force) {
  12718. // we loop over all edges INITIALLY connected to this hub
  12719. for (j = 0; j < amountOfInitialEdges; j++) {
  12720. edge = this.edges[edgesIdarray[j]];
  12721. // the edge can be clustered by this function in a previous loop
  12722. if (edge !== undefined) {
  12723. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12724. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12725. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12726. (childNode.id != hubNode.id)) {
  12727. this._addToCluster(hubNode,childNode,force);
  12728. }
  12729. }
  12730. }
  12731. }
  12732. }
  12733. },
  12734. /**
  12735. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12736. *
  12737. * @param {Node} parentNode | this is the node that will house the child node
  12738. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12739. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12740. * @private
  12741. */
  12742. _addToCluster : function(parentNode, childNode, force) {
  12743. // join child node in the parent node
  12744. parentNode.containedNodes[childNode.id] = childNode;
  12745. // manage all the edges connected to the child and parent nodes
  12746. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12747. var edge = childNode.dynamicEdges[i];
  12748. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12749. this._addToContainedEdges(parentNode,childNode,edge);
  12750. }
  12751. else {
  12752. this._connectEdgeToCluster(parentNode,childNode,edge);
  12753. }
  12754. }
  12755. // a contained node has no dynamic edges.
  12756. childNode.dynamicEdges = [];
  12757. // remove circular edges from clusters
  12758. this._containCircularEdgesFromNode(parentNode,childNode);
  12759. // remove the childNode from the global nodes object
  12760. delete this.nodes[childNode.id];
  12761. // update the properties of the child and parent
  12762. var massBefore = parentNode.mass;
  12763. childNode.clusterSession = this.clusterSession;
  12764. parentNode.mass += childNode.mass;
  12765. parentNode.clusterSize += childNode.clusterSize;
  12766. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12767. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12768. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12769. parentNode.clusterSessions.push(this.clusterSession);
  12770. }
  12771. // forced clusters only open from screen size and double tap
  12772. if (force == true) {
  12773. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12774. parentNode.formationScale = 0;
  12775. }
  12776. else {
  12777. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12778. }
  12779. // recalculate the size of the node on the next time the node is rendered
  12780. parentNode.clearSizeCache();
  12781. // set the pop-out scale for the childnode
  12782. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12783. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12784. childNode.clearVelocity();
  12785. // the mass has altered, preservation of energy dictates the velocity to be updated
  12786. parentNode.updateVelocity(massBefore);
  12787. // restart the simulation to reorganise all nodes
  12788. this.moving = true;
  12789. },
  12790. /**
  12791. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12792. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12793. * It has to be called if a level is collapsed. It is called by _formClusters().
  12794. * @private
  12795. */
  12796. _updateDynamicEdges : function() {
  12797. for (var i = 0; i < this.nodeIndices.length; i++) {
  12798. var node = this.nodes[this.nodeIndices[i]];
  12799. node.dynamicEdgesLength = node.dynamicEdges.length;
  12800. // this corrects for multiple edges pointing at the same other node
  12801. var correction = 0;
  12802. if (node.dynamicEdgesLength > 1) {
  12803. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12804. var edgeToId = node.dynamicEdges[j].toId;
  12805. var edgeFromId = node.dynamicEdges[j].fromId;
  12806. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12807. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12808. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12809. correction += 1;
  12810. }
  12811. }
  12812. }
  12813. }
  12814. node.dynamicEdgesLength -= correction;
  12815. }
  12816. },
  12817. /**
  12818. * This adds an edge from the childNode to the contained edges of the parent node
  12819. *
  12820. * @param parentNode | Node object
  12821. * @param childNode | Node object
  12822. * @param edge | Edge object
  12823. * @private
  12824. */
  12825. _addToContainedEdges : function(parentNode, childNode, edge) {
  12826. // create an array object if it does not yet exist for this childNode
  12827. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12828. parentNode.containedEdges[childNode.id] = []
  12829. }
  12830. // add this edge to the list
  12831. parentNode.containedEdges[childNode.id].push(edge);
  12832. // remove the edge from the global edges object
  12833. delete this.edges[edge.id];
  12834. // remove the edge from the parent object
  12835. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12836. if (parentNode.dynamicEdges[i].id == edge.id) {
  12837. parentNode.dynamicEdges.splice(i,1);
  12838. break;
  12839. }
  12840. }
  12841. },
  12842. /**
  12843. * This function connects an edge that was connected to a child node to the parent node.
  12844. * It keeps track of which nodes it has been connected to with the originalId array.
  12845. *
  12846. * @param {Node} parentNode | Node object
  12847. * @param {Node} childNode | Node object
  12848. * @param {Edge} edge | Edge object
  12849. * @private
  12850. */
  12851. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12852. // handle circular edges
  12853. if (edge.toId == edge.fromId) {
  12854. this._addToContainedEdges(parentNode, childNode, edge);
  12855. }
  12856. else {
  12857. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12858. edge.originalToId.push(childNode.id);
  12859. edge.to = parentNode;
  12860. edge.toId = parentNode.id;
  12861. }
  12862. else { // edge connected to other node with the "from" side
  12863. edge.originalFromId.push(childNode.id);
  12864. edge.from = parentNode;
  12865. edge.fromId = parentNode.id;
  12866. }
  12867. this._addToReroutedEdges(parentNode,childNode,edge);
  12868. }
  12869. },
  12870. /**
  12871. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12872. * these edges inside of the cluster.
  12873. *
  12874. * @param parentNode
  12875. * @param childNode
  12876. * @private
  12877. */
  12878. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12879. // manage all the edges connected to the child and parent nodes
  12880. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12881. var edge = parentNode.dynamicEdges[i];
  12882. // handle circular edges
  12883. if (edge.toId == edge.fromId) {
  12884. this._addToContainedEdges(parentNode, childNode, edge);
  12885. }
  12886. }
  12887. },
  12888. /**
  12889. * This adds an edge from the childNode to the rerouted edges of the parent node
  12890. *
  12891. * @param parentNode | Node object
  12892. * @param childNode | Node object
  12893. * @param edge | Edge object
  12894. * @private
  12895. */
  12896. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12897. // create an array object if it does not yet exist for this childNode
  12898. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12899. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12900. parentNode.reroutedEdges[childNode.id] = [];
  12901. }
  12902. parentNode.reroutedEdges[childNode.id].push(edge);
  12903. // this edge becomes part of the dynamicEdges of the cluster node
  12904. parentNode.dynamicEdges.push(edge);
  12905. },
  12906. /**
  12907. * This function connects an edge that was connected to a cluster node back to the child node.
  12908. *
  12909. * @param parentNode | Node object
  12910. * @param childNode | Node object
  12911. * @private
  12912. */
  12913. _connectEdgeBackToChild : function(parentNode, childNode) {
  12914. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12915. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12916. var edge = parentNode.reroutedEdges[childNode.id][i];
  12917. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12918. edge.originalFromId.pop();
  12919. edge.fromId = childNode.id;
  12920. edge.from = childNode;
  12921. }
  12922. else {
  12923. edge.originalToId.pop();
  12924. edge.toId = childNode.id;
  12925. edge.to = childNode;
  12926. }
  12927. // append this edge to the list of edges connecting to the childnode
  12928. childNode.dynamicEdges.push(edge);
  12929. // remove the edge from the parent object
  12930. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12931. if (parentNode.dynamicEdges[j].id == edge.id) {
  12932. parentNode.dynamicEdges.splice(j,1);
  12933. break;
  12934. }
  12935. }
  12936. }
  12937. // remove the entry from the rerouted edges
  12938. delete parentNode.reroutedEdges[childNode.id];
  12939. }
  12940. },
  12941. /**
  12942. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12943. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12944. * parentNode
  12945. *
  12946. * @param parentNode | Node object
  12947. * @private
  12948. */
  12949. _validateEdges : function(parentNode) {
  12950. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12951. var edge = parentNode.dynamicEdges[i];
  12952. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12953. parentNode.dynamicEdges.splice(i,1);
  12954. }
  12955. }
  12956. },
  12957. /**
  12958. * This function released the contained edges back into the global domain and puts them back into the
  12959. * dynamic edges of both parent and child.
  12960. *
  12961. * @param {Node} parentNode |
  12962. * @param {Node} childNode |
  12963. * @private
  12964. */
  12965. _releaseContainedEdges : function(parentNode, childNode) {
  12966. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12967. var edge = parentNode.containedEdges[childNode.id][i];
  12968. // put the edge back in the global edges object
  12969. this.edges[edge.id] = edge;
  12970. // put the edge back in the dynamic edges of the child and parent
  12971. childNode.dynamicEdges.push(edge);
  12972. parentNode.dynamicEdges.push(edge);
  12973. }
  12974. // remove the entry from the contained edges
  12975. delete parentNode.containedEdges[childNode.id];
  12976. },
  12977. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  12978. /**
  12979. * This updates the node labels for all nodes (for debugging purposes)
  12980. */
  12981. updateLabels : function() {
  12982. var nodeId;
  12983. // update node labels
  12984. for (nodeId in this.nodes) {
  12985. if (this.nodes.hasOwnProperty(nodeId)) {
  12986. var node = this.nodes[nodeId];
  12987. if (node.clusterSize > 1) {
  12988. node.label = "[".concat(String(node.clusterSize),"]");
  12989. }
  12990. }
  12991. }
  12992. // update node labels
  12993. for (nodeId in this.nodes) {
  12994. if (this.nodes.hasOwnProperty(nodeId)) {
  12995. node = this.nodes[nodeId];
  12996. if (node.clusterSize == 1) {
  12997. if (node.originalLabel !== undefined) {
  12998. node.label = node.originalLabel;
  12999. }
  13000. else {
  13001. node.label = String(node.id);
  13002. }
  13003. }
  13004. }
  13005. }
  13006. // /* Debug Override */
  13007. // for (nodeId in this.nodes) {
  13008. // if (this.nodes.hasOwnProperty(nodeId)) {
  13009. // node = this.nodes[nodeId];
  13010. // node.label = String(node.level);
  13011. // }
  13012. // }
  13013. },
  13014. /**
  13015. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  13016. * if the rest of the nodes are already a few cluster levels in.
  13017. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  13018. * clustered enough to the clusterToSmallestNeighbours function.
  13019. */
  13020. normalizeClusterLevels : function() {
  13021. var maxLevel = 0;
  13022. var minLevel = 1e9;
  13023. var clusterLevel = 0;
  13024. // we loop over all nodes in the list
  13025. for (var nodeId in this.nodes) {
  13026. if (this.nodes.hasOwnProperty(nodeId)) {
  13027. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  13028. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  13029. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  13030. }
  13031. }
  13032. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  13033. var amountOfNodes = this.nodeIndices.length;
  13034. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  13035. // we loop over all nodes in the list
  13036. for (var nodeId in this.nodes) {
  13037. if (this.nodes.hasOwnProperty(nodeId)) {
  13038. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  13039. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  13040. }
  13041. }
  13042. }
  13043. this._updateNodeIndexList();
  13044. this._updateDynamicEdges();
  13045. // if a cluster was formed, we increase the clusterSession
  13046. if (this.nodeIndices.length != amountOfNodes) {
  13047. this.clusterSession += 1;
  13048. }
  13049. }
  13050. },
  13051. /**
  13052. * This function determines if the cluster we want to decluster is in the active area
  13053. * this means around the zoom center
  13054. *
  13055. * @param {Node} node
  13056. * @returns {boolean}
  13057. * @private
  13058. */
  13059. _nodeInActiveArea : function(node) {
  13060. return (
  13061. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  13062. &&
  13063. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  13064. )
  13065. },
  13066. /**
  13067. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  13068. * It puts large clusters away from the center and randomizes the order.
  13069. *
  13070. */
  13071. repositionNodes : function() {
  13072. for (var i = 0; i < this.nodeIndices.length; i++) {
  13073. var node = this.nodes[this.nodeIndices[i]];
  13074. if ((node.xFixed == false || node.yFixed == false)) {
  13075. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.mass);
  13076. var angle = 2 * Math.PI * Math.random();
  13077. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  13078. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  13079. this._repositionBezierNodes(node);
  13080. }
  13081. }
  13082. },
  13083. /**
  13084. * We determine how many connections denote an important hub.
  13085. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  13086. *
  13087. * @private
  13088. */
  13089. _getHubSize : function() {
  13090. var average = 0;
  13091. var averageSquared = 0;
  13092. var hubCounter = 0;
  13093. var largestHub = 0;
  13094. for (var i = 0; i < this.nodeIndices.length; i++) {
  13095. var node = this.nodes[this.nodeIndices[i]];
  13096. if (node.dynamicEdgesLength > largestHub) {
  13097. largestHub = node.dynamicEdgesLength;
  13098. }
  13099. average += node.dynamicEdgesLength;
  13100. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  13101. hubCounter += 1;
  13102. }
  13103. average = average / hubCounter;
  13104. averageSquared = averageSquared / hubCounter;
  13105. var variance = averageSquared - Math.pow(average,2);
  13106. var standardDeviation = Math.sqrt(variance);
  13107. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  13108. // always have at least one to cluster
  13109. if (this.hubThreshold > largestHub) {
  13110. this.hubThreshold = largestHub;
  13111. }
  13112. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  13113. // console.log("hubThreshold:",this.hubThreshold);
  13114. },
  13115. /**
  13116. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  13117. * with this amount we can cluster specifically on these chains.
  13118. *
  13119. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  13120. * @private
  13121. */
  13122. _reduceAmountOfChains : function(fraction) {
  13123. this.hubThreshold = 2;
  13124. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  13125. for (var nodeId in this.nodes) {
  13126. if (this.nodes.hasOwnProperty(nodeId)) {
  13127. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  13128. if (reduceAmount > 0) {
  13129. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  13130. reduceAmount -= 1;
  13131. }
  13132. }
  13133. }
  13134. }
  13135. },
  13136. /**
  13137. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  13138. * with this amount we can cluster specifically on these chains.
  13139. *
  13140. * @private
  13141. */
  13142. _getChainFraction : function() {
  13143. var chains = 0;
  13144. var total = 0;
  13145. for (var nodeId in this.nodes) {
  13146. if (this.nodes.hasOwnProperty(nodeId)) {
  13147. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  13148. chains += 1;
  13149. }
  13150. total += 1;
  13151. }
  13152. }
  13153. return chains/total;
  13154. }
  13155. };
  13156. var SelectionMixin = {
  13157. /**
  13158. * This function can be called from the _doInAllSectors function
  13159. *
  13160. * @param object
  13161. * @param overlappingNodes
  13162. * @private
  13163. */
  13164. _getNodesOverlappingWith : function(object, overlappingNodes) {
  13165. var nodes = this.nodes;
  13166. for (var nodeId in nodes) {
  13167. if (nodes.hasOwnProperty(nodeId)) {
  13168. if (nodes[nodeId].isOverlappingWith(object)) {
  13169. overlappingNodes.push(nodeId);
  13170. }
  13171. }
  13172. }
  13173. },
  13174. /**
  13175. * retrieve all nodes overlapping with given object
  13176. * @param {Object} object An object with parameters left, top, right, bottom
  13177. * @return {Number[]} An array with id's of the overlapping nodes
  13178. * @private
  13179. */
  13180. _getAllNodesOverlappingWith : function (object) {
  13181. var overlappingNodes = [];
  13182. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  13183. return overlappingNodes;
  13184. },
  13185. /**
  13186. * Return a position object in canvasspace from a single point in screenspace
  13187. *
  13188. * @param pointer
  13189. * @returns {{left: number, top: number, right: number, bottom: number}}
  13190. * @private
  13191. */
  13192. _pointerToPositionObject : function(pointer) {
  13193. var x = this._canvasToX(pointer.x);
  13194. var y = this._canvasToY(pointer.y);
  13195. return {left: x,
  13196. top: y,
  13197. right: x,
  13198. bottom: y};
  13199. },
  13200. /**
  13201. * Get the top node at the a specific point (like a click)
  13202. *
  13203. * @param {{x: Number, y: Number}} pointer
  13204. * @return {Node | null} node
  13205. * @private
  13206. */
  13207. _getNodeAt : function (pointer) {
  13208. // we first check if this is an navigation controls element
  13209. var positionObject = this._pointerToPositionObject(pointer);
  13210. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  13211. // if there are overlapping nodes, select the last one, this is the
  13212. // one which is drawn on top of the others
  13213. if (overlappingNodes.length > 0) {
  13214. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  13215. }
  13216. else {
  13217. return null;
  13218. }
  13219. },
  13220. /**
  13221. * retrieve all edges overlapping with given object, selector is around center
  13222. * @param {Object} object An object with parameters left, top, right, bottom
  13223. * @return {Number[]} An array with id's of the overlapping nodes
  13224. * @private
  13225. */
  13226. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  13227. var edges = this.edges;
  13228. for (var edgeId in edges) {
  13229. if (edges.hasOwnProperty(edgeId)) {
  13230. if (edges[edgeId].isOverlappingWith(object)) {
  13231. overlappingEdges.push(edgeId);
  13232. }
  13233. }
  13234. }
  13235. },
  13236. /**
  13237. * retrieve all nodes overlapping with given object
  13238. * @param {Object} object An object with parameters left, top, right, bottom
  13239. * @return {Number[]} An array with id's of the overlapping nodes
  13240. * @private
  13241. */
  13242. _getAllEdgesOverlappingWith : function (object) {
  13243. var overlappingEdges = [];
  13244. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  13245. return overlappingEdges;
  13246. },
  13247. /**
  13248. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  13249. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  13250. *
  13251. * @param pointer
  13252. * @returns {null}
  13253. * @private
  13254. */
  13255. _getEdgeAt : function(pointer) {
  13256. var positionObject = this._pointerToPositionObject(pointer);
  13257. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  13258. if (overlappingEdges.length > 0) {
  13259. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  13260. }
  13261. else {
  13262. return null;
  13263. }
  13264. },
  13265. /**
  13266. * Add object to the selection array.
  13267. *
  13268. * @param obj
  13269. * @private
  13270. */
  13271. _addToSelection : function(obj) {
  13272. if (obj instanceof Node) {
  13273. this.selectionObj.nodes[obj.id] = obj;
  13274. }
  13275. else {
  13276. this.selectionObj.edges[obj.id] = obj;
  13277. }
  13278. },
  13279. /**
  13280. * Remove a single option from selection.
  13281. *
  13282. * @param {Object} obj
  13283. * @private
  13284. */
  13285. _removeFromSelection : function(obj) {
  13286. if (obj instanceof Node) {
  13287. delete this.selectionObj.nodes[obj.id];
  13288. }
  13289. else {
  13290. delete this.selectionObj.edges[obj.id];
  13291. }
  13292. },
  13293. /**
  13294. * Unselect all. The selectionObj is useful for this.
  13295. *
  13296. * @param {Boolean} [doNotTrigger] | ignore trigger
  13297. * @private
  13298. */
  13299. _unselectAll : function(doNotTrigger) {
  13300. if (doNotTrigger === undefined) {
  13301. doNotTrigger = false;
  13302. }
  13303. for(var nodeId in this.selectionObj.nodes) {
  13304. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13305. this.selectionObj.nodes[nodeId].unselect();
  13306. }
  13307. }
  13308. for(var edgeId in this.selectionObj.edges) {
  13309. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13310. this.selectionObj.edges[edgeId].unselect();;
  13311. }
  13312. }
  13313. this.selectionObj = {nodes:{},edges:{}};
  13314. if (doNotTrigger == false) {
  13315. this.emit('select', this.getSelection());
  13316. }
  13317. },
  13318. /**
  13319. * Unselect all clusters. The selectionObj is useful for this.
  13320. *
  13321. * @param {Boolean} [doNotTrigger] | ignore trigger
  13322. * @private
  13323. */
  13324. _unselectClusters : function(doNotTrigger) {
  13325. if (doNotTrigger === undefined) {
  13326. doNotTrigger = false;
  13327. }
  13328. for (var nodeId in this.selectionObj.nodes) {
  13329. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13330. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13331. this.selectionObj.nodes[nodeId].unselect();
  13332. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  13333. }
  13334. }
  13335. }
  13336. if (doNotTrigger == false) {
  13337. this.emit('select', this.getSelection());
  13338. }
  13339. },
  13340. /**
  13341. * return the number of selected nodes
  13342. *
  13343. * @returns {number}
  13344. * @private
  13345. */
  13346. _getSelectedNodeCount : function() {
  13347. var count = 0;
  13348. for (var nodeId in this.selectionObj.nodes) {
  13349. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13350. count += 1;
  13351. }
  13352. }
  13353. return count;
  13354. },
  13355. /**
  13356. * return the number of selected nodes
  13357. *
  13358. * @returns {number}
  13359. * @private
  13360. */
  13361. _getSelectedNode : function() {
  13362. for (var nodeId in this.selectionObj.nodes) {
  13363. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13364. return this.selectionObj.nodes[nodeId];
  13365. }
  13366. }
  13367. return null;
  13368. },
  13369. /**
  13370. * return the number of selected edges
  13371. *
  13372. * @returns {number}
  13373. * @private
  13374. */
  13375. _getSelectedEdgeCount : function() {
  13376. var count = 0;
  13377. for (var edgeId in this.selectionObj.edges) {
  13378. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13379. count += 1;
  13380. }
  13381. }
  13382. return count;
  13383. },
  13384. /**
  13385. * return the number of selected objects.
  13386. *
  13387. * @returns {number}
  13388. * @private
  13389. */
  13390. _getSelectedObjectCount : function() {
  13391. var count = 0;
  13392. for(var nodeId in this.selectionObj.nodes) {
  13393. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13394. count += 1;
  13395. }
  13396. }
  13397. for(var edgeId in this.selectionObj.edges) {
  13398. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13399. count += 1;
  13400. }
  13401. }
  13402. return count;
  13403. },
  13404. /**
  13405. * Check if anything is selected
  13406. *
  13407. * @returns {boolean}
  13408. * @private
  13409. */
  13410. _selectionIsEmpty : function() {
  13411. for(var nodeId in this.selectionObj.nodes) {
  13412. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13413. return false;
  13414. }
  13415. }
  13416. for(var edgeId in this.selectionObj.edges) {
  13417. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13418. return false;
  13419. }
  13420. }
  13421. return true;
  13422. },
  13423. /**
  13424. * check if one of the selected nodes is a cluster.
  13425. *
  13426. * @returns {boolean}
  13427. * @private
  13428. */
  13429. _clusterInSelection : function() {
  13430. for(var nodeId in this.selectionObj.nodes) {
  13431. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13432. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13433. return true;
  13434. }
  13435. }
  13436. }
  13437. return false;
  13438. },
  13439. /**
  13440. * select the edges connected to the node that is being selected
  13441. *
  13442. * @param {Node} node
  13443. * @private
  13444. */
  13445. _selectConnectedEdges : function(node) {
  13446. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13447. var edge = node.dynamicEdges[i];
  13448. edge.select();
  13449. this._addToSelection(edge);
  13450. }
  13451. },
  13452. /**
  13453. * unselect the edges connected to the node that is being selected
  13454. *
  13455. * @param {Node} node
  13456. * @private
  13457. */
  13458. _unselectConnectedEdges : function(node) {
  13459. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13460. var edge = node.dynamicEdges[i];
  13461. edge.unselect();
  13462. this._removeFromSelection(edge);
  13463. }
  13464. },
  13465. /**
  13466. * This is called when someone clicks on a node. either select or deselect it.
  13467. * If there is an existing selection and we don't want to append to it, clear the existing selection
  13468. *
  13469. * @param {Node || Edge} object
  13470. * @param {Boolean} append
  13471. * @param {Boolean} [doNotTrigger] | ignore trigger
  13472. * @private
  13473. */
  13474. _selectObject : function(object, append, doNotTrigger) {
  13475. if (doNotTrigger === undefined) {
  13476. doNotTrigger = false;
  13477. }
  13478. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  13479. this._unselectAll(true);
  13480. }
  13481. if (object.selected == false) {
  13482. object.select();
  13483. this._addToSelection(object);
  13484. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  13485. this._selectConnectedEdges(object);
  13486. }
  13487. }
  13488. else {
  13489. object.unselect();
  13490. this._removeFromSelection(object);
  13491. }
  13492. if (doNotTrigger == false) {
  13493. this.emit('select', this.getSelection());
  13494. }
  13495. },
  13496. /**
  13497. * handles the selection part of the touch, only for navigation controls elements;
  13498. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13499. * This is the most responsive solution
  13500. *
  13501. * @param {Object} pointer
  13502. * @private
  13503. */
  13504. _handleTouch : function(pointer) {
  13505. },
  13506. /**
  13507. * handles the selection part of the tap;
  13508. *
  13509. * @param {Object} pointer
  13510. * @private
  13511. */
  13512. _handleTap : function(pointer) {
  13513. var node = this._getNodeAt(pointer);
  13514. if (node != null) {
  13515. this._selectObject(node,false);
  13516. }
  13517. else {
  13518. var edge = this._getEdgeAt(pointer);
  13519. if (edge != null) {
  13520. this._selectObject(edge,false);
  13521. }
  13522. else {
  13523. this._unselectAll();
  13524. }
  13525. }
  13526. this.emit("click", this.getSelection());
  13527. this._redraw();
  13528. },
  13529. /**
  13530. * handles the selection part of the double tap and opens a cluster if needed
  13531. *
  13532. * @param {Object} pointer
  13533. * @private
  13534. */
  13535. _handleDoubleTap : function(pointer) {
  13536. var node = this._getNodeAt(pointer);
  13537. if (node != null && node !== undefined) {
  13538. // we reset the areaCenter here so the opening of the node will occur
  13539. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  13540. "y" : this._canvasToY(pointer.y)};
  13541. this.openCluster(node);
  13542. }
  13543. this.emit("doubleClick", this.getSelection());
  13544. },
  13545. /**
  13546. * Handle the onHold selection part
  13547. *
  13548. * @param pointer
  13549. * @private
  13550. */
  13551. _handleOnHold : function(pointer) {
  13552. var node = this._getNodeAt(pointer);
  13553. if (node != null) {
  13554. this._selectObject(node,true);
  13555. }
  13556. else {
  13557. var edge = this._getEdgeAt(pointer);
  13558. if (edge != null) {
  13559. this._selectObject(edge,true);
  13560. }
  13561. }
  13562. this._redraw();
  13563. },
  13564. /**
  13565. * handle the onRelease event. These functions are here for the navigation controls module.
  13566. *
  13567. * @private
  13568. */
  13569. _handleOnRelease : function(pointer) {
  13570. },
  13571. /**
  13572. *
  13573. * retrieve the currently selected objects
  13574. * @return {Number[] | String[]} selection An array with the ids of the
  13575. * selected nodes.
  13576. */
  13577. getSelection : function() {
  13578. var nodeIds = this.getSelectedNodes();
  13579. var edgeIds = this.getSelectedEdges();
  13580. return {nodes:nodeIds, edges:edgeIds};
  13581. },
  13582. /**
  13583. *
  13584. * retrieve the currently selected nodes
  13585. * @return {String} selection An array with the ids of the
  13586. * selected nodes.
  13587. */
  13588. getSelectedNodes : function() {
  13589. var idArray = [];
  13590. for(var nodeId in this.selectionObj.nodes) {
  13591. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13592. idArray.push(nodeId);
  13593. }
  13594. }
  13595. return idArray
  13596. },
  13597. /**
  13598. *
  13599. * retrieve the currently selected edges
  13600. * @return {Array} selection An array with the ids of the
  13601. * selected nodes.
  13602. */
  13603. getSelectedEdges : function() {
  13604. var idArray = [];
  13605. for(var edgeId in this.selectionObj.edges) {
  13606. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13607. idArray.push(edgeId);
  13608. }
  13609. }
  13610. return idArray;
  13611. },
  13612. /**
  13613. * select zero or more nodes
  13614. * @param {Number[] | String[]} selection An array with the ids of the
  13615. * selected nodes.
  13616. */
  13617. setSelection : function(selection) {
  13618. var i, iMax, id;
  13619. if (!selection || (selection.length == undefined))
  13620. throw 'Selection must be an array with ids';
  13621. // first unselect any selected node
  13622. this._unselectAll(true);
  13623. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13624. id = selection[i];
  13625. var node = this.nodes[id];
  13626. if (!node) {
  13627. throw new RangeError('Node with id "' + id + '" not found');
  13628. }
  13629. this._selectObject(node,true,true);
  13630. }
  13631. this.redraw();
  13632. },
  13633. /**
  13634. * Validate the selection: remove ids of nodes which no longer exist
  13635. * @private
  13636. */
  13637. _updateSelection : function () {
  13638. for(var nodeId in this.selectionObj.nodes) {
  13639. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13640. if (!this.nodes.hasOwnProperty(nodeId)) {
  13641. delete this.selectionObj.nodes[nodeId];
  13642. }
  13643. }
  13644. }
  13645. for(var edgeId in this.selectionObj.edges) {
  13646. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13647. if (!this.edges.hasOwnProperty(edgeId)) {
  13648. delete this.selectionObj.edges[edgeId];
  13649. }
  13650. }
  13651. }
  13652. }
  13653. };
  13654. /**
  13655. * Created by Alex on 1/22/14.
  13656. */
  13657. var NavigationMixin = {
  13658. _cleanNavigation : function() {
  13659. // clean up previosu navigation items
  13660. var wrapper = document.getElementById('graph-navigation_wrapper');
  13661. if (wrapper != null) {
  13662. this.containerElement.removeChild(wrapper);
  13663. }
  13664. document.onmouseup = null;
  13665. },
  13666. /**
  13667. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13668. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13669. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13670. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13671. *
  13672. * @private
  13673. */
  13674. _loadNavigationElements : function() {
  13675. this._cleanNavigation();
  13676. this.navigationDivs = {};
  13677. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13678. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  13679. this.navigationDivs['wrapper'] = document.createElement('div');
  13680. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13681. this.navigationDivs['wrapper'].style.position = "absolute";
  13682. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  13683. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  13684. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13685. for (var i = 0; i < navigationDivs.length; i++) {
  13686. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13687. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13688. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13689. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13690. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13691. }
  13692. document.onmouseup = this._stopMovement.bind(this);
  13693. },
  13694. /**
  13695. * this stops all movement induced by the navigation buttons
  13696. *
  13697. * @private
  13698. */
  13699. _stopMovement : function() {
  13700. this._xStopMoving();
  13701. this._yStopMoving();
  13702. this._stopZoom();
  13703. },
  13704. /**
  13705. * stops the actions performed by page up and down etc.
  13706. *
  13707. * @param event
  13708. * @private
  13709. */
  13710. _preventDefault : function(event) {
  13711. if (event !== undefined) {
  13712. if (event.preventDefault) {
  13713. event.preventDefault();
  13714. } else {
  13715. event.returnValue = false;
  13716. }
  13717. }
  13718. },
  13719. /**
  13720. * move the screen up
  13721. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13722. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13723. * To avoid this behaviour, we do the translation in the start loop.
  13724. *
  13725. * @private
  13726. */
  13727. _moveUp : function(event) {
  13728. this.yIncrement = this.constants.keyboard.speed.y;
  13729. this.start(); // if there is no node movement, the calculation wont be done
  13730. this._preventDefault(event);
  13731. if (this.navigationDivs) {
  13732. this.navigationDivs['up'].className += " active";
  13733. }
  13734. },
  13735. /**
  13736. * move the screen down
  13737. * @private
  13738. */
  13739. _moveDown : function(event) {
  13740. this.yIncrement = -this.constants.keyboard.speed.y;
  13741. this.start(); // if there is no node movement, the calculation wont be done
  13742. this._preventDefault(event);
  13743. if (this.navigationDivs) {
  13744. this.navigationDivs['down'].className += " active";
  13745. }
  13746. },
  13747. /**
  13748. * move the screen left
  13749. * @private
  13750. */
  13751. _moveLeft : function(event) {
  13752. this.xIncrement = this.constants.keyboard.speed.x;
  13753. this.start(); // if there is no node movement, the calculation wont be done
  13754. this._preventDefault(event);
  13755. if (this.navigationDivs) {
  13756. this.navigationDivs['left'].className += " active";
  13757. }
  13758. },
  13759. /**
  13760. * move the screen right
  13761. * @private
  13762. */
  13763. _moveRight : function(event) {
  13764. this.xIncrement = -this.constants.keyboard.speed.y;
  13765. this.start(); // if there is no node movement, the calculation wont be done
  13766. this._preventDefault(event);
  13767. if (this.navigationDivs) {
  13768. this.navigationDivs['right'].className += " active";
  13769. }
  13770. },
  13771. /**
  13772. * Zoom in, using the same method as the movement.
  13773. * @private
  13774. */
  13775. _zoomIn : function(event) {
  13776. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13777. this.start(); // if there is no node movement, the calculation wont be done
  13778. this._preventDefault(event);
  13779. if (this.navigationDivs) {
  13780. this.navigationDivs['zoomIn'].className += " active";
  13781. }
  13782. },
  13783. /**
  13784. * Zoom out
  13785. * @private
  13786. */
  13787. _zoomOut : function() {
  13788. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13789. this.start(); // if there is no node movement, the calculation wont be done
  13790. this._preventDefault(event);
  13791. if (this.navigationDivs) {
  13792. this.navigationDivs['zoomOut'].className += " active";
  13793. }
  13794. },
  13795. /**
  13796. * Stop zooming and unhighlight the zoom controls
  13797. * @private
  13798. */
  13799. _stopZoom : function() {
  13800. this.zoomIncrement = 0;
  13801. if (this.navigationDivs) {
  13802. this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active","");
  13803. this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active","");
  13804. }
  13805. },
  13806. /**
  13807. * Stop moving in the Y direction and unHighlight the up and down
  13808. * @private
  13809. */
  13810. _yStopMoving : function() {
  13811. this.yIncrement = 0;
  13812. if (this.navigationDivs) {
  13813. this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active","");
  13814. this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active","");
  13815. }
  13816. },
  13817. /**
  13818. * Stop moving in the X direction and unHighlight left and right.
  13819. * @private
  13820. */
  13821. _xStopMoving : function() {
  13822. this.xIncrement = 0;
  13823. if (this.navigationDivs) {
  13824. this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active","");
  13825. this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active","");
  13826. }
  13827. }
  13828. };
  13829. /**
  13830. * Created by Alex on 2/10/14.
  13831. */
  13832. var graphMixinLoaders = {
  13833. /**
  13834. * Load a mixin into the graph object
  13835. *
  13836. * @param {Object} sourceVariable | this object has to contain functions.
  13837. * @private
  13838. */
  13839. _loadMixin : function(sourceVariable) {
  13840. for (var mixinFunction in sourceVariable) {
  13841. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13842. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13843. }
  13844. }
  13845. },
  13846. /**
  13847. * removes a mixin from the graph object.
  13848. *
  13849. * @param {Object} sourceVariable | this object has to contain functions.
  13850. * @private
  13851. */
  13852. _clearMixin : function(sourceVariable) {
  13853. for (var mixinFunction in sourceVariable) {
  13854. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13855. Graph.prototype[mixinFunction] = undefined;
  13856. }
  13857. }
  13858. },
  13859. /**
  13860. * Mixin the physics system and initialize the parameters required.
  13861. *
  13862. * @private
  13863. */
  13864. _loadPhysicsSystem : function() {
  13865. this._loadMixin(physicsMixin);
  13866. this._loadSelectedForceSolver();
  13867. if (this.constants.configurePhysics == true) {
  13868. this._loadPhysicsConfiguration();
  13869. }
  13870. },
  13871. /**
  13872. * Mixin the cluster system and initialize the parameters required.
  13873. *
  13874. * @private
  13875. */
  13876. _loadClusterSystem : function() {
  13877. this.clusterSession = 0;
  13878. this.hubThreshold = 5;
  13879. this._loadMixin(ClusterMixin);
  13880. },
  13881. /**
  13882. * Mixin the sector system and initialize the parameters required
  13883. *
  13884. * @private
  13885. */
  13886. _loadSectorSystem : function() {
  13887. this.sectors = { },
  13888. this.activeSector = ["default"];
  13889. this.sectors["active"] = { },
  13890. this.sectors["active"]["default"] = {"nodes":{},
  13891. "edges":{},
  13892. "nodeIndices":[],
  13893. "formationScale": 1.0,
  13894. "drawingNode": undefined };
  13895. this.sectors["frozen"] = {},
  13896. this.sectors["support"] = {"nodes":{},
  13897. "edges":{},
  13898. "nodeIndices":[],
  13899. "formationScale": 1.0,
  13900. "drawingNode": undefined };
  13901. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13902. this._loadMixin(SectorMixin);
  13903. },
  13904. /**
  13905. * Mixin the selection system and initialize the parameters required
  13906. *
  13907. * @private
  13908. */
  13909. _loadSelectionSystem : function() {
  13910. this.selectionObj = {nodes:{},edges:{}};
  13911. this._loadMixin(SelectionMixin);
  13912. },
  13913. /**
  13914. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13915. *
  13916. * @private
  13917. */
  13918. _loadManipulationSystem : function() {
  13919. // reset global variables -- these are used by the selection of nodes and edges.
  13920. this.blockConnectingEdgeSelection = false;
  13921. this.forceAppendSelection = false
  13922. if (this.constants.dataManipulation.enabled == true) {
  13923. // load the manipulator HTML elements. All styling done in css.
  13924. if (this.manipulationDiv === undefined) {
  13925. this.manipulationDiv = document.createElement('div');
  13926. this.manipulationDiv.className = 'graph-manipulationDiv';
  13927. this.manipulationDiv.id = 'graph-manipulationDiv';
  13928. if (this.editMode == true) {
  13929. this.manipulationDiv.style.display = "block";
  13930. }
  13931. else {
  13932. this.manipulationDiv.style.display = "none";
  13933. }
  13934. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13935. }
  13936. if (this.editModeDiv === undefined) {
  13937. this.editModeDiv = document.createElement('div');
  13938. this.editModeDiv.className = 'graph-manipulation-editMode';
  13939. this.editModeDiv.id = 'graph-manipulation-editMode';
  13940. if (this.editMode == true) {
  13941. this.editModeDiv.style.display = "none";
  13942. }
  13943. else {
  13944. this.editModeDiv.style.display = "block";
  13945. }
  13946. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13947. }
  13948. if (this.closeDiv === undefined) {
  13949. this.closeDiv = document.createElement('div');
  13950. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13951. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13952. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13953. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13954. }
  13955. // load the manipulation functions
  13956. this._loadMixin(manipulationMixin);
  13957. // create the manipulator toolbar
  13958. this._createManipulatorBar();
  13959. }
  13960. else {
  13961. if (this.manipulationDiv !== undefined) {
  13962. // removes all the bindings and overloads
  13963. this._createManipulatorBar();
  13964. // remove the manipulation divs
  13965. this.containerElement.removeChild(this.manipulationDiv);
  13966. this.containerElement.removeChild(this.editModeDiv);
  13967. this.containerElement.removeChild(this.closeDiv);
  13968. this.manipulationDiv = undefined;
  13969. this.editModeDiv = undefined;
  13970. this.closeDiv = undefined;
  13971. // remove the mixin functions
  13972. this._clearMixin(manipulationMixin);
  13973. }
  13974. }
  13975. },
  13976. /**
  13977. * Mixin the navigation (User Interface) system and initialize the parameters required
  13978. *
  13979. * @private
  13980. */
  13981. _loadNavigationControls : function() {
  13982. this._loadMixin(NavigationMixin);
  13983. // the clean function removes the button divs, this is done to remove the bindings.
  13984. this._cleanNavigation();
  13985. if (this.constants.navigation.enabled == true) {
  13986. this._loadNavigationElements();
  13987. }
  13988. },
  13989. /**
  13990. * Mixin the hierarchical layout system.
  13991. *
  13992. * @private
  13993. */
  13994. _loadHierarchySystem : function() {
  13995. this._loadMixin(HierarchicalLayoutMixin);
  13996. }
  13997. }
  13998. /**
  13999. * @constructor Graph
  14000. * Create a graph visualization, displaying nodes and edges.
  14001. *
  14002. * @param {Element} container The DOM element in which the Graph will
  14003. * be created. Normally a div element.
  14004. * @param {Object} data An object containing parameters
  14005. * {Array} nodes
  14006. * {Array} edges
  14007. * @param {Object} options Options
  14008. */
  14009. function Graph (container, data, options) {
  14010. this._initializeMixinLoaders();
  14011. // create variables and set default values
  14012. this.containerElement = container;
  14013. this.width = '100%';
  14014. this.height = '100%';
  14015. // render and calculation settings
  14016. this.renderRefreshRate = 60; // hz (fps)
  14017. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  14018. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  14019. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  14020. this.physicsDiscreteStepsize = 0.65; // discrete stepsize of the simulation
  14021. this.stabilize = true; // stabilize before displaying the graph
  14022. this.selectable = true;
  14023. this.initializing = true;
  14024. // these functions are triggered when the dataset is edited
  14025. this.triggerFunctions = {add:null,edit:null,connect:null,delete:null};
  14026. // set constant values
  14027. this.constants = {
  14028. nodes: {
  14029. radiusMin: 5,
  14030. radiusMax: 20,
  14031. radius: 5,
  14032. shape: 'ellipse',
  14033. image: undefined,
  14034. widthMin: 16, // px
  14035. widthMax: 64, // px
  14036. fixed: false,
  14037. fontColor: 'black',
  14038. fontSize: 14, // px
  14039. fontFace: 'verdana',
  14040. level: -1,
  14041. color: {
  14042. border: '#2B7CE9',
  14043. background: '#97C2FC',
  14044. highlight: {
  14045. border: '#2B7CE9',
  14046. background: '#D2E5FF'
  14047. }
  14048. },
  14049. borderColor: '#2B7CE9',
  14050. backgroundColor: '#97C2FC',
  14051. highlightColor: '#D2E5FF',
  14052. group: undefined
  14053. },
  14054. edges: {
  14055. widthMin: 1,
  14056. widthMax: 15,
  14057. width: 1,
  14058. style: 'line',
  14059. color: {
  14060. color:'#848484',
  14061. highlight:'#848484'
  14062. },
  14063. fontColor: '#343434',
  14064. fontSize: 14, // px
  14065. fontFace: 'arial',
  14066. dash: {
  14067. length: 10,
  14068. gap: 5,
  14069. altLength: undefined
  14070. }
  14071. },
  14072. configurePhysics:false,
  14073. physics: {
  14074. barnesHut: {
  14075. enabled: true,
  14076. theta: 1 / 0.6, // inverted to save time during calculation
  14077. gravitationalConstant: -2000,
  14078. centralGravity: 0.3,
  14079. springLength: 95,
  14080. springConstant: 0.04,
  14081. damping: 0.09
  14082. },
  14083. repulsion: {
  14084. centralGravity: 0.1,
  14085. springLength: 200,
  14086. springConstant: 0.05,
  14087. nodeDistance: 100,
  14088. damping: 0.09
  14089. },
  14090. hierarchicalRepulsion: {
  14091. enabled: false,
  14092. centralGravity: 0.0,
  14093. springLength: 100,
  14094. springConstant: 0.01,
  14095. nodeDistance: 60,
  14096. damping: 0.09
  14097. },
  14098. damping: null,
  14099. centralGravity: null,
  14100. springLength: null,
  14101. springConstant: null
  14102. },
  14103. clustering: { // Per Node in Cluster = PNiC
  14104. enabled: false, // (Boolean) | global on/off switch for clustering.
  14105. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  14106. 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
  14107. 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
  14108. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  14109. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  14110. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  14111. 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.
  14112. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  14113. maxFontSize: 1000,
  14114. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  14115. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  14116. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  14117. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  14118. height: 1, // (px PNiC) | growth of the height per node in cluster.
  14119. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  14120. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  14121. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  14122. clusterLevelDifference: 2
  14123. },
  14124. navigation: {
  14125. enabled: false
  14126. },
  14127. keyboard: {
  14128. enabled: false,
  14129. speed: {x: 10, y: 10, zoom: 0.02}
  14130. },
  14131. dataManipulation: {
  14132. enabled: false,
  14133. initiallyVisible: false
  14134. },
  14135. hierarchicalLayout: {
  14136. enabled:false,
  14137. levelSeparation: 150,
  14138. nodeSpacing: 100,
  14139. direction: "UD" // UD, DU, LR, RL
  14140. },
  14141. freezeForStabilization: false,
  14142. smoothCurves: true,
  14143. maxVelocity: 10,
  14144. minVelocity: 0.1, // px/s
  14145. stabilizationIterations: 1000 // maximum number of iteration to stabilize
  14146. };
  14147. this.editMode = this.constants.dataManipulation.initiallyVisible;
  14148. // Node variables
  14149. var graph = this;
  14150. this.groups = new Groups(); // object with groups
  14151. this.images = new Images(); // object with images
  14152. this.images.setOnloadCallback(function () {
  14153. graph._redraw();
  14154. });
  14155. // keyboard navigation variables
  14156. this.xIncrement = 0;
  14157. this.yIncrement = 0;
  14158. this.zoomIncrement = 0;
  14159. // loading all the mixins:
  14160. // load the force calculation functions, grouped under the physics system.
  14161. this._loadPhysicsSystem();
  14162. // create a frame and canvas
  14163. this._create();
  14164. // load the sector system. (mandatory, fully integrated with Graph)
  14165. this._loadSectorSystem();
  14166. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  14167. this._loadClusterSystem();
  14168. // load the selection system. (mandatory, required by Graph)
  14169. this._loadSelectionSystem();
  14170. // load the selection system. (mandatory, required by Graph)
  14171. this._loadHierarchySystem();
  14172. // apply options
  14173. this.setOptions(options);
  14174. // other vars
  14175. this.freezeSimulation = false;// freeze the simulation
  14176. this.cachedFunctions = {};
  14177. // containers for nodes and edges
  14178. this.calculationNodes = {};
  14179. this.calculationNodeIndices = [];
  14180. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  14181. this.nodes = {}; // object with Node objects
  14182. this.edges = {}; // object with Edge objects
  14183. // position and scale variables and objects
  14184. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  14185. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  14186. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  14187. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  14188. this.scale = 1; // defining the global scale variable in the constructor
  14189. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  14190. // datasets or dataviews
  14191. this.nodesData = null; // A DataSet or DataView
  14192. this.edgesData = null; // A DataSet or DataView
  14193. // create event listeners used to subscribe on the DataSets of the nodes and edges
  14194. this.nodesListeners = {
  14195. 'add': function (event, params) {
  14196. graph._addNodes(params.items);
  14197. graph.start();
  14198. },
  14199. 'update': function (event, params) {
  14200. graph._updateNodes(params.items);
  14201. graph.start();
  14202. },
  14203. 'remove': function (event, params) {
  14204. graph._removeNodes(params.items);
  14205. graph.start();
  14206. }
  14207. };
  14208. this.edgesListeners = {
  14209. 'add': function (event, params) {
  14210. graph._addEdges(params.items);
  14211. graph.start();
  14212. },
  14213. 'update': function (event, params) {
  14214. graph._updateEdges(params.items);
  14215. graph.start();
  14216. },
  14217. 'remove': function (event, params) {
  14218. graph._removeEdges(params.items);
  14219. graph.start();
  14220. }
  14221. };
  14222. // properties for the animation
  14223. this.moving = true;
  14224. this.timer = undefined; // Scheduling function. Is definded in this.start();
  14225. // load data (the disable start variable will be the same as the enabled clustering)
  14226. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  14227. // hierarchical layout
  14228. this.initializing = false;
  14229. if (this.constants.hierarchicalLayout.enabled == true) {
  14230. this._setupHierarchicalLayout();
  14231. }
  14232. else {
  14233. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  14234. if (this.stabilize == false) {
  14235. this.zoomExtent(true,this.constants.clustering.enabled);
  14236. }
  14237. }
  14238. // if clustering is disabled, the simulation will have started in the setData function
  14239. if (this.constants.clustering.enabled) {
  14240. this.startWithClustering();
  14241. }
  14242. }
  14243. // Extend Graph with an Emitter mixin
  14244. Emitter(Graph.prototype);
  14245. /**
  14246. * Get the script path where the vis.js library is located
  14247. *
  14248. * @returns {string | null} path Path or null when not found. Path does not
  14249. * end with a slash.
  14250. * @private
  14251. */
  14252. Graph.prototype._getScriptPath = function() {
  14253. var scripts = document.getElementsByTagName( 'script' );
  14254. // find script named vis.js or vis.min.js
  14255. for (var i = 0; i < scripts.length; i++) {
  14256. var src = scripts[i].src;
  14257. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  14258. if (match) {
  14259. // return path without the script name
  14260. return src.substring(0, src.length - match[0].length);
  14261. }
  14262. }
  14263. return null;
  14264. };
  14265. /**
  14266. * Find the center position of the graph
  14267. * @private
  14268. */
  14269. Graph.prototype._getRange = function() {
  14270. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  14271. for (var nodeId in this.nodes) {
  14272. if (this.nodes.hasOwnProperty(nodeId)) {
  14273. node = this.nodes[nodeId];
  14274. if (minX > (node.x)) {minX = node.x;}
  14275. if (maxX < (node.x)) {maxX = node.x;}
  14276. if (minY > (node.y)) {minY = node.y;}
  14277. if (maxY < (node.y)) {maxY = node.y;}
  14278. }
  14279. }
  14280. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  14281. minY = 0, maxY = 0, minX = 0, maxX = 0;
  14282. }
  14283. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14284. };
  14285. /**
  14286. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14287. * @returns {{x: number, y: number}}
  14288. * @private
  14289. */
  14290. Graph.prototype._findCenter = function(range) {
  14291. return {x: (0.5 * (range.maxX + range.minX)),
  14292. y: (0.5 * (range.maxY + range.minY))};
  14293. };
  14294. /**
  14295. * center the graph
  14296. *
  14297. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14298. */
  14299. Graph.prototype._centerGraph = function(range) {
  14300. var center = this._findCenter(range);
  14301. center.x *= this.scale;
  14302. center.y *= this.scale;
  14303. center.x -= 0.5 * this.frame.canvas.clientWidth;
  14304. center.y -= 0.5 * this.frame.canvas.clientHeight;
  14305. this._setTranslation(-center.x,-center.y); // set at 0,0
  14306. };
  14307. /**
  14308. * This function zooms out to fit all data on screen based on amount of nodes
  14309. *
  14310. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  14311. */
  14312. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  14313. if (initialZoom === undefined) {
  14314. initialZoom = false;
  14315. }
  14316. if (disableStart === undefined) {
  14317. disableStart = false;
  14318. }
  14319. var range = this._getRange();
  14320. var zoomLevel;
  14321. if (initialZoom == true) {
  14322. var numberOfNodes = this.nodeIndices.length;
  14323. if (this.constants.smoothCurves == true) {
  14324. if (this.constants.clustering.enabled == true &&
  14325. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14326. 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.
  14327. }
  14328. else {
  14329. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14330. }
  14331. }
  14332. else {
  14333. if (this.constants.clustering.enabled == true &&
  14334. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14335. 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.
  14336. }
  14337. else {
  14338. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14339. }
  14340. }
  14341. // correct for larger canvasses.
  14342. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  14343. zoomLevel *= factor;
  14344. }
  14345. else {
  14346. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  14347. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  14348. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  14349. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  14350. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  14351. }
  14352. if (zoomLevel > 1.0) {
  14353. zoomLevel = 1.0;
  14354. }
  14355. this._setScale(zoomLevel);
  14356. this._centerGraph(range);
  14357. if (disableStart == false) {
  14358. this.moving = true;
  14359. this.start();
  14360. }
  14361. };
  14362. /**
  14363. * Update the this.nodeIndices with the most recent node index list
  14364. * @private
  14365. */
  14366. Graph.prototype._updateNodeIndexList = function() {
  14367. this._clearNodeIndexList();
  14368. for (var idx in this.nodes) {
  14369. if (this.nodes.hasOwnProperty(idx)) {
  14370. this.nodeIndices.push(idx);
  14371. }
  14372. }
  14373. };
  14374. /**
  14375. * Set nodes and edges, and optionally options as well.
  14376. *
  14377. * @param {Object} data Object containing parameters:
  14378. * {Array | DataSet | DataView} [nodes] Array with nodes
  14379. * {Array | DataSet | DataView} [edges] Array with edges
  14380. * {String} [dot] String containing data in DOT format
  14381. * {Options} [options] Object with options
  14382. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  14383. */
  14384. Graph.prototype.setData = function(data, disableStart) {
  14385. if (disableStart === undefined) {
  14386. disableStart = false;
  14387. }
  14388. if (data && data.dot && (data.nodes || data.edges)) {
  14389. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  14390. ' parameter pair "nodes" and "edges", but not both.');
  14391. }
  14392. // set options
  14393. this.setOptions(data && data.options);
  14394. // set all data
  14395. if (data && data.dot) {
  14396. // parse DOT file
  14397. if(data && data.dot) {
  14398. var dotData = vis.util.DOTToGraph(data.dot);
  14399. this.setData(dotData);
  14400. return;
  14401. }
  14402. }
  14403. else {
  14404. this._setNodes(data && data.nodes);
  14405. this._setEdges(data && data.edges);
  14406. }
  14407. this._putDataInSector();
  14408. if (!disableStart) {
  14409. // find a stable position or start animating to a stable position
  14410. if (this.stabilize) {
  14411. this._stabilize();
  14412. }
  14413. this.start();
  14414. }
  14415. };
  14416. /**
  14417. * Set options
  14418. * @param {Object} options
  14419. */
  14420. Graph.prototype.setOptions = function (options) {
  14421. if (options) {
  14422. var prop;
  14423. // retrieve parameter values
  14424. if (options.width !== undefined) {this.width = options.width;}
  14425. if (options.height !== undefined) {this.height = options.height;}
  14426. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14427. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14428. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14429. if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;}
  14430. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14431. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  14432. if (options.onAdd) {
  14433. this.triggerFunctions.add = options.onAdd;
  14434. }
  14435. if (options.onEdit) {
  14436. this.triggerFunctions.edit = options.onEdit;
  14437. }
  14438. if (options.onConnect) {
  14439. this.triggerFunctions.connect = options.onConnect;
  14440. }
  14441. if (options.onDelete) {
  14442. this.triggerFunctions.delete = options.onDelete;
  14443. }
  14444. if (options.physics) {
  14445. if (options.physics.barnesHut) {
  14446. this.constants.physics.barnesHut.enabled = true;
  14447. for (prop in options.physics.barnesHut) {
  14448. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14449. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14450. }
  14451. }
  14452. }
  14453. if (options.physics.repulsion) {
  14454. this.constants.physics.barnesHut.enabled = false;
  14455. for (prop in options.physics.repulsion) {
  14456. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14457. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14458. }
  14459. }
  14460. }
  14461. }
  14462. if (options.hierarchicalLayout) {
  14463. this.constants.hierarchicalLayout.enabled = true;
  14464. for (prop in options.hierarchicalLayout) {
  14465. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14466. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14467. }
  14468. }
  14469. }
  14470. else if (options.hierarchicalLayout !== undefined) {
  14471. this.constants.hierarchicalLayout.enabled = false;
  14472. }
  14473. if (options.clustering) {
  14474. this.constants.clustering.enabled = true;
  14475. for (prop in options.clustering) {
  14476. if (options.clustering.hasOwnProperty(prop)) {
  14477. this.constants.clustering[prop] = options.clustering[prop];
  14478. }
  14479. }
  14480. }
  14481. else if (options.clustering !== undefined) {
  14482. this.constants.clustering.enabled = false;
  14483. }
  14484. if (options.navigation) {
  14485. this.constants.navigation.enabled = true;
  14486. for (prop in options.navigation) {
  14487. if (options.navigation.hasOwnProperty(prop)) {
  14488. this.constants.navigation[prop] = options.navigation[prop];
  14489. }
  14490. }
  14491. }
  14492. else if (options.navigation !== undefined) {
  14493. this.constants.navigation.enabled = false;
  14494. }
  14495. if (options.keyboard) {
  14496. this.constants.keyboard.enabled = true;
  14497. for (prop in options.keyboard) {
  14498. if (options.keyboard.hasOwnProperty(prop)) {
  14499. this.constants.keyboard[prop] = options.keyboard[prop];
  14500. }
  14501. }
  14502. }
  14503. else if (options.keyboard !== undefined) {
  14504. this.constants.keyboard.enabled = false;
  14505. }
  14506. if (options.dataManipulation) {
  14507. this.constants.dataManipulation.enabled = true;
  14508. for (prop in options.dataManipulation) {
  14509. if (options.dataManipulation.hasOwnProperty(prop)) {
  14510. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14511. }
  14512. }
  14513. }
  14514. else if (options.dataManipulation !== undefined) {
  14515. this.constants.dataManipulation.enabled = false;
  14516. }
  14517. // TODO: work out these options and document them
  14518. if (options.edges) {
  14519. for (prop in options.edges) {
  14520. if (options.edges.hasOwnProperty(prop)) {
  14521. if (typeof options.edges[prop] != "object") {
  14522. this.constants.edges[prop] = options.edges[prop];
  14523. }
  14524. }
  14525. }
  14526. if (options.edges.color !== undefined) {
  14527. if (util.isString(options.edges.color)) {
  14528. this.constants.edges.color.color = options.edges.color;
  14529. this.constants.edges.color.highlight = options.edges.color;
  14530. }
  14531. else {
  14532. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  14533. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  14534. }
  14535. }
  14536. if (!options.edges.fontColor) {
  14537. if (options.edges.color !== undefined) {
  14538. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  14539. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  14540. }
  14541. }
  14542. // Added to support dashed lines
  14543. // David Jordan
  14544. // 2012-08-08
  14545. if (options.edges.dash) {
  14546. if (options.edges.dash.length !== undefined) {
  14547. this.constants.edges.dash.length = options.edges.dash.length;
  14548. }
  14549. if (options.edges.dash.gap !== undefined) {
  14550. this.constants.edges.dash.gap = options.edges.dash.gap;
  14551. }
  14552. if (options.edges.dash.altLength !== undefined) {
  14553. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14554. }
  14555. }
  14556. }
  14557. if (options.nodes) {
  14558. for (prop in options.nodes) {
  14559. if (options.nodes.hasOwnProperty(prop)) {
  14560. this.constants.nodes[prop] = options.nodes[prop];
  14561. }
  14562. }
  14563. if (options.nodes.color) {
  14564. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  14565. }
  14566. /*
  14567. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14568. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14569. */
  14570. }
  14571. if (options.groups) {
  14572. for (var groupname in options.groups) {
  14573. if (options.groups.hasOwnProperty(groupname)) {
  14574. var group = options.groups[groupname];
  14575. this.groups.add(groupname, group);
  14576. }
  14577. }
  14578. }
  14579. }
  14580. // (Re)loading the mixins that can be enabled or disabled in the options.
  14581. // load the force calculation functions, grouped under the physics system.
  14582. this._loadPhysicsSystem();
  14583. // load the navigation system.
  14584. this._loadNavigationControls();
  14585. // load the data manipulation system
  14586. this._loadManipulationSystem();
  14587. // configure the smooth curves
  14588. this._configureSmoothCurves();
  14589. // bind keys. If disabled, this will not do anything;
  14590. this._createKeyBinds();
  14591. this.setSize(this.width, this.height);
  14592. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14593. this._setScale(1);
  14594. this._redraw();
  14595. };
  14596. /**
  14597. * Create the main frame for the Graph.
  14598. * This function is executed once when a Graph object is created. The frame
  14599. * contains a canvas, and this canvas contains all objects like the axis and
  14600. * nodes.
  14601. * @private
  14602. */
  14603. Graph.prototype._create = function () {
  14604. // remove all elements from the container element.
  14605. while (this.containerElement.hasChildNodes()) {
  14606. this.containerElement.removeChild(this.containerElement.firstChild);
  14607. }
  14608. this.frame = document.createElement('div');
  14609. this.frame.className = 'graph-frame';
  14610. this.frame.style.position = 'relative';
  14611. this.frame.style.overflow = 'hidden';
  14612. this.frame.style.zIndex = "1";
  14613. // create the graph canvas (HTML canvas element)
  14614. this.frame.canvas = document.createElement( 'canvas' );
  14615. this.frame.canvas.style.position = 'relative';
  14616. this.frame.appendChild(this.frame.canvas);
  14617. if (!this.frame.canvas.getContext) {
  14618. var noCanvas = document.createElement( 'DIV' );
  14619. noCanvas.style.color = 'red';
  14620. noCanvas.style.fontWeight = 'bold' ;
  14621. noCanvas.style.padding = '10px';
  14622. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14623. this.frame.canvas.appendChild(noCanvas);
  14624. }
  14625. var me = this;
  14626. this.drag = {};
  14627. this.pinch = {};
  14628. this.hammer = Hammer(this.frame.canvas, {
  14629. prevent_default: true
  14630. });
  14631. this.hammer.on('tap', me._onTap.bind(me) );
  14632. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14633. this.hammer.on('hold', me._onHold.bind(me) );
  14634. this.hammer.on('pinch', me._onPinch.bind(me) );
  14635. this.hammer.on('touch', me._onTouch.bind(me) );
  14636. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14637. this.hammer.on('drag', me._onDrag.bind(me) );
  14638. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14639. this.hammer.on('release', me._onRelease.bind(me) );
  14640. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14641. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14642. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14643. // add the frame to the container element
  14644. this.containerElement.appendChild(this.frame);
  14645. };
  14646. /**
  14647. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14648. * @private
  14649. */
  14650. Graph.prototype._createKeyBinds = function() {
  14651. var me = this;
  14652. this.mousetrap = mousetrap;
  14653. this.mousetrap.reset();
  14654. if (this.constants.keyboard.enabled == true) {
  14655. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14656. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14657. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14658. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14659. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14660. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14661. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14662. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14663. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14664. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14665. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14666. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14667. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14668. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14669. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14670. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14671. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14672. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14673. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14674. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14675. }
  14676. if (this.constants.dataManipulation.enabled == true) {
  14677. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14678. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14679. }
  14680. };
  14681. /**
  14682. * Get the pointer location from a touch location
  14683. * @param {{pageX: Number, pageY: Number}} touch
  14684. * @return {{x: Number, y: Number}} pointer
  14685. * @private
  14686. */
  14687. Graph.prototype._getPointer = function (touch) {
  14688. return {
  14689. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14690. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14691. };
  14692. };
  14693. /**
  14694. * On start of a touch gesture, store the pointer
  14695. * @param event
  14696. * @private
  14697. */
  14698. Graph.prototype._onTouch = function (event) {
  14699. this.drag.pointer = this._getPointer(event.gesture.center);
  14700. this.drag.pinched = false;
  14701. this.pinch.scale = this._getScale();
  14702. this._handleTouch(this.drag.pointer);
  14703. };
  14704. /**
  14705. * handle drag start event
  14706. * @private
  14707. */
  14708. Graph.prototype._onDragStart = function () {
  14709. this._handleDragStart();
  14710. };
  14711. /**
  14712. * This function is called by _onDragStart.
  14713. * It is separated out because we can then overload it for the datamanipulation system.
  14714. *
  14715. * @private
  14716. */
  14717. Graph.prototype._handleDragStart = function() {
  14718. var drag = this.drag;
  14719. var node = this._getNodeAt(drag.pointer);
  14720. // note: drag.pointer is set in _onTouch to get the initial touch location
  14721. drag.dragging = true;
  14722. drag.selection = [];
  14723. drag.translation = this._getTranslation();
  14724. drag.nodeId = null;
  14725. if (node != null) {
  14726. drag.nodeId = node.id;
  14727. // select the clicked node if not yet selected
  14728. if (!node.isSelected()) {
  14729. this._selectObject(node,false);
  14730. }
  14731. // create an array with the selected nodes and their original location and status
  14732. for (var objectId in this.selectionObj.nodes) {
  14733. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  14734. var object = this.selectionObj.nodes[objectId];
  14735. var s = {
  14736. id: object.id,
  14737. node: object,
  14738. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14739. x: object.x,
  14740. y: object.y,
  14741. xFixed: object.xFixed,
  14742. yFixed: object.yFixed
  14743. };
  14744. object.xFixed = true;
  14745. object.yFixed = true;
  14746. drag.selection.push(s);
  14747. }
  14748. }
  14749. }
  14750. };
  14751. /**
  14752. * handle drag event
  14753. * @private
  14754. */
  14755. Graph.prototype._onDrag = function (event) {
  14756. this._handleOnDrag(event)
  14757. };
  14758. /**
  14759. * This function is called by _onDrag.
  14760. * It is separated out because we can then overload it for the datamanipulation system.
  14761. *
  14762. * @private
  14763. */
  14764. Graph.prototype._handleOnDrag = function(event) {
  14765. if (this.drag.pinched) {
  14766. return;
  14767. }
  14768. var pointer = this._getPointer(event.gesture.center);
  14769. var me = this,
  14770. drag = this.drag,
  14771. selection = drag.selection;
  14772. if (selection && selection.length) {
  14773. // calculate delta's and new location
  14774. var deltaX = pointer.x - drag.pointer.x,
  14775. deltaY = pointer.y - drag.pointer.y;
  14776. // update position of all selected nodes
  14777. selection.forEach(function (s) {
  14778. var node = s.node;
  14779. if (!s.xFixed) {
  14780. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14781. }
  14782. if (!s.yFixed) {
  14783. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14784. }
  14785. });
  14786. // start _animationStep if not yet running
  14787. if (!this.moving) {
  14788. this.moving = true;
  14789. this.start();
  14790. }
  14791. }
  14792. else {
  14793. // move the graph
  14794. var diffX = pointer.x - this.drag.pointer.x;
  14795. var diffY = pointer.y - this.drag.pointer.y;
  14796. this._setTranslation(
  14797. this.drag.translation.x + diffX,
  14798. this.drag.translation.y + diffY);
  14799. this._redraw();
  14800. this.moved = true;
  14801. }
  14802. };
  14803. /**
  14804. * handle drag start event
  14805. * @private
  14806. */
  14807. Graph.prototype._onDragEnd = function () {
  14808. this.drag.dragging = false;
  14809. var selection = this.drag.selection;
  14810. if (selection) {
  14811. selection.forEach(function (s) {
  14812. // restore original xFixed and yFixed
  14813. s.node.xFixed = s.xFixed;
  14814. s.node.yFixed = s.yFixed;
  14815. });
  14816. }
  14817. };
  14818. /**
  14819. * handle tap/click event: select/unselect a node
  14820. * @private
  14821. */
  14822. Graph.prototype._onTap = function (event) {
  14823. var pointer = this._getPointer(event.gesture.center);
  14824. this.pointerPosition = pointer;
  14825. this._handleTap(pointer);
  14826. };
  14827. /**
  14828. * handle doubletap event
  14829. * @private
  14830. */
  14831. Graph.prototype._onDoubleTap = function (event) {
  14832. var pointer = this._getPointer(event.gesture.center);
  14833. this._handleDoubleTap(pointer);
  14834. };
  14835. /**
  14836. * handle long tap event: multi select nodes
  14837. * @private
  14838. */
  14839. Graph.prototype._onHold = function (event) {
  14840. var pointer = this._getPointer(event.gesture.center);
  14841. this.pointerPosition = pointer;
  14842. this._handleOnHold(pointer);
  14843. };
  14844. /**
  14845. * handle the release of the screen
  14846. *
  14847. * @private
  14848. */
  14849. Graph.prototype._onRelease = function (event) {
  14850. var pointer = this._getPointer(event.gesture.center);
  14851. this._handleOnRelease(pointer);
  14852. };
  14853. /**
  14854. * Handle pinch event
  14855. * @param event
  14856. * @private
  14857. */
  14858. Graph.prototype._onPinch = function (event) {
  14859. var pointer = this._getPointer(event.gesture.center);
  14860. this.drag.pinched = true;
  14861. if (!('scale' in this.pinch)) {
  14862. this.pinch.scale = 1;
  14863. }
  14864. // TODO: enabled moving while pinching?
  14865. var scale = this.pinch.scale * event.gesture.scale;
  14866. this._zoom(scale, pointer)
  14867. };
  14868. /**
  14869. * Zoom the graph in or out
  14870. * @param {Number} scale a number around 1, and between 0.01 and 10
  14871. * @param {{x: Number, y: Number}} pointer Position on screen
  14872. * @return {Number} appliedScale scale is limited within the boundaries
  14873. * @private
  14874. */
  14875. Graph.prototype._zoom = function(scale, pointer) {
  14876. var scaleOld = this._getScale();
  14877. if (scale < 0.00001) {
  14878. scale = 0.00001;
  14879. }
  14880. if (scale > 10) {
  14881. scale = 10;
  14882. }
  14883. // + this.frame.canvas.clientHeight / 2
  14884. var translation = this._getTranslation();
  14885. var scaleFrac = scale / scaleOld;
  14886. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14887. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14888. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  14889. "y" : this._canvasToY(pointer.y)};
  14890. this._setScale(scale);
  14891. this._setTranslation(tx, ty);
  14892. this.updateClustersDefault();
  14893. this._redraw();
  14894. return scale;
  14895. };
  14896. /**
  14897. * Event handler for mouse wheel event, used to zoom the timeline
  14898. * See http://adomas.org/javascript-mouse-wheel/
  14899. * https://github.com/EightMedia/hammer.js/issues/256
  14900. * @param {MouseEvent} event
  14901. * @private
  14902. */
  14903. Graph.prototype._onMouseWheel = function(event) {
  14904. // retrieve delta
  14905. var delta = 0;
  14906. if (event.wheelDelta) { /* IE/Opera. */
  14907. delta = event.wheelDelta/120;
  14908. } else if (event.detail) { /* Mozilla case. */
  14909. // In Mozilla, sign of delta is different than in IE.
  14910. // Also, delta is multiple of 3.
  14911. delta = -event.detail/3;
  14912. }
  14913. // If delta is nonzero, handle it.
  14914. // Basically, delta is now positive if wheel was scrolled up,
  14915. // and negative, if wheel was scrolled down.
  14916. if (delta) {
  14917. // calculate the new scale
  14918. var scale = this._getScale();
  14919. var zoom = delta / 10;
  14920. if (delta < 0) {
  14921. zoom = zoom / (1 - zoom);
  14922. }
  14923. scale *= (1 + zoom);
  14924. // calculate the pointer location
  14925. var gesture = util.fakeGesture(this, event);
  14926. var pointer = this._getPointer(gesture.center);
  14927. // apply the new scale
  14928. this._zoom(scale, pointer);
  14929. }
  14930. // Prevent default actions caused by mouse wheel.
  14931. event.preventDefault();
  14932. };
  14933. /**
  14934. * Mouse move handler for checking whether the title moves over a node with a title.
  14935. * @param {Event} event
  14936. * @private
  14937. */
  14938. Graph.prototype._onMouseMoveTitle = function (event) {
  14939. var gesture = util.fakeGesture(this, event);
  14940. var pointer = this._getPointer(gesture.center);
  14941. // check if the previously selected node is still selected
  14942. if (this.popupNode) {
  14943. this._checkHidePopup(pointer);
  14944. }
  14945. // start a timeout that will check if the mouse is positioned above
  14946. // an element
  14947. var me = this;
  14948. var checkShow = function() {
  14949. me._checkShowPopup(pointer);
  14950. };
  14951. if (this.popupTimer) {
  14952. clearInterval(this.popupTimer); // stop any running calculationTimer
  14953. }
  14954. if (!this.drag.dragging) {
  14955. this.popupTimer = setTimeout(checkShow, 300);
  14956. }
  14957. };
  14958. /**
  14959. * Check if there is an element on the given position in the graph
  14960. * (a node or edge). If so, and if this element has a title,
  14961. * show a popup window with its title.
  14962. *
  14963. * @param {{x:Number, y:Number}} pointer
  14964. * @private
  14965. */
  14966. Graph.prototype._checkShowPopup = function (pointer) {
  14967. var obj = {
  14968. left: this._canvasToX(pointer.x),
  14969. top: this._canvasToY(pointer.y),
  14970. right: this._canvasToX(pointer.x),
  14971. bottom: this._canvasToY(pointer.y)
  14972. };
  14973. var id;
  14974. var lastPopupNode = this.popupNode;
  14975. if (this.popupNode == undefined) {
  14976. // search the nodes for overlap, select the top one in case of multiple nodes
  14977. var nodes = this.nodes;
  14978. for (id in nodes) {
  14979. if (nodes.hasOwnProperty(id)) {
  14980. var node = nodes[id];
  14981. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14982. this.popupNode = node;
  14983. break;
  14984. }
  14985. }
  14986. }
  14987. }
  14988. if (this.popupNode === undefined) {
  14989. // search the edges for overlap
  14990. var edges = this.edges;
  14991. for (id in edges) {
  14992. if (edges.hasOwnProperty(id)) {
  14993. var edge = edges[id];
  14994. if (edge.connected && (edge.getTitle() !== undefined) &&
  14995. edge.isOverlappingWith(obj)) {
  14996. this.popupNode = edge;
  14997. break;
  14998. }
  14999. }
  15000. }
  15001. }
  15002. if (this.popupNode) {
  15003. // show popup message window
  15004. if (this.popupNode != lastPopupNode) {
  15005. var me = this;
  15006. if (!me.popup) {
  15007. me.popup = new Popup(me.frame);
  15008. }
  15009. // adjust a small offset such that the mouse cursor is located in the
  15010. // bottom left location of the popup, and you can easily move over the
  15011. // popup area
  15012. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  15013. me.popup.setText(me.popupNode.getTitle());
  15014. me.popup.show();
  15015. }
  15016. }
  15017. else {
  15018. if (this.popup) {
  15019. this.popup.hide();
  15020. }
  15021. }
  15022. };
  15023. /**
  15024. * Check if the popup must be hided, which is the case when the mouse is no
  15025. * longer hovering on the object
  15026. * @param {{x:Number, y:Number}} pointer
  15027. * @private
  15028. */
  15029. Graph.prototype._checkHidePopup = function (pointer) {
  15030. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  15031. this.popupNode = undefined;
  15032. if (this.popup) {
  15033. this.popup.hide();
  15034. }
  15035. }
  15036. };
  15037. /**
  15038. * Set a new size for the graph
  15039. * @param {string} width Width in pixels or percentage (for example '800px'
  15040. * or '50%')
  15041. * @param {string} height Height in pixels or percentage (for example '400px'
  15042. * or '30%')
  15043. */
  15044. Graph.prototype.setSize = function(width, height) {
  15045. this.frame.style.width = width;
  15046. this.frame.style.height = height;
  15047. this.frame.canvas.style.width = '100%';
  15048. this.frame.canvas.style.height = '100%';
  15049. this.frame.canvas.width = this.frame.canvas.clientWidth;
  15050. this.frame.canvas.height = this.frame.canvas.clientHeight;
  15051. if (this.manipulationDiv !== undefined) {
  15052. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  15053. }
  15054. if (this.navigationDivs !== undefined) {
  15055. if (this.navigationDivs['wrapper'] !== undefined) {
  15056. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  15057. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  15058. }
  15059. }
  15060. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  15061. };
  15062. /**
  15063. * Set a data set with nodes for the graph
  15064. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  15065. * @private
  15066. */
  15067. Graph.prototype._setNodes = function(nodes) {
  15068. var oldNodesData = this.nodesData;
  15069. if (nodes instanceof DataSet || nodes instanceof DataView) {
  15070. this.nodesData = nodes;
  15071. }
  15072. else if (nodes instanceof Array) {
  15073. this.nodesData = new DataSet();
  15074. this.nodesData.add(nodes);
  15075. }
  15076. else if (!nodes) {
  15077. this.nodesData = new DataSet();
  15078. }
  15079. else {
  15080. throw new TypeError('Array or DataSet expected');
  15081. }
  15082. if (oldNodesData) {
  15083. // unsubscribe from old dataset
  15084. util.forEach(this.nodesListeners, function (callback, event) {
  15085. oldNodesData.off(event, callback);
  15086. });
  15087. }
  15088. // remove drawn nodes
  15089. this.nodes = {};
  15090. if (this.nodesData) {
  15091. // subscribe to new dataset
  15092. var me = this;
  15093. util.forEach(this.nodesListeners, function (callback, event) {
  15094. me.nodesData.on(event, callback);
  15095. });
  15096. // draw all new nodes
  15097. var ids = this.nodesData.getIds();
  15098. this._addNodes(ids);
  15099. }
  15100. this._updateSelection();
  15101. };
  15102. /**
  15103. * Add nodes
  15104. * @param {Number[] | String[]} ids
  15105. * @private
  15106. */
  15107. Graph.prototype._addNodes = function(ids) {
  15108. var id;
  15109. for (var i = 0, len = ids.length; i < len; i++) {
  15110. id = ids[i];
  15111. var data = this.nodesData.get(id);
  15112. var node = new Node(data, this.images, this.groups, this.constants);
  15113. this.nodes[id] = node; // note: this may replace an existing node
  15114. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  15115. var radius = 10 * 0.1*ids.length;
  15116. var angle = 2 * Math.PI * Math.random();
  15117. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  15118. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  15119. }
  15120. this.moving = true;
  15121. }
  15122. this._updateNodeIndexList();
  15123. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15124. this._resetLevels();
  15125. this._setupHierarchicalLayout();
  15126. }
  15127. this._updateCalculationNodes();
  15128. this._reconnectEdges();
  15129. this._updateValueRange(this.nodes);
  15130. this.updateLabels();
  15131. };
  15132. /**
  15133. * Update existing nodes, or create them when not yet existing
  15134. * @param {Number[] | String[]} ids
  15135. * @private
  15136. */
  15137. Graph.prototype._updateNodes = function(ids) {
  15138. var nodes = this.nodes,
  15139. nodesData = this.nodesData;
  15140. for (var i = 0, len = ids.length; i < len; i++) {
  15141. var id = ids[i];
  15142. var node = nodes[id];
  15143. var data = nodesData.get(id);
  15144. if (node) {
  15145. // update node
  15146. node.setProperties(data, this.constants);
  15147. }
  15148. else {
  15149. // create node
  15150. node = new Node(properties, this.images, this.groups, this.constants);
  15151. nodes[id] = node;
  15152. if (!node.isFixed()) {
  15153. this.moving = true;
  15154. }
  15155. }
  15156. }
  15157. this._updateNodeIndexList();
  15158. this._reconnectEdges();
  15159. this._updateValueRange(nodes);
  15160. };
  15161. /**
  15162. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  15163. * @param {Number[] | String[]} ids
  15164. * @private
  15165. */
  15166. Graph.prototype._removeNodes = function(ids) {
  15167. var nodes = this.nodes;
  15168. for (var i = 0, len = ids.length; i < len; i++) {
  15169. var id = ids[i];
  15170. delete nodes[id];
  15171. }
  15172. this._updateNodeIndexList();
  15173. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15174. this._resetLevels();
  15175. this._setupHierarchicalLayout();
  15176. }
  15177. this._updateCalculationNodes();
  15178. this._reconnectEdges();
  15179. this._updateSelection();
  15180. this._updateValueRange(nodes);
  15181. };
  15182. /**
  15183. * Load edges by reading the data table
  15184. * @param {Array | DataSet | DataView} edges The data containing the edges.
  15185. * @private
  15186. * @private
  15187. */
  15188. Graph.prototype._setEdges = function(edges) {
  15189. var oldEdgesData = this.edgesData;
  15190. if (edges instanceof DataSet || edges instanceof DataView) {
  15191. this.edgesData = edges;
  15192. }
  15193. else if (edges instanceof Array) {
  15194. this.edgesData = new DataSet();
  15195. this.edgesData.add(edges);
  15196. }
  15197. else if (!edges) {
  15198. this.edgesData = new DataSet();
  15199. }
  15200. else {
  15201. throw new TypeError('Array or DataSet expected');
  15202. }
  15203. if (oldEdgesData) {
  15204. // unsubscribe from old dataset
  15205. util.forEach(this.edgesListeners, function (callback, event) {
  15206. oldEdgesData.off(event, callback);
  15207. });
  15208. }
  15209. // remove drawn edges
  15210. this.edges = {};
  15211. if (this.edgesData) {
  15212. // subscribe to new dataset
  15213. var me = this;
  15214. util.forEach(this.edgesListeners, function (callback, event) {
  15215. me.edgesData.on(event, callback);
  15216. });
  15217. // draw all new nodes
  15218. var ids = this.edgesData.getIds();
  15219. this._addEdges(ids);
  15220. }
  15221. this._reconnectEdges();
  15222. };
  15223. /**
  15224. * Add edges
  15225. * @param {Number[] | String[]} ids
  15226. * @private
  15227. */
  15228. Graph.prototype._addEdges = function (ids) {
  15229. var edges = this.edges,
  15230. edgesData = this.edgesData;
  15231. for (var i = 0, len = ids.length; i < len; i++) {
  15232. var id = ids[i];
  15233. var oldEdge = edges[id];
  15234. if (oldEdge) {
  15235. oldEdge.disconnect();
  15236. }
  15237. var data = edgesData.get(id, {"showInternalIds" : true});
  15238. edges[id] = new Edge(data, this, this.constants);
  15239. }
  15240. this.moving = true;
  15241. this._updateValueRange(edges);
  15242. this._createBezierNodes();
  15243. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15244. this._resetLevels();
  15245. this._setupHierarchicalLayout();
  15246. }
  15247. this._updateCalculationNodes();
  15248. };
  15249. /**
  15250. * Update existing edges, or create them when not yet existing
  15251. * @param {Number[] | String[]} ids
  15252. * @private
  15253. */
  15254. Graph.prototype._updateEdges = function (ids) {
  15255. var edges = this.edges,
  15256. edgesData = this.edgesData;
  15257. for (var i = 0, len = ids.length; i < len; i++) {
  15258. var id = ids[i];
  15259. var data = edgesData.get(id);
  15260. var edge = edges[id];
  15261. if (edge) {
  15262. // update edge
  15263. edge.disconnect();
  15264. edge.setProperties(data, this.constants);
  15265. edge.connect();
  15266. }
  15267. else {
  15268. // create edge
  15269. edge = new Edge(data, this, this.constants);
  15270. this.edges[id] = edge;
  15271. }
  15272. }
  15273. this._createBezierNodes();
  15274. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15275. this._resetLevels();
  15276. this._setupHierarchicalLayout();
  15277. }
  15278. this.moving = true;
  15279. this._updateValueRange(edges);
  15280. };
  15281. /**
  15282. * Remove existing edges. Non existing ids will be ignored
  15283. * @param {Number[] | String[]} ids
  15284. * @private
  15285. */
  15286. Graph.prototype._removeEdges = function (ids) {
  15287. var edges = this.edges;
  15288. for (var i = 0, len = ids.length; i < len; i++) {
  15289. var id = ids[i];
  15290. var edge = edges[id];
  15291. if (edge) {
  15292. if (edge.via != null) {
  15293. delete this.sectors['support']['nodes'][edge.via.id];
  15294. }
  15295. edge.disconnect();
  15296. delete edges[id];
  15297. }
  15298. }
  15299. this.moving = true;
  15300. this._updateValueRange(edges);
  15301. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15302. this._resetLevels();
  15303. this._setupHierarchicalLayout();
  15304. }
  15305. this._updateCalculationNodes();
  15306. };
  15307. /**
  15308. * Reconnect all edges
  15309. * @private
  15310. */
  15311. Graph.prototype._reconnectEdges = function() {
  15312. var id,
  15313. nodes = this.nodes,
  15314. edges = this.edges;
  15315. for (id in nodes) {
  15316. if (nodes.hasOwnProperty(id)) {
  15317. nodes[id].edges = [];
  15318. }
  15319. }
  15320. for (id in edges) {
  15321. if (edges.hasOwnProperty(id)) {
  15322. var edge = edges[id];
  15323. edge.from = null;
  15324. edge.to = null;
  15325. edge.connect();
  15326. }
  15327. }
  15328. };
  15329. /**
  15330. * Update the values of all object in the given array according to the current
  15331. * value range of the objects in the array.
  15332. * @param {Object} obj An object containing a set of Edges or Nodes
  15333. * The objects must have a method getValue() and
  15334. * setValueRange(min, max).
  15335. * @private
  15336. */
  15337. Graph.prototype._updateValueRange = function(obj) {
  15338. var id;
  15339. // determine the range of the objects
  15340. var valueMin = undefined;
  15341. var valueMax = undefined;
  15342. for (id in obj) {
  15343. if (obj.hasOwnProperty(id)) {
  15344. var value = obj[id].getValue();
  15345. if (value !== undefined) {
  15346. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  15347. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  15348. }
  15349. }
  15350. }
  15351. // adjust the range of all objects
  15352. if (valueMin !== undefined && valueMax !== undefined) {
  15353. for (id in obj) {
  15354. if (obj.hasOwnProperty(id)) {
  15355. obj[id].setValueRange(valueMin, valueMax);
  15356. }
  15357. }
  15358. }
  15359. };
  15360. /**
  15361. * Redraw the graph with the current data
  15362. * chart will be resized too.
  15363. */
  15364. Graph.prototype.redraw = function() {
  15365. this.setSize(this.width, this.height);
  15366. this._redraw();
  15367. };
  15368. /**
  15369. * Redraw the graph with the current data
  15370. * @private
  15371. */
  15372. Graph.prototype._redraw = function() {
  15373. var ctx = this.frame.canvas.getContext('2d');
  15374. // clear the canvas
  15375. var w = this.frame.canvas.width;
  15376. var h = this.frame.canvas.height;
  15377. ctx.clearRect(0, 0, w, h);
  15378. // set scaling and translation
  15379. ctx.save();
  15380. ctx.translate(this.translation.x, this.translation.y);
  15381. ctx.scale(this.scale, this.scale);
  15382. this.canvasTopLeft = {
  15383. "x": this._canvasToX(0),
  15384. "y": this._canvasToY(0)
  15385. };
  15386. this.canvasBottomRight = {
  15387. "x": this._canvasToX(this.frame.canvas.clientWidth),
  15388. "y": this._canvasToY(this.frame.canvas.clientHeight)
  15389. };
  15390. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15391. this._doInAllSectors("_drawEdges",ctx);
  15392. this._doInAllSectors("_drawNodes",ctx,false);
  15393. // this._doInSupportSector("_drawNodes",ctx,true);
  15394. // this._drawTree(ctx,"#F00F0F");
  15395. // restore original scaling and translation
  15396. ctx.restore();
  15397. };
  15398. /**
  15399. * Set the translation of the graph
  15400. * @param {Number} offsetX Horizontal offset
  15401. * @param {Number} offsetY Vertical offset
  15402. * @private
  15403. */
  15404. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15405. if (this.translation === undefined) {
  15406. this.translation = {
  15407. x: 0,
  15408. y: 0
  15409. };
  15410. }
  15411. if (offsetX !== undefined) {
  15412. this.translation.x = offsetX;
  15413. }
  15414. if (offsetY !== undefined) {
  15415. this.translation.y = offsetY;
  15416. }
  15417. };
  15418. /**
  15419. * Get the translation of the graph
  15420. * @return {Object} translation An object with parameters x and y, both a number
  15421. * @private
  15422. */
  15423. Graph.prototype._getTranslation = function() {
  15424. return {
  15425. x: this.translation.x,
  15426. y: this.translation.y
  15427. };
  15428. };
  15429. /**
  15430. * Scale the graph
  15431. * @param {Number} scale Scaling factor 1.0 is unscaled
  15432. * @private
  15433. */
  15434. Graph.prototype._setScale = function(scale) {
  15435. this.scale = scale;
  15436. };
  15437. /**
  15438. * Get the current scale of the graph
  15439. * @return {Number} scale Scaling factor 1.0 is unscaled
  15440. * @private
  15441. */
  15442. Graph.prototype._getScale = function() {
  15443. return this.scale;
  15444. };
  15445. /**
  15446. * Convert a horizontal point on the HTML canvas to the x-value of the model
  15447. * @param {number} x
  15448. * @returns {number}
  15449. * @private
  15450. */
  15451. Graph.prototype._canvasToX = function(x) {
  15452. return (x - this.translation.x) / this.scale;
  15453. };
  15454. /**
  15455. * Convert an x-value in the model to a horizontal point on the HTML canvas
  15456. * @param {number} x
  15457. * @returns {number}
  15458. * @private
  15459. */
  15460. Graph.prototype._xToCanvas = function(x) {
  15461. return x * this.scale + this.translation.x;
  15462. };
  15463. /**
  15464. * Convert a vertical point on the HTML canvas to the y-value of the model
  15465. * @param {number} y
  15466. * @returns {number}
  15467. * @private
  15468. */
  15469. Graph.prototype._canvasToY = function(y) {
  15470. return (y - this.translation.y) / this.scale;
  15471. };
  15472. /**
  15473. * Convert an y-value in the model to a vertical point on the HTML canvas
  15474. * @param {number} y
  15475. * @returns {number}
  15476. * @private
  15477. */
  15478. Graph.prototype._yToCanvas = function(y) {
  15479. return y * this.scale + this.translation.y ;
  15480. };
  15481. /**
  15482. * Redraw all nodes
  15483. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15484. * @param {CanvasRenderingContext2D} ctx
  15485. * @param {Boolean} [alwaysShow]
  15486. * @private
  15487. */
  15488. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  15489. if (alwaysShow === undefined) {
  15490. alwaysShow = false;
  15491. }
  15492. // first draw the unselected nodes
  15493. var nodes = this.nodes;
  15494. var selected = [];
  15495. for (var id in nodes) {
  15496. if (nodes.hasOwnProperty(id)) {
  15497. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15498. if (nodes[id].isSelected()) {
  15499. selected.push(id);
  15500. }
  15501. else {
  15502. if (nodes[id].inArea() || alwaysShow) {
  15503. nodes[id].draw(ctx);
  15504. }
  15505. }
  15506. }
  15507. }
  15508. // draw the selected nodes on top
  15509. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15510. if (nodes[selected[s]].inArea() || alwaysShow) {
  15511. nodes[selected[s]].draw(ctx);
  15512. }
  15513. }
  15514. };
  15515. /**
  15516. * Redraw all edges
  15517. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15518. * @param {CanvasRenderingContext2D} ctx
  15519. * @private
  15520. */
  15521. Graph.prototype._drawEdges = function(ctx) {
  15522. var edges = this.edges;
  15523. for (var id in edges) {
  15524. if (edges.hasOwnProperty(id)) {
  15525. var edge = edges[id];
  15526. edge.setScale(this.scale);
  15527. if (edge.connected) {
  15528. edges[id].draw(ctx);
  15529. }
  15530. }
  15531. }
  15532. };
  15533. /**
  15534. * Find a stable position for all nodes
  15535. * @private
  15536. */
  15537. Graph.prototype._stabilize = function() {
  15538. if (this.constants.freezeForStabilization == true) {
  15539. this._freezeDefinedNodes();
  15540. }
  15541. // find stable position
  15542. var count = 0;
  15543. while (this.moving && count < this.constants.stabilizationIterations) {
  15544. this._physicsTick();
  15545. count++;
  15546. }
  15547. this.zoomExtent(false,true);
  15548. if (this.constants.freezeForStabilization == true) {
  15549. this._restoreFrozenNodes();
  15550. }
  15551. this.emit("stabilized",{iterations:count});
  15552. };
  15553. Graph.prototype._freezeDefinedNodes = function() {
  15554. var nodes = this.nodes;
  15555. for (var id in nodes) {
  15556. if (nodes.hasOwnProperty(id)) {
  15557. if (nodes[id].x != null && nodes[id].y != null) {
  15558. nodes[id].fixedData.x = nodes[id].xFixed;
  15559. nodes[id].fixedData.y = nodes[id].yFixed;
  15560. nodes[id].xFixed = true;
  15561. nodes[id].yFixed = true;
  15562. }
  15563. }
  15564. }
  15565. };
  15566. Graph.prototype._restoreFrozenNodes = function() {
  15567. var nodes = this.nodes;
  15568. for (var id in nodes) {
  15569. if (nodes.hasOwnProperty(id)) {
  15570. if (nodes[id].fixedData.x != null) {
  15571. nodes[id].xFixed = nodes[id].fixedData.x;
  15572. nodes[id].yFixed = nodes[id].fixedData.y;
  15573. }
  15574. }
  15575. }
  15576. };
  15577. /**
  15578. * Check if any of the nodes is still moving
  15579. * @param {number} vmin the minimum velocity considered as 'moving'
  15580. * @return {boolean} true if moving, false if non of the nodes is moving
  15581. * @private
  15582. */
  15583. Graph.prototype._isMoving = function(vmin) {
  15584. var nodes = this.nodes;
  15585. for (var id in nodes) {
  15586. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15587. return true;
  15588. }
  15589. }
  15590. return false;
  15591. };
  15592. /**
  15593. * /**
  15594. * Perform one discrete step for all nodes
  15595. *
  15596. * @private
  15597. */
  15598. Graph.prototype._discreteStepNodes = function() {
  15599. var interval = this.physicsDiscreteStepsize;
  15600. var nodes = this.nodes;
  15601. var nodeId;
  15602. var nodesPresent = false;
  15603. if (this.constants.maxVelocity > 0) {
  15604. for (nodeId in nodes) {
  15605. if (nodes.hasOwnProperty(nodeId)) {
  15606. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15607. nodesPresent = true;
  15608. }
  15609. }
  15610. }
  15611. else {
  15612. for (nodeId in nodes) {
  15613. if (nodes.hasOwnProperty(nodeId)) {
  15614. nodes[nodeId].discreteStep(interval);
  15615. nodesPresent = true;
  15616. }
  15617. }
  15618. }
  15619. if (nodesPresent == true) {
  15620. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15621. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15622. this.moving = true;
  15623. }
  15624. else {
  15625. this.moving = this._isMoving(vminCorrected);
  15626. }
  15627. }
  15628. };
  15629. Graph.prototype._physicsTick = function() {
  15630. if (!this.freezeSimulation) {
  15631. if (this.moving) {
  15632. this._doInAllActiveSectors("_initializeForceCalculation");
  15633. this._doInAllActiveSectors("_discreteStepNodes");
  15634. if (this.constants.smoothCurves) {
  15635. this._doInSupportSector("_discreteStepNodes");
  15636. }
  15637. this._findCenter(this._getRange())
  15638. }
  15639. }
  15640. };
  15641. /**
  15642. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15643. * It reschedules itself at the beginning of the function
  15644. *
  15645. * @private
  15646. */
  15647. Graph.prototype._animationStep = function() {
  15648. // reset the timer so a new scheduled animation step can be set
  15649. this.timer = undefined;
  15650. // handle the keyboad movement
  15651. this._handleNavigation();
  15652. // this schedules a new animation step
  15653. this.start();
  15654. // start the physics simulation
  15655. var calculationTime = Date.now();
  15656. var maxSteps = 1;
  15657. this._physicsTick();
  15658. var timeRequired = Date.now() - calculationTime;
  15659. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  15660. this._physicsTick();
  15661. timeRequired = Date.now() - calculationTime;
  15662. maxSteps++;
  15663. }
  15664. // start the rendering process
  15665. var renderTime = Date.now();
  15666. this._redraw();
  15667. this.renderTime = Date.now() - renderTime;
  15668. };
  15669. if (typeof window !== 'undefined') {
  15670. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15671. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15672. }
  15673. /**
  15674. * Schedule a animation step with the refreshrate interval.
  15675. *
  15676. * @poram {Boolean} runCalculationStep
  15677. */
  15678. Graph.prototype.start = function() {
  15679. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15680. if (!this.timer) {
  15681. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15682. }
  15683. }
  15684. else {
  15685. this._redraw();
  15686. }
  15687. };
  15688. /**
  15689. * Move the graph according to the keyboard presses.
  15690. *
  15691. * @private
  15692. */
  15693. Graph.prototype._handleNavigation = function() {
  15694. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15695. var translation = this._getTranslation();
  15696. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15697. }
  15698. if (this.zoomIncrement != 0) {
  15699. var center = {
  15700. x: this.frame.canvas.clientWidth / 2,
  15701. y: this.frame.canvas.clientHeight / 2
  15702. };
  15703. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15704. }
  15705. };
  15706. /**
  15707. * Freeze the _animationStep
  15708. */
  15709. Graph.prototype.toggleFreeze = function() {
  15710. if (this.freezeSimulation == false) {
  15711. this.freezeSimulation = true;
  15712. }
  15713. else {
  15714. this.freezeSimulation = false;
  15715. this.start();
  15716. }
  15717. };
  15718. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15719. if (disableStart === undefined) {
  15720. disableStart = true;
  15721. }
  15722. if (this.constants.smoothCurves == true) {
  15723. this._createBezierNodes();
  15724. }
  15725. else {
  15726. // delete the support nodes
  15727. this.sectors['support']['nodes'] = {};
  15728. for (var edgeId in this.edges) {
  15729. if (this.edges.hasOwnProperty(edgeId)) {
  15730. this.edges[edgeId].smooth = false;
  15731. this.edges[edgeId].via = null;
  15732. }
  15733. }
  15734. }
  15735. this._updateCalculationNodes();
  15736. if (!disableStart) {
  15737. this.moving = true;
  15738. this.start();
  15739. }
  15740. };
  15741. Graph.prototype._createBezierNodes = function() {
  15742. if (this.constants.smoothCurves == true) {
  15743. for (var edgeId in this.edges) {
  15744. if (this.edges.hasOwnProperty(edgeId)) {
  15745. var edge = this.edges[edgeId];
  15746. if (edge.via == null) {
  15747. edge.smooth = true;
  15748. var nodeId = "edgeId:".concat(edge.id);
  15749. this.sectors['support']['nodes'][nodeId] = new Node(
  15750. {id:nodeId,
  15751. mass:1,
  15752. shape:'circle',
  15753. image:"",
  15754. internalMultiplier:1
  15755. },{},{},this.constants);
  15756. edge.via = this.sectors['support']['nodes'][nodeId];
  15757. edge.via.parentEdgeId = edge.id;
  15758. edge.positionBezierNode();
  15759. }
  15760. }
  15761. }
  15762. }
  15763. };
  15764. Graph.prototype._initializeMixinLoaders = function () {
  15765. for (var mixinFunction in graphMixinLoaders) {
  15766. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15767. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15768. }
  15769. }
  15770. };
  15771. /**
  15772. * Load the XY positions of the nodes into the dataset.
  15773. */
  15774. Graph.prototype.storePosition = function() {
  15775. var dataArray = [];
  15776. for (var nodeId in this.nodes) {
  15777. if (this.nodes.hasOwnProperty(nodeId)) {
  15778. var node = this.nodes[nodeId];
  15779. var allowedToMoveX = !this.nodes.xFixed;
  15780. var allowedToMoveY = !this.nodes.yFixed;
  15781. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  15782. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15783. }
  15784. }
  15785. }
  15786. this.nodesData.update(dataArray);
  15787. };
  15788. /**
  15789. * vis.js module exports
  15790. */
  15791. var vis = {
  15792. util: util,
  15793. Controller: Controller,
  15794. DataSet: DataSet,
  15795. DataView: DataView,
  15796. Range: Range,
  15797. Stack: Stack,
  15798. TimeStep: TimeStep,
  15799. components: {
  15800. items: {
  15801. Item: Item,
  15802. ItemBox: ItemBox,
  15803. ItemPoint: ItemPoint,
  15804. ItemRange: ItemRange
  15805. },
  15806. Component: Component,
  15807. Panel: Panel,
  15808. RootPanel: RootPanel,
  15809. ItemSet: ItemSet,
  15810. TimeAxis: TimeAxis
  15811. },
  15812. graph: {
  15813. Node: Node,
  15814. Edge: Edge,
  15815. Popup: Popup,
  15816. Groups: Groups,
  15817. Images: Images
  15818. },
  15819. Timeline: Timeline,
  15820. Graph: Graph
  15821. };
  15822. /**
  15823. * CommonJS module exports
  15824. */
  15825. if (typeof exports !== 'undefined') {
  15826. exports = vis;
  15827. }
  15828. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15829. module.exports = vis;
  15830. }
  15831. /**
  15832. * AMD module exports
  15833. */
  15834. if (typeof(define) === 'function') {
  15835. define(function () {
  15836. return vis;
  15837. });
  15838. }
  15839. /**
  15840. * Window exports
  15841. */
  15842. if (typeof window !== 'undefined') {
  15843. // attach the module to the window, load as a regular javascript file
  15844. window['vis'] = vis;
  15845. }
  15846. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15847. /**
  15848. * Expose `Emitter`.
  15849. */
  15850. module.exports = Emitter;
  15851. /**
  15852. * Initialize a new `Emitter`.
  15853. *
  15854. * @api public
  15855. */
  15856. function Emitter(obj) {
  15857. if (obj) return mixin(obj);
  15858. };
  15859. /**
  15860. * Mixin the emitter properties.
  15861. *
  15862. * @param {Object} obj
  15863. * @return {Object}
  15864. * @api private
  15865. */
  15866. function mixin(obj) {
  15867. for (var key in Emitter.prototype) {
  15868. obj[key] = Emitter.prototype[key];
  15869. }
  15870. return obj;
  15871. }
  15872. /**
  15873. * Listen on the given `event` with `fn`.
  15874. *
  15875. * @param {String} event
  15876. * @param {Function} fn
  15877. * @return {Emitter}
  15878. * @api public
  15879. */
  15880. Emitter.prototype.on =
  15881. Emitter.prototype.addEventListener = function(event, fn){
  15882. this._callbacks = this._callbacks || {};
  15883. (this._callbacks[event] = this._callbacks[event] || [])
  15884. .push(fn);
  15885. return this;
  15886. };
  15887. /**
  15888. * Adds an `event` listener that will be invoked a single
  15889. * time then automatically removed.
  15890. *
  15891. * @param {String} event
  15892. * @param {Function} fn
  15893. * @return {Emitter}
  15894. * @api public
  15895. */
  15896. Emitter.prototype.once = function(event, fn){
  15897. var self = this;
  15898. this._callbacks = this._callbacks || {};
  15899. function on() {
  15900. self.off(event, on);
  15901. fn.apply(this, arguments);
  15902. }
  15903. on.fn = fn;
  15904. this.on(event, on);
  15905. return this;
  15906. };
  15907. /**
  15908. * Remove the given callback for `event` or all
  15909. * registered callbacks.
  15910. *
  15911. * @param {String} event
  15912. * @param {Function} fn
  15913. * @return {Emitter}
  15914. * @api public
  15915. */
  15916. Emitter.prototype.off =
  15917. Emitter.prototype.removeListener =
  15918. Emitter.prototype.removeAllListeners =
  15919. Emitter.prototype.removeEventListener = function(event, fn){
  15920. this._callbacks = this._callbacks || {};
  15921. // all
  15922. if (0 == arguments.length) {
  15923. this._callbacks = {};
  15924. return this;
  15925. }
  15926. // specific event
  15927. var callbacks = this._callbacks[event];
  15928. if (!callbacks) return this;
  15929. // remove all handlers
  15930. if (1 == arguments.length) {
  15931. delete this._callbacks[event];
  15932. return this;
  15933. }
  15934. // remove specific handler
  15935. var cb;
  15936. for (var i = 0; i < callbacks.length; i++) {
  15937. cb = callbacks[i];
  15938. if (cb === fn || cb.fn === fn) {
  15939. callbacks.splice(i, 1);
  15940. break;
  15941. }
  15942. }
  15943. return this;
  15944. };
  15945. /**
  15946. * Emit `event` with the given args.
  15947. *
  15948. * @param {String} event
  15949. * @param {Mixed} ...
  15950. * @return {Emitter}
  15951. */
  15952. Emitter.prototype.emit = function(event){
  15953. this._callbacks = this._callbacks || {};
  15954. var args = [].slice.call(arguments, 1)
  15955. , callbacks = this._callbacks[event];
  15956. if (callbacks) {
  15957. callbacks = callbacks.slice(0);
  15958. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15959. callbacks[i].apply(this, args);
  15960. }
  15961. }
  15962. return this;
  15963. };
  15964. /**
  15965. * Return array of callbacks for `event`.
  15966. *
  15967. * @param {String} event
  15968. * @return {Array}
  15969. * @api public
  15970. */
  15971. Emitter.prototype.listeners = function(event){
  15972. this._callbacks = this._callbacks || {};
  15973. return this._callbacks[event] || [];
  15974. };
  15975. /**
  15976. * Check if this emitter has `event` handlers.
  15977. *
  15978. * @param {String} event
  15979. * @return {Boolean}
  15980. * @api public
  15981. */
  15982. Emitter.prototype.hasListeners = function(event){
  15983. return !! this.listeners(event).length;
  15984. };
  15985. },{}],3:[function(require,module,exports){
  15986. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15987. * http://eightmedia.github.com/hammer.js
  15988. *
  15989. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  15990. * Licensed under the MIT license */
  15991. (function(window, undefined) {
  15992. 'use strict';
  15993. /**
  15994. * Hammer
  15995. * use this to create instances
  15996. * @param {HTMLElement} element
  15997. * @param {Object} options
  15998. * @returns {Hammer.Instance}
  15999. * @constructor
  16000. */
  16001. var Hammer = function(element, options) {
  16002. return new Hammer.Instance(element, options || {});
  16003. };
  16004. // default settings
  16005. Hammer.defaults = {
  16006. // add styles and attributes to the element to prevent the browser from doing
  16007. // its native behavior. this doesnt prevent the scrolling, but cancels
  16008. // the contextmenu, tap highlighting etc
  16009. // set to false to disable this
  16010. stop_browser_behavior: {
  16011. // this also triggers onselectstart=false for IE
  16012. userSelect: 'none',
  16013. // this makes the element blocking in IE10 >, you could experiment with the value
  16014. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  16015. touchAction: 'none',
  16016. touchCallout: 'none',
  16017. contentZooming: 'none',
  16018. userDrag: 'none',
  16019. tapHighlightColor: 'rgba(0,0,0,0)'
  16020. }
  16021. // more settings are defined per gesture at gestures.js
  16022. };
  16023. // detect touchevents
  16024. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  16025. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  16026. // dont use mouseevents on mobile devices
  16027. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  16028. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  16029. // eventtypes per touchevent (start, move, end)
  16030. // are filled by Hammer.event.determineEventTypes on setup
  16031. Hammer.EVENT_TYPES = {};
  16032. // direction defines
  16033. Hammer.DIRECTION_DOWN = 'down';
  16034. Hammer.DIRECTION_LEFT = 'left';
  16035. Hammer.DIRECTION_UP = 'up';
  16036. Hammer.DIRECTION_RIGHT = 'right';
  16037. // pointer type
  16038. Hammer.POINTER_MOUSE = 'mouse';
  16039. Hammer.POINTER_TOUCH = 'touch';
  16040. Hammer.POINTER_PEN = 'pen';
  16041. // touch event defines
  16042. Hammer.EVENT_START = 'start';
  16043. Hammer.EVENT_MOVE = 'move';
  16044. Hammer.EVENT_END = 'end';
  16045. // hammer document where the base events are added at
  16046. Hammer.DOCUMENT = document;
  16047. // plugins namespace
  16048. Hammer.plugins = {};
  16049. // if the window events are set...
  16050. Hammer.READY = false;
  16051. /**
  16052. * setup events to detect gestures on the document
  16053. */
  16054. function setup() {
  16055. if(Hammer.READY) {
  16056. return;
  16057. }
  16058. // find what eventtypes we add listeners to
  16059. Hammer.event.determineEventTypes();
  16060. // Register all gestures inside Hammer.gestures
  16061. for(var name in Hammer.gestures) {
  16062. if(Hammer.gestures.hasOwnProperty(name)) {
  16063. Hammer.detection.register(Hammer.gestures[name]);
  16064. }
  16065. }
  16066. // Add touch events on the document
  16067. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  16068. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  16069. // Hammer is ready...!
  16070. Hammer.READY = true;
  16071. }
  16072. /**
  16073. * create new hammer instance
  16074. * all methods should return the instance itself, so it is chainable.
  16075. * @param {HTMLElement} element
  16076. * @param {Object} [options={}]
  16077. * @returns {Hammer.Instance}
  16078. * @constructor
  16079. */
  16080. Hammer.Instance = function(element, options) {
  16081. var self = this;
  16082. // setup HammerJS window events and register all gestures
  16083. // this also sets up the default options
  16084. setup();
  16085. this.element = element;
  16086. // start/stop detection option
  16087. this.enabled = true;
  16088. // merge options
  16089. this.options = Hammer.utils.extend(
  16090. Hammer.utils.extend({}, Hammer.defaults),
  16091. options || {});
  16092. // add some css to the element to prevent the browser from doing its native behavoir
  16093. if(this.options.stop_browser_behavior) {
  16094. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  16095. }
  16096. // start detection on touchstart
  16097. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  16098. if(self.enabled) {
  16099. Hammer.detection.startDetect(self, ev);
  16100. }
  16101. });
  16102. // return instance
  16103. return this;
  16104. };
  16105. Hammer.Instance.prototype = {
  16106. /**
  16107. * bind events to the instance
  16108. * @param {String} gesture
  16109. * @param {Function} handler
  16110. * @returns {Hammer.Instance}
  16111. */
  16112. on: function onEvent(gesture, handler){
  16113. var gestures = gesture.split(' ');
  16114. for(var t=0; t<gestures.length; t++) {
  16115. this.element.addEventListener(gestures[t], handler, false);
  16116. }
  16117. return this;
  16118. },
  16119. /**
  16120. * unbind events to the instance
  16121. * @param {String} gesture
  16122. * @param {Function} handler
  16123. * @returns {Hammer.Instance}
  16124. */
  16125. off: function offEvent(gesture, handler){
  16126. var gestures = gesture.split(' ');
  16127. for(var t=0; t<gestures.length; t++) {
  16128. this.element.removeEventListener(gestures[t], handler, false);
  16129. }
  16130. return this;
  16131. },
  16132. /**
  16133. * trigger gesture event
  16134. * @param {String} gesture
  16135. * @param {Object} eventData
  16136. * @returns {Hammer.Instance}
  16137. */
  16138. trigger: function triggerEvent(gesture, eventData){
  16139. // create DOM event
  16140. var event = Hammer.DOCUMENT.createEvent('Event');
  16141. event.initEvent(gesture, true, true);
  16142. event.gesture = eventData;
  16143. // trigger on the target if it is in the instance element,
  16144. // this is for event delegation tricks
  16145. var element = this.element;
  16146. if(Hammer.utils.hasParent(eventData.target, element)) {
  16147. element = eventData.target;
  16148. }
  16149. element.dispatchEvent(event);
  16150. return this;
  16151. },
  16152. /**
  16153. * enable of disable hammer.js detection
  16154. * @param {Boolean} state
  16155. * @returns {Hammer.Instance}
  16156. */
  16157. enable: function enable(state) {
  16158. this.enabled = state;
  16159. return this;
  16160. }
  16161. };
  16162. /**
  16163. * this holds the last move event,
  16164. * used to fix empty touchend issue
  16165. * see the onTouch event for an explanation
  16166. * @type {Object}
  16167. */
  16168. var last_move_event = null;
  16169. /**
  16170. * when the mouse is hold down, this is true
  16171. * @type {Boolean}
  16172. */
  16173. var enable_detect = false;
  16174. /**
  16175. * when touch events have been fired, this is true
  16176. * @type {Boolean}
  16177. */
  16178. var touch_triggered = false;
  16179. Hammer.event = {
  16180. /**
  16181. * simple addEventListener
  16182. * @param {HTMLElement} element
  16183. * @param {String} type
  16184. * @param {Function} handler
  16185. */
  16186. bindDom: function(element, type, handler) {
  16187. var types = type.split(' ');
  16188. for(var t=0; t<types.length; t++) {
  16189. element.addEventListener(types[t], handler, false);
  16190. }
  16191. },
  16192. /**
  16193. * touch events with mouse fallback
  16194. * @param {HTMLElement} element
  16195. * @param {String} eventType like Hammer.EVENT_MOVE
  16196. * @param {Function} handler
  16197. */
  16198. onTouch: function onTouch(element, eventType, handler) {
  16199. var self = this;
  16200. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  16201. var sourceEventType = ev.type.toLowerCase();
  16202. // onmouseup, but when touchend has been fired we do nothing.
  16203. // this is for touchdevices which also fire a mouseup on touchend
  16204. if(sourceEventType.match(/mouse/) && touch_triggered) {
  16205. return;
  16206. }
  16207. // mousebutton must be down or a touch event
  16208. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  16209. sourceEventType.match(/pointerdown/) || // pointerevents touch
  16210. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  16211. ){
  16212. enable_detect = true;
  16213. }
  16214. // we are in a touch event, set the touch triggered bool to true,
  16215. // this for the conflicts that may occur on ios and android
  16216. if(sourceEventType.match(/touch|pointer/)) {
  16217. touch_triggered = true;
  16218. }
  16219. // count the total touches on the screen
  16220. var count_touches = 0;
  16221. // when touch has been triggered in this detection session
  16222. // and we are now handling a mouse event, we stop that to prevent conflicts
  16223. if(enable_detect) {
  16224. // update pointerevent
  16225. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  16226. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16227. }
  16228. // touch
  16229. else if(sourceEventType.match(/touch/)) {
  16230. count_touches = ev.touches.length;
  16231. }
  16232. // mouse
  16233. else if(!touch_triggered) {
  16234. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  16235. }
  16236. // if we are in a end event, but when we remove one touch and
  16237. // we still have enough, set eventType to move
  16238. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  16239. eventType = Hammer.EVENT_MOVE;
  16240. }
  16241. // no touches, force the end event
  16242. else if(!count_touches) {
  16243. eventType = Hammer.EVENT_END;
  16244. }
  16245. // because touchend has no touches, and we often want to use these in our gestures,
  16246. // we send the last move event as our eventData in touchend
  16247. if(!count_touches && last_move_event !== null) {
  16248. ev = last_move_event;
  16249. }
  16250. // store the last move event
  16251. else {
  16252. last_move_event = ev;
  16253. }
  16254. // trigger the handler
  16255. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  16256. // remove pointerevent from list
  16257. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  16258. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16259. }
  16260. }
  16261. //debug(sourceEventType +" "+ eventType);
  16262. // on the end we reset everything
  16263. if(!count_touches) {
  16264. last_move_event = null;
  16265. enable_detect = false;
  16266. touch_triggered = false;
  16267. Hammer.PointerEvent.reset();
  16268. }
  16269. });
  16270. },
  16271. /**
  16272. * we have different events for each device/browser
  16273. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  16274. */
  16275. determineEventTypes: function determineEventTypes() {
  16276. // determine the eventtype we want to set
  16277. var types;
  16278. // pointerEvents magic
  16279. if(Hammer.HAS_POINTEREVENTS) {
  16280. types = Hammer.PointerEvent.getEvents();
  16281. }
  16282. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  16283. else if(Hammer.NO_MOUSEEVENTS) {
  16284. types = [
  16285. 'touchstart',
  16286. 'touchmove',
  16287. 'touchend touchcancel'];
  16288. }
  16289. // for non pointer events browsers and mixed browsers,
  16290. // like chrome on windows8 touch laptop
  16291. else {
  16292. types = [
  16293. 'touchstart mousedown',
  16294. 'touchmove mousemove',
  16295. 'touchend touchcancel mouseup'];
  16296. }
  16297. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  16298. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  16299. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  16300. },
  16301. /**
  16302. * create touchlist depending on the event
  16303. * @param {Object} ev
  16304. * @param {String} eventType used by the fakemultitouch plugin
  16305. */
  16306. getTouchList: function getTouchList(ev/*, eventType*/) {
  16307. // get the fake pointerEvent touchlist
  16308. if(Hammer.HAS_POINTEREVENTS) {
  16309. return Hammer.PointerEvent.getTouchList();
  16310. }
  16311. // get the touchlist
  16312. else if(ev.touches) {
  16313. return ev.touches;
  16314. }
  16315. // make fake touchlist from mouse position
  16316. else {
  16317. return [{
  16318. identifier: 1,
  16319. pageX: ev.pageX,
  16320. pageY: ev.pageY,
  16321. target: ev.target
  16322. }];
  16323. }
  16324. },
  16325. /**
  16326. * collect event data for Hammer js
  16327. * @param {HTMLElement} element
  16328. * @param {String} eventType like Hammer.EVENT_MOVE
  16329. * @param {Object} eventData
  16330. */
  16331. collectEventData: function collectEventData(element, eventType, ev) {
  16332. var touches = this.getTouchList(ev, eventType);
  16333. // find out pointerType
  16334. var pointerType = Hammer.POINTER_TOUCH;
  16335. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  16336. pointerType = Hammer.POINTER_MOUSE;
  16337. }
  16338. return {
  16339. center : Hammer.utils.getCenter(touches),
  16340. timeStamp : new Date().getTime(),
  16341. target : ev.target,
  16342. touches : touches,
  16343. eventType : eventType,
  16344. pointerType : pointerType,
  16345. srcEvent : ev,
  16346. /**
  16347. * prevent the browser default actions
  16348. * mostly used to disable scrolling of the browser
  16349. */
  16350. preventDefault: function() {
  16351. if(this.srcEvent.preventManipulation) {
  16352. this.srcEvent.preventManipulation();
  16353. }
  16354. if(this.srcEvent.preventDefault) {
  16355. this.srcEvent.preventDefault();
  16356. }
  16357. },
  16358. /**
  16359. * stop bubbling the event up to its parents
  16360. */
  16361. stopPropagation: function() {
  16362. this.srcEvent.stopPropagation();
  16363. },
  16364. /**
  16365. * immediately stop gesture detection
  16366. * might be useful after a swipe was detected
  16367. * @return {*}
  16368. */
  16369. stopDetect: function() {
  16370. return Hammer.detection.stopDetect();
  16371. }
  16372. };
  16373. }
  16374. };
  16375. Hammer.PointerEvent = {
  16376. /**
  16377. * holds all pointers
  16378. * @type {Object}
  16379. */
  16380. pointers: {},
  16381. /**
  16382. * get a list of pointers
  16383. * @returns {Array} touchlist
  16384. */
  16385. getTouchList: function() {
  16386. var self = this;
  16387. var touchlist = [];
  16388. // we can use forEach since pointerEvents only is in IE10
  16389. Object.keys(self.pointers).sort().forEach(function(id) {
  16390. touchlist.push(self.pointers[id]);
  16391. });
  16392. return touchlist;
  16393. },
  16394. /**
  16395. * update the position of a pointer
  16396. * @param {String} type Hammer.EVENT_END
  16397. * @param {Object} pointerEvent
  16398. */
  16399. updatePointer: function(type, pointerEvent) {
  16400. if(type == Hammer.EVENT_END) {
  16401. this.pointers = {};
  16402. }
  16403. else {
  16404. pointerEvent.identifier = pointerEvent.pointerId;
  16405. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16406. }
  16407. return Object.keys(this.pointers).length;
  16408. },
  16409. /**
  16410. * check if ev matches pointertype
  16411. * @param {String} pointerType Hammer.POINTER_MOUSE
  16412. * @param {PointerEvent} ev
  16413. */
  16414. matchType: function(pointerType, ev) {
  16415. if(!ev.pointerType) {
  16416. return false;
  16417. }
  16418. var types = {};
  16419. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16420. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16421. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16422. return types[pointerType];
  16423. },
  16424. /**
  16425. * get events
  16426. */
  16427. getEvents: function() {
  16428. return [
  16429. 'pointerdown MSPointerDown',
  16430. 'pointermove MSPointerMove',
  16431. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16432. ];
  16433. },
  16434. /**
  16435. * reset the list
  16436. */
  16437. reset: function() {
  16438. this.pointers = {};
  16439. }
  16440. };
  16441. Hammer.utils = {
  16442. /**
  16443. * extend method,
  16444. * also used for cloning when dest is an empty object
  16445. * @param {Object} dest
  16446. * @param {Object} src
  16447. * @parm {Boolean} merge do a merge
  16448. * @returns {Object} dest
  16449. */
  16450. extend: function extend(dest, src, merge) {
  16451. for (var key in src) {
  16452. if(dest[key] !== undefined && merge) {
  16453. continue;
  16454. }
  16455. dest[key] = src[key];
  16456. }
  16457. return dest;
  16458. },
  16459. /**
  16460. * find if a node is in the given parent
  16461. * used for event delegation tricks
  16462. * @param {HTMLElement} node
  16463. * @param {HTMLElement} parent
  16464. * @returns {boolean} has_parent
  16465. */
  16466. hasParent: function(node, parent) {
  16467. while(node){
  16468. if(node == parent) {
  16469. return true;
  16470. }
  16471. node = node.parentNode;
  16472. }
  16473. return false;
  16474. },
  16475. /**
  16476. * get the center of all the touches
  16477. * @param {Array} touches
  16478. * @returns {Object} center
  16479. */
  16480. getCenter: function getCenter(touches) {
  16481. var valuesX = [], valuesY = [];
  16482. for(var t= 0,len=touches.length; t<len; t++) {
  16483. valuesX.push(touches[t].pageX);
  16484. valuesY.push(touches[t].pageY);
  16485. }
  16486. return {
  16487. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  16488. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  16489. };
  16490. },
  16491. /**
  16492. * calculate the velocity between two points
  16493. * @param {Number} delta_time
  16494. * @param {Number} delta_x
  16495. * @param {Number} delta_y
  16496. * @returns {Object} velocity
  16497. */
  16498. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  16499. return {
  16500. x: Math.abs(delta_x / delta_time) || 0,
  16501. y: Math.abs(delta_y / delta_time) || 0
  16502. };
  16503. },
  16504. /**
  16505. * calculate the angle between two coordinates
  16506. * @param {Touch} touch1
  16507. * @param {Touch} touch2
  16508. * @returns {Number} angle
  16509. */
  16510. getAngle: function getAngle(touch1, touch2) {
  16511. var y = touch2.pageY - touch1.pageY,
  16512. x = touch2.pageX - touch1.pageX;
  16513. return Math.atan2(y, x) * 180 / Math.PI;
  16514. },
  16515. /**
  16516. * angle to direction define
  16517. * @param {Touch} touch1
  16518. * @param {Touch} touch2
  16519. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  16520. */
  16521. getDirection: function getDirection(touch1, touch2) {
  16522. var x = Math.abs(touch1.pageX - touch2.pageX),
  16523. y = Math.abs(touch1.pageY - touch2.pageY);
  16524. if(x >= y) {
  16525. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16526. }
  16527. else {
  16528. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16529. }
  16530. },
  16531. /**
  16532. * calculate the distance between two touches
  16533. * @param {Touch} touch1
  16534. * @param {Touch} touch2
  16535. * @returns {Number} distance
  16536. */
  16537. getDistance: function getDistance(touch1, touch2) {
  16538. var x = touch2.pageX - touch1.pageX,
  16539. y = touch2.pageY - touch1.pageY;
  16540. return Math.sqrt((x*x) + (y*y));
  16541. },
  16542. /**
  16543. * calculate the scale factor between two touchLists (fingers)
  16544. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16545. * @param {Array} start
  16546. * @param {Array} end
  16547. * @returns {Number} scale
  16548. */
  16549. getScale: function getScale(start, end) {
  16550. // need two fingers...
  16551. if(start.length >= 2 && end.length >= 2) {
  16552. return this.getDistance(end[0], end[1]) /
  16553. this.getDistance(start[0], start[1]);
  16554. }
  16555. return 1;
  16556. },
  16557. /**
  16558. * calculate the rotation degrees between two touchLists (fingers)
  16559. * @param {Array} start
  16560. * @param {Array} end
  16561. * @returns {Number} rotation
  16562. */
  16563. getRotation: function getRotation(start, end) {
  16564. // need two fingers
  16565. if(start.length >= 2 && end.length >= 2) {
  16566. return this.getAngle(end[1], end[0]) -
  16567. this.getAngle(start[1], start[0]);
  16568. }
  16569. return 0;
  16570. },
  16571. /**
  16572. * boolean if the direction is vertical
  16573. * @param {String} direction
  16574. * @returns {Boolean} is_vertical
  16575. */
  16576. isVertical: function isVertical(direction) {
  16577. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16578. },
  16579. /**
  16580. * stop browser default behavior with css props
  16581. * @param {HtmlElement} element
  16582. * @param {Object} css_props
  16583. */
  16584. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16585. var prop,
  16586. vendors = ['webkit','khtml','moz','ms','o',''];
  16587. if(!css_props || !element.style) {
  16588. return;
  16589. }
  16590. // with css properties for modern browsers
  16591. for(var i = 0; i < vendors.length; i++) {
  16592. for(var p in css_props) {
  16593. if(css_props.hasOwnProperty(p)) {
  16594. prop = p;
  16595. // vender prefix at the property
  16596. if(vendors[i]) {
  16597. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16598. }
  16599. // set the style
  16600. element.style[prop] = css_props[p];
  16601. }
  16602. }
  16603. }
  16604. // also the disable onselectstart
  16605. if(css_props.userSelect == 'none') {
  16606. element.onselectstart = function() {
  16607. return false;
  16608. };
  16609. }
  16610. }
  16611. };
  16612. Hammer.detection = {
  16613. // contains all registred Hammer.gestures in the correct order
  16614. gestures: [],
  16615. // data of the current Hammer.gesture detection session
  16616. current: null,
  16617. // the previous Hammer.gesture session data
  16618. // is a full clone of the previous gesture.current object
  16619. previous: null,
  16620. // when this becomes true, no gestures are fired
  16621. stopped: false,
  16622. /**
  16623. * start Hammer.gesture detection
  16624. * @param {Hammer.Instance} inst
  16625. * @param {Object} eventData
  16626. */
  16627. startDetect: function startDetect(inst, eventData) {
  16628. // already busy with a Hammer.gesture detection on an element
  16629. if(this.current) {
  16630. return;
  16631. }
  16632. this.stopped = false;
  16633. this.current = {
  16634. inst : inst, // reference to HammerInstance we're working for
  16635. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16636. lastEvent : false, // last eventData
  16637. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16638. };
  16639. this.detect(eventData);
  16640. },
  16641. /**
  16642. * Hammer.gesture detection
  16643. * @param {Object} eventData
  16644. * @param {Object} eventData
  16645. */
  16646. detect: function detect(eventData) {
  16647. if(!this.current || this.stopped) {
  16648. return;
  16649. }
  16650. // extend event data with calculations about scale, distance etc
  16651. eventData = this.extendEventData(eventData);
  16652. // instance options
  16653. var inst_options = this.current.inst.options;
  16654. // call Hammer.gesture handlers
  16655. for(var g=0,len=this.gestures.length; g<len; g++) {
  16656. var gesture = this.gestures[g];
  16657. // only when the instance options have enabled this gesture
  16658. if(!this.stopped && inst_options[gesture.name] !== false) {
  16659. // if a handler returns false, we stop with the detection
  16660. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16661. this.stopDetect();
  16662. break;
  16663. }
  16664. }
  16665. }
  16666. // store as previous event event
  16667. if(this.current) {
  16668. this.current.lastEvent = eventData;
  16669. }
  16670. // endevent, but not the last touch, so dont stop
  16671. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16672. this.stopDetect();
  16673. }
  16674. return eventData;
  16675. },
  16676. /**
  16677. * clear the Hammer.gesture vars
  16678. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16679. * to stop other Hammer.gestures from being fired
  16680. */
  16681. stopDetect: function stopDetect() {
  16682. // clone current data to the store as the previous gesture
  16683. // used for the double tap gesture, since this is an other gesture detect session
  16684. this.previous = Hammer.utils.extend({}, this.current);
  16685. // reset the current
  16686. this.current = null;
  16687. // stopped!
  16688. this.stopped = true;
  16689. },
  16690. /**
  16691. * extend eventData for Hammer.gestures
  16692. * @param {Object} ev
  16693. * @returns {Object} ev
  16694. */
  16695. extendEventData: function extendEventData(ev) {
  16696. var startEv = this.current.startEvent;
  16697. // if the touches change, set the new touches over the startEvent touches
  16698. // this because touchevents don't have all the touches on touchstart, or the
  16699. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16700. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16701. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16702. // extend 1 level deep to get the touchlist with the touch objects
  16703. startEv.touches = [];
  16704. for(var i=0,len=ev.touches.length; i<len; i++) {
  16705. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16706. }
  16707. }
  16708. var delta_time = ev.timeStamp - startEv.timeStamp,
  16709. delta_x = ev.center.pageX - startEv.center.pageX,
  16710. delta_y = ev.center.pageY - startEv.center.pageY,
  16711. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16712. Hammer.utils.extend(ev, {
  16713. deltaTime : delta_time,
  16714. deltaX : delta_x,
  16715. deltaY : delta_y,
  16716. velocityX : velocity.x,
  16717. velocityY : velocity.y,
  16718. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16719. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16720. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16721. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16722. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16723. startEvent : startEv
  16724. });
  16725. return ev;
  16726. },
  16727. /**
  16728. * register new gesture
  16729. * @param {Object} gesture object, see gestures.js for documentation
  16730. * @returns {Array} gestures
  16731. */
  16732. register: function register(gesture) {
  16733. // add an enable gesture options if there is no given
  16734. var options = gesture.defaults || {};
  16735. if(options[gesture.name] === undefined) {
  16736. options[gesture.name] = true;
  16737. }
  16738. // extend Hammer default options with the Hammer.gesture options
  16739. Hammer.utils.extend(Hammer.defaults, options, true);
  16740. // set its index
  16741. gesture.index = gesture.index || 1000;
  16742. // add Hammer.gesture to the list
  16743. this.gestures.push(gesture);
  16744. // sort the list by index
  16745. this.gestures.sort(function(a, b) {
  16746. if (a.index < b.index) {
  16747. return -1;
  16748. }
  16749. if (a.index > b.index) {
  16750. return 1;
  16751. }
  16752. return 0;
  16753. });
  16754. return this.gestures;
  16755. }
  16756. };
  16757. Hammer.gestures = Hammer.gestures || {};
  16758. /**
  16759. * Custom gestures
  16760. * ==============================
  16761. *
  16762. * Gesture object
  16763. * --------------------
  16764. * The object structure of a gesture:
  16765. *
  16766. * { name: 'mygesture',
  16767. * index: 1337,
  16768. * defaults: {
  16769. * mygesture_option: true
  16770. * }
  16771. * handler: function(type, ev, inst) {
  16772. * // trigger gesture event
  16773. * inst.trigger(this.name, ev);
  16774. * }
  16775. * }
  16776. * @param {String} name
  16777. * this should be the name of the gesture, lowercase
  16778. * it is also being used to disable/enable the gesture per instance config.
  16779. *
  16780. * @param {Number} [index=1000]
  16781. * the index of the gesture, where it is going to be in the stack of gestures detection
  16782. * like when you build an gesture that depends on the drag gesture, it is a good
  16783. * idea to place it after the index of the drag gesture.
  16784. *
  16785. * @param {Object} [defaults={}]
  16786. * the default settings of the gesture. these are added to the instance settings,
  16787. * and can be overruled per instance. you can also add the name of the gesture,
  16788. * but this is also added by default (and set to true).
  16789. *
  16790. * @param {Function} handler
  16791. * this handles the gesture detection of your custom gesture and receives the
  16792. * following arguments:
  16793. *
  16794. * @param {Object} eventData
  16795. * event data containing the following properties:
  16796. * timeStamp {Number} time the event occurred
  16797. * target {HTMLElement} target element
  16798. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16799. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16800. * center {Object} center position of the touches. contains pageX and pageY
  16801. * deltaTime {Number} the total time of the touches in the screen
  16802. * deltaX {Number} the delta on x axis we haved moved
  16803. * deltaY {Number} the delta on y axis we haved moved
  16804. * velocityX {Number} the velocity on the x
  16805. * velocityY {Number} the velocity on y
  16806. * angle {Number} the angle we are moving
  16807. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16808. * distance {Number} the distance we haved moved
  16809. * scale {Number} scaling of the touches, needs 2 touches
  16810. * rotation {Number} rotation of the touches, needs 2 touches *
  16811. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16812. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16813. * startEvent {Object} contains the same properties as above,
  16814. * but from the first touch. this is used to calculate
  16815. * distances, deltaTime, scaling etc
  16816. *
  16817. * @param {Hammer.Instance} inst
  16818. * the instance we are doing the detection for. you can get the options from
  16819. * the inst.options object and trigger the gesture event by calling inst.trigger
  16820. *
  16821. *
  16822. * Handle gestures
  16823. * --------------------
  16824. * inside the handler you can get/set Hammer.detection.current. This is the current
  16825. * detection session. It has the following properties
  16826. * @param {String} name
  16827. * contains the name of the gesture we have detected. it has not a real function,
  16828. * only to check in other gestures if something is detected.
  16829. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16830. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16831. *
  16832. * @readonly
  16833. * @param {Hammer.Instance} inst
  16834. * the instance we do the detection for
  16835. *
  16836. * @readonly
  16837. * @param {Object} startEvent
  16838. * contains the properties of the first gesture detection in this session.
  16839. * Used for calculations about timing, distance, etc.
  16840. *
  16841. * @readonly
  16842. * @param {Object} lastEvent
  16843. * contains all the properties of the last gesture detect in this session.
  16844. *
  16845. * after the gesture detection session has been completed (user has released the screen)
  16846. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16847. * this is usefull for gestures like doubletap, where you need to know if the
  16848. * previous gesture was a tap
  16849. *
  16850. * options that have been set by the instance can be received by calling inst.options
  16851. *
  16852. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16853. * The first param is the name of your gesture, the second the event argument
  16854. *
  16855. *
  16856. * Register gestures
  16857. * --------------------
  16858. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16859. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16860. * manually and pass your gesture object as a param
  16861. *
  16862. */
  16863. /**
  16864. * Hold
  16865. * Touch stays at the same place for x time
  16866. * @events hold
  16867. */
  16868. Hammer.gestures.Hold = {
  16869. name: 'hold',
  16870. index: 10,
  16871. defaults: {
  16872. hold_timeout : 500,
  16873. hold_threshold : 1
  16874. },
  16875. timer: null,
  16876. handler: function holdGesture(ev, inst) {
  16877. switch(ev.eventType) {
  16878. case Hammer.EVENT_START:
  16879. // clear any running timers
  16880. clearTimeout(this.timer);
  16881. // set the gesture so we can check in the timeout if it still is
  16882. Hammer.detection.current.name = this.name;
  16883. // set timer and if after the timeout it still is hold,
  16884. // we trigger the hold event
  16885. this.timer = setTimeout(function() {
  16886. if(Hammer.detection.current.name == 'hold') {
  16887. inst.trigger('hold', ev);
  16888. }
  16889. }, inst.options.hold_timeout);
  16890. break;
  16891. // when you move or end we clear the timer
  16892. case Hammer.EVENT_MOVE:
  16893. if(ev.distance > inst.options.hold_threshold) {
  16894. clearTimeout(this.timer);
  16895. }
  16896. break;
  16897. case Hammer.EVENT_END:
  16898. clearTimeout(this.timer);
  16899. break;
  16900. }
  16901. }
  16902. };
  16903. /**
  16904. * Tap/DoubleTap
  16905. * Quick touch at a place or double at the same place
  16906. * @events tap, doubletap
  16907. */
  16908. Hammer.gestures.Tap = {
  16909. name: 'tap',
  16910. index: 100,
  16911. defaults: {
  16912. tap_max_touchtime : 250,
  16913. tap_max_distance : 10,
  16914. tap_always : true,
  16915. doubletap_distance : 20,
  16916. doubletap_interval : 300
  16917. },
  16918. handler: function tapGesture(ev, inst) {
  16919. if(ev.eventType == Hammer.EVENT_END) {
  16920. // previous gesture, for the double tap since these are two different gesture detections
  16921. var prev = Hammer.detection.previous,
  16922. did_doubletap = false;
  16923. // when the touchtime is higher then the max touch time
  16924. // or when the moving distance is too much
  16925. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16926. ev.distance > inst.options.tap_max_distance) {
  16927. return;
  16928. }
  16929. // check if double tap
  16930. if(prev && prev.name == 'tap' &&
  16931. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16932. ev.distance < inst.options.doubletap_distance) {
  16933. inst.trigger('doubletap', ev);
  16934. did_doubletap = true;
  16935. }
  16936. // do a single tap
  16937. if(!did_doubletap || inst.options.tap_always) {
  16938. Hammer.detection.current.name = 'tap';
  16939. inst.trigger(Hammer.detection.current.name, ev);
  16940. }
  16941. }
  16942. }
  16943. };
  16944. /**
  16945. * Swipe
  16946. * triggers swipe events when the end velocity is above the threshold
  16947. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16948. */
  16949. Hammer.gestures.Swipe = {
  16950. name: 'swipe',
  16951. index: 40,
  16952. defaults: {
  16953. // set 0 for unlimited, but this can conflict with transform
  16954. swipe_max_touches : 1,
  16955. swipe_velocity : 0.7
  16956. },
  16957. handler: function swipeGesture(ev, inst) {
  16958. if(ev.eventType == Hammer.EVENT_END) {
  16959. // max touches
  16960. if(inst.options.swipe_max_touches > 0 &&
  16961. ev.touches.length > inst.options.swipe_max_touches) {
  16962. return;
  16963. }
  16964. // when the distance we moved is too small we skip this gesture
  16965. // or we can be already in dragging
  16966. if(ev.velocityX > inst.options.swipe_velocity ||
  16967. ev.velocityY > inst.options.swipe_velocity) {
  16968. // trigger swipe events
  16969. inst.trigger(this.name, ev);
  16970. inst.trigger(this.name + ev.direction, ev);
  16971. }
  16972. }
  16973. }
  16974. };
  16975. /**
  16976. * Drag
  16977. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16978. * moving left and right is a good practice. When all the drag events are blocking
  16979. * you disable scrolling on that area.
  16980. * @events drag, drapleft, dragright, dragup, dragdown
  16981. */
  16982. Hammer.gestures.Drag = {
  16983. name: 'drag',
  16984. index: 50,
  16985. defaults: {
  16986. drag_min_distance : 10,
  16987. // set 0 for unlimited, but this can conflict with transform
  16988. drag_max_touches : 1,
  16989. // prevent default browser behavior when dragging occurs
  16990. // be careful with it, it makes the element a blocking element
  16991. // when you are using the drag gesture, it is a good practice to set this true
  16992. drag_block_horizontal : false,
  16993. drag_block_vertical : false,
  16994. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  16995. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  16996. drag_lock_to_axis : false,
  16997. // drag lock only kicks in when distance > drag_lock_min_distance
  16998. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  16999. drag_lock_min_distance : 25
  17000. },
  17001. triggered: false,
  17002. handler: function dragGesture(ev, inst) {
  17003. // current gesture isnt drag, but dragged is true
  17004. // this means an other gesture is busy. now call dragend
  17005. if(Hammer.detection.current.name != this.name && this.triggered) {
  17006. inst.trigger(this.name +'end', ev);
  17007. this.triggered = false;
  17008. return;
  17009. }
  17010. // max touches
  17011. if(inst.options.drag_max_touches > 0 &&
  17012. ev.touches.length > inst.options.drag_max_touches) {
  17013. return;
  17014. }
  17015. switch(ev.eventType) {
  17016. case Hammer.EVENT_START:
  17017. this.triggered = false;
  17018. break;
  17019. case Hammer.EVENT_MOVE:
  17020. // when the distance we moved is too small we skip this gesture
  17021. // or we can be already in dragging
  17022. if(ev.distance < inst.options.drag_min_distance &&
  17023. Hammer.detection.current.name != this.name) {
  17024. return;
  17025. }
  17026. // we are dragging!
  17027. Hammer.detection.current.name = this.name;
  17028. // lock drag to axis?
  17029. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  17030. ev.drag_locked_to_axis = true;
  17031. }
  17032. var last_direction = Hammer.detection.current.lastEvent.direction;
  17033. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  17034. // keep direction on the axis that the drag gesture started on
  17035. if(Hammer.utils.isVertical(last_direction)) {
  17036. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  17037. }
  17038. else {
  17039. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  17040. }
  17041. }
  17042. // first time, trigger dragstart event
  17043. if(!this.triggered) {
  17044. inst.trigger(this.name +'start', ev);
  17045. this.triggered = true;
  17046. }
  17047. // trigger normal event
  17048. inst.trigger(this.name, ev);
  17049. // direction event, like dragdown
  17050. inst.trigger(this.name + ev.direction, ev);
  17051. // block the browser events
  17052. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  17053. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  17054. ev.preventDefault();
  17055. }
  17056. break;
  17057. case Hammer.EVENT_END:
  17058. // trigger dragend
  17059. if(this.triggered) {
  17060. inst.trigger(this.name +'end', ev);
  17061. }
  17062. this.triggered = false;
  17063. break;
  17064. }
  17065. }
  17066. };
  17067. /**
  17068. * Transform
  17069. * User want to scale or rotate with 2 fingers
  17070. * @events transform, pinch, pinchin, pinchout, rotate
  17071. */
  17072. Hammer.gestures.Transform = {
  17073. name: 'transform',
  17074. index: 45,
  17075. defaults: {
  17076. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  17077. transform_min_scale : 0.01,
  17078. // rotation in degrees
  17079. transform_min_rotation : 1,
  17080. // prevent default browser behavior when two touches are on the screen
  17081. // but it makes the element a blocking element
  17082. // when you are using the transform gesture, it is a good practice to set this true
  17083. transform_always_block : false
  17084. },
  17085. triggered: false,
  17086. handler: function transformGesture(ev, inst) {
  17087. // current gesture isnt drag, but dragged is true
  17088. // this means an other gesture is busy. now call dragend
  17089. if(Hammer.detection.current.name != this.name && this.triggered) {
  17090. inst.trigger(this.name +'end', ev);
  17091. this.triggered = false;
  17092. return;
  17093. }
  17094. // atleast multitouch
  17095. if(ev.touches.length < 2) {
  17096. return;
  17097. }
  17098. // prevent default when two fingers are on the screen
  17099. if(inst.options.transform_always_block) {
  17100. ev.preventDefault();
  17101. }
  17102. switch(ev.eventType) {
  17103. case Hammer.EVENT_START:
  17104. this.triggered = false;
  17105. break;
  17106. case Hammer.EVENT_MOVE:
  17107. var scale_threshold = Math.abs(1-ev.scale);
  17108. var rotation_threshold = Math.abs(ev.rotation);
  17109. // when the distance we moved is too small we skip this gesture
  17110. // or we can be already in dragging
  17111. if(scale_threshold < inst.options.transform_min_scale &&
  17112. rotation_threshold < inst.options.transform_min_rotation) {
  17113. return;
  17114. }
  17115. // we are transforming!
  17116. Hammer.detection.current.name = this.name;
  17117. // first time, trigger dragstart event
  17118. if(!this.triggered) {
  17119. inst.trigger(this.name +'start', ev);
  17120. this.triggered = true;
  17121. }
  17122. inst.trigger(this.name, ev); // basic transform event
  17123. // trigger rotate event
  17124. if(rotation_threshold > inst.options.transform_min_rotation) {
  17125. inst.trigger('rotate', ev);
  17126. }
  17127. // trigger pinch event
  17128. if(scale_threshold > inst.options.transform_min_scale) {
  17129. inst.trigger('pinch', ev);
  17130. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  17131. }
  17132. break;
  17133. case Hammer.EVENT_END:
  17134. // trigger dragend
  17135. if(this.triggered) {
  17136. inst.trigger(this.name +'end', ev);
  17137. }
  17138. this.triggered = false;
  17139. break;
  17140. }
  17141. }
  17142. };
  17143. /**
  17144. * Touch
  17145. * Called as first, tells the user has touched the screen
  17146. * @events touch
  17147. */
  17148. Hammer.gestures.Touch = {
  17149. name: 'touch',
  17150. index: -Infinity,
  17151. defaults: {
  17152. // call preventDefault at touchstart, and makes the element blocking by
  17153. // disabling the scrolling of the page, but it improves gestures like
  17154. // transforming and dragging.
  17155. // be careful with using this, it can be very annoying for users to be stuck
  17156. // on the page
  17157. prevent_default: false,
  17158. // disable mouse events, so only touch (or pen!) input triggers events
  17159. prevent_mouseevents: false
  17160. },
  17161. handler: function touchGesture(ev, inst) {
  17162. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  17163. ev.stopDetect();
  17164. return;
  17165. }
  17166. if(inst.options.prevent_default) {
  17167. ev.preventDefault();
  17168. }
  17169. if(ev.eventType == Hammer.EVENT_START) {
  17170. inst.trigger(this.name, ev);
  17171. }
  17172. }
  17173. };
  17174. /**
  17175. * Release
  17176. * Called as last, tells the user has released the screen
  17177. * @events release
  17178. */
  17179. Hammer.gestures.Release = {
  17180. name: 'release',
  17181. index: Infinity,
  17182. handler: function releaseGesture(ev, inst) {
  17183. if(ev.eventType == Hammer.EVENT_END) {
  17184. inst.trigger(this.name, ev);
  17185. }
  17186. }
  17187. };
  17188. // node export
  17189. if(typeof module === 'object' && typeof module.exports === 'object'){
  17190. module.exports = Hammer;
  17191. }
  17192. // just window export
  17193. else {
  17194. window.Hammer = Hammer;
  17195. // requireJS module definition
  17196. if(typeof window.define === 'function' && window.define.amd) {
  17197. window.define('hammer', [], function() {
  17198. return Hammer;
  17199. });
  17200. }
  17201. }
  17202. })(this);
  17203. },{}],4:[function(require,module,exports){
  17204. //! moment.js
  17205. //! version : 2.5.1
  17206. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  17207. //! license : MIT
  17208. //! momentjs.com
  17209. (function (undefined) {
  17210. /************************************
  17211. Constants
  17212. ************************************/
  17213. var moment,
  17214. VERSION = "2.5.1",
  17215. global = this,
  17216. round = Math.round,
  17217. i,
  17218. YEAR = 0,
  17219. MONTH = 1,
  17220. DATE = 2,
  17221. HOUR = 3,
  17222. MINUTE = 4,
  17223. SECOND = 5,
  17224. MILLISECOND = 6,
  17225. // internal storage for language config files
  17226. languages = {},
  17227. // moment internal properties
  17228. momentProperties = {
  17229. _isAMomentObject: null,
  17230. _i : null,
  17231. _f : null,
  17232. _l : null,
  17233. _strict : null,
  17234. _isUTC : null,
  17235. _offset : null, // optional. Combine with _isUTC
  17236. _pf : null,
  17237. _lang : null // optional
  17238. },
  17239. // check for nodeJS
  17240. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  17241. // ASP.NET json date format regex
  17242. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  17243. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  17244. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  17245. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  17246. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  17247. // format tokens
  17248. formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,
  17249. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  17250. // parsing token regexes
  17251. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  17252. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  17253. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  17254. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  17255. parseTokenDigits = /\d+/, // nonzero number of digits
  17256. 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.
  17257. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  17258. parseTokenT = /T/i, // T (ISO separator)
  17259. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  17260. //strict parsing regexes
  17261. parseTokenOneDigit = /\d/, // 0 - 9
  17262. parseTokenTwoDigits = /\d\d/, // 00 - 99
  17263. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  17264. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  17265. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  17266. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  17267. // iso 8601 regex
  17268. // 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)
  17269. 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)?)?$/,
  17270. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  17271. isoDates = [
  17272. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  17273. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  17274. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  17275. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  17276. ['YYYY-DDD', /\d{4}-\d{3}/]
  17277. ],
  17278. // iso time formats and regexes
  17279. isoTimes = [
  17280. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  17281. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  17282. ['HH:mm', /(T| )\d\d:\d\d/],
  17283. ['HH', /(T| )\d\d/]
  17284. ],
  17285. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  17286. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  17287. // getter and setter names
  17288. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  17289. unitMillisecondFactors = {
  17290. 'Milliseconds' : 1,
  17291. 'Seconds' : 1e3,
  17292. 'Minutes' : 6e4,
  17293. 'Hours' : 36e5,
  17294. 'Days' : 864e5,
  17295. 'Months' : 2592e6,
  17296. 'Years' : 31536e6
  17297. },
  17298. unitAliases = {
  17299. ms : 'millisecond',
  17300. s : 'second',
  17301. m : 'minute',
  17302. h : 'hour',
  17303. d : 'day',
  17304. D : 'date',
  17305. w : 'week',
  17306. W : 'isoWeek',
  17307. M : 'month',
  17308. y : 'year',
  17309. DDD : 'dayOfYear',
  17310. e : 'weekday',
  17311. E : 'isoWeekday',
  17312. gg: 'weekYear',
  17313. GG: 'isoWeekYear'
  17314. },
  17315. camelFunctions = {
  17316. dayofyear : 'dayOfYear',
  17317. isoweekday : 'isoWeekday',
  17318. isoweek : 'isoWeek',
  17319. weekyear : 'weekYear',
  17320. isoweekyear : 'isoWeekYear'
  17321. },
  17322. // format function strings
  17323. formatFunctions = {},
  17324. // tokens to ordinalize and pad
  17325. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  17326. paddedTokens = 'M D H h m s w W'.split(' '),
  17327. formatTokenFunctions = {
  17328. M : function () {
  17329. return this.month() + 1;
  17330. },
  17331. MMM : function (format) {
  17332. return this.lang().monthsShort(this, format);
  17333. },
  17334. MMMM : function (format) {
  17335. return this.lang().months(this, format);
  17336. },
  17337. D : function () {
  17338. return this.date();
  17339. },
  17340. DDD : function () {
  17341. return this.dayOfYear();
  17342. },
  17343. d : function () {
  17344. return this.day();
  17345. },
  17346. dd : function (format) {
  17347. return this.lang().weekdaysMin(this, format);
  17348. },
  17349. ddd : function (format) {
  17350. return this.lang().weekdaysShort(this, format);
  17351. },
  17352. dddd : function (format) {
  17353. return this.lang().weekdays(this, format);
  17354. },
  17355. w : function () {
  17356. return this.week();
  17357. },
  17358. W : function () {
  17359. return this.isoWeek();
  17360. },
  17361. YY : function () {
  17362. return leftZeroFill(this.year() % 100, 2);
  17363. },
  17364. YYYY : function () {
  17365. return leftZeroFill(this.year(), 4);
  17366. },
  17367. YYYYY : function () {
  17368. return leftZeroFill(this.year(), 5);
  17369. },
  17370. YYYYYY : function () {
  17371. var y = this.year(), sign = y >= 0 ? '+' : '-';
  17372. return sign + leftZeroFill(Math.abs(y), 6);
  17373. },
  17374. gg : function () {
  17375. return leftZeroFill(this.weekYear() % 100, 2);
  17376. },
  17377. gggg : function () {
  17378. return leftZeroFill(this.weekYear(), 4);
  17379. },
  17380. ggggg : function () {
  17381. return leftZeroFill(this.weekYear(), 5);
  17382. },
  17383. GG : function () {
  17384. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17385. },
  17386. GGGG : function () {
  17387. return leftZeroFill(this.isoWeekYear(), 4);
  17388. },
  17389. GGGGG : function () {
  17390. return leftZeroFill(this.isoWeekYear(), 5);
  17391. },
  17392. e : function () {
  17393. return this.weekday();
  17394. },
  17395. E : function () {
  17396. return this.isoWeekday();
  17397. },
  17398. a : function () {
  17399. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17400. },
  17401. A : function () {
  17402. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17403. },
  17404. H : function () {
  17405. return this.hours();
  17406. },
  17407. h : function () {
  17408. return this.hours() % 12 || 12;
  17409. },
  17410. m : function () {
  17411. return this.minutes();
  17412. },
  17413. s : function () {
  17414. return this.seconds();
  17415. },
  17416. S : function () {
  17417. return toInt(this.milliseconds() / 100);
  17418. },
  17419. SS : function () {
  17420. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17421. },
  17422. SSS : function () {
  17423. return leftZeroFill(this.milliseconds(), 3);
  17424. },
  17425. SSSS : function () {
  17426. return leftZeroFill(this.milliseconds(), 3);
  17427. },
  17428. Z : function () {
  17429. var a = -this.zone(),
  17430. b = "+";
  17431. if (a < 0) {
  17432. a = -a;
  17433. b = "-";
  17434. }
  17435. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  17436. },
  17437. ZZ : function () {
  17438. var a = -this.zone(),
  17439. b = "+";
  17440. if (a < 0) {
  17441. a = -a;
  17442. b = "-";
  17443. }
  17444. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  17445. },
  17446. z : function () {
  17447. return this.zoneAbbr();
  17448. },
  17449. zz : function () {
  17450. return this.zoneName();
  17451. },
  17452. X : function () {
  17453. return this.unix();
  17454. },
  17455. Q : function () {
  17456. return this.quarter();
  17457. }
  17458. },
  17459. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  17460. function defaultParsingFlags() {
  17461. // We need to deep clone this object, and es5 standard is not very
  17462. // helpful.
  17463. return {
  17464. empty : false,
  17465. unusedTokens : [],
  17466. unusedInput : [],
  17467. overflow : -2,
  17468. charsLeftOver : 0,
  17469. nullInput : false,
  17470. invalidMonth : null,
  17471. invalidFormat : false,
  17472. userInvalidated : false,
  17473. iso: false
  17474. };
  17475. }
  17476. function padToken(func, count) {
  17477. return function (a) {
  17478. return leftZeroFill(func.call(this, a), count);
  17479. };
  17480. }
  17481. function ordinalizeToken(func, period) {
  17482. return function (a) {
  17483. return this.lang().ordinal(func.call(this, a), period);
  17484. };
  17485. }
  17486. while (ordinalizeTokens.length) {
  17487. i = ordinalizeTokens.pop();
  17488. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  17489. }
  17490. while (paddedTokens.length) {
  17491. i = paddedTokens.pop();
  17492. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  17493. }
  17494. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  17495. /************************************
  17496. Constructors
  17497. ************************************/
  17498. function Language() {
  17499. }
  17500. // Moment prototype object
  17501. function Moment(config) {
  17502. checkOverflow(config);
  17503. extend(this, config);
  17504. }
  17505. // Duration Constructor
  17506. function Duration(duration) {
  17507. var normalizedInput = normalizeObjectUnits(duration),
  17508. years = normalizedInput.year || 0,
  17509. months = normalizedInput.month || 0,
  17510. weeks = normalizedInput.week || 0,
  17511. days = normalizedInput.day || 0,
  17512. hours = normalizedInput.hour || 0,
  17513. minutes = normalizedInput.minute || 0,
  17514. seconds = normalizedInput.second || 0,
  17515. milliseconds = normalizedInput.millisecond || 0;
  17516. // representation for dateAddRemove
  17517. this._milliseconds = +milliseconds +
  17518. seconds * 1e3 + // 1000
  17519. minutes * 6e4 + // 1000 * 60
  17520. hours * 36e5; // 1000 * 60 * 60
  17521. // Because of dateAddRemove treats 24 hours as different from a
  17522. // day when working around DST, we need to store them separately
  17523. this._days = +days +
  17524. weeks * 7;
  17525. // It is impossible translate months into days without knowing
  17526. // which months you are are talking about, so we have to store
  17527. // it separately.
  17528. this._months = +months +
  17529. years * 12;
  17530. this._data = {};
  17531. this._bubble();
  17532. }
  17533. /************************************
  17534. Helpers
  17535. ************************************/
  17536. function extend(a, b) {
  17537. for (var i in b) {
  17538. if (b.hasOwnProperty(i)) {
  17539. a[i] = b[i];
  17540. }
  17541. }
  17542. if (b.hasOwnProperty("toString")) {
  17543. a.toString = b.toString;
  17544. }
  17545. if (b.hasOwnProperty("valueOf")) {
  17546. a.valueOf = b.valueOf;
  17547. }
  17548. return a;
  17549. }
  17550. function cloneMoment(m) {
  17551. var result = {}, i;
  17552. for (i in m) {
  17553. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17554. result[i] = m[i];
  17555. }
  17556. }
  17557. return result;
  17558. }
  17559. function absRound(number) {
  17560. if (number < 0) {
  17561. return Math.ceil(number);
  17562. } else {
  17563. return Math.floor(number);
  17564. }
  17565. }
  17566. // left zero fill a number
  17567. // see http://jsperf.com/left-zero-filling for performance comparison
  17568. function leftZeroFill(number, targetLength, forceSign) {
  17569. var output = '' + Math.abs(number),
  17570. sign = number >= 0;
  17571. while (output.length < targetLength) {
  17572. output = '0' + output;
  17573. }
  17574. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17575. }
  17576. // helper function for _.addTime and _.subtractTime
  17577. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  17578. var milliseconds = duration._milliseconds,
  17579. days = duration._days,
  17580. months = duration._months,
  17581. minutes,
  17582. hours;
  17583. if (milliseconds) {
  17584. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17585. }
  17586. // store the minutes and hours so we can restore them
  17587. if (days || months) {
  17588. minutes = mom.minute();
  17589. hours = mom.hour();
  17590. }
  17591. if (days) {
  17592. mom.date(mom.date() + days * isAdding);
  17593. }
  17594. if (months) {
  17595. mom.month(mom.month() + months * isAdding);
  17596. }
  17597. if (milliseconds && !ignoreUpdateOffset) {
  17598. moment.updateOffset(mom);
  17599. }
  17600. // restore the minutes and hours after possibly changing dst
  17601. if (days || months) {
  17602. mom.minute(minutes);
  17603. mom.hour(hours);
  17604. }
  17605. }
  17606. // check if is an array
  17607. function isArray(input) {
  17608. return Object.prototype.toString.call(input) === '[object Array]';
  17609. }
  17610. function isDate(input) {
  17611. return Object.prototype.toString.call(input) === '[object Date]' ||
  17612. input instanceof Date;
  17613. }
  17614. // compare two arrays, return the number of differences
  17615. function compareArrays(array1, array2, dontConvert) {
  17616. var len = Math.min(array1.length, array2.length),
  17617. lengthDiff = Math.abs(array1.length - array2.length),
  17618. diffs = 0,
  17619. i;
  17620. for (i = 0; i < len; i++) {
  17621. if ((dontConvert && array1[i] !== array2[i]) ||
  17622. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17623. diffs++;
  17624. }
  17625. }
  17626. return diffs + lengthDiff;
  17627. }
  17628. function normalizeUnits(units) {
  17629. if (units) {
  17630. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17631. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17632. }
  17633. return units;
  17634. }
  17635. function normalizeObjectUnits(inputObject) {
  17636. var normalizedInput = {},
  17637. normalizedProp,
  17638. prop;
  17639. for (prop in inputObject) {
  17640. if (inputObject.hasOwnProperty(prop)) {
  17641. normalizedProp = normalizeUnits(prop);
  17642. if (normalizedProp) {
  17643. normalizedInput[normalizedProp] = inputObject[prop];
  17644. }
  17645. }
  17646. }
  17647. return normalizedInput;
  17648. }
  17649. function makeList(field) {
  17650. var count, setter;
  17651. if (field.indexOf('week') === 0) {
  17652. count = 7;
  17653. setter = 'day';
  17654. }
  17655. else if (field.indexOf('month') === 0) {
  17656. count = 12;
  17657. setter = 'month';
  17658. }
  17659. else {
  17660. return;
  17661. }
  17662. moment[field] = function (format, index) {
  17663. var i, getter,
  17664. method = moment.fn._lang[field],
  17665. results = [];
  17666. if (typeof format === 'number') {
  17667. index = format;
  17668. format = undefined;
  17669. }
  17670. getter = function (i) {
  17671. var m = moment().utc().set(setter, i);
  17672. return method.call(moment.fn._lang, m, format || '');
  17673. };
  17674. if (index != null) {
  17675. return getter(index);
  17676. }
  17677. else {
  17678. for (i = 0; i < count; i++) {
  17679. results.push(getter(i));
  17680. }
  17681. return results;
  17682. }
  17683. };
  17684. }
  17685. function toInt(argumentForCoercion) {
  17686. var coercedNumber = +argumentForCoercion,
  17687. value = 0;
  17688. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17689. if (coercedNumber >= 0) {
  17690. value = Math.floor(coercedNumber);
  17691. } else {
  17692. value = Math.ceil(coercedNumber);
  17693. }
  17694. }
  17695. return value;
  17696. }
  17697. function daysInMonth(year, month) {
  17698. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17699. }
  17700. function daysInYear(year) {
  17701. return isLeapYear(year) ? 366 : 365;
  17702. }
  17703. function isLeapYear(year) {
  17704. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17705. }
  17706. function checkOverflow(m) {
  17707. var overflow;
  17708. if (m._a && m._pf.overflow === -2) {
  17709. overflow =
  17710. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17711. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17712. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17713. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17714. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17715. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17716. -1;
  17717. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17718. overflow = DATE;
  17719. }
  17720. m._pf.overflow = overflow;
  17721. }
  17722. }
  17723. function isValid(m) {
  17724. if (m._isValid == null) {
  17725. m._isValid = !isNaN(m._d.getTime()) &&
  17726. m._pf.overflow < 0 &&
  17727. !m._pf.empty &&
  17728. !m._pf.invalidMonth &&
  17729. !m._pf.nullInput &&
  17730. !m._pf.invalidFormat &&
  17731. !m._pf.userInvalidated;
  17732. if (m._strict) {
  17733. m._isValid = m._isValid &&
  17734. m._pf.charsLeftOver === 0 &&
  17735. m._pf.unusedTokens.length === 0;
  17736. }
  17737. }
  17738. return m._isValid;
  17739. }
  17740. function normalizeLanguage(key) {
  17741. return key ? key.toLowerCase().replace('_', '-') : key;
  17742. }
  17743. // Return a moment from input, that is local/utc/zone equivalent to model.
  17744. function makeAs(input, model) {
  17745. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17746. moment(input).local();
  17747. }
  17748. /************************************
  17749. Languages
  17750. ************************************/
  17751. extend(Language.prototype, {
  17752. set : function (config) {
  17753. var prop, i;
  17754. for (i in config) {
  17755. prop = config[i];
  17756. if (typeof prop === 'function') {
  17757. this[i] = prop;
  17758. } else {
  17759. this['_' + i] = prop;
  17760. }
  17761. }
  17762. },
  17763. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17764. months : function (m) {
  17765. return this._months[m.month()];
  17766. },
  17767. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17768. monthsShort : function (m) {
  17769. return this._monthsShort[m.month()];
  17770. },
  17771. monthsParse : function (monthName) {
  17772. var i, mom, regex;
  17773. if (!this._monthsParse) {
  17774. this._monthsParse = [];
  17775. }
  17776. for (i = 0; i < 12; i++) {
  17777. // make the regex if we don't have it already
  17778. if (!this._monthsParse[i]) {
  17779. mom = moment.utc([2000, i]);
  17780. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17781. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17782. }
  17783. // test the regex
  17784. if (this._monthsParse[i].test(monthName)) {
  17785. return i;
  17786. }
  17787. }
  17788. },
  17789. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17790. weekdays : function (m) {
  17791. return this._weekdays[m.day()];
  17792. },
  17793. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17794. weekdaysShort : function (m) {
  17795. return this._weekdaysShort[m.day()];
  17796. },
  17797. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17798. weekdaysMin : function (m) {
  17799. return this._weekdaysMin[m.day()];
  17800. },
  17801. weekdaysParse : function (weekdayName) {
  17802. var i, mom, regex;
  17803. if (!this._weekdaysParse) {
  17804. this._weekdaysParse = [];
  17805. }
  17806. for (i = 0; i < 7; i++) {
  17807. // make the regex if we don't have it already
  17808. if (!this._weekdaysParse[i]) {
  17809. mom = moment([2000, 1]).day(i);
  17810. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17811. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17812. }
  17813. // test the regex
  17814. if (this._weekdaysParse[i].test(weekdayName)) {
  17815. return i;
  17816. }
  17817. }
  17818. },
  17819. _longDateFormat : {
  17820. LT : "h:mm A",
  17821. L : "MM/DD/YYYY",
  17822. LL : "MMMM D YYYY",
  17823. LLL : "MMMM D YYYY LT",
  17824. LLLL : "dddd, MMMM D YYYY LT"
  17825. },
  17826. longDateFormat : function (key) {
  17827. var output = this._longDateFormat[key];
  17828. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17829. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17830. return val.slice(1);
  17831. });
  17832. this._longDateFormat[key] = output;
  17833. }
  17834. return output;
  17835. },
  17836. isPM : function (input) {
  17837. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17838. // Using charAt should be more compatible.
  17839. return ((input + '').toLowerCase().charAt(0) === 'p');
  17840. },
  17841. _meridiemParse : /[ap]\.?m?\.?/i,
  17842. meridiem : function (hours, minutes, isLower) {
  17843. if (hours > 11) {
  17844. return isLower ? 'pm' : 'PM';
  17845. } else {
  17846. return isLower ? 'am' : 'AM';
  17847. }
  17848. },
  17849. _calendar : {
  17850. sameDay : '[Today at] LT',
  17851. nextDay : '[Tomorrow at] LT',
  17852. nextWeek : 'dddd [at] LT',
  17853. lastDay : '[Yesterday at] LT',
  17854. lastWeek : '[Last] dddd [at] LT',
  17855. sameElse : 'L'
  17856. },
  17857. calendar : function (key, mom) {
  17858. var output = this._calendar[key];
  17859. return typeof output === 'function' ? output.apply(mom) : output;
  17860. },
  17861. _relativeTime : {
  17862. future : "in %s",
  17863. past : "%s ago",
  17864. s : "a few seconds",
  17865. m : "a minute",
  17866. mm : "%d minutes",
  17867. h : "an hour",
  17868. hh : "%d hours",
  17869. d : "a day",
  17870. dd : "%d days",
  17871. M : "a month",
  17872. MM : "%d months",
  17873. y : "a year",
  17874. yy : "%d years"
  17875. },
  17876. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17877. var output = this._relativeTime[string];
  17878. return (typeof output === 'function') ?
  17879. output(number, withoutSuffix, string, isFuture) :
  17880. output.replace(/%d/i, number);
  17881. },
  17882. pastFuture : function (diff, output) {
  17883. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17884. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17885. },
  17886. ordinal : function (number) {
  17887. return this._ordinal.replace("%d", number);
  17888. },
  17889. _ordinal : "%d",
  17890. preparse : function (string) {
  17891. return string;
  17892. },
  17893. postformat : function (string) {
  17894. return string;
  17895. },
  17896. week : function (mom) {
  17897. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17898. },
  17899. _week : {
  17900. dow : 0, // Sunday is the first day of the week.
  17901. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17902. },
  17903. _invalidDate: 'Invalid date',
  17904. invalidDate: function () {
  17905. return this._invalidDate;
  17906. }
  17907. });
  17908. // Loads a language definition into the `languages` cache. The function
  17909. // takes a key and optionally values. If not in the browser and no values
  17910. // are provided, it will load the language file module. As a convenience,
  17911. // this function also returns the language values.
  17912. function loadLang(key, values) {
  17913. values.abbr = key;
  17914. if (!languages[key]) {
  17915. languages[key] = new Language();
  17916. }
  17917. languages[key].set(values);
  17918. return languages[key];
  17919. }
  17920. // Remove a language from the `languages` cache. Mostly useful in tests.
  17921. function unloadLang(key) {
  17922. delete languages[key];
  17923. }
  17924. // Determines which language definition to use and returns it.
  17925. //
  17926. // With no parameters, it will return the global language. If you
  17927. // pass in a language key, such as 'en', it will return the
  17928. // definition for 'en', so long as 'en' has already been loaded using
  17929. // moment.lang.
  17930. function getLangDefinition(key) {
  17931. var i = 0, j, lang, next, split,
  17932. get = function (k) {
  17933. if (!languages[k] && hasModule) {
  17934. try {
  17935. require('./lang/' + k);
  17936. } catch (e) { }
  17937. }
  17938. return languages[k];
  17939. };
  17940. if (!key) {
  17941. return moment.fn._lang;
  17942. }
  17943. if (!isArray(key)) {
  17944. //short-circuit everything else
  17945. lang = get(key);
  17946. if (lang) {
  17947. return lang;
  17948. }
  17949. key = [key];
  17950. }
  17951. //pick the language from the array
  17952. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17953. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17954. while (i < key.length) {
  17955. split = normalizeLanguage(key[i]).split('-');
  17956. j = split.length;
  17957. next = normalizeLanguage(key[i + 1]);
  17958. next = next ? next.split('-') : null;
  17959. while (j > 0) {
  17960. lang = get(split.slice(0, j).join('-'));
  17961. if (lang) {
  17962. return lang;
  17963. }
  17964. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17965. //the next array item is better than a shallower substring of this one
  17966. break;
  17967. }
  17968. j--;
  17969. }
  17970. i++;
  17971. }
  17972. return moment.fn._lang;
  17973. }
  17974. /************************************
  17975. Formatting
  17976. ************************************/
  17977. function removeFormattingTokens(input) {
  17978. if (input.match(/\[[\s\S]/)) {
  17979. return input.replace(/^\[|\]$/g, "");
  17980. }
  17981. return input.replace(/\\/g, "");
  17982. }
  17983. function makeFormatFunction(format) {
  17984. var array = format.match(formattingTokens), i, length;
  17985. for (i = 0, length = array.length; i < length; i++) {
  17986. if (formatTokenFunctions[array[i]]) {
  17987. array[i] = formatTokenFunctions[array[i]];
  17988. } else {
  17989. array[i] = removeFormattingTokens(array[i]);
  17990. }
  17991. }
  17992. return function (mom) {
  17993. var output = "";
  17994. for (i = 0; i < length; i++) {
  17995. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  17996. }
  17997. return output;
  17998. };
  17999. }
  18000. // format date using native date object
  18001. function formatMoment(m, format) {
  18002. if (!m.isValid()) {
  18003. return m.lang().invalidDate();
  18004. }
  18005. format = expandFormat(format, m.lang());
  18006. if (!formatFunctions[format]) {
  18007. formatFunctions[format] = makeFormatFunction(format);
  18008. }
  18009. return formatFunctions[format](m);
  18010. }
  18011. function expandFormat(format, lang) {
  18012. var i = 5;
  18013. function replaceLongDateFormatTokens(input) {
  18014. return lang.longDateFormat(input) || input;
  18015. }
  18016. localFormattingTokens.lastIndex = 0;
  18017. while (i >= 0 && localFormattingTokens.test(format)) {
  18018. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  18019. localFormattingTokens.lastIndex = 0;
  18020. i -= 1;
  18021. }
  18022. return format;
  18023. }
  18024. /************************************
  18025. Parsing
  18026. ************************************/
  18027. // get the regex to find the next token
  18028. function getParseRegexForToken(token, config) {
  18029. var a, strict = config._strict;
  18030. switch (token) {
  18031. case 'DDDD':
  18032. return parseTokenThreeDigits;
  18033. case 'YYYY':
  18034. case 'GGGG':
  18035. case 'gggg':
  18036. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  18037. case 'Y':
  18038. case 'G':
  18039. case 'g':
  18040. return parseTokenSignedNumber;
  18041. case 'YYYYYY':
  18042. case 'YYYYY':
  18043. case 'GGGGG':
  18044. case 'ggggg':
  18045. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  18046. case 'S':
  18047. if (strict) { return parseTokenOneDigit; }
  18048. /* falls through */
  18049. case 'SS':
  18050. if (strict) { return parseTokenTwoDigits; }
  18051. /* falls through */
  18052. case 'SSS':
  18053. if (strict) { return parseTokenThreeDigits; }
  18054. /* falls through */
  18055. case 'DDD':
  18056. return parseTokenOneToThreeDigits;
  18057. case 'MMM':
  18058. case 'MMMM':
  18059. case 'dd':
  18060. case 'ddd':
  18061. case 'dddd':
  18062. return parseTokenWord;
  18063. case 'a':
  18064. case 'A':
  18065. return getLangDefinition(config._l)._meridiemParse;
  18066. case 'X':
  18067. return parseTokenTimestampMs;
  18068. case 'Z':
  18069. case 'ZZ':
  18070. return parseTokenTimezone;
  18071. case 'T':
  18072. return parseTokenT;
  18073. case 'SSSS':
  18074. return parseTokenDigits;
  18075. case 'MM':
  18076. case 'DD':
  18077. case 'YY':
  18078. case 'GG':
  18079. case 'gg':
  18080. case 'HH':
  18081. case 'hh':
  18082. case 'mm':
  18083. case 'ss':
  18084. case 'ww':
  18085. case 'WW':
  18086. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  18087. case 'M':
  18088. case 'D':
  18089. case 'd':
  18090. case 'H':
  18091. case 'h':
  18092. case 'm':
  18093. case 's':
  18094. case 'w':
  18095. case 'W':
  18096. case 'e':
  18097. case 'E':
  18098. return parseTokenOneOrTwoDigits;
  18099. default :
  18100. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  18101. return a;
  18102. }
  18103. }
  18104. function timezoneMinutesFromString(string) {
  18105. string = string || "";
  18106. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  18107. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  18108. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  18109. minutes = +(parts[1] * 60) + toInt(parts[2]);
  18110. return parts[0] === '+' ? -minutes : minutes;
  18111. }
  18112. // function to convert string input to date
  18113. function addTimeToArrayFromToken(token, input, config) {
  18114. var a, datePartArray = config._a;
  18115. switch (token) {
  18116. // MONTH
  18117. case 'M' : // fall through to MM
  18118. case 'MM' :
  18119. if (input != null) {
  18120. datePartArray[MONTH] = toInt(input) - 1;
  18121. }
  18122. break;
  18123. case 'MMM' : // fall through to MMMM
  18124. case 'MMMM' :
  18125. a = getLangDefinition(config._l).monthsParse(input);
  18126. // if we didn't find a month name, mark the date as invalid.
  18127. if (a != null) {
  18128. datePartArray[MONTH] = a;
  18129. } else {
  18130. config._pf.invalidMonth = input;
  18131. }
  18132. break;
  18133. // DAY OF MONTH
  18134. case 'D' : // fall through to DD
  18135. case 'DD' :
  18136. if (input != null) {
  18137. datePartArray[DATE] = toInt(input);
  18138. }
  18139. break;
  18140. // DAY OF YEAR
  18141. case 'DDD' : // fall through to DDDD
  18142. case 'DDDD' :
  18143. if (input != null) {
  18144. config._dayOfYear = toInt(input);
  18145. }
  18146. break;
  18147. // YEAR
  18148. case 'YY' :
  18149. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  18150. break;
  18151. case 'YYYY' :
  18152. case 'YYYYY' :
  18153. case 'YYYYYY' :
  18154. datePartArray[YEAR] = toInt(input);
  18155. break;
  18156. // AM / PM
  18157. case 'a' : // fall through to A
  18158. case 'A' :
  18159. config._isPm = getLangDefinition(config._l).isPM(input);
  18160. break;
  18161. // 24 HOUR
  18162. case 'H' : // fall through to hh
  18163. case 'HH' : // fall through to hh
  18164. case 'h' : // fall through to hh
  18165. case 'hh' :
  18166. datePartArray[HOUR] = toInt(input);
  18167. break;
  18168. // MINUTE
  18169. case 'm' : // fall through to mm
  18170. case 'mm' :
  18171. datePartArray[MINUTE] = toInt(input);
  18172. break;
  18173. // SECOND
  18174. case 's' : // fall through to ss
  18175. case 'ss' :
  18176. datePartArray[SECOND] = toInt(input);
  18177. break;
  18178. // MILLISECOND
  18179. case 'S' :
  18180. case 'SS' :
  18181. case 'SSS' :
  18182. case 'SSSS' :
  18183. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  18184. break;
  18185. // UNIX TIMESTAMP WITH MS
  18186. case 'X':
  18187. config._d = new Date(parseFloat(input) * 1000);
  18188. break;
  18189. // TIMEZONE
  18190. case 'Z' : // fall through to ZZ
  18191. case 'ZZ' :
  18192. config._useUTC = true;
  18193. config._tzm = timezoneMinutesFromString(input);
  18194. break;
  18195. case 'w':
  18196. case 'ww':
  18197. case 'W':
  18198. case 'WW':
  18199. case 'd':
  18200. case 'dd':
  18201. case 'ddd':
  18202. case 'dddd':
  18203. case 'e':
  18204. case 'E':
  18205. token = token.substr(0, 1);
  18206. /* falls through */
  18207. case 'gg':
  18208. case 'gggg':
  18209. case 'GG':
  18210. case 'GGGG':
  18211. case 'GGGGG':
  18212. token = token.substr(0, 2);
  18213. if (input) {
  18214. config._w = config._w || {};
  18215. config._w[token] = input;
  18216. }
  18217. break;
  18218. }
  18219. }
  18220. // convert an array to a date.
  18221. // the array should mirror the parameters below
  18222. // note: all values past the year are optional and will default to the lowest possible value.
  18223. // [year, month, day , hour, minute, second, millisecond]
  18224. function dateFromConfig(config) {
  18225. var i, date, input = [], currentDate,
  18226. yearToUse, fixYear, w, temp, lang, weekday, week;
  18227. if (config._d) {
  18228. return;
  18229. }
  18230. currentDate = currentDateArray(config);
  18231. //compute day of the year from weeks and weekdays
  18232. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  18233. fixYear = function (val) {
  18234. var int_val = parseInt(val, 10);
  18235. return val ?
  18236. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  18237. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  18238. };
  18239. w = config._w;
  18240. if (w.GG != null || w.W != null || w.E != null) {
  18241. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  18242. }
  18243. else {
  18244. lang = getLangDefinition(config._l);
  18245. weekday = w.d != null ? parseWeekday(w.d, lang) :
  18246. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  18247. week = parseInt(w.w, 10) || 1;
  18248. //if we're parsing 'd', then the low day numbers may be next week
  18249. if (w.d != null && weekday < lang._week.dow) {
  18250. week++;
  18251. }
  18252. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  18253. }
  18254. config._a[YEAR] = temp.year;
  18255. config._dayOfYear = temp.dayOfYear;
  18256. }
  18257. //if the day of the year is set, figure out what it is
  18258. if (config._dayOfYear) {
  18259. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  18260. if (config._dayOfYear > daysInYear(yearToUse)) {
  18261. config._pf._overflowDayOfYear = true;
  18262. }
  18263. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  18264. config._a[MONTH] = date.getUTCMonth();
  18265. config._a[DATE] = date.getUTCDate();
  18266. }
  18267. // Default to current date.
  18268. // * if no year, month, day of month are given, default to today
  18269. // * if day of month is given, default month and year
  18270. // * if month is given, default only year
  18271. // * if year is given, don't default anything
  18272. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  18273. config._a[i] = input[i] = currentDate[i];
  18274. }
  18275. // Zero out whatever was not defaulted, including time
  18276. for (; i < 7; i++) {
  18277. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  18278. }
  18279. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  18280. input[HOUR] += toInt((config._tzm || 0) / 60);
  18281. input[MINUTE] += toInt((config._tzm || 0) % 60);
  18282. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  18283. }
  18284. function dateFromObject(config) {
  18285. var normalizedInput;
  18286. if (config._d) {
  18287. return;
  18288. }
  18289. normalizedInput = normalizeObjectUnits(config._i);
  18290. config._a = [
  18291. normalizedInput.year,
  18292. normalizedInput.month,
  18293. normalizedInput.day,
  18294. normalizedInput.hour,
  18295. normalizedInput.minute,
  18296. normalizedInput.second,
  18297. normalizedInput.millisecond
  18298. ];
  18299. dateFromConfig(config);
  18300. }
  18301. function currentDateArray(config) {
  18302. var now = new Date();
  18303. if (config._useUTC) {
  18304. return [
  18305. now.getUTCFullYear(),
  18306. now.getUTCMonth(),
  18307. now.getUTCDate()
  18308. ];
  18309. } else {
  18310. return [now.getFullYear(), now.getMonth(), now.getDate()];
  18311. }
  18312. }
  18313. // date from string and format string
  18314. function makeDateFromStringAndFormat(config) {
  18315. config._a = [];
  18316. config._pf.empty = true;
  18317. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  18318. var lang = getLangDefinition(config._l),
  18319. string = '' + config._i,
  18320. i, parsedInput, tokens, token, skipped,
  18321. stringLength = string.length,
  18322. totalParsedInputLength = 0;
  18323. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  18324. for (i = 0; i < tokens.length; i++) {
  18325. token = tokens[i];
  18326. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  18327. if (parsedInput) {
  18328. skipped = string.substr(0, string.indexOf(parsedInput));
  18329. if (skipped.length > 0) {
  18330. config._pf.unusedInput.push(skipped);
  18331. }
  18332. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  18333. totalParsedInputLength += parsedInput.length;
  18334. }
  18335. // don't parse if it's not a known token
  18336. if (formatTokenFunctions[token]) {
  18337. if (parsedInput) {
  18338. config._pf.empty = false;
  18339. }
  18340. else {
  18341. config._pf.unusedTokens.push(token);
  18342. }
  18343. addTimeToArrayFromToken(token, parsedInput, config);
  18344. }
  18345. else if (config._strict && !parsedInput) {
  18346. config._pf.unusedTokens.push(token);
  18347. }
  18348. }
  18349. // add remaining unparsed input length to the string
  18350. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  18351. if (string.length > 0) {
  18352. config._pf.unusedInput.push(string);
  18353. }
  18354. // handle am pm
  18355. if (config._isPm && config._a[HOUR] < 12) {
  18356. config._a[HOUR] += 12;
  18357. }
  18358. // if is 12 am, change hours to 0
  18359. if (config._isPm === false && config._a[HOUR] === 12) {
  18360. config._a[HOUR] = 0;
  18361. }
  18362. dateFromConfig(config);
  18363. checkOverflow(config);
  18364. }
  18365. function unescapeFormat(s) {
  18366. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  18367. return p1 || p2 || p3 || p4;
  18368. });
  18369. }
  18370. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  18371. function regexpEscape(s) {
  18372. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18373. }
  18374. // date from string and array of format strings
  18375. function makeDateFromStringAndArray(config) {
  18376. var tempConfig,
  18377. bestMoment,
  18378. scoreToBeat,
  18379. i,
  18380. currentScore;
  18381. if (config._f.length === 0) {
  18382. config._pf.invalidFormat = true;
  18383. config._d = new Date(NaN);
  18384. return;
  18385. }
  18386. for (i = 0; i < config._f.length; i++) {
  18387. currentScore = 0;
  18388. tempConfig = extend({}, config);
  18389. tempConfig._pf = defaultParsingFlags();
  18390. tempConfig._f = config._f[i];
  18391. makeDateFromStringAndFormat(tempConfig);
  18392. if (!isValid(tempConfig)) {
  18393. continue;
  18394. }
  18395. // if there is any input that was not parsed add a penalty for that format
  18396. currentScore += tempConfig._pf.charsLeftOver;
  18397. //or tokens
  18398. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18399. tempConfig._pf.score = currentScore;
  18400. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18401. scoreToBeat = currentScore;
  18402. bestMoment = tempConfig;
  18403. }
  18404. }
  18405. extend(config, bestMoment || tempConfig);
  18406. }
  18407. // date from iso format
  18408. function makeDateFromString(config) {
  18409. var i, l,
  18410. string = config._i,
  18411. match = isoRegex.exec(string);
  18412. if (match) {
  18413. config._pf.iso = true;
  18414. for (i = 0, l = isoDates.length; i < l; i++) {
  18415. if (isoDates[i][1].exec(string)) {
  18416. // match[5] should be "T" or undefined
  18417. config._f = isoDates[i][0] + (match[6] || " ");
  18418. break;
  18419. }
  18420. }
  18421. for (i = 0, l = isoTimes.length; i < l; i++) {
  18422. if (isoTimes[i][1].exec(string)) {
  18423. config._f += isoTimes[i][0];
  18424. break;
  18425. }
  18426. }
  18427. if (string.match(parseTokenTimezone)) {
  18428. config._f += "Z";
  18429. }
  18430. makeDateFromStringAndFormat(config);
  18431. }
  18432. else {
  18433. config._d = new Date(string);
  18434. }
  18435. }
  18436. function makeDateFromInput(config) {
  18437. var input = config._i,
  18438. matched = aspNetJsonRegex.exec(input);
  18439. if (input === undefined) {
  18440. config._d = new Date();
  18441. } else if (matched) {
  18442. config._d = new Date(+matched[1]);
  18443. } else if (typeof input === 'string') {
  18444. makeDateFromString(config);
  18445. } else if (isArray(input)) {
  18446. config._a = input.slice(0);
  18447. dateFromConfig(config);
  18448. } else if (isDate(input)) {
  18449. config._d = new Date(+input);
  18450. } else if (typeof(input) === 'object') {
  18451. dateFromObject(config);
  18452. } else {
  18453. config._d = new Date(input);
  18454. }
  18455. }
  18456. function makeDate(y, m, d, h, M, s, ms) {
  18457. //can't just apply() to create a date:
  18458. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  18459. var date = new Date(y, m, d, h, M, s, ms);
  18460. //the date constructor doesn't accept years < 1970
  18461. if (y < 1970) {
  18462. date.setFullYear(y);
  18463. }
  18464. return date;
  18465. }
  18466. function makeUTCDate(y) {
  18467. var date = new Date(Date.UTC.apply(null, arguments));
  18468. if (y < 1970) {
  18469. date.setUTCFullYear(y);
  18470. }
  18471. return date;
  18472. }
  18473. function parseWeekday(input, language) {
  18474. if (typeof input === 'string') {
  18475. if (!isNaN(input)) {
  18476. input = parseInt(input, 10);
  18477. }
  18478. else {
  18479. input = language.weekdaysParse(input);
  18480. if (typeof input !== 'number') {
  18481. return null;
  18482. }
  18483. }
  18484. }
  18485. return input;
  18486. }
  18487. /************************************
  18488. Relative Time
  18489. ************************************/
  18490. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  18491. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  18492. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  18493. }
  18494. function relativeTime(milliseconds, withoutSuffix, lang) {
  18495. var seconds = round(Math.abs(milliseconds) / 1000),
  18496. minutes = round(seconds / 60),
  18497. hours = round(minutes / 60),
  18498. days = round(hours / 24),
  18499. years = round(days / 365),
  18500. args = seconds < 45 && ['s', seconds] ||
  18501. minutes === 1 && ['m'] ||
  18502. minutes < 45 && ['mm', minutes] ||
  18503. hours === 1 && ['h'] ||
  18504. hours < 22 && ['hh', hours] ||
  18505. days === 1 && ['d'] ||
  18506. days <= 25 && ['dd', days] ||
  18507. days <= 45 && ['M'] ||
  18508. days < 345 && ['MM', round(days / 30)] ||
  18509. years === 1 && ['y'] || ['yy', years];
  18510. args[2] = withoutSuffix;
  18511. args[3] = milliseconds > 0;
  18512. args[4] = lang;
  18513. return substituteTimeAgo.apply({}, args);
  18514. }
  18515. /************************************
  18516. Week of Year
  18517. ************************************/
  18518. // firstDayOfWeek 0 = sun, 6 = sat
  18519. // the day of the week that starts the week
  18520. // (usually sunday or monday)
  18521. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18522. // the first week is the week that contains the first
  18523. // of this day of the week
  18524. // (eg. ISO weeks use thursday (4))
  18525. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18526. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18527. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18528. adjustedMoment;
  18529. if (daysToDayOfWeek > end) {
  18530. daysToDayOfWeek -= 7;
  18531. }
  18532. if (daysToDayOfWeek < end - 7) {
  18533. daysToDayOfWeek += 7;
  18534. }
  18535. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18536. return {
  18537. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18538. year: adjustedMoment.year()
  18539. };
  18540. }
  18541. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18542. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18543. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18544. weekday = weekday != null ? weekday : firstDayOfWeek;
  18545. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18546. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18547. return {
  18548. year: dayOfYear > 0 ? year : year - 1,
  18549. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18550. };
  18551. }
  18552. /************************************
  18553. Top Level Functions
  18554. ************************************/
  18555. function makeMoment(config) {
  18556. var input = config._i,
  18557. format = config._f;
  18558. if (input === null) {
  18559. return moment.invalid({nullInput: true});
  18560. }
  18561. if (typeof input === 'string') {
  18562. config._i = input = getLangDefinition().preparse(input);
  18563. }
  18564. if (moment.isMoment(input)) {
  18565. config = cloneMoment(input);
  18566. config._d = new Date(+input._d);
  18567. } else if (format) {
  18568. if (isArray(format)) {
  18569. makeDateFromStringAndArray(config);
  18570. } else {
  18571. makeDateFromStringAndFormat(config);
  18572. }
  18573. } else {
  18574. makeDateFromInput(config);
  18575. }
  18576. return new Moment(config);
  18577. }
  18578. moment = function (input, format, lang, strict) {
  18579. var c;
  18580. if (typeof(lang) === "boolean") {
  18581. strict = lang;
  18582. lang = undefined;
  18583. }
  18584. // object construction must be done this way.
  18585. // https://github.com/moment/moment/issues/1423
  18586. c = {};
  18587. c._isAMomentObject = true;
  18588. c._i = input;
  18589. c._f = format;
  18590. c._l = lang;
  18591. c._strict = strict;
  18592. c._isUTC = false;
  18593. c._pf = defaultParsingFlags();
  18594. return makeMoment(c);
  18595. };
  18596. // creating with utc
  18597. moment.utc = function (input, format, lang, strict) {
  18598. var c;
  18599. if (typeof(lang) === "boolean") {
  18600. strict = lang;
  18601. lang = undefined;
  18602. }
  18603. // object construction must be done this way.
  18604. // https://github.com/moment/moment/issues/1423
  18605. c = {};
  18606. c._isAMomentObject = true;
  18607. c._useUTC = true;
  18608. c._isUTC = true;
  18609. c._l = lang;
  18610. c._i = input;
  18611. c._f = format;
  18612. c._strict = strict;
  18613. c._pf = defaultParsingFlags();
  18614. return makeMoment(c).utc();
  18615. };
  18616. // creating with unix timestamp (in seconds)
  18617. moment.unix = function (input) {
  18618. return moment(input * 1000);
  18619. };
  18620. // duration
  18621. moment.duration = function (input, key) {
  18622. var duration = input,
  18623. // matching against regexp is expensive, do it on demand
  18624. match = null,
  18625. sign,
  18626. ret,
  18627. parseIso;
  18628. if (moment.isDuration(input)) {
  18629. duration = {
  18630. ms: input._milliseconds,
  18631. d: input._days,
  18632. M: input._months
  18633. };
  18634. } else if (typeof input === 'number') {
  18635. duration = {};
  18636. if (key) {
  18637. duration[key] = input;
  18638. } else {
  18639. duration.milliseconds = input;
  18640. }
  18641. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18642. sign = (match[1] === "-") ? -1 : 1;
  18643. duration = {
  18644. y: 0,
  18645. d: toInt(match[DATE]) * sign,
  18646. h: toInt(match[HOUR]) * sign,
  18647. m: toInt(match[MINUTE]) * sign,
  18648. s: toInt(match[SECOND]) * sign,
  18649. ms: toInt(match[MILLISECOND]) * sign
  18650. };
  18651. } else if (!!(match = isoDurationRegex.exec(input))) {
  18652. sign = (match[1] === "-") ? -1 : 1;
  18653. parseIso = function (inp) {
  18654. // We'd normally use ~~inp for this, but unfortunately it also
  18655. // converts floats to ints.
  18656. // inp may be undefined, so careful calling replace on it.
  18657. var res = inp && parseFloat(inp.replace(',', '.'));
  18658. // apply sign while we're at it
  18659. return (isNaN(res) ? 0 : res) * sign;
  18660. };
  18661. duration = {
  18662. y: parseIso(match[2]),
  18663. M: parseIso(match[3]),
  18664. d: parseIso(match[4]),
  18665. h: parseIso(match[5]),
  18666. m: parseIso(match[6]),
  18667. s: parseIso(match[7]),
  18668. w: parseIso(match[8])
  18669. };
  18670. }
  18671. ret = new Duration(duration);
  18672. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18673. ret._lang = input._lang;
  18674. }
  18675. return ret;
  18676. };
  18677. // version number
  18678. moment.version = VERSION;
  18679. // default format
  18680. moment.defaultFormat = isoFormat;
  18681. // This function will be called whenever a moment is mutated.
  18682. // It is intended to keep the offset in sync with the timezone.
  18683. moment.updateOffset = function () {};
  18684. // This function will load languages and then set the global language. If
  18685. // no arguments are passed in, it will simply return the current global
  18686. // language key.
  18687. moment.lang = function (key, values) {
  18688. var r;
  18689. if (!key) {
  18690. return moment.fn._lang._abbr;
  18691. }
  18692. if (values) {
  18693. loadLang(normalizeLanguage(key), values);
  18694. } else if (values === null) {
  18695. unloadLang(key);
  18696. key = 'en';
  18697. } else if (!languages[key]) {
  18698. getLangDefinition(key);
  18699. }
  18700. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18701. return r._abbr;
  18702. };
  18703. // returns language data
  18704. moment.langData = function (key) {
  18705. if (key && key._lang && key._lang._abbr) {
  18706. key = key._lang._abbr;
  18707. }
  18708. return getLangDefinition(key);
  18709. };
  18710. // compare moment object
  18711. moment.isMoment = function (obj) {
  18712. return obj instanceof Moment ||
  18713. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18714. };
  18715. // for typechecking Duration objects
  18716. moment.isDuration = function (obj) {
  18717. return obj instanceof Duration;
  18718. };
  18719. for (i = lists.length - 1; i >= 0; --i) {
  18720. makeList(lists[i]);
  18721. }
  18722. moment.normalizeUnits = function (units) {
  18723. return normalizeUnits(units);
  18724. };
  18725. moment.invalid = function (flags) {
  18726. var m = moment.utc(NaN);
  18727. if (flags != null) {
  18728. extend(m._pf, flags);
  18729. }
  18730. else {
  18731. m._pf.userInvalidated = true;
  18732. }
  18733. return m;
  18734. };
  18735. moment.parseZone = function (input) {
  18736. return moment(input).parseZone();
  18737. };
  18738. /************************************
  18739. Moment Prototype
  18740. ************************************/
  18741. extend(moment.fn = Moment.prototype, {
  18742. clone : function () {
  18743. return moment(this);
  18744. },
  18745. valueOf : function () {
  18746. return +this._d + ((this._offset || 0) * 60000);
  18747. },
  18748. unix : function () {
  18749. return Math.floor(+this / 1000);
  18750. },
  18751. toString : function () {
  18752. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18753. },
  18754. toDate : function () {
  18755. return this._offset ? new Date(+this) : this._d;
  18756. },
  18757. toISOString : function () {
  18758. var m = moment(this).utc();
  18759. if (0 < m.year() && m.year() <= 9999) {
  18760. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18761. } else {
  18762. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18763. }
  18764. },
  18765. toArray : function () {
  18766. var m = this;
  18767. return [
  18768. m.year(),
  18769. m.month(),
  18770. m.date(),
  18771. m.hours(),
  18772. m.minutes(),
  18773. m.seconds(),
  18774. m.milliseconds()
  18775. ];
  18776. },
  18777. isValid : function () {
  18778. return isValid(this);
  18779. },
  18780. isDSTShifted : function () {
  18781. if (this._a) {
  18782. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18783. }
  18784. return false;
  18785. },
  18786. parsingFlags : function () {
  18787. return extend({}, this._pf);
  18788. },
  18789. invalidAt: function () {
  18790. return this._pf.overflow;
  18791. },
  18792. utc : function () {
  18793. return this.zone(0);
  18794. },
  18795. local : function () {
  18796. this.zone(0);
  18797. this._isUTC = false;
  18798. return this;
  18799. },
  18800. format : function (inputString) {
  18801. var output = formatMoment(this, inputString || moment.defaultFormat);
  18802. return this.lang().postformat(output);
  18803. },
  18804. add : function (input, val) {
  18805. var dur;
  18806. // switch args to support add('s', 1) and add(1, 's')
  18807. if (typeof input === 'string') {
  18808. dur = moment.duration(+val, input);
  18809. } else {
  18810. dur = moment.duration(input, val);
  18811. }
  18812. addOrSubtractDurationFromMoment(this, dur, 1);
  18813. return this;
  18814. },
  18815. subtract : function (input, val) {
  18816. var dur;
  18817. // switch args to support subtract('s', 1) and subtract(1, 's')
  18818. if (typeof input === 'string') {
  18819. dur = moment.duration(+val, input);
  18820. } else {
  18821. dur = moment.duration(input, val);
  18822. }
  18823. addOrSubtractDurationFromMoment(this, dur, -1);
  18824. return this;
  18825. },
  18826. diff : function (input, units, asFloat) {
  18827. var that = makeAs(input, this),
  18828. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18829. diff, output;
  18830. units = normalizeUnits(units);
  18831. if (units === 'year' || units === 'month') {
  18832. // average number of days in the months in the given dates
  18833. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18834. // difference in months
  18835. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18836. // adjust by taking difference in days, average number of days
  18837. // and dst in the given months.
  18838. output += ((this - moment(this).startOf('month')) -
  18839. (that - moment(that).startOf('month'))) / diff;
  18840. // same as above but with zones, to negate all dst
  18841. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18842. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18843. if (units === 'year') {
  18844. output = output / 12;
  18845. }
  18846. } else {
  18847. diff = (this - that);
  18848. output = units === 'second' ? diff / 1e3 : // 1000
  18849. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18850. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18851. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18852. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18853. diff;
  18854. }
  18855. return asFloat ? output : absRound(output);
  18856. },
  18857. from : function (time, withoutSuffix) {
  18858. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18859. },
  18860. fromNow : function (withoutSuffix) {
  18861. return this.from(moment(), withoutSuffix);
  18862. },
  18863. calendar : function () {
  18864. // We want to compare the start of today, vs this.
  18865. // Getting start-of-today depends on whether we're zone'd or not.
  18866. var sod = makeAs(moment(), this).startOf('day'),
  18867. diff = this.diff(sod, 'days', true),
  18868. format = diff < -6 ? 'sameElse' :
  18869. diff < -1 ? 'lastWeek' :
  18870. diff < 0 ? 'lastDay' :
  18871. diff < 1 ? 'sameDay' :
  18872. diff < 2 ? 'nextDay' :
  18873. diff < 7 ? 'nextWeek' : 'sameElse';
  18874. return this.format(this.lang().calendar(format, this));
  18875. },
  18876. isLeapYear : function () {
  18877. return isLeapYear(this.year());
  18878. },
  18879. isDST : function () {
  18880. return (this.zone() < this.clone().month(0).zone() ||
  18881. this.zone() < this.clone().month(5).zone());
  18882. },
  18883. day : function (input) {
  18884. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18885. if (input != null) {
  18886. input = parseWeekday(input, this.lang());
  18887. return this.add({ d : input - day });
  18888. } else {
  18889. return day;
  18890. }
  18891. },
  18892. month : function (input) {
  18893. var utc = this._isUTC ? 'UTC' : '',
  18894. dayOfMonth;
  18895. if (input != null) {
  18896. if (typeof input === 'string') {
  18897. input = this.lang().monthsParse(input);
  18898. if (typeof input !== 'number') {
  18899. return this;
  18900. }
  18901. }
  18902. dayOfMonth = this.date();
  18903. this.date(1);
  18904. this._d['set' + utc + 'Month'](input);
  18905. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  18906. moment.updateOffset(this);
  18907. return this;
  18908. } else {
  18909. return this._d['get' + utc + 'Month']();
  18910. }
  18911. },
  18912. startOf: function (units) {
  18913. units = normalizeUnits(units);
  18914. // the following switch intentionally omits break keywords
  18915. // to utilize falling through the cases.
  18916. switch (units) {
  18917. case 'year':
  18918. this.month(0);
  18919. /* falls through */
  18920. case 'month':
  18921. this.date(1);
  18922. /* falls through */
  18923. case 'week':
  18924. case 'isoWeek':
  18925. case 'day':
  18926. this.hours(0);
  18927. /* falls through */
  18928. case 'hour':
  18929. this.minutes(0);
  18930. /* falls through */
  18931. case 'minute':
  18932. this.seconds(0);
  18933. /* falls through */
  18934. case 'second':
  18935. this.milliseconds(0);
  18936. /* falls through */
  18937. }
  18938. // weeks are a special case
  18939. if (units === 'week') {
  18940. this.weekday(0);
  18941. } else if (units === 'isoWeek') {
  18942. this.isoWeekday(1);
  18943. }
  18944. return this;
  18945. },
  18946. endOf: function (units) {
  18947. units = normalizeUnits(units);
  18948. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18949. },
  18950. isAfter: function (input, units) {
  18951. units = typeof units !== 'undefined' ? units : 'millisecond';
  18952. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18953. },
  18954. isBefore: function (input, units) {
  18955. units = typeof units !== 'undefined' ? units : 'millisecond';
  18956. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18957. },
  18958. isSame: function (input, units) {
  18959. units = units || 'ms';
  18960. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18961. },
  18962. min: function (other) {
  18963. other = moment.apply(null, arguments);
  18964. return other < this ? this : other;
  18965. },
  18966. max: function (other) {
  18967. other = moment.apply(null, arguments);
  18968. return other > this ? this : other;
  18969. },
  18970. zone : function (input) {
  18971. var offset = this._offset || 0;
  18972. if (input != null) {
  18973. if (typeof input === "string") {
  18974. input = timezoneMinutesFromString(input);
  18975. }
  18976. if (Math.abs(input) < 16) {
  18977. input = input * 60;
  18978. }
  18979. this._offset = input;
  18980. this._isUTC = true;
  18981. if (offset !== input) {
  18982. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  18983. }
  18984. } else {
  18985. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18986. }
  18987. return this;
  18988. },
  18989. zoneAbbr : function () {
  18990. return this._isUTC ? "UTC" : "";
  18991. },
  18992. zoneName : function () {
  18993. return this._isUTC ? "Coordinated Universal Time" : "";
  18994. },
  18995. parseZone : function () {
  18996. if (this._tzm) {
  18997. this.zone(this._tzm);
  18998. } else if (typeof this._i === 'string') {
  18999. this.zone(this._i);
  19000. }
  19001. return this;
  19002. },
  19003. hasAlignedHourOffset : function (input) {
  19004. if (!input) {
  19005. input = 0;
  19006. }
  19007. else {
  19008. input = moment(input).zone();
  19009. }
  19010. return (this.zone() - input) % 60 === 0;
  19011. },
  19012. daysInMonth : function () {
  19013. return daysInMonth(this.year(), this.month());
  19014. },
  19015. dayOfYear : function (input) {
  19016. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  19017. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  19018. },
  19019. quarter : function () {
  19020. return Math.ceil((this.month() + 1.0) / 3.0);
  19021. },
  19022. weekYear : function (input) {
  19023. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  19024. return input == null ? year : this.add("y", (input - year));
  19025. },
  19026. isoWeekYear : function (input) {
  19027. var year = weekOfYear(this, 1, 4).year;
  19028. return input == null ? year : this.add("y", (input - year));
  19029. },
  19030. week : function (input) {
  19031. var week = this.lang().week(this);
  19032. return input == null ? week : this.add("d", (input - week) * 7);
  19033. },
  19034. isoWeek : function (input) {
  19035. var week = weekOfYear(this, 1, 4).week;
  19036. return input == null ? week : this.add("d", (input - week) * 7);
  19037. },
  19038. weekday : function (input) {
  19039. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  19040. return input == null ? weekday : this.add("d", input - weekday);
  19041. },
  19042. isoWeekday : function (input) {
  19043. // behaves the same as moment#day except
  19044. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  19045. // as a setter, sunday should belong to the previous week.
  19046. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  19047. },
  19048. get : function (units) {
  19049. units = normalizeUnits(units);
  19050. return this[units]();
  19051. },
  19052. set : function (units, value) {
  19053. units = normalizeUnits(units);
  19054. if (typeof this[units] === 'function') {
  19055. this[units](value);
  19056. }
  19057. return this;
  19058. },
  19059. // If passed a language key, it will set the language for this
  19060. // instance. Otherwise, it will return the language configuration
  19061. // variables for this instance.
  19062. lang : function (key) {
  19063. if (key === undefined) {
  19064. return this._lang;
  19065. } else {
  19066. this._lang = getLangDefinition(key);
  19067. return this;
  19068. }
  19069. }
  19070. });
  19071. // helper for adding shortcuts
  19072. function makeGetterAndSetter(name, key) {
  19073. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  19074. var utc = this._isUTC ? 'UTC' : '';
  19075. if (input != null) {
  19076. this._d['set' + utc + key](input);
  19077. moment.updateOffset(this);
  19078. return this;
  19079. } else {
  19080. return this._d['get' + utc + key]();
  19081. }
  19082. };
  19083. }
  19084. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  19085. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  19086. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  19087. }
  19088. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  19089. makeGetterAndSetter('year', 'FullYear');
  19090. // add plural methods
  19091. moment.fn.days = moment.fn.day;
  19092. moment.fn.months = moment.fn.month;
  19093. moment.fn.weeks = moment.fn.week;
  19094. moment.fn.isoWeeks = moment.fn.isoWeek;
  19095. // add aliased format methods
  19096. moment.fn.toJSON = moment.fn.toISOString;
  19097. /************************************
  19098. Duration Prototype
  19099. ************************************/
  19100. extend(moment.duration.fn = Duration.prototype, {
  19101. _bubble : function () {
  19102. var milliseconds = this._milliseconds,
  19103. days = this._days,
  19104. months = this._months,
  19105. data = this._data,
  19106. seconds, minutes, hours, years;
  19107. // The following code bubbles up values, see the tests for
  19108. // examples of what that means.
  19109. data.milliseconds = milliseconds % 1000;
  19110. seconds = absRound(milliseconds / 1000);
  19111. data.seconds = seconds % 60;
  19112. minutes = absRound(seconds / 60);
  19113. data.minutes = minutes % 60;
  19114. hours = absRound(minutes / 60);
  19115. data.hours = hours % 24;
  19116. days += absRound(hours / 24);
  19117. data.days = days % 30;
  19118. months += absRound(days / 30);
  19119. data.months = months % 12;
  19120. years = absRound(months / 12);
  19121. data.years = years;
  19122. },
  19123. weeks : function () {
  19124. return absRound(this.days() / 7);
  19125. },
  19126. valueOf : function () {
  19127. return this._milliseconds +
  19128. this._days * 864e5 +
  19129. (this._months % 12) * 2592e6 +
  19130. toInt(this._months / 12) * 31536e6;
  19131. },
  19132. humanize : function (withSuffix) {
  19133. var difference = +this,
  19134. output = relativeTime(difference, !withSuffix, this.lang());
  19135. if (withSuffix) {
  19136. output = this.lang().pastFuture(difference, output);
  19137. }
  19138. return this.lang().postformat(output);
  19139. },
  19140. add : function (input, val) {
  19141. // supports only 2.0-style add(1, 's') or add(moment)
  19142. var dur = moment.duration(input, val);
  19143. this._milliseconds += dur._milliseconds;
  19144. this._days += dur._days;
  19145. this._months += dur._months;
  19146. this._bubble();
  19147. return this;
  19148. },
  19149. subtract : function (input, val) {
  19150. var dur = moment.duration(input, val);
  19151. this._milliseconds -= dur._milliseconds;
  19152. this._days -= dur._days;
  19153. this._months -= dur._months;
  19154. this._bubble();
  19155. return this;
  19156. },
  19157. get : function (units) {
  19158. units = normalizeUnits(units);
  19159. return this[units.toLowerCase() + 's']();
  19160. },
  19161. as : function (units) {
  19162. units = normalizeUnits(units);
  19163. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  19164. },
  19165. lang : moment.fn.lang,
  19166. toIsoString : function () {
  19167. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  19168. var years = Math.abs(this.years()),
  19169. months = Math.abs(this.months()),
  19170. days = Math.abs(this.days()),
  19171. hours = Math.abs(this.hours()),
  19172. minutes = Math.abs(this.minutes()),
  19173. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  19174. if (!this.asSeconds()) {
  19175. // this is the same as C#'s (Noda) and python (isodate)...
  19176. // but not other JS (goog.date)
  19177. return 'P0D';
  19178. }
  19179. return (this.asSeconds() < 0 ? '-' : '') +
  19180. 'P' +
  19181. (years ? years + 'Y' : '') +
  19182. (months ? months + 'M' : '') +
  19183. (days ? days + 'D' : '') +
  19184. ((hours || minutes || seconds) ? 'T' : '') +
  19185. (hours ? hours + 'H' : '') +
  19186. (minutes ? minutes + 'M' : '') +
  19187. (seconds ? seconds + 'S' : '');
  19188. }
  19189. });
  19190. function makeDurationGetter(name) {
  19191. moment.duration.fn[name] = function () {
  19192. return this._data[name];
  19193. };
  19194. }
  19195. function makeDurationAsGetter(name, factor) {
  19196. moment.duration.fn['as' + name] = function () {
  19197. return +this / factor;
  19198. };
  19199. }
  19200. for (i in unitMillisecondFactors) {
  19201. if (unitMillisecondFactors.hasOwnProperty(i)) {
  19202. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  19203. makeDurationGetter(i.toLowerCase());
  19204. }
  19205. }
  19206. makeDurationAsGetter('Weeks', 6048e5);
  19207. moment.duration.fn.asMonths = function () {
  19208. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  19209. };
  19210. /************************************
  19211. Default Lang
  19212. ************************************/
  19213. // Set default language, other languages will inherit from English.
  19214. moment.lang('en', {
  19215. ordinal : function (number) {
  19216. var b = number % 10,
  19217. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  19218. (b === 1) ? 'st' :
  19219. (b === 2) ? 'nd' :
  19220. (b === 3) ? 'rd' : 'th';
  19221. return number + output;
  19222. }
  19223. });
  19224. /* EMBED_LANGUAGES */
  19225. /************************************
  19226. Exposing Moment
  19227. ************************************/
  19228. function makeGlobal(deprecate) {
  19229. var warned = false, local_moment = moment;
  19230. /*global ender:false */
  19231. if (typeof ender !== 'undefined') {
  19232. return;
  19233. }
  19234. // here, `this` means `window` in the browser, or `global` on the server
  19235. // add `moment` as a global object via a string identifier,
  19236. // for Closure Compiler "advanced" mode
  19237. if (deprecate) {
  19238. global.moment = function () {
  19239. if (!warned && console && console.warn) {
  19240. warned = true;
  19241. console.warn(
  19242. "Accessing Moment through the global scope is " +
  19243. "deprecated, and will be removed in an upcoming " +
  19244. "release.");
  19245. }
  19246. return local_moment.apply(null, arguments);
  19247. };
  19248. extend(global.moment, local_moment);
  19249. } else {
  19250. global['moment'] = moment;
  19251. }
  19252. }
  19253. // CommonJS module is defined
  19254. if (hasModule) {
  19255. module.exports = moment;
  19256. makeGlobal(true);
  19257. } else if (typeof define === "function" && define.amd) {
  19258. define("moment", function (require, exports, module) {
  19259. if (module.config && module.config() && module.config().noGlobal !== true) {
  19260. // If user provided noGlobal, he is aware of global
  19261. makeGlobal(module.config().noGlobal === undefined);
  19262. }
  19263. return moment;
  19264. });
  19265. } else {
  19266. makeGlobal();
  19267. }
  19268. }).call(this);
  19269. },{}],5:[function(require,module,exports){
  19270. /**
  19271. * Copyright 2012 Craig Campbell
  19272. *
  19273. * Licensed under the Apache License, Version 2.0 (the "License");
  19274. * you may not use this file except in compliance with the License.
  19275. * You may obtain a copy of the License at
  19276. *
  19277. * http://www.apache.org/licenses/LICENSE-2.0
  19278. *
  19279. * Unless required by applicable law or agreed to in writing, software
  19280. * distributed under the License is distributed on an "AS IS" BASIS,
  19281. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19282. * See the License for the specific language governing permissions and
  19283. * limitations under the License.
  19284. *
  19285. * Mousetrap is a simple keyboard shortcut library for Javascript with
  19286. * no external dependencies
  19287. *
  19288. * @version 1.1.2
  19289. * @url craig.is/killing/mice
  19290. */
  19291. /**
  19292. * mapping of special keycodes to their corresponding keys
  19293. *
  19294. * everything in this dictionary cannot use keypress events
  19295. * so it has to be here to map to the correct keycodes for
  19296. * keyup/keydown events
  19297. *
  19298. * @type {Object}
  19299. */
  19300. var _MAP = {
  19301. 8: 'backspace',
  19302. 9: 'tab',
  19303. 13: 'enter',
  19304. 16: 'shift',
  19305. 17: 'ctrl',
  19306. 18: 'alt',
  19307. 20: 'capslock',
  19308. 27: 'esc',
  19309. 32: 'space',
  19310. 33: 'pageup',
  19311. 34: 'pagedown',
  19312. 35: 'end',
  19313. 36: 'home',
  19314. 37: 'left',
  19315. 38: 'up',
  19316. 39: 'right',
  19317. 40: 'down',
  19318. 45: 'ins',
  19319. 46: 'del',
  19320. 91: 'meta',
  19321. 93: 'meta',
  19322. 224: 'meta'
  19323. },
  19324. /**
  19325. * mapping for special characters so they can support
  19326. *
  19327. * this dictionary is only used incase you want to bind a
  19328. * keyup or keydown event to one of these keys
  19329. *
  19330. * @type {Object}
  19331. */
  19332. _KEYCODE_MAP = {
  19333. 106: '*',
  19334. 107: '+',
  19335. 109: '-',
  19336. 110: '.',
  19337. 111 : '/',
  19338. 186: ';',
  19339. 187: '=',
  19340. 188: ',',
  19341. 189: '-',
  19342. 190: '.',
  19343. 191: '/',
  19344. 192: '`',
  19345. 219: '[',
  19346. 220: '\\',
  19347. 221: ']',
  19348. 222: '\''
  19349. },
  19350. /**
  19351. * this is a mapping of keys that require shift on a US keypad
  19352. * back to the non shift equivelents
  19353. *
  19354. * this is so you can use keyup events with these keys
  19355. *
  19356. * note that this will only work reliably on US keyboards
  19357. *
  19358. * @type {Object}
  19359. */
  19360. _SHIFT_MAP = {
  19361. '~': '`',
  19362. '!': '1',
  19363. '@': '2',
  19364. '#': '3',
  19365. '$': '4',
  19366. '%': '5',
  19367. '^': '6',
  19368. '&': '7',
  19369. '*': '8',
  19370. '(': '9',
  19371. ')': '0',
  19372. '_': '-',
  19373. '+': '=',
  19374. ':': ';',
  19375. '\"': '\'',
  19376. '<': ',',
  19377. '>': '.',
  19378. '?': '/',
  19379. '|': '\\'
  19380. },
  19381. /**
  19382. * this is a list of special strings you can use to map
  19383. * to modifier keys when you specify your keyboard shortcuts
  19384. *
  19385. * @type {Object}
  19386. */
  19387. _SPECIAL_ALIASES = {
  19388. 'option': 'alt',
  19389. 'command': 'meta',
  19390. 'return': 'enter',
  19391. 'escape': 'esc'
  19392. },
  19393. /**
  19394. * variable to store the flipped version of _MAP from above
  19395. * needed to check if we should use keypress or not when no action
  19396. * is specified
  19397. *
  19398. * @type {Object|undefined}
  19399. */
  19400. _REVERSE_MAP,
  19401. /**
  19402. * a list of all the callbacks setup via Mousetrap.bind()
  19403. *
  19404. * @type {Object}
  19405. */
  19406. _callbacks = {},
  19407. /**
  19408. * direct map of string combinations to callbacks used for trigger()
  19409. *
  19410. * @type {Object}
  19411. */
  19412. _direct_map = {},
  19413. /**
  19414. * keeps track of what level each sequence is at since multiple
  19415. * sequences can start out with the same sequence
  19416. *
  19417. * @type {Object}
  19418. */
  19419. _sequence_levels = {},
  19420. /**
  19421. * variable to store the setTimeout call
  19422. *
  19423. * @type {null|number}
  19424. */
  19425. _reset_timer,
  19426. /**
  19427. * temporary state where we will ignore the next keyup
  19428. *
  19429. * @type {boolean|string}
  19430. */
  19431. _ignore_next_keyup = false,
  19432. /**
  19433. * are we currently inside of a sequence?
  19434. * type of action ("keyup" or "keydown" or "keypress") or false
  19435. *
  19436. * @type {boolean|string}
  19437. */
  19438. _inside_sequence = false;
  19439. /**
  19440. * loop through the f keys, f1 to f19 and add them to the map
  19441. * programatically
  19442. */
  19443. for (var i = 1; i < 20; ++i) {
  19444. _MAP[111 + i] = 'f' + i;
  19445. }
  19446. /**
  19447. * loop through to map numbers on the numeric keypad
  19448. */
  19449. for (i = 0; i <= 9; ++i) {
  19450. _MAP[i + 96] = i;
  19451. }
  19452. /**
  19453. * cross browser add event method
  19454. *
  19455. * @param {Element|HTMLDocument} object
  19456. * @param {string} type
  19457. * @param {Function} callback
  19458. * @returns void
  19459. */
  19460. function _addEvent(object, type, callback) {
  19461. if (object.addEventListener) {
  19462. return object.addEventListener(type, callback, false);
  19463. }
  19464. object.attachEvent('on' + type, callback);
  19465. }
  19466. /**
  19467. * takes the event and returns the key character
  19468. *
  19469. * @param {Event} e
  19470. * @return {string}
  19471. */
  19472. function _characterFromEvent(e) {
  19473. // for keypress events we should return the character as is
  19474. if (e.type == 'keypress') {
  19475. return String.fromCharCode(e.which);
  19476. }
  19477. // for non keypress events the special maps are needed
  19478. if (_MAP[e.which]) {
  19479. return _MAP[e.which];
  19480. }
  19481. if (_KEYCODE_MAP[e.which]) {
  19482. return _KEYCODE_MAP[e.which];
  19483. }
  19484. // if it is not in the special map
  19485. return String.fromCharCode(e.which).toLowerCase();
  19486. }
  19487. /**
  19488. * should we stop this event before firing off callbacks
  19489. *
  19490. * @param {Event} e
  19491. * @return {boolean}
  19492. */
  19493. function _stop(e) {
  19494. var element = e.target || e.srcElement,
  19495. tag_name = element.tagName;
  19496. // if the element has the class "mousetrap" then no need to stop
  19497. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19498. return false;
  19499. }
  19500. // stop for input, select, and textarea
  19501. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19502. }
  19503. /**
  19504. * checks if two arrays are equal
  19505. *
  19506. * @param {Array} modifiers1
  19507. * @param {Array} modifiers2
  19508. * @returns {boolean}
  19509. */
  19510. function _modifiersMatch(modifiers1, modifiers2) {
  19511. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19512. }
  19513. /**
  19514. * resets all sequence counters except for the ones passed in
  19515. *
  19516. * @param {Object} do_not_reset
  19517. * @returns void
  19518. */
  19519. function _resetSequences(do_not_reset) {
  19520. do_not_reset = do_not_reset || {};
  19521. var active_sequences = false,
  19522. key;
  19523. for (key in _sequence_levels) {
  19524. if (do_not_reset[key]) {
  19525. active_sequences = true;
  19526. continue;
  19527. }
  19528. _sequence_levels[key] = 0;
  19529. }
  19530. if (!active_sequences) {
  19531. _inside_sequence = false;
  19532. }
  19533. }
  19534. /**
  19535. * finds all callbacks that match based on the keycode, modifiers,
  19536. * and action
  19537. *
  19538. * @param {string} character
  19539. * @param {Array} modifiers
  19540. * @param {string} action
  19541. * @param {boolean=} remove - should we remove any matches
  19542. * @param {string=} combination
  19543. * @returns {Array}
  19544. */
  19545. function _getMatches(character, modifiers, action, remove, combination) {
  19546. var i,
  19547. callback,
  19548. matches = [];
  19549. // if there are no events related to this keycode
  19550. if (!_callbacks[character]) {
  19551. return [];
  19552. }
  19553. // if a modifier key is coming up on its own we should allow it
  19554. if (action == 'keyup' && _isModifier(character)) {
  19555. modifiers = [character];
  19556. }
  19557. // loop through all callbacks for the key that was pressed
  19558. // and see if any of them match
  19559. for (i = 0; i < _callbacks[character].length; ++i) {
  19560. callback = _callbacks[character][i];
  19561. // if this is a sequence but it is not at the right level
  19562. // then move onto the next match
  19563. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19564. continue;
  19565. }
  19566. // if the action we are looking for doesn't match the action we got
  19567. // then we should keep going
  19568. if (action != callback.action) {
  19569. continue;
  19570. }
  19571. // if this is a keypress event that means that we need to only
  19572. // look at the character, otherwise check the modifiers as
  19573. // well
  19574. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19575. // remove is used so if you change your mind and call bind a
  19576. // second time with a new function the first one is overwritten
  19577. if (remove && callback.combo == combination) {
  19578. _callbacks[character].splice(i, 1);
  19579. }
  19580. matches.push(callback);
  19581. }
  19582. }
  19583. return matches;
  19584. }
  19585. /**
  19586. * takes a key event and figures out what the modifiers are
  19587. *
  19588. * @param {Event} e
  19589. * @returns {Array}
  19590. */
  19591. function _eventModifiers(e) {
  19592. var modifiers = [];
  19593. if (e.shiftKey) {
  19594. modifiers.push('shift');
  19595. }
  19596. if (e.altKey) {
  19597. modifiers.push('alt');
  19598. }
  19599. if (e.ctrlKey) {
  19600. modifiers.push('ctrl');
  19601. }
  19602. if (e.metaKey) {
  19603. modifiers.push('meta');
  19604. }
  19605. return modifiers;
  19606. }
  19607. /**
  19608. * actually calls the callback function
  19609. *
  19610. * if your callback function returns false this will use the jquery
  19611. * convention - prevent default and stop propogation on the event
  19612. *
  19613. * @param {Function} callback
  19614. * @param {Event} e
  19615. * @returns void
  19616. */
  19617. function _fireCallback(callback, e) {
  19618. if (callback(e) === false) {
  19619. if (e.preventDefault) {
  19620. e.preventDefault();
  19621. }
  19622. if (e.stopPropagation) {
  19623. e.stopPropagation();
  19624. }
  19625. e.returnValue = false;
  19626. e.cancelBubble = true;
  19627. }
  19628. }
  19629. /**
  19630. * handles a character key event
  19631. *
  19632. * @param {string} character
  19633. * @param {Event} e
  19634. * @returns void
  19635. */
  19636. function _handleCharacter(character, e) {
  19637. // if this event should not happen stop here
  19638. if (_stop(e)) {
  19639. return;
  19640. }
  19641. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19642. i,
  19643. do_not_reset = {},
  19644. processed_sequence_callback = false;
  19645. // loop through matching callbacks for this key event
  19646. for (i = 0; i < callbacks.length; ++i) {
  19647. // fire for all sequence callbacks
  19648. // this is because if for example you have multiple sequences
  19649. // bound such as "g i" and "g t" they both need to fire the
  19650. // callback for matching g cause otherwise you can only ever
  19651. // match the first one
  19652. if (callbacks[i].seq) {
  19653. processed_sequence_callback = true;
  19654. // keep a list of which sequences were matches for later
  19655. do_not_reset[callbacks[i].seq] = 1;
  19656. _fireCallback(callbacks[i].callback, e);
  19657. continue;
  19658. }
  19659. // if there were no sequence matches but we are still here
  19660. // that means this is a regular match so we should fire that
  19661. if (!processed_sequence_callback && !_inside_sequence) {
  19662. _fireCallback(callbacks[i].callback, e);
  19663. }
  19664. }
  19665. // if you are inside of a sequence and the key you are pressing
  19666. // is not a modifier key then we should reset all sequences
  19667. // that were not matched by this key event
  19668. if (e.type == _inside_sequence && !_isModifier(character)) {
  19669. _resetSequences(do_not_reset);
  19670. }
  19671. }
  19672. /**
  19673. * handles a keydown event
  19674. *
  19675. * @param {Event} e
  19676. * @returns void
  19677. */
  19678. function _handleKey(e) {
  19679. // normalize e.which for key events
  19680. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19681. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19682. var character = _characterFromEvent(e);
  19683. // no character found then stop
  19684. if (!character) {
  19685. return;
  19686. }
  19687. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19688. _ignore_next_keyup = false;
  19689. return;
  19690. }
  19691. _handleCharacter(character, e);
  19692. }
  19693. /**
  19694. * determines if the keycode specified is a modifier key or not
  19695. *
  19696. * @param {string} key
  19697. * @returns {boolean}
  19698. */
  19699. function _isModifier(key) {
  19700. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19701. }
  19702. /**
  19703. * called to set a 1 second timeout on the specified sequence
  19704. *
  19705. * this is so after each key press in the sequence you have 1 second
  19706. * to press the next key before you have to start over
  19707. *
  19708. * @returns void
  19709. */
  19710. function _resetSequenceTimer() {
  19711. clearTimeout(_reset_timer);
  19712. _reset_timer = setTimeout(_resetSequences, 1000);
  19713. }
  19714. /**
  19715. * reverses the map lookup so that we can look for specific keys
  19716. * to see what can and can't use keypress
  19717. *
  19718. * @return {Object}
  19719. */
  19720. function _getReverseMap() {
  19721. if (!_REVERSE_MAP) {
  19722. _REVERSE_MAP = {};
  19723. for (var key in _MAP) {
  19724. // pull out the numeric keypad from here cause keypress should
  19725. // be able to detect the keys from the character
  19726. if (key > 95 && key < 112) {
  19727. continue;
  19728. }
  19729. if (_MAP.hasOwnProperty(key)) {
  19730. _REVERSE_MAP[_MAP[key]] = key;
  19731. }
  19732. }
  19733. }
  19734. return _REVERSE_MAP;
  19735. }
  19736. /**
  19737. * picks the best action based on the key combination
  19738. *
  19739. * @param {string} key - character for key
  19740. * @param {Array} modifiers
  19741. * @param {string=} action passed in
  19742. */
  19743. function _pickBestAction(key, modifiers, action) {
  19744. // if no action was picked in we should try to pick the one
  19745. // that we think would work best for this key
  19746. if (!action) {
  19747. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19748. }
  19749. // modifier keys don't work as expected with keypress,
  19750. // switch to keydown
  19751. if (action == 'keypress' && modifiers.length) {
  19752. action = 'keydown';
  19753. }
  19754. return action;
  19755. }
  19756. /**
  19757. * binds a key sequence to an event
  19758. *
  19759. * @param {string} combo - combo specified in bind call
  19760. * @param {Array} keys
  19761. * @param {Function} callback
  19762. * @param {string=} action
  19763. * @returns void
  19764. */
  19765. function _bindSequence(combo, keys, callback, action) {
  19766. // start off by adding a sequence level record for this combination
  19767. // and setting the level to 0
  19768. _sequence_levels[combo] = 0;
  19769. // if there is no action pick the best one for the first key
  19770. // in the sequence
  19771. if (!action) {
  19772. action = _pickBestAction(keys[0], []);
  19773. }
  19774. /**
  19775. * callback to increase the sequence level for this sequence and reset
  19776. * all other sequences that were active
  19777. *
  19778. * @param {Event} e
  19779. * @returns void
  19780. */
  19781. var _increaseSequence = function(e) {
  19782. _inside_sequence = action;
  19783. ++_sequence_levels[combo];
  19784. _resetSequenceTimer();
  19785. },
  19786. /**
  19787. * wraps the specified callback inside of another function in order
  19788. * to reset all sequence counters as soon as this sequence is done
  19789. *
  19790. * @param {Event} e
  19791. * @returns void
  19792. */
  19793. _callbackAndReset = function(e) {
  19794. _fireCallback(callback, e);
  19795. // we should ignore the next key up if the action is key down
  19796. // or keypress. this is so if you finish a sequence and
  19797. // release the key the final key will not trigger a keyup
  19798. if (action !== 'keyup') {
  19799. _ignore_next_keyup = _characterFromEvent(e);
  19800. }
  19801. // weird race condition if a sequence ends with the key
  19802. // another sequence begins with
  19803. setTimeout(_resetSequences, 10);
  19804. },
  19805. i;
  19806. // loop through keys one at a time and bind the appropriate callback
  19807. // function. for any key leading up to the final one it should
  19808. // increase the sequence. after the final, it should reset all sequences
  19809. for (i = 0; i < keys.length; ++i) {
  19810. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19811. }
  19812. }
  19813. /**
  19814. * binds a single keyboard combination
  19815. *
  19816. * @param {string} combination
  19817. * @param {Function} callback
  19818. * @param {string=} action
  19819. * @param {string=} sequence_name - name of sequence if part of sequence
  19820. * @param {number=} level - what part of the sequence the command is
  19821. * @returns void
  19822. */
  19823. function _bindSingle(combination, callback, action, sequence_name, level) {
  19824. // make sure multiple spaces in a row become a single space
  19825. combination = combination.replace(/\s+/g, ' ');
  19826. var sequence = combination.split(' '),
  19827. i,
  19828. key,
  19829. keys,
  19830. modifiers = [];
  19831. // if this pattern is a sequence of keys then run through this method
  19832. // to reprocess each pattern one key at a time
  19833. if (sequence.length > 1) {
  19834. return _bindSequence(combination, sequence, callback, action);
  19835. }
  19836. // take the keys from this pattern and figure out what the actual
  19837. // pattern is all about
  19838. keys = combination === '+' ? ['+'] : combination.split('+');
  19839. for (i = 0; i < keys.length; ++i) {
  19840. key = keys[i];
  19841. // normalize key names
  19842. if (_SPECIAL_ALIASES[key]) {
  19843. key = _SPECIAL_ALIASES[key];
  19844. }
  19845. // if this is not a keypress event then we should
  19846. // be smart about using shift keys
  19847. // this will only work for US keyboards however
  19848. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19849. key = _SHIFT_MAP[key];
  19850. modifiers.push('shift');
  19851. }
  19852. // if this key is a modifier then add it to the list of modifiers
  19853. if (_isModifier(key)) {
  19854. modifiers.push(key);
  19855. }
  19856. }
  19857. // depending on what the key combination is
  19858. // we will try to pick the best event for it
  19859. action = _pickBestAction(key, modifiers, action);
  19860. // make sure to initialize array if this is the first time
  19861. // a callback is added for this key
  19862. if (!_callbacks[key]) {
  19863. _callbacks[key] = [];
  19864. }
  19865. // remove an existing match if there is one
  19866. _getMatches(key, modifiers, action, !sequence_name, combination);
  19867. // add this call back to the array
  19868. // if it is a sequence put it at the beginning
  19869. // if not put it at the end
  19870. //
  19871. // this is important because the way these are processed expects
  19872. // the sequence ones to come first
  19873. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19874. callback: callback,
  19875. modifiers: modifiers,
  19876. action: action,
  19877. seq: sequence_name,
  19878. level: level,
  19879. combo: combination
  19880. });
  19881. }
  19882. /**
  19883. * binds multiple combinations to the same callback
  19884. *
  19885. * @param {Array} combinations
  19886. * @param {Function} callback
  19887. * @param {string|undefined} action
  19888. * @returns void
  19889. */
  19890. function _bindMultiple(combinations, callback, action) {
  19891. for (var i = 0; i < combinations.length; ++i) {
  19892. _bindSingle(combinations[i], callback, action);
  19893. }
  19894. }
  19895. // start!
  19896. _addEvent(document, 'keypress', _handleKey);
  19897. _addEvent(document, 'keydown', _handleKey);
  19898. _addEvent(document, 'keyup', _handleKey);
  19899. var mousetrap = {
  19900. /**
  19901. * binds an event to mousetrap
  19902. *
  19903. * can be a single key, a combination of keys separated with +,
  19904. * a comma separated list of keys, an array of keys, or
  19905. * a sequence of keys separated by spaces
  19906. *
  19907. * be sure to list the modifier keys first to make sure that the
  19908. * correct key ends up getting bound (the last key in the pattern)
  19909. *
  19910. * @param {string|Array} keys
  19911. * @param {Function} callback
  19912. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19913. * @returns void
  19914. */
  19915. bind: function(keys, callback, action) {
  19916. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19917. _direct_map[keys + ':' + action] = callback;
  19918. return this;
  19919. },
  19920. /**
  19921. * unbinds an event to mousetrap
  19922. *
  19923. * the unbinding sets the callback function of the specified key combo
  19924. * to an empty function and deletes the corresponding key in the
  19925. * _direct_map dict.
  19926. *
  19927. * the keycombo+action has to be exactly the same as
  19928. * it was defined in the bind method
  19929. *
  19930. * TODO: actually remove this from the _callbacks dictionary instead
  19931. * of binding an empty function
  19932. *
  19933. * @param {string|Array} keys
  19934. * @param {string} action
  19935. * @returns void
  19936. */
  19937. unbind: function(keys, action) {
  19938. if (_direct_map[keys + ':' + action]) {
  19939. delete _direct_map[keys + ':' + action];
  19940. this.bind(keys, function() {}, action);
  19941. }
  19942. return this;
  19943. },
  19944. /**
  19945. * triggers an event that has already been bound
  19946. *
  19947. * @param {string} keys
  19948. * @param {string=} action
  19949. * @returns void
  19950. */
  19951. trigger: function(keys, action) {
  19952. _direct_map[keys + ':' + action]();
  19953. return this;
  19954. },
  19955. /**
  19956. * resets the library back to its initial state. this is useful
  19957. * if you want to clear out the current keyboard shortcuts and bind
  19958. * new ones - for example if you switch to another page
  19959. *
  19960. * @returns void
  19961. */
  19962. reset: function() {
  19963. _callbacks = {};
  19964. _direct_map = {};
  19965. return this;
  19966. }
  19967. };
  19968. module.exports = mousetrap;
  19969. },{}]},{},[1])
  19970. (1)
  19971. });