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.

22932 lines
672 KiB

10 years ago
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.7.2
  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. tooltip: {
  14147. delay: 300
  14148. }
  14149. };
  14150. this.editMode = this.constants.dataManipulation.initiallyVisible;
  14151. // Node variables
  14152. var graph = this;
  14153. this.groups = new Groups(); // object with groups
  14154. this.images = new Images(); // object with images
  14155. this.images.setOnloadCallback(function () {
  14156. graph._redraw();
  14157. });
  14158. // keyboard navigation variables
  14159. this.xIncrement = 0;
  14160. this.yIncrement = 0;
  14161. this.zoomIncrement = 0;
  14162. // loading all the mixins:
  14163. // load the force calculation functions, grouped under the physics system.
  14164. this._loadPhysicsSystem();
  14165. // create a frame and canvas
  14166. this._create();
  14167. // load the sector system. (mandatory, fully integrated with Graph)
  14168. this._loadSectorSystem();
  14169. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  14170. this._loadClusterSystem();
  14171. // load the selection system. (mandatory, required by Graph)
  14172. this._loadSelectionSystem();
  14173. // load the selection system. (mandatory, required by Graph)
  14174. this._loadHierarchySystem();
  14175. // apply options
  14176. this.setOptions(options);
  14177. // other vars
  14178. this.freezeSimulation = false;// freeze the simulation
  14179. this.cachedFunctions = {};
  14180. // containers for nodes and edges
  14181. this.calculationNodes = {};
  14182. this.calculationNodeIndices = [];
  14183. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  14184. this.nodes = {}; // object with Node objects
  14185. this.edges = {}; // object with Edge objects
  14186. // position and scale variables and objects
  14187. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  14188. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  14189. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  14190. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  14191. this.scale = 1; // defining the global scale variable in the constructor
  14192. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  14193. // datasets or dataviews
  14194. this.nodesData = null; // A DataSet or DataView
  14195. this.edgesData = null; // A DataSet or DataView
  14196. // create event listeners used to subscribe on the DataSets of the nodes and edges
  14197. this.nodesListeners = {
  14198. 'add': function (event, params) {
  14199. graph._addNodes(params.items);
  14200. graph.start();
  14201. },
  14202. 'update': function (event, params) {
  14203. graph._updateNodes(params.items);
  14204. graph.start();
  14205. },
  14206. 'remove': function (event, params) {
  14207. graph._removeNodes(params.items);
  14208. graph.start();
  14209. }
  14210. };
  14211. this.edgesListeners = {
  14212. 'add': function (event, params) {
  14213. graph._addEdges(params.items);
  14214. graph.start();
  14215. },
  14216. 'update': function (event, params) {
  14217. graph._updateEdges(params.items);
  14218. graph.start();
  14219. },
  14220. 'remove': function (event, params) {
  14221. graph._removeEdges(params.items);
  14222. graph.start();
  14223. }
  14224. };
  14225. // properties for the animation
  14226. this.moving = true;
  14227. this.timer = undefined; // Scheduling function. Is definded in this.start();
  14228. // load data (the disable start variable will be the same as the enabled clustering)
  14229. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  14230. // hierarchical layout
  14231. this.initializing = false;
  14232. if (this.constants.hierarchicalLayout.enabled == true) {
  14233. this._setupHierarchicalLayout();
  14234. }
  14235. else {
  14236. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  14237. if (this.stabilize == false) {
  14238. this.zoomExtent(true,this.constants.clustering.enabled);
  14239. }
  14240. }
  14241. // if clustering is disabled, the simulation will have started in the setData function
  14242. if (this.constants.clustering.enabled) {
  14243. this.startWithClustering();
  14244. }
  14245. }
  14246. // Extend Graph with an Emitter mixin
  14247. Emitter(Graph.prototype);
  14248. /**
  14249. * Get the script path where the vis.js library is located
  14250. *
  14251. * @returns {string | null} path Path or null when not found. Path does not
  14252. * end with a slash.
  14253. * @private
  14254. */
  14255. Graph.prototype._getScriptPath = function() {
  14256. var scripts = document.getElementsByTagName( 'script' );
  14257. // find script named vis.js or vis.min.js
  14258. for (var i = 0; i < scripts.length; i++) {
  14259. var src = scripts[i].src;
  14260. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  14261. if (match) {
  14262. // return path without the script name
  14263. return src.substring(0, src.length - match[0].length);
  14264. }
  14265. }
  14266. return null;
  14267. };
  14268. /**
  14269. * Find the center position of the graph
  14270. * @private
  14271. */
  14272. Graph.prototype._getRange = function() {
  14273. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  14274. for (var nodeId in this.nodes) {
  14275. if (this.nodes.hasOwnProperty(nodeId)) {
  14276. node = this.nodes[nodeId];
  14277. if (minX > (node.x)) {minX = node.x;}
  14278. if (maxX < (node.x)) {maxX = node.x;}
  14279. if (minY > (node.y)) {minY = node.y;}
  14280. if (maxY < (node.y)) {maxY = node.y;}
  14281. }
  14282. }
  14283. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  14284. minY = 0, maxY = 0, minX = 0, maxX = 0;
  14285. }
  14286. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14287. };
  14288. /**
  14289. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14290. * @returns {{x: number, y: number}}
  14291. * @private
  14292. */
  14293. Graph.prototype._findCenter = function(range) {
  14294. return {x: (0.5 * (range.maxX + range.minX)),
  14295. y: (0.5 * (range.maxY + range.minY))};
  14296. };
  14297. /**
  14298. * center the graph
  14299. *
  14300. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14301. */
  14302. Graph.prototype._centerGraph = function(range) {
  14303. var center = this._findCenter(range);
  14304. center.x *= this.scale;
  14305. center.y *= this.scale;
  14306. center.x -= 0.5 * this.frame.canvas.clientWidth;
  14307. center.y -= 0.5 * this.frame.canvas.clientHeight;
  14308. this._setTranslation(-center.x,-center.y); // set at 0,0
  14309. };
  14310. /**
  14311. * This function zooms out to fit all data on screen based on amount of nodes
  14312. *
  14313. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  14314. */
  14315. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  14316. if (initialZoom === undefined) {
  14317. initialZoom = false;
  14318. }
  14319. if (disableStart === undefined) {
  14320. disableStart = false;
  14321. }
  14322. var range = this._getRange();
  14323. var zoomLevel;
  14324. if (initialZoom == true) {
  14325. var numberOfNodes = this.nodeIndices.length;
  14326. if (this.constants.smoothCurves == true) {
  14327. if (this.constants.clustering.enabled == true &&
  14328. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14329. 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.
  14330. }
  14331. else {
  14332. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14333. }
  14334. }
  14335. else {
  14336. if (this.constants.clustering.enabled == true &&
  14337. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14338. 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.
  14339. }
  14340. else {
  14341. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14342. }
  14343. }
  14344. // correct for larger canvasses.
  14345. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  14346. zoomLevel *= factor;
  14347. }
  14348. else {
  14349. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  14350. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  14351. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  14352. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  14353. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  14354. }
  14355. if (zoomLevel > 1.0) {
  14356. zoomLevel = 1.0;
  14357. }
  14358. this._setScale(zoomLevel);
  14359. this._centerGraph(range);
  14360. if (disableStart == false) {
  14361. this.moving = true;
  14362. this.start();
  14363. }
  14364. };
  14365. /**
  14366. * Update the this.nodeIndices with the most recent node index list
  14367. * @private
  14368. */
  14369. Graph.prototype._updateNodeIndexList = function() {
  14370. this._clearNodeIndexList();
  14371. for (var idx in this.nodes) {
  14372. if (this.nodes.hasOwnProperty(idx)) {
  14373. this.nodeIndices.push(idx);
  14374. }
  14375. }
  14376. };
  14377. /**
  14378. * Set nodes and edges, and optionally options as well.
  14379. *
  14380. * @param {Object} data Object containing parameters:
  14381. * {Array | DataSet | DataView} [nodes] Array with nodes
  14382. * {Array | DataSet | DataView} [edges] Array with edges
  14383. * {String} [dot] String containing data in DOT format
  14384. * {Options} [options] Object with options
  14385. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  14386. */
  14387. Graph.prototype.setData = function(data, disableStart) {
  14388. if (disableStart === undefined) {
  14389. disableStart = false;
  14390. }
  14391. if (data && data.dot && (data.nodes || data.edges)) {
  14392. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  14393. ' parameter pair "nodes" and "edges", but not both.');
  14394. }
  14395. // set options
  14396. this.setOptions(data && data.options);
  14397. // set all data
  14398. if (data && data.dot) {
  14399. // parse DOT file
  14400. if(data && data.dot) {
  14401. var dotData = vis.util.DOTToGraph(data.dot);
  14402. this.setData(dotData);
  14403. return;
  14404. }
  14405. }
  14406. else {
  14407. this._setNodes(data && data.nodes);
  14408. this._setEdges(data && data.edges);
  14409. }
  14410. this._putDataInSector();
  14411. if (!disableStart) {
  14412. // find a stable position or start animating to a stable position
  14413. if (this.stabilize) {
  14414. this._stabilize();
  14415. }
  14416. this.start();
  14417. }
  14418. };
  14419. /**
  14420. * Set options
  14421. * @param {Object} options
  14422. */
  14423. Graph.prototype.setOptions = function (options) {
  14424. if (options) {
  14425. var prop;
  14426. // retrieve parameter values
  14427. if (options.width !== undefined) {this.width = options.width;}
  14428. if (options.height !== undefined) {this.height = options.height;}
  14429. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14430. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14431. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14432. if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;}
  14433. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14434. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  14435. if (options.onAdd) {
  14436. this.triggerFunctions.add = options.onAdd;
  14437. }
  14438. if (options.onEdit) {
  14439. this.triggerFunctions.edit = options.onEdit;
  14440. }
  14441. if (options.onConnect) {
  14442. this.triggerFunctions.connect = options.onConnect;
  14443. }
  14444. if (options.onDelete) {
  14445. this.triggerFunctions.delete = options.onDelete;
  14446. }
  14447. if (options.physics) {
  14448. if (options.physics.barnesHut) {
  14449. this.constants.physics.barnesHut.enabled = true;
  14450. for (prop in options.physics.barnesHut) {
  14451. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14452. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14453. }
  14454. }
  14455. }
  14456. if (options.physics.repulsion) {
  14457. this.constants.physics.barnesHut.enabled = false;
  14458. for (prop in options.physics.repulsion) {
  14459. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14460. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14461. }
  14462. }
  14463. }
  14464. }
  14465. if (options.hierarchicalLayout) {
  14466. this.constants.hierarchicalLayout.enabled = true;
  14467. for (prop in options.hierarchicalLayout) {
  14468. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14469. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14470. }
  14471. }
  14472. }
  14473. else if (options.hierarchicalLayout !== undefined) {
  14474. this.constants.hierarchicalLayout.enabled = false;
  14475. }
  14476. if (options.clustering) {
  14477. this.constants.clustering.enabled = true;
  14478. for (prop in options.clustering) {
  14479. if (options.clustering.hasOwnProperty(prop)) {
  14480. this.constants.clustering[prop] = options.clustering[prop];
  14481. }
  14482. }
  14483. }
  14484. else if (options.clustering !== undefined) {
  14485. this.constants.clustering.enabled = false;
  14486. }
  14487. if (options.navigation) {
  14488. this.constants.navigation.enabled = true;
  14489. for (prop in options.navigation) {
  14490. if (options.navigation.hasOwnProperty(prop)) {
  14491. this.constants.navigation[prop] = options.navigation[prop];
  14492. }
  14493. }
  14494. }
  14495. else if (options.navigation !== undefined) {
  14496. this.constants.navigation.enabled = false;
  14497. }
  14498. if (options.keyboard) {
  14499. this.constants.keyboard.enabled = true;
  14500. for (prop in options.keyboard) {
  14501. if (options.keyboard.hasOwnProperty(prop)) {
  14502. this.constants.keyboard[prop] = options.keyboard[prop];
  14503. }
  14504. }
  14505. }
  14506. else if (options.keyboard !== undefined) {
  14507. this.constants.keyboard.enabled = false;
  14508. }
  14509. if (options.dataManipulation) {
  14510. this.constants.dataManipulation.enabled = true;
  14511. for (prop in options.dataManipulation) {
  14512. if (options.dataManipulation.hasOwnProperty(prop)) {
  14513. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14514. }
  14515. }
  14516. }
  14517. else if (options.dataManipulation !== undefined) {
  14518. this.constants.dataManipulation.enabled = false;
  14519. }
  14520. // TODO: work out these options and document them
  14521. if (options.edges) {
  14522. for (prop in options.edges) {
  14523. if (options.edges.hasOwnProperty(prop)) {
  14524. if (typeof options.edges[prop] != "object") {
  14525. this.constants.edges[prop] = options.edges[prop];
  14526. }
  14527. }
  14528. }
  14529. if (options.edges.color !== undefined) {
  14530. if (util.isString(options.edges.color)) {
  14531. this.constants.edges.color.color = options.edges.color;
  14532. this.constants.edges.color.highlight = options.edges.color;
  14533. }
  14534. else {
  14535. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  14536. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  14537. }
  14538. }
  14539. if (!options.edges.fontColor) {
  14540. if (options.edges.color !== undefined) {
  14541. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  14542. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  14543. }
  14544. }
  14545. // Added to support dashed lines
  14546. // David Jordan
  14547. // 2012-08-08
  14548. if (options.edges.dash) {
  14549. if (options.edges.dash.length !== undefined) {
  14550. this.constants.edges.dash.length = options.edges.dash.length;
  14551. }
  14552. if (options.edges.dash.gap !== undefined) {
  14553. this.constants.edges.dash.gap = options.edges.dash.gap;
  14554. }
  14555. if (options.edges.dash.altLength !== undefined) {
  14556. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14557. }
  14558. }
  14559. }
  14560. if (options.nodes) {
  14561. for (prop in options.nodes) {
  14562. if (options.nodes.hasOwnProperty(prop)) {
  14563. this.constants.nodes[prop] = options.nodes[prop];
  14564. }
  14565. }
  14566. if (options.nodes.color) {
  14567. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  14568. }
  14569. /*
  14570. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14571. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14572. */
  14573. }
  14574. if (options.groups) {
  14575. for (var groupname in options.groups) {
  14576. if (options.groups.hasOwnProperty(groupname)) {
  14577. var group = options.groups[groupname];
  14578. this.groups.add(groupname, group);
  14579. }
  14580. }
  14581. }
  14582. if (options.tooltip) {
  14583. for (prop in options.tooltip) {
  14584. if (options.tooltip.hasOwnProperty(prop)) {
  14585. this.constants.tooltip[prop] = options.tooltip[prop];
  14586. }
  14587. }
  14588. }
  14589. }
  14590. // (Re)loading the mixins that can be enabled or disabled in the options.
  14591. // load the force calculation functions, grouped under the physics system.
  14592. this._loadPhysicsSystem();
  14593. // load the navigation system.
  14594. this._loadNavigationControls();
  14595. // load the data manipulation system
  14596. this._loadManipulationSystem();
  14597. // configure the smooth curves
  14598. this._configureSmoothCurves();
  14599. // bind keys. If disabled, this will not do anything;
  14600. this._createKeyBinds();
  14601. this.setSize(this.width, this.height);
  14602. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14603. this._setScale(1);
  14604. this._redraw();
  14605. };
  14606. /**
  14607. * Create the main frame for the Graph.
  14608. * This function is executed once when a Graph object is created. The frame
  14609. * contains a canvas, and this canvas contains all objects like the axis and
  14610. * nodes.
  14611. * @private
  14612. */
  14613. Graph.prototype._create = function () {
  14614. // remove all elements from the container element.
  14615. while (this.containerElement.hasChildNodes()) {
  14616. this.containerElement.removeChild(this.containerElement.firstChild);
  14617. }
  14618. this.frame = document.createElement('div');
  14619. this.frame.className = 'graph-frame';
  14620. this.frame.style.position = 'relative';
  14621. this.frame.style.overflow = 'hidden';
  14622. this.frame.style.zIndex = "1";
  14623. // create the graph canvas (HTML canvas element)
  14624. this.frame.canvas = document.createElement( 'canvas' );
  14625. this.frame.canvas.style.position = 'relative';
  14626. this.frame.appendChild(this.frame.canvas);
  14627. if (!this.frame.canvas.getContext) {
  14628. var noCanvas = document.createElement( 'DIV' );
  14629. noCanvas.style.color = 'red';
  14630. noCanvas.style.fontWeight = 'bold' ;
  14631. noCanvas.style.padding = '10px';
  14632. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14633. this.frame.canvas.appendChild(noCanvas);
  14634. }
  14635. var me = this;
  14636. this.drag = {};
  14637. this.pinch = {};
  14638. this.hammer = Hammer(this.frame.canvas, {
  14639. prevent_default: true
  14640. });
  14641. this.hammer.on('tap', me._onTap.bind(me) );
  14642. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14643. this.hammer.on('hold', me._onHold.bind(me) );
  14644. this.hammer.on('pinch', me._onPinch.bind(me) );
  14645. this.hammer.on('touch', me._onTouch.bind(me) );
  14646. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14647. this.hammer.on('drag', me._onDrag.bind(me) );
  14648. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14649. this.hammer.on('release', me._onRelease.bind(me) );
  14650. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14651. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14652. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14653. // add the frame to the container element
  14654. this.containerElement.appendChild(this.frame);
  14655. };
  14656. /**
  14657. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14658. * @private
  14659. */
  14660. Graph.prototype._createKeyBinds = function() {
  14661. var me = this;
  14662. this.mousetrap = mousetrap;
  14663. this.mousetrap.reset();
  14664. if (this.constants.keyboard.enabled == true) {
  14665. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14666. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14667. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14668. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14669. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14670. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14671. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14672. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14673. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14674. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14675. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14676. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14677. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14678. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14679. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14680. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14681. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14682. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14683. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14684. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14685. }
  14686. if (this.constants.dataManipulation.enabled == true) {
  14687. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14688. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14689. }
  14690. };
  14691. /**
  14692. * Get the pointer location from a touch location
  14693. * @param {{pageX: Number, pageY: Number}} touch
  14694. * @return {{x: Number, y: Number}} pointer
  14695. * @private
  14696. */
  14697. Graph.prototype._getPointer = function (touch) {
  14698. return {
  14699. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14700. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14701. };
  14702. };
  14703. /**
  14704. * On start of a touch gesture, store the pointer
  14705. * @param event
  14706. * @private
  14707. */
  14708. Graph.prototype._onTouch = function (event) {
  14709. this.drag.pointer = this._getPointer(event.gesture.center);
  14710. this.drag.pinched = false;
  14711. this.pinch.scale = this._getScale();
  14712. this._handleTouch(this.drag.pointer);
  14713. };
  14714. /**
  14715. * handle drag start event
  14716. * @private
  14717. */
  14718. Graph.prototype._onDragStart = function () {
  14719. this._handleDragStart();
  14720. };
  14721. /**
  14722. * This function is called by _onDragStart.
  14723. * It is separated out because we can then overload it for the datamanipulation system.
  14724. *
  14725. * @private
  14726. */
  14727. Graph.prototype._handleDragStart = function() {
  14728. var drag = this.drag;
  14729. var node = this._getNodeAt(drag.pointer);
  14730. // note: drag.pointer is set in _onTouch to get the initial touch location
  14731. drag.dragging = true;
  14732. drag.selection = [];
  14733. drag.translation = this._getTranslation();
  14734. drag.nodeId = null;
  14735. if (node != null) {
  14736. drag.nodeId = node.id;
  14737. // select the clicked node if not yet selected
  14738. if (!node.isSelected()) {
  14739. this._selectObject(node,false);
  14740. }
  14741. // create an array with the selected nodes and their original location and status
  14742. for (var objectId in this.selectionObj.nodes) {
  14743. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  14744. var object = this.selectionObj.nodes[objectId];
  14745. var s = {
  14746. id: object.id,
  14747. node: object,
  14748. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14749. x: object.x,
  14750. y: object.y,
  14751. xFixed: object.xFixed,
  14752. yFixed: object.yFixed
  14753. };
  14754. object.xFixed = true;
  14755. object.yFixed = true;
  14756. drag.selection.push(s);
  14757. }
  14758. }
  14759. }
  14760. };
  14761. /**
  14762. * handle drag event
  14763. * @private
  14764. */
  14765. Graph.prototype._onDrag = function (event) {
  14766. this._handleOnDrag(event)
  14767. };
  14768. /**
  14769. * This function is called by _onDrag.
  14770. * It is separated out because we can then overload it for the datamanipulation system.
  14771. *
  14772. * @private
  14773. */
  14774. Graph.prototype._handleOnDrag = function(event) {
  14775. if (this.drag.pinched) {
  14776. return;
  14777. }
  14778. var pointer = this._getPointer(event.gesture.center);
  14779. var me = this,
  14780. drag = this.drag,
  14781. selection = drag.selection;
  14782. if (selection && selection.length) {
  14783. // calculate delta's and new location
  14784. var deltaX = pointer.x - drag.pointer.x,
  14785. deltaY = pointer.y - drag.pointer.y;
  14786. // update position of all selected nodes
  14787. selection.forEach(function (s) {
  14788. var node = s.node;
  14789. if (!s.xFixed) {
  14790. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14791. }
  14792. if (!s.yFixed) {
  14793. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14794. }
  14795. });
  14796. // start _animationStep if not yet running
  14797. if (!this.moving) {
  14798. this.moving = true;
  14799. this.start();
  14800. }
  14801. }
  14802. else {
  14803. // move the graph
  14804. var diffX = pointer.x - this.drag.pointer.x;
  14805. var diffY = pointer.y - this.drag.pointer.y;
  14806. this._setTranslation(
  14807. this.drag.translation.x + diffX,
  14808. this.drag.translation.y + diffY);
  14809. this._redraw();
  14810. this.moved = true;
  14811. }
  14812. };
  14813. /**
  14814. * handle drag start event
  14815. * @private
  14816. */
  14817. Graph.prototype._onDragEnd = function () {
  14818. this.drag.dragging = false;
  14819. var selection = this.drag.selection;
  14820. if (selection) {
  14821. selection.forEach(function (s) {
  14822. // restore original xFixed and yFixed
  14823. s.node.xFixed = s.xFixed;
  14824. s.node.yFixed = s.yFixed;
  14825. });
  14826. }
  14827. };
  14828. /**
  14829. * handle tap/click event: select/unselect a node
  14830. * @private
  14831. */
  14832. Graph.prototype._onTap = function (event) {
  14833. var pointer = this._getPointer(event.gesture.center);
  14834. this.pointerPosition = pointer;
  14835. this._handleTap(pointer);
  14836. };
  14837. /**
  14838. * handle doubletap event
  14839. * @private
  14840. */
  14841. Graph.prototype._onDoubleTap = function (event) {
  14842. var pointer = this._getPointer(event.gesture.center);
  14843. this._handleDoubleTap(pointer);
  14844. };
  14845. /**
  14846. * handle long tap event: multi select nodes
  14847. * @private
  14848. */
  14849. Graph.prototype._onHold = function (event) {
  14850. var pointer = this._getPointer(event.gesture.center);
  14851. this.pointerPosition = pointer;
  14852. this._handleOnHold(pointer);
  14853. };
  14854. /**
  14855. * handle the release of the screen
  14856. *
  14857. * @private
  14858. */
  14859. Graph.prototype._onRelease = function (event) {
  14860. var pointer = this._getPointer(event.gesture.center);
  14861. this._handleOnRelease(pointer);
  14862. };
  14863. /**
  14864. * Handle pinch event
  14865. * @param event
  14866. * @private
  14867. */
  14868. Graph.prototype._onPinch = function (event) {
  14869. var pointer = this._getPointer(event.gesture.center);
  14870. this.drag.pinched = true;
  14871. if (!('scale' in this.pinch)) {
  14872. this.pinch.scale = 1;
  14873. }
  14874. // TODO: enabled moving while pinching?
  14875. var scale = this.pinch.scale * event.gesture.scale;
  14876. this._zoom(scale, pointer)
  14877. };
  14878. /**
  14879. * Zoom the graph in or out
  14880. * @param {Number} scale a number around 1, and between 0.01 and 10
  14881. * @param {{x: Number, y: Number}} pointer Position on screen
  14882. * @return {Number} appliedScale scale is limited within the boundaries
  14883. * @private
  14884. */
  14885. Graph.prototype._zoom = function(scale, pointer) {
  14886. var scaleOld = this._getScale();
  14887. if (scale < 0.00001) {
  14888. scale = 0.00001;
  14889. }
  14890. if (scale > 10) {
  14891. scale = 10;
  14892. }
  14893. // + this.frame.canvas.clientHeight / 2
  14894. var translation = this._getTranslation();
  14895. var scaleFrac = scale / scaleOld;
  14896. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14897. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14898. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  14899. "y" : this._canvasToY(pointer.y)};
  14900. this._setScale(scale);
  14901. this._setTranslation(tx, ty);
  14902. this.updateClustersDefault();
  14903. this._redraw();
  14904. return scale;
  14905. };
  14906. /**
  14907. * Event handler for mouse wheel event, used to zoom the timeline
  14908. * See http://adomas.org/javascript-mouse-wheel/
  14909. * https://github.com/EightMedia/hammer.js/issues/256
  14910. * @param {MouseEvent} event
  14911. * @private
  14912. */
  14913. Graph.prototype._onMouseWheel = function(event) {
  14914. // retrieve delta
  14915. var delta = 0;
  14916. if (event.wheelDelta) { /* IE/Opera. */
  14917. delta = event.wheelDelta/120;
  14918. } else if (event.detail) { /* Mozilla case. */
  14919. // In Mozilla, sign of delta is different than in IE.
  14920. // Also, delta is multiple of 3.
  14921. delta = -event.detail/3;
  14922. }
  14923. // If delta is nonzero, handle it.
  14924. // Basically, delta is now positive if wheel was scrolled up,
  14925. // and negative, if wheel was scrolled down.
  14926. if (delta) {
  14927. // calculate the new scale
  14928. var scale = this._getScale();
  14929. var zoom = delta / 10;
  14930. if (delta < 0) {
  14931. zoom = zoom / (1 - zoom);
  14932. }
  14933. scale *= (1 + zoom);
  14934. // calculate the pointer location
  14935. var gesture = util.fakeGesture(this, event);
  14936. var pointer = this._getPointer(gesture.center);
  14937. // apply the new scale
  14938. this._zoom(scale, pointer);
  14939. }
  14940. // Prevent default actions caused by mouse wheel.
  14941. event.preventDefault();
  14942. };
  14943. /**
  14944. * Mouse move handler for checking whether the title moves over a node with a title.
  14945. * @param {Event} event
  14946. * @private
  14947. */
  14948. Graph.prototype._onMouseMoveTitle = function (event) {
  14949. var gesture = util.fakeGesture(this, event);
  14950. var pointer = this._getPointer(gesture.center);
  14951. // check if the previously selected node is still selected
  14952. if (this.popupNode) {
  14953. this._checkHidePopup(pointer);
  14954. }
  14955. // start a timeout that will check if the mouse is positioned above
  14956. // an element
  14957. var me = this;
  14958. var checkShow = function() {
  14959. me._checkShowPopup(pointer);
  14960. };
  14961. if (this.popupTimer) {
  14962. clearInterval(this.popupTimer); // stop any running calculationTimer
  14963. }
  14964. if (!this.drag.dragging) {
  14965. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  14966. }
  14967. };
  14968. /**
  14969. * Check if there is an element on the given position in the graph
  14970. * (a node or edge). If so, and if this element has a title,
  14971. * show a popup window with its title.
  14972. *
  14973. * @param {{x:Number, y:Number}} pointer
  14974. * @private
  14975. */
  14976. Graph.prototype._checkShowPopup = function (pointer) {
  14977. var obj = {
  14978. left: this._canvasToX(pointer.x),
  14979. top: this._canvasToY(pointer.y),
  14980. right: this._canvasToX(pointer.x),
  14981. bottom: this._canvasToY(pointer.y)
  14982. };
  14983. var id;
  14984. var lastPopupNode = this.popupNode;
  14985. if (this.popupNode == undefined) {
  14986. // search the nodes for overlap, select the top one in case of multiple nodes
  14987. var nodes = this.nodes;
  14988. for (id in nodes) {
  14989. if (nodes.hasOwnProperty(id)) {
  14990. var node = nodes[id];
  14991. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14992. this.popupNode = node;
  14993. break;
  14994. }
  14995. }
  14996. }
  14997. }
  14998. if (this.popupNode === undefined) {
  14999. // search the edges for overlap
  15000. var edges = this.edges;
  15001. for (id in edges) {
  15002. if (edges.hasOwnProperty(id)) {
  15003. var edge = edges[id];
  15004. if (edge.connected && (edge.getTitle() !== undefined) &&
  15005. edge.isOverlappingWith(obj)) {
  15006. this.popupNode = edge;
  15007. break;
  15008. }
  15009. }
  15010. }
  15011. }
  15012. if (this.popupNode) {
  15013. // show popup message window
  15014. if (this.popupNode != lastPopupNode) {
  15015. var me = this;
  15016. if (!me.popup) {
  15017. me.popup = new Popup(me.frame);
  15018. }
  15019. // adjust a small offset such that the mouse cursor is located in the
  15020. // bottom left location of the popup, and you can easily move over the
  15021. // popup area
  15022. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  15023. me.popup.setText(me.popupNode.getTitle());
  15024. me.popup.show();
  15025. }
  15026. }
  15027. else {
  15028. if (this.popup) {
  15029. this.popup.hide();
  15030. }
  15031. }
  15032. };
  15033. /**
  15034. * Check if the popup must be hided, which is the case when the mouse is no
  15035. * longer hovering on the object
  15036. * @param {{x:Number, y:Number}} pointer
  15037. * @private
  15038. */
  15039. Graph.prototype._checkHidePopup = function (pointer) {
  15040. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  15041. this.popupNode = undefined;
  15042. if (this.popup) {
  15043. this.popup.hide();
  15044. }
  15045. }
  15046. };
  15047. /**
  15048. * Set a new size for the graph
  15049. * @param {string} width Width in pixels or percentage (for example '800px'
  15050. * or '50%')
  15051. * @param {string} height Height in pixels or percentage (for example '400px'
  15052. * or '30%')
  15053. */
  15054. Graph.prototype.setSize = function(width, height) {
  15055. this.frame.style.width = width;
  15056. this.frame.style.height = height;
  15057. this.frame.canvas.style.width = '100%';
  15058. this.frame.canvas.style.height = '100%';
  15059. this.frame.canvas.width = this.frame.canvas.clientWidth;
  15060. this.frame.canvas.height = this.frame.canvas.clientHeight;
  15061. if (this.manipulationDiv !== undefined) {
  15062. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  15063. }
  15064. if (this.navigationDivs !== undefined) {
  15065. if (this.navigationDivs['wrapper'] !== undefined) {
  15066. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  15067. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  15068. }
  15069. }
  15070. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  15071. };
  15072. /**
  15073. * Set a data set with nodes for the graph
  15074. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  15075. * @private
  15076. */
  15077. Graph.prototype._setNodes = function(nodes) {
  15078. var oldNodesData = this.nodesData;
  15079. if (nodes instanceof DataSet || nodes instanceof DataView) {
  15080. this.nodesData = nodes;
  15081. }
  15082. else if (nodes instanceof Array) {
  15083. this.nodesData = new DataSet();
  15084. this.nodesData.add(nodes);
  15085. }
  15086. else if (!nodes) {
  15087. this.nodesData = new DataSet();
  15088. }
  15089. else {
  15090. throw new TypeError('Array or DataSet expected');
  15091. }
  15092. if (oldNodesData) {
  15093. // unsubscribe from old dataset
  15094. util.forEach(this.nodesListeners, function (callback, event) {
  15095. oldNodesData.off(event, callback);
  15096. });
  15097. }
  15098. // remove drawn nodes
  15099. this.nodes = {};
  15100. if (this.nodesData) {
  15101. // subscribe to new dataset
  15102. var me = this;
  15103. util.forEach(this.nodesListeners, function (callback, event) {
  15104. me.nodesData.on(event, callback);
  15105. });
  15106. // draw all new nodes
  15107. var ids = this.nodesData.getIds();
  15108. this._addNodes(ids);
  15109. }
  15110. this._updateSelection();
  15111. };
  15112. /**
  15113. * Add nodes
  15114. * @param {Number[] | String[]} ids
  15115. * @private
  15116. */
  15117. Graph.prototype._addNodes = function(ids) {
  15118. var id;
  15119. for (var i = 0, len = ids.length; i < len; i++) {
  15120. id = ids[i];
  15121. var data = this.nodesData.get(id);
  15122. var node = new Node(data, this.images, this.groups, this.constants);
  15123. this.nodes[id] = node; // note: this may replace an existing node
  15124. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  15125. var radius = 10 * 0.1*ids.length;
  15126. var angle = 2 * Math.PI * Math.random();
  15127. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  15128. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  15129. }
  15130. this.moving = true;
  15131. }
  15132. this._updateNodeIndexList();
  15133. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15134. this._resetLevels();
  15135. this._setupHierarchicalLayout();
  15136. }
  15137. this._updateCalculationNodes();
  15138. this._reconnectEdges();
  15139. this._updateValueRange(this.nodes);
  15140. this.updateLabels();
  15141. };
  15142. /**
  15143. * Update existing nodes, or create them when not yet existing
  15144. * @param {Number[] | String[]} ids
  15145. * @private
  15146. */
  15147. Graph.prototype._updateNodes = function(ids) {
  15148. var nodes = this.nodes,
  15149. nodesData = this.nodesData;
  15150. for (var i = 0, len = ids.length; i < len; i++) {
  15151. var id = ids[i];
  15152. var node = nodes[id];
  15153. var data = nodesData.get(id);
  15154. if (node) {
  15155. // update node
  15156. node.setProperties(data, this.constants);
  15157. }
  15158. else {
  15159. // create node
  15160. node = new Node(properties, this.images, this.groups, this.constants);
  15161. nodes[id] = node;
  15162. if (!node.isFixed()) {
  15163. this.moving = true;
  15164. }
  15165. }
  15166. }
  15167. this._updateNodeIndexList();
  15168. this._reconnectEdges();
  15169. this._updateValueRange(nodes);
  15170. };
  15171. /**
  15172. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  15173. * @param {Number[] | String[]} ids
  15174. * @private
  15175. */
  15176. Graph.prototype._removeNodes = function(ids) {
  15177. var nodes = this.nodes;
  15178. for (var i = 0, len = ids.length; i < len; i++) {
  15179. var id = ids[i];
  15180. delete nodes[id];
  15181. }
  15182. this._updateNodeIndexList();
  15183. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15184. this._resetLevels();
  15185. this._setupHierarchicalLayout();
  15186. }
  15187. this._updateCalculationNodes();
  15188. this._reconnectEdges();
  15189. this._updateSelection();
  15190. this._updateValueRange(nodes);
  15191. };
  15192. /**
  15193. * Load edges by reading the data table
  15194. * @param {Array | DataSet | DataView} edges The data containing the edges.
  15195. * @private
  15196. * @private
  15197. */
  15198. Graph.prototype._setEdges = function(edges) {
  15199. var oldEdgesData = this.edgesData;
  15200. if (edges instanceof DataSet || edges instanceof DataView) {
  15201. this.edgesData = edges;
  15202. }
  15203. else if (edges instanceof Array) {
  15204. this.edgesData = new DataSet();
  15205. this.edgesData.add(edges);
  15206. }
  15207. else if (!edges) {
  15208. this.edgesData = new DataSet();
  15209. }
  15210. else {
  15211. throw new TypeError('Array or DataSet expected');
  15212. }
  15213. if (oldEdgesData) {
  15214. // unsubscribe from old dataset
  15215. util.forEach(this.edgesListeners, function (callback, event) {
  15216. oldEdgesData.off(event, callback);
  15217. });
  15218. }
  15219. // remove drawn edges
  15220. this.edges = {};
  15221. if (this.edgesData) {
  15222. // subscribe to new dataset
  15223. var me = this;
  15224. util.forEach(this.edgesListeners, function (callback, event) {
  15225. me.edgesData.on(event, callback);
  15226. });
  15227. // draw all new nodes
  15228. var ids = this.edgesData.getIds();
  15229. this._addEdges(ids);
  15230. }
  15231. this._reconnectEdges();
  15232. };
  15233. /**
  15234. * Add edges
  15235. * @param {Number[] | String[]} ids
  15236. * @private
  15237. */
  15238. Graph.prototype._addEdges = function (ids) {
  15239. var edges = this.edges,
  15240. edgesData = this.edgesData;
  15241. for (var i = 0, len = ids.length; i < len; i++) {
  15242. var id = ids[i];
  15243. var oldEdge = edges[id];
  15244. if (oldEdge) {
  15245. oldEdge.disconnect();
  15246. }
  15247. var data = edgesData.get(id, {"showInternalIds" : true});
  15248. edges[id] = new Edge(data, this, this.constants);
  15249. }
  15250. this.moving = true;
  15251. this._updateValueRange(edges);
  15252. this._createBezierNodes();
  15253. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15254. this._resetLevels();
  15255. this._setupHierarchicalLayout();
  15256. }
  15257. this._updateCalculationNodes();
  15258. };
  15259. /**
  15260. * Update existing edges, or create them when not yet existing
  15261. * @param {Number[] | String[]} ids
  15262. * @private
  15263. */
  15264. Graph.prototype._updateEdges = function (ids) {
  15265. var edges = this.edges,
  15266. edgesData = this.edgesData;
  15267. for (var i = 0, len = ids.length; i < len; i++) {
  15268. var id = ids[i];
  15269. var data = edgesData.get(id);
  15270. var edge = edges[id];
  15271. if (edge) {
  15272. // update edge
  15273. edge.disconnect();
  15274. edge.setProperties(data, this.constants);
  15275. edge.connect();
  15276. }
  15277. else {
  15278. // create edge
  15279. edge = new Edge(data, this, this.constants);
  15280. this.edges[id] = edge;
  15281. }
  15282. }
  15283. this._createBezierNodes();
  15284. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15285. this._resetLevels();
  15286. this._setupHierarchicalLayout();
  15287. }
  15288. this.moving = true;
  15289. this._updateValueRange(edges);
  15290. };
  15291. /**
  15292. * Remove existing edges. Non existing ids will be ignored
  15293. * @param {Number[] | String[]} ids
  15294. * @private
  15295. */
  15296. Graph.prototype._removeEdges = function (ids) {
  15297. var edges = this.edges;
  15298. for (var i = 0, len = ids.length; i < len; i++) {
  15299. var id = ids[i];
  15300. var edge = edges[id];
  15301. if (edge) {
  15302. if (edge.via != null) {
  15303. delete this.sectors['support']['nodes'][edge.via.id];
  15304. }
  15305. edge.disconnect();
  15306. delete edges[id];
  15307. }
  15308. }
  15309. this.moving = true;
  15310. this._updateValueRange(edges);
  15311. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15312. this._resetLevels();
  15313. this._setupHierarchicalLayout();
  15314. }
  15315. this._updateCalculationNodes();
  15316. };
  15317. /**
  15318. * Reconnect all edges
  15319. * @private
  15320. */
  15321. Graph.prototype._reconnectEdges = function() {
  15322. var id,
  15323. nodes = this.nodes,
  15324. edges = this.edges;
  15325. for (id in nodes) {
  15326. if (nodes.hasOwnProperty(id)) {
  15327. nodes[id].edges = [];
  15328. }
  15329. }
  15330. for (id in edges) {
  15331. if (edges.hasOwnProperty(id)) {
  15332. var edge = edges[id];
  15333. edge.from = null;
  15334. edge.to = null;
  15335. edge.connect();
  15336. }
  15337. }
  15338. };
  15339. /**
  15340. * Update the values of all object in the given array according to the current
  15341. * value range of the objects in the array.
  15342. * @param {Object} obj An object containing a set of Edges or Nodes
  15343. * The objects must have a method getValue() and
  15344. * setValueRange(min, max).
  15345. * @private
  15346. */
  15347. Graph.prototype._updateValueRange = function(obj) {
  15348. var id;
  15349. // determine the range of the objects
  15350. var valueMin = undefined;
  15351. var valueMax = undefined;
  15352. for (id in obj) {
  15353. if (obj.hasOwnProperty(id)) {
  15354. var value = obj[id].getValue();
  15355. if (value !== undefined) {
  15356. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  15357. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  15358. }
  15359. }
  15360. }
  15361. // adjust the range of all objects
  15362. if (valueMin !== undefined && valueMax !== undefined) {
  15363. for (id in obj) {
  15364. if (obj.hasOwnProperty(id)) {
  15365. obj[id].setValueRange(valueMin, valueMax);
  15366. }
  15367. }
  15368. }
  15369. };
  15370. /**
  15371. * Redraw the graph with the current data
  15372. * chart will be resized too.
  15373. */
  15374. Graph.prototype.redraw = function() {
  15375. this.setSize(this.width, this.height);
  15376. this._redraw();
  15377. };
  15378. /**
  15379. * Redraw the graph with the current data
  15380. * @private
  15381. */
  15382. Graph.prototype._redraw = function() {
  15383. var ctx = this.frame.canvas.getContext('2d');
  15384. // clear the canvas
  15385. var w = this.frame.canvas.width;
  15386. var h = this.frame.canvas.height;
  15387. ctx.clearRect(0, 0, w, h);
  15388. // set scaling and translation
  15389. ctx.save();
  15390. ctx.translate(this.translation.x, this.translation.y);
  15391. ctx.scale(this.scale, this.scale);
  15392. this.canvasTopLeft = {
  15393. "x": this._canvasToX(0),
  15394. "y": this._canvasToY(0)
  15395. };
  15396. this.canvasBottomRight = {
  15397. "x": this._canvasToX(this.frame.canvas.clientWidth),
  15398. "y": this._canvasToY(this.frame.canvas.clientHeight)
  15399. };
  15400. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15401. this._doInAllSectors("_drawEdges",ctx);
  15402. this._doInAllSectors("_drawNodes",ctx,false);
  15403. // this._doInSupportSector("_drawNodes",ctx,true);
  15404. // this._drawTree(ctx,"#F00F0F");
  15405. // restore original scaling and translation
  15406. ctx.restore();
  15407. };
  15408. /**
  15409. * Set the translation of the graph
  15410. * @param {Number} offsetX Horizontal offset
  15411. * @param {Number} offsetY Vertical offset
  15412. * @private
  15413. */
  15414. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15415. if (this.translation === undefined) {
  15416. this.translation = {
  15417. x: 0,
  15418. y: 0
  15419. };
  15420. }
  15421. if (offsetX !== undefined) {
  15422. this.translation.x = offsetX;
  15423. }
  15424. if (offsetY !== undefined) {
  15425. this.translation.y = offsetY;
  15426. }
  15427. };
  15428. /**
  15429. * Get the translation of the graph
  15430. * @return {Object} translation An object with parameters x and y, both a number
  15431. * @private
  15432. */
  15433. Graph.prototype._getTranslation = function() {
  15434. return {
  15435. x: this.translation.x,
  15436. y: this.translation.y
  15437. };
  15438. };
  15439. /**
  15440. * Scale the graph
  15441. * @param {Number} scale Scaling factor 1.0 is unscaled
  15442. * @private
  15443. */
  15444. Graph.prototype._setScale = function(scale) {
  15445. this.scale = scale;
  15446. };
  15447. /**
  15448. * Get the current scale of the graph
  15449. * @return {Number} scale Scaling factor 1.0 is unscaled
  15450. * @private
  15451. */
  15452. Graph.prototype._getScale = function() {
  15453. return this.scale;
  15454. };
  15455. /**
  15456. * Convert a horizontal point on the HTML canvas to the x-value of the model
  15457. * @param {number} x
  15458. * @returns {number}
  15459. * @private
  15460. */
  15461. Graph.prototype._canvasToX = function(x) {
  15462. return (x - this.translation.x) / this.scale;
  15463. };
  15464. /**
  15465. * Convert an x-value in the model to a horizontal point on the HTML canvas
  15466. * @param {number} x
  15467. * @returns {number}
  15468. * @private
  15469. */
  15470. Graph.prototype._xToCanvas = function(x) {
  15471. return x * this.scale + this.translation.x;
  15472. };
  15473. /**
  15474. * Convert a vertical point on the HTML canvas to the y-value of the model
  15475. * @param {number} y
  15476. * @returns {number}
  15477. * @private
  15478. */
  15479. Graph.prototype._canvasToY = function(y) {
  15480. return (y - this.translation.y) / this.scale;
  15481. };
  15482. /**
  15483. * Convert an y-value in the model to a vertical point on the HTML canvas
  15484. * @param {number} y
  15485. * @returns {number}
  15486. * @private
  15487. */
  15488. Graph.prototype._yToCanvas = function(y) {
  15489. return y * this.scale + this.translation.y ;
  15490. };
  15491. /**
  15492. * Redraw all nodes
  15493. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15494. * @param {CanvasRenderingContext2D} ctx
  15495. * @param {Boolean} [alwaysShow]
  15496. * @private
  15497. */
  15498. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  15499. if (alwaysShow === undefined) {
  15500. alwaysShow = false;
  15501. }
  15502. // first draw the unselected nodes
  15503. var nodes = this.nodes;
  15504. var selected = [];
  15505. for (var id in nodes) {
  15506. if (nodes.hasOwnProperty(id)) {
  15507. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15508. if (nodes[id].isSelected()) {
  15509. selected.push(id);
  15510. }
  15511. else {
  15512. if (nodes[id].inArea() || alwaysShow) {
  15513. nodes[id].draw(ctx);
  15514. }
  15515. }
  15516. }
  15517. }
  15518. // draw the selected nodes on top
  15519. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15520. if (nodes[selected[s]].inArea() || alwaysShow) {
  15521. nodes[selected[s]].draw(ctx);
  15522. }
  15523. }
  15524. };
  15525. /**
  15526. * Redraw all edges
  15527. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15528. * @param {CanvasRenderingContext2D} ctx
  15529. * @private
  15530. */
  15531. Graph.prototype._drawEdges = function(ctx) {
  15532. var edges = this.edges;
  15533. for (var id in edges) {
  15534. if (edges.hasOwnProperty(id)) {
  15535. var edge = edges[id];
  15536. edge.setScale(this.scale);
  15537. if (edge.connected) {
  15538. edges[id].draw(ctx);
  15539. }
  15540. }
  15541. }
  15542. };
  15543. /**
  15544. * Find a stable position for all nodes
  15545. * @private
  15546. */
  15547. Graph.prototype._stabilize = function() {
  15548. if (this.constants.freezeForStabilization == true) {
  15549. this._freezeDefinedNodes();
  15550. }
  15551. // find stable position
  15552. var count = 0;
  15553. while (this.moving && count < this.constants.stabilizationIterations) {
  15554. this._physicsTick();
  15555. count++;
  15556. }
  15557. this.zoomExtent(false,true);
  15558. if (this.constants.freezeForStabilization == true) {
  15559. this._restoreFrozenNodes();
  15560. }
  15561. this.emit("stabilized",{iterations:count});
  15562. };
  15563. Graph.prototype._freezeDefinedNodes = function() {
  15564. var nodes = this.nodes;
  15565. for (var id in nodes) {
  15566. if (nodes.hasOwnProperty(id)) {
  15567. if (nodes[id].x != null && nodes[id].y != null) {
  15568. nodes[id].fixedData.x = nodes[id].xFixed;
  15569. nodes[id].fixedData.y = nodes[id].yFixed;
  15570. nodes[id].xFixed = true;
  15571. nodes[id].yFixed = true;
  15572. }
  15573. }
  15574. }
  15575. };
  15576. Graph.prototype._restoreFrozenNodes = function() {
  15577. var nodes = this.nodes;
  15578. for (var id in nodes) {
  15579. if (nodes.hasOwnProperty(id)) {
  15580. if (nodes[id].fixedData.x != null) {
  15581. nodes[id].xFixed = nodes[id].fixedData.x;
  15582. nodes[id].yFixed = nodes[id].fixedData.y;
  15583. }
  15584. }
  15585. }
  15586. };
  15587. /**
  15588. * Check if any of the nodes is still moving
  15589. * @param {number} vmin the minimum velocity considered as 'moving'
  15590. * @return {boolean} true if moving, false if non of the nodes is moving
  15591. * @private
  15592. */
  15593. Graph.prototype._isMoving = function(vmin) {
  15594. var nodes = this.nodes;
  15595. for (var id in nodes) {
  15596. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15597. return true;
  15598. }
  15599. }
  15600. return false;
  15601. };
  15602. /**
  15603. * /**
  15604. * Perform one discrete step for all nodes
  15605. *
  15606. * @private
  15607. */
  15608. Graph.prototype._discreteStepNodes = function() {
  15609. var interval = this.physicsDiscreteStepsize;
  15610. var nodes = this.nodes;
  15611. var nodeId;
  15612. var nodesPresent = false;
  15613. if (this.constants.maxVelocity > 0) {
  15614. for (nodeId in nodes) {
  15615. if (nodes.hasOwnProperty(nodeId)) {
  15616. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15617. nodesPresent = true;
  15618. }
  15619. }
  15620. }
  15621. else {
  15622. for (nodeId in nodes) {
  15623. if (nodes.hasOwnProperty(nodeId)) {
  15624. nodes[nodeId].discreteStep(interval);
  15625. nodesPresent = true;
  15626. }
  15627. }
  15628. }
  15629. if (nodesPresent == true) {
  15630. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15631. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15632. this.moving = true;
  15633. }
  15634. else {
  15635. this.moving = this._isMoving(vminCorrected);
  15636. }
  15637. }
  15638. };
  15639. Graph.prototype._physicsTick = function() {
  15640. if (!this.freezeSimulation) {
  15641. if (this.moving) {
  15642. this._doInAllActiveSectors("_initializeForceCalculation");
  15643. this._doInAllActiveSectors("_discreteStepNodes");
  15644. if (this.constants.smoothCurves) {
  15645. this._doInSupportSector("_discreteStepNodes");
  15646. }
  15647. this._findCenter(this._getRange())
  15648. }
  15649. }
  15650. };
  15651. /**
  15652. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15653. * It reschedules itself at the beginning of the function
  15654. *
  15655. * @private
  15656. */
  15657. Graph.prototype._animationStep = function() {
  15658. // reset the timer so a new scheduled animation step can be set
  15659. this.timer = undefined;
  15660. // handle the keyboad movement
  15661. this._handleNavigation();
  15662. // this schedules a new animation step
  15663. this.start();
  15664. // start the physics simulation
  15665. var calculationTime = Date.now();
  15666. var maxSteps = 1;
  15667. this._physicsTick();
  15668. var timeRequired = Date.now() - calculationTime;
  15669. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  15670. this._physicsTick();
  15671. timeRequired = Date.now() - calculationTime;
  15672. maxSteps++;
  15673. }
  15674. // start the rendering process
  15675. var renderTime = Date.now();
  15676. this._redraw();
  15677. this.renderTime = Date.now() - renderTime;
  15678. };
  15679. if (typeof window !== 'undefined') {
  15680. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15681. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15682. }
  15683. /**
  15684. * Schedule a animation step with the refreshrate interval.
  15685. *
  15686. * @poram {Boolean} runCalculationStep
  15687. */
  15688. Graph.prototype.start = function() {
  15689. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15690. if (!this.timer) {
  15691. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15692. }
  15693. }
  15694. else {
  15695. this._redraw();
  15696. }
  15697. };
  15698. /**
  15699. * Move the graph according to the keyboard presses.
  15700. *
  15701. * @private
  15702. */
  15703. Graph.prototype._handleNavigation = function() {
  15704. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15705. var translation = this._getTranslation();
  15706. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15707. }
  15708. if (this.zoomIncrement != 0) {
  15709. var center = {
  15710. x: this.frame.canvas.clientWidth / 2,
  15711. y: this.frame.canvas.clientHeight / 2
  15712. };
  15713. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15714. }
  15715. };
  15716. /**
  15717. * Freeze the _animationStep
  15718. */
  15719. Graph.prototype.toggleFreeze = function() {
  15720. if (this.freezeSimulation == false) {
  15721. this.freezeSimulation = true;
  15722. }
  15723. else {
  15724. this.freezeSimulation = false;
  15725. this.start();
  15726. }
  15727. };
  15728. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15729. if (disableStart === undefined) {
  15730. disableStart = true;
  15731. }
  15732. if (this.constants.smoothCurves == true) {
  15733. this._createBezierNodes();
  15734. }
  15735. else {
  15736. // delete the support nodes
  15737. this.sectors['support']['nodes'] = {};
  15738. for (var edgeId in this.edges) {
  15739. if (this.edges.hasOwnProperty(edgeId)) {
  15740. this.edges[edgeId].smooth = false;
  15741. this.edges[edgeId].via = null;
  15742. }
  15743. }
  15744. }
  15745. this._updateCalculationNodes();
  15746. if (!disableStart) {
  15747. this.moving = true;
  15748. this.start();
  15749. }
  15750. };
  15751. Graph.prototype._createBezierNodes = function() {
  15752. if (this.constants.smoothCurves == true) {
  15753. for (var edgeId in this.edges) {
  15754. if (this.edges.hasOwnProperty(edgeId)) {
  15755. var edge = this.edges[edgeId];
  15756. if (edge.via == null) {
  15757. edge.smooth = true;
  15758. var nodeId = "edgeId:".concat(edge.id);
  15759. this.sectors['support']['nodes'][nodeId] = new Node(
  15760. {id:nodeId,
  15761. mass:1,
  15762. shape:'circle',
  15763. image:"",
  15764. internalMultiplier:1
  15765. },{},{},this.constants);
  15766. edge.via = this.sectors['support']['nodes'][nodeId];
  15767. edge.via.parentEdgeId = edge.id;
  15768. edge.positionBezierNode();
  15769. }
  15770. }
  15771. }
  15772. }
  15773. };
  15774. Graph.prototype._initializeMixinLoaders = function () {
  15775. for (var mixinFunction in graphMixinLoaders) {
  15776. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15777. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15778. }
  15779. }
  15780. };
  15781. /**
  15782. * Load the XY positions of the nodes into the dataset.
  15783. */
  15784. Graph.prototype.storePosition = function() {
  15785. var dataArray = [];
  15786. for (var nodeId in this.nodes) {
  15787. if (this.nodes.hasOwnProperty(nodeId)) {
  15788. var node = this.nodes[nodeId];
  15789. var allowedToMoveX = !this.nodes.xFixed;
  15790. var allowedToMoveY = !this.nodes.yFixed;
  15791. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  15792. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15793. }
  15794. }
  15795. }
  15796. this.nodesData.update(dataArray);
  15797. };
  15798. /**
  15799. * vis.js module exports
  15800. */
  15801. var vis = {
  15802. util: util,
  15803. Controller: Controller,
  15804. DataSet: DataSet,
  15805. DataView: DataView,
  15806. Range: Range,
  15807. Stack: Stack,
  15808. TimeStep: TimeStep,
  15809. components: {
  15810. items: {
  15811. Item: Item,
  15812. ItemBox: ItemBox,
  15813. ItemPoint: ItemPoint,
  15814. ItemRange: ItemRange
  15815. },
  15816. Component: Component,
  15817. Panel: Panel,
  15818. RootPanel: RootPanel,
  15819. ItemSet: ItemSet,
  15820. TimeAxis: TimeAxis
  15821. },
  15822. graph: {
  15823. Node: Node,
  15824. Edge: Edge,
  15825. Popup: Popup,
  15826. Groups: Groups,
  15827. Images: Images
  15828. },
  15829. Timeline: Timeline,
  15830. Graph: Graph
  15831. };
  15832. /**
  15833. * CommonJS module exports
  15834. */
  15835. if (typeof exports !== 'undefined') {
  15836. exports = vis;
  15837. }
  15838. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15839. module.exports = vis;
  15840. }
  15841. /**
  15842. * AMD module exports
  15843. */
  15844. if (typeof(define) === 'function') {
  15845. define(function () {
  15846. return vis;
  15847. });
  15848. }
  15849. /**
  15850. * Window exports
  15851. */
  15852. if (typeof window !== 'undefined') {
  15853. // attach the module to the window, load as a regular javascript file
  15854. window['vis'] = vis;
  15855. }
  15856. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15857. /**
  15858. * Expose `Emitter`.
  15859. */
  15860. module.exports = Emitter;
  15861. /**
  15862. * Initialize a new `Emitter`.
  15863. *
  15864. * @api public
  15865. */
  15866. function Emitter(obj) {
  15867. if (obj) return mixin(obj);
  15868. };
  15869. /**
  15870. * Mixin the emitter properties.
  15871. *
  15872. * @param {Object} obj
  15873. * @return {Object}
  15874. * @api private
  15875. */
  15876. function mixin(obj) {
  15877. for (var key in Emitter.prototype) {
  15878. obj[key] = Emitter.prototype[key];
  15879. }
  15880. return obj;
  15881. }
  15882. /**
  15883. * Listen on the given `event` with `fn`.
  15884. *
  15885. * @param {String} event
  15886. * @param {Function} fn
  15887. * @return {Emitter}
  15888. * @api public
  15889. */
  15890. Emitter.prototype.on =
  15891. Emitter.prototype.addEventListener = function(event, fn){
  15892. this._callbacks = this._callbacks || {};
  15893. (this._callbacks[event] = this._callbacks[event] || [])
  15894. .push(fn);
  15895. return this;
  15896. };
  15897. /**
  15898. * Adds an `event` listener that will be invoked a single
  15899. * time then automatically removed.
  15900. *
  15901. * @param {String} event
  15902. * @param {Function} fn
  15903. * @return {Emitter}
  15904. * @api public
  15905. */
  15906. Emitter.prototype.once = function(event, fn){
  15907. var self = this;
  15908. this._callbacks = this._callbacks || {};
  15909. function on() {
  15910. self.off(event, on);
  15911. fn.apply(this, arguments);
  15912. }
  15913. on.fn = fn;
  15914. this.on(event, on);
  15915. return this;
  15916. };
  15917. /**
  15918. * Remove the given callback for `event` or all
  15919. * registered callbacks.
  15920. *
  15921. * @param {String} event
  15922. * @param {Function} fn
  15923. * @return {Emitter}
  15924. * @api public
  15925. */
  15926. Emitter.prototype.off =
  15927. Emitter.prototype.removeListener =
  15928. Emitter.prototype.removeAllListeners =
  15929. Emitter.prototype.removeEventListener = function(event, fn){
  15930. this._callbacks = this._callbacks || {};
  15931. // all
  15932. if (0 == arguments.length) {
  15933. this._callbacks = {};
  15934. return this;
  15935. }
  15936. // specific event
  15937. var callbacks = this._callbacks[event];
  15938. if (!callbacks) return this;
  15939. // remove all handlers
  15940. if (1 == arguments.length) {
  15941. delete this._callbacks[event];
  15942. return this;
  15943. }
  15944. // remove specific handler
  15945. var cb;
  15946. for (var i = 0; i < callbacks.length; i++) {
  15947. cb = callbacks[i];
  15948. if (cb === fn || cb.fn === fn) {
  15949. callbacks.splice(i, 1);
  15950. break;
  15951. }
  15952. }
  15953. return this;
  15954. };
  15955. /**
  15956. * Emit `event` with the given args.
  15957. *
  15958. * @param {String} event
  15959. * @param {Mixed} ...
  15960. * @return {Emitter}
  15961. */
  15962. Emitter.prototype.emit = function(event){
  15963. this._callbacks = this._callbacks || {};
  15964. var args = [].slice.call(arguments, 1)
  15965. , callbacks = this._callbacks[event];
  15966. if (callbacks) {
  15967. callbacks = callbacks.slice(0);
  15968. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15969. callbacks[i].apply(this, args);
  15970. }
  15971. }
  15972. return this;
  15973. };
  15974. /**
  15975. * Return array of callbacks for `event`.
  15976. *
  15977. * @param {String} event
  15978. * @return {Array}
  15979. * @api public
  15980. */
  15981. Emitter.prototype.listeners = function(event){
  15982. this._callbacks = this._callbacks || {};
  15983. return this._callbacks[event] || [];
  15984. };
  15985. /**
  15986. * Check if this emitter has `event` handlers.
  15987. *
  15988. * @param {String} event
  15989. * @return {Boolean}
  15990. * @api public
  15991. */
  15992. Emitter.prototype.hasListeners = function(event){
  15993. return !! this.listeners(event).length;
  15994. };
  15995. },{}],3:[function(require,module,exports){
  15996. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15997. * http://eightmedia.github.com/hammer.js
  15998. *
  15999. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  16000. * Licensed under the MIT license */
  16001. (function(window, undefined) {
  16002. 'use strict';
  16003. /**
  16004. * Hammer
  16005. * use this to create instances
  16006. * @param {HTMLElement} element
  16007. * @param {Object} options
  16008. * @returns {Hammer.Instance}
  16009. * @constructor
  16010. */
  16011. var Hammer = function(element, options) {
  16012. return new Hammer.Instance(element, options || {});
  16013. };
  16014. // default settings
  16015. Hammer.defaults = {
  16016. // add styles and attributes to the element to prevent the browser from doing
  16017. // its native behavior. this doesnt prevent the scrolling, but cancels
  16018. // the contextmenu, tap highlighting etc
  16019. // set to false to disable this
  16020. stop_browser_behavior: {
  16021. // this also triggers onselectstart=false for IE
  16022. userSelect: 'none',
  16023. // this makes the element blocking in IE10 >, you could experiment with the value
  16024. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  16025. touchAction: 'none',
  16026. touchCallout: 'none',
  16027. contentZooming: 'none',
  16028. userDrag: 'none',
  16029. tapHighlightColor: 'rgba(0,0,0,0)'
  16030. }
  16031. // more settings are defined per gesture at gestures.js
  16032. };
  16033. // detect touchevents
  16034. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  16035. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  16036. // dont use mouseevents on mobile devices
  16037. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  16038. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  16039. // eventtypes per touchevent (start, move, end)
  16040. // are filled by Hammer.event.determineEventTypes on setup
  16041. Hammer.EVENT_TYPES = {};
  16042. // direction defines
  16043. Hammer.DIRECTION_DOWN = 'down';
  16044. Hammer.DIRECTION_LEFT = 'left';
  16045. Hammer.DIRECTION_UP = 'up';
  16046. Hammer.DIRECTION_RIGHT = 'right';
  16047. // pointer type
  16048. Hammer.POINTER_MOUSE = 'mouse';
  16049. Hammer.POINTER_TOUCH = 'touch';
  16050. Hammer.POINTER_PEN = 'pen';
  16051. // touch event defines
  16052. Hammer.EVENT_START = 'start';
  16053. Hammer.EVENT_MOVE = 'move';
  16054. Hammer.EVENT_END = 'end';
  16055. // hammer document where the base events are added at
  16056. Hammer.DOCUMENT = document;
  16057. // plugins namespace
  16058. Hammer.plugins = {};
  16059. // if the window events are set...
  16060. Hammer.READY = false;
  16061. /**
  16062. * setup events to detect gestures on the document
  16063. */
  16064. function setup() {
  16065. if(Hammer.READY) {
  16066. return;
  16067. }
  16068. // find what eventtypes we add listeners to
  16069. Hammer.event.determineEventTypes();
  16070. // Register all gestures inside Hammer.gestures
  16071. for(var name in Hammer.gestures) {
  16072. if(Hammer.gestures.hasOwnProperty(name)) {
  16073. Hammer.detection.register(Hammer.gestures[name]);
  16074. }
  16075. }
  16076. // Add touch events on the document
  16077. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  16078. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  16079. // Hammer is ready...!
  16080. Hammer.READY = true;
  16081. }
  16082. /**
  16083. * create new hammer instance
  16084. * all methods should return the instance itself, so it is chainable.
  16085. * @param {HTMLElement} element
  16086. * @param {Object} [options={}]
  16087. * @returns {Hammer.Instance}
  16088. * @constructor
  16089. */
  16090. Hammer.Instance = function(element, options) {
  16091. var self = this;
  16092. // setup HammerJS window events and register all gestures
  16093. // this also sets up the default options
  16094. setup();
  16095. this.element = element;
  16096. // start/stop detection option
  16097. this.enabled = true;
  16098. // merge options
  16099. this.options = Hammer.utils.extend(
  16100. Hammer.utils.extend({}, Hammer.defaults),
  16101. options || {});
  16102. // add some css to the element to prevent the browser from doing its native behavoir
  16103. if(this.options.stop_browser_behavior) {
  16104. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  16105. }
  16106. // start detection on touchstart
  16107. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  16108. if(self.enabled) {
  16109. Hammer.detection.startDetect(self, ev);
  16110. }
  16111. });
  16112. // return instance
  16113. return this;
  16114. };
  16115. Hammer.Instance.prototype = {
  16116. /**
  16117. * bind events to the instance
  16118. * @param {String} gesture
  16119. * @param {Function} handler
  16120. * @returns {Hammer.Instance}
  16121. */
  16122. on: function onEvent(gesture, handler){
  16123. var gestures = gesture.split(' ');
  16124. for(var t=0; t<gestures.length; t++) {
  16125. this.element.addEventListener(gestures[t], handler, false);
  16126. }
  16127. return this;
  16128. },
  16129. /**
  16130. * unbind events to the instance
  16131. * @param {String} gesture
  16132. * @param {Function} handler
  16133. * @returns {Hammer.Instance}
  16134. */
  16135. off: function offEvent(gesture, handler){
  16136. var gestures = gesture.split(' ');
  16137. for(var t=0; t<gestures.length; t++) {
  16138. this.element.removeEventListener(gestures[t], handler, false);
  16139. }
  16140. return this;
  16141. },
  16142. /**
  16143. * trigger gesture event
  16144. * @param {String} gesture
  16145. * @param {Object} eventData
  16146. * @returns {Hammer.Instance}
  16147. */
  16148. trigger: function triggerEvent(gesture, eventData){
  16149. // create DOM event
  16150. var event = Hammer.DOCUMENT.createEvent('Event');
  16151. event.initEvent(gesture, true, true);
  16152. event.gesture = eventData;
  16153. // trigger on the target if it is in the instance element,
  16154. // this is for event delegation tricks
  16155. var element = this.element;
  16156. if(Hammer.utils.hasParent(eventData.target, element)) {
  16157. element = eventData.target;
  16158. }
  16159. element.dispatchEvent(event);
  16160. return this;
  16161. },
  16162. /**
  16163. * enable of disable hammer.js detection
  16164. * @param {Boolean} state
  16165. * @returns {Hammer.Instance}
  16166. */
  16167. enable: function enable(state) {
  16168. this.enabled = state;
  16169. return this;
  16170. }
  16171. };
  16172. /**
  16173. * this holds the last move event,
  16174. * used to fix empty touchend issue
  16175. * see the onTouch event for an explanation
  16176. * @type {Object}
  16177. */
  16178. var last_move_event = null;
  16179. /**
  16180. * when the mouse is hold down, this is true
  16181. * @type {Boolean}
  16182. */
  16183. var enable_detect = false;
  16184. /**
  16185. * when touch events have been fired, this is true
  16186. * @type {Boolean}
  16187. */
  16188. var touch_triggered = false;
  16189. Hammer.event = {
  16190. /**
  16191. * simple addEventListener
  16192. * @param {HTMLElement} element
  16193. * @param {String} type
  16194. * @param {Function} handler
  16195. */
  16196. bindDom: function(element, type, handler) {
  16197. var types = type.split(' ');
  16198. for(var t=0; t<types.length; t++) {
  16199. element.addEventListener(types[t], handler, false);
  16200. }
  16201. },
  16202. /**
  16203. * touch events with mouse fallback
  16204. * @param {HTMLElement} element
  16205. * @param {String} eventType like Hammer.EVENT_MOVE
  16206. * @param {Function} handler
  16207. */
  16208. onTouch: function onTouch(element, eventType, handler) {
  16209. var self = this;
  16210. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  16211. var sourceEventType = ev.type.toLowerCase();
  16212. // onmouseup, but when touchend has been fired we do nothing.
  16213. // this is for touchdevices which also fire a mouseup on touchend
  16214. if(sourceEventType.match(/mouse/) && touch_triggered) {
  16215. return;
  16216. }
  16217. // mousebutton must be down or a touch event
  16218. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  16219. sourceEventType.match(/pointerdown/) || // pointerevents touch
  16220. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  16221. ){
  16222. enable_detect = true;
  16223. }
  16224. // we are in a touch event, set the touch triggered bool to true,
  16225. // this for the conflicts that may occur on ios and android
  16226. if(sourceEventType.match(/touch|pointer/)) {
  16227. touch_triggered = true;
  16228. }
  16229. // count the total touches on the screen
  16230. var count_touches = 0;
  16231. // when touch has been triggered in this detection session
  16232. // and we are now handling a mouse event, we stop that to prevent conflicts
  16233. if(enable_detect) {
  16234. // update pointerevent
  16235. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  16236. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16237. }
  16238. // touch
  16239. else if(sourceEventType.match(/touch/)) {
  16240. count_touches = ev.touches.length;
  16241. }
  16242. // mouse
  16243. else if(!touch_triggered) {
  16244. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  16245. }
  16246. // if we are in a end event, but when we remove one touch and
  16247. // we still have enough, set eventType to move
  16248. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  16249. eventType = Hammer.EVENT_MOVE;
  16250. }
  16251. // no touches, force the end event
  16252. else if(!count_touches) {
  16253. eventType = Hammer.EVENT_END;
  16254. }
  16255. // because touchend has no touches, and we often want to use these in our gestures,
  16256. // we send the last move event as our eventData in touchend
  16257. if(!count_touches && last_move_event !== null) {
  16258. ev = last_move_event;
  16259. }
  16260. // store the last move event
  16261. else {
  16262. last_move_event = ev;
  16263. }
  16264. // trigger the handler
  16265. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  16266. // remove pointerevent from list
  16267. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  16268. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16269. }
  16270. }
  16271. //debug(sourceEventType +" "+ eventType);
  16272. // on the end we reset everything
  16273. if(!count_touches) {
  16274. last_move_event = null;
  16275. enable_detect = false;
  16276. touch_triggered = false;
  16277. Hammer.PointerEvent.reset();
  16278. }
  16279. });
  16280. },
  16281. /**
  16282. * we have different events for each device/browser
  16283. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  16284. */
  16285. determineEventTypes: function determineEventTypes() {
  16286. // determine the eventtype we want to set
  16287. var types;
  16288. // pointerEvents magic
  16289. if(Hammer.HAS_POINTEREVENTS) {
  16290. types = Hammer.PointerEvent.getEvents();
  16291. }
  16292. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  16293. else if(Hammer.NO_MOUSEEVENTS) {
  16294. types = [
  16295. 'touchstart',
  16296. 'touchmove',
  16297. 'touchend touchcancel'];
  16298. }
  16299. // for non pointer events browsers and mixed browsers,
  16300. // like chrome on windows8 touch laptop
  16301. else {
  16302. types = [
  16303. 'touchstart mousedown',
  16304. 'touchmove mousemove',
  16305. 'touchend touchcancel mouseup'];
  16306. }
  16307. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  16308. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  16309. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  16310. },
  16311. /**
  16312. * create touchlist depending on the event
  16313. * @param {Object} ev
  16314. * @param {String} eventType used by the fakemultitouch plugin
  16315. */
  16316. getTouchList: function getTouchList(ev/*, eventType*/) {
  16317. // get the fake pointerEvent touchlist
  16318. if(Hammer.HAS_POINTEREVENTS) {
  16319. return Hammer.PointerEvent.getTouchList();
  16320. }
  16321. // get the touchlist
  16322. else if(ev.touches) {
  16323. return ev.touches;
  16324. }
  16325. // make fake touchlist from mouse position
  16326. else {
  16327. return [{
  16328. identifier: 1,
  16329. pageX: ev.pageX,
  16330. pageY: ev.pageY,
  16331. target: ev.target
  16332. }];
  16333. }
  16334. },
  16335. /**
  16336. * collect event data for Hammer js
  16337. * @param {HTMLElement} element
  16338. * @param {String} eventType like Hammer.EVENT_MOVE
  16339. * @param {Object} eventData
  16340. */
  16341. collectEventData: function collectEventData(element, eventType, ev) {
  16342. var touches = this.getTouchList(ev, eventType);
  16343. // find out pointerType
  16344. var pointerType = Hammer.POINTER_TOUCH;
  16345. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  16346. pointerType = Hammer.POINTER_MOUSE;
  16347. }
  16348. return {
  16349. center : Hammer.utils.getCenter(touches),
  16350. timeStamp : new Date().getTime(),
  16351. target : ev.target,
  16352. touches : touches,
  16353. eventType : eventType,
  16354. pointerType : pointerType,
  16355. srcEvent : ev,
  16356. /**
  16357. * prevent the browser default actions
  16358. * mostly used to disable scrolling of the browser
  16359. */
  16360. preventDefault: function() {
  16361. if(this.srcEvent.preventManipulation) {
  16362. this.srcEvent.preventManipulation();
  16363. }
  16364. if(this.srcEvent.preventDefault) {
  16365. this.srcEvent.preventDefault();
  16366. }
  16367. },
  16368. /**
  16369. * stop bubbling the event up to its parents
  16370. */
  16371. stopPropagation: function() {
  16372. this.srcEvent.stopPropagation();
  16373. },
  16374. /**
  16375. * immediately stop gesture detection
  16376. * might be useful after a swipe was detected
  16377. * @return {*}
  16378. */
  16379. stopDetect: function() {
  16380. return Hammer.detection.stopDetect();
  16381. }
  16382. };
  16383. }
  16384. };
  16385. Hammer.PointerEvent = {
  16386. /**
  16387. * holds all pointers
  16388. * @type {Object}
  16389. */
  16390. pointers: {},
  16391. /**
  16392. * get a list of pointers
  16393. * @returns {Array} touchlist
  16394. */
  16395. getTouchList: function() {
  16396. var self = this;
  16397. var touchlist = [];
  16398. // we can use forEach since pointerEvents only is in IE10
  16399. Object.keys(self.pointers).sort().forEach(function(id) {
  16400. touchlist.push(self.pointers[id]);
  16401. });
  16402. return touchlist;
  16403. },
  16404. /**
  16405. * update the position of a pointer
  16406. * @param {String} type Hammer.EVENT_END
  16407. * @param {Object} pointerEvent
  16408. */
  16409. updatePointer: function(type, pointerEvent) {
  16410. if(type == Hammer.EVENT_END) {
  16411. this.pointers = {};
  16412. }
  16413. else {
  16414. pointerEvent.identifier = pointerEvent.pointerId;
  16415. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16416. }
  16417. return Object.keys(this.pointers).length;
  16418. },
  16419. /**
  16420. * check if ev matches pointertype
  16421. * @param {String} pointerType Hammer.POINTER_MOUSE
  16422. * @param {PointerEvent} ev
  16423. */
  16424. matchType: function(pointerType, ev) {
  16425. if(!ev.pointerType) {
  16426. return false;
  16427. }
  16428. var types = {};
  16429. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16430. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16431. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16432. return types[pointerType];
  16433. },
  16434. /**
  16435. * get events
  16436. */
  16437. getEvents: function() {
  16438. return [
  16439. 'pointerdown MSPointerDown',
  16440. 'pointermove MSPointerMove',
  16441. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16442. ];
  16443. },
  16444. /**
  16445. * reset the list
  16446. */
  16447. reset: function() {
  16448. this.pointers = {};
  16449. }
  16450. };
  16451. Hammer.utils = {
  16452. /**
  16453. * extend method,
  16454. * also used for cloning when dest is an empty object
  16455. * @param {Object} dest
  16456. * @param {Object} src
  16457. * @parm {Boolean} merge do a merge
  16458. * @returns {Object} dest
  16459. */
  16460. extend: function extend(dest, src, merge) {
  16461. for (var key in src) {
  16462. if(dest[key] !== undefined && merge) {
  16463. continue;
  16464. }
  16465. dest[key] = src[key];
  16466. }
  16467. return dest;
  16468. },
  16469. /**
  16470. * find if a node is in the given parent
  16471. * used for event delegation tricks
  16472. * @param {HTMLElement} node
  16473. * @param {HTMLElement} parent
  16474. * @returns {boolean} has_parent
  16475. */
  16476. hasParent: function(node, parent) {
  16477. while(node){
  16478. if(node == parent) {
  16479. return true;
  16480. }
  16481. node = node.parentNode;
  16482. }
  16483. return false;
  16484. },
  16485. /**
  16486. * get the center of all the touches
  16487. * @param {Array} touches
  16488. * @returns {Object} center
  16489. */
  16490. getCenter: function getCenter(touches) {
  16491. var valuesX = [], valuesY = [];
  16492. for(var t= 0,len=touches.length; t<len; t++) {
  16493. valuesX.push(touches[t].pageX);
  16494. valuesY.push(touches[t].pageY);
  16495. }
  16496. return {
  16497. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  16498. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  16499. };
  16500. },
  16501. /**
  16502. * calculate the velocity between two points
  16503. * @param {Number} delta_time
  16504. * @param {Number} delta_x
  16505. * @param {Number} delta_y
  16506. * @returns {Object} velocity
  16507. */
  16508. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  16509. return {
  16510. x: Math.abs(delta_x / delta_time) || 0,
  16511. y: Math.abs(delta_y / delta_time) || 0
  16512. };
  16513. },
  16514. /**
  16515. * calculate the angle between two coordinates
  16516. * @param {Touch} touch1
  16517. * @param {Touch} touch2
  16518. * @returns {Number} angle
  16519. */
  16520. getAngle: function getAngle(touch1, touch2) {
  16521. var y = touch2.pageY - touch1.pageY,
  16522. x = touch2.pageX - touch1.pageX;
  16523. return Math.atan2(y, x) * 180 / Math.PI;
  16524. },
  16525. /**
  16526. * angle to direction define
  16527. * @param {Touch} touch1
  16528. * @param {Touch} touch2
  16529. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  16530. */
  16531. getDirection: function getDirection(touch1, touch2) {
  16532. var x = Math.abs(touch1.pageX - touch2.pageX),
  16533. y = Math.abs(touch1.pageY - touch2.pageY);
  16534. if(x >= y) {
  16535. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16536. }
  16537. else {
  16538. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16539. }
  16540. },
  16541. /**
  16542. * calculate the distance between two touches
  16543. * @param {Touch} touch1
  16544. * @param {Touch} touch2
  16545. * @returns {Number} distance
  16546. */
  16547. getDistance: function getDistance(touch1, touch2) {
  16548. var x = touch2.pageX - touch1.pageX,
  16549. y = touch2.pageY - touch1.pageY;
  16550. return Math.sqrt((x*x) + (y*y));
  16551. },
  16552. /**
  16553. * calculate the scale factor between two touchLists (fingers)
  16554. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16555. * @param {Array} start
  16556. * @param {Array} end
  16557. * @returns {Number} scale
  16558. */
  16559. getScale: function getScale(start, end) {
  16560. // need two fingers...
  16561. if(start.length >= 2 && end.length >= 2) {
  16562. return this.getDistance(end[0], end[1]) /
  16563. this.getDistance(start[0], start[1]);
  16564. }
  16565. return 1;
  16566. },
  16567. /**
  16568. * calculate the rotation degrees between two touchLists (fingers)
  16569. * @param {Array} start
  16570. * @param {Array} end
  16571. * @returns {Number} rotation
  16572. */
  16573. getRotation: function getRotation(start, end) {
  16574. // need two fingers
  16575. if(start.length >= 2 && end.length >= 2) {
  16576. return this.getAngle(end[1], end[0]) -
  16577. this.getAngle(start[1], start[0]);
  16578. }
  16579. return 0;
  16580. },
  16581. /**
  16582. * boolean if the direction is vertical
  16583. * @param {String} direction
  16584. * @returns {Boolean} is_vertical
  16585. */
  16586. isVertical: function isVertical(direction) {
  16587. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16588. },
  16589. /**
  16590. * stop browser default behavior with css props
  16591. * @param {HtmlElement} element
  16592. * @param {Object} css_props
  16593. */
  16594. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16595. var prop,
  16596. vendors = ['webkit','khtml','moz','ms','o',''];
  16597. if(!css_props || !element.style) {
  16598. return;
  16599. }
  16600. // with css properties for modern browsers
  16601. for(var i = 0; i < vendors.length; i++) {
  16602. for(var p in css_props) {
  16603. if(css_props.hasOwnProperty(p)) {
  16604. prop = p;
  16605. // vender prefix at the property
  16606. if(vendors[i]) {
  16607. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16608. }
  16609. // set the style
  16610. element.style[prop] = css_props[p];
  16611. }
  16612. }
  16613. }
  16614. // also the disable onselectstart
  16615. if(css_props.userSelect == 'none') {
  16616. element.onselectstart = function() {
  16617. return false;
  16618. };
  16619. }
  16620. }
  16621. };
  16622. Hammer.detection = {
  16623. // contains all registred Hammer.gestures in the correct order
  16624. gestures: [],
  16625. // data of the current Hammer.gesture detection session
  16626. current: null,
  16627. // the previous Hammer.gesture session data
  16628. // is a full clone of the previous gesture.current object
  16629. previous: null,
  16630. // when this becomes true, no gestures are fired
  16631. stopped: false,
  16632. /**
  16633. * start Hammer.gesture detection
  16634. * @param {Hammer.Instance} inst
  16635. * @param {Object} eventData
  16636. */
  16637. startDetect: function startDetect(inst, eventData) {
  16638. // already busy with a Hammer.gesture detection on an element
  16639. if(this.current) {
  16640. return;
  16641. }
  16642. this.stopped = false;
  16643. this.current = {
  16644. inst : inst, // reference to HammerInstance we're working for
  16645. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16646. lastEvent : false, // last eventData
  16647. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16648. };
  16649. this.detect(eventData);
  16650. },
  16651. /**
  16652. * Hammer.gesture detection
  16653. * @param {Object} eventData
  16654. * @param {Object} eventData
  16655. */
  16656. detect: function detect(eventData) {
  16657. if(!this.current || this.stopped) {
  16658. return;
  16659. }
  16660. // extend event data with calculations about scale, distance etc
  16661. eventData = this.extendEventData(eventData);
  16662. // instance options
  16663. var inst_options = this.current.inst.options;
  16664. // call Hammer.gesture handlers
  16665. for(var g=0,len=this.gestures.length; g<len; g++) {
  16666. var gesture = this.gestures[g];
  16667. // only when the instance options have enabled this gesture
  16668. if(!this.stopped && inst_options[gesture.name] !== false) {
  16669. // if a handler returns false, we stop with the detection
  16670. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16671. this.stopDetect();
  16672. break;
  16673. }
  16674. }
  16675. }
  16676. // store as previous event event
  16677. if(this.current) {
  16678. this.current.lastEvent = eventData;
  16679. }
  16680. // endevent, but not the last touch, so dont stop
  16681. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16682. this.stopDetect();
  16683. }
  16684. return eventData;
  16685. },
  16686. /**
  16687. * clear the Hammer.gesture vars
  16688. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16689. * to stop other Hammer.gestures from being fired
  16690. */
  16691. stopDetect: function stopDetect() {
  16692. // clone current data to the store as the previous gesture
  16693. // used for the double tap gesture, since this is an other gesture detect session
  16694. this.previous = Hammer.utils.extend({}, this.current);
  16695. // reset the current
  16696. this.current = null;
  16697. // stopped!
  16698. this.stopped = true;
  16699. },
  16700. /**
  16701. * extend eventData for Hammer.gestures
  16702. * @param {Object} ev
  16703. * @returns {Object} ev
  16704. */
  16705. extendEventData: function extendEventData(ev) {
  16706. var startEv = this.current.startEvent;
  16707. // if the touches change, set the new touches over the startEvent touches
  16708. // this because touchevents don't have all the touches on touchstart, or the
  16709. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16710. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16711. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16712. // extend 1 level deep to get the touchlist with the touch objects
  16713. startEv.touches = [];
  16714. for(var i=0,len=ev.touches.length; i<len; i++) {
  16715. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16716. }
  16717. }
  16718. var delta_time = ev.timeStamp - startEv.timeStamp,
  16719. delta_x = ev.center.pageX - startEv.center.pageX,
  16720. delta_y = ev.center.pageY - startEv.center.pageY,
  16721. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16722. Hammer.utils.extend(ev, {
  16723. deltaTime : delta_time,
  16724. deltaX : delta_x,
  16725. deltaY : delta_y,
  16726. velocityX : velocity.x,
  16727. velocityY : velocity.y,
  16728. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16729. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16730. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16731. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16732. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16733. startEvent : startEv
  16734. });
  16735. return ev;
  16736. },
  16737. /**
  16738. * register new gesture
  16739. * @param {Object} gesture object, see gestures.js for documentation
  16740. * @returns {Array} gestures
  16741. */
  16742. register: function register(gesture) {
  16743. // add an enable gesture options if there is no given
  16744. var options = gesture.defaults || {};
  16745. if(options[gesture.name] === undefined) {
  16746. options[gesture.name] = true;
  16747. }
  16748. // extend Hammer default options with the Hammer.gesture options
  16749. Hammer.utils.extend(Hammer.defaults, options, true);
  16750. // set its index
  16751. gesture.index = gesture.index || 1000;
  16752. // add Hammer.gesture to the list
  16753. this.gestures.push(gesture);
  16754. // sort the list by index
  16755. this.gestures.sort(function(a, b) {
  16756. if (a.index < b.index) {
  16757. return -1;
  16758. }
  16759. if (a.index > b.index) {
  16760. return 1;
  16761. }
  16762. return 0;
  16763. });
  16764. return this.gestures;
  16765. }
  16766. };
  16767. Hammer.gestures = Hammer.gestures || {};
  16768. /**
  16769. * Custom gestures
  16770. * ==============================
  16771. *
  16772. * Gesture object
  16773. * --------------------
  16774. * The object structure of a gesture:
  16775. *
  16776. * { name: 'mygesture',
  16777. * index: 1337,
  16778. * defaults: {
  16779. * mygesture_option: true
  16780. * }
  16781. * handler: function(type, ev, inst) {
  16782. * // trigger gesture event
  16783. * inst.trigger(this.name, ev);
  16784. * }
  16785. * }
  16786. * @param {String} name
  16787. * this should be the name of the gesture, lowercase
  16788. * it is also being used to disable/enable the gesture per instance config.
  16789. *
  16790. * @param {Number} [index=1000]
  16791. * the index of the gesture, where it is going to be in the stack of gestures detection
  16792. * like when you build an gesture that depends on the drag gesture, it is a good
  16793. * idea to place it after the index of the drag gesture.
  16794. *
  16795. * @param {Object} [defaults={}]
  16796. * the default settings of the gesture. these are added to the instance settings,
  16797. * and can be overruled per instance. you can also add the name of the gesture,
  16798. * but this is also added by default (and set to true).
  16799. *
  16800. * @param {Function} handler
  16801. * this handles the gesture detection of your custom gesture and receives the
  16802. * following arguments:
  16803. *
  16804. * @param {Object} eventData
  16805. * event data containing the following properties:
  16806. * timeStamp {Number} time the event occurred
  16807. * target {HTMLElement} target element
  16808. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16809. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16810. * center {Object} center position of the touches. contains pageX and pageY
  16811. * deltaTime {Number} the total time of the touches in the screen
  16812. * deltaX {Number} the delta on x axis we haved moved
  16813. * deltaY {Number} the delta on y axis we haved moved
  16814. * velocityX {Number} the velocity on the x
  16815. * velocityY {Number} the velocity on y
  16816. * angle {Number} the angle we are moving
  16817. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16818. * distance {Number} the distance we haved moved
  16819. * scale {Number} scaling of the touches, needs 2 touches
  16820. * rotation {Number} rotation of the touches, needs 2 touches *
  16821. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16822. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16823. * startEvent {Object} contains the same properties as above,
  16824. * but from the first touch. this is used to calculate
  16825. * distances, deltaTime, scaling etc
  16826. *
  16827. * @param {Hammer.Instance} inst
  16828. * the instance we are doing the detection for. you can get the options from
  16829. * the inst.options object and trigger the gesture event by calling inst.trigger
  16830. *
  16831. *
  16832. * Handle gestures
  16833. * --------------------
  16834. * inside the handler you can get/set Hammer.detection.current. This is the current
  16835. * detection session. It has the following properties
  16836. * @param {String} name
  16837. * contains the name of the gesture we have detected. it has not a real function,
  16838. * only to check in other gestures if something is detected.
  16839. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16840. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16841. *
  16842. * @readonly
  16843. * @param {Hammer.Instance} inst
  16844. * the instance we do the detection for
  16845. *
  16846. * @readonly
  16847. * @param {Object} startEvent
  16848. * contains the properties of the first gesture detection in this session.
  16849. * Used for calculations about timing, distance, etc.
  16850. *
  16851. * @readonly
  16852. * @param {Object} lastEvent
  16853. * contains all the properties of the last gesture detect in this session.
  16854. *
  16855. * after the gesture detection session has been completed (user has released the screen)
  16856. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16857. * this is usefull for gestures like doubletap, where you need to know if the
  16858. * previous gesture was a tap
  16859. *
  16860. * options that have been set by the instance can be received by calling inst.options
  16861. *
  16862. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16863. * The first param is the name of your gesture, the second the event argument
  16864. *
  16865. *
  16866. * Register gestures
  16867. * --------------------
  16868. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16869. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16870. * manually and pass your gesture object as a param
  16871. *
  16872. */
  16873. /**
  16874. * Hold
  16875. * Touch stays at the same place for x time
  16876. * @events hold
  16877. */
  16878. Hammer.gestures.Hold = {
  16879. name: 'hold',
  16880. index: 10,
  16881. defaults: {
  16882. hold_timeout : 500,
  16883. hold_threshold : 1
  16884. },
  16885. timer: null,
  16886. handler: function holdGesture(ev, inst) {
  16887. switch(ev.eventType) {
  16888. case Hammer.EVENT_START:
  16889. // clear any running timers
  16890. clearTimeout(this.timer);
  16891. // set the gesture so we can check in the timeout if it still is
  16892. Hammer.detection.current.name = this.name;
  16893. // set timer and if after the timeout it still is hold,
  16894. // we trigger the hold event
  16895. this.timer = setTimeout(function() {
  16896. if(Hammer.detection.current.name == 'hold') {
  16897. inst.trigger('hold', ev);
  16898. }
  16899. }, inst.options.hold_timeout);
  16900. break;
  16901. // when you move or end we clear the timer
  16902. case Hammer.EVENT_MOVE:
  16903. if(ev.distance > inst.options.hold_threshold) {
  16904. clearTimeout(this.timer);
  16905. }
  16906. break;
  16907. case Hammer.EVENT_END:
  16908. clearTimeout(this.timer);
  16909. break;
  16910. }
  16911. }
  16912. };
  16913. /**
  16914. * Tap/DoubleTap
  16915. * Quick touch at a place or double at the same place
  16916. * @events tap, doubletap
  16917. */
  16918. Hammer.gestures.Tap = {
  16919. name: 'tap',
  16920. index: 100,
  16921. defaults: {
  16922. tap_max_touchtime : 250,
  16923. tap_max_distance : 10,
  16924. tap_always : true,
  16925. doubletap_distance : 20,
  16926. doubletap_interval : 300
  16927. },
  16928. handler: function tapGesture(ev, inst) {
  16929. if(ev.eventType == Hammer.EVENT_END) {
  16930. // previous gesture, for the double tap since these are two different gesture detections
  16931. var prev = Hammer.detection.previous,
  16932. did_doubletap = false;
  16933. // when the touchtime is higher then the max touch time
  16934. // or when the moving distance is too much
  16935. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16936. ev.distance > inst.options.tap_max_distance) {
  16937. return;
  16938. }
  16939. // check if double tap
  16940. if(prev && prev.name == 'tap' &&
  16941. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16942. ev.distance < inst.options.doubletap_distance) {
  16943. inst.trigger('doubletap', ev);
  16944. did_doubletap = true;
  16945. }
  16946. // do a single tap
  16947. if(!did_doubletap || inst.options.tap_always) {
  16948. Hammer.detection.current.name = 'tap';
  16949. inst.trigger(Hammer.detection.current.name, ev);
  16950. }
  16951. }
  16952. }
  16953. };
  16954. /**
  16955. * Swipe
  16956. * triggers swipe events when the end velocity is above the threshold
  16957. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16958. */
  16959. Hammer.gestures.Swipe = {
  16960. name: 'swipe',
  16961. index: 40,
  16962. defaults: {
  16963. // set 0 for unlimited, but this can conflict with transform
  16964. swipe_max_touches : 1,
  16965. swipe_velocity : 0.7
  16966. },
  16967. handler: function swipeGesture(ev, inst) {
  16968. if(ev.eventType == Hammer.EVENT_END) {
  16969. // max touches
  16970. if(inst.options.swipe_max_touches > 0 &&
  16971. ev.touches.length > inst.options.swipe_max_touches) {
  16972. return;
  16973. }
  16974. // when the distance we moved is too small we skip this gesture
  16975. // or we can be already in dragging
  16976. if(ev.velocityX > inst.options.swipe_velocity ||
  16977. ev.velocityY > inst.options.swipe_velocity) {
  16978. // trigger swipe events
  16979. inst.trigger(this.name, ev);
  16980. inst.trigger(this.name + ev.direction, ev);
  16981. }
  16982. }
  16983. }
  16984. };
  16985. /**
  16986. * Drag
  16987. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16988. * moving left and right is a good practice. When all the drag events are blocking
  16989. * you disable scrolling on that area.
  16990. * @events drag, drapleft, dragright, dragup, dragdown
  16991. */
  16992. Hammer.gestures.Drag = {
  16993. name: 'drag',
  16994. index: 50,
  16995. defaults: {
  16996. drag_min_distance : 10,
  16997. // set 0 for unlimited, but this can conflict with transform
  16998. drag_max_touches : 1,
  16999. // prevent default browser behavior when dragging occurs
  17000. // be careful with it, it makes the element a blocking element
  17001. // when you are using the drag gesture, it is a good practice to set this true
  17002. drag_block_horizontal : false,
  17003. drag_block_vertical : false,
  17004. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  17005. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  17006. drag_lock_to_axis : false,
  17007. // drag lock only kicks in when distance > drag_lock_min_distance
  17008. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  17009. drag_lock_min_distance : 25
  17010. },
  17011. triggered: false,
  17012. handler: function dragGesture(ev, inst) {
  17013. // current gesture isnt drag, but dragged is true
  17014. // this means an other gesture is busy. now call dragend
  17015. if(Hammer.detection.current.name != this.name && this.triggered) {
  17016. inst.trigger(this.name +'end', ev);
  17017. this.triggered = false;
  17018. return;
  17019. }
  17020. // max touches
  17021. if(inst.options.drag_max_touches > 0 &&
  17022. ev.touches.length > inst.options.drag_max_touches) {
  17023. return;
  17024. }
  17025. switch(ev.eventType) {
  17026. case Hammer.EVENT_START:
  17027. this.triggered = false;
  17028. break;
  17029. case Hammer.EVENT_MOVE:
  17030. // when the distance we moved is too small we skip this gesture
  17031. // or we can be already in dragging
  17032. if(ev.distance < inst.options.drag_min_distance &&
  17033. Hammer.detection.current.name != this.name) {
  17034. return;
  17035. }
  17036. // we are dragging!
  17037. Hammer.detection.current.name = this.name;
  17038. // lock drag to axis?
  17039. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  17040. ev.drag_locked_to_axis = true;
  17041. }
  17042. var last_direction = Hammer.detection.current.lastEvent.direction;
  17043. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  17044. // keep direction on the axis that the drag gesture started on
  17045. if(Hammer.utils.isVertical(last_direction)) {
  17046. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  17047. }
  17048. else {
  17049. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  17050. }
  17051. }
  17052. // first time, trigger dragstart event
  17053. if(!this.triggered) {
  17054. inst.trigger(this.name +'start', ev);
  17055. this.triggered = true;
  17056. }
  17057. // trigger normal event
  17058. inst.trigger(this.name, ev);
  17059. // direction event, like dragdown
  17060. inst.trigger(this.name + ev.direction, ev);
  17061. // block the browser events
  17062. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  17063. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  17064. ev.preventDefault();
  17065. }
  17066. break;
  17067. case Hammer.EVENT_END:
  17068. // trigger dragend
  17069. if(this.triggered) {
  17070. inst.trigger(this.name +'end', ev);
  17071. }
  17072. this.triggered = false;
  17073. break;
  17074. }
  17075. }
  17076. };
  17077. /**
  17078. * Transform
  17079. * User want to scale or rotate with 2 fingers
  17080. * @events transform, pinch, pinchin, pinchout, rotate
  17081. */
  17082. Hammer.gestures.Transform = {
  17083. name: 'transform',
  17084. index: 45,
  17085. defaults: {
  17086. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  17087. transform_min_scale : 0.01,
  17088. // rotation in degrees
  17089. transform_min_rotation : 1,
  17090. // prevent default browser behavior when two touches are on the screen
  17091. // but it makes the element a blocking element
  17092. // when you are using the transform gesture, it is a good practice to set this true
  17093. transform_always_block : false
  17094. },
  17095. triggered: false,
  17096. handler: function transformGesture(ev, inst) {
  17097. // current gesture isnt drag, but dragged is true
  17098. // this means an other gesture is busy. now call dragend
  17099. if(Hammer.detection.current.name != this.name && this.triggered) {
  17100. inst.trigger(this.name +'end', ev);
  17101. this.triggered = false;
  17102. return;
  17103. }
  17104. // atleast multitouch
  17105. if(ev.touches.length < 2) {
  17106. return;
  17107. }
  17108. // prevent default when two fingers are on the screen
  17109. if(inst.options.transform_always_block) {
  17110. ev.preventDefault();
  17111. }
  17112. switch(ev.eventType) {
  17113. case Hammer.EVENT_START:
  17114. this.triggered = false;
  17115. break;
  17116. case Hammer.EVENT_MOVE:
  17117. var scale_threshold = Math.abs(1-ev.scale);
  17118. var rotation_threshold = Math.abs(ev.rotation);
  17119. // when the distance we moved is too small we skip this gesture
  17120. // or we can be already in dragging
  17121. if(scale_threshold < inst.options.transform_min_scale &&
  17122. rotation_threshold < inst.options.transform_min_rotation) {
  17123. return;
  17124. }
  17125. // we are transforming!
  17126. Hammer.detection.current.name = this.name;
  17127. // first time, trigger dragstart event
  17128. if(!this.triggered) {
  17129. inst.trigger(this.name +'start', ev);
  17130. this.triggered = true;
  17131. }
  17132. inst.trigger(this.name, ev); // basic transform event
  17133. // trigger rotate event
  17134. if(rotation_threshold > inst.options.transform_min_rotation) {
  17135. inst.trigger('rotate', ev);
  17136. }
  17137. // trigger pinch event
  17138. if(scale_threshold > inst.options.transform_min_scale) {
  17139. inst.trigger('pinch', ev);
  17140. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  17141. }
  17142. break;
  17143. case Hammer.EVENT_END:
  17144. // trigger dragend
  17145. if(this.triggered) {
  17146. inst.trigger(this.name +'end', ev);
  17147. }
  17148. this.triggered = false;
  17149. break;
  17150. }
  17151. }
  17152. };
  17153. /**
  17154. * Touch
  17155. * Called as first, tells the user has touched the screen
  17156. * @events touch
  17157. */
  17158. Hammer.gestures.Touch = {
  17159. name: 'touch',
  17160. index: -Infinity,
  17161. defaults: {
  17162. // call preventDefault at touchstart, and makes the element blocking by
  17163. // disabling the scrolling of the page, but it improves gestures like
  17164. // transforming and dragging.
  17165. // be careful with using this, it can be very annoying for users to be stuck
  17166. // on the page
  17167. prevent_default: false,
  17168. // disable mouse events, so only touch (or pen!) input triggers events
  17169. prevent_mouseevents: false
  17170. },
  17171. handler: function touchGesture(ev, inst) {
  17172. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  17173. ev.stopDetect();
  17174. return;
  17175. }
  17176. if(inst.options.prevent_default) {
  17177. ev.preventDefault();
  17178. }
  17179. if(ev.eventType == Hammer.EVENT_START) {
  17180. inst.trigger(this.name, ev);
  17181. }
  17182. }
  17183. };
  17184. /**
  17185. * Release
  17186. * Called as last, tells the user has released the screen
  17187. * @events release
  17188. */
  17189. Hammer.gestures.Release = {
  17190. name: 'release',
  17191. index: Infinity,
  17192. handler: function releaseGesture(ev, inst) {
  17193. if(ev.eventType == Hammer.EVENT_END) {
  17194. inst.trigger(this.name, ev);
  17195. }
  17196. }
  17197. };
  17198. // node export
  17199. if(typeof module === 'object' && typeof module.exports === 'object'){
  17200. module.exports = Hammer;
  17201. }
  17202. // just window export
  17203. else {
  17204. window.Hammer = Hammer;
  17205. // requireJS module definition
  17206. if(typeof window.define === 'function' && window.define.amd) {
  17207. window.define('hammer', [], function() {
  17208. return Hammer;
  17209. });
  17210. }
  17211. }
  17212. })(this);
  17213. },{}],4:[function(require,module,exports){
  17214. //! moment.js
  17215. //! version : 2.5.1
  17216. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  17217. //! license : MIT
  17218. //! momentjs.com
  17219. (function (undefined) {
  17220. /************************************
  17221. Constants
  17222. ************************************/
  17223. var moment,
  17224. VERSION = "2.5.1",
  17225. global = this,
  17226. round = Math.round,
  17227. i,
  17228. YEAR = 0,
  17229. MONTH = 1,
  17230. DATE = 2,
  17231. HOUR = 3,
  17232. MINUTE = 4,
  17233. SECOND = 5,
  17234. MILLISECOND = 6,
  17235. // internal storage for language config files
  17236. languages = {},
  17237. // moment internal properties
  17238. momentProperties = {
  17239. _isAMomentObject: null,
  17240. _i : null,
  17241. _f : null,
  17242. _l : null,
  17243. _strict : null,
  17244. _isUTC : null,
  17245. _offset : null, // optional. Combine with _isUTC
  17246. _pf : null,
  17247. _lang : null // optional
  17248. },
  17249. // check for nodeJS
  17250. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  17251. // ASP.NET json date format regex
  17252. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  17253. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  17254. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  17255. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  17256. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  17257. // format tokens
  17258. 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,
  17259. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  17260. // parsing token regexes
  17261. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  17262. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  17263. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  17264. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  17265. parseTokenDigits = /\d+/, // nonzero number of digits
  17266. 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.
  17267. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  17268. parseTokenT = /T/i, // T (ISO separator)
  17269. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  17270. //strict parsing regexes
  17271. parseTokenOneDigit = /\d/, // 0 - 9
  17272. parseTokenTwoDigits = /\d\d/, // 00 - 99
  17273. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  17274. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  17275. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  17276. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  17277. // iso 8601 regex
  17278. // 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)
  17279. 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)?)?$/,
  17280. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  17281. isoDates = [
  17282. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  17283. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  17284. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  17285. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  17286. ['YYYY-DDD', /\d{4}-\d{3}/]
  17287. ],
  17288. // iso time formats and regexes
  17289. isoTimes = [
  17290. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  17291. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  17292. ['HH:mm', /(T| )\d\d:\d\d/],
  17293. ['HH', /(T| )\d\d/]
  17294. ],
  17295. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  17296. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  17297. // getter and setter names
  17298. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  17299. unitMillisecondFactors = {
  17300. 'Milliseconds' : 1,
  17301. 'Seconds' : 1e3,
  17302. 'Minutes' : 6e4,
  17303. 'Hours' : 36e5,
  17304. 'Days' : 864e5,
  17305. 'Months' : 2592e6,
  17306. 'Years' : 31536e6
  17307. },
  17308. unitAliases = {
  17309. ms : 'millisecond',
  17310. s : 'second',
  17311. m : 'minute',
  17312. h : 'hour',
  17313. d : 'day',
  17314. D : 'date',
  17315. w : 'week',
  17316. W : 'isoWeek',
  17317. M : 'month',
  17318. y : 'year',
  17319. DDD : 'dayOfYear',
  17320. e : 'weekday',
  17321. E : 'isoWeekday',
  17322. gg: 'weekYear',
  17323. GG: 'isoWeekYear'
  17324. },
  17325. camelFunctions = {
  17326. dayofyear : 'dayOfYear',
  17327. isoweekday : 'isoWeekday',
  17328. isoweek : 'isoWeek',
  17329. weekyear : 'weekYear',
  17330. isoweekyear : 'isoWeekYear'
  17331. },
  17332. // format function strings
  17333. formatFunctions = {},
  17334. // tokens to ordinalize and pad
  17335. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  17336. paddedTokens = 'M D H h m s w W'.split(' '),
  17337. formatTokenFunctions = {
  17338. M : function () {
  17339. return this.month() + 1;
  17340. },
  17341. MMM : function (format) {
  17342. return this.lang().monthsShort(this, format);
  17343. },
  17344. MMMM : function (format) {
  17345. return this.lang().months(this, format);
  17346. },
  17347. D : function () {
  17348. return this.date();
  17349. },
  17350. DDD : function () {
  17351. return this.dayOfYear();
  17352. },
  17353. d : function () {
  17354. return this.day();
  17355. },
  17356. dd : function (format) {
  17357. return this.lang().weekdaysMin(this, format);
  17358. },
  17359. ddd : function (format) {
  17360. return this.lang().weekdaysShort(this, format);
  17361. },
  17362. dddd : function (format) {
  17363. return this.lang().weekdays(this, format);
  17364. },
  17365. w : function () {
  17366. return this.week();
  17367. },
  17368. W : function () {
  17369. return this.isoWeek();
  17370. },
  17371. YY : function () {
  17372. return leftZeroFill(this.year() % 100, 2);
  17373. },
  17374. YYYY : function () {
  17375. return leftZeroFill(this.year(), 4);
  17376. },
  17377. YYYYY : function () {
  17378. return leftZeroFill(this.year(), 5);
  17379. },
  17380. YYYYYY : function () {
  17381. var y = this.year(), sign = y >= 0 ? '+' : '-';
  17382. return sign + leftZeroFill(Math.abs(y), 6);
  17383. },
  17384. gg : function () {
  17385. return leftZeroFill(this.weekYear() % 100, 2);
  17386. },
  17387. gggg : function () {
  17388. return leftZeroFill(this.weekYear(), 4);
  17389. },
  17390. ggggg : function () {
  17391. return leftZeroFill(this.weekYear(), 5);
  17392. },
  17393. GG : function () {
  17394. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17395. },
  17396. GGGG : function () {
  17397. return leftZeroFill(this.isoWeekYear(), 4);
  17398. },
  17399. GGGGG : function () {
  17400. return leftZeroFill(this.isoWeekYear(), 5);
  17401. },
  17402. e : function () {
  17403. return this.weekday();
  17404. },
  17405. E : function () {
  17406. return this.isoWeekday();
  17407. },
  17408. a : function () {
  17409. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17410. },
  17411. A : function () {
  17412. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17413. },
  17414. H : function () {
  17415. return this.hours();
  17416. },
  17417. h : function () {
  17418. return this.hours() % 12 || 12;
  17419. },
  17420. m : function () {
  17421. return this.minutes();
  17422. },
  17423. s : function () {
  17424. return this.seconds();
  17425. },
  17426. S : function () {
  17427. return toInt(this.milliseconds() / 100);
  17428. },
  17429. SS : function () {
  17430. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17431. },
  17432. SSS : function () {
  17433. return leftZeroFill(this.milliseconds(), 3);
  17434. },
  17435. SSSS : function () {
  17436. return leftZeroFill(this.milliseconds(), 3);
  17437. },
  17438. Z : function () {
  17439. var a = -this.zone(),
  17440. b = "+";
  17441. if (a < 0) {
  17442. a = -a;
  17443. b = "-";
  17444. }
  17445. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  17446. },
  17447. ZZ : function () {
  17448. var a = -this.zone(),
  17449. b = "+";
  17450. if (a < 0) {
  17451. a = -a;
  17452. b = "-";
  17453. }
  17454. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  17455. },
  17456. z : function () {
  17457. return this.zoneAbbr();
  17458. },
  17459. zz : function () {
  17460. return this.zoneName();
  17461. },
  17462. X : function () {
  17463. return this.unix();
  17464. },
  17465. Q : function () {
  17466. return this.quarter();
  17467. }
  17468. },
  17469. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  17470. function defaultParsingFlags() {
  17471. // We need to deep clone this object, and es5 standard is not very
  17472. // helpful.
  17473. return {
  17474. empty : false,
  17475. unusedTokens : [],
  17476. unusedInput : [],
  17477. overflow : -2,
  17478. charsLeftOver : 0,
  17479. nullInput : false,
  17480. invalidMonth : null,
  17481. invalidFormat : false,
  17482. userInvalidated : false,
  17483. iso: false
  17484. };
  17485. }
  17486. function padToken(func, count) {
  17487. return function (a) {
  17488. return leftZeroFill(func.call(this, a), count);
  17489. };
  17490. }
  17491. function ordinalizeToken(func, period) {
  17492. return function (a) {
  17493. return this.lang().ordinal(func.call(this, a), period);
  17494. };
  17495. }
  17496. while (ordinalizeTokens.length) {
  17497. i = ordinalizeTokens.pop();
  17498. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  17499. }
  17500. while (paddedTokens.length) {
  17501. i = paddedTokens.pop();
  17502. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  17503. }
  17504. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  17505. /************************************
  17506. Constructors
  17507. ************************************/
  17508. function Language() {
  17509. }
  17510. // Moment prototype object
  17511. function Moment(config) {
  17512. checkOverflow(config);
  17513. extend(this, config);
  17514. }
  17515. // Duration Constructor
  17516. function Duration(duration) {
  17517. var normalizedInput = normalizeObjectUnits(duration),
  17518. years = normalizedInput.year || 0,
  17519. months = normalizedInput.month || 0,
  17520. weeks = normalizedInput.week || 0,
  17521. days = normalizedInput.day || 0,
  17522. hours = normalizedInput.hour || 0,
  17523. minutes = normalizedInput.minute || 0,
  17524. seconds = normalizedInput.second || 0,
  17525. milliseconds = normalizedInput.millisecond || 0;
  17526. // representation for dateAddRemove
  17527. this._milliseconds = +milliseconds +
  17528. seconds * 1e3 + // 1000
  17529. minutes * 6e4 + // 1000 * 60
  17530. hours * 36e5; // 1000 * 60 * 60
  17531. // Because of dateAddRemove treats 24 hours as different from a
  17532. // day when working around DST, we need to store them separately
  17533. this._days = +days +
  17534. weeks * 7;
  17535. // It is impossible translate months into days without knowing
  17536. // which months you are are talking about, so we have to store
  17537. // it separately.
  17538. this._months = +months +
  17539. years * 12;
  17540. this._data = {};
  17541. this._bubble();
  17542. }
  17543. /************************************
  17544. Helpers
  17545. ************************************/
  17546. function extend(a, b) {
  17547. for (var i in b) {
  17548. if (b.hasOwnProperty(i)) {
  17549. a[i] = b[i];
  17550. }
  17551. }
  17552. if (b.hasOwnProperty("toString")) {
  17553. a.toString = b.toString;
  17554. }
  17555. if (b.hasOwnProperty("valueOf")) {
  17556. a.valueOf = b.valueOf;
  17557. }
  17558. return a;
  17559. }
  17560. function cloneMoment(m) {
  17561. var result = {}, i;
  17562. for (i in m) {
  17563. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17564. result[i] = m[i];
  17565. }
  17566. }
  17567. return result;
  17568. }
  17569. function absRound(number) {
  17570. if (number < 0) {
  17571. return Math.ceil(number);
  17572. } else {
  17573. return Math.floor(number);
  17574. }
  17575. }
  17576. // left zero fill a number
  17577. // see http://jsperf.com/left-zero-filling for performance comparison
  17578. function leftZeroFill(number, targetLength, forceSign) {
  17579. var output = '' + Math.abs(number),
  17580. sign = number >= 0;
  17581. while (output.length < targetLength) {
  17582. output = '0' + output;
  17583. }
  17584. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17585. }
  17586. // helper function for _.addTime and _.subtractTime
  17587. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  17588. var milliseconds = duration._milliseconds,
  17589. days = duration._days,
  17590. months = duration._months,
  17591. minutes,
  17592. hours;
  17593. if (milliseconds) {
  17594. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17595. }
  17596. // store the minutes and hours so we can restore them
  17597. if (days || months) {
  17598. minutes = mom.minute();
  17599. hours = mom.hour();
  17600. }
  17601. if (days) {
  17602. mom.date(mom.date() + days * isAdding);
  17603. }
  17604. if (months) {
  17605. mom.month(mom.month() + months * isAdding);
  17606. }
  17607. if (milliseconds && !ignoreUpdateOffset) {
  17608. moment.updateOffset(mom);
  17609. }
  17610. // restore the minutes and hours after possibly changing dst
  17611. if (days || months) {
  17612. mom.minute(minutes);
  17613. mom.hour(hours);
  17614. }
  17615. }
  17616. // check if is an array
  17617. function isArray(input) {
  17618. return Object.prototype.toString.call(input) === '[object Array]';
  17619. }
  17620. function isDate(input) {
  17621. return Object.prototype.toString.call(input) === '[object Date]' ||
  17622. input instanceof Date;
  17623. }
  17624. // compare two arrays, return the number of differences
  17625. function compareArrays(array1, array2, dontConvert) {
  17626. var len = Math.min(array1.length, array2.length),
  17627. lengthDiff = Math.abs(array1.length - array2.length),
  17628. diffs = 0,
  17629. i;
  17630. for (i = 0; i < len; i++) {
  17631. if ((dontConvert && array1[i] !== array2[i]) ||
  17632. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17633. diffs++;
  17634. }
  17635. }
  17636. return diffs + lengthDiff;
  17637. }
  17638. function normalizeUnits(units) {
  17639. if (units) {
  17640. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17641. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17642. }
  17643. return units;
  17644. }
  17645. function normalizeObjectUnits(inputObject) {
  17646. var normalizedInput = {},
  17647. normalizedProp,
  17648. prop;
  17649. for (prop in inputObject) {
  17650. if (inputObject.hasOwnProperty(prop)) {
  17651. normalizedProp = normalizeUnits(prop);
  17652. if (normalizedProp) {
  17653. normalizedInput[normalizedProp] = inputObject[prop];
  17654. }
  17655. }
  17656. }
  17657. return normalizedInput;
  17658. }
  17659. function makeList(field) {
  17660. var count, setter;
  17661. if (field.indexOf('week') === 0) {
  17662. count = 7;
  17663. setter = 'day';
  17664. }
  17665. else if (field.indexOf('month') === 0) {
  17666. count = 12;
  17667. setter = 'month';
  17668. }
  17669. else {
  17670. return;
  17671. }
  17672. moment[field] = function (format, index) {
  17673. var i, getter,
  17674. method = moment.fn._lang[field],
  17675. results = [];
  17676. if (typeof format === 'number') {
  17677. index = format;
  17678. format = undefined;
  17679. }
  17680. getter = function (i) {
  17681. var m = moment().utc().set(setter, i);
  17682. return method.call(moment.fn._lang, m, format || '');
  17683. };
  17684. if (index != null) {
  17685. return getter(index);
  17686. }
  17687. else {
  17688. for (i = 0; i < count; i++) {
  17689. results.push(getter(i));
  17690. }
  17691. return results;
  17692. }
  17693. };
  17694. }
  17695. function toInt(argumentForCoercion) {
  17696. var coercedNumber = +argumentForCoercion,
  17697. value = 0;
  17698. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17699. if (coercedNumber >= 0) {
  17700. value = Math.floor(coercedNumber);
  17701. } else {
  17702. value = Math.ceil(coercedNumber);
  17703. }
  17704. }
  17705. return value;
  17706. }
  17707. function daysInMonth(year, month) {
  17708. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17709. }
  17710. function daysInYear(year) {
  17711. return isLeapYear(year) ? 366 : 365;
  17712. }
  17713. function isLeapYear(year) {
  17714. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17715. }
  17716. function checkOverflow(m) {
  17717. var overflow;
  17718. if (m._a && m._pf.overflow === -2) {
  17719. overflow =
  17720. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17721. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17722. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17723. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17724. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17725. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17726. -1;
  17727. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17728. overflow = DATE;
  17729. }
  17730. m._pf.overflow = overflow;
  17731. }
  17732. }
  17733. function isValid(m) {
  17734. if (m._isValid == null) {
  17735. m._isValid = !isNaN(m._d.getTime()) &&
  17736. m._pf.overflow < 0 &&
  17737. !m._pf.empty &&
  17738. !m._pf.invalidMonth &&
  17739. !m._pf.nullInput &&
  17740. !m._pf.invalidFormat &&
  17741. !m._pf.userInvalidated;
  17742. if (m._strict) {
  17743. m._isValid = m._isValid &&
  17744. m._pf.charsLeftOver === 0 &&
  17745. m._pf.unusedTokens.length === 0;
  17746. }
  17747. }
  17748. return m._isValid;
  17749. }
  17750. function normalizeLanguage(key) {
  17751. return key ? key.toLowerCase().replace('_', '-') : key;
  17752. }
  17753. // Return a moment from input, that is local/utc/zone equivalent to model.
  17754. function makeAs(input, model) {
  17755. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17756. moment(input).local();
  17757. }
  17758. /************************************
  17759. Languages
  17760. ************************************/
  17761. extend(Language.prototype, {
  17762. set : function (config) {
  17763. var prop, i;
  17764. for (i in config) {
  17765. prop = config[i];
  17766. if (typeof prop === 'function') {
  17767. this[i] = prop;
  17768. } else {
  17769. this['_' + i] = prop;
  17770. }
  17771. }
  17772. },
  17773. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17774. months : function (m) {
  17775. return this._months[m.month()];
  17776. },
  17777. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17778. monthsShort : function (m) {
  17779. return this._monthsShort[m.month()];
  17780. },
  17781. monthsParse : function (monthName) {
  17782. var i, mom, regex;
  17783. if (!this._monthsParse) {
  17784. this._monthsParse = [];
  17785. }
  17786. for (i = 0; i < 12; i++) {
  17787. // make the regex if we don't have it already
  17788. if (!this._monthsParse[i]) {
  17789. mom = moment.utc([2000, i]);
  17790. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17791. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17792. }
  17793. // test the regex
  17794. if (this._monthsParse[i].test(monthName)) {
  17795. return i;
  17796. }
  17797. }
  17798. },
  17799. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17800. weekdays : function (m) {
  17801. return this._weekdays[m.day()];
  17802. },
  17803. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17804. weekdaysShort : function (m) {
  17805. return this._weekdaysShort[m.day()];
  17806. },
  17807. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17808. weekdaysMin : function (m) {
  17809. return this._weekdaysMin[m.day()];
  17810. },
  17811. weekdaysParse : function (weekdayName) {
  17812. var i, mom, regex;
  17813. if (!this._weekdaysParse) {
  17814. this._weekdaysParse = [];
  17815. }
  17816. for (i = 0; i < 7; i++) {
  17817. // make the regex if we don't have it already
  17818. if (!this._weekdaysParse[i]) {
  17819. mom = moment([2000, 1]).day(i);
  17820. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17821. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17822. }
  17823. // test the regex
  17824. if (this._weekdaysParse[i].test(weekdayName)) {
  17825. return i;
  17826. }
  17827. }
  17828. },
  17829. _longDateFormat : {
  17830. LT : "h:mm A",
  17831. L : "MM/DD/YYYY",
  17832. LL : "MMMM D YYYY",
  17833. LLL : "MMMM D YYYY LT",
  17834. LLLL : "dddd, MMMM D YYYY LT"
  17835. },
  17836. longDateFormat : function (key) {
  17837. var output = this._longDateFormat[key];
  17838. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17839. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17840. return val.slice(1);
  17841. });
  17842. this._longDateFormat[key] = output;
  17843. }
  17844. return output;
  17845. },
  17846. isPM : function (input) {
  17847. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17848. // Using charAt should be more compatible.
  17849. return ((input + '').toLowerCase().charAt(0) === 'p');
  17850. },
  17851. _meridiemParse : /[ap]\.?m?\.?/i,
  17852. meridiem : function (hours, minutes, isLower) {
  17853. if (hours > 11) {
  17854. return isLower ? 'pm' : 'PM';
  17855. } else {
  17856. return isLower ? 'am' : 'AM';
  17857. }
  17858. },
  17859. _calendar : {
  17860. sameDay : '[Today at] LT',
  17861. nextDay : '[Tomorrow at] LT',
  17862. nextWeek : 'dddd [at] LT',
  17863. lastDay : '[Yesterday at] LT',
  17864. lastWeek : '[Last] dddd [at] LT',
  17865. sameElse : 'L'
  17866. },
  17867. calendar : function (key, mom) {
  17868. var output = this._calendar[key];
  17869. return typeof output === 'function' ? output.apply(mom) : output;
  17870. },
  17871. _relativeTime : {
  17872. future : "in %s",
  17873. past : "%s ago",
  17874. s : "a few seconds",
  17875. m : "a minute",
  17876. mm : "%d minutes",
  17877. h : "an hour",
  17878. hh : "%d hours",
  17879. d : "a day",
  17880. dd : "%d days",
  17881. M : "a month",
  17882. MM : "%d months",
  17883. y : "a year",
  17884. yy : "%d years"
  17885. },
  17886. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17887. var output = this._relativeTime[string];
  17888. return (typeof output === 'function') ?
  17889. output(number, withoutSuffix, string, isFuture) :
  17890. output.replace(/%d/i, number);
  17891. },
  17892. pastFuture : function (diff, output) {
  17893. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17894. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17895. },
  17896. ordinal : function (number) {
  17897. return this._ordinal.replace("%d", number);
  17898. },
  17899. _ordinal : "%d",
  17900. preparse : function (string) {
  17901. return string;
  17902. },
  17903. postformat : function (string) {
  17904. return string;
  17905. },
  17906. week : function (mom) {
  17907. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17908. },
  17909. _week : {
  17910. dow : 0, // Sunday is the first day of the week.
  17911. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17912. },
  17913. _invalidDate: 'Invalid date',
  17914. invalidDate: function () {
  17915. return this._invalidDate;
  17916. }
  17917. });
  17918. // Loads a language definition into the `languages` cache. The function
  17919. // takes a key and optionally values. If not in the browser and no values
  17920. // are provided, it will load the language file module. As a convenience,
  17921. // this function also returns the language values.
  17922. function loadLang(key, values) {
  17923. values.abbr = key;
  17924. if (!languages[key]) {
  17925. languages[key] = new Language();
  17926. }
  17927. languages[key].set(values);
  17928. return languages[key];
  17929. }
  17930. // Remove a language from the `languages` cache. Mostly useful in tests.
  17931. function unloadLang(key) {
  17932. delete languages[key];
  17933. }
  17934. // Determines which language definition to use and returns it.
  17935. //
  17936. // With no parameters, it will return the global language. If you
  17937. // pass in a language key, such as 'en', it will return the
  17938. // definition for 'en', so long as 'en' has already been loaded using
  17939. // moment.lang.
  17940. function getLangDefinition(key) {
  17941. var i = 0, j, lang, next, split,
  17942. get = function (k) {
  17943. if (!languages[k] && hasModule) {
  17944. try {
  17945. require('./lang/' + k);
  17946. } catch (e) { }
  17947. }
  17948. return languages[k];
  17949. };
  17950. if (!key) {
  17951. return moment.fn._lang;
  17952. }
  17953. if (!isArray(key)) {
  17954. //short-circuit everything else
  17955. lang = get(key);
  17956. if (lang) {
  17957. return lang;
  17958. }
  17959. key = [key];
  17960. }
  17961. //pick the language from the array
  17962. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17963. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17964. while (i < key.length) {
  17965. split = normalizeLanguage(key[i]).split('-');
  17966. j = split.length;
  17967. next = normalizeLanguage(key[i + 1]);
  17968. next = next ? next.split('-') : null;
  17969. while (j > 0) {
  17970. lang = get(split.slice(0, j).join('-'));
  17971. if (lang) {
  17972. return lang;
  17973. }
  17974. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17975. //the next array item is better than a shallower substring of this one
  17976. break;
  17977. }
  17978. j--;
  17979. }
  17980. i++;
  17981. }
  17982. return moment.fn._lang;
  17983. }
  17984. /************************************
  17985. Formatting
  17986. ************************************/
  17987. function removeFormattingTokens(input) {
  17988. if (input.match(/\[[\s\S]/)) {
  17989. return input.replace(/^\[|\]$/g, "");
  17990. }
  17991. return input.replace(/\\/g, "");
  17992. }
  17993. function makeFormatFunction(format) {
  17994. var array = format.match(formattingTokens), i, length;
  17995. for (i = 0, length = array.length; i < length; i++) {
  17996. if (formatTokenFunctions[array[i]]) {
  17997. array[i] = formatTokenFunctions[array[i]];
  17998. } else {
  17999. array[i] = removeFormattingTokens(array[i]);
  18000. }
  18001. }
  18002. return function (mom) {
  18003. var output = "";
  18004. for (i = 0; i < length; i++) {
  18005. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  18006. }
  18007. return output;
  18008. };
  18009. }
  18010. // format date using native date object
  18011. function formatMoment(m, format) {
  18012. if (!m.isValid()) {
  18013. return m.lang().invalidDate();
  18014. }
  18015. format = expandFormat(format, m.lang());
  18016. if (!formatFunctions[format]) {
  18017. formatFunctions[format] = makeFormatFunction(format);
  18018. }
  18019. return formatFunctions[format](m);
  18020. }
  18021. function expandFormat(format, lang) {
  18022. var i = 5;
  18023. function replaceLongDateFormatTokens(input) {
  18024. return lang.longDateFormat(input) || input;
  18025. }
  18026. localFormattingTokens.lastIndex = 0;
  18027. while (i >= 0 && localFormattingTokens.test(format)) {
  18028. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  18029. localFormattingTokens.lastIndex = 0;
  18030. i -= 1;
  18031. }
  18032. return format;
  18033. }
  18034. /************************************
  18035. Parsing
  18036. ************************************/
  18037. // get the regex to find the next token
  18038. function getParseRegexForToken(token, config) {
  18039. var a, strict = config._strict;
  18040. switch (token) {
  18041. case 'DDDD':
  18042. return parseTokenThreeDigits;
  18043. case 'YYYY':
  18044. case 'GGGG':
  18045. case 'gggg':
  18046. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  18047. case 'Y':
  18048. case 'G':
  18049. case 'g':
  18050. return parseTokenSignedNumber;
  18051. case 'YYYYYY':
  18052. case 'YYYYY':
  18053. case 'GGGGG':
  18054. case 'ggggg':
  18055. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  18056. case 'S':
  18057. if (strict) { return parseTokenOneDigit; }
  18058. /* falls through */
  18059. case 'SS':
  18060. if (strict) { return parseTokenTwoDigits; }
  18061. /* falls through */
  18062. case 'SSS':
  18063. if (strict) { return parseTokenThreeDigits; }
  18064. /* falls through */
  18065. case 'DDD':
  18066. return parseTokenOneToThreeDigits;
  18067. case 'MMM':
  18068. case 'MMMM':
  18069. case 'dd':
  18070. case 'ddd':
  18071. case 'dddd':
  18072. return parseTokenWord;
  18073. case 'a':
  18074. case 'A':
  18075. return getLangDefinition(config._l)._meridiemParse;
  18076. case 'X':
  18077. return parseTokenTimestampMs;
  18078. case 'Z':
  18079. case 'ZZ':
  18080. return parseTokenTimezone;
  18081. case 'T':
  18082. return parseTokenT;
  18083. case 'SSSS':
  18084. return parseTokenDigits;
  18085. case 'MM':
  18086. case 'DD':
  18087. case 'YY':
  18088. case 'GG':
  18089. case 'gg':
  18090. case 'HH':
  18091. case 'hh':
  18092. case 'mm':
  18093. case 'ss':
  18094. case 'ww':
  18095. case 'WW':
  18096. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  18097. case 'M':
  18098. case 'D':
  18099. case 'd':
  18100. case 'H':
  18101. case 'h':
  18102. case 'm':
  18103. case 's':
  18104. case 'w':
  18105. case 'W':
  18106. case 'e':
  18107. case 'E':
  18108. return parseTokenOneOrTwoDigits;
  18109. default :
  18110. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  18111. return a;
  18112. }
  18113. }
  18114. function timezoneMinutesFromString(string) {
  18115. string = string || "";
  18116. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  18117. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  18118. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  18119. minutes = +(parts[1] * 60) + toInt(parts[2]);
  18120. return parts[0] === '+' ? -minutes : minutes;
  18121. }
  18122. // function to convert string input to date
  18123. function addTimeToArrayFromToken(token, input, config) {
  18124. var a, datePartArray = config._a;
  18125. switch (token) {
  18126. // MONTH
  18127. case 'M' : // fall through to MM
  18128. case 'MM' :
  18129. if (input != null) {
  18130. datePartArray[MONTH] = toInt(input) - 1;
  18131. }
  18132. break;
  18133. case 'MMM' : // fall through to MMMM
  18134. case 'MMMM' :
  18135. a = getLangDefinition(config._l).monthsParse(input);
  18136. // if we didn't find a month name, mark the date as invalid.
  18137. if (a != null) {
  18138. datePartArray[MONTH] = a;
  18139. } else {
  18140. config._pf.invalidMonth = input;
  18141. }
  18142. break;
  18143. // DAY OF MONTH
  18144. case 'D' : // fall through to DD
  18145. case 'DD' :
  18146. if (input != null) {
  18147. datePartArray[DATE] = toInt(input);
  18148. }
  18149. break;
  18150. // DAY OF YEAR
  18151. case 'DDD' : // fall through to DDDD
  18152. case 'DDDD' :
  18153. if (input != null) {
  18154. config._dayOfYear = toInt(input);
  18155. }
  18156. break;
  18157. // YEAR
  18158. case 'YY' :
  18159. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  18160. break;
  18161. case 'YYYY' :
  18162. case 'YYYYY' :
  18163. case 'YYYYYY' :
  18164. datePartArray[YEAR] = toInt(input);
  18165. break;
  18166. // AM / PM
  18167. case 'a' : // fall through to A
  18168. case 'A' :
  18169. config._isPm = getLangDefinition(config._l).isPM(input);
  18170. break;
  18171. // 24 HOUR
  18172. case 'H' : // fall through to hh
  18173. case 'HH' : // fall through to hh
  18174. case 'h' : // fall through to hh
  18175. case 'hh' :
  18176. datePartArray[HOUR] = toInt(input);
  18177. break;
  18178. // MINUTE
  18179. case 'm' : // fall through to mm
  18180. case 'mm' :
  18181. datePartArray[MINUTE] = toInt(input);
  18182. break;
  18183. // SECOND
  18184. case 's' : // fall through to ss
  18185. case 'ss' :
  18186. datePartArray[SECOND] = toInt(input);
  18187. break;
  18188. // MILLISECOND
  18189. case 'S' :
  18190. case 'SS' :
  18191. case 'SSS' :
  18192. case 'SSSS' :
  18193. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  18194. break;
  18195. // UNIX TIMESTAMP WITH MS
  18196. case 'X':
  18197. config._d = new Date(parseFloat(input) * 1000);
  18198. break;
  18199. // TIMEZONE
  18200. case 'Z' : // fall through to ZZ
  18201. case 'ZZ' :
  18202. config._useUTC = true;
  18203. config._tzm = timezoneMinutesFromString(input);
  18204. break;
  18205. case 'w':
  18206. case 'ww':
  18207. case 'W':
  18208. case 'WW':
  18209. case 'd':
  18210. case 'dd':
  18211. case 'ddd':
  18212. case 'dddd':
  18213. case 'e':
  18214. case 'E':
  18215. token = token.substr(0, 1);
  18216. /* falls through */
  18217. case 'gg':
  18218. case 'gggg':
  18219. case 'GG':
  18220. case 'GGGG':
  18221. case 'GGGGG':
  18222. token = token.substr(0, 2);
  18223. if (input) {
  18224. config._w = config._w || {};
  18225. config._w[token] = input;
  18226. }
  18227. break;
  18228. }
  18229. }
  18230. // convert an array to a date.
  18231. // the array should mirror the parameters below
  18232. // note: all values past the year are optional and will default to the lowest possible value.
  18233. // [year, month, day , hour, minute, second, millisecond]
  18234. function dateFromConfig(config) {
  18235. var i, date, input = [], currentDate,
  18236. yearToUse, fixYear, w, temp, lang, weekday, week;
  18237. if (config._d) {
  18238. return;
  18239. }
  18240. currentDate = currentDateArray(config);
  18241. //compute day of the year from weeks and weekdays
  18242. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  18243. fixYear = function (val) {
  18244. var int_val = parseInt(val, 10);
  18245. return val ?
  18246. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  18247. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  18248. };
  18249. w = config._w;
  18250. if (w.GG != null || w.W != null || w.E != null) {
  18251. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  18252. }
  18253. else {
  18254. lang = getLangDefinition(config._l);
  18255. weekday = w.d != null ? parseWeekday(w.d, lang) :
  18256. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  18257. week = parseInt(w.w, 10) || 1;
  18258. //if we're parsing 'd', then the low day numbers may be next week
  18259. if (w.d != null && weekday < lang._week.dow) {
  18260. week++;
  18261. }
  18262. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  18263. }
  18264. config._a[YEAR] = temp.year;
  18265. config._dayOfYear = temp.dayOfYear;
  18266. }
  18267. //if the day of the year is set, figure out what it is
  18268. if (config._dayOfYear) {
  18269. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  18270. if (config._dayOfYear > daysInYear(yearToUse)) {
  18271. config._pf._overflowDayOfYear = true;
  18272. }
  18273. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  18274. config._a[MONTH] = date.getUTCMonth();
  18275. config._a[DATE] = date.getUTCDate();
  18276. }
  18277. // Default to current date.
  18278. // * if no year, month, day of month are given, default to today
  18279. // * if day of month is given, default month and year
  18280. // * if month is given, default only year
  18281. // * if year is given, don't default anything
  18282. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  18283. config._a[i] = input[i] = currentDate[i];
  18284. }
  18285. // Zero out whatever was not defaulted, including time
  18286. for (; i < 7; i++) {
  18287. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  18288. }
  18289. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  18290. input[HOUR] += toInt((config._tzm || 0) / 60);
  18291. input[MINUTE] += toInt((config._tzm || 0) % 60);
  18292. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  18293. }
  18294. function dateFromObject(config) {
  18295. var normalizedInput;
  18296. if (config._d) {
  18297. return;
  18298. }
  18299. normalizedInput = normalizeObjectUnits(config._i);
  18300. config._a = [
  18301. normalizedInput.year,
  18302. normalizedInput.month,
  18303. normalizedInput.day,
  18304. normalizedInput.hour,
  18305. normalizedInput.minute,
  18306. normalizedInput.second,
  18307. normalizedInput.millisecond
  18308. ];
  18309. dateFromConfig(config);
  18310. }
  18311. function currentDateArray(config) {
  18312. var now = new Date();
  18313. if (config._useUTC) {
  18314. return [
  18315. now.getUTCFullYear(),
  18316. now.getUTCMonth(),
  18317. now.getUTCDate()
  18318. ];
  18319. } else {
  18320. return [now.getFullYear(), now.getMonth(), now.getDate()];
  18321. }
  18322. }
  18323. // date from string and format string
  18324. function makeDateFromStringAndFormat(config) {
  18325. config._a = [];
  18326. config._pf.empty = true;
  18327. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  18328. var lang = getLangDefinition(config._l),
  18329. string = '' + config._i,
  18330. i, parsedInput, tokens, token, skipped,
  18331. stringLength = string.length,
  18332. totalParsedInputLength = 0;
  18333. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  18334. for (i = 0; i < tokens.length; i++) {
  18335. token = tokens[i];
  18336. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  18337. if (parsedInput) {
  18338. skipped = string.substr(0, string.indexOf(parsedInput));
  18339. if (skipped.length > 0) {
  18340. config._pf.unusedInput.push(skipped);
  18341. }
  18342. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  18343. totalParsedInputLength += parsedInput.length;
  18344. }
  18345. // don't parse if it's not a known token
  18346. if (formatTokenFunctions[token]) {
  18347. if (parsedInput) {
  18348. config._pf.empty = false;
  18349. }
  18350. else {
  18351. config._pf.unusedTokens.push(token);
  18352. }
  18353. addTimeToArrayFromToken(token, parsedInput, config);
  18354. }
  18355. else if (config._strict && !parsedInput) {
  18356. config._pf.unusedTokens.push(token);
  18357. }
  18358. }
  18359. // add remaining unparsed input length to the string
  18360. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  18361. if (string.length > 0) {
  18362. config._pf.unusedInput.push(string);
  18363. }
  18364. // handle am pm
  18365. if (config._isPm && config._a[HOUR] < 12) {
  18366. config._a[HOUR] += 12;
  18367. }
  18368. // if is 12 am, change hours to 0
  18369. if (config._isPm === false && config._a[HOUR] === 12) {
  18370. config._a[HOUR] = 0;
  18371. }
  18372. dateFromConfig(config);
  18373. checkOverflow(config);
  18374. }
  18375. function unescapeFormat(s) {
  18376. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  18377. return p1 || p2 || p3 || p4;
  18378. });
  18379. }
  18380. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  18381. function regexpEscape(s) {
  18382. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18383. }
  18384. // date from string and array of format strings
  18385. function makeDateFromStringAndArray(config) {
  18386. var tempConfig,
  18387. bestMoment,
  18388. scoreToBeat,
  18389. i,
  18390. currentScore;
  18391. if (config._f.length === 0) {
  18392. config._pf.invalidFormat = true;
  18393. config._d = new Date(NaN);
  18394. return;
  18395. }
  18396. for (i = 0; i < config._f.length; i++) {
  18397. currentScore = 0;
  18398. tempConfig = extend({}, config);
  18399. tempConfig._pf = defaultParsingFlags();
  18400. tempConfig._f = config._f[i];
  18401. makeDateFromStringAndFormat(tempConfig);
  18402. if (!isValid(tempConfig)) {
  18403. continue;
  18404. }
  18405. // if there is any input that was not parsed add a penalty for that format
  18406. currentScore += tempConfig._pf.charsLeftOver;
  18407. //or tokens
  18408. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18409. tempConfig._pf.score = currentScore;
  18410. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18411. scoreToBeat = currentScore;
  18412. bestMoment = tempConfig;
  18413. }
  18414. }
  18415. extend(config, bestMoment || tempConfig);
  18416. }
  18417. // date from iso format
  18418. function makeDateFromString(config) {
  18419. var i, l,
  18420. string = config._i,
  18421. match = isoRegex.exec(string);
  18422. if (match) {
  18423. config._pf.iso = true;
  18424. for (i = 0, l = isoDates.length; i < l; i++) {
  18425. if (isoDates[i][1].exec(string)) {
  18426. // match[5] should be "T" or undefined
  18427. config._f = isoDates[i][0] + (match[6] || " ");
  18428. break;
  18429. }
  18430. }
  18431. for (i = 0, l = isoTimes.length; i < l; i++) {
  18432. if (isoTimes[i][1].exec(string)) {
  18433. config._f += isoTimes[i][0];
  18434. break;
  18435. }
  18436. }
  18437. if (string.match(parseTokenTimezone)) {
  18438. config._f += "Z";
  18439. }
  18440. makeDateFromStringAndFormat(config);
  18441. }
  18442. else {
  18443. config._d = new Date(string);
  18444. }
  18445. }
  18446. function makeDateFromInput(config) {
  18447. var input = config._i,
  18448. matched = aspNetJsonRegex.exec(input);
  18449. if (input === undefined) {
  18450. config._d = new Date();
  18451. } else if (matched) {
  18452. config._d = new Date(+matched[1]);
  18453. } else if (typeof input === 'string') {
  18454. makeDateFromString(config);
  18455. } else if (isArray(input)) {
  18456. config._a = input.slice(0);
  18457. dateFromConfig(config);
  18458. } else if (isDate(input)) {
  18459. config._d = new Date(+input);
  18460. } else if (typeof(input) === 'object') {
  18461. dateFromObject(config);
  18462. } else {
  18463. config._d = new Date(input);
  18464. }
  18465. }
  18466. function makeDate(y, m, d, h, M, s, ms) {
  18467. //can't just apply() to create a date:
  18468. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  18469. var date = new Date(y, m, d, h, M, s, ms);
  18470. //the date constructor doesn't accept years < 1970
  18471. if (y < 1970) {
  18472. date.setFullYear(y);
  18473. }
  18474. return date;
  18475. }
  18476. function makeUTCDate(y) {
  18477. var date = new Date(Date.UTC.apply(null, arguments));
  18478. if (y < 1970) {
  18479. date.setUTCFullYear(y);
  18480. }
  18481. return date;
  18482. }
  18483. function parseWeekday(input, language) {
  18484. if (typeof input === 'string') {
  18485. if (!isNaN(input)) {
  18486. input = parseInt(input, 10);
  18487. }
  18488. else {
  18489. input = language.weekdaysParse(input);
  18490. if (typeof input !== 'number') {
  18491. return null;
  18492. }
  18493. }
  18494. }
  18495. return input;
  18496. }
  18497. /************************************
  18498. Relative Time
  18499. ************************************/
  18500. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  18501. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  18502. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  18503. }
  18504. function relativeTime(milliseconds, withoutSuffix, lang) {
  18505. var seconds = round(Math.abs(milliseconds) / 1000),
  18506. minutes = round(seconds / 60),
  18507. hours = round(minutes / 60),
  18508. days = round(hours / 24),
  18509. years = round(days / 365),
  18510. args = seconds < 45 && ['s', seconds] ||
  18511. minutes === 1 && ['m'] ||
  18512. minutes < 45 && ['mm', minutes] ||
  18513. hours === 1 && ['h'] ||
  18514. hours < 22 && ['hh', hours] ||
  18515. days === 1 && ['d'] ||
  18516. days <= 25 && ['dd', days] ||
  18517. days <= 45 && ['M'] ||
  18518. days < 345 && ['MM', round(days / 30)] ||
  18519. years === 1 && ['y'] || ['yy', years];
  18520. args[2] = withoutSuffix;
  18521. args[3] = milliseconds > 0;
  18522. args[4] = lang;
  18523. return substituteTimeAgo.apply({}, args);
  18524. }
  18525. /************************************
  18526. Week of Year
  18527. ************************************/
  18528. // firstDayOfWeek 0 = sun, 6 = sat
  18529. // the day of the week that starts the week
  18530. // (usually sunday or monday)
  18531. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18532. // the first week is the week that contains the first
  18533. // of this day of the week
  18534. // (eg. ISO weeks use thursday (4))
  18535. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18536. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18537. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18538. adjustedMoment;
  18539. if (daysToDayOfWeek > end) {
  18540. daysToDayOfWeek -= 7;
  18541. }
  18542. if (daysToDayOfWeek < end - 7) {
  18543. daysToDayOfWeek += 7;
  18544. }
  18545. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18546. return {
  18547. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18548. year: adjustedMoment.year()
  18549. };
  18550. }
  18551. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18552. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18553. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18554. weekday = weekday != null ? weekday : firstDayOfWeek;
  18555. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18556. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18557. return {
  18558. year: dayOfYear > 0 ? year : year - 1,
  18559. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18560. };
  18561. }
  18562. /************************************
  18563. Top Level Functions
  18564. ************************************/
  18565. function makeMoment(config) {
  18566. var input = config._i,
  18567. format = config._f;
  18568. if (input === null) {
  18569. return moment.invalid({nullInput: true});
  18570. }
  18571. if (typeof input === 'string') {
  18572. config._i = input = getLangDefinition().preparse(input);
  18573. }
  18574. if (moment.isMoment(input)) {
  18575. config = cloneMoment(input);
  18576. config._d = new Date(+input._d);
  18577. } else if (format) {
  18578. if (isArray(format)) {
  18579. makeDateFromStringAndArray(config);
  18580. } else {
  18581. makeDateFromStringAndFormat(config);
  18582. }
  18583. } else {
  18584. makeDateFromInput(config);
  18585. }
  18586. return new Moment(config);
  18587. }
  18588. moment = function (input, format, lang, strict) {
  18589. var c;
  18590. if (typeof(lang) === "boolean") {
  18591. strict = lang;
  18592. lang = undefined;
  18593. }
  18594. // object construction must be done this way.
  18595. // https://github.com/moment/moment/issues/1423
  18596. c = {};
  18597. c._isAMomentObject = true;
  18598. c._i = input;
  18599. c._f = format;
  18600. c._l = lang;
  18601. c._strict = strict;
  18602. c._isUTC = false;
  18603. c._pf = defaultParsingFlags();
  18604. return makeMoment(c);
  18605. };
  18606. // creating with utc
  18607. moment.utc = function (input, format, lang, strict) {
  18608. var c;
  18609. if (typeof(lang) === "boolean") {
  18610. strict = lang;
  18611. lang = undefined;
  18612. }
  18613. // object construction must be done this way.
  18614. // https://github.com/moment/moment/issues/1423
  18615. c = {};
  18616. c._isAMomentObject = true;
  18617. c._useUTC = true;
  18618. c._isUTC = true;
  18619. c._l = lang;
  18620. c._i = input;
  18621. c._f = format;
  18622. c._strict = strict;
  18623. c._pf = defaultParsingFlags();
  18624. return makeMoment(c).utc();
  18625. };
  18626. // creating with unix timestamp (in seconds)
  18627. moment.unix = function (input) {
  18628. return moment(input * 1000);
  18629. };
  18630. // duration
  18631. moment.duration = function (input, key) {
  18632. var duration = input,
  18633. // matching against regexp is expensive, do it on demand
  18634. match = null,
  18635. sign,
  18636. ret,
  18637. parseIso;
  18638. if (moment.isDuration(input)) {
  18639. duration = {
  18640. ms: input._milliseconds,
  18641. d: input._days,
  18642. M: input._months
  18643. };
  18644. } else if (typeof input === 'number') {
  18645. duration = {};
  18646. if (key) {
  18647. duration[key] = input;
  18648. } else {
  18649. duration.milliseconds = input;
  18650. }
  18651. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18652. sign = (match[1] === "-") ? -1 : 1;
  18653. duration = {
  18654. y: 0,
  18655. d: toInt(match[DATE]) * sign,
  18656. h: toInt(match[HOUR]) * sign,
  18657. m: toInt(match[MINUTE]) * sign,
  18658. s: toInt(match[SECOND]) * sign,
  18659. ms: toInt(match[MILLISECOND]) * sign
  18660. };
  18661. } else if (!!(match = isoDurationRegex.exec(input))) {
  18662. sign = (match[1] === "-") ? -1 : 1;
  18663. parseIso = function (inp) {
  18664. // We'd normally use ~~inp for this, but unfortunately it also
  18665. // converts floats to ints.
  18666. // inp may be undefined, so careful calling replace on it.
  18667. var res = inp && parseFloat(inp.replace(',', '.'));
  18668. // apply sign while we're at it
  18669. return (isNaN(res) ? 0 : res) * sign;
  18670. };
  18671. duration = {
  18672. y: parseIso(match[2]),
  18673. M: parseIso(match[3]),
  18674. d: parseIso(match[4]),
  18675. h: parseIso(match[5]),
  18676. m: parseIso(match[6]),
  18677. s: parseIso(match[7]),
  18678. w: parseIso(match[8])
  18679. };
  18680. }
  18681. ret = new Duration(duration);
  18682. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18683. ret._lang = input._lang;
  18684. }
  18685. return ret;
  18686. };
  18687. // version number
  18688. moment.version = VERSION;
  18689. // default format
  18690. moment.defaultFormat = isoFormat;
  18691. // This function will be called whenever a moment is mutated.
  18692. // It is intended to keep the offset in sync with the timezone.
  18693. moment.updateOffset = function () {};
  18694. // This function will load languages and then set the global language. If
  18695. // no arguments are passed in, it will simply return the current global
  18696. // language key.
  18697. moment.lang = function (key, values) {
  18698. var r;
  18699. if (!key) {
  18700. return moment.fn._lang._abbr;
  18701. }
  18702. if (values) {
  18703. loadLang(normalizeLanguage(key), values);
  18704. } else if (values === null) {
  18705. unloadLang(key);
  18706. key = 'en';
  18707. } else if (!languages[key]) {
  18708. getLangDefinition(key);
  18709. }
  18710. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18711. return r._abbr;
  18712. };
  18713. // returns language data
  18714. moment.langData = function (key) {
  18715. if (key && key._lang && key._lang._abbr) {
  18716. key = key._lang._abbr;
  18717. }
  18718. return getLangDefinition(key);
  18719. };
  18720. // compare moment object
  18721. moment.isMoment = function (obj) {
  18722. return obj instanceof Moment ||
  18723. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18724. };
  18725. // for typechecking Duration objects
  18726. moment.isDuration = function (obj) {
  18727. return obj instanceof Duration;
  18728. };
  18729. for (i = lists.length - 1; i >= 0; --i) {
  18730. makeList(lists[i]);
  18731. }
  18732. moment.normalizeUnits = function (units) {
  18733. return normalizeUnits(units);
  18734. };
  18735. moment.invalid = function (flags) {
  18736. var m = moment.utc(NaN);
  18737. if (flags != null) {
  18738. extend(m._pf, flags);
  18739. }
  18740. else {
  18741. m._pf.userInvalidated = true;
  18742. }
  18743. return m;
  18744. };
  18745. moment.parseZone = function (input) {
  18746. return moment(input).parseZone();
  18747. };
  18748. /************************************
  18749. Moment Prototype
  18750. ************************************/
  18751. extend(moment.fn = Moment.prototype, {
  18752. clone : function () {
  18753. return moment(this);
  18754. },
  18755. valueOf : function () {
  18756. return +this._d + ((this._offset || 0) * 60000);
  18757. },
  18758. unix : function () {
  18759. return Math.floor(+this / 1000);
  18760. },
  18761. toString : function () {
  18762. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18763. },
  18764. toDate : function () {
  18765. return this._offset ? new Date(+this) : this._d;
  18766. },
  18767. toISOString : function () {
  18768. var m = moment(this).utc();
  18769. if (0 < m.year() && m.year() <= 9999) {
  18770. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18771. } else {
  18772. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18773. }
  18774. },
  18775. toArray : function () {
  18776. var m = this;
  18777. return [
  18778. m.year(),
  18779. m.month(),
  18780. m.date(),
  18781. m.hours(),
  18782. m.minutes(),
  18783. m.seconds(),
  18784. m.milliseconds()
  18785. ];
  18786. },
  18787. isValid : function () {
  18788. return isValid(this);
  18789. },
  18790. isDSTShifted : function () {
  18791. if (this._a) {
  18792. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18793. }
  18794. return false;
  18795. },
  18796. parsingFlags : function () {
  18797. return extend({}, this._pf);
  18798. },
  18799. invalidAt: function () {
  18800. return this._pf.overflow;
  18801. },
  18802. utc : function () {
  18803. return this.zone(0);
  18804. },
  18805. local : function () {
  18806. this.zone(0);
  18807. this._isUTC = false;
  18808. return this;
  18809. },
  18810. format : function (inputString) {
  18811. var output = formatMoment(this, inputString || moment.defaultFormat);
  18812. return this.lang().postformat(output);
  18813. },
  18814. add : function (input, val) {
  18815. var dur;
  18816. // switch args to support add('s', 1) and add(1, 's')
  18817. if (typeof input === 'string') {
  18818. dur = moment.duration(+val, input);
  18819. } else {
  18820. dur = moment.duration(input, val);
  18821. }
  18822. addOrSubtractDurationFromMoment(this, dur, 1);
  18823. return this;
  18824. },
  18825. subtract : function (input, val) {
  18826. var dur;
  18827. // switch args to support subtract('s', 1) and subtract(1, 's')
  18828. if (typeof input === 'string') {
  18829. dur = moment.duration(+val, input);
  18830. } else {
  18831. dur = moment.duration(input, val);
  18832. }
  18833. addOrSubtractDurationFromMoment(this, dur, -1);
  18834. return this;
  18835. },
  18836. diff : function (input, units, asFloat) {
  18837. var that = makeAs(input, this),
  18838. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18839. diff, output;
  18840. units = normalizeUnits(units);
  18841. if (units === 'year' || units === 'month') {
  18842. // average number of days in the months in the given dates
  18843. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18844. // difference in months
  18845. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18846. // adjust by taking difference in days, average number of days
  18847. // and dst in the given months.
  18848. output += ((this - moment(this).startOf('month')) -
  18849. (that - moment(that).startOf('month'))) / diff;
  18850. // same as above but with zones, to negate all dst
  18851. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18852. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18853. if (units === 'year') {
  18854. output = output / 12;
  18855. }
  18856. } else {
  18857. diff = (this - that);
  18858. output = units === 'second' ? diff / 1e3 : // 1000
  18859. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18860. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18861. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18862. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18863. diff;
  18864. }
  18865. return asFloat ? output : absRound(output);
  18866. },
  18867. from : function (time, withoutSuffix) {
  18868. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18869. },
  18870. fromNow : function (withoutSuffix) {
  18871. return this.from(moment(), withoutSuffix);
  18872. },
  18873. calendar : function () {
  18874. // We want to compare the start of today, vs this.
  18875. // Getting start-of-today depends on whether we're zone'd or not.
  18876. var sod = makeAs(moment(), this).startOf('day'),
  18877. diff = this.diff(sod, 'days', true),
  18878. format = diff < -6 ? 'sameElse' :
  18879. diff < -1 ? 'lastWeek' :
  18880. diff < 0 ? 'lastDay' :
  18881. diff < 1 ? 'sameDay' :
  18882. diff < 2 ? 'nextDay' :
  18883. diff < 7 ? 'nextWeek' : 'sameElse';
  18884. return this.format(this.lang().calendar(format, this));
  18885. },
  18886. isLeapYear : function () {
  18887. return isLeapYear(this.year());
  18888. },
  18889. isDST : function () {
  18890. return (this.zone() < this.clone().month(0).zone() ||
  18891. this.zone() < this.clone().month(5).zone());
  18892. },
  18893. day : function (input) {
  18894. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18895. if (input != null) {
  18896. input = parseWeekday(input, this.lang());
  18897. return this.add({ d : input - day });
  18898. } else {
  18899. return day;
  18900. }
  18901. },
  18902. month : function (input) {
  18903. var utc = this._isUTC ? 'UTC' : '',
  18904. dayOfMonth;
  18905. if (input != null) {
  18906. if (typeof input === 'string') {
  18907. input = this.lang().monthsParse(input);
  18908. if (typeof input !== 'number') {
  18909. return this;
  18910. }
  18911. }
  18912. dayOfMonth = this.date();
  18913. this.date(1);
  18914. this._d['set' + utc + 'Month'](input);
  18915. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  18916. moment.updateOffset(this);
  18917. return this;
  18918. } else {
  18919. return this._d['get' + utc + 'Month']();
  18920. }
  18921. },
  18922. startOf: function (units) {
  18923. units = normalizeUnits(units);
  18924. // the following switch intentionally omits break keywords
  18925. // to utilize falling through the cases.
  18926. switch (units) {
  18927. case 'year':
  18928. this.month(0);
  18929. /* falls through */
  18930. case 'month':
  18931. this.date(1);
  18932. /* falls through */
  18933. case 'week':
  18934. case 'isoWeek':
  18935. case 'day':
  18936. this.hours(0);
  18937. /* falls through */
  18938. case 'hour':
  18939. this.minutes(0);
  18940. /* falls through */
  18941. case 'minute':
  18942. this.seconds(0);
  18943. /* falls through */
  18944. case 'second':
  18945. this.milliseconds(0);
  18946. /* falls through */
  18947. }
  18948. // weeks are a special case
  18949. if (units === 'week') {
  18950. this.weekday(0);
  18951. } else if (units === 'isoWeek') {
  18952. this.isoWeekday(1);
  18953. }
  18954. return this;
  18955. },
  18956. endOf: function (units) {
  18957. units = normalizeUnits(units);
  18958. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18959. },
  18960. isAfter: function (input, units) {
  18961. units = typeof units !== 'undefined' ? units : 'millisecond';
  18962. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18963. },
  18964. isBefore: function (input, units) {
  18965. units = typeof units !== 'undefined' ? units : 'millisecond';
  18966. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18967. },
  18968. isSame: function (input, units) {
  18969. units = units || 'ms';
  18970. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18971. },
  18972. min: function (other) {
  18973. other = moment.apply(null, arguments);
  18974. return other < this ? this : other;
  18975. },
  18976. max: function (other) {
  18977. other = moment.apply(null, arguments);
  18978. return other > this ? this : other;
  18979. },
  18980. zone : function (input) {
  18981. var offset = this._offset || 0;
  18982. if (input != null) {
  18983. if (typeof input === "string") {
  18984. input = timezoneMinutesFromString(input);
  18985. }
  18986. if (Math.abs(input) < 16) {
  18987. input = input * 60;
  18988. }
  18989. this._offset = input;
  18990. this._isUTC = true;
  18991. if (offset !== input) {
  18992. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  18993. }
  18994. } else {
  18995. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18996. }
  18997. return this;
  18998. },
  18999. zoneAbbr : function () {
  19000. return this._isUTC ? "UTC" : "";
  19001. },
  19002. zoneName : function () {
  19003. return this._isUTC ? "Coordinated Universal Time" : "";
  19004. },
  19005. parseZone : function () {
  19006. if (this._tzm) {
  19007. this.zone(this._tzm);
  19008. } else if (typeof this._i === 'string') {
  19009. this.zone(this._i);
  19010. }
  19011. return this;
  19012. },
  19013. hasAlignedHourOffset : function (input) {
  19014. if (!input) {
  19015. input = 0;
  19016. }
  19017. else {
  19018. input = moment(input).zone();
  19019. }
  19020. return (this.zone() - input) % 60 === 0;
  19021. },
  19022. daysInMonth : function () {
  19023. return daysInMonth(this.year(), this.month());
  19024. },
  19025. dayOfYear : function (input) {
  19026. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  19027. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  19028. },
  19029. quarter : function () {
  19030. return Math.ceil((this.month() + 1.0) / 3.0);
  19031. },
  19032. weekYear : function (input) {
  19033. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  19034. return input == null ? year : this.add("y", (input - year));
  19035. },
  19036. isoWeekYear : function (input) {
  19037. var year = weekOfYear(this, 1, 4).year;
  19038. return input == null ? year : this.add("y", (input - year));
  19039. },
  19040. week : function (input) {
  19041. var week = this.lang().week(this);
  19042. return input == null ? week : this.add("d", (input - week) * 7);
  19043. },
  19044. isoWeek : function (input) {
  19045. var week = weekOfYear(this, 1, 4).week;
  19046. return input == null ? week : this.add("d", (input - week) * 7);
  19047. },
  19048. weekday : function (input) {
  19049. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  19050. return input == null ? weekday : this.add("d", input - weekday);
  19051. },
  19052. isoWeekday : function (input) {
  19053. // behaves the same as moment#day except
  19054. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  19055. // as a setter, sunday should belong to the previous week.
  19056. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  19057. },
  19058. get : function (units) {
  19059. units = normalizeUnits(units);
  19060. return this[units]();
  19061. },
  19062. set : function (units, value) {
  19063. units = normalizeUnits(units);
  19064. if (typeof this[units] === 'function') {
  19065. this[units](value);
  19066. }
  19067. return this;
  19068. },
  19069. // If passed a language key, it will set the language for this
  19070. // instance. Otherwise, it will return the language configuration
  19071. // variables for this instance.
  19072. lang : function (key) {
  19073. if (key === undefined) {
  19074. return this._lang;
  19075. } else {
  19076. this._lang = getLangDefinition(key);
  19077. return this;
  19078. }
  19079. }
  19080. });
  19081. // helper for adding shortcuts
  19082. function makeGetterAndSetter(name, key) {
  19083. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  19084. var utc = this._isUTC ? 'UTC' : '';
  19085. if (input != null) {
  19086. this._d['set' + utc + key](input);
  19087. moment.updateOffset(this);
  19088. return this;
  19089. } else {
  19090. return this._d['get' + utc + key]();
  19091. }
  19092. };
  19093. }
  19094. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  19095. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  19096. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  19097. }
  19098. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  19099. makeGetterAndSetter('year', 'FullYear');
  19100. // add plural methods
  19101. moment.fn.days = moment.fn.day;
  19102. moment.fn.months = moment.fn.month;
  19103. moment.fn.weeks = moment.fn.week;
  19104. moment.fn.isoWeeks = moment.fn.isoWeek;
  19105. // add aliased format methods
  19106. moment.fn.toJSON = moment.fn.toISOString;
  19107. /************************************
  19108. Duration Prototype
  19109. ************************************/
  19110. extend(moment.duration.fn = Duration.prototype, {
  19111. _bubble : function () {
  19112. var milliseconds = this._milliseconds,
  19113. days = this._days,
  19114. months = this._months,
  19115. data = this._data,
  19116. seconds, minutes, hours, years;
  19117. // The following code bubbles up values, see the tests for
  19118. // examples of what that means.
  19119. data.milliseconds = milliseconds % 1000;
  19120. seconds = absRound(milliseconds / 1000);
  19121. data.seconds = seconds % 60;
  19122. minutes = absRound(seconds / 60);
  19123. data.minutes = minutes % 60;
  19124. hours = absRound(minutes / 60);
  19125. data.hours = hours % 24;
  19126. days += absRound(hours / 24);
  19127. data.days = days % 30;
  19128. months += absRound(days / 30);
  19129. data.months = months % 12;
  19130. years = absRound(months / 12);
  19131. data.years = years;
  19132. },
  19133. weeks : function () {
  19134. return absRound(this.days() / 7);
  19135. },
  19136. valueOf : function () {
  19137. return this._milliseconds +
  19138. this._days * 864e5 +
  19139. (this._months % 12) * 2592e6 +
  19140. toInt(this._months / 12) * 31536e6;
  19141. },
  19142. humanize : function (withSuffix) {
  19143. var difference = +this,
  19144. output = relativeTime(difference, !withSuffix, this.lang());
  19145. if (withSuffix) {
  19146. output = this.lang().pastFuture(difference, output);
  19147. }
  19148. return this.lang().postformat(output);
  19149. },
  19150. add : function (input, val) {
  19151. // supports only 2.0-style add(1, 's') or add(moment)
  19152. var dur = moment.duration(input, val);
  19153. this._milliseconds += dur._milliseconds;
  19154. this._days += dur._days;
  19155. this._months += dur._months;
  19156. this._bubble();
  19157. return this;
  19158. },
  19159. subtract : function (input, val) {
  19160. var dur = moment.duration(input, val);
  19161. this._milliseconds -= dur._milliseconds;
  19162. this._days -= dur._days;
  19163. this._months -= dur._months;
  19164. this._bubble();
  19165. return this;
  19166. },
  19167. get : function (units) {
  19168. units = normalizeUnits(units);
  19169. return this[units.toLowerCase() + 's']();
  19170. },
  19171. as : function (units) {
  19172. units = normalizeUnits(units);
  19173. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  19174. },
  19175. lang : moment.fn.lang,
  19176. toIsoString : function () {
  19177. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  19178. var years = Math.abs(this.years()),
  19179. months = Math.abs(this.months()),
  19180. days = Math.abs(this.days()),
  19181. hours = Math.abs(this.hours()),
  19182. minutes = Math.abs(this.minutes()),
  19183. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  19184. if (!this.asSeconds()) {
  19185. // this is the same as C#'s (Noda) and python (isodate)...
  19186. // but not other JS (goog.date)
  19187. return 'P0D';
  19188. }
  19189. return (this.asSeconds() < 0 ? '-' : '') +
  19190. 'P' +
  19191. (years ? years + 'Y' : '') +
  19192. (months ? months + 'M' : '') +
  19193. (days ? days + 'D' : '') +
  19194. ((hours || minutes || seconds) ? 'T' : '') +
  19195. (hours ? hours + 'H' : '') +
  19196. (minutes ? minutes + 'M' : '') +
  19197. (seconds ? seconds + 'S' : '');
  19198. }
  19199. });
  19200. function makeDurationGetter(name) {
  19201. moment.duration.fn[name] = function () {
  19202. return this._data[name];
  19203. };
  19204. }
  19205. function makeDurationAsGetter(name, factor) {
  19206. moment.duration.fn['as' + name] = function () {
  19207. return +this / factor;
  19208. };
  19209. }
  19210. for (i in unitMillisecondFactors) {
  19211. if (unitMillisecondFactors.hasOwnProperty(i)) {
  19212. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  19213. makeDurationGetter(i.toLowerCase());
  19214. }
  19215. }
  19216. makeDurationAsGetter('Weeks', 6048e5);
  19217. moment.duration.fn.asMonths = function () {
  19218. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  19219. };
  19220. /************************************
  19221. Default Lang
  19222. ************************************/
  19223. // Set default language, other languages will inherit from English.
  19224. moment.lang('en', {
  19225. ordinal : function (number) {
  19226. var b = number % 10,
  19227. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  19228. (b === 1) ? 'st' :
  19229. (b === 2) ? 'nd' :
  19230. (b === 3) ? 'rd' : 'th';
  19231. return number + output;
  19232. }
  19233. });
  19234. /* EMBED_LANGUAGES */
  19235. /************************************
  19236. Exposing Moment
  19237. ************************************/
  19238. function makeGlobal(deprecate) {
  19239. var warned = false, local_moment = moment;
  19240. /*global ender:false */
  19241. if (typeof ender !== 'undefined') {
  19242. return;
  19243. }
  19244. // here, `this` means `window` in the browser, or `global` on the server
  19245. // add `moment` as a global object via a string identifier,
  19246. // for Closure Compiler "advanced" mode
  19247. if (deprecate) {
  19248. global.moment = function () {
  19249. if (!warned && console && console.warn) {
  19250. warned = true;
  19251. console.warn(
  19252. "Accessing Moment through the global scope is " +
  19253. "deprecated, and will be removed in an upcoming " +
  19254. "release.");
  19255. }
  19256. return local_moment.apply(null, arguments);
  19257. };
  19258. extend(global.moment, local_moment);
  19259. } else {
  19260. global['moment'] = moment;
  19261. }
  19262. }
  19263. // CommonJS module is defined
  19264. if (hasModule) {
  19265. module.exports = moment;
  19266. makeGlobal(true);
  19267. } else if (typeof define === "function" && define.amd) {
  19268. define("moment", function (require, exports, module) {
  19269. if (module.config && module.config() && module.config().noGlobal !== true) {
  19270. // If user provided noGlobal, he is aware of global
  19271. makeGlobal(module.config().noGlobal === undefined);
  19272. }
  19273. return moment;
  19274. });
  19275. } else {
  19276. makeGlobal();
  19277. }
  19278. }).call(this);
  19279. },{}],5:[function(require,module,exports){
  19280. /**
  19281. * Copyright 2012 Craig Campbell
  19282. *
  19283. * Licensed under the Apache License, Version 2.0 (the "License");
  19284. * you may not use this file except in compliance with the License.
  19285. * You may obtain a copy of the License at
  19286. *
  19287. * http://www.apache.org/licenses/LICENSE-2.0
  19288. *
  19289. * Unless required by applicable law or agreed to in writing, software
  19290. * distributed under the License is distributed on an "AS IS" BASIS,
  19291. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19292. * See the License for the specific language governing permissions and
  19293. * limitations under the License.
  19294. *
  19295. * Mousetrap is a simple keyboard shortcut library for Javascript with
  19296. * no external dependencies
  19297. *
  19298. * @version 1.1.2
  19299. * @url craig.is/killing/mice
  19300. */
  19301. /**
  19302. * mapping of special keycodes to their corresponding keys
  19303. *
  19304. * everything in this dictionary cannot use keypress events
  19305. * so it has to be here to map to the correct keycodes for
  19306. * keyup/keydown events
  19307. *
  19308. * @type {Object}
  19309. */
  19310. var _MAP = {
  19311. 8: 'backspace',
  19312. 9: 'tab',
  19313. 13: 'enter',
  19314. 16: 'shift',
  19315. 17: 'ctrl',
  19316. 18: 'alt',
  19317. 20: 'capslock',
  19318. 27: 'esc',
  19319. 32: 'space',
  19320. 33: 'pageup',
  19321. 34: 'pagedown',
  19322. 35: 'end',
  19323. 36: 'home',
  19324. 37: 'left',
  19325. 38: 'up',
  19326. 39: 'right',
  19327. 40: 'down',
  19328. 45: 'ins',
  19329. 46: 'del',
  19330. 91: 'meta',
  19331. 93: 'meta',
  19332. 224: 'meta'
  19333. },
  19334. /**
  19335. * mapping for special characters so they can support
  19336. *
  19337. * this dictionary is only used incase you want to bind a
  19338. * keyup or keydown event to one of these keys
  19339. *
  19340. * @type {Object}
  19341. */
  19342. _KEYCODE_MAP = {
  19343. 106: '*',
  19344. 107: '+',
  19345. 109: '-',
  19346. 110: '.',
  19347. 111 : '/',
  19348. 186: ';',
  19349. 187: '=',
  19350. 188: ',',
  19351. 189: '-',
  19352. 190: '.',
  19353. 191: '/',
  19354. 192: '`',
  19355. 219: '[',
  19356. 220: '\\',
  19357. 221: ']',
  19358. 222: '\''
  19359. },
  19360. /**
  19361. * this is a mapping of keys that require shift on a US keypad
  19362. * back to the non shift equivelents
  19363. *
  19364. * this is so you can use keyup events with these keys
  19365. *
  19366. * note that this will only work reliably on US keyboards
  19367. *
  19368. * @type {Object}
  19369. */
  19370. _SHIFT_MAP = {
  19371. '~': '`',
  19372. '!': '1',
  19373. '@': '2',
  19374. '#': '3',
  19375. '$': '4',
  19376. '%': '5',
  19377. '^': '6',
  19378. '&': '7',
  19379. '*': '8',
  19380. '(': '9',
  19381. ')': '0',
  19382. '_': '-',
  19383. '+': '=',
  19384. ':': ';',
  19385. '\"': '\'',
  19386. '<': ',',
  19387. '>': '.',
  19388. '?': '/',
  19389. '|': '\\'
  19390. },
  19391. /**
  19392. * this is a list of special strings you can use to map
  19393. * to modifier keys when you specify your keyboard shortcuts
  19394. *
  19395. * @type {Object}
  19396. */
  19397. _SPECIAL_ALIASES = {
  19398. 'option': 'alt',
  19399. 'command': 'meta',
  19400. 'return': 'enter',
  19401. 'escape': 'esc'
  19402. },
  19403. /**
  19404. * variable to store the flipped version of _MAP from above
  19405. * needed to check if we should use keypress or not when no action
  19406. * is specified
  19407. *
  19408. * @type {Object|undefined}
  19409. */
  19410. _REVERSE_MAP,
  19411. /**
  19412. * a list of all the callbacks setup via Mousetrap.bind()
  19413. *
  19414. * @type {Object}
  19415. */
  19416. _callbacks = {},
  19417. /**
  19418. * direct map of string combinations to callbacks used for trigger()
  19419. *
  19420. * @type {Object}
  19421. */
  19422. _direct_map = {},
  19423. /**
  19424. * keeps track of what level each sequence is at since multiple
  19425. * sequences can start out with the same sequence
  19426. *
  19427. * @type {Object}
  19428. */
  19429. _sequence_levels = {},
  19430. /**
  19431. * variable to store the setTimeout call
  19432. *
  19433. * @type {null|number}
  19434. */
  19435. _reset_timer,
  19436. /**
  19437. * temporary state where we will ignore the next keyup
  19438. *
  19439. * @type {boolean|string}
  19440. */
  19441. _ignore_next_keyup = false,
  19442. /**
  19443. * are we currently inside of a sequence?
  19444. * type of action ("keyup" or "keydown" or "keypress") or false
  19445. *
  19446. * @type {boolean|string}
  19447. */
  19448. _inside_sequence = false;
  19449. /**
  19450. * loop through the f keys, f1 to f19 and add them to the map
  19451. * programatically
  19452. */
  19453. for (var i = 1; i < 20; ++i) {
  19454. _MAP[111 + i] = 'f' + i;
  19455. }
  19456. /**
  19457. * loop through to map numbers on the numeric keypad
  19458. */
  19459. for (i = 0; i <= 9; ++i) {
  19460. _MAP[i + 96] = i;
  19461. }
  19462. /**
  19463. * cross browser add event method
  19464. *
  19465. * @param {Element|HTMLDocument} object
  19466. * @param {string} type
  19467. * @param {Function} callback
  19468. * @returns void
  19469. */
  19470. function _addEvent(object, type, callback) {
  19471. if (object.addEventListener) {
  19472. return object.addEventListener(type, callback, false);
  19473. }
  19474. object.attachEvent('on' + type, callback);
  19475. }
  19476. /**
  19477. * takes the event and returns the key character
  19478. *
  19479. * @param {Event} e
  19480. * @return {string}
  19481. */
  19482. function _characterFromEvent(e) {
  19483. // for keypress events we should return the character as is
  19484. if (e.type == 'keypress') {
  19485. return String.fromCharCode(e.which);
  19486. }
  19487. // for non keypress events the special maps are needed
  19488. if (_MAP[e.which]) {
  19489. return _MAP[e.which];
  19490. }
  19491. if (_KEYCODE_MAP[e.which]) {
  19492. return _KEYCODE_MAP[e.which];
  19493. }
  19494. // if it is not in the special map
  19495. return String.fromCharCode(e.which).toLowerCase();
  19496. }
  19497. /**
  19498. * should we stop this event before firing off callbacks
  19499. *
  19500. * @param {Event} e
  19501. * @return {boolean}
  19502. */
  19503. function _stop(e) {
  19504. var element = e.target || e.srcElement,
  19505. tag_name = element.tagName;
  19506. // if the element has the class "mousetrap" then no need to stop
  19507. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19508. return false;
  19509. }
  19510. // stop for input, select, and textarea
  19511. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19512. }
  19513. /**
  19514. * checks if two arrays are equal
  19515. *
  19516. * @param {Array} modifiers1
  19517. * @param {Array} modifiers2
  19518. * @returns {boolean}
  19519. */
  19520. function _modifiersMatch(modifiers1, modifiers2) {
  19521. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19522. }
  19523. /**
  19524. * resets all sequence counters except for the ones passed in
  19525. *
  19526. * @param {Object} do_not_reset
  19527. * @returns void
  19528. */
  19529. function _resetSequences(do_not_reset) {
  19530. do_not_reset = do_not_reset || {};
  19531. var active_sequences = false,
  19532. key;
  19533. for (key in _sequence_levels) {
  19534. if (do_not_reset[key]) {
  19535. active_sequences = true;
  19536. continue;
  19537. }
  19538. _sequence_levels[key] = 0;
  19539. }
  19540. if (!active_sequences) {
  19541. _inside_sequence = false;
  19542. }
  19543. }
  19544. /**
  19545. * finds all callbacks that match based on the keycode, modifiers,
  19546. * and action
  19547. *
  19548. * @param {string} character
  19549. * @param {Array} modifiers
  19550. * @param {string} action
  19551. * @param {boolean=} remove - should we remove any matches
  19552. * @param {string=} combination
  19553. * @returns {Array}
  19554. */
  19555. function _getMatches(character, modifiers, action, remove, combination) {
  19556. var i,
  19557. callback,
  19558. matches = [];
  19559. // if there are no events related to this keycode
  19560. if (!_callbacks[character]) {
  19561. return [];
  19562. }
  19563. // if a modifier key is coming up on its own we should allow it
  19564. if (action == 'keyup' && _isModifier(character)) {
  19565. modifiers = [character];
  19566. }
  19567. // loop through all callbacks for the key that was pressed
  19568. // and see if any of them match
  19569. for (i = 0; i < _callbacks[character].length; ++i) {
  19570. callback = _callbacks[character][i];
  19571. // if this is a sequence but it is not at the right level
  19572. // then move onto the next match
  19573. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19574. continue;
  19575. }
  19576. // if the action we are looking for doesn't match the action we got
  19577. // then we should keep going
  19578. if (action != callback.action) {
  19579. continue;
  19580. }
  19581. // if this is a keypress event that means that we need to only
  19582. // look at the character, otherwise check the modifiers as
  19583. // well
  19584. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19585. // remove is used so if you change your mind and call bind a
  19586. // second time with a new function the first one is overwritten
  19587. if (remove && callback.combo == combination) {
  19588. _callbacks[character].splice(i, 1);
  19589. }
  19590. matches.push(callback);
  19591. }
  19592. }
  19593. return matches;
  19594. }
  19595. /**
  19596. * takes a key event and figures out what the modifiers are
  19597. *
  19598. * @param {Event} e
  19599. * @returns {Array}
  19600. */
  19601. function _eventModifiers(e) {
  19602. var modifiers = [];
  19603. if (e.shiftKey) {
  19604. modifiers.push('shift');
  19605. }
  19606. if (e.altKey) {
  19607. modifiers.push('alt');
  19608. }
  19609. if (e.ctrlKey) {
  19610. modifiers.push('ctrl');
  19611. }
  19612. if (e.metaKey) {
  19613. modifiers.push('meta');
  19614. }
  19615. return modifiers;
  19616. }
  19617. /**
  19618. * actually calls the callback function
  19619. *
  19620. * if your callback function returns false this will use the jquery
  19621. * convention - prevent default and stop propogation on the event
  19622. *
  19623. * @param {Function} callback
  19624. * @param {Event} e
  19625. * @returns void
  19626. */
  19627. function _fireCallback(callback, e) {
  19628. if (callback(e) === false) {
  19629. if (e.preventDefault) {
  19630. e.preventDefault();
  19631. }
  19632. if (e.stopPropagation) {
  19633. e.stopPropagation();
  19634. }
  19635. e.returnValue = false;
  19636. e.cancelBubble = true;
  19637. }
  19638. }
  19639. /**
  19640. * handles a character key event
  19641. *
  19642. * @param {string} character
  19643. * @param {Event} e
  19644. * @returns void
  19645. */
  19646. function _handleCharacter(character, e) {
  19647. // if this event should not happen stop here
  19648. if (_stop(e)) {
  19649. return;
  19650. }
  19651. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19652. i,
  19653. do_not_reset = {},
  19654. processed_sequence_callback = false;
  19655. // loop through matching callbacks for this key event
  19656. for (i = 0; i < callbacks.length; ++i) {
  19657. // fire for all sequence callbacks
  19658. // this is because if for example you have multiple sequences
  19659. // bound such as "g i" and "g t" they both need to fire the
  19660. // callback for matching g cause otherwise you can only ever
  19661. // match the first one
  19662. if (callbacks[i].seq) {
  19663. processed_sequence_callback = true;
  19664. // keep a list of which sequences were matches for later
  19665. do_not_reset[callbacks[i].seq] = 1;
  19666. _fireCallback(callbacks[i].callback, e);
  19667. continue;
  19668. }
  19669. // if there were no sequence matches but we are still here
  19670. // that means this is a regular match so we should fire that
  19671. if (!processed_sequence_callback && !_inside_sequence) {
  19672. _fireCallback(callbacks[i].callback, e);
  19673. }
  19674. }
  19675. // if you are inside of a sequence and the key you are pressing
  19676. // is not a modifier key then we should reset all sequences
  19677. // that were not matched by this key event
  19678. if (e.type == _inside_sequence && !_isModifier(character)) {
  19679. _resetSequences(do_not_reset);
  19680. }
  19681. }
  19682. /**
  19683. * handles a keydown event
  19684. *
  19685. * @param {Event} e
  19686. * @returns void
  19687. */
  19688. function _handleKey(e) {
  19689. // normalize e.which for key events
  19690. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19691. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19692. var character = _characterFromEvent(e);
  19693. // no character found then stop
  19694. if (!character) {
  19695. return;
  19696. }
  19697. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19698. _ignore_next_keyup = false;
  19699. return;
  19700. }
  19701. _handleCharacter(character, e);
  19702. }
  19703. /**
  19704. * determines if the keycode specified is a modifier key or not
  19705. *
  19706. * @param {string} key
  19707. * @returns {boolean}
  19708. */
  19709. function _isModifier(key) {
  19710. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19711. }
  19712. /**
  19713. * called to set a 1 second timeout on the specified sequence
  19714. *
  19715. * this is so after each key press in the sequence you have 1 second
  19716. * to press the next key before you have to start over
  19717. *
  19718. * @returns void
  19719. */
  19720. function _resetSequenceTimer() {
  19721. clearTimeout(_reset_timer);
  19722. _reset_timer = setTimeout(_resetSequences, 1000);
  19723. }
  19724. /**
  19725. * reverses the map lookup so that we can look for specific keys
  19726. * to see what can and can't use keypress
  19727. *
  19728. * @return {Object}
  19729. */
  19730. function _getReverseMap() {
  19731. if (!_REVERSE_MAP) {
  19732. _REVERSE_MAP = {};
  19733. for (var key in _MAP) {
  19734. // pull out the numeric keypad from here cause keypress should
  19735. // be able to detect the keys from the character
  19736. if (key > 95 && key < 112) {
  19737. continue;
  19738. }
  19739. if (_MAP.hasOwnProperty(key)) {
  19740. _REVERSE_MAP[_MAP[key]] = key;
  19741. }
  19742. }
  19743. }
  19744. return _REVERSE_MAP;
  19745. }
  19746. /**
  19747. * picks the best action based on the key combination
  19748. *
  19749. * @param {string} key - character for key
  19750. * @param {Array} modifiers
  19751. * @param {string=} action passed in
  19752. */
  19753. function _pickBestAction(key, modifiers, action) {
  19754. // if no action was picked in we should try to pick the one
  19755. // that we think would work best for this key
  19756. if (!action) {
  19757. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19758. }
  19759. // modifier keys don't work as expected with keypress,
  19760. // switch to keydown
  19761. if (action == 'keypress' && modifiers.length) {
  19762. action = 'keydown';
  19763. }
  19764. return action;
  19765. }
  19766. /**
  19767. * binds a key sequence to an event
  19768. *
  19769. * @param {string} combo - combo specified in bind call
  19770. * @param {Array} keys
  19771. * @param {Function} callback
  19772. * @param {string=} action
  19773. * @returns void
  19774. */
  19775. function _bindSequence(combo, keys, callback, action) {
  19776. // start off by adding a sequence level record for this combination
  19777. // and setting the level to 0
  19778. _sequence_levels[combo] = 0;
  19779. // if there is no action pick the best one for the first key
  19780. // in the sequence
  19781. if (!action) {
  19782. action = _pickBestAction(keys[0], []);
  19783. }
  19784. /**
  19785. * callback to increase the sequence level for this sequence and reset
  19786. * all other sequences that were active
  19787. *
  19788. * @param {Event} e
  19789. * @returns void
  19790. */
  19791. var _increaseSequence = function(e) {
  19792. _inside_sequence = action;
  19793. ++_sequence_levels[combo];
  19794. _resetSequenceTimer();
  19795. },
  19796. /**
  19797. * wraps the specified callback inside of another function in order
  19798. * to reset all sequence counters as soon as this sequence is done
  19799. *
  19800. * @param {Event} e
  19801. * @returns void
  19802. */
  19803. _callbackAndReset = function(e) {
  19804. _fireCallback(callback, e);
  19805. // we should ignore the next key up if the action is key down
  19806. // or keypress. this is so if you finish a sequence and
  19807. // release the key the final key will not trigger a keyup
  19808. if (action !== 'keyup') {
  19809. _ignore_next_keyup = _characterFromEvent(e);
  19810. }
  19811. // weird race condition if a sequence ends with the key
  19812. // another sequence begins with
  19813. setTimeout(_resetSequences, 10);
  19814. },
  19815. i;
  19816. // loop through keys one at a time and bind the appropriate callback
  19817. // function. for any key leading up to the final one it should
  19818. // increase the sequence. after the final, it should reset all sequences
  19819. for (i = 0; i < keys.length; ++i) {
  19820. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19821. }
  19822. }
  19823. /**
  19824. * binds a single keyboard combination
  19825. *
  19826. * @param {string} combination
  19827. * @param {Function} callback
  19828. * @param {string=} action
  19829. * @param {string=} sequence_name - name of sequence if part of sequence
  19830. * @param {number=} level - what part of the sequence the command is
  19831. * @returns void
  19832. */
  19833. function _bindSingle(combination, callback, action, sequence_name, level) {
  19834. // make sure multiple spaces in a row become a single space
  19835. combination = combination.replace(/\s+/g, ' ');
  19836. var sequence = combination.split(' '),
  19837. i,
  19838. key,
  19839. keys,
  19840. modifiers = [];
  19841. // if this pattern is a sequence of keys then run through this method
  19842. // to reprocess each pattern one key at a time
  19843. if (sequence.length > 1) {
  19844. return _bindSequence(combination, sequence, callback, action);
  19845. }
  19846. // take the keys from this pattern and figure out what the actual
  19847. // pattern is all about
  19848. keys = combination === '+' ? ['+'] : combination.split('+');
  19849. for (i = 0; i < keys.length; ++i) {
  19850. key = keys[i];
  19851. // normalize key names
  19852. if (_SPECIAL_ALIASES[key]) {
  19853. key = _SPECIAL_ALIASES[key];
  19854. }
  19855. // if this is not a keypress event then we should
  19856. // be smart about using shift keys
  19857. // this will only work for US keyboards however
  19858. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19859. key = _SHIFT_MAP[key];
  19860. modifiers.push('shift');
  19861. }
  19862. // if this key is a modifier then add it to the list of modifiers
  19863. if (_isModifier(key)) {
  19864. modifiers.push(key);
  19865. }
  19866. }
  19867. // depending on what the key combination is
  19868. // we will try to pick the best event for it
  19869. action = _pickBestAction(key, modifiers, action);
  19870. // make sure to initialize array if this is the first time
  19871. // a callback is added for this key
  19872. if (!_callbacks[key]) {
  19873. _callbacks[key] = [];
  19874. }
  19875. // remove an existing match if there is one
  19876. _getMatches(key, modifiers, action, !sequence_name, combination);
  19877. // add this call back to the array
  19878. // if it is a sequence put it at the beginning
  19879. // if not put it at the end
  19880. //
  19881. // this is important because the way these are processed expects
  19882. // the sequence ones to come first
  19883. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19884. callback: callback,
  19885. modifiers: modifiers,
  19886. action: action,
  19887. seq: sequence_name,
  19888. level: level,
  19889. combo: combination
  19890. });
  19891. }
  19892. /**
  19893. * binds multiple combinations to the same callback
  19894. *
  19895. * @param {Array} combinations
  19896. * @param {Function} callback
  19897. * @param {string|undefined} action
  19898. * @returns void
  19899. */
  19900. function _bindMultiple(combinations, callback, action) {
  19901. for (var i = 0; i < combinations.length; ++i) {
  19902. _bindSingle(combinations[i], callback, action);
  19903. }
  19904. }
  19905. // start!
  19906. _addEvent(document, 'keypress', _handleKey);
  19907. _addEvent(document, 'keydown', _handleKey);
  19908. _addEvent(document, 'keyup', _handleKey);
  19909. var mousetrap = {
  19910. /**
  19911. * binds an event to mousetrap
  19912. *
  19913. * can be a single key, a combination of keys separated with +,
  19914. * a comma separated list of keys, an array of keys, or
  19915. * a sequence of keys separated by spaces
  19916. *
  19917. * be sure to list the modifier keys first to make sure that the
  19918. * correct key ends up getting bound (the last key in the pattern)
  19919. *
  19920. * @param {string|Array} keys
  19921. * @param {Function} callback
  19922. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19923. * @returns void
  19924. */
  19925. bind: function(keys, callback, action) {
  19926. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19927. _direct_map[keys + ':' + action] = callback;
  19928. return this;
  19929. },
  19930. /**
  19931. * unbinds an event to mousetrap
  19932. *
  19933. * the unbinding sets the callback function of the specified key combo
  19934. * to an empty function and deletes the corresponding key in the
  19935. * _direct_map dict.
  19936. *
  19937. * the keycombo+action has to be exactly the same as
  19938. * it was defined in the bind method
  19939. *
  19940. * TODO: actually remove this from the _callbacks dictionary instead
  19941. * of binding an empty function
  19942. *
  19943. * @param {string|Array} keys
  19944. * @param {string} action
  19945. * @returns void
  19946. */
  19947. unbind: function(keys, action) {
  19948. if (_direct_map[keys + ':' + action]) {
  19949. delete _direct_map[keys + ':' + action];
  19950. this.bind(keys, function() {}, action);
  19951. }
  19952. return this;
  19953. },
  19954. /**
  19955. * triggers an event that has already been bound
  19956. *
  19957. * @param {string} keys
  19958. * @param {string=} action
  19959. * @returns void
  19960. */
  19961. trigger: function(keys, action) {
  19962. _direct_map[keys + ':' + action]();
  19963. return this;
  19964. },
  19965. /**
  19966. * resets the library back to its initial state. this is useful
  19967. * if you want to clear out the current keyboard shortcuts and bind
  19968. * new ones - for example if you switch to another page
  19969. *
  19970. * @returns void
  19971. */
  19972. reset: function() {
  19973. _callbacks = {};
  19974. _direct_map = {};
  19975. return this;
  19976. }
  19977. };
  19978. module.exports = mousetrap;
  19979. },{}]},{},[1])
  19980. (1)
  19981. });