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.

22501 lines
661 KiB

  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.7.2-SNAPSHOT
  8. * @date 2014-04-01
  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. * Convert an object into an array: all objects properties are put into the
  671. * array. The resulting array is unordered.
  672. * @param {Object} object
  673. * @param {Array} array
  674. */
  675. util.toArray = function toArray(object) {
  676. var array = [];
  677. for (var prop in object) {
  678. if (object.hasOwnProperty(prop)) array.push(object[prop]);
  679. }
  680. return array;
  681. }
  682. /**
  683. * Update a property in an object
  684. * @param {Object} object
  685. * @param {String} key
  686. * @param {*} value
  687. * @return {Boolean} changed
  688. */
  689. util.updateProperty = function updateProp (object, key, value) {
  690. if (object[key] !== value) {
  691. object[key] = value;
  692. return true;
  693. }
  694. else {
  695. return false;
  696. }
  697. };
  698. /**
  699. * Add and event listener. Works for all browsers
  700. * @param {Element} element An html element
  701. * @param {string} action The action, for example "click",
  702. * without the prefix "on"
  703. * @param {function} listener The callback function to be executed
  704. * @param {boolean} [useCapture]
  705. */
  706. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  707. if (element.addEventListener) {
  708. if (useCapture === undefined)
  709. useCapture = false;
  710. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  711. action = "DOMMouseScroll"; // For Firefox
  712. }
  713. element.addEventListener(action, listener, useCapture);
  714. } else {
  715. element.attachEvent("on" + action, listener); // IE browsers
  716. }
  717. };
  718. /**
  719. * Remove an event listener from an element
  720. * @param {Element} element An html dom element
  721. * @param {string} action The name of the event, for example "mousedown"
  722. * @param {function} listener The listener function
  723. * @param {boolean} [useCapture]
  724. */
  725. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  726. if (element.removeEventListener) {
  727. // non-IE browsers
  728. if (useCapture === undefined)
  729. useCapture = false;
  730. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  731. action = "DOMMouseScroll"; // For Firefox
  732. }
  733. element.removeEventListener(action, listener, useCapture);
  734. } else {
  735. // IE browsers
  736. element.detachEvent("on" + action, listener);
  737. }
  738. };
  739. /**
  740. * Get HTML element which is the target of the event
  741. * @param {Event} event
  742. * @return {Element} target element
  743. */
  744. util.getTarget = function getTarget(event) {
  745. // code from http://www.quirksmode.org/js/events_properties.html
  746. if (!event) {
  747. event = window.event;
  748. }
  749. var target;
  750. if (event.target) {
  751. target = event.target;
  752. }
  753. else if (event.srcElement) {
  754. target = event.srcElement;
  755. }
  756. if (target.nodeType != undefined && target.nodeType == 3) {
  757. // defeat Safari bug
  758. target = target.parentNode;
  759. }
  760. return target;
  761. };
  762. /**
  763. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  764. * @param {Element} element
  765. * @param {Event} event
  766. */
  767. util.fakeGesture = function fakeGesture (element, event) {
  768. var eventType = null;
  769. // for hammer.js 1.0.5
  770. var gesture = Hammer.event.collectEventData(this, eventType, event);
  771. // for hammer.js 1.0.6
  772. //var touches = Hammer.event.getTouchList(event, eventType);
  773. // var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  774. // on IE in standards mode, no touches are recognized by hammer.js,
  775. // resulting in NaN values for center.pageX and center.pageY
  776. if (isNaN(gesture.center.pageX)) {
  777. gesture.center.pageX = event.pageX;
  778. }
  779. if (isNaN(gesture.center.pageY)) {
  780. gesture.center.pageY = event.pageY;
  781. }
  782. return gesture;
  783. };
  784. util.option = {};
  785. /**
  786. * Convert a value into a boolean
  787. * @param {Boolean | function | undefined} value
  788. * @param {Boolean} [defaultValue]
  789. * @returns {Boolean} bool
  790. */
  791. util.option.asBoolean = function (value, defaultValue) {
  792. if (typeof value == 'function') {
  793. value = value();
  794. }
  795. if (value != null) {
  796. return (value != false);
  797. }
  798. return defaultValue || null;
  799. };
  800. /**
  801. * Convert a value into a number
  802. * @param {Boolean | function | undefined} value
  803. * @param {Number} [defaultValue]
  804. * @returns {Number} number
  805. */
  806. util.option.asNumber = function (value, defaultValue) {
  807. if (typeof value == 'function') {
  808. value = value();
  809. }
  810. if (value != null) {
  811. return Number(value) || defaultValue || null;
  812. }
  813. return defaultValue || null;
  814. };
  815. /**
  816. * Convert a value into a string
  817. * @param {String | function | undefined} value
  818. * @param {String} [defaultValue]
  819. * @returns {String} str
  820. */
  821. util.option.asString = function (value, defaultValue) {
  822. if (typeof value == 'function') {
  823. value = value();
  824. }
  825. if (value != null) {
  826. return String(value);
  827. }
  828. return defaultValue || null;
  829. };
  830. /**
  831. * Convert a size or location into a string with pixels or a percentage
  832. * @param {String | Number | function | undefined} value
  833. * @param {String} [defaultValue]
  834. * @returns {String} size
  835. */
  836. util.option.asSize = function (value, defaultValue) {
  837. if (typeof value == 'function') {
  838. value = value();
  839. }
  840. if (util.isString(value)) {
  841. return value;
  842. }
  843. else if (util.isNumber(value)) {
  844. return value + 'px';
  845. }
  846. else {
  847. return defaultValue || null;
  848. }
  849. };
  850. /**
  851. * Convert a value into a DOM element
  852. * @param {HTMLElement | function | undefined} value
  853. * @param {HTMLElement} [defaultValue]
  854. * @returns {HTMLElement | null} dom
  855. */
  856. util.option.asElement = function (value, defaultValue) {
  857. if (typeof value == 'function') {
  858. value = value();
  859. }
  860. return value || defaultValue || null;
  861. };
  862. util.GiveDec = function GiveDec(Hex)
  863. {
  864. if(Hex == "A")
  865. Value = 10;
  866. else
  867. if(Hex == "B")
  868. Value = 11;
  869. else
  870. if(Hex == "C")
  871. Value = 12;
  872. else
  873. if(Hex == "D")
  874. Value = 13;
  875. else
  876. if(Hex == "E")
  877. Value = 14;
  878. else
  879. if(Hex == "F")
  880. Value = 15;
  881. else
  882. Value = eval(Hex)
  883. return Value;
  884. }
  885. util.GiveHex = function GiveHex(Dec)
  886. {
  887. if(Dec == 10)
  888. Value = "A";
  889. else
  890. if(Dec == 11)
  891. Value = "B";
  892. else
  893. if(Dec == 12)
  894. Value = "C";
  895. else
  896. if(Dec == 13)
  897. Value = "D";
  898. else
  899. if(Dec == 14)
  900. Value = "E";
  901. else
  902. if(Dec == 15)
  903. Value = "F";
  904. else
  905. Value = "" + Dec;
  906. return Value;
  907. }
  908. /**
  909. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  910. *
  911. * @param {String} hex
  912. * @returns {{r: *, g: *, b: *}}
  913. */
  914. util.hexToRGB = function hexToRGB(hex) {
  915. hex = hex.replace("#","").toUpperCase();
  916. var a = util.GiveDec(hex.substring(0, 1));
  917. var b = util.GiveDec(hex.substring(1, 2));
  918. var c = util.GiveDec(hex.substring(2, 3));
  919. var d = util.GiveDec(hex.substring(3, 4));
  920. var e = util.GiveDec(hex.substring(4, 5));
  921. var f = util.GiveDec(hex.substring(5, 6));
  922. var r = (a * 16) + b;
  923. var g = (c * 16) + d;
  924. var b = (e * 16) + f;
  925. return {r:r,g:g,b:b};
  926. };
  927. util.RGBToHex = function RGBToHex(red,green,blue) {
  928. var a = util.GiveHex(Math.floor(red / 16));
  929. var b = util.GiveHex(red % 16);
  930. var c = util.GiveHex(Math.floor(green / 16));
  931. var d = util.GiveHex(green % 16);
  932. var e = util.GiveHex(Math.floor(blue / 16));
  933. var f = util.GiveHex(blue % 16);
  934. var hex = a + b + c + d + e + f;
  935. return "#" + hex;
  936. };
  937. /**
  938. * http://www.javascripter.net/faq/rgb2hsv.htm
  939. *
  940. * @param red
  941. * @param green
  942. * @param blue
  943. * @returns {*}
  944. * @constructor
  945. */
  946. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  947. red=red/255; green=green/255; blue=blue/255;
  948. var minRGB = Math.min(red,Math.min(green,blue));
  949. var maxRGB = Math.max(red,Math.max(green,blue));
  950. // Black-gray-white
  951. if (minRGB == maxRGB) {
  952. return {h:0,s:0,v:minRGB};
  953. }
  954. // Colors other than black-gray-white:
  955. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  956. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  957. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  958. var saturation = (maxRGB - minRGB)/maxRGB;
  959. var value = maxRGB;
  960. return {h:hue,s:saturation,v:value};
  961. };
  962. /**
  963. * https://gist.github.com/mjijackson/5311256
  964. * @param hue
  965. * @param saturation
  966. * @param value
  967. * @returns {{r: number, g: number, b: number}}
  968. * @constructor
  969. */
  970. util.HSVToRGB = function HSVToRGB(h, s, v) {
  971. var r, g, b;
  972. var i = Math.floor(h * 6);
  973. var f = h * 6 - i;
  974. var p = v * (1 - s);
  975. var q = v * (1 - f * s);
  976. var t = v * (1 - (1 - f) * s);
  977. switch (i % 6) {
  978. case 0: r = v, g = t, b = p; break;
  979. case 1: r = q, g = v, b = p; break;
  980. case 2: r = p, g = v, b = t; break;
  981. case 3: r = p, g = q, b = v; break;
  982. case 4: r = t, g = p, b = v; break;
  983. case 5: r = v, g = p, b = q; break;
  984. }
  985. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  986. };
  987. util.HSVToHex = function HSVToHex(h,s,v) {
  988. var rgb = util.HSVToRGB(h,s,v);
  989. return util.RGBToHex(rgb.r,rgb.g,rgb.b);
  990. }
  991. util.hexToHSV = function hexToHSV(hex) {
  992. var rgb = util.hexToRGB(hex);
  993. return util.RGBToHSV(rgb.r,rgb.g,rgb.b);
  994. }
  995. util.isValidHex = function isValidHex(hex) {
  996. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  997. return isOk;
  998. }
  999. util.copyObject = function copyObject(objectFrom,objectTo) {
  1000. for (var i in objectFrom) {
  1001. if (objectFrom.hasOwnProperty(i)) {
  1002. if (typeof objectFrom[i] == "object") {
  1003. objectTo[i] = {};
  1004. util.copyObject(objectFrom[i],objectTo[i]);
  1005. }
  1006. else {
  1007. objectTo[i] = objectFrom[i];
  1008. }
  1009. }
  1010. }
  1011. }
  1012. /**
  1013. * DataSet
  1014. *
  1015. * Usage:
  1016. * var dataSet = new DataSet({
  1017. * fieldId: '_id',
  1018. * convert: {
  1019. * // ...
  1020. * }
  1021. * });
  1022. *
  1023. * dataSet.add(item);
  1024. * dataSet.add(data);
  1025. * dataSet.update(item);
  1026. * dataSet.update(data);
  1027. * dataSet.remove(id);
  1028. * dataSet.remove(ids);
  1029. * var data = dataSet.get();
  1030. * var data = dataSet.get(id);
  1031. * var data = dataSet.get(ids);
  1032. * var data = dataSet.get(ids, options, data);
  1033. * dataSet.clear();
  1034. *
  1035. * A data set can:
  1036. * - add/remove/update data
  1037. * - gives triggers upon changes in the data
  1038. * - can import/export data in various data formats
  1039. *
  1040. * @param {Object} [options] Available options:
  1041. * {String} fieldId Field name of the id in the
  1042. * items, 'id' by default.
  1043. * {Object.<String, String} convert
  1044. * A map with field names as key,
  1045. * and the field type as value.
  1046. * @constructor DataSet
  1047. */
  1048. // TODO: add a DataSet constructor DataSet(data, options)
  1049. function DataSet (options) {
  1050. this.id = util.randomUUID();
  1051. this.options = options || {};
  1052. this.data = {}; // map with data indexed by id
  1053. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1054. this.convert = {}; // field types by field name
  1055. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1056. if (this.options.convert) {
  1057. for (var field in this.options.convert) {
  1058. if (this.options.convert.hasOwnProperty(field)) {
  1059. var value = this.options.convert[field];
  1060. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1061. this.convert[field] = 'Date';
  1062. }
  1063. else {
  1064. this.convert[field] = value;
  1065. }
  1066. }
  1067. }
  1068. }
  1069. // event subscribers
  1070. this.subscribers = {};
  1071. this.internalIds = {}; // internally generated id's
  1072. }
  1073. /**
  1074. * Subscribe to an event, add an event listener
  1075. * @param {String} event Event name. Available events: 'put', 'update',
  1076. * 'remove'
  1077. * @param {function} callback Callback method. Called with three parameters:
  1078. * {String} event
  1079. * {Object | null} params
  1080. * {String | Number} senderId
  1081. */
  1082. DataSet.prototype.on = function on (event, callback) {
  1083. var subscribers = this.subscribers[event];
  1084. if (!subscribers) {
  1085. subscribers = [];
  1086. this.subscribers[event] = subscribers;
  1087. }
  1088. subscribers.push({
  1089. callback: callback
  1090. });
  1091. };
  1092. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1093. DataSet.prototype.subscribe = DataSet.prototype.on;
  1094. /**
  1095. * Unsubscribe from an event, remove an event listener
  1096. * @param {String} event
  1097. * @param {function} callback
  1098. */
  1099. DataSet.prototype.off = function off(event, callback) {
  1100. var subscribers = this.subscribers[event];
  1101. if (subscribers) {
  1102. this.subscribers[event] = subscribers.filter(function (listener) {
  1103. return (listener.callback != callback);
  1104. });
  1105. }
  1106. };
  1107. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1108. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1109. /**
  1110. * Trigger an event
  1111. * @param {String} event
  1112. * @param {Object | null} params
  1113. * @param {String} [senderId] Optional id of the sender.
  1114. * @private
  1115. */
  1116. DataSet.prototype._trigger = function (event, params, senderId) {
  1117. if (event == '*') {
  1118. throw new Error('Cannot trigger event *');
  1119. }
  1120. var subscribers = [];
  1121. if (event in this.subscribers) {
  1122. subscribers = subscribers.concat(this.subscribers[event]);
  1123. }
  1124. if ('*' in this.subscribers) {
  1125. subscribers = subscribers.concat(this.subscribers['*']);
  1126. }
  1127. for (var i = 0; i < subscribers.length; i++) {
  1128. var subscriber = subscribers[i];
  1129. if (subscriber.callback) {
  1130. subscriber.callback(event, params, senderId || null);
  1131. }
  1132. }
  1133. };
  1134. /**
  1135. * Add data.
  1136. * Adding an item will fail when there already is an item with the same id.
  1137. * @param {Object | Array | DataTable} data
  1138. * @param {String} [senderId] Optional sender id
  1139. * @return {Array} addedIds Array with the ids of the added items
  1140. */
  1141. DataSet.prototype.add = function (data, senderId) {
  1142. var addedIds = [],
  1143. id,
  1144. me = this;
  1145. if (data instanceof Array) {
  1146. // Array
  1147. for (var i = 0, len = data.length; i < len; i++) {
  1148. id = me._addItem(data[i]);
  1149. addedIds.push(id);
  1150. }
  1151. }
  1152. else if (util.isDataTable(data)) {
  1153. // Google DataTable
  1154. var columns = this._getColumnNames(data);
  1155. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1156. var item = {};
  1157. for (var col = 0, cols = columns.length; col < cols; col++) {
  1158. var field = columns[col];
  1159. item[field] = data.getValue(row, col);
  1160. }
  1161. id = me._addItem(item);
  1162. addedIds.push(id);
  1163. }
  1164. }
  1165. else if (data instanceof Object) {
  1166. // Single item
  1167. id = me._addItem(data);
  1168. addedIds.push(id);
  1169. }
  1170. else {
  1171. throw new Error('Unknown dataType');
  1172. }
  1173. if (addedIds.length) {
  1174. this._trigger('add', {items: addedIds}, senderId);
  1175. }
  1176. return addedIds;
  1177. };
  1178. /**
  1179. * Update existing items. When an item does not exist, it will be created
  1180. * @param {Object | Array | DataTable} data
  1181. * @param {String} [senderId] Optional sender id
  1182. * @return {Array} updatedIds The ids of the added or updated items
  1183. */
  1184. DataSet.prototype.update = function (data, senderId) {
  1185. var addedIds = [],
  1186. updatedIds = [],
  1187. me = this,
  1188. fieldId = me.fieldId;
  1189. var addOrUpdate = function (item) {
  1190. var id = item[fieldId];
  1191. if (me.data[id]) {
  1192. // update item
  1193. id = me._updateItem(item);
  1194. updatedIds.push(id);
  1195. }
  1196. else {
  1197. // add new item
  1198. id = me._addItem(item);
  1199. addedIds.push(id);
  1200. }
  1201. };
  1202. if (data instanceof Array) {
  1203. // Array
  1204. for (var i = 0, len = data.length; i < len; i++) {
  1205. addOrUpdate(data[i]);
  1206. }
  1207. }
  1208. else if (util.isDataTable(data)) {
  1209. // Google DataTable
  1210. var columns = this._getColumnNames(data);
  1211. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1212. var item = {};
  1213. for (var col = 0, cols = columns.length; col < cols; col++) {
  1214. var field = columns[col];
  1215. item[field] = data.getValue(row, col);
  1216. }
  1217. addOrUpdate(item);
  1218. }
  1219. }
  1220. else if (data instanceof Object) {
  1221. // Single item
  1222. addOrUpdate(data);
  1223. }
  1224. else {
  1225. throw new Error('Unknown dataType');
  1226. }
  1227. if (addedIds.length) {
  1228. this._trigger('add', {items: addedIds}, senderId);
  1229. }
  1230. if (updatedIds.length) {
  1231. this._trigger('update', {items: updatedIds}, senderId);
  1232. }
  1233. return addedIds.concat(updatedIds);
  1234. };
  1235. /**
  1236. * Get a data item or multiple items.
  1237. *
  1238. * Usage:
  1239. *
  1240. * get()
  1241. * get(options: Object)
  1242. * get(options: Object, data: Array | DataTable)
  1243. *
  1244. * get(id: Number | String)
  1245. * get(id: Number | String, options: Object)
  1246. * get(id: Number | String, options: Object, data: Array | DataTable)
  1247. *
  1248. * get(ids: Number[] | String[])
  1249. * get(ids: Number[] | String[], options: Object)
  1250. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1251. *
  1252. * Where:
  1253. *
  1254. * {Number | String} id The id of an item
  1255. * {Number[] | String{}} ids An array with ids of items
  1256. * {Object} options An Object with options. Available options:
  1257. * {String} [type] Type of data to be returned. Can
  1258. * be 'DataTable' or 'Array' (default)
  1259. * {Object.<String, String>} [convert]
  1260. * {String[]} [fields] field names to be returned
  1261. * {function} [filter] filter items
  1262. * {String | function} [order] Order the items by
  1263. * a field name or custom sort function.
  1264. * {Array | DataTable} [data] If provided, items will be appended to this
  1265. * array or table. Required in case of Google
  1266. * DataTable.
  1267. *
  1268. * @throws Error
  1269. */
  1270. DataSet.prototype.get = function (args) {
  1271. var me = this;
  1272. var globalShowInternalIds = this.showInternalIds;
  1273. // parse the arguments
  1274. var id, ids, options, data;
  1275. var firstType = util.getType(arguments[0]);
  1276. if (firstType == 'String' || firstType == 'Number') {
  1277. // get(id [, options] [, data])
  1278. id = arguments[0];
  1279. options = arguments[1];
  1280. data = arguments[2];
  1281. }
  1282. else if (firstType == 'Array') {
  1283. // get(ids [, options] [, data])
  1284. ids = arguments[0];
  1285. options = arguments[1];
  1286. data = arguments[2];
  1287. }
  1288. else {
  1289. // get([, options] [, data])
  1290. options = arguments[0];
  1291. data = arguments[1];
  1292. }
  1293. // determine the return type
  1294. var type;
  1295. if (options && options.type) {
  1296. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1297. if (data && (type != util.getType(data))) {
  1298. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1299. 'does not correspond with specified options.type (' + options.type + ')');
  1300. }
  1301. if (type == 'DataTable' && !util.isDataTable(data)) {
  1302. throw new Error('Parameter "data" must be a DataTable ' +
  1303. 'when options.type is "DataTable"');
  1304. }
  1305. }
  1306. else if (data) {
  1307. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1308. }
  1309. else {
  1310. type = 'Array';
  1311. }
  1312. // we allow the setting of this value for a single get request.
  1313. if (options != undefined) {
  1314. if (options.showInternalIds != undefined) {
  1315. this.showInternalIds = options.showInternalIds;
  1316. }
  1317. }
  1318. // build options
  1319. var convert = options && options.convert || this.options.convert;
  1320. var filter = options && options.filter;
  1321. var items = [], item, itemId, i, len;
  1322. // convert items
  1323. if (id != undefined) {
  1324. // return a single item
  1325. item = me._getItem(id, convert);
  1326. if (filter && !filter(item)) {
  1327. item = null;
  1328. }
  1329. }
  1330. else if (ids != undefined) {
  1331. // return a subset of items
  1332. for (i = 0, len = ids.length; i < len; i++) {
  1333. item = me._getItem(ids[i], convert);
  1334. if (!filter || filter(item)) {
  1335. items.push(item);
  1336. }
  1337. }
  1338. }
  1339. else {
  1340. // return all items
  1341. for (itemId in this.data) {
  1342. if (this.data.hasOwnProperty(itemId)) {
  1343. item = me._getItem(itemId, convert);
  1344. if (!filter || filter(item)) {
  1345. items.push(item);
  1346. }
  1347. }
  1348. }
  1349. }
  1350. // restore the global value of showInternalIds
  1351. this.showInternalIds = globalShowInternalIds;
  1352. // order the results
  1353. if (options && options.order && id == undefined) {
  1354. this._sort(items, options.order);
  1355. }
  1356. // filter fields of the items
  1357. if (options && options.fields) {
  1358. var fields = options.fields;
  1359. if (id != undefined) {
  1360. item = this._filterFields(item, fields);
  1361. }
  1362. else {
  1363. for (i = 0, len = items.length; i < len; i++) {
  1364. items[i] = this._filterFields(items[i], fields);
  1365. }
  1366. }
  1367. }
  1368. // return the results
  1369. if (type == 'DataTable') {
  1370. var columns = this._getColumnNames(data);
  1371. if (id != undefined) {
  1372. // append a single item to the data table
  1373. me._appendRow(data, columns, item);
  1374. }
  1375. else {
  1376. // copy the items to the provided data table
  1377. for (i = 0, len = items.length; i < len; i++) {
  1378. me._appendRow(data, columns, items[i]);
  1379. }
  1380. }
  1381. return data;
  1382. }
  1383. else {
  1384. // return an array
  1385. if (id != undefined) {
  1386. // a single item
  1387. return item;
  1388. }
  1389. else {
  1390. // multiple items
  1391. if (data) {
  1392. // copy the items to the provided array
  1393. for (i = 0, len = items.length; i < len; i++) {
  1394. data.push(items[i]);
  1395. }
  1396. return data;
  1397. }
  1398. else {
  1399. // just return our array
  1400. return items;
  1401. }
  1402. }
  1403. }
  1404. };
  1405. /**
  1406. * Get ids of all items or from a filtered set of items.
  1407. * @param {Object} [options] An Object with options. Available options:
  1408. * {function} [filter] filter items
  1409. * {String | function} [order] Order the items by
  1410. * a field name or custom sort function.
  1411. * @return {Array} ids
  1412. */
  1413. DataSet.prototype.getIds = function (options) {
  1414. var data = this.data,
  1415. filter = options && options.filter,
  1416. order = options && options.order,
  1417. convert = options && options.convert || this.options.convert,
  1418. i,
  1419. len,
  1420. id,
  1421. item,
  1422. items,
  1423. ids = [];
  1424. if (filter) {
  1425. // get filtered items
  1426. if (order) {
  1427. // create ordered list
  1428. items = [];
  1429. for (id in data) {
  1430. if (data.hasOwnProperty(id)) {
  1431. item = this._getItem(id, convert);
  1432. if (filter(item)) {
  1433. items.push(item);
  1434. }
  1435. }
  1436. }
  1437. this._sort(items, order);
  1438. for (i = 0, len = items.length; i < len; i++) {
  1439. ids[i] = items[i][this.fieldId];
  1440. }
  1441. }
  1442. else {
  1443. // create unordered list
  1444. for (id in data) {
  1445. if (data.hasOwnProperty(id)) {
  1446. item = this._getItem(id, convert);
  1447. if (filter(item)) {
  1448. ids.push(item[this.fieldId]);
  1449. }
  1450. }
  1451. }
  1452. }
  1453. }
  1454. else {
  1455. // get all items
  1456. if (order) {
  1457. // create an ordered list
  1458. items = [];
  1459. for (id in data) {
  1460. if (data.hasOwnProperty(id)) {
  1461. items.push(data[id]);
  1462. }
  1463. }
  1464. this._sort(items, order);
  1465. for (i = 0, len = items.length; i < len; i++) {
  1466. ids[i] = items[i][this.fieldId];
  1467. }
  1468. }
  1469. else {
  1470. // create unordered list
  1471. for (id in data) {
  1472. if (data.hasOwnProperty(id)) {
  1473. item = data[id];
  1474. ids.push(item[this.fieldId]);
  1475. }
  1476. }
  1477. }
  1478. }
  1479. return ids;
  1480. };
  1481. /**
  1482. * Execute a callback function for every item in the dataset.
  1483. * The order of the items is not determined.
  1484. * @param {function} callback
  1485. * @param {Object} [options] Available options:
  1486. * {Object.<String, String>} [convert]
  1487. * {String[]} [fields] filter fields
  1488. * {function} [filter] filter items
  1489. * {String | function} [order] Order the items by
  1490. * a field name or custom sort function.
  1491. */
  1492. DataSet.prototype.forEach = function (callback, options) {
  1493. var filter = options && options.filter,
  1494. convert = options && options.convert || this.options.convert,
  1495. data = this.data,
  1496. item,
  1497. id;
  1498. if (options && options.order) {
  1499. // execute forEach on ordered list
  1500. var items = this.get(options);
  1501. for (var i = 0, len = items.length; i < len; i++) {
  1502. item = items[i];
  1503. id = item[this.fieldId];
  1504. callback(item, id);
  1505. }
  1506. }
  1507. else {
  1508. // unordered
  1509. for (id in data) {
  1510. if (data.hasOwnProperty(id)) {
  1511. item = this._getItem(id, convert);
  1512. if (!filter || filter(item)) {
  1513. callback(item, id);
  1514. }
  1515. }
  1516. }
  1517. }
  1518. };
  1519. /**
  1520. * Map every item in the dataset.
  1521. * @param {function} callback
  1522. * @param {Object} [options] Available options:
  1523. * {Object.<String, String>} [convert]
  1524. * {String[]} [fields] filter fields
  1525. * {function} [filter] filter items
  1526. * {String | function} [order] Order the items by
  1527. * a field name or custom sort function.
  1528. * @return {Object[]} mappedItems
  1529. */
  1530. DataSet.prototype.map = function (callback, options) {
  1531. var filter = options && options.filter,
  1532. convert = options && options.convert || this.options.convert,
  1533. mappedItems = [],
  1534. data = this.data,
  1535. item;
  1536. // convert and filter items
  1537. for (var id in data) {
  1538. if (data.hasOwnProperty(id)) {
  1539. item = this._getItem(id, convert);
  1540. if (!filter || filter(item)) {
  1541. mappedItems.push(callback(item, id));
  1542. }
  1543. }
  1544. }
  1545. // order items
  1546. if (options && options.order) {
  1547. this._sort(mappedItems, options.order);
  1548. }
  1549. return mappedItems;
  1550. };
  1551. /**
  1552. * Filter the fields of an item
  1553. * @param {Object} item
  1554. * @param {String[]} fields Field names
  1555. * @return {Object} filteredItem
  1556. * @private
  1557. */
  1558. DataSet.prototype._filterFields = function (item, fields) {
  1559. var filteredItem = {};
  1560. for (var field in item) {
  1561. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1562. filteredItem[field] = item[field];
  1563. }
  1564. }
  1565. return filteredItem;
  1566. };
  1567. /**
  1568. * Sort the provided array with items
  1569. * @param {Object[]} items
  1570. * @param {String | function} order A field name or custom sort function.
  1571. * @private
  1572. */
  1573. DataSet.prototype._sort = function (items, order) {
  1574. if (util.isString(order)) {
  1575. // order by provided field name
  1576. var name = order; // field name
  1577. items.sort(function (a, b) {
  1578. var av = a[name];
  1579. var bv = b[name];
  1580. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1581. });
  1582. }
  1583. else if (typeof order === 'function') {
  1584. // order by sort function
  1585. items.sort(order);
  1586. }
  1587. // TODO: extend order by an Object {field:String, direction:String}
  1588. // where direction can be 'asc' or 'desc'
  1589. else {
  1590. throw new TypeError('Order must be a function or a string');
  1591. }
  1592. };
  1593. /**
  1594. * Remove an object by pointer or by id
  1595. * @param {String | Number | Object | Array} id Object or id, or an array with
  1596. * objects or ids to be removed
  1597. * @param {String} [senderId] Optional sender id
  1598. * @return {Array} removedIds
  1599. */
  1600. DataSet.prototype.remove = function (id, senderId) {
  1601. var removedIds = [],
  1602. i, len, removedId;
  1603. if (id instanceof Array) {
  1604. for (i = 0, len = id.length; i < len; i++) {
  1605. removedId = this._remove(id[i]);
  1606. if (removedId != null) {
  1607. removedIds.push(removedId);
  1608. }
  1609. }
  1610. }
  1611. else {
  1612. removedId = this._remove(id);
  1613. if (removedId != null) {
  1614. removedIds.push(removedId);
  1615. }
  1616. }
  1617. if (removedIds.length) {
  1618. this._trigger('remove', {items: removedIds}, senderId);
  1619. }
  1620. return removedIds;
  1621. };
  1622. /**
  1623. * Remove an item by its id
  1624. * @param {Number | String | Object} id id or item
  1625. * @returns {Number | String | null} id
  1626. * @private
  1627. */
  1628. DataSet.prototype._remove = function (id) {
  1629. if (util.isNumber(id) || util.isString(id)) {
  1630. if (this.data[id]) {
  1631. delete this.data[id];
  1632. delete this.internalIds[id];
  1633. return id;
  1634. }
  1635. }
  1636. else if (id instanceof Object) {
  1637. var itemId = id[this.fieldId];
  1638. if (itemId && this.data[itemId]) {
  1639. delete this.data[itemId];
  1640. delete this.internalIds[itemId];
  1641. return itemId;
  1642. }
  1643. }
  1644. return null;
  1645. };
  1646. /**
  1647. * Clear the data
  1648. * @param {String} [senderId] Optional sender id
  1649. * @return {Array} removedIds The ids of all removed items
  1650. */
  1651. DataSet.prototype.clear = function (senderId) {
  1652. var ids = Object.keys(this.data);
  1653. this.data = {};
  1654. this.internalIds = {};
  1655. this._trigger('remove', {items: ids}, senderId);
  1656. return ids;
  1657. };
  1658. /**
  1659. * Find the item with maximum value of a specified field
  1660. * @param {String} field
  1661. * @return {Object | null} item Item containing max value, or null if no items
  1662. */
  1663. DataSet.prototype.max = function (field) {
  1664. var data = this.data,
  1665. max = null,
  1666. maxField = null;
  1667. for (var id in data) {
  1668. if (data.hasOwnProperty(id)) {
  1669. var item = data[id];
  1670. var itemField = item[field];
  1671. if (itemField != null && (!max || itemField > maxField)) {
  1672. max = item;
  1673. maxField = itemField;
  1674. }
  1675. }
  1676. }
  1677. return max;
  1678. };
  1679. /**
  1680. * Find the item with minimum value of a specified field
  1681. * @param {String} field
  1682. * @return {Object | null} item Item containing max value, or null if no items
  1683. */
  1684. DataSet.prototype.min = function (field) {
  1685. var data = this.data,
  1686. min = null,
  1687. minField = null;
  1688. for (var id in data) {
  1689. if (data.hasOwnProperty(id)) {
  1690. var item = data[id];
  1691. var itemField = item[field];
  1692. if (itemField != null && (!min || itemField < minField)) {
  1693. min = item;
  1694. minField = itemField;
  1695. }
  1696. }
  1697. }
  1698. return min;
  1699. };
  1700. /**
  1701. * Find all distinct values of a specified field
  1702. * @param {String} field
  1703. * @return {Array} values Array containing all distinct values. If the data
  1704. * items do not contain the specified field, an array
  1705. * containing a single value undefined is returned.
  1706. * The returned array is unordered.
  1707. */
  1708. DataSet.prototype.distinct = function (field) {
  1709. var data = this.data,
  1710. values = [],
  1711. fieldType = this.options.convert[field],
  1712. count = 0;
  1713. for (var prop in data) {
  1714. if (data.hasOwnProperty(prop)) {
  1715. var item = data[prop];
  1716. var value = util.convert(item[field], fieldType);
  1717. var exists = false;
  1718. for (var i = 0; i < count; i++) {
  1719. if (values[i] == value) {
  1720. exists = true;
  1721. break;
  1722. }
  1723. }
  1724. if (!exists) {
  1725. values[count] = value;
  1726. count++;
  1727. }
  1728. }
  1729. }
  1730. return values;
  1731. };
  1732. /**
  1733. * Add a single item. Will fail when an item with the same id already exists.
  1734. * @param {Object} item
  1735. * @return {String} id
  1736. * @private
  1737. */
  1738. DataSet.prototype._addItem = function (item) {
  1739. var id = item[this.fieldId];
  1740. if (id != undefined) {
  1741. // check whether this id is already taken
  1742. if (this.data[id]) {
  1743. // item already exists
  1744. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1745. }
  1746. }
  1747. else {
  1748. // generate an id
  1749. id = util.randomUUID();
  1750. item[this.fieldId] = id;
  1751. this.internalIds[id] = item;
  1752. }
  1753. var d = {};
  1754. for (var field in item) {
  1755. if (item.hasOwnProperty(field)) {
  1756. var fieldType = this.convert[field]; // type may be undefined
  1757. d[field] = util.convert(item[field], fieldType);
  1758. }
  1759. }
  1760. this.data[id] = d;
  1761. return id;
  1762. };
  1763. /**
  1764. * Get an item. Fields can be converted to a specific type
  1765. * @param {String} id
  1766. * @param {Object.<String, String>} [convert] field types to convert
  1767. * @return {Object | null} item
  1768. * @private
  1769. */
  1770. DataSet.prototype._getItem = function (id, convert) {
  1771. var field, value;
  1772. // get the item from the dataset
  1773. var raw = this.data[id];
  1774. if (!raw) {
  1775. return null;
  1776. }
  1777. // convert the items field types
  1778. var converted = {},
  1779. fieldId = this.fieldId,
  1780. internalIds = this.internalIds;
  1781. if (convert) {
  1782. for (field in raw) {
  1783. if (raw.hasOwnProperty(field)) {
  1784. value = raw[field];
  1785. // output all fields, except internal ids
  1786. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1787. converted[field] = util.convert(value, convert[field]);
  1788. }
  1789. }
  1790. }
  1791. }
  1792. else {
  1793. // no field types specified, no converting needed
  1794. for (field in raw) {
  1795. if (raw.hasOwnProperty(field)) {
  1796. value = raw[field];
  1797. // output all fields, except internal ids
  1798. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1799. converted[field] = value;
  1800. }
  1801. }
  1802. }
  1803. }
  1804. return converted;
  1805. };
  1806. /**
  1807. * Update a single item: merge with existing item.
  1808. * Will fail when the item has no id, or when there does not exist an item
  1809. * with the same id.
  1810. * @param {Object} item
  1811. * @return {String} id
  1812. * @private
  1813. */
  1814. DataSet.prototype._updateItem = function (item) {
  1815. var id = item[this.fieldId];
  1816. if (id == undefined) {
  1817. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1818. }
  1819. var d = this.data[id];
  1820. if (!d) {
  1821. // item doesn't exist
  1822. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1823. }
  1824. // merge with current item
  1825. for (var field in item) {
  1826. if (item.hasOwnProperty(field)) {
  1827. var fieldType = this.convert[field]; // type may be undefined
  1828. d[field] = util.convert(item[field], fieldType);
  1829. }
  1830. }
  1831. return id;
  1832. };
  1833. /**
  1834. * check if an id is an internal or external id
  1835. * @param id
  1836. * @returns {boolean}
  1837. * @private
  1838. */
  1839. DataSet.prototype.isInternalId = function(id) {
  1840. return (id in this.internalIds);
  1841. };
  1842. /**
  1843. * Get an array with the column names of a Google DataTable
  1844. * @param {DataTable} dataTable
  1845. * @return {String[]} columnNames
  1846. * @private
  1847. */
  1848. DataSet.prototype._getColumnNames = function (dataTable) {
  1849. var columns = [];
  1850. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1851. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1852. }
  1853. return columns;
  1854. };
  1855. /**
  1856. * Append an item as a row to the dataTable
  1857. * @param dataTable
  1858. * @param columns
  1859. * @param item
  1860. * @private
  1861. */
  1862. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1863. var row = dataTable.addRow();
  1864. for (var col = 0, cols = columns.length; col < cols; col++) {
  1865. var field = columns[col];
  1866. dataTable.setValue(row, col, item[field]);
  1867. }
  1868. };
  1869. /**
  1870. * DataView
  1871. *
  1872. * a dataview offers a filtered view on a dataset or an other dataview.
  1873. *
  1874. * @param {DataSet | DataView} data
  1875. * @param {Object} [options] Available options: see method get
  1876. *
  1877. * @constructor DataView
  1878. */
  1879. function DataView (data, options) {
  1880. this.id = util.randomUUID();
  1881. this.data = null;
  1882. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1883. this.options = options || {};
  1884. this.fieldId = 'id'; // name of the field containing id
  1885. this.subscribers = {}; // event subscribers
  1886. var me = this;
  1887. this.listener = function () {
  1888. me._onEvent.apply(me, arguments);
  1889. };
  1890. this.setData(data);
  1891. }
  1892. // TODO: implement a function .config() to dynamically update things like configured filter
  1893. // and trigger changes accordingly
  1894. /**
  1895. * Set a data source for the view
  1896. * @param {DataSet | DataView} data
  1897. */
  1898. DataView.prototype.setData = function (data) {
  1899. var ids, dataItems, i, len;
  1900. if (this.data) {
  1901. // unsubscribe from current dataset
  1902. if (this.data.unsubscribe) {
  1903. this.data.unsubscribe('*', this.listener);
  1904. }
  1905. // trigger a remove of all items in memory
  1906. ids = [];
  1907. for (var id in this.ids) {
  1908. if (this.ids.hasOwnProperty(id)) {
  1909. ids.push(id);
  1910. }
  1911. }
  1912. this.ids = {};
  1913. this._trigger('remove', {items: ids});
  1914. }
  1915. this.data = data;
  1916. if (this.data) {
  1917. // update fieldId
  1918. this.fieldId = this.options.fieldId ||
  1919. (this.data && this.data.options && this.data.options.fieldId) ||
  1920. 'id';
  1921. // trigger an add of all added items
  1922. ids = this.data.getIds({filter: this.options && this.options.filter});
  1923. for (i = 0, len = ids.length; i < len; i++) {
  1924. id = ids[i];
  1925. this.ids[id] = true;
  1926. }
  1927. this._trigger('add', {items: ids});
  1928. // subscribe to new dataset
  1929. if (this.data.on) {
  1930. this.data.on('*', this.listener);
  1931. }
  1932. }
  1933. };
  1934. /**
  1935. * Get data from the data view
  1936. *
  1937. * Usage:
  1938. *
  1939. * get()
  1940. * get(options: Object)
  1941. * get(options: Object, data: Array | DataTable)
  1942. *
  1943. * get(id: Number)
  1944. * get(id: Number, options: Object)
  1945. * get(id: Number, options: Object, data: Array | DataTable)
  1946. *
  1947. * get(ids: Number[])
  1948. * get(ids: Number[], options: Object)
  1949. * get(ids: Number[], options: Object, data: Array | DataTable)
  1950. *
  1951. * Where:
  1952. *
  1953. * {Number | String} id The id of an item
  1954. * {Number[] | String{}} ids An array with ids of items
  1955. * {Object} options An Object with options. Available options:
  1956. * {String} [type] Type of data to be returned. Can
  1957. * be 'DataTable' or 'Array' (default)
  1958. * {Object.<String, String>} [convert]
  1959. * {String[]} [fields] field names to be returned
  1960. * {function} [filter] filter items
  1961. * {String | function} [order] Order the items by
  1962. * a field name or custom sort function.
  1963. * {Array | DataTable} [data] If provided, items will be appended to this
  1964. * array or table. Required in case of Google
  1965. * DataTable.
  1966. * @param args
  1967. */
  1968. DataView.prototype.get = function (args) {
  1969. var me = this;
  1970. // parse the arguments
  1971. var ids, options, data;
  1972. var firstType = util.getType(arguments[0]);
  1973. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  1974. // get(id(s) [, options] [, data])
  1975. ids = arguments[0]; // can be a single id or an array with ids
  1976. options = arguments[1];
  1977. data = arguments[2];
  1978. }
  1979. else {
  1980. // get([, options] [, data])
  1981. options = arguments[0];
  1982. data = arguments[1];
  1983. }
  1984. // extend the options with the default options and provided options
  1985. var viewOptions = util.extend({}, this.options, options);
  1986. // create a combined filter method when needed
  1987. if (this.options.filter && options && options.filter) {
  1988. viewOptions.filter = function (item) {
  1989. return me.options.filter(item) && options.filter(item);
  1990. }
  1991. }
  1992. // build up the call to the linked data set
  1993. var getArguments = [];
  1994. if (ids != undefined) {
  1995. getArguments.push(ids);
  1996. }
  1997. getArguments.push(viewOptions);
  1998. getArguments.push(data);
  1999. return this.data && this.data.get.apply(this.data, getArguments);
  2000. };
  2001. /**
  2002. * Get ids of all items or from a filtered set of items.
  2003. * @param {Object} [options] An Object with options. Available options:
  2004. * {function} [filter] filter items
  2005. * {String | function} [order] Order the items by
  2006. * a field name or custom sort function.
  2007. * @return {Array} ids
  2008. */
  2009. DataView.prototype.getIds = function (options) {
  2010. var ids;
  2011. if (this.data) {
  2012. var defaultFilter = this.options.filter;
  2013. var filter;
  2014. if (options && options.filter) {
  2015. if (defaultFilter) {
  2016. filter = function (item) {
  2017. return defaultFilter(item) && options.filter(item);
  2018. }
  2019. }
  2020. else {
  2021. filter = options.filter;
  2022. }
  2023. }
  2024. else {
  2025. filter = defaultFilter;
  2026. }
  2027. ids = this.data.getIds({
  2028. filter: filter,
  2029. order: options && options.order
  2030. });
  2031. }
  2032. else {
  2033. ids = [];
  2034. }
  2035. return ids;
  2036. };
  2037. /**
  2038. * Event listener. Will propagate all events from the connected data set to
  2039. * the subscribers of the DataView, but will filter the items and only trigger
  2040. * when there are changes in the filtered data set.
  2041. * @param {String} event
  2042. * @param {Object | null} params
  2043. * @param {String} senderId
  2044. * @private
  2045. */
  2046. DataView.prototype._onEvent = function (event, params, senderId) {
  2047. var i, len, id, item,
  2048. ids = params && params.items,
  2049. data = this.data,
  2050. added = [],
  2051. updated = [],
  2052. removed = [];
  2053. if (ids && data) {
  2054. switch (event) {
  2055. case 'add':
  2056. // filter the ids of the added items
  2057. for (i = 0, len = ids.length; i < len; i++) {
  2058. id = ids[i];
  2059. item = this.get(id);
  2060. if (item) {
  2061. this.ids[id] = true;
  2062. added.push(id);
  2063. }
  2064. }
  2065. break;
  2066. case 'update':
  2067. // determine the event from the views viewpoint: an updated
  2068. // item can be added, updated, or removed from this view.
  2069. for (i = 0, len = ids.length; i < len; i++) {
  2070. id = ids[i];
  2071. item = this.get(id);
  2072. if (item) {
  2073. if (this.ids[id]) {
  2074. updated.push(id);
  2075. }
  2076. else {
  2077. this.ids[id] = true;
  2078. added.push(id);
  2079. }
  2080. }
  2081. else {
  2082. if (this.ids[id]) {
  2083. delete this.ids[id];
  2084. removed.push(id);
  2085. }
  2086. else {
  2087. // nothing interesting for me :-(
  2088. }
  2089. }
  2090. }
  2091. break;
  2092. case 'remove':
  2093. // filter the ids of the removed items
  2094. for (i = 0, len = ids.length; i < len; i++) {
  2095. id = ids[i];
  2096. if (this.ids[id]) {
  2097. delete this.ids[id];
  2098. removed.push(id);
  2099. }
  2100. }
  2101. break;
  2102. }
  2103. if (added.length) {
  2104. this._trigger('add', {items: added}, senderId);
  2105. }
  2106. if (updated.length) {
  2107. this._trigger('update', {items: updated}, senderId);
  2108. }
  2109. if (removed.length) {
  2110. this._trigger('remove', {items: removed}, senderId);
  2111. }
  2112. }
  2113. };
  2114. // copy subscription functionality from DataSet
  2115. DataView.prototype.on = DataSet.prototype.on;
  2116. DataView.prototype.off = DataSet.prototype.off;
  2117. DataView.prototype._trigger = DataSet.prototype._trigger;
  2118. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2119. DataView.prototype.subscribe = DataView.prototype.on;
  2120. DataView.prototype.unsubscribe = DataView.prototype.off;
  2121. /**
  2122. * @constructor TimeStep
  2123. * The class TimeStep is an iterator for dates. You provide a start date and an
  2124. * end date. The class itself determines the best scale (step size) based on the
  2125. * provided start Date, end Date, and minimumStep.
  2126. *
  2127. * If minimumStep is provided, the step size is chosen as close as possible
  2128. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2129. * provided, the scale is set to 1 DAY.
  2130. * The minimumStep should correspond with the onscreen size of about 6 characters
  2131. *
  2132. * Alternatively, you can set a scale by hand.
  2133. * After creation, you can initialize the class by executing first(). Then you
  2134. * can iterate from the start date to the end date via next(). You can check if
  2135. * the end date is reached with the function hasNext(). After each step, you can
  2136. * retrieve the current date via getCurrent().
  2137. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2138. * days, to years.
  2139. *
  2140. * Version: 1.2
  2141. *
  2142. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2143. * or new Date(2010, 9, 21, 23, 45, 00)
  2144. * @param {Date} [end] The end date
  2145. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2146. */
  2147. TimeStep = function(start, end, minimumStep) {
  2148. // variables
  2149. this.current = new Date();
  2150. this._start = new Date();
  2151. this._end = new Date();
  2152. this.autoScale = true;
  2153. this.scale = TimeStep.SCALE.DAY;
  2154. this.step = 1;
  2155. // initialize the range
  2156. this.setRange(start, end, minimumStep);
  2157. };
  2158. /// enum scale
  2159. TimeStep.SCALE = {
  2160. MILLISECOND: 1,
  2161. SECOND: 2,
  2162. MINUTE: 3,
  2163. HOUR: 4,
  2164. DAY: 5,
  2165. WEEKDAY: 6,
  2166. MONTH: 7,
  2167. YEAR: 8
  2168. };
  2169. /**
  2170. * Set a new range
  2171. * If minimumStep is provided, the step size is chosen as close as possible
  2172. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2173. * provided, the scale is set to 1 DAY.
  2174. * The minimumStep should correspond with the onscreen size of about 6 characters
  2175. * @param {Date} [start] The start date and time.
  2176. * @param {Date} [end] The end date and time.
  2177. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2178. */
  2179. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2180. if (!(start instanceof Date) || !(end instanceof Date)) {
  2181. throw "No legal start or end date in method setRange";
  2182. }
  2183. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2184. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2185. if (this.autoScale) {
  2186. this.setMinimumStep(minimumStep);
  2187. }
  2188. };
  2189. /**
  2190. * Set the range iterator to the start date.
  2191. */
  2192. TimeStep.prototype.first = function() {
  2193. this.current = new Date(this._start.valueOf());
  2194. this.roundToMinor();
  2195. };
  2196. /**
  2197. * Round the current date to the first minor date value
  2198. * This must be executed once when the current date is set to start Date
  2199. */
  2200. TimeStep.prototype.roundToMinor = function() {
  2201. // round to floor
  2202. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2203. //noinspection FallthroughInSwitchStatementJS
  2204. switch (this.scale) {
  2205. case TimeStep.SCALE.YEAR:
  2206. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2207. this.current.setMonth(0);
  2208. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2209. case TimeStep.SCALE.DAY: // intentional fall through
  2210. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2211. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2212. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2213. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2214. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2215. }
  2216. if (this.step != 1) {
  2217. // round down to the first minor value that is a multiple of the current step size
  2218. switch (this.scale) {
  2219. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2220. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2221. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2222. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2223. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2224. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2225. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2226. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2227. default: break;
  2228. }
  2229. }
  2230. };
  2231. /**
  2232. * Check if the there is a next step
  2233. * @return {boolean} true if the current date has not passed the end date
  2234. */
  2235. TimeStep.prototype.hasNext = function () {
  2236. return (this.current.valueOf() <= this._end.valueOf());
  2237. };
  2238. /**
  2239. * Do the next step
  2240. */
  2241. TimeStep.prototype.next = function() {
  2242. var prev = this.current.valueOf();
  2243. // Two cases, needed to prevent issues with switching daylight savings
  2244. // (end of March and end of October)
  2245. if (this.current.getMonth() < 6) {
  2246. switch (this.scale) {
  2247. case TimeStep.SCALE.MILLISECOND:
  2248. this.current = new Date(this.current.valueOf() + this.step); break;
  2249. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2250. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2251. case TimeStep.SCALE.HOUR:
  2252. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2253. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2254. var h = this.current.getHours();
  2255. this.current.setHours(h - (h % this.step));
  2256. 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. else {
  2265. switch (this.scale) {
  2266. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2267. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2268. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2269. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2270. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2271. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2272. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2273. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2274. default: break;
  2275. }
  2276. }
  2277. if (this.step != 1) {
  2278. // round down to the correct major value
  2279. switch (this.scale) {
  2280. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2281. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2282. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2283. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2284. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2285. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2286. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2287. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2288. default: break;
  2289. }
  2290. }
  2291. // safety mechanism: if current time is still unchanged, move to the end
  2292. if (this.current.valueOf() == prev) {
  2293. this.current = new Date(this._end.valueOf());
  2294. }
  2295. };
  2296. /**
  2297. * Get the current datetime
  2298. * @return {Date} current The current date
  2299. */
  2300. TimeStep.prototype.getCurrent = function() {
  2301. return this.current;
  2302. };
  2303. /**
  2304. * Set a custom scale. Autoscaling will be disabled.
  2305. * For example setScale(SCALE.MINUTES, 5) will result
  2306. * in minor steps of 5 minutes, and major steps of an hour.
  2307. *
  2308. * @param {TimeStep.SCALE} newScale
  2309. * A scale. Choose from SCALE.MILLISECOND,
  2310. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2311. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2312. * SCALE.YEAR.
  2313. * @param {Number} newStep A step size, by default 1. Choose for
  2314. * example 1, 2, 5, or 10.
  2315. */
  2316. TimeStep.prototype.setScale = function(newScale, newStep) {
  2317. this.scale = newScale;
  2318. if (newStep > 0) {
  2319. this.step = newStep;
  2320. }
  2321. this.autoScale = false;
  2322. };
  2323. /**
  2324. * Enable or disable autoscaling
  2325. * @param {boolean} enable If true, autoascaling is set true
  2326. */
  2327. TimeStep.prototype.setAutoScale = function (enable) {
  2328. this.autoScale = enable;
  2329. };
  2330. /**
  2331. * Automatically determine the scale that bests fits the provided minimum step
  2332. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2333. */
  2334. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2335. if (minimumStep == undefined) {
  2336. return;
  2337. }
  2338. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2339. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2340. var stepDay = (1000 * 60 * 60 * 24);
  2341. var stepHour = (1000 * 60 * 60);
  2342. var stepMinute = (1000 * 60);
  2343. var stepSecond = (1000);
  2344. var stepMillisecond= (1);
  2345. // find the smallest step that is larger than the provided minimumStep
  2346. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2347. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2348. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2349. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2350. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2351. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2352. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2353. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2354. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2355. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2356. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2357. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2358. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2359. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2360. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2361. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2362. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2363. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2364. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2365. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2366. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2367. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2368. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2369. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2370. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2371. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2372. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2373. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2374. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2375. };
  2376. /**
  2377. * Snap a date to a rounded value.
  2378. * The snap intervals are dependent on the current scale and step.
  2379. * @param {Date} date the date to be snapped.
  2380. * @return {Date} snappedDate
  2381. */
  2382. TimeStep.prototype.snap = function(date) {
  2383. var clone = new Date(date.valueOf());
  2384. if (this.scale == TimeStep.SCALE.YEAR) {
  2385. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2386. clone.setFullYear(Math.round(year / this.step) * this.step);
  2387. clone.setMonth(0);
  2388. clone.setDate(0);
  2389. clone.setHours(0);
  2390. clone.setMinutes(0);
  2391. clone.setSeconds(0);
  2392. clone.setMilliseconds(0);
  2393. }
  2394. else if (this.scale == TimeStep.SCALE.MONTH) {
  2395. if (clone.getDate() > 15) {
  2396. clone.setDate(1);
  2397. clone.setMonth(clone.getMonth() + 1);
  2398. // important: first set Date to 1, after that change the month.
  2399. }
  2400. else {
  2401. clone.setDate(1);
  2402. }
  2403. clone.setHours(0);
  2404. clone.setMinutes(0);
  2405. clone.setSeconds(0);
  2406. clone.setMilliseconds(0);
  2407. }
  2408. else if (this.scale == TimeStep.SCALE.DAY ||
  2409. this.scale == TimeStep.SCALE.WEEKDAY) {
  2410. //noinspection FallthroughInSwitchStatementJS
  2411. switch (this.step) {
  2412. case 5:
  2413. case 2:
  2414. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2415. default:
  2416. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2417. }
  2418. clone.setMinutes(0);
  2419. clone.setSeconds(0);
  2420. clone.setMilliseconds(0);
  2421. }
  2422. else if (this.scale == TimeStep.SCALE.HOUR) {
  2423. switch (this.step) {
  2424. case 4:
  2425. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2426. default:
  2427. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2428. }
  2429. clone.setSeconds(0);
  2430. clone.setMilliseconds(0);
  2431. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2432. //noinspection FallthroughInSwitchStatementJS
  2433. switch (this.step) {
  2434. case 15:
  2435. case 10:
  2436. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2437. clone.setSeconds(0);
  2438. break;
  2439. case 5:
  2440. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2441. default:
  2442. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2443. }
  2444. clone.setMilliseconds(0);
  2445. }
  2446. else if (this.scale == TimeStep.SCALE.SECOND) {
  2447. //noinspection FallthroughInSwitchStatementJS
  2448. switch (this.step) {
  2449. case 15:
  2450. case 10:
  2451. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2452. clone.setMilliseconds(0);
  2453. break;
  2454. case 5:
  2455. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2456. default:
  2457. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2458. }
  2459. }
  2460. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2461. var step = this.step > 5 ? this.step / 2 : 1;
  2462. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2463. }
  2464. return clone;
  2465. };
  2466. /**
  2467. * Check if the current value is a major value (for example when the step
  2468. * is DAY, a major value is each first day of the MONTH)
  2469. * @return {boolean} true if current date is major, else false.
  2470. */
  2471. TimeStep.prototype.isMajor = function() {
  2472. switch (this.scale) {
  2473. case TimeStep.SCALE.MILLISECOND:
  2474. return (this.current.getMilliseconds() == 0);
  2475. case TimeStep.SCALE.SECOND:
  2476. return (this.current.getSeconds() == 0);
  2477. case TimeStep.SCALE.MINUTE:
  2478. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2479. // Note: this is no bug. Major label is equal for both minute and hour scale
  2480. case TimeStep.SCALE.HOUR:
  2481. return (this.current.getHours() == 0);
  2482. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2483. case TimeStep.SCALE.DAY:
  2484. return (this.current.getDate() == 1);
  2485. case TimeStep.SCALE.MONTH:
  2486. return (this.current.getMonth() == 0);
  2487. case TimeStep.SCALE.YEAR:
  2488. return false;
  2489. default:
  2490. return false;
  2491. }
  2492. };
  2493. /**
  2494. * Returns formatted text for the minor axislabel, depending on the current
  2495. * date and the scale. For example when scale is MINUTE, the current time is
  2496. * formatted as "hh:mm".
  2497. * @param {Date} [date] custom date. if not provided, current date is taken
  2498. */
  2499. TimeStep.prototype.getLabelMinor = function(date) {
  2500. if (date == undefined) {
  2501. date = this.current;
  2502. }
  2503. switch (this.scale) {
  2504. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2505. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2506. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2507. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2508. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2509. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2510. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2511. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2512. default: return '';
  2513. }
  2514. };
  2515. /**
  2516. * Returns formatted text for the major axis label, depending on the current
  2517. * date and the scale. For example when scale is MINUTE, the major scale is
  2518. * hours, and the hour will be formatted as "hh".
  2519. * @param {Date} [date] custom date. if not provided, current date is taken
  2520. */
  2521. TimeStep.prototype.getLabelMajor = function(date) {
  2522. if (date == undefined) {
  2523. date = this.current;
  2524. }
  2525. //noinspection FallthroughInSwitchStatementJS
  2526. switch (this.scale) {
  2527. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2528. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2529. case TimeStep.SCALE.MINUTE:
  2530. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2531. case TimeStep.SCALE.WEEKDAY:
  2532. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2533. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2534. case TimeStep.SCALE.YEAR: return '';
  2535. default: return '';
  2536. }
  2537. };
  2538. // TODO: turn Stack into a Mixin?
  2539. /**
  2540. * @constructor Stack
  2541. * Stacks items on top of each other.
  2542. * @param {Object} [options]
  2543. */
  2544. function Stack (options) {
  2545. this.options = options || {};
  2546. this.defaultOptions = {
  2547. order: function (a, b) {
  2548. // Order: ranges over non-ranges, ranged ordered by width,
  2549. // and non-ranges ordered by start.
  2550. if (a instanceof ItemRange) {
  2551. if (b instanceof ItemRange) {
  2552. var aInt = (a.data.end - a.data.start);
  2553. var bInt = (b.data.end - b.data.start);
  2554. return (aInt - bInt) || (a.data.start - b.data.start);
  2555. }
  2556. else {
  2557. return -1;
  2558. }
  2559. }
  2560. else {
  2561. if (b instanceof ItemRange) {
  2562. return 1;
  2563. }
  2564. else {
  2565. return (a.data.start - b.data.start);
  2566. }
  2567. }
  2568. },
  2569. margin: {
  2570. item: 10,
  2571. axis: 20
  2572. }
  2573. };
  2574. }
  2575. /**
  2576. * Set options for the stack
  2577. * @param {Object} options Available options:
  2578. * {Number} [margin.item=10]
  2579. * {Number} [margin.axis=20]
  2580. * {function} [order] Stacking order
  2581. */
  2582. Stack.prototype.setOptions = function setOptions (options) {
  2583. util.extend(this.options, options);
  2584. };
  2585. /**
  2586. * Order an array with items using a predefined order function for items
  2587. * @param {Item[]} items
  2588. */
  2589. Stack.prototype.order = function order(items) {
  2590. //order the items
  2591. var order = this.options.order || this.defaultOptions.order;
  2592. if (!(typeof order === 'function')) {
  2593. throw new Error('Option order must be a function');
  2594. }
  2595. items.sort(order);
  2596. };
  2597. /**
  2598. * Order items by their start data
  2599. * @param {Item[]} items
  2600. */
  2601. Stack.prototype.orderByStart = function orderByStart(items) {
  2602. items.sort(function (a, b) {
  2603. return a.data.start - b.data.start;
  2604. });
  2605. };
  2606. /**
  2607. * Order items by their end date. If they have no end date, their start date
  2608. * is used.
  2609. * @param {Item[]} items
  2610. */
  2611. Stack.prototype.orderByEnd = function orderByEnd(items) {
  2612. items.sort(function (a, b) {
  2613. var aTime = ('end' in a.data) ? a.data.end : a.data.start,
  2614. bTime = ('end' in b.data) ? b.data.end : b.data.start;
  2615. return aTime - bTime;
  2616. });
  2617. };
  2618. /**
  2619. * Adjust vertical positions of the events such that they don't overlap each
  2620. * other.
  2621. * @param {Item[]} items All visible items
  2622. * @private
  2623. */
  2624. Stack.prototype.stack = function stack (items) {
  2625. var i,
  2626. iMax,
  2627. options = this.options,
  2628. marginItem,
  2629. marginAxis;
  2630. if (options.margin && options.margin.item !== undefined) {
  2631. marginItem = options.margin.item;
  2632. }
  2633. else {
  2634. marginItem = this.defaultOptions.margin.item
  2635. }
  2636. if (options.margin && options.margin.axis !== undefined) {
  2637. marginAxis = options.margin.axis;
  2638. }
  2639. else {
  2640. marginAxis = this.defaultOptions.margin.axis
  2641. }
  2642. // calculate new, non-overlapping positions
  2643. for (i = 0, iMax = items.length; i < iMax; i++) {
  2644. var item = items[i];
  2645. if (item.top === null) {
  2646. // initialize top position
  2647. item.top = marginAxis;
  2648. do {
  2649. // TODO: optimize checking for overlap. when there is a gap without items,
  2650. // you only need to check for items from the next item on, not from zero
  2651. var collidingItem = null;
  2652. for (var j = 0, jj = items.length; j < jj; j++) {
  2653. var other = items[j];
  2654. if (other.top !== null && other !== item && this.collision(item, other, marginItem)) {
  2655. collidingItem = other;
  2656. break;
  2657. }
  2658. }
  2659. if (collidingItem != null) {
  2660. // There is a collision. Reposition the event above the colliding element
  2661. item.top = collidingItem.top + collidingItem.height + marginItem;
  2662. }
  2663. } while (collidingItem);
  2664. }
  2665. }
  2666. };
  2667. /**
  2668. * Test if the two provided items collide
  2669. * The items must have parameters left, width, top, and height.
  2670. * @param {Component} a The first item
  2671. * @param {Component} b The second item
  2672. * @param {Number} margin A minimum required margin.
  2673. * If margin is provided, the two items will be
  2674. * marked colliding when they overlap or
  2675. * when the margin between the two is smaller than
  2676. * the requested margin.
  2677. * @return {boolean} true if a and b collide, else false
  2678. */
  2679. Stack.prototype.collision = function collision (a, b, margin) {
  2680. return ((a.left - margin) < (b.left + b.width) &&
  2681. (a.left + a.width + margin) > b.left &&
  2682. (a.top - margin) < (b.top + b.height) &&
  2683. (a.top + a.height + margin) > b.top);
  2684. };
  2685. /**
  2686. * @constructor Range
  2687. * A Range controls a numeric range with a start and end value.
  2688. * The Range adjusts the range based on mouse events or programmatic changes,
  2689. * and triggers events when the range is changing or has been changed.
  2690. * @param {Object} [options] See description at Range.setOptions
  2691. * @extends Controller
  2692. */
  2693. function Range(options) {
  2694. this.id = util.randomUUID();
  2695. this.start = null; // Number
  2696. this.end = null; // Number
  2697. this.options = options || {};
  2698. this.setOptions(options);
  2699. }
  2700. // extend the Range prototype with an event emitter mixin
  2701. Emitter(Range.prototype);
  2702. /**
  2703. * Set options for the range controller
  2704. * @param {Object} options Available options:
  2705. * {Number} min Minimum value for start
  2706. * {Number} max Maximum value for end
  2707. * {Number} zoomMin Set a minimum value for
  2708. * (end - start).
  2709. * {Number} zoomMax Set a maximum value for
  2710. * (end - start).
  2711. */
  2712. Range.prototype.setOptions = function (options) {
  2713. util.extend(this.options, options);
  2714. // re-apply range with new limitations
  2715. if (this.start !== null && this.end !== null) {
  2716. this.setRange(this.start, this.end);
  2717. }
  2718. };
  2719. /**
  2720. * Test whether direction has a valid value
  2721. * @param {String} direction 'horizontal' or 'vertical'
  2722. */
  2723. function validateDirection (direction) {
  2724. if (direction != 'horizontal' && direction != 'vertical') {
  2725. throw new TypeError('Unknown direction "' + direction + '". ' +
  2726. 'Choose "horizontal" or "vertical".');
  2727. }
  2728. }
  2729. /**
  2730. * Add listeners for mouse and touch events to the component
  2731. * @param {Controller} controller
  2732. * @param {Component} component Should be a rootpanel
  2733. * @param {String} event Available events: 'move', 'zoom'
  2734. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2735. */
  2736. Range.prototype.subscribe = function (controller, component, event, direction) {
  2737. var me = this;
  2738. if (event == 'move') {
  2739. // drag start listener
  2740. controller.on('dragstart', function (event) {
  2741. me._onDragStart(event, component);
  2742. });
  2743. // drag listener
  2744. controller.on('drag', function (event) {
  2745. me._onDrag(event, component, direction);
  2746. });
  2747. // drag end listener
  2748. controller.on('dragend', function (event) {
  2749. me._onDragEnd(event, component);
  2750. });
  2751. // ignore dragging when holding
  2752. controller.on('hold', function (event) {
  2753. me._onHold();
  2754. });
  2755. }
  2756. else if (event == 'zoom') {
  2757. // mouse wheel
  2758. function mousewheel (event) {
  2759. me._onMouseWheel(event, component, direction);
  2760. }
  2761. controller.on('mousewheel', mousewheel);
  2762. controller.on('DOMMouseScroll', mousewheel); // For FF
  2763. // pinch
  2764. controller.on('touch', function (event) {
  2765. me._onTouch(event);
  2766. });
  2767. controller.on('pinch', function (event) {
  2768. me._onPinch(event, component, direction);
  2769. });
  2770. }
  2771. else {
  2772. throw new TypeError('Unknown event "' + event + '". ' +
  2773. 'Choose "move" or "zoom".');
  2774. }
  2775. };
  2776. /**
  2777. * Set a new start and end range
  2778. * @param {Number} [start]
  2779. * @param {Number} [end]
  2780. */
  2781. Range.prototype.setRange = function(start, end) {
  2782. var changed = this._applyRange(start, end);
  2783. if (changed) {
  2784. var params = {
  2785. start: this.start,
  2786. end: this.end
  2787. };
  2788. this.emit('rangechange', params);
  2789. this.emit('rangechanged', params);
  2790. }
  2791. };
  2792. /**
  2793. * Set a new start and end range. This method is the same as setRange, but
  2794. * does not trigger a range change and range changed event, and it returns
  2795. * true when the range is changed
  2796. * @param {Number} [start]
  2797. * @param {Number} [end]
  2798. * @return {Boolean} changed
  2799. * @private
  2800. */
  2801. Range.prototype._applyRange = function(start, end) {
  2802. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2803. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2804. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2805. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2806. diff;
  2807. // check for valid number
  2808. if (isNaN(newStart) || newStart === null) {
  2809. throw new Error('Invalid start "' + start + '"');
  2810. }
  2811. if (isNaN(newEnd) || newEnd === null) {
  2812. throw new Error('Invalid end "' + end + '"');
  2813. }
  2814. // prevent start < end
  2815. if (newEnd < newStart) {
  2816. newEnd = newStart;
  2817. }
  2818. // prevent start < min
  2819. if (min !== null) {
  2820. if (newStart < min) {
  2821. diff = (min - newStart);
  2822. newStart += diff;
  2823. newEnd += diff;
  2824. // prevent end > max
  2825. if (max != null) {
  2826. if (newEnd > max) {
  2827. newEnd = max;
  2828. }
  2829. }
  2830. }
  2831. }
  2832. // prevent end > max
  2833. if (max !== null) {
  2834. if (newEnd > max) {
  2835. diff = (newEnd - max);
  2836. newStart -= diff;
  2837. newEnd -= diff;
  2838. // prevent start < min
  2839. if (min != null) {
  2840. if (newStart < min) {
  2841. newStart = min;
  2842. }
  2843. }
  2844. }
  2845. }
  2846. // prevent (end-start) < zoomMin
  2847. if (this.options.zoomMin !== null) {
  2848. var zoomMin = parseFloat(this.options.zoomMin);
  2849. if (zoomMin < 0) {
  2850. zoomMin = 0;
  2851. }
  2852. if ((newEnd - newStart) < zoomMin) {
  2853. if ((this.end - this.start) === zoomMin) {
  2854. // ignore this action, we are already zoomed to the minimum
  2855. newStart = this.start;
  2856. newEnd = this.end;
  2857. }
  2858. else {
  2859. // zoom to the minimum
  2860. diff = (zoomMin - (newEnd - newStart));
  2861. newStart -= diff / 2;
  2862. newEnd += diff / 2;
  2863. }
  2864. }
  2865. }
  2866. // prevent (end-start) > zoomMax
  2867. if (this.options.zoomMax !== null) {
  2868. var zoomMax = parseFloat(this.options.zoomMax);
  2869. if (zoomMax < 0) {
  2870. zoomMax = 0;
  2871. }
  2872. if ((newEnd - newStart) > zoomMax) {
  2873. if ((this.end - this.start) === zoomMax) {
  2874. // ignore this action, we are already zoomed to the maximum
  2875. newStart = this.start;
  2876. newEnd = this.end;
  2877. }
  2878. else {
  2879. // zoom to the maximum
  2880. diff = ((newEnd - newStart) - zoomMax);
  2881. newStart += diff / 2;
  2882. newEnd -= diff / 2;
  2883. }
  2884. }
  2885. }
  2886. var changed = (this.start != newStart || this.end != newEnd);
  2887. this.start = newStart;
  2888. this.end = newEnd;
  2889. return changed;
  2890. };
  2891. /**
  2892. * Retrieve the current range.
  2893. * @return {Object} An object with start and end properties
  2894. */
  2895. Range.prototype.getRange = function() {
  2896. return {
  2897. start: this.start,
  2898. end: this.end
  2899. };
  2900. };
  2901. /**
  2902. * Calculate the conversion offset and scale for current range, based on
  2903. * the provided width
  2904. * @param {Number} width
  2905. * @returns {{offset: number, scale: number}} conversion
  2906. */
  2907. Range.prototype.conversion = function (width) {
  2908. return Range.conversion(this.start, this.end, width);
  2909. };
  2910. /**
  2911. * Static method to calculate the conversion offset and scale for a range,
  2912. * based on the provided start, end, and width
  2913. * @param {Number} start
  2914. * @param {Number} end
  2915. * @param {Number} width
  2916. * @returns {{offset: number, scale: number}} conversion
  2917. */
  2918. Range.conversion = function (start, end, width) {
  2919. if (width != 0 && (end - start != 0)) {
  2920. return {
  2921. offset: start,
  2922. scale: width / (end - start)
  2923. }
  2924. }
  2925. else {
  2926. return {
  2927. offset: 0,
  2928. scale: 1
  2929. };
  2930. }
  2931. };
  2932. // global (private) object to store drag params
  2933. var touchParams = {};
  2934. /**
  2935. * Start dragging horizontally or vertically
  2936. * @param {Event} event
  2937. * @param {Object} component
  2938. * @private
  2939. */
  2940. Range.prototype._onDragStart = function(event, component) {
  2941. // refuse to drag when we where pinching to prevent the timeline make a jump
  2942. // when releasing the fingers in opposite order from the touch screen
  2943. if (touchParams.ignore) return;
  2944. // TODO: reckon with option movable
  2945. touchParams.start = this.start;
  2946. touchParams.end = this.end;
  2947. var frame = component.frame;
  2948. if (frame) {
  2949. frame.style.cursor = 'move';
  2950. }
  2951. };
  2952. /**
  2953. * Perform dragging operating.
  2954. * @param {Event} event
  2955. * @param {Component} component
  2956. * @param {String} direction 'horizontal' or 'vertical'
  2957. * @private
  2958. */
  2959. Range.prototype._onDrag = function (event, component, direction) {
  2960. validateDirection(direction);
  2961. // TODO: reckon with option movable
  2962. // refuse to drag when we where pinching to prevent the timeline make a jump
  2963. // when releasing the fingers in opposite order from the touch screen
  2964. if (touchParams.ignore) return;
  2965. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  2966. interval = (touchParams.end - touchParams.start),
  2967. width = (direction == 'horizontal') ? component.width : component.height,
  2968. diffRange = -delta / width * interval;
  2969. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  2970. this.emit('rangechange', {
  2971. start: this.start,
  2972. end: this.end
  2973. });
  2974. };
  2975. /**
  2976. * Stop dragging operating.
  2977. * @param {event} event
  2978. * @param {Component} component
  2979. * @private
  2980. */
  2981. Range.prototype._onDragEnd = function (event, component) {
  2982. // refuse to drag when we where pinching to prevent the timeline make a jump
  2983. // when releasing the fingers in opposite order from the touch screen
  2984. if (touchParams.ignore) return;
  2985. // TODO: reckon with option movable
  2986. if (component.frame) {
  2987. component.frame.style.cursor = 'auto';
  2988. }
  2989. // fire a rangechanged event
  2990. this.emit('rangechanged', {
  2991. start: this.start,
  2992. end: this.end
  2993. });
  2994. };
  2995. /**
  2996. * Event handler for mouse wheel event, used to zoom
  2997. * Code from http://adomas.org/javascript-mouse-wheel/
  2998. * @param {Event} event
  2999. * @param {Component} component
  3000. * @param {String} direction 'horizontal' or 'vertical'
  3001. * @private
  3002. */
  3003. Range.prototype._onMouseWheel = function(event, component, direction) {
  3004. validateDirection(direction);
  3005. // TODO: reckon with option zoomable
  3006. // retrieve delta
  3007. var delta = 0;
  3008. if (event.wheelDelta) { /* IE/Opera. */
  3009. delta = event.wheelDelta / 120;
  3010. } else if (event.detail) { /* Mozilla case. */
  3011. // In Mozilla, sign of delta is different than in IE.
  3012. // Also, delta is multiple of 3.
  3013. delta = -event.detail / 3;
  3014. }
  3015. // If delta is nonzero, handle it.
  3016. // Basically, delta is now positive if wheel was scrolled up,
  3017. // and negative, if wheel was scrolled down.
  3018. if (delta) {
  3019. // perform the zoom action. Delta is normally 1 or -1
  3020. // adjust a negative delta such that zooming in with delta 0.1
  3021. // equals zooming out with a delta -0.1
  3022. var scale;
  3023. if (delta < 0) {
  3024. scale = 1 - (delta / 5);
  3025. }
  3026. else {
  3027. scale = 1 / (1 + (delta / 5)) ;
  3028. }
  3029. // calculate center, the date to zoom around
  3030. var gesture = util.fakeGesture(this, event),
  3031. pointer = getPointer(gesture.center, component.frame),
  3032. pointerDate = this._pointerToDate(component, direction, pointer);
  3033. this.zoom(scale, pointerDate);
  3034. }
  3035. // Prevent default actions caused by mouse wheel
  3036. // (else the page and timeline both zoom and scroll)
  3037. event.preventDefault();
  3038. };
  3039. /**
  3040. * Start of a touch gesture
  3041. * @private
  3042. */
  3043. Range.prototype._onTouch = function (event) {
  3044. touchParams.start = this.start;
  3045. touchParams.end = this.end;
  3046. touchParams.ignore = false;
  3047. touchParams.center = null;
  3048. // don't move the range when dragging a selected event
  3049. // TODO: it's not so neat to have to know about the state of the ItemSet
  3050. var item = ItemSet.itemFromTarget(event);
  3051. if (item && item.selected && this.options.editable) {
  3052. touchParams.ignore = true;
  3053. }
  3054. };
  3055. /**
  3056. * On start of a hold gesture
  3057. * @private
  3058. */
  3059. Range.prototype._onHold = function () {
  3060. touchParams.ignore = true;
  3061. };
  3062. /**
  3063. * Handle pinch event
  3064. * @param {Event} event
  3065. * @param {Component} component
  3066. * @param {String} direction 'horizontal' or 'vertical'
  3067. * @private
  3068. */
  3069. Range.prototype._onPinch = function (event, component, direction) {
  3070. touchParams.ignore = true;
  3071. // TODO: reckon with option zoomable
  3072. if (event.gesture.touches.length > 1) {
  3073. if (!touchParams.center) {
  3074. touchParams.center = getPointer(event.gesture.center, component.frame);
  3075. }
  3076. var scale = 1 / event.gesture.scale,
  3077. initDate = this._pointerToDate(component, direction, touchParams.center),
  3078. center = getPointer(event.gesture.center, component.frame),
  3079. date = this._pointerToDate(component, direction, center),
  3080. delta = date - initDate; // TODO: utilize delta
  3081. // calculate new start and end
  3082. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3083. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3084. // apply new range
  3085. this.setRange(newStart, newEnd);
  3086. }
  3087. };
  3088. /**
  3089. * Helper function to calculate the center date for zooming
  3090. * @param {Component} component
  3091. * @param {{x: Number, y: Number}} pointer
  3092. * @param {String} direction 'horizontal' or 'vertical'
  3093. * @return {number} date
  3094. * @private
  3095. */
  3096. Range.prototype._pointerToDate = function (component, direction, pointer) {
  3097. var conversion;
  3098. if (direction == 'horizontal') {
  3099. var width = component.width;
  3100. conversion = this.conversion(width);
  3101. return pointer.x / conversion.scale + conversion.offset;
  3102. }
  3103. else {
  3104. var height = component.height;
  3105. conversion = this.conversion(height);
  3106. return pointer.y / conversion.scale + conversion.offset;
  3107. }
  3108. };
  3109. /**
  3110. * Get the pointer location relative to the location of the dom element
  3111. * @param {{pageX: Number, pageY: Number}} touch
  3112. * @param {Element} element HTML DOM element
  3113. * @return {{x: Number, y: Number}} pointer
  3114. * @private
  3115. */
  3116. function getPointer (touch, element) {
  3117. return {
  3118. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3119. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3120. };
  3121. }
  3122. /**
  3123. * Zoom the range the given scale in or out. Start and end date will
  3124. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3125. * date around which to zoom.
  3126. * For example, try scale = 0.9 or 1.1
  3127. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3128. * values below 1 will zoom in.
  3129. * @param {Number} [center] Value representing a date around which will
  3130. * be zoomed.
  3131. */
  3132. Range.prototype.zoom = function(scale, center) {
  3133. // if centerDate is not provided, take it half between start Date and end Date
  3134. if (center == null) {
  3135. center = (this.start + this.end) / 2;
  3136. }
  3137. // calculate new start and end
  3138. var newStart = center + (this.start - center) * scale;
  3139. var newEnd = center + (this.end - center) * scale;
  3140. this.setRange(newStart, newEnd);
  3141. };
  3142. /**
  3143. * Move the range with a given delta to the left or right. Start and end
  3144. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3145. * @param {Number} delta Moving amount. Positive value will move right,
  3146. * negative value will move left
  3147. */
  3148. Range.prototype.move = function(delta) {
  3149. // zoom start Date and end Date relative to the centerDate
  3150. var diff = (this.end - this.start);
  3151. // apply new values
  3152. var newStart = this.start + diff * delta;
  3153. var newEnd = this.end + diff * delta;
  3154. // TODO: reckon with min and max range
  3155. this.start = newStart;
  3156. this.end = newEnd;
  3157. };
  3158. /**
  3159. * Move the range to a new center point
  3160. * @param {Number} moveTo New center point of the range
  3161. */
  3162. Range.prototype.moveTo = function(moveTo) {
  3163. var center = (this.start + this.end) / 2;
  3164. var diff = center - moveTo;
  3165. // calculate new start and end
  3166. var newStart = this.start - diff;
  3167. var newEnd = this.end - diff;
  3168. this.setRange(newStart, newEnd);
  3169. };
  3170. /**
  3171. * @constructor Controller
  3172. *
  3173. * A Controller controls the reflows and repaints of all components,
  3174. * and is used as an event bus for all components.
  3175. */
  3176. function Controller () {
  3177. var me = this;
  3178. this.id = util.randomUUID();
  3179. this.components = {};
  3180. /**
  3181. * Listen for a 'request-reflow' event. The controller will schedule a reflow
  3182. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3183. * is false.
  3184. */
  3185. var reflowTimer = null;
  3186. this.on('request-reflow', function requestReflow(force) {
  3187. if (force) {
  3188. me.reflow();
  3189. }
  3190. else {
  3191. if (!reflowTimer) {
  3192. reflowTimer = requestAnimationFrame(function () {
  3193. reflowTimer = null;
  3194. me.reflow();
  3195. });
  3196. }
  3197. }
  3198. });
  3199. /**
  3200. * Request a repaint. The controller will schedule a repaint
  3201. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3202. * is false.
  3203. */
  3204. var repaintTimer = null;
  3205. this.on('request-repaint', function requestRepaint(force) {
  3206. if (force) {
  3207. me.repaint();
  3208. }
  3209. else {
  3210. if (!repaintTimer) {
  3211. repaintTimer = requestAnimationFrame(function () {
  3212. repaintTimer = null;
  3213. me.repaint();
  3214. });
  3215. }
  3216. }
  3217. });
  3218. }
  3219. // Extend controller with Emitter mixin
  3220. Emitter(Controller.prototype);
  3221. /**
  3222. * Add a component to the controller
  3223. * @param {Component} component
  3224. */
  3225. Controller.prototype.add = function add(component) {
  3226. // validate the component
  3227. if (component.id == undefined) {
  3228. throw new Error('Component has no field id');
  3229. }
  3230. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3231. throw new TypeError('Component must be an instance of ' +
  3232. 'prototype Component or Controller');
  3233. }
  3234. // add the component
  3235. component.setController(this);
  3236. this.components[component.id] = component;
  3237. };
  3238. /**
  3239. * Remove a component from the controller
  3240. * @param {Component | String} component
  3241. */
  3242. Controller.prototype.remove = function remove(component) {
  3243. var id;
  3244. for (id in this.components) {
  3245. if (this.components.hasOwnProperty(id)) {
  3246. if (id == component || this.components[id] === component) {
  3247. break;
  3248. }
  3249. }
  3250. }
  3251. if (id) {
  3252. // unregister the controller (gives the component the ability to unregister
  3253. // event listeners and clean up other stuff)
  3254. this.components[id].setController(null);
  3255. delete this.components[id];
  3256. }
  3257. };
  3258. /**
  3259. * Repaint all components
  3260. */
  3261. Controller.prototype.repaint = function repaint() {
  3262. var changed = false;
  3263. // cancel any running repaint request
  3264. if (this.repaintTimer) {
  3265. clearTimeout(this.repaintTimer);
  3266. this.repaintTimer = undefined;
  3267. }
  3268. var done = {};
  3269. function repaint(component, id) {
  3270. if (!(id in done)) {
  3271. // first repaint the components on which this component is dependent
  3272. if (component.depends) {
  3273. component.depends.forEach(function (dep) {
  3274. repaint(dep, dep.id);
  3275. });
  3276. }
  3277. if (component.parent) {
  3278. repaint(component.parent, component.parent.id);
  3279. }
  3280. // repaint the component itself and mark as done
  3281. changed = component.repaint() || changed;
  3282. done[id] = true;
  3283. }
  3284. }
  3285. util.forEach(this.components, repaint);
  3286. this.emit('repaint');
  3287. // immediately reflow when needed
  3288. if (changed) {
  3289. this.reflow();
  3290. }
  3291. // TODO: limit the number of nested reflows/repaints, prevent loop
  3292. };
  3293. /**
  3294. * Reflow all components
  3295. */
  3296. Controller.prototype.reflow = function reflow() {
  3297. var resized = false;
  3298. // cancel any running repaint request
  3299. if (this.reflowTimer) {
  3300. clearTimeout(this.reflowTimer);
  3301. this.reflowTimer = undefined;
  3302. }
  3303. var done = {};
  3304. function reflow(component, id) {
  3305. if (!(id in done)) {
  3306. // first reflow the components on which this component is dependent
  3307. if (component.depends) {
  3308. component.depends.forEach(function (dep) {
  3309. reflow(dep, dep.id);
  3310. });
  3311. }
  3312. if (component.parent) {
  3313. reflow(component.parent, component.parent.id);
  3314. }
  3315. // reflow the component itself and mark as done
  3316. resized = component.reflow() || resized;
  3317. done[id] = true;
  3318. }
  3319. }
  3320. util.forEach(this.components, reflow);
  3321. this.emit('reflow');
  3322. // immediately repaint when needed
  3323. //if (resized) {
  3324. if (true) { // TODO: fix this loop
  3325. this.repaint();
  3326. }
  3327. // TODO: limit the number of nested reflows/repaints, prevent loop
  3328. };
  3329. /**
  3330. * Prototype for visual components
  3331. */
  3332. function Component () {
  3333. this.id = null;
  3334. this.parent = null;
  3335. this.depends = null;
  3336. this.controller = null;
  3337. this.options = null;
  3338. this.frame = null; // main DOM element
  3339. this.top = 0;
  3340. this.left = 0;
  3341. this.width = 0;
  3342. this.height = 0;
  3343. }
  3344. /**
  3345. * Set parameters for the frame. Parameters will be merged in current parameter
  3346. * set.
  3347. * @param {Object} options Available parameters:
  3348. * {String | function} [className]
  3349. * {String | Number | function} [left]
  3350. * {String | Number | function} [top]
  3351. * {String | Number | function} [width]
  3352. * {String | Number | function} [height]
  3353. */
  3354. Component.prototype.setOptions = function setOptions(options) {
  3355. if (options) {
  3356. util.extend(this.options, options);
  3357. if (this.controller) {
  3358. this.requestRepaint();
  3359. this.requestReflow();
  3360. }
  3361. }
  3362. };
  3363. /**
  3364. * Get an option value by name
  3365. * The function will first check this.options object, and else will check
  3366. * this.defaultOptions.
  3367. * @param {String} name
  3368. * @return {*} value
  3369. */
  3370. Component.prototype.getOption = function getOption(name) {
  3371. var value;
  3372. if (this.options) {
  3373. value = this.options[name];
  3374. }
  3375. if (value === undefined && this.defaultOptions) {
  3376. value = this.defaultOptions[name];
  3377. }
  3378. return value;
  3379. };
  3380. /**
  3381. * Set controller for this component, or remove current controller by passing
  3382. * null as parameter value.
  3383. * @param {Controller | null} controller
  3384. */
  3385. Component.prototype.setController = function setController (controller) {
  3386. this.controller = controller || null;
  3387. };
  3388. /**
  3389. * Get controller of this component
  3390. * @return {Controller} controller
  3391. */
  3392. Component.prototype.getController = function getController () {
  3393. return this.controller;
  3394. };
  3395. /**
  3396. * Get the container element of the component, which can be used by a child to
  3397. * add its own widgets. Not all components do have a container for childs, in
  3398. * that case null is returned.
  3399. * @returns {HTMLElement | null} container
  3400. */
  3401. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3402. Component.prototype.getContainer = function getContainer() {
  3403. // should be implemented by the component
  3404. return null;
  3405. };
  3406. /**
  3407. * Get the frame element of the component, the outer HTML DOM element.
  3408. * @returns {HTMLElement | null} frame
  3409. */
  3410. Component.prototype.getFrame = function getFrame() {
  3411. return this.frame;
  3412. };
  3413. /**
  3414. * Repaint the component
  3415. */
  3416. Component.prototype.repaint = function repaint() {
  3417. // should be implemented by the component
  3418. };
  3419. /**
  3420. * Reflow the component
  3421. * @return {Boolean} resized
  3422. */
  3423. Component.prototype.reflow = function reflow() {
  3424. // should be implemented by the component
  3425. return false;
  3426. };
  3427. /**
  3428. * Hide the component from the DOM
  3429. * @return {Boolean} changed
  3430. */
  3431. Component.prototype.hide = function hide() {
  3432. if (this.frame && this.frame.parentNode) {
  3433. this.frame.parentNode.removeChild(this.frame);
  3434. return true;
  3435. }
  3436. else {
  3437. return false;
  3438. }
  3439. };
  3440. /**
  3441. * Show the component in the DOM (when not already visible).
  3442. * A repaint will be executed when the component is not visible
  3443. * @return {Boolean} changed
  3444. */
  3445. Component.prototype.show = function show() {
  3446. if (!this.frame || !this.frame.parentNode) {
  3447. return this.repaint();
  3448. }
  3449. else {
  3450. return false;
  3451. }
  3452. };
  3453. /**
  3454. * Request a repaint. The controller will schedule a repaint
  3455. */
  3456. Component.prototype.requestRepaint = function requestRepaint() {
  3457. if (this.controller) {
  3458. this.controller.emit('request-repaint');
  3459. }
  3460. else {
  3461. throw new Error('Cannot request a repaint: no controller configured');
  3462. // TODO: just do a repaint when no parent is configured?
  3463. }
  3464. };
  3465. /**
  3466. * Request a reflow. The controller will schedule a reflow
  3467. */
  3468. Component.prototype.requestReflow = function requestReflow() {
  3469. if (this.controller) {
  3470. this.controller.emit('request-reflow');
  3471. }
  3472. else {
  3473. throw new Error('Cannot request a reflow: no controller configured');
  3474. // TODO: just do a reflow when no parent is configured?
  3475. }
  3476. };
  3477. /**
  3478. * A panel can contain components
  3479. * @param {Component} [parent]
  3480. * @param {Component[]} [depends] Components on which this components depends
  3481. * (except for the parent)
  3482. * @param {Object} [options] Available parameters:
  3483. * {String | Number | function} [left]
  3484. * {String | Number | function} [top]
  3485. * {String | Number | function} [width]
  3486. * {String | Number | function} [height]
  3487. * {String | function} [className]
  3488. * @constructor Panel
  3489. * @extends Component
  3490. */
  3491. function Panel(parent, depends, options) {
  3492. this.id = util.randomUUID();
  3493. this.parent = parent;
  3494. this.depends = depends;
  3495. this.options = options || {};
  3496. }
  3497. Panel.prototype = new Component();
  3498. /**
  3499. * Set options. Will extend the current options.
  3500. * @param {Object} [options] Available parameters:
  3501. * {String | function} [className]
  3502. * {String | Number | function} [left]
  3503. * {String | Number | function} [top]
  3504. * {String | Number | function} [width]
  3505. * {String | Number | function} [height]
  3506. */
  3507. Panel.prototype.setOptions = Component.prototype.setOptions;
  3508. /**
  3509. * Get the container element of the panel, which can be used by a child to
  3510. * add its own widgets.
  3511. * @returns {HTMLElement} container
  3512. */
  3513. Panel.prototype.getContainer = function () {
  3514. return this.frame;
  3515. };
  3516. /**
  3517. * Repaint the component
  3518. */
  3519. Panel.prototype.repaint = function () {
  3520. var asSize = util.option.asSize,
  3521. options = this.options,
  3522. frame = this.frame;
  3523. // create frame
  3524. if (!frame) {
  3525. frame = document.createElement('div');
  3526. if (!this.parent) throw new Error('Cannot repaint panel: no parent attached');
  3527. var parentContainer = this.parent.getContainer();
  3528. if (!parentContainer) throw new Error('Cannot repaint panel: parent has no container element');
  3529. parentContainer.appendChild(frame);
  3530. this.frame = frame;
  3531. }
  3532. // update className
  3533. frame.className = 'vpanel' + (options.className ? (' ' + asSize(options.className)) : '');
  3534. // update class name
  3535. var className = 'vis timeline rootpanel ' + options.orientation + (options.editable ? ' editable' : '');
  3536. if (options.className) className += ' ' + util.option.asString(className);
  3537. frame.className = className;
  3538. // update frame size
  3539. this._updateSize();
  3540. };
  3541. /**
  3542. * Apply the size from options to the panel, and recalculate it's actual size.
  3543. * @private
  3544. */
  3545. Panel.prototype._updateSize = function () {
  3546. // apply size
  3547. this.frame.style.top = util.option.asSize(this.options.top, '0px');
  3548. this.frame.style.left = util.option.asSize(this.options.left, '0px');
  3549. this.frame.style.width = util.option.asSize(this.options.width, '100%');
  3550. this.frame.style.height = util.option.asSize(this.options.height, '100%');
  3551. // get actual size
  3552. this.top = this.frame.offsetTop;
  3553. this.left = this.frame.offsetLeft;
  3554. this.width = this.frame.offsetWidth;
  3555. this.height = this.frame.offsetHeight;
  3556. };
  3557. /**
  3558. * A root panel can hold components. The root panel must be initialized with
  3559. * a DOM element as container.
  3560. * @param {HTMLElement} container
  3561. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3562. * @constructor RootPanel
  3563. * @extends Panel
  3564. */
  3565. function RootPanel(container, options) {
  3566. this.id = util.randomUUID();
  3567. this.container = container;
  3568. // create functions to be used as DOM event listeners
  3569. var me = this;
  3570. this.hammer = null;
  3571. // create listeners for all interesting events, these events will be emitted
  3572. // via the controller
  3573. var events = [
  3574. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3575. 'dragstart', 'drag', 'dragend',
  3576. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3577. ];
  3578. this.listeners = {};
  3579. events.forEach(function (event) {
  3580. me.listeners[event] = function () {
  3581. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3582. me.controller.emit.apply(me.controller, args);
  3583. };
  3584. });
  3585. this.options = options || {};
  3586. this.defaultOptions = {
  3587. autoResize: true
  3588. };
  3589. }
  3590. RootPanel.prototype = new Panel();
  3591. /**
  3592. * Set options. Will extend the current options.
  3593. * @param {Object} [options] Available parameters:
  3594. * {String | function} [className]
  3595. * {String | Number | function} [left]
  3596. * {String | Number | function} [top]
  3597. * {String | Number | function} [width]
  3598. * {String | Number | function} [height]
  3599. * {Boolean | function} [autoResize]
  3600. */
  3601. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3602. /**
  3603. * Repaint the component
  3604. */
  3605. RootPanel.prototype.repaint = function () {
  3606. var asSize = util.option.asSize,
  3607. options = this.options,
  3608. frame = this.frame;
  3609. // create frame
  3610. if (!frame) {
  3611. frame = document.createElement('div');
  3612. this.frame = frame;
  3613. if (!this.container) throw new Error('Cannot repaint root panel: no container attached');
  3614. this.container.appendChild(frame);
  3615. this._registerListeners();
  3616. }
  3617. // update class name
  3618. var className = 'vis timeline rootpanel ' + options.orientation + (options.editable ? ' editable' : '');
  3619. if (options.className) className += ' ' + util.option.asString(className);
  3620. frame.className = className;
  3621. // update frame size
  3622. this._updateSize();
  3623. this._updateWatch();
  3624. };
  3625. /**
  3626. * Update watching for resize, depending on the current option
  3627. * @private
  3628. */
  3629. RootPanel.prototype._updateWatch = function () {
  3630. var autoResize = this.getOption('autoResize');
  3631. if (autoResize) {
  3632. this._watch();
  3633. }
  3634. else {
  3635. this._unwatch();
  3636. }
  3637. };
  3638. /**
  3639. * Watch for changes in the size of the frame. On resize, the Panel will
  3640. * automatically redraw itself.
  3641. * @private
  3642. */
  3643. RootPanel.prototype._watch = function () {
  3644. var me = this;
  3645. this._unwatch();
  3646. var checkSize = function () {
  3647. var autoResize = me.getOption('autoResize');
  3648. if (!autoResize) {
  3649. // stop watching when the option autoResize is changed to false
  3650. me._unwatch();
  3651. return;
  3652. }
  3653. if (me.frame) {
  3654. // check whether the frame is resized
  3655. if ((me.frame.clientWidth != me.lastWidth) ||
  3656. (me.frame.clientHeight != me.lastHeight)) {
  3657. me.lastWidth = me.frame.clientWidth;
  3658. me.lastHeight = me.frame.clientHeight;
  3659. me.requestRepaint();
  3660. }
  3661. }
  3662. };
  3663. // TODO: automatically cleanup the event listener when the frame is deleted
  3664. util.addEventListener(window, 'resize', checkSize);
  3665. this.watchTimer = setInterval(checkSize, 1000);
  3666. };
  3667. /**
  3668. * Stop watching for a resize of the frame.
  3669. * @private
  3670. */
  3671. RootPanel.prototype._unwatch = function () {
  3672. if (this.watchTimer) {
  3673. clearInterval(this.watchTimer);
  3674. this.watchTimer = undefined;
  3675. }
  3676. // TODO: remove event listener on window.resize
  3677. };
  3678. /**
  3679. * Set controller for this component, or remove current controller by passing
  3680. * null as parameter value.
  3681. * @param {Controller | null} controller
  3682. */
  3683. RootPanel.prototype.setController = function setController (controller) {
  3684. this.controller = controller || null;
  3685. if (this.controller) {
  3686. this._registerListeners();
  3687. }
  3688. else {
  3689. this._unregisterListeners();
  3690. }
  3691. };
  3692. /**
  3693. * Register event emitters emitted by the rootpanel
  3694. * @private
  3695. */
  3696. RootPanel.prototype._registerListeners = function () {
  3697. if (this.frame && this.controller && !this.hammer) {
  3698. this.hammer = Hammer(this.frame, {
  3699. prevent_default: true
  3700. });
  3701. for (var event in this.listeners) {
  3702. if (this.listeners.hasOwnProperty(event)) {
  3703. this.hammer.on(event, this.listeners[event]);
  3704. }
  3705. }
  3706. }
  3707. };
  3708. /**
  3709. * Unregister event emitters from the rootpanel
  3710. * @private
  3711. */
  3712. RootPanel.prototype._unregisterListeners = function () {
  3713. if (this.hammer) {
  3714. for (var event in this.listeners) {
  3715. if (this.listeners.hasOwnProperty(event)) {
  3716. this.hammer.off(event, this.listeners[event]);
  3717. }
  3718. }
  3719. this.hammer = null;
  3720. }
  3721. };
  3722. /**
  3723. * A horizontal time axis
  3724. * @param {Component} parent
  3725. * @param {Component[]} [depends] Components on which this components depends
  3726. * (except for the parent)
  3727. * @param {Object} [options] See TimeAxis.setOptions for the available
  3728. * options.
  3729. * @constructor TimeAxis
  3730. * @extends Component
  3731. */
  3732. function TimeAxis (parent, depends, options) {
  3733. this.id = util.randomUUID();
  3734. this.parent = parent;
  3735. this.depends = depends;
  3736. this.dom = {
  3737. majorLines: [],
  3738. majorTexts: [],
  3739. minorLines: [],
  3740. minorTexts: [],
  3741. redundant: {
  3742. majorLines: [],
  3743. majorTexts: [],
  3744. minorLines: [],
  3745. minorTexts: []
  3746. }
  3747. };
  3748. this.props = {
  3749. range: {
  3750. start: 0,
  3751. end: 0,
  3752. minimumStep: 0
  3753. },
  3754. lineTop: 0
  3755. };
  3756. this.options = options || {};
  3757. this.defaultOptions = {
  3758. orientation: 'bottom', // supported: 'top', 'bottom'
  3759. // TODO: implement timeaxis orientations 'left' and 'right'
  3760. showMinorLabels: true,
  3761. showMajorLabels: true
  3762. };
  3763. this.conversion = null;
  3764. this.range = null;
  3765. }
  3766. TimeAxis.prototype = new Component();
  3767. // TODO: comment options
  3768. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3769. /**
  3770. * Set a range (start and end)
  3771. * @param {Range | Object} range A Range or an object containing start and end.
  3772. */
  3773. TimeAxis.prototype.setRange = function (range) {
  3774. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3775. throw new TypeError('Range must be an instance of Range, ' +
  3776. 'or an object containing start and end.');
  3777. }
  3778. this.range = range;
  3779. };
  3780. /**
  3781. * Convert a position on screen (pixels) to a datetime
  3782. * @param {int} x Position on the screen in pixels
  3783. * @return {Date} time The datetime the corresponds with given position x
  3784. */
  3785. TimeAxis.prototype.toTime = function(x) {
  3786. var conversion = this.conversion;
  3787. return new Date(x / conversion.scale + conversion.offset);
  3788. };
  3789. /**
  3790. * Convert a datetime (Date object) into a position on the screen
  3791. * @param {Date} time A date
  3792. * @return {int} x The position on the screen in pixels which corresponds
  3793. * with the given date.
  3794. * @private
  3795. */
  3796. TimeAxis.prototype.toScreen = function(time) {
  3797. var conversion = this.conversion;
  3798. return (time.valueOf() - conversion.offset) * conversion.scale;
  3799. };
  3800. /**
  3801. * Repaint the component
  3802. */
  3803. TimeAxis.prototype.repaint = function () {
  3804. var asSize = util.option.asSize,
  3805. options = this.options,
  3806. props = this.props;
  3807. var frame = this.frame;
  3808. if (!frame) {
  3809. frame = document.createElement('div');
  3810. this.frame = frame;
  3811. }
  3812. frame.className = 'axis';
  3813. // TODO: custom className?
  3814. // update its size
  3815. this.width = frame.offsetWidth; // TODO: only update the width when the frame is resized
  3816. if (!frame.parentNode) {
  3817. if (!this.parent) {
  3818. throw new Error('Cannot repaint time axis: no parent attached');
  3819. }
  3820. var parentContainer = this.parent.getContainer();
  3821. if (!parentContainer) {
  3822. throw new Error('Cannot repaint time axis: parent has no container element');
  3823. }
  3824. parentContainer.appendChild(frame);
  3825. }
  3826. var parent = frame.parentNode;
  3827. if (parent) {
  3828. // calculate character width and height
  3829. this._calculateCharSize();
  3830. // TODO: recalculate sizes only needed when parent is resized or options is changed
  3831. var orientation = this.getOption('orientation'),
  3832. showMinorLabels = this.getOption('showMinorLabels'),
  3833. showMajorLabels = this.getOption('showMajorLabels');
  3834. // determine the width and height of the elemens for the axis
  3835. var parentHeight = this.parent.height;
  3836. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  3837. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  3838. this.height = props.minorLabelHeight + props.majorLabelHeight;
  3839. props.minorLineHeight = parentHeight + props.minorLabelHeight;
  3840. props.minorLineWidth = 1; // TODO: really calculate width
  3841. props.majorLineHeight = parentHeight + this.height;
  3842. props.majorLineWidth = 1; // TODO: really calculate width
  3843. // take frame offline while updating (is almost twice as fast)
  3844. var beforeChild = frame.nextSibling;
  3845. parent.removeChild(frame);
  3846. if (orientation == 'top') {
  3847. frame.style.top = '0';
  3848. frame.style.left = '0';
  3849. frame.style.bottom = '';
  3850. frame.style.width = asSize(options.width, '100%');
  3851. frame.style.height = this.height + 'px';
  3852. }
  3853. else { // bottom
  3854. frame.style.top = '';
  3855. frame.style.bottom = '0';
  3856. frame.style.left = '0';
  3857. frame.style.width = asSize(options.width, '100%');
  3858. frame.style.height = this.height + 'px';
  3859. }
  3860. this._repaintLabels();
  3861. this._repaintLine();
  3862. // put frame online again
  3863. if (beforeChild) {
  3864. parent.insertBefore(frame, beforeChild);
  3865. }
  3866. else {
  3867. parent.appendChild(frame)
  3868. }
  3869. }
  3870. };
  3871. /**
  3872. * Repaint major and minor text labels and vertical grid lines
  3873. * @private
  3874. */
  3875. TimeAxis.prototype._repaintLabels = function () {
  3876. var orientation = this.getOption('orientation');
  3877. // calculate range and step
  3878. this._updateConversion();
  3879. var start = util.convert(this.range.start, 'Number'),
  3880. end = util.convert(this.range.end, 'Number'),
  3881. minimumStep = this.toTime((this.props.minorCharWidth || 10) * 5).valueOf()
  3882. -this.toTime(0).valueOf();
  3883. var step = new TimeStep(new Date(start), new Date(end), minimumStep);
  3884. this.step = step;
  3885. // Move all DOM elements to a "redundant" list, where they
  3886. // can be picked for re-use, and clear the lists with lines and texts.
  3887. // At the end of the function _repaintLabels, left over elements will be cleaned up
  3888. var dom = this.dom;
  3889. dom.redundant.majorLines = dom.majorLines;
  3890. dom.redundant.majorTexts = dom.majorTexts;
  3891. dom.redundant.minorLines = dom.minorLines;
  3892. dom.redundant.minorTexts = dom.minorTexts;
  3893. dom.majorLines = [];
  3894. dom.majorTexts = [];
  3895. dom.minorLines = [];
  3896. dom.minorTexts = [];
  3897. step.first();
  3898. var xFirstMajorLabel = undefined;
  3899. var max = 0;
  3900. while (step.hasNext() && max < 1000) {
  3901. max++;
  3902. var cur = step.getCurrent(),
  3903. x = this.toScreen(cur),
  3904. isMajor = step.isMajor();
  3905. // TODO: lines must have a width, such that we can create css backgrounds
  3906. if (this.getOption('showMinorLabels')) {
  3907. this._repaintMinorText(x, step.getLabelMinor(), orientation);
  3908. }
  3909. if (isMajor && this.getOption('showMajorLabels')) {
  3910. if (x > 0) {
  3911. if (xFirstMajorLabel == undefined) {
  3912. xFirstMajorLabel = x;
  3913. }
  3914. this._repaintMajorText(x, step.getLabelMajor(), orientation);
  3915. }
  3916. this._repaintMajorLine(x, orientation);
  3917. }
  3918. else {
  3919. this._repaintMinorLine(x, orientation);
  3920. }
  3921. step.next();
  3922. }
  3923. // create a major label on the left when needed
  3924. if (this.getOption('showMajorLabels')) {
  3925. var leftTime = this.toTime(0),
  3926. leftText = step.getLabelMajor(leftTime),
  3927. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  3928. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3929. this._repaintMajorText(0, leftText, orientation);
  3930. }
  3931. }
  3932. // Cleanup leftover DOM elements from the redundant list
  3933. util.forEach(this.dom.redundant, function (arr) {
  3934. while (arr.length) {
  3935. var elem = arr.pop();
  3936. if (elem && elem.parentNode) {
  3937. elem.parentNode.removeChild(elem);
  3938. }
  3939. }
  3940. });
  3941. };
  3942. /**
  3943. * Create a minor label for the axis at position x
  3944. * @param {Number} x
  3945. * @param {String} text
  3946. * @param {String} orientation "top" or "bottom" (default)
  3947. * @private
  3948. */
  3949. TimeAxis.prototype._repaintMinorText = function (x, text, orientation) {
  3950. // reuse redundant label
  3951. var label = this.dom.redundant.minorTexts.shift();
  3952. if (!label) {
  3953. // create new label
  3954. var content = document.createTextNode('');
  3955. label = document.createElement('div');
  3956. label.appendChild(content);
  3957. label.className = 'text minor';
  3958. this.frame.appendChild(label);
  3959. }
  3960. this.dom.minorTexts.push(label);
  3961. label.childNodes[0].nodeValue = text;
  3962. if (orientation == 'top') {
  3963. label.style.top = this.props.minorLabelHeight + 'px';
  3964. label.style.bottom = '';
  3965. }
  3966. else {
  3967. label.style.top = '';
  3968. label.style.bottom = this.props.minorLabelHeight + 'px';
  3969. }
  3970. label.style.left = x + 'px';
  3971. //label.title = title; // TODO: this is a heavy operation
  3972. };
  3973. /**
  3974. * Create a Major label for the axis at position x
  3975. * @param {Number} x
  3976. * @param {String} text
  3977. * @param {String} orientation "top" or "bottom" (default)
  3978. * @private
  3979. */
  3980. TimeAxis.prototype._repaintMajorText = function (x, text, orientation) {
  3981. // reuse redundant label
  3982. var label = this.dom.redundant.majorTexts.shift();
  3983. if (!label) {
  3984. // create label
  3985. var content = document.createTextNode(text);
  3986. label = document.createElement('div');
  3987. label.className = 'text major';
  3988. label.appendChild(content);
  3989. this.frame.appendChild(label);
  3990. }
  3991. this.dom.majorTexts.push(label);
  3992. label.childNodes[0].nodeValue = text;
  3993. //label.title = title; // TODO: this is a heavy operation
  3994. if (orientation == 'top') {
  3995. label.style.top = '0px';
  3996. label.style.bottom = '';
  3997. }
  3998. else {
  3999. label.style.top = '';
  4000. label.style.bottom = '0px';
  4001. }
  4002. label.style.left = x + 'px';
  4003. };
  4004. /**
  4005. * Create a minor line for the axis at position x
  4006. * @param {Number} x
  4007. * @param {String} orientation "top" or "bottom" (default)
  4008. * @private
  4009. */
  4010. TimeAxis.prototype._repaintMinorLine = function (x, orientation) {
  4011. // reuse redundant line
  4012. var line = this.dom.redundant.minorLines.shift();
  4013. if (!line) {
  4014. // create vertical line
  4015. line = document.createElement('div');
  4016. line.className = 'grid vertical minor';
  4017. this.frame.appendChild(line);
  4018. }
  4019. this.dom.minorLines.push(line);
  4020. var props = this.props;
  4021. if (orientation == 'top') {
  4022. line.style.top = this.props.minorLabelHeight + 'px';
  4023. line.style.bottom = '';
  4024. }
  4025. else {
  4026. line.style.top = '';
  4027. line.style.bottom = this.props.minorLabelHeight + 'px';
  4028. }
  4029. line.style.height = props.minorLineHeight + 'px';
  4030. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  4031. };
  4032. /**
  4033. * Create a Major line for the axis at position x
  4034. * @param {Number} x
  4035. * @param {String} orientation "top" or "bottom" (default)
  4036. * @private
  4037. */
  4038. TimeAxis.prototype._repaintMajorLine = function (x, orientation) {
  4039. // reuse redundant line
  4040. var line = this.dom.redundant.majorLines.shift();
  4041. if (!line) {
  4042. // create vertical line
  4043. line = document.createElement('DIV');
  4044. line.className = 'grid vertical major';
  4045. this.frame.appendChild(line);
  4046. }
  4047. this.dom.majorLines.push(line);
  4048. var props = this.props;
  4049. if (orientation == 'top') {
  4050. line.style.top = '0px';
  4051. line.style.bottom = '';
  4052. }
  4053. else {
  4054. line.style.top = '';
  4055. line.style.bottom = '0px';
  4056. }
  4057. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4058. line.style.height = props.majorLineHeight + 'px';
  4059. };
  4060. /**
  4061. * Repaint the horizontal line for the axis
  4062. * @private
  4063. */
  4064. TimeAxis.prototype._repaintLine = function() {
  4065. var line = this.dom.line,
  4066. frame = this.frame,
  4067. orientation = this.getOption('orientation');
  4068. // line before all axis elements
  4069. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4070. if (line) {
  4071. // put this line at the end of all childs
  4072. frame.removeChild(line);
  4073. frame.appendChild(line);
  4074. }
  4075. else {
  4076. // create the axis line
  4077. line = document.createElement('div');
  4078. line.className = 'grid horizontal major';
  4079. frame.appendChild(line);
  4080. this.dom.line = line;
  4081. }
  4082. if (orientation == 'top') {
  4083. line.style.top = this.height + 'px';
  4084. line.style.bottom = '';
  4085. }
  4086. else {
  4087. line.style.top = '';
  4088. line.style.bottom = this.height + 'px';
  4089. }
  4090. }
  4091. else {
  4092. if (line && line.parentElement) {
  4093. frame.removeChild(line.line);
  4094. delete this.dom.line;
  4095. }
  4096. }
  4097. };
  4098. /**
  4099. * Determine the size of text on the axis (both major and minor axis).
  4100. * The size is calculated only once and then cached in this.props.
  4101. * @private
  4102. */
  4103. TimeAxis.prototype._calculateCharSize = function () {
  4104. // determine the char width and height on the minor axis
  4105. if (!('minorCharHeight' in this.props)) {
  4106. var textMinor = document.createTextNode('0');
  4107. var measureCharMinor = document.createElement('DIV');
  4108. measureCharMinor.className = 'text minor measure';
  4109. measureCharMinor.appendChild(textMinor);
  4110. this.frame.appendChild(measureCharMinor);
  4111. this.props.minorCharHeight = measureCharMinor.clientHeight;
  4112. this.props.minorCharWidth = measureCharMinor.clientWidth;
  4113. this.frame.removeChild(measureCharMinor);
  4114. }
  4115. if (!('majorCharHeight' in this.props)) {
  4116. var textMajor = document.createTextNode('0');
  4117. var measureCharMajor = document.createElement('DIV');
  4118. measureCharMajor.className = 'text major measure';
  4119. measureCharMajor.appendChild(textMajor);
  4120. this.frame.appendChild(measureCharMajor);
  4121. this.props.majorCharHeight = measureCharMajor.clientHeight;
  4122. this.props.majorCharWidth = measureCharMajor.clientWidth;
  4123. this.frame.removeChild(measureCharMajor);
  4124. }
  4125. };
  4126. /**
  4127. * Calculate the scale and offset to convert a position on screen to the
  4128. * corresponding date and vice versa.
  4129. * After the method _updateConversion is executed once, the methods toTime
  4130. * and toScreen can be used.
  4131. * @private
  4132. */
  4133. TimeAxis.prototype._updateConversion = function() {
  4134. var range = this.range;
  4135. if (!range) {
  4136. throw new Error('No range configured');
  4137. }
  4138. if (range.conversion) {
  4139. this.conversion = range.conversion(this.width);
  4140. }
  4141. else {
  4142. this.conversion = Range.conversion(range.start, range.end, this.width);
  4143. }
  4144. };
  4145. /**
  4146. * Snap a date to a rounded value.
  4147. * The snap intervals are dependent on the current scale and step.
  4148. * @param {Date} date the date to be snapped.
  4149. * @return {Date} snappedDate
  4150. */
  4151. TimeAxis.prototype.snap = function snap (date) {
  4152. return this.step.snap(date);
  4153. };
  4154. /**
  4155. * A current time bar
  4156. * @param {Component} parent
  4157. * @param {Component[]} [depends] Components on which this components depends
  4158. * (except for the parent)
  4159. * @param {Object} [options] Available parameters:
  4160. * {Boolean} [showCurrentTime]
  4161. * @constructor CurrentTime
  4162. * @extends Component
  4163. */
  4164. function CurrentTime (parent, depends, options) {
  4165. this.id = util.randomUUID();
  4166. this.parent = parent;
  4167. this.depends = depends;
  4168. this.options = options || {};
  4169. this.defaultOptions = {
  4170. showCurrentTime: false
  4171. };
  4172. }
  4173. CurrentTime.prototype = new Component();
  4174. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  4175. /**
  4176. * Get the container element of the bar, which can be used by a child to
  4177. * add its own widgets.
  4178. * @returns {HTMLElement} container
  4179. */
  4180. CurrentTime.prototype.getContainer = function () {
  4181. return this.frame;
  4182. };
  4183. /**
  4184. * Repaint the component
  4185. * @return {Boolean} changed
  4186. */
  4187. CurrentTime.prototype.repaint = function () {
  4188. var bar = this.frame,
  4189. parent = this.parent,
  4190. parentContainer = parent.parent.getContainer();
  4191. if (!parent) {
  4192. throw new Error('Cannot repaint bar: no parent attached');
  4193. }
  4194. if (!parentContainer) {
  4195. throw new Error('Cannot repaint bar: parent has no container element');
  4196. }
  4197. if (!this.getOption('showCurrentTime')) {
  4198. if (bar) {
  4199. parentContainer.removeChild(bar);
  4200. delete this.frame;
  4201. }
  4202. return false;
  4203. }
  4204. if (!bar) {
  4205. bar = document.createElement('div');
  4206. bar.className = 'currenttime';
  4207. bar.style.position = 'absolute';
  4208. bar.style.top = '0px';
  4209. bar.style.height = '100%';
  4210. parentContainer.appendChild(bar);
  4211. this.frame = bar;
  4212. }
  4213. if (!parent.conversion) {
  4214. parent._updateConversion();
  4215. }
  4216. var now = new Date();
  4217. var x = parent.toScreen(now);
  4218. bar.style.left = x + 'px';
  4219. bar.title = 'Current time: ' + now;
  4220. // start a timer to adjust for the new time
  4221. if (this.currentTimeTimer !== undefined) {
  4222. clearTimeout(this.currentTimeTimer);
  4223. delete this.currentTimeTimer;
  4224. }
  4225. var timeline = this;
  4226. var interval = 1 / parent.conversion.scale / 2;
  4227. if (interval < 30) {
  4228. interval = 30;
  4229. }
  4230. this.currentTimeTimer = setTimeout(function() {
  4231. timeline.repaint();
  4232. }, interval);
  4233. return false;
  4234. };
  4235. /**
  4236. * A custom time bar
  4237. * @param {Component} parent
  4238. * @param {Component[]} [depends] Components on which this components depends
  4239. * (except for the parent)
  4240. * @param {Object} [options] Available parameters:
  4241. * {Boolean} [showCustomTime]
  4242. * @constructor CustomTime
  4243. * @extends Component
  4244. */
  4245. function CustomTime (parent, depends, options) {
  4246. this.id = util.randomUUID();
  4247. this.parent = parent;
  4248. this.depends = depends;
  4249. this.options = options || {};
  4250. this.defaultOptions = {
  4251. showCustomTime: false
  4252. };
  4253. this.customTime = new Date();
  4254. this.eventParams = {}; // stores state parameters while dragging the bar
  4255. }
  4256. CustomTime.prototype = new Component();
  4257. Emitter(CustomTime.prototype);
  4258. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4259. /**
  4260. * Get the container element of the bar, which can be used by a child to
  4261. * add its own widgets.
  4262. * @returns {HTMLElement} container
  4263. */
  4264. CustomTime.prototype.getContainer = function () {
  4265. return this.frame;
  4266. };
  4267. /**
  4268. * Repaint the component
  4269. * @return {Boolean} changed
  4270. */
  4271. CustomTime.prototype.repaint = function () {
  4272. var bar = this.frame,
  4273. parent = this.parent;
  4274. if (!parent) {
  4275. throw new Error('Cannot repaint bar: no parent attached');
  4276. }
  4277. var parentContainer = parent.parent.getContainer();
  4278. if (!parentContainer) {
  4279. throw new Error('Cannot repaint bar: parent has no container element');
  4280. }
  4281. if (!this.getOption('showCustomTime')) {
  4282. if (bar) {
  4283. parentContainer.removeChild(bar);
  4284. delete this.frame;
  4285. }
  4286. return false;
  4287. }
  4288. if (!bar) {
  4289. bar = document.createElement('div');
  4290. bar.className = 'customtime';
  4291. bar.style.position = 'absolute';
  4292. bar.style.top = '0px';
  4293. bar.style.height = '100%';
  4294. parentContainer.appendChild(bar);
  4295. var drag = document.createElement('div');
  4296. drag.style.position = 'relative';
  4297. drag.style.top = '0px';
  4298. drag.style.left = '-10px';
  4299. drag.style.height = '100%';
  4300. drag.style.width = '20px';
  4301. bar.appendChild(drag);
  4302. this.frame = bar;
  4303. // attach event listeners
  4304. this.hammer = Hammer(bar, {
  4305. prevent_default: true
  4306. });
  4307. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4308. this.hammer.on('drag', this._onDrag.bind(this));
  4309. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4310. }
  4311. if (!parent.conversion) {
  4312. parent._updateConversion();
  4313. }
  4314. var x = parent.toScreen(this.customTime);
  4315. bar.style.left = x + 'px';
  4316. bar.title = 'Time: ' + this.customTime;
  4317. return false;
  4318. };
  4319. /**
  4320. * Set custom time.
  4321. * @param {Date} time
  4322. */
  4323. CustomTime.prototype.setCustomTime = function(time) {
  4324. this.customTime = new Date(time.valueOf());
  4325. this.repaint();
  4326. };
  4327. /**
  4328. * Retrieve the current custom time.
  4329. * @return {Date} customTime
  4330. */
  4331. CustomTime.prototype.getCustomTime = function() {
  4332. return new Date(this.customTime.valueOf());
  4333. };
  4334. /**
  4335. * Start moving horizontally
  4336. * @param {Event} event
  4337. * @private
  4338. */
  4339. CustomTime.prototype._onDragStart = function(event) {
  4340. this.eventParams.customTime = this.customTime;
  4341. event.stopPropagation();
  4342. event.preventDefault();
  4343. };
  4344. /**
  4345. * Perform moving operating.
  4346. * @param {Event} event
  4347. * @private
  4348. */
  4349. CustomTime.prototype._onDrag = function (event) {
  4350. var deltaX = event.gesture.deltaX,
  4351. x = this.parent.toScreen(this.eventParams.customTime) + deltaX,
  4352. time = this.parent.toTime(x);
  4353. this.setCustomTime(time);
  4354. // fire a timechange event
  4355. if (this.controller) {
  4356. this.controller.emit('timechange', {
  4357. time: this.customTime
  4358. })
  4359. }
  4360. event.stopPropagation();
  4361. event.preventDefault();
  4362. };
  4363. /**
  4364. * Stop moving operating.
  4365. * @param {event} event
  4366. * @private
  4367. */
  4368. CustomTime.prototype._onDragEnd = function (event) {
  4369. // fire a timechanged event
  4370. if (this.controller) {
  4371. this.controller.emit('timechanged', {
  4372. time: this.customTime
  4373. })
  4374. }
  4375. event.stopPropagation();
  4376. event.preventDefault();
  4377. };
  4378. /**
  4379. * An ItemSet holds a set of items and ranges which can be displayed in a
  4380. * range. The width is determined by the parent of the ItemSet, and the height
  4381. * is determined by the size of the items.
  4382. * @param {Component} parent
  4383. * @param {Component[]} [depends] Components on which this components depends
  4384. * (except for the parent)
  4385. * @param {Object} [options] See ItemSet.setOptions for the available
  4386. * options.
  4387. * @constructor ItemSet
  4388. * @extends Panel
  4389. */
  4390. // TODO: improve performance by replacing all Array.forEach with a for loop
  4391. function ItemSet(parent, depends, options) {
  4392. this.id = util.randomUUID();
  4393. this.parent = parent;
  4394. this.depends = depends;
  4395. // event listeners
  4396. this.eventListeners = {
  4397. dragstart: this._onDragStart.bind(this),
  4398. drag: this._onDrag.bind(this),
  4399. dragend: this._onDragEnd.bind(this)
  4400. };
  4401. // one options object is shared by this itemset and all its items
  4402. this.options = options || {};
  4403. this.itemOptions = Object.create(this.options);
  4404. this.dom = {};
  4405. var me = this;
  4406. this.itemsData = null; // DataSet
  4407. this.range = null; // Range or Object {start: number, end: number}
  4408. // data change listeners
  4409. this.listeners = {
  4410. 'add': function (event, params, senderId) {
  4411. if (senderId != me.id) me._onAdd(params.items);
  4412. },
  4413. 'update': function (event, params, senderId) {
  4414. if (senderId != me.id) me._onUpdate(params.items);
  4415. },
  4416. 'remove': function (event, params, senderId) {
  4417. if (senderId != me.id) me._onRemove(params.items);
  4418. }
  4419. };
  4420. this.items = {}; // object with an Item for every data item
  4421. this.orderedItems = {
  4422. byStart: [],
  4423. byEnd: []
  4424. };
  4425. this.visibleItems = []; // visible, ordered items
  4426. this.visibleItemsStart = 0; // start index of visible items in this.orderedItems // TODO: cleanup
  4427. this.visibleItemsEnd = 0; // start index of visible items in this.orderedItems // TODO: cleanup
  4428. this.selection = []; // list with the ids of all selected nodes
  4429. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4430. this.stack = new Stack(Object.create(this.options));
  4431. this.conversion = null;
  4432. this.touchParams = {}; // stores properties while dragging
  4433. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4434. }
  4435. ItemSet.prototype = new Panel();
  4436. // available item types will be registered here
  4437. ItemSet.types = {
  4438. box: ItemBox,
  4439. range: ItemRange,
  4440. rangeoverflow: ItemRangeOverflow,
  4441. point: ItemPoint
  4442. };
  4443. /**
  4444. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4445. * @param {Object} [options] The following options are available:
  4446. * {String | function} [className]
  4447. * class name for the itemset
  4448. * {String} [type]
  4449. * Default type for the items. Choose from 'box'
  4450. * (default), 'point', or 'range'. The default
  4451. * Style can be overwritten by individual items.
  4452. * {String} align
  4453. * Alignment for the items, only applicable for
  4454. * ItemBox. Choose 'center' (default), 'left', or
  4455. * 'right'.
  4456. * {String} orientation
  4457. * Orientation of the item set. Choose 'top' or
  4458. * 'bottom' (default).
  4459. * {Number} margin.axis
  4460. * Margin between the axis and the items in pixels.
  4461. * Default is 20.
  4462. * {Number} margin.item
  4463. * Margin between items in pixels. Default is 10.
  4464. * {Number} padding
  4465. * Padding of the contents of an item in pixels.
  4466. * Must correspond with the items css. Default is 5.
  4467. * {Function} snap
  4468. * Function to let items snap to nice dates when
  4469. * dragging items.
  4470. */
  4471. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4472. /**
  4473. * Set controller for this component
  4474. * @param {Controller | null} controller
  4475. */
  4476. ItemSet.prototype.setController = function setController (controller) {
  4477. var event;
  4478. // unregister old event listeners
  4479. if (this.controller) {
  4480. for (event in this.eventListeners) {
  4481. if (this.eventListeners.hasOwnProperty(event)) {
  4482. this.controller.off(event, this.eventListeners[event]);
  4483. }
  4484. }
  4485. }
  4486. this.controller = controller || null;
  4487. // register new event listeners
  4488. if (this.controller) {
  4489. for (event in this.eventListeners) {
  4490. if (this.eventListeners.hasOwnProperty(event)) {
  4491. this.controller.on(event, this.eventListeners[event]);
  4492. }
  4493. }
  4494. }
  4495. };
  4496. /**
  4497. * Set range (start and end).
  4498. * @param {Range | Object} range A Range or an object containing start and end.
  4499. */
  4500. ItemSet.prototype.setRange = function setRange(range) {
  4501. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4502. throw new TypeError('Range must be an instance of Range, ' +
  4503. 'or an object containing start and end.');
  4504. }
  4505. this.range = range;
  4506. };
  4507. /**
  4508. * Set selected items by their id. Replaces the current selection
  4509. * Unknown id's are silently ignored.
  4510. * @param {Array} [ids] An array with zero or more id's of the items to be
  4511. * selected. If ids is an empty array, all items will be
  4512. * unselected.
  4513. */
  4514. ItemSet.prototype.setSelection = function setSelection(ids) {
  4515. var i, ii, id, item;
  4516. if (ids) {
  4517. if (!Array.isArray(ids)) {
  4518. throw new TypeError('Array expected');
  4519. }
  4520. // unselect currently selected items
  4521. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4522. id = this.selection[i];
  4523. item = this.items[id];
  4524. if (item) item.unselect();
  4525. }
  4526. // select items
  4527. this.selection = [];
  4528. for (i = 0, ii = ids.length; i < ii; i++) {
  4529. id = ids[i];
  4530. item = this.items[id];
  4531. if (item) {
  4532. this.selection.push(id);
  4533. item.select();
  4534. }
  4535. }
  4536. if (this.controller) {
  4537. this.requestRepaint();
  4538. }
  4539. }
  4540. };
  4541. /**
  4542. * Get the selected items by their id
  4543. * @return {Array} ids The ids of the selected items
  4544. */
  4545. ItemSet.prototype.getSelection = function getSelection() {
  4546. return this.selection.concat([]);
  4547. };
  4548. /**
  4549. * Deselect a selected item
  4550. * @param {String | Number} id
  4551. * @private
  4552. */
  4553. ItemSet.prototype._deselect = function _deselect(id) {
  4554. var selection = this.selection;
  4555. for (var i = 0, ii = selection.length; i < ii; i++) {
  4556. if (selection[i] == id) { // non-strict comparison!
  4557. selection.splice(i, 1);
  4558. break;
  4559. }
  4560. }
  4561. };
  4562. /**
  4563. * Repaint the component
  4564. */
  4565. ItemSet.prototype.repaint = function repaint() {
  4566. var asSize = util.option.asSize,
  4567. asNumber = util.option.asNumber,
  4568. options = this.options,
  4569. orientation = this.getOption('orientation'),
  4570. frame = this.frame;
  4571. this._updateConversion();
  4572. if (!frame) {
  4573. frame = document.createElement('div');
  4574. frame.className = 'itemset';
  4575. frame['timeline-itemset'] = this;
  4576. var className = options.className;
  4577. if (className) {
  4578. util.addClassName(frame, util.option.asString(className));
  4579. }
  4580. // create background panel
  4581. var background = document.createElement('div');
  4582. background.className = 'background';
  4583. frame.appendChild(background);
  4584. this.dom.background = background;
  4585. // create foreground panel
  4586. var foreground = document.createElement('div');
  4587. foreground.className = 'foreground';
  4588. frame.appendChild(foreground);
  4589. this.dom.foreground = foreground;
  4590. // create axis panel
  4591. var axis = document.createElement('div');
  4592. axis.className = 'itemset-axis';
  4593. //frame.appendChild(axis);
  4594. this.dom.axis = axis;
  4595. this.frame = frame;
  4596. }
  4597. if (!this.parent) {
  4598. throw new Error('Cannot repaint itemset: no parent attached');
  4599. }
  4600. var parentContainer = this.parent.getContainer();
  4601. if (!parentContainer) {
  4602. throw new Error('Cannot repaint itemset: parent has no container element');
  4603. }
  4604. if (!frame.parentNode) {
  4605. parentContainer.appendChild(frame);
  4606. }
  4607. if (!this.dom.axis.parentNode) {
  4608. parentContainer.appendChild(this.dom.axis);
  4609. }
  4610. // check whether zoomed (in that case we need to re-stack everything)
  4611. var visibleInterval = this.range.end - this.range.start;
  4612. var zoomed = this.visibleInterval != visibleInterval;
  4613. this.visibleInterval = visibleInterval;
  4614. /* TODO: implement+fix smarter way to update visible items
  4615. // find the first visible item
  4616. // TODO: use faster search, not linear
  4617. var byEnd = this.orderedItems.byEnd;
  4618. var start = 0;
  4619. var item = null;
  4620. while ((item = byEnd[start]) &&
  4621. (('end' in item.data) ? item.data.end : item.data.start) < this.range.start) {
  4622. start++;
  4623. }
  4624. // find the last visible item
  4625. // TODO: use faster search, not linear
  4626. var byStart = this.orderedItems.byStart;
  4627. var end = 0;
  4628. while ((item = byStart[end]) && item.data.start < this.range.end) {
  4629. end++;
  4630. }
  4631. console.log('visible items', start, end); // TODO: cleanup
  4632. console.log('visible item ids', byStart[start] && byStart[start].id, byEnd[end-1] && byEnd[end-1].id); // TODO: cleanup
  4633. this.visibleItems = [];
  4634. var i = start;
  4635. item = byStart[i];
  4636. var lastItem = byEnd[end];
  4637. while (item && item !== lastItem) {
  4638. this.visibleItems.push(item);
  4639. item = byStart[++i];
  4640. }
  4641. this.stack.order(this.visibleItems);
  4642. // show visible items
  4643. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  4644. item = this.visibleItems[i];
  4645. if (!item.displayed) item.show();
  4646. item.top = null; // reset stacking position
  4647. // reposition item horizontally
  4648. item.repositionX();
  4649. }
  4650. */
  4651. // simple, brute force calculation of visible items
  4652. // TODO: replace with a faster, more sophisticated solution
  4653. this.visibleItems = [];
  4654. for (var id in this.items) {
  4655. if (this.items.hasOwnProperty(id)) {
  4656. var item = this.items[id];
  4657. if (item.isVisible(this.range)) {
  4658. if (!item.displayed) item.show();
  4659. // reset stacking position
  4660. if (zoomed) item.top = null;
  4661. // reposition item horizontally
  4662. item.repositionX();
  4663. this.visibleItems.push(item);
  4664. }
  4665. else {
  4666. if (item.displayed) item.hide();
  4667. }
  4668. }
  4669. }
  4670. // reposition visible items vertically
  4671. //this.stack.order(this.visibleItems); // TODO: solve ordering issue
  4672. this.stack.stack(this.visibleItems);
  4673. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  4674. this.visibleItems[i].repositionY();
  4675. }
  4676. // recalculate the height of the itemset
  4677. var marginAxis = (options.margin && 'axis' in options.margin) ? options.margin.axis : this.itemOptions.margin.axis,
  4678. marginItem = (options.margin && 'item' in options.margin) ? options.margin.item : this.itemOptions.margin.item,
  4679. maxHeight = asNumber(options.maxHeight),
  4680. fixedHeight = (asSize(options.height) != null),
  4681. height;
  4682. // recalculate the frames size and position
  4683. // TODO: request frame's actual top, left, width only when size is changed (mark as dirty)
  4684. if (fixedHeight) {
  4685. height = frame.offsetHeight;
  4686. }
  4687. else {
  4688. // height is not specified, determine the height from the height and positioned items
  4689. var visibleItems = this.visibleItems;
  4690. if (visibleItems.length) {
  4691. var min = visibleItems[0].top;
  4692. var max = visibleItems[0].top + visibleItems[0].height;
  4693. util.forEach(visibleItems, function (item) {
  4694. min = Math.min(min, item.top);
  4695. max = Math.max(max, (item.top + item.height));
  4696. });
  4697. height = (max - min) + marginAxis + marginItem;
  4698. }
  4699. else {
  4700. height = marginAxis + marginItem;
  4701. }
  4702. }
  4703. if (maxHeight != null) {
  4704. height = Math.min(height, maxHeight);
  4705. }
  4706. this.top = frame.offsetTop;
  4707. this.left = frame.offsetLeft;
  4708. this.width = frame.offsetWidth;
  4709. this.height = height;
  4710. // reposition frame
  4711. frame.style.left = asSize(options.left, '0px');
  4712. frame.style.top = asSize(options.top, '');
  4713. frame.style.bottom = asSize(options.bottom, '');
  4714. frame.style.width = asSize(options.width, '100%');
  4715. frame.style.height = asSize(options.height, this.height + 'px');
  4716. // reposition axis
  4717. this.dom.axis.style.left = asSize(options.left, '0px');
  4718. this.dom.axis.style.width = asSize(options.width, '100%');
  4719. if (orientation == 'bottom') {
  4720. this.dom.axis.style.top = (this.top + this.height) + 'px';
  4721. }
  4722. else { // orientation == 'top'
  4723. this.dom.axis.style.top = this.top + 'px';
  4724. }
  4725. return false;
  4726. };
  4727. /**
  4728. * Get the foreground container element
  4729. * @return {HTMLElement} foreground
  4730. */
  4731. ItemSet.prototype.getForeground = function getForeground() {
  4732. return this.dom.foreground;
  4733. };
  4734. /**
  4735. * Get the background container element
  4736. * @return {HTMLElement} background
  4737. */
  4738. ItemSet.prototype.getBackground = function getBackground() {
  4739. return this.dom.background;
  4740. };
  4741. /**
  4742. * Get the axis container element
  4743. * @return {HTMLElement} axis
  4744. */
  4745. ItemSet.prototype.getAxis = function getAxis() {
  4746. return this.dom.axis;
  4747. };
  4748. /**
  4749. * Hide this component from the DOM
  4750. */
  4751. ItemSet.prototype.hide = function hide() {
  4752. // remove the DOM
  4753. if (this.frame && this.frame.parentNode) {
  4754. this.frame.parentNode.removeChild(this.frame);
  4755. }
  4756. if (this.dom.axis && this.dom.axis.parentNode) {
  4757. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4758. }
  4759. };
  4760. /**
  4761. * Set items
  4762. * @param {vis.DataSet | null} items
  4763. */
  4764. ItemSet.prototype.setItems = function setItems(items) {
  4765. var me = this,
  4766. ids,
  4767. oldItemsData = this.itemsData;
  4768. // replace the dataset
  4769. if (!items) {
  4770. this.itemsData = null;
  4771. }
  4772. else if (items instanceof DataSet || items instanceof DataView) {
  4773. this.itemsData = items;
  4774. }
  4775. else {
  4776. throw new TypeError('Data must be an instance of DataSet');
  4777. }
  4778. if (oldItemsData) {
  4779. // unsubscribe from old dataset
  4780. util.forEach(this.listeners, function (callback, event) {
  4781. oldItemsData.unsubscribe(event, callback);
  4782. });
  4783. // remove all drawn items
  4784. ids = oldItemsData.getIds();
  4785. this._onRemove(ids);
  4786. }
  4787. if (this.itemsData) {
  4788. // subscribe to new dataset
  4789. var id = this.id;
  4790. util.forEach(this.listeners, function (callback, event) {
  4791. me.itemsData.on(event, callback, id);
  4792. });
  4793. // draw all new items
  4794. ids = this.itemsData.getIds();
  4795. this._onAdd(ids);
  4796. }
  4797. };
  4798. /**
  4799. * Get the current items items
  4800. * @returns {vis.DataSet | null}
  4801. */
  4802. ItemSet.prototype.getItems = function getItems() {
  4803. return this.itemsData;
  4804. };
  4805. /**
  4806. * Remove an item by its id
  4807. * @param {String | Number} id
  4808. */
  4809. ItemSet.prototype.removeItem = function removeItem (id) {
  4810. var item = this.itemsData.get(id),
  4811. dataset = this._myDataSet();
  4812. if (item) {
  4813. // confirm deletion
  4814. this.options.onRemove(item, function (item) {
  4815. if (item) {
  4816. dataset.remove(item);
  4817. }
  4818. });
  4819. }
  4820. };
  4821. /**
  4822. * Handle updated items
  4823. * @param {Number[]} ids
  4824. * @private
  4825. */
  4826. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4827. var me = this,
  4828. items = this.items,
  4829. itemOptions = this.itemOptions;
  4830. ids.forEach(function (id) {
  4831. var itemData = me.itemsData.get(id),
  4832. item = items[id],
  4833. type = itemData.type ||
  4834. (itemData.start && itemData.end && 'range') ||
  4835. options.type ||
  4836. 'box';
  4837. var constructor = ItemSet.types[type];
  4838. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4839. if (item) {
  4840. // update item
  4841. if (!constructor || !(item instanceof constructor)) {
  4842. // item type has changed, hide and delete the item
  4843. if (!('hide' in item)) {
  4844. console.log('item has no hide?!', item, Object.keys(items))
  4845. console.trace()
  4846. }
  4847. item.hide();
  4848. item = null;
  4849. }
  4850. else {
  4851. item.data = itemData; // TODO: create a method item.setData ?
  4852. }
  4853. }
  4854. if (!item) {
  4855. // create item
  4856. if (constructor) {
  4857. item = new constructor(me, itemData, options, itemOptions);
  4858. item.id = id;
  4859. }
  4860. else {
  4861. throw new TypeError('Unknown item type "' + type + '"');
  4862. }
  4863. }
  4864. me.items[id] = item;
  4865. });
  4866. this._order();
  4867. this.repaint();
  4868. };
  4869. /**
  4870. * Handle added items
  4871. * @param {Number[]} ids
  4872. * @private
  4873. */
  4874. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  4875. /**
  4876. * Handle removed items
  4877. * @param {Number[]} ids
  4878. * @private
  4879. */
  4880. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4881. var me = this;
  4882. ids.forEach(function (id) {
  4883. var item = me.items[id];
  4884. if (item) {
  4885. item.hide(); // TODO: only hide when displayed
  4886. delete me.items[id];
  4887. delete me.visibleItems[id];
  4888. }
  4889. });
  4890. this._order();
  4891. };
  4892. /**
  4893. * Order the items
  4894. * @private
  4895. */
  4896. ItemSet.prototype._order = function _order() {
  4897. var array = util.toArray(this.items);
  4898. this.orderedItems.byStart = array;
  4899. this.orderedItems.byEnd = [].concat(array);
  4900. // reorder the items
  4901. this.stack.orderByStart(this.orderedItems.byStart);
  4902. this.stack.orderByEnd(this.orderedItems.byEnd);
  4903. // TODO: cleanup
  4904. //console.log('byStart', this.orderedItems.byStart.map(function (item) {return item.id}))
  4905. //console.log('byEnd', this.orderedItems.byEnd.map(function (item) {return item.id}))
  4906. }
  4907. /**
  4908. * Calculate the scale and offset to convert a position on screen to the
  4909. * corresponding date and vice versa.
  4910. * After the method _updateConversion is executed once, the methods toTime
  4911. * and toScreen can be used.
  4912. * @private
  4913. */
  4914. ItemSet.prototype._updateConversion = function _updateConversion() {
  4915. var range = this.range;
  4916. if (!range) {
  4917. throw new Error('No range configured');
  4918. }
  4919. if (range.conversion) {
  4920. this.conversion = range.conversion(this.width);
  4921. }
  4922. else {
  4923. this.conversion = Range.conversion(range.start, range.end, this.width);
  4924. }
  4925. };
  4926. /**
  4927. * Convert a position on screen (pixels) to a datetime
  4928. * Before this method can be used, the method _updateConversion must be
  4929. * executed once.
  4930. * @param {int} x Position on the screen in pixels
  4931. * @return {Date} time The datetime the corresponds with given position x
  4932. */
  4933. ItemSet.prototype.toTime = function toTime(x) {
  4934. var conversion = this.conversion;
  4935. return new Date(x / conversion.scale + conversion.offset);
  4936. };
  4937. /**
  4938. * Convert a datetime (Date object) into a position on the screen
  4939. * Before this method can be used, the method _updateConversion must be
  4940. * executed once.
  4941. * @param {Date} time A date
  4942. * @return {int} x The position on the screen in pixels which corresponds
  4943. * with the given date.
  4944. */
  4945. ItemSet.prototype.toScreen = function toScreen(time) {
  4946. var conversion = this.conversion;
  4947. return (time.valueOf() - conversion.offset) * conversion.scale;
  4948. };
  4949. /**
  4950. * Start dragging the selected events
  4951. * @param {Event} event
  4952. * @private
  4953. */
  4954. ItemSet.prototype._onDragStart = function (event) {
  4955. if (!this.options.editable) {
  4956. return;
  4957. }
  4958. var item = ItemSet.itemFromTarget(event),
  4959. me = this;
  4960. if (item && item.selected) {
  4961. var dragLeftItem = event.target.dragLeftItem;
  4962. var dragRightItem = event.target.dragRightItem;
  4963. if (dragLeftItem) {
  4964. this.touchParams.itemProps = [{
  4965. item: dragLeftItem,
  4966. start: item.data.start.valueOf()
  4967. }];
  4968. }
  4969. else if (dragRightItem) {
  4970. this.touchParams.itemProps = [{
  4971. item: dragRightItem,
  4972. end: item.data.end.valueOf()
  4973. }];
  4974. }
  4975. else {
  4976. this.touchParams.itemProps = this.getSelection().map(function (id) {
  4977. var item = me.items[id];
  4978. var props = {
  4979. item: item
  4980. };
  4981. if ('start' in item.data) {
  4982. props.start = item.data.start.valueOf()
  4983. }
  4984. if ('end' in item.data) {
  4985. props.end = item.data.end.valueOf()
  4986. }
  4987. return props;
  4988. });
  4989. }
  4990. event.stopPropagation();
  4991. }
  4992. };
  4993. /**
  4994. * Drag selected items
  4995. * @param {Event} event
  4996. * @private
  4997. */
  4998. ItemSet.prototype._onDrag = function (event) {
  4999. if (this.touchParams.itemProps) {
  5000. var snap = this.options.snap || null,
  5001. deltaX = event.gesture.deltaX,
  5002. offset = deltaX / this.conversion.scale;
  5003. // move
  5004. this.touchParams.itemProps.forEach(function (props) {
  5005. if ('start' in props) {
  5006. var start = new Date(props.start + offset);
  5007. props.item.data.start = snap ? snap(start) : start;
  5008. }
  5009. if ('end' in props) {
  5010. var end = new Date(props.end + offset);
  5011. props.item.data.end = snap ? snap(end) : end;
  5012. }
  5013. });
  5014. // TODO: implement onMoving handler
  5015. // TODO: implement dragging from one group to another
  5016. this.repaint();
  5017. event.stopPropagation();
  5018. }
  5019. };
  5020. /**
  5021. * End of dragging selected items
  5022. * @param {Event} event
  5023. * @private
  5024. */
  5025. ItemSet.prototype._onDragEnd = function (event) {
  5026. if (this.touchParams.itemProps) {
  5027. // prepare a change set for the changed items
  5028. var changes = [],
  5029. me = this,
  5030. dataset = this._myDataSet();
  5031. this.touchParams.itemProps.forEach(function (props) {
  5032. var id = props.item.id,
  5033. item = me.itemsData.get(id);
  5034. var changed = false;
  5035. if ('start' in props.item.data) {
  5036. changed = (props.start != props.item.data.start.valueOf());
  5037. item.start = util.convert(props.item.data.start, dataset.convert['start']);
  5038. }
  5039. if ('end' in props.item.data) {
  5040. changed = changed || (props.end != props.item.data.end.valueOf());
  5041. item.end = util.convert(props.item.data.end, dataset.convert['end']);
  5042. }
  5043. // only apply changes when start or end is actually changed
  5044. if (changed) {
  5045. me.options.onMove(item, function (item) {
  5046. if (item) {
  5047. // apply changes
  5048. changes.push(item);
  5049. }
  5050. else {
  5051. // restore original values
  5052. if ('start' in props) props.item.data.start = props.start;
  5053. if ('end' in props) props.item.data.end = props.end;
  5054. me.repaint();
  5055. }
  5056. });
  5057. }
  5058. });
  5059. this.touchParams.itemProps = null;
  5060. // apply the changes to the data (if there are changes)
  5061. if (changes.length) {
  5062. dataset.update(changes);
  5063. }
  5064. event.stopPropagation();
  5065. }
  5066. };
  5067. /**
  5068. * Find an item from an event target:
  5069. * searches for the attribute 'timeline-item' in the event target's element tree
  5070. * @param {Event} event
  5071. * @return {Item | null} item
  5072. */
  5073. ItemSet.itemFromTarget = function itemFromTarget (event) {
  5074. var target = event.target;
  5075. while (target) {
  5076. if (target.hasOwnProperty('timeline-item')) {
  5077. return target['timeline-item'];
  5078. }
  5079. target = target.parentNode;
  5080. }
  5081. return null;
  5082. };
  5083. /**
  5084. * Find the ItemSet from an event target:
  5085. * searches for the attribute 'timeline-itemset' in the event target's element tree
  5086. * @param {Event} event
  5087. * @return {ItemSet | null} item
  5088. */
  5089. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  5090. var target = event.target;
  5091. while (target) {
  5092. if (target.hasOwnProperty('timeline-itemset')) {
  5093. return target['timeline-itemset'];
  5094. }
  5095. target = target.parentNode;
  5096. }
  5097. return null;
  5098. };
  5099. /**
  5100. * Find the DataSet to which this ItemSet is connected
  5101. * @returns {null | DataSet} dataset
  5102. * @private
  5103. */
  5104. ItemSet.prototype._myDataSet = function _myDataSet() {
  5105. // find the root DataSet
  5106. var dataset = this.itemsData;
  5107. while (dataset instanceof DataView) {
  5108. dataset = dataset.data;
  5109. }
  5110. return dataset;
  5111. };
  5112. /**
  5113. * @constructor Item
  5114. * @param {ItemSet} parent
  5115. * @param {Object} data Object containing (optional) parameters type,
  5116. * start, end, content, group, className.
  5117. * @param {Object} [options] Options to set initial property values
  5118. * @param {Object} [defaultOptions] default options
  5119. * // TODO: describe available options
  5120. */
  5121. function Item (parent, data, options, defaultOptions) {
  5122. this.parent = parent;
  5123. this.data = data;
  5124. this.dom = null;
  5125. this.options = options || {};
  5126. this.defaultOptions = defaultOptions || {};
  5127. this.selected = false;
  5128. this.displayed = false;
  5129. this.dirty = true;
  5130. this.top = null;
  5131. this.left = null;
  5132. this.width = null;
  5133. this.height = null;
  5134. }
  5135. /**
  5136. * Select current item
  5137. */
  5138. Item.prototype.select = function select() {
  5139. this.selected = true;
  5140. if (this.displayed) this.repaint();
  5141. };
  5142. /**
  5143. * Unselect current item
  5144. */
  5145. Item.prototype.unselect = function unselect() {
  5146. this.selected = false;
  5147. if (this.displayed) this.repaint();
  5148. };
  5149. /**
  5150. * Show the Item in the DOM (when not already visible)
  5151. * @return {Boolean} changed
  5152. */
  5153. Item.prototype.show = function show() {
  5154. return false;
  5155. };
  5156. /**
  5157. * Hide the Item from the DOM (when visible)
  5158. * @return {Boolean} changed
  5159. */
  5160. Item.prototype.hide = function hide() {
  5161. return false;
  5162. };
  5163. /**
  5164. * Repaint the item
  5165. */
  5166. Item.prototype.repaint = function repaint() {
  5167. // should be implemented by the item
  5168. };
  5169. /**
  5170. * Reposition the Item horizontally
  5171. */
  5172. Item.prototype.repositionX = function repositionX() {
  5173. // should be implemented by the item
  5174. };
  5175. /**
  5176. * Reposition the Item vertically
  5177. */
  5178. Item.prototype.repositionY = function repositionY() {
  5179. // should be implemented by the item
  5180. };
  5181. /**
  5182. * Repaint a delete button on the top right of the item when the item is selected
  5183. * @param {HTMLElement} anchor
  5184. * @private
  5185. */
  5186. Item.prototype._repaintDeleteButton = function (anchor) {
  5187. if (this.selected && this.options.editable && !this.dom.deleteButton) {
  5188. // create and show button
  5189. var parent = this.parent;
  5190. var id = this.id;
  5191. var deleteButton = document.createElement('div');
  5192. deleteButton.className = 'delete';
  5193. deleteButton.title = 'Delete this item';
  5194. Hammer(deleteButton, {
  5195. preventDefault: true
  5196. }).on('tap', function (event) {
  5197. parent.removeItem(id);
  5198. event.stopPropagation();
  5199. });
  5200. anchor.appendChild(deleteButton);
  5201. this.dom.deleteButton = deleteButton;
  5202. }
  5203. else if (!this.selected && this.dom.deleteButton) {
  5204. // remove button
  5205. if (this.dom.deleteButton.parentNode) {
  5206. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5207. }
  5208. this.dom.deleteButton = null;
  5209. }
  5210. };
  5211. /**
  5212. * @constructor ItemBox
  5213. * @extends Item
  5214. * @param {ItemSet} parent
  5215. * @param {Object} data Object containing parameters start
  5216. * content, className.
  5217. * @param {Object} [options] Options to set initial property values
  5218. * @param {Object} [defaultOptions] default options
  5219. * // TODO: describe available options
  5220. */
  5221. function ItemBox (parent, data, options, defaultOptions) {
  5222. this.props = {
  5223. dot: {
  5224. width: 0,
  5225. height: 0
  5226. },
  5227. line: {
  5228. width: 0,
  5229. height: 0
  5230. }
  5231. };
  5232. // validate data
  5233. if (data) {
  5234. if (data.start == undefined) {
  5235. throw new Error('Property "start" missing in item ' + data);
  5236. }
  5237. }
  5238. Item.call(this, parent, data, options, defaultOptions);
  5239. }
  5240. ItemBox.prototype = new Item (null, null);
  5241. /**
  5242. * Check whether this item is visible inside given range
  5243. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5244. * @returns {boolean} True if visible
  5245. */
  5246. ItemBox.prototype.isVisible = function isVisible (range) {
  5247. // determine visibility
  5248. // TODO: account for the width of the item. Right now we add 1/4 to the window
  5249. var interval = (range.end - range.start) / 4;
  5250. interval = 0; // TODO: remove
  5251. return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
  5252. };
  5253. /**
  5254. * Repaint the item
  5255. */
  5256. ItemBox.prototype.repaint = function repaint() {
  5257. var dom = this.dom;
  5258. if (!dom) {
  5259. // create DOM
  5260. this.dom = {};
  5261. dom = this.dom;
  5262. // create main box
  5263. dom.box = document.createElement('DIV');
  5264. // contents box (inside the background box). used for making margins
  5265. dom.content = document.createElement('DIV');
  5266. dom.content.className = 'content';
  5267. dom.box.appendChild(dom.content);
  5268. // line to axis
  5269. dom.line = document.createElement('DIV');
  5270. dom.line.className = 'line';
  5271. // dot on axis
  5272. dom.dot = document.createElement('DIV');
  5273. dom.dot.className = 'dot';
  5274. // attach this item as attribute
  5275. dom.box['timeline-item'] = this;
  5276. }
  5277. // append DOM to parent DOM
  5278. if (!this.parent) {
  5279. throw new Error('Cannot repaint item: no parent attached');
  5280. }
  5281. if (!dom.box.parentNode) {
  5282. var foreground = this.parent.getForeground();
  5283. if (!foreground) throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5284. foreground.appendChild(dom.box);
  5285. }
  5286. if (!dom.line.parentNode) {
  5287. var background = this.parent.getBackground();
  5288. if (!background) throw new Error('Cannot repaint time axis: parent has no background container element');
  5289. background.appendChild(dom.line);
  5290. }
  5291. if (!dom.dot.parentNode) {
  5292. var axis = this.parent.getAxis();
  5293. if (!background) throw new Error('Cannot repaint time axis: parent has no axis container element');
  5294. axis.appendChild(dom.dot);
  5295. }
  5296. this.displayed = true;
  5297. // update contents
  5298. if (this.data.content != this.content) {
  5299. this.content = this.data.content;
  5300. if (this.content instanceof Element) {
  5301. dom.content.innerHTML = '';
  5302. dom.content.appendChild(this.content);
  5303. }
  5304. else if (this.data.content != undefined) {
  5305. dom.content.innerHTML = this.content;
  5306. }
  5307. else {
  5308. throw new Error('Property "content" missing in item ' + this.data.id);
  5309. }
  5310. this.dirty = true;
  5311. }
  5312. // update class
  5313. var className = (this.data.className? ' ' + this.data.className : '') +
  5314. (this.selected ? ' selected' : '');
  5315. if (this.className != className) {
  5316. this.className = className;
  5317. dom.box.className = 'item box' + className;
  5318. dom.line.className = 'item line' + className;
  5319. dom.dot.className = 'item dot' + className;
  5320. this.dirty = true;
  5321. }
  5322. // recalculate size
  5323. if (this.dirty) {
  5324. this.props.dot.height = dom.dot.offsetHeight;
  5325. this.props.dot.width = dom.dot.offsetWidth;
  5326. this.props.line.width = dom.line.offsetWidth;
  5327. this.width = dom.box.offsetWidth;
  5328. this.height = dom.box.offsetHeight;
  5329. this.dirty = false;
  5330. }
  5331. this._repaintDeleteButton(dom.box);
  5332. };
  5333. /**
  5334. * Show the item in the DOM (when not already displayed). The items DOM will
  5335. * be created when needed.
  5336. */
  5337. ItemBox.prototype.show = function show() {
  5338. if (!this.displayed) {
  5339. this.repaint();
  5340. }
  5341. };
  5342. /**
  5343. * Hide the item from the DOM (when visible)
  5344. */
  5345. ItemBox.prototype.hide = function hide() {
  5346. if (this.displayed) {
  5347. var dom = this.dom;
  5348. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  5349. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  5350. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  5351. this.top = null;
  5352. this.left = null;
  5353. this.displayed = false;
  5354. }
  5355. };
  5356. /**
  5357. * Reposition the item horizontally
  5358. * @Override
  5359. */
  5360. ItemBox.prototype.repositionX = function repositionX() {
  5361. var start = this.parent.toScreen(this.data.start),
  5362. align = this.options.align || this.defaultOptions.align,
  5363. left,
  5364. box = this.dom.box,
  5365. line = this.dom.line,
  5366. dot = this.dom.dot;
  5367. // calculate left position of the box
  5368. if (align == 'right') {
  5369. this.left = start - this.width;
  5370. }
  5371. else if (align == 'left') {
  5372. this.left = start;
  5373. }
  5374. else {
  5375. // default or 'center'
  5376. this.left = start - this.width / 2;
  5377. }
  5378. // reposition box
  5379. box.style.left = this.left + 'px';
  5380. // reposition line
  5381. line.style.left = (start - this.props.line.width / 2) + 'px';
  5382. // reposition dot
  5383. dot.style.left = (start - this.props.dot.width / 2) + 'px';
  5384. };
  5385. /**
  5386. * Reposition the item vertically
  5387. * @Override
  5388. */
  5389. ItemBox.prototype.repositionY = function repositionY () {
  5390. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5391. box = this.dom.box,
  5392. line = this.dom.line,
  5393. dot = this.dom.dot;
  5394. if (orientation == 'top') {
  5395. box.style.top = (this.top || 0) + 'px';
  5396. box.style.bottom = '';
  5397. line.style.top = '0px';
  5398. line.style.bottom = '';
  5399. line.style.height = this.top + 'px';
  5400. }
  5401. else { // orientation 'bottom'
  5402. box.style.top = '';
  5403. box.style.bottom = (this.top || 0) + 'px';
  5404. line.style.top = '';
  5405. line.style.bottom = '0px';
  5406. line.style.height = this.top + 'px';
  5407. }
  5408. dot.style.top = (-this.props.dot.height / 2) + 'px';
  5409. }
  5410. /**
  5411. * @constructor ItemPoint
  5412. * @extends Item
  5413. * @param {ItemSet} parent
  5414. * @param {Object} data Object containing parameters start
  5415. * content, className.
  5416. * @param {Object} [options] Options to set initial property values
  5417. * @param {Object} [defaultOptions] default options
  5418. * // TODO: describe available options
  5419. */
  5420. function ItemPoint (parent, data, options, defaultOptions) {
  5421. this.props = {
  5422. dot: {
  5423. top: 0,
  5424. width: 0,
  5425. height: 0
  5426. },
  5427. content: {
  5428. height: 0,
  5429. marginLeft: 0
  5430. }
  5431. };
  5432. // validate data
  5433. if (data) {
  5434. if (data.start == undefined) {
  5435. throw new Error('Property "start" missing in item ' + data);
  5436. }
  5437. }
  5438. Item.call(this, parent, data, options, defaultOptions);
  5439. }
  5440. ItemPoint.prototype = new Item (null, null);
  5441. /**
  5442. * Check whether this item is visible inside given range
  5443. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5444. * @returns {boolean} True if visible
  5445. */
  5446. ItemPoint.prototype.isVisible = function isVisible (range) {
  5447. // determine visibility
  5448. var interval = (range.end - range.start);
  5449. return (this.data.start > range.start - interval) && (this.data.start < range.end);
  5450. }
  5451. /**
  5452. * Repaint the item
  5453. */
  5454. ItemPoint.prototype.repaint = function repaint() {
  5455. var dom = this.dom;
  5456. if (!dom) {
  5457. // create DOM
  5458. this.dom = {};
  5459. dom = this.dom;
  5460. // background box
  5461. dom.point = document.createElement('div');
  5462. // className is updated in repaint()
  5463. // contents box, right from the dot
  5464. dom.content = document.createElement('div');
  5465. dom.content.className = 'content';
  5466. dom.point.appendChild(dom.content);
  5467. // dot at start
  5468. dom.dot = document.createElement('div');
  5469. dom.dot.className = 'dot';
  5470. dom.point.appendChild(dom.dot);
  5471. // attach this item as attribute
  5472. dom.point['timeline-item'] = this;
  5473. }
  5474. // append DOM to parent DOM
  5475. if (!this.parent) {
  5476. throw new Error('Cannot repaint item: no parent attached');
  5477. }
  5478. if (!dom.point.parentNode) {
  5479. var foreground = this.parent.getForeground();
  5480. if (!foreground) {
  5481. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5482. }
  5483. foreground.appendChild(dom.point);
  5484. }
  5485. this.displayed = true;
  5486. // update contents
  5487. if (this.data.content != this.content) {
  5488. this.content = this.data.content;
  5489. if (this.content instanceof Element) {
  5490. dom.content.innerHTML = '';
  5491. dom.content.appendChild(this.content);
  5492. }
  5493. else if (this.data.content != undefined) {
  5494. dom.content.innerHTML = this.content;
  5495. }
  5496. else {
  5497. throw new Error('Property "content" missing in item ' + this.data.id);
  5498. }
  5499. this.dirty = true;
  5500. }
  5501. // update class
  5502. var className = (this.data.className? ' ' + this.data.className : '') +
  5503. (this.selected ? ' selected' : '');
  5504. if (this.className != className) {
  5505. this.className = className;
  5506. dom.point.className = 'item point' + className;
  5507. this.dirty = true;
  5508. }
  5509. // recalculate size
  5510. if (this.dirty) {
  5511. this.width = dom.point.offsetWidth;
  5512. this.height = dom.point.offsetHeight;
  5513. this.props.dot.width = dom.dot.offsetWidth;
  5514. this.props.dot.height = dom.dot.offsetHeight;
  5515. this.props.content.height = dom.content.offsetHeight;
  5516. // resize contents
  5517. dom.content.style.marginLeft = 1.5 * this.props.dot.width + 'px';
  5518. //dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  5519. dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px';
  5520. this.dirty = false;
  5521. }
  5522. this._repaintDeleteButton(dom.point);
  5523. };
  5524. /**
  5525. * Show the item in the DOM (when not already visible). The items DOM will
  5526. * be created when needed.
  5527. */
  5528. ItemPoint.prototype.show = function show() {
  5529. if (!this.displayed) {
  5530. this.repaint();
  5531. }
  5532. };
  5533. /**
  5534. * Hide the item from the DOM (when visible)
  5535. */
  5536. ItemPoint.prototype.hide = function hide() {
  5537. if (this.displayed) {
  5538. if (this.dom.point.parentNode) {
  5539. this.dom.point.parentNode.removeChild(this.dom.point);
  5540. }
  5541. this.top = null;
  5542. this.left = null;
  5543. this.displayed = false;
  5544. }
  5545. };
  5546. /**
  5547. * Reposition the item horizontally
  5548. * @Override
  5549. */
  5550. ItemPoint.prototype.repositionX = function repositionX() {
  5551. var start = this.parent.toScreen(this.data.start);
  5552. this.left = start - this.props.dot.width / 2;
  5553. // reposition point
  5554. this.dom.point.style.left = this.left + 'px';
  5555. };
  5556. /**
  5557. * Reposition the item vertically
  5558. * @Override
  5559. */
  5560. ItemPoint.prototype.repositionY = function repositionY () {
  5561. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5562. point = this.dom.point;
  5563. if (orientation == 'top') {
  5564. point.style.top = this.top + 'px';
  5565. point.style.bottom = '';
  5566. }
  5567. else {
  5568. point.style.top = '';
  5569. point.style.bottom = this.top + 'px';
  5570. }
  5571. }
  5572. /**
  5573. * @constructor ItemRange
  5574. * @extends Item
  5575. * @param {ItemSet} parent
  5576. * @param {Object} data Object containing parameters start, end
  5577. * content, className.
  5578. * @param {Object} [options] Options to set initial property values
  5579. * @param {Object} [defaultOptions] default options
  5580. * // TODO: describe available options
  5581. */
  5582. function ItemRange (parent, data, options, defaultOptions) {
  5583. this.props = {
  5584. content: {
  5585. width: 0
  5586. }
  5587. };
  5588. // validate data
  5589. if (data) {
  5590. if (data.start == undefined) {
  5591. throw new Error('Property "start" missing in item ' + data.id);
  5592. }
  5593. if (data.end == undefined) {
  5594. throw new Error('Property "end" missing in item ' + data.id);
  5595. }
  5596. }
  5597. Item.call(this, parent, data, options, defaultOptions);
  5598. }
  5599. ItemRange.prototype = new Item (null, null);
  5600. ItemRange.prototype.baseClassName = 'item range';
  5601. /**
  5602. * Check whether this item is visible inside given range
  5603. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  5604. * @returns {boolean} True if visible
  5605. */
  5606. ItemRange.prototype.isVisible = function isVisible (range) {
  5607. // determine visibility
  5608. return (this.data.start < range.end) && (this.data.end > range.start);
  5609. };
  5610. /**
  5611. * Repaint the item
  5612. */
  5613. ItemRange.prototype.repaint = function repaint() {
  5614. var dom = this.dom;
  5615. if (!dom) {
  5616. // create DOM
  5617. this.dom = {};
  5618. dom = this.dom;
  5619. // background box
  5620. dom.box = document.createElement('div');
  5621. // className is updated in repaint()
  5622. // contents box
  5623. dom.content = document.createElement('div');
  5624. dom.content.className = 'content';
  5625. dom.box.appendChild(dom.content);
  5626. // attach this item as attribute
  5627. dom.box['timeline-item'] = this;
  5628. }
  5629. // append DOM to parent DOM
  5630. if (!this.parent) {
  5631. throw new Error('Cannot repaint item: no parent attached');
  5632. }
  5633. if (!dom.box.parentNode) {
  5634. var foreground = this.parent.getForeground();
  5635. if (!foreground) {
  5636. throw new Error('Cannot repaint time axis: parent has no foreground container element');
  5637. }
  5638. foreground.appendChild(dom.box);
  5639. }
  5640. this.displayed = true;
  5641. // update contents
  5642. if (this.data.content != this.content) {
  5643. this.content = this.data.content;
  5644. if (this.content instanceof Element) {
  5645. dom.content.innerHTML = '';
  5646. dom.content.appendChild(this.content);
  5647. }
  5648. else if (this.data.content != undefined) {
  5649. dom.content.innerHTML = this.content;
  5650. }
  5651. else {
  5652. throw new Error('Property "content" missing in item ' + this.data.id);
  5653. }
  5654. this.dirty = true;
  5655. }
  5656. // update class
  5657. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5658. (this.selected ? ' selected' : '');
  5659. if (this.className != className) {
  5660. this.className = className;
  5661. dom.box.className = this.baseClassName + className;
  5662. this.dirty = true;
  5663. }
  5664. // recalculate size
  5665. if (this.dirty) {
  5666. this.props.content.width = this.dom.content.offsetWidth;
  5667. this.height = this.dom.box.offsetHeight;
  5668. this.dirty = false;
  5669. }
  5670. this._repaintDeleteButton(dom.box);
  5671. this._repaintDragLeft();
  5672. this._repaintDragRight();
  5673. };
  5674. /**
  5675. * Show the item in the DOM (when not already visible). The items DOM will
  5676. * be created when needed.
  5677. */
  5678. ItemRange.prototype.show = function show() {
  5679. if (!this.displayed) {
  5680. this.repaint();
  5681. }
  5682. };
  5683. /**
  5684. * Hide the item from the DOM (when visible)
  5685. * @return {Boolean} changed
  5686. */
  5687. ItemRange.prototype.hide = function hide() {
  5688. if (this.displayed) {
  5689. var box = this.dom.box;
  5690. if (box.parentNode) {
  5691. box.parentNode.removeChild(box);
  5692. }
  5693. this.top = null;
  5694. this.left = null;
  5695. this.displayed = false;
  5696. }
  5697. };
  5698. /**
  5699. * Reposition the item horizontally
  5700. * @Override
  5701. */
  5702. ItemRange.prototype.repositionX = function repositionX() {
  5703. var props = this.props,
  5704. parentWidth = this.parent.width,
  5705. start = this.parent.toScreen(this.data.start),
  5706. end = this.parent.toScreen(this.data.end),
  5707. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5708. contentLeft;
  5709. // limit the width of the this, as browsers cannot draw very wide divs
  5710. if (start < -parentWidth) {
  5711. start = -parentWidth;
  5712. }
  5713. if (end > 2 * parentWidth) {
  5714. end = 2 * parentWidth;
  5715. }
  5716. // when range exceeds left of the window, position the contents at the left of the visible area
  5717. if (start < 0) {
  5718. contentLeft = Math.min(-start,
  5719. (end - start - props.content.width - 2 * padding));
  5720. // TODO: remove the need for options.padding. it's terrible.
  5721. }
  5722. else {
  5723. contentLeft = 0;
  5724. }
  5725. this.left = start;
  5726. this.width = Math.max(end - start, 1);
  5727. this.dom.box.style.left = this.left + 'px';
  5728. this.dom.box.style.width = this.width + 'px';
  5729. this.dom.content.style.left = contentLeft + 'px';
  5730. };
  5731. /**
  5732. * Reposition the item vertically
  5733. * @Override
  5734. */
  5735. ItemRange.prototype.repositionY = function repositionY() {
  5736. var orientation = this.options.orientation || this.defaultOptions.orientation,
  5737. box = this.dom.box;
  5738. if (orientation == 'top') {
  5739. box.style.top = this.top + 'px';
  5740. box.style.bottom = '';
  5741. }
  5742. else {
  5743. box.style.top = '';
  5744. box.style.bottom = this.top + 'px';
  5745. }
  5746. };
  5747. /**
  5748. * Repaint a drag area on the left side of the range when the range is selected
  5749. * @private
  5750. */
  5751. ItemRange.prototype._repaintDragLeft = function () {
  5752. if (this.selected && this.options.editable && !this.dom.dragLeft) {
  5753. // create and show drag area
  5754. var dragLeft = document.createElement('div');
  5755. dragLeft.className = 'drag-left';
  5756. dragLeft.dragLeftItem = this;
  5757. // TODO: this should be redundant?
  5758. Hammer(dragLeft, {
  5759. preventDefault: true
  5760. }).on('drag', function () {
  5761. //console.log('drag left')
  5762. });
  5763. this.dom.box.appendChild(dragLeft);
  5764. this.dom.dragLeft = dragLeft;
  5765. }
  5766. else if (!this.selected && this.dom.dragLeft) {
  5767. // delete drag area
  5768. if (this.dom.dragLeft.parentNode) {
  5769. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  5770. }
  5771. this.dom.dragLeft = null;
  5772. }
  5773. };
  5774. /**
  5775. * Repaint a drag area on the right side of the range when the range is selected
  5776. * @private
  5777. */
  5778. ItemRange.prototype._repaintDragRight = function () {
  5779. if (this.selected && this.options.editable && !this.dom.dragRight) {
  5780. // create and show drag area
  5781. var dragRight = document.createElement('div');
  5782. dragRight.className = 'drag-right';
  5783. dragRight.dragRightItem = this;
  5784. // TODO: this should be redundant?
  5785. Hammer(dragRight, {
  5786. preventDefault: true
  5787. }).on('drag', function () {
  5788. //console.log('drag right')
  5789. });
  5790. this.dom.box.appendChild(dragRight);
  5791. this.dom.dragRight = dragRight;
  5792. }
  5793. else if (!this.selected && this.dom.dragRight) {
  5794. // delete drag area
  5795. if (this.dom.dragRight.parentNode) {
  5796. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  5797. }
  5798. this.dom.dragRight = null;
  5799. }
  5800. };
  5801. /**
  5802. * @constructor ItemRangeOverflow
  5803. * @extends ItemRange
  5804. * @param {ItemSet} parent
  5805. * @param {Object} data Object containing parameters start, end
  5806. * content, className.
  5807. * @param {Object} [options] Options to set initial property values
  5808. * @param {Object} [defaultOptions] default options
  5809. * // TODO: describe available options
  5810. */
  5811. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  5812. this.props = {
  5813. content: {
  5814. left: 0,
  5815. width: 0
  5816. }
  5817. };
  5818. ItemRange.call(this, parent, data, options, defaultOptions);
  5819. }
  5820. ItemRangeOverflow.prototype = new ItemRange (null, null);
  5821. ItemRangeOverflow.prototype.baseClassName = 'item rangeoverflow';
  5822. /**
  5823. * Reposition the item horizontally
  5824. * @Override
  5825. */
  5826. ItemRangeOverflow.prototype.repositionX = function repositionX() {
  5827. var parentWidth = this.parent.width,
  5828. start = this.parent.toScreen(this.data.start),
  5829. end = this.parent.toScreen(this.data.end),
  5830. padding = 'padding' in this.options ? this.options.padding : this.defaultOptions.padding,
  5831. contentLeft;
  5832. // limit the width of the this, as browsers cannot draw very wide divs
  5833. if (start < -parentWidth) {
  5834. start = -parentWidth;
  5835. }
  5836. if (end > 2 * parentWidth) {
  5837. end = 2 * parentWidth;
  5838. }
  5839. // when range exceeds left of the window, position the contents at the left of the visible area
  5840. contentLeft = Math.max(-start, 0);
  5841. this.left = start;
  5842. var boxWidth = Math.max(end - start, 1);
  5843. this.width = (this.props.content.width < boxWidth) ?
  5844. boxWidth :
  5845. start + contentLeft + this.props.content.width;
  5846. this.dom.box.style.left = this.left + 'px';
  5847. this.dom.box.style.width = boxWidth + 'px';
  5848. this.dom.content.style.left = contentLeft + 'px';
  5849. };
  5850. /**
  5851. * @constructor Group
  5852. * @param {GroupSet} parent
  5853. * @param {Number | String} groupId
  5854. * @param {Object} [options] Options to set initial property values
  5855. * // TODO: describe available options
  5856. * @extends Component
  5857. */
  5858. function Group (parent, groupId, options) {
  5859. this.id = util.randomUUID();
  5860. this.parent = parent;
  5861. this.groupId = groupId;
  5862. this.itemset = null; // ItemSet
  5863. this.options = options || {};
  5864. this.options.top = 0;
  5865. this.props = {
  5866. label: {
  5867. width: 0,
  5868. height: 0
  5869. }
  5870. };
  5871. this.top = 0;
  5872. this.left = 0;
  5873. this.width = 0;
  5874. this.height = 0;
  5875. }
  5876. Group.prototype = new Component();
  5877. // TODO: comment
  5878. Group.prototype.setOptions = Component.prototype.setOptions;
  5879. /**
  5880. * Get the container element of the panel, which can be used by a child to
  5881. * add its own widgets.
  5882. * @returns {HTMLElement} container
  5883. */
  5884. Group.prototype.getContainer = function () {
  5885. return this.parent.getContainer();
  5886. };
  5887. /**
  5888. * Set item set for the group. The group will create a view on the itemset,
  5889. * filtered by the groups id.
  5890. * @param {DataSet | DataView} items
  5891. */
  5892. Group.prototype.setItems = function setItems(items) {
  5893. if (this.itemset) {
  5894. // remove current item set
  5895. this.itemset.hide();
  5896. this.itemset.setItems();
  5897. this.parent.controller.remove(this.itemset);
  5898. this.itemset = null;
  5899. }
  5900. if (items) {
  5901. var groupId = this.groupId;
  5902. var itemsetOptions = Object.create(this.options);
  5903. this.itemset = new ItemSet(this, null, itemsetOptions);
  5904. this.itemset.setRange(this.parent.range);
  5905. this.view = new DataView(items, {
  5906. filter: function (item) {
  5907. return item.group == groupId;
  5908. }
  5909. });
  5910. this.itemset.setItems(this.view);
  5911. this.parent.controller.add(this.itemset);
  5912. }
  5913. };
  5914. /**
  5915. * Set selected items by their id. Replaces the current selection.
  5916. * Unknown id's are silently ignored.
  5917. * @param {Array} [ids] An array with zero or more id's of the items to be
  5918. * selected. If ids is an empty array, all items will be
  5919. * unselected.
  5920. */
  5921. Group.prototype.setSelection = function setSelection(ids) {
  5922. if (this.itemset) this.itemset.setSelection(ids);
  5923. };
  5924. /**
  5925. * Get the selected items by their id
  5926. * @return {Array} ids The ids of the selected items
  5927. */
  5928. Group.prototype.getSelection = function getSelection() {
  5929. return this.itemset ? this.itemset.getSelection() : [];
  5930. };
  5931. /**
  5932. * Repaint the item
  5933. * @return {Boolean} changed
  5934. */
  5935. Group.prototype.repaint = function repaint() {
  5936. var update = util.updateProperty;
  5937. this.top = this.itemset ? this.itemset.top : 0;
  5938. this.height = this.itemset ? this.itemset.height : 0;
  5939. // TODO: reckon with the height of the group label
  5940. if (this.label) {
  5941. var inner = this.label.firstChild;
  5942. this.props.label.width = inner.clientWidth;
  5943. this.props.label.height = inner.clientHeight;
  5944. }
  5945. else {
  5946. this.props.label.width = 0;
  5947. this.props.label.height = 0;
  5948. }
  5949. };
  5950. /**
  5951. * An GroupSet holds a set of groups
  5952. * @param {Component} parent
  5953. * @param {Component[]} [depends] Components on which this components depends
  5954. * (except for the parent)
  5955. * @param {Object} [options] See GroupSet.setOptions for the available
  5956. * options.
  5957. * @constructor GroupSet
  5958. * @extends Panel
  5959. */
  5960. function GroupSet(parent, depends, options) {
  5961. this.id = util.randomUUID();
  5962. this.parent = parent;
  5963. this.depends = depends;
  5964. this.options = options || {};
  5965. this.range = null; // Range or Object {start: number, end: number}
  5966. this.itemsData = null; // DataSet with items
  5967. this.groupsData = null; // DataSet with groups
  5968. this.groups = {}; // map with groups
  5969. this.dom = {};
  5970. this.props = {
  5971. labels: {
  5972. width: 0
  5973. }
  5974. };
  5975. // TODO: implement right orientation of the labels
  5976. // changes in groups are queued key/value map containing id/action
  5977. this.queue = {};
  5978. var me = this;
  5979. this.listeners = {
  5980. 'add': function (event, params) {
  5981. me._onAdd(params.items);
  5982. },
  5983. 'update': function (event, params) {
  5984. me._onUpdate(params.items);
  5985. },
  5986. 'remove': function (event, params) {
  5987. me._onRemove(params.items);
  5988. }
  5989. };
  5990. }
  5991. GroupSet.prototype = new Panel();
  5992. /**
  5993. * Set options for the GroupSet. Existing options will be extended/overwritten.
  5994. * @param {Object} [options] The following options are available:
  5995. * {String | function} groupsOrder
  5996. * TODO: describe options
  5997. */
  5998. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  5999. GroupSet.prototype.setRange = function (range) {
  6000. // TODO: implement setRange
  6001. };
  6002. /**
  6003. * Set items
  6004. * @param {vis.DataSet | null} items
  6005. */
  6006. GroupSet.prototype.setItems = function setItems(items) {
  6007. this.itemsData = items;
  6008. for (var id in this.groups) {
  6009. if (this.groups.hasOwnProperty(id)) {
  6010. var group = this.groups[id];
  6011. group.setItems(items);
  6012. }
  6013. }
  6014. };
  6015. /**
  6016. * Get items
  6017. * @return {vis.DataSet | null} items
  6018. */
  6019. GroupSet.prototype.getItems = function getItems() {
  6020. return this.itemsData;
  6021. };
  6022. /**
  6023. * Set range (start and end).
  6024. * @param {Range | Object} range A Range or an object containing start and end.
  6025. */
  6026. GroupSet.prototype.setRange = function setRange(range) {
  6027. this.range = range;
  6028. };
  6029. /**
  6030. * Set groups
  6031. * @param {vis.DataSet} groups
  6032. */
  6033. GroupSet.prototype.setGroups = function setGroups(groups) {
  6034. var me = this,
  6035. ids;
  6036. // unsubscribe from current dataset
  6037. if (this.groupsData) {
  6038. util.forEach(this.listeners, function (callback, event) {
  6039. me.groupsData.unsubscribe(event, callback);
  6040. });
  6041. // remove all drawn groups
  6042. ids = this.groupsData.getIds();
  6043. this._onRemove(ids);
  6044. }
  6045. // replace the dataset
  6046. if (!groups) {
  6047. this.groupsData = null;
  6048. }
  6049. else if (groups instanceof DataSet) {
  6050. this.groupsData = groups;
  6051. }
  6052. else {
  6053. this.groupsData = new DataSet({
  6054. convert: {
  6055. start: 'Date',
  6056. end: 'Date'
  6057. }
  6058. });
  6059. this.groupsData.add(groups);
  6060. }
  6061. if (this.groupsData) {
  6062. // subscribe to new dataset
  6063. var id = this.id;
  6064. util.forEach(this.listeners, function (callback, event) {
  6065. me.groupsData.on(event, callback, id);
  6066. });
  6067. // draw all new groups
  6068. ids = this.groupsData.getIds();
  6069. this._onAdd(ids);
  6070. }
  6071. };
  6072. /**
  6073. * Get groups
  6074. * @return {vis.DataSet | null} groups
  6075. */
  6076. GroupSet.prototype.getGroups = function getGroups() {
  6077. return this.groupsData;
  6078. };
  6079. /**
  6080. * Set selected items by their id. Replaces the current selection.
  6081. * Unknown id's are silently ignored.
  6082. * @param {Array} [ids] An array with zero or more id's of the items to be
  6083. * selected. If ids is an empty array, all items will be
  6084. * unselected.
  6085. */
  6086. GroupSet.prototype.setSelection = function setSelection(ids) {
  6087. var selection = [],
  6088. groups = this.groups;
  6089. // iterate over each of the groups
  6090. for (var id in groups) {
  6091. if (groups.hasOwnProperty(id)) {
  6092. var group = groups[id];
  6093. group.setSelection(ids);
  6094. }
  6095. }
  6096. return selection;
  6097. };
  6098. /**
  6099. * Get the selected items by their id
  6100. * @return {Array} ids The ids of the selected items
  6101. */
  6102. GroupSet.prototype.getSelection = function getSelection() {
  6103. var selection = [],
  6104. groups = this.groups;
  6105. // iterate over each of the groups
  6106. for (var id in groups) {
  6107. if (groups.hasOwnProperty(id)) {
  6108. var group = groups[id];
  6109. selection = selection.concat(group.getSelection());
  6110. }
  6111. }
  6112. return selection;
  6113. };
  6114. /**
  6115. * Repaint the component
  6116. * @return {Boolean} changed
  6117. */
  6118. GroupSet.prototype.repaint = function repaint() {
  6119. var changed = 0,
  6120. i, id, group, label,
  6121. update = util.updateProperty,
  6122. asSize = util.option.asSize,
  6123. asElement = util.option.asElement,
  6124. options = this.options,
  6125. frame = this.dom.frame,
  6126. labels = this.dom.labels,
  6127. labelSet = this.dom.labelSet;
  6128. // create frame
  6129. if (!this.parent) {
  6130. throw new Error('Cannot repaint groupset: no parent attached');
  6131. }
  6132. var parentContainer = this.parent.getContainer();
  6133. if (!parentContainer) {
  6134. throw new Error('Cannot repaint groupset: parent has no container element');
  6135. }
  6136. if (!frame) {
  6137. frame = document.createElement('div');
  6138. frame.className = 'groupset';
  6139. frame['timeline-groupset'] = this;
  6140. this.dom.frame = frame;
  6141. var className = options.className;
  6142. if (className) {
  6143. util.addClassName(frame, util.option.asString(className));
  6144. }
  6145. changed += 1;
  6146. }
  6147. if (!frame.parentNode) {
  6148. parentContainer.appendChild(frame);
  6149. changed += 1;
  6150. }
  6151. // create labels
  6152. var labelContainer = asElement(options.labelContainer);
  6153. if (!labelContainer) {
  6154. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  6155. }
  6156. if (!labels) {
  6157. labels = document.createElement('div');
  6158. labels.className = 'labels';
  6159. this.dom.labels = labels;
  6160. }
  6161. if (!labelSet) {
  6162. labelSet = document.createElement('div');
  6163. labelSet.className = 'label-set';
  6164. labels.appendChild(labelSet);
  6165. this.dom.labelSet = labelSet;
  6166. }
  6167. if (!labels.parentNode || labels.parentNode != labelContainer) {
  6168. if (labels.parentNode) {
  6169. labels.parentNode.removeChild(labels.parentNode);
  6170. }
  6171. labelContainer.appendChild(labels);
  6172. }
  6173. // reposition frame
  6174. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  6175. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6176. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6177. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6178. // reposition labels
  6179. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  6180. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  6181. var me = this,
  6182. queue = this.queue,
  6183. groups = this.groups,
  6184. groupsData = this.groupsData;
  6185. // show/hide added/changed/removed groups
  6186. var ids = Object.keys(queue);
  6187. if (ids.length) {
  6188. ids.forEach(function (id) {
  6189. var action = queue[id];
  6190. var group = groups[id];
  6191. //noinspection FallthroughInSwitchStatementJS
  6192. switch (action) {
  6193. case 'add':
  6194. case 'update':
  6195. if (!group) {
  6196. var groupOptions = Object.create(me.options);
  6197. util.extend(groupOptions, {
  6198. height: null,
  6199. maxHeight: null
  6200. });
  6201. group = new Group(me, id, groupOptions);
  6202. group.setItems(me.itemsData); // attach items data
  6203. groups[id] = group;
  6204. me.controller.add(group);
  6205. }
  6206. // TODO: update group data
  6207. group.data = groupsData.get(id);
  6208. delete queue[id];
  6209. break;
  6210. case 'remove':
  6211. if (group) {
  6212. group.setItems(); // detach items data
  6213. delete groups[id];
  6214. me.controller.remove(group);
  6215. }
  6216. // update lists
  6217. delete queue[id];
  6218. break;
  6219. default:
  6220. console.log('Error: unknown action "' + action + '"');
  6221. }
  6222. });
  6223. // the groupset depends on each of the groups
  6224. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  6225. // TODO: apply dependencies of the groupset
  6226. // update the top positions of the groups in the correct order
  6227. var orderedGroups = this.groupsData.getIds({
  6228. order: this.options.groupOrder
  6229. });
  6230. for (i = 0; i < orderedGroups.length; i++) {
  6231. (function (group, prevGroup) {
  6232. var top = 0;
  6233. if (prevGroup) {
  6234. top = function () {
  6235. // TODO: top must reckon with options.maxHeight
  6236. return prevGroup.top + prevGroup.height;
  6237. }
  6238. }
  6239. group.setOptions({
  6240. top: top
  6241. });
  6242. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  6243. }
  6244. // (re)create the labels
  6245. while (labelSet.firstChild) {
  6246. labelSet.removeChild(labelSet.firstChild);
  6247. }
  6248. for (i = 0; i < orderedGroups.length; i++) {
  6249. id = orderedGroups[i];
  6250. label = this._createLabel(id);
  6251. labelSet.appendChild(label);
  6252. }
  6253. changed++;
  6254. }
  6255. // reposition the labels
  6256. // TODO: labels are not displayed correctly when orientation=='top'
  6257. // TODO: width of labelPanel is not immediately updated on a change in groups
  6258. for (id in groups) {
  6259. if (groups.hasOwnProperty(id)) {
  6260. group = groups[id];
  6261. label = group.label;
  6262. if (label) {
  6263. label.style.top = group.top + 'px';
  6264. label.style.height = group.height + 'px';
  6265. }
  6266. }
  6267. }
  6268. return (changed > 0);
  6269. };
  6270. /**
  6271. * Create a label for group with given id
  6272. * @param {Number} id
  6273. * @return {Element} label
  6274. * @private
  6275. */
  6276. GroupSet.prototype._createLabel = function(id) {
  6277. var group = this.groups[id];
  6278. var label = document.createElement('div');
  6279. label.className = 'vlabel';
  6280. var inner = document.createElement('div');
  6281. inner.className = 'inner';
  6282. label.appendChild(inner);
  6283. var content = group.data && group.data.content;
  6284. if (content instanceof Element) {
  6285. inner.appendChild(content);
  6286. }
  6287. else if (content != undefined) {
  6288. inner.innerHTML = content;
  6289. }
  6290. var className = group.data && group.data.className;
  6291. if (className) {
  6292. util.addClassName(label, className);
  6293. }
  6294. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  6295. return label;
  6296. };
  6297. /**
  6298. * Get container element
  6299. * @return {HTMLElement} container
  6300. */
  6301. GroupSet.prototype.getContainer = function getContainer() {
  6302. return this.dom.frame;
  6303. };
  6304. /**
  6305. * Get the width of the group labels
  6306. * @return {Number} width
  6307. */
  6308. GroupSet.prototype.getLabelsWidth = function getContainer() {
  6309. return this.props.labels.width;
  6310. };
  6311. /**
  6312. * Reflow the component
  6313. * @return {Boolean} resized
  6314. */
  6315. GroupSet.prototype.reflow = function reflow() {
  6316. var changed = 0,
  6317. id, group,
  6318. options = this.options,
  6319. update = util.updateProperty,
  6320. asNumber = util.option.asNumber,
  6321. asSize = util.option.asSize,
  6322. frame = this.dom.frame;
  6323. if (frame) {
  6324. var maxHeight = asNumber(options.maxHeight);
  6325. var fixedHeight = (asSize(options.height) != null);
  6326. var height;
  6327. if (fixedHeight) {
  6328. height = frame.offsetHeight;
  6329. }
  6330. else {
  6331. // height is not specified, calculate the sum of the height of all groups
  6332. height = 0;
  6333. for (id in this.groups) {
  6334. if (this.groups.hasOwnProperty(id)) {
  6335. group = this.groups[id];
  6336. height += group.height;
  6337. }
  6338. }
  6339. }
  6340. if (maxHeight != null) {
  6341. height = Math.min(height, maxHeight);
  6342. }
  6343. changed += update(this, 'height', height);
  6344. changed += update(this, 'top', frame.offsetTop);
  6345. changed += update(this, 'left', frame.offsetLeft);
  6346. changed += update(this, 'width', frame.offsetWidth);
  6347. }
  6348. // calculate the maximum width of the labels
  6349. var width = 0;
  6350. for (id in this.groups) {
  6351. if (this.groups.hasOwnProperty(id)) {
  6352. group = this.groups[id];
  6353. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  6354. width = Math.max(width, labelWidth);
  6355. }
  6356. }
  6357. changed += update(this.props.labels, 'width', width);
  6358. return (changed > 0);
  6359. };
  6360. /**
  6361. * Hide the component from the DOM
  6362. * @return {Boolean} changed
  6363. */
  6364. GroupSet.prototype.hide = function hide() {
  6365. if (this.dom.frame && this.dom.frame.parentNode) {
  6366. this.dom.frame.parentNode.removeChild(this.dom.frame);
  6367. return true;
  6368. }
  6369. else {
  6370. return false;
  6371. }
  6372. };
  6373. /**
  6374. * Show the component in the DOM (when not already visible).
  6375. * A repaint will be executed when the component is not visible
  6376. * @return {Boolean} changed
  6377. */
  6378. GroupSet.prototype.show = function show() {
  6379. if (!this.dom.frame || !this.dom.frame.parentNode) {
  6380. return this.repaint();
  6381. }
  6382. else {
  6383. return false;
  6384. }
  6385. };
  6386. /**
  6387. * Handle updated groups
  6388. * @param {Number[]} ids
  6389. * @private
  6390. */
  6391. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  6392. this._toQueue(ids, 'update');
  6393. };
  6394. /**
  6395. * Handle changed groups
  6396. * @param {Number[]} ids
  6397. * @private
  6398. */
  6399. GroupSet.prototype._onAdd = function _onAdd(ids) {
  6400. this._toQueue(ids, 'add');
  6401. };
  6402. /**
  6403. * Handle removed groups
  6404. * @param {Number[]} ids
  6405. * @private
  6406. */
  6407. GroupSet.prototype._onRemove = function _onRemove(ids) {
  6408. this._toQueue(ids, 'remove');
  6409. };
  6410. /**
  6411. * Put groups in the queue to be added/updated/remove
  6412. * @param {Number[]} ids
  6413. * @param {String} action can be 'add', 'update', 'remove'
  6414. */
  6415. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  6416. var queue = this.queue;
  6417. ids.forEach(function (id) {
  6418. queue[id] = action;
  6419. });
  6420. if (this.controller) {
  6421. //this.requestReflow();
  6422. this.requestRepaint();
  6423. }
  6424. };
  6425. /**
  6426. * Find the Group from an event target:
  6427. * searches for the attribute 'timeline-groupset' in the event target's element
  6428. * tree, then finds the right group in this groupset
  6429. * @param {Event} event
  6430. * @return {Group | null} group
  6431. */
  6432. GroupSet.groupFromTarget = function groupFromTarget (event) {
  6433. var groupset,
  6434. target = event.target;
  6435. while (target) {
  6436. if (target.hasOwnProperty('timeline-groupset')) {
  6437. groupset = target['timeline-groupset'];
  6438. break;
  6439. }
  6440. target = target.parentNode;
  6441. }
  6442. if (groupset) {
  6443. for (var groupId in groupset.groups) {
  6444. if (groupset.groups.hasOwnProperty(groupId)) {
  6445. var group = groupset.groups[groupId];
  6446. if (group.itemset && ItemSet.itemSetFromTarget(event) == group.itemset) {
  6447. return group;
  6448. }
  6449. }
  6450. }
  6451. }
  6452. return null;
  6453. };
  6454. /**
  6455. * Create a timeline visualization
  6456. * @param {HTMLElement} container
  6457. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6458. * @param {Object} [options] See Timeline.setOptions for the available options.
  6459. * @constructor
  6460. */
  6461. function Timeline (container, items, options) {
  6462. var me = this;
  6463. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6464. this.options = {
  6465. orientation: 'bottom',
  6466. autoResize: true,
  6467. editable: false,
  6468. selectable: true,
  6469. snap: null, // will be specified after timeaxis is created
  6470. min: null,
  6471. max: null,
  6472. zoomMin: 10, // milliseconds
  6473. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6474. // moveable: true, // TODO: option moveable
  6475. // zoomable: true, // TODO: option zoomable
  6476. showMinorLabels: true,
  6477. showMajorLabels: true,
  6478. showCurrentTime: false,
  6479. showCustomTime: false,
  6480. type: 'box',
  6481. align: 'center',
  6482. orientation: 'bottom',
  6483. margin: {
  6484. axis: 20,
  6485. item: 10
  6486. },
  6487. padding: 5,
  6488. onAdd: function (item, callback) {
  6489. callback(item);
  6490. },
  6491. onUpdate: function (item, callback) {
  6492. callback(item);
  6493. },
  6494. onMove: function (item, callback) {
  6495. callback(item);
  6496. },
  6497. onRemove: function (item, callback) {
  6498. callback(item);
  6499. }
  6500. };
  6501. // controller
  6502. this.controller = new Controller();
  6503. // root panel
  6504. if (!container) {
  6505. throw new Error('No container element provided');
  6506. }
  6507. var rootOptions = Object.create(this.options);
  6508. rootOptions.height = function () {
  6509. // TODO: change to height
  6510. if (me.options.height) {
  6511. // fixed height
  6512. return me.options.height;
  6513. }
  6514. else {
  6515. // auto height
  6516. return (me.timeaxis.height + me.content.height) + 'px';
  6517. }
  6518. };
  6519. this.rootPanel = new RootPanel(container, rootOptions);
  6520. this.controller.add(this.rootPanel);
  6521. // single select (or unselect) when tapping an item
  6522. this.controller.on('tap', this._onSelectItem.bind(this));
  6523. // multi select when holding mouse/touch, or on ctrl+click
  6524. this.controller.on('hold', this._onMultiSelectItem.bind(this));
  6525. // add item on doubletap
  6526. this.controller.on('doubletap', this._onAddItem.bind(this));
  6527. // item panel
  6528. var itemOptions = Object.create(this.options);
  6529. itemOptions.left = function () {
  6530. return me.labelPanel.width;
  6531. };
  6532. itemOptions.width = function () {
  6533. return me.rootPanel.width - me.labelPanel.width;
  6534. };
  6535. itemOptions.top = null;
  6536. itemOptions.height = null;
  6537. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  6538. this.controller.add(this.itemPanel);
  6539. // label panel
  6540. var labelOptions = Object.create(this.options);
  6541. labelOptions.top = null;
  6542. labelOptions.left = null;
  6543. labelOptions.height = null;
  6544. labelOptions.width = function () {
  6545. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  6546. return me.content.getLabelsWidth();
  6547. }
  6548. else {
  6549. return 0;
  6550. }
  6551. };
  6552. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  6553. this.controller.add(this.labelPanel);
  6554. // range
  6555. var rangeOptions = Object.create(this.options);
  6556. this.range = new Range(rangeOptions);
  6557. this.range.setRange(
  6558. now.clone().add('days', -3).valueOf(),
  6559. now.clone().add('days', 4).valueOf()
  6560. );
  6561. this.range.subscribe(this.controller, this.rootPanel, 'move', 'horizontal');
  6562. this.range.subscribe(this.controller, this.rootPanel, 'zoom', 'horizontal');
  6563. this.range.on('rangechange', function (properties) {
  6564. var force = true;
  6565. me.controller.emit('rangechange', properties);
  6566. me.controller.emit('request-reflow', force);
  6567. });
  6568. this.range.on('rangechanged', function (properties) {
  6569. var force = true;
  6570. me.controller.emit('rangechanged', properties);
  6571. me.controller.emit('request-reflow', force);
  6572. });
  6573. // time axis
  6574. var timeaxisOptions = Object.create(rootOptions);
  6575. timeaxisOptions.range = this.range;
  6576. timeaxisOptions.left = null;
  6577. timeaxisOptions.top = null;
  6578. timeaxisOptions.width = '100%';
  6579. timeaxisOptions.height = null;
  6580. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6581. this.timeaxis.setRange(this.range);
  6582. this.controller.add(this.timeaxis);
  6583. this.options.snap = this.timeaxis.snap.bind(this.timeaxis);
  6584. // current time bar
  6585. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  6586. this.controller.add(this.currenttime);
  6587. // custom time bar
  6588. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  6589. this.controller.add(this.customtime);
  6590. // create groupset
  6591. this.setGroups(null);
  6592. this.itemsData = null; // DataSet
  6593. this.groupsData = null; // DataSet
  6594. // apply options
  6595. if (options) {
  6596. this.setOptions(options);
  6597. }
  6598. // create itemset and groupset
  6599. if (items) {
  6600. this.setItems(items);
  6601. }
  6602. }
  6603. /**
  6604. * Add an event listener to the timeline
  6605. * @param {String} event Available events: select, rangechange, rangechanged,
  6606. * timechange, timechanged
  6607. * @param {function} callback
  6608. */
  6609. Timeline.prototype.on = function on (event, callback) {
  6610. this.controller.on(event, callback);
  6611. };
  6612. /**
  6613. * Add an event listener from the timeline
  6614. * @param {String} event
  6615. * @param {function} callback
  6616. */
  6617. Timeline.prototype.off = function off (event, callback) {
  6618. this.controller.off(event, callback);
  6619. };
  6620. /**
  6621. * Set options
  6622. * @param {Object} options TODO: describe the available options
  6623. */
  6624. Timeline.prototype.setOptions = function (options) {
  6625. util.extend(this.options, options);
  6626. // force update of range (apply new min/max etc.)
  6627. // both start and end are optional
  6628. this.range.setRange(options.start, options.end);
  6629. if ('editable' in options || 'selectable' in options) {
  6630. if (this.options.selectable) {
  6631. // force update of selection
  6632. this.setSelection(this.getSelection());
  6633. }
  6634. else {
  6635. // remove selection
  6636. this.setSelection([]);
  6637. }
  6638. }
  6639. // validate the callback functions
  6640. var validateCallback = (function (fn) {
  6641. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  6642. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  6643. }
  6644. }).bind(this);
  6645. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  6646. this.controller.reflow();
  6647. this.controller.repaint();
  6648. };
  6649. /**
  6650. * Set a custom time bar
  6651. * @param {Date} time
  6652. */
  6653. Timeline.prototype.setCustomTime = function (time) {
  6654. if (!this.customtime) {
  6655. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6656. }
  6657. this.customtime.setCustomTime(time);
  6658. };
  6659. /**
  6660. * Retrieve the current custom time.
  6661. * @return {Date} customTime
  6662. */
  6663. Timeline.prototype.getCustomTime = function() {
  6664. if (!this.customtime) {
  6665. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6666. }
  6667. return this.customtime.getCustomTime();
  6668. };
  6669. /**
  6670. * Set items
  6671. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  6672. */
  6673. Timeline.prototype.setItems = function(items) {
  6674. var initialLoad = (this.itemsData == null);
  6675. // convert to type DataSet when needed
  6676. var newDataSet;
  6677. if (!items) {
  6678. newDataSet = null;
  6679. }
  6680. else if (items instanceof DataSet) {
  6681. newDataSet = items;
  6682. }
  6683. if (!(items instanceof DataSet)) {
  6684. newDataSet = new DataSet({
  6685. convert: {
  6686. start: 'Date',
  6687. end: 'Date'
  6688. }
  6689. });
  6690. newDataSet.add(items);
  6691. }
  6692. // set items
  6693. this.itemsData = newDataSet;
  6694. this.content.setItems(newDataSet);
  6695. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6696. // apply the data range as range
  6697. var dataRange = this.getItemRange();
  6698. // add 5% space on both sides
  6699. var start = dataRange.min;
  6700. var end = dataRange.max;
  6701. if (start != null && end != null) {
  6702. var interval = (end.valueOf() - start.valueOf());
  6703. if (interval <= 0) {
  6704. // prevent an empty interval
  6705. interval = 24 * 60 * 60 * 1000; // 1 day
  6706. }
  6707. start = new Date(start.valueOf() - interval * 0.05);
  6708. end = new Date(end.valueOf() + interval * 0.05);
  6709. }
  6710. // override specified start and/or end date
  6711. if (this.options.start != undefined) {
  6712. start = util.convert(this.options.start, 'Date');
  6713. }
  6714. if (this.options.end != undefined) {
  6715. end = util.convert(this.options.end, 'Date');
  6716. }
  6717. // apply range if there is a min or max available
  6718. if (start != null || end != null) {
  6719. this.range.setRange(start, end);
  6720. }
  6721. }
  6722. };
  6723. /**
  6724. * Set groups
  6725. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  6726. */
  6727. Timeline.prototype.setGroups = function(groups) {
  6728. var me = this;
  6729. this.groupsData = groups;
  6730. // switch content type between ItemSet or GroupSet when needed
  6731. var Type = this.groupsData ? GroupSet : ItemSet;
  6732. if (!(this.content instanceof Type)) {
  6733. // remove old content set
  6734. if (this.content) {
  6735. this.content.hide();
  6736. if (this.content.setItems) {
  6737. this.content.setItems(); // disconnect from items
  6738. }
  6739. if (this.content.setGroups) {
  6740. this.content.setGroups(); // disconnect from groups
  6741. }
  6742. this.controller.remove(this.content);
  6743. }
  6744. // create new content set
  6745. var options = Object.create(this.options);
  6746. util.extend(options, {
  6747. top: function () {
  6748. if (me.options.orientation == 'top') {
  6749. return me.timeaxis.height;
  6750. }
  6751. else {
  6752. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  6753. }
  6754. },
  6755. left: null,
  6756. width: '100%',
  6757. height: function () {
  6758. if (me.options.height) {
  6759. // fixed height
  6760. return me.itemPanel.height - me.timeaxis.height;
  6761. }
  6762. else {
  6763. // auto height
  6764. return null;
  6765. }
  6766. },
  6767. maxHeight: function () {
  6768. // TODO: change maxHeight to be a css string like '100%' or '300px'
  6769. if (me.options.maxHeight) {
  6770. if (!util.isNumber(me.options.maxHeight)) {
  6771. throw new TypeError('Number expected for property maxHeight');
  6772. }
  6773. return me.options.maxHeight - me.timeaxis.height;
  6774. }
  6775. else {
  6776. return null;
  6777. }
  6778. },
  6779. labelContainer: function () {
  6780. return me.labelPanel.getContainer();
  6781. }
  6782. });
  6783. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  6784. if (this.content.setRange) {
  6785. this.content.setRange(this.range);
  6786. }
  6787. if (this.content.setItems) {
  6788. this.content.setItems(this.itemsData);
  6789. }
  6790. if (this.content.setGroups) {
  6791. this.content.setGroups(this.groupsData);
  6792. }
  6793. this.controller.add(this.content);
  6794. }
  6795. };
  6796. /**
  6797. * Get the data range of the item set.
  6798. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6799. * When no minimum is found, min==null
  6800. * When no maximum is found, max==null
  6801. */
  6802. Timeline.prototype.getItemRange = function getItemRange() {
  6803. // calculate min from start filed
  6804. var itemsData = this.itemsData,
  6805. min = null,
  6806. max = null;
  6807. if (itemsData) {
  6808. // calculate the minimum value of the field 'start'
  6809. var minItem = itemsData.min('start');
  6810. min = minItem ? minItem.start.valueOf() : null;
  6811. // calculate maximum value of fields 'start' and 'end'
  6812. var maxStartItem = itemsData.max('start');
  6813. if (maxStartItem) {
  6814. max = maxStartItem.start.valueOf();
  6815. }
  6816. var maxEndItem = itemsData.max('end');
  6817. if (maxEndItem) {
  6818. if (max == null) {
  6819. max = maxEndItem.end.valueOf();
  6820. }
  6821. else {
  6822. max = Math.max(max, maxEndItem.end.valueOf());
  6823. }
  6824. }
  6825. }
  6826. return {
  6827. min: (min != null) ? new Date(min) : null,
  6828. max: (max != null) ? new Date(max) : null
  6829. };
  6830. };
  6831. /**
  6832. * Set selected items by their id. Replaces the current selection
  6833. * Unknown id's are silently ignored.
  6834. * @param {Array} [ids] An array with zero or more id's of the items to be
  6835. * selected. If ids is an empty array, all items will be
  6836. * unselected.
  6837. */
  6838. Timeline.prototype.setSelection = function setSelection (ids) {
  6839. if (this.content) this.content.setSelection(ids);
  6840. };
  6841. /**
  6842. * Get the selected items by their id
  6843. * @return {Array} ids The ids of the selected items
  6844. */
  6845. Timeline.prototype.getSelection = function getSelection() {
  6846. return this.content ? this.content.getSelection() : [];
  6847. };
  6848. /**
  6849. * Set the visible window. Both parameters are optional, you can change only
  6850. * start or only end.
  6851. * @param {Date | Number | String} [start] Start date of visible window
  6852. * @param {Date | Number | String} [end] End date of visible window
  6853. */
  6854. Timeline.prototype.setWindow = function setWindow(start, end) {
  6855. this.range.setRange(start, end);
  6856. };
  6857. /**
  6858. * Get the visible window
  6859. * @return {{start: Date, end: Date}} Visible range
  6860. */
  6861. Timeline.prototype.getWindow = function setWindow() {
  6862. var range = this.range.getRange();
  6863. return {
  6864. start: new Date(range.start),
  6865. end: new Date(range.end)
  6866. };
  6867. };
  6868. /**
  6869. * Handle selecting/deselecting an item when tapping it
  6870. * @param {Event} event
  6871. * @private
  6872. */
  6873. // TODO: move this function to ItemSet
  6874. Timeline.prototype._onSelectItem = function (event) {
  6875. if (!this.options.selectable) return;
  6876. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  6877. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  6878. if (ctrlKey || shiftKey) {
  6879. this._onMultiSelectItem(event);
  6880. return;
  6881. }
  6882. var item = ItemSet.itemFromTarget(event);
  6883. var selection = item ? [item.id] : [];
  6884. this.setSelection(selection);
  6885. this.controller.emit('select', {
  6886. items: this.getSelection()
  6887. });
  6888. event.stopPropagation();
  6889. };
  6890. /**
  6891. * Handle creation and updates of an item on double tap
  6892. * @param event
  6893. * @private
  6894. */
  6895. Timeline.prototype._onAddItem = function (event) {
  6896. if (!this.options.selectable) return;
  6897. if (!this.options.editable) return;
  6898. var me = this,
  6899. item = ItemSet.itemFromTarget(event);
  6900. if (item) {
  6901. // update item
  6902. // execute async handler to update the item (or cancel it)
  6903. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  6904. this.options.onUpdate(itemData, function (itemData) {
  6905. if (itemData) {
  6906. me.itemsData.update(itemData);
  6907. }
  6908. });
  6909. }
  6910. else {
  6911. // add item
  6912. var xAbs = vis.util.getAbsoluteLeft(this.rootPanel.frame);
  6913. var x = event.gesture.center.pageX - xAbs;
  6914. var newItem = {
  6915. start: this.timeaxis.snap(this._toTime(x)),
  6916. content: 'new item'
  6917. };
  6918. var id = util.randomUUID();
  6919. newItem[this.itemsData.fieldId] = id;
  6920. var group = GroupSet.groupFromTarget(event);
  6921. if (group) {
  6922. newItem.group = group.groupId;
  6923. }
  6924. // execute async handler to customize (or cancel) adding an item
  6925. this.options.onAdd(newItem, function (item) {
  6926. if (item) {
  6927. me.itemsData.add(newItem);
  6928. // select the created item after it is repainted
  6929. me.controller.once('repaint', function () {
  6930. me.setSelection([id]);
  6931. me.controller.emit('select', {
  6932. items: me.getSelection()
  6933. });
  6934. }.bind(me));
  6935. }
  6936. });
  6937. }
  6938. };
  6939. /**
  6940. * Handle selecting/deselecting multiple items when holding an item
  6941. * @param {Event} event
  6942. * @private
  6943. */
  6944. // TODO: move this function to ItemSet
  6945. Timeline.prototype._onMultiSelectItem = function (event) {
  6946. if (!this.options.selectable) return;
  6947. var selection,
  6948. item = ItemSet.itemFromTarget(event);
  6949. if (item) {
  6950. // multi select items
  6951. selection = this.getSelection(); // current selection
  6952. var index = selection.indexOf(item.id);
  6953. if (index == -1) {
  6954. // item is not yet selected -> select it
  6955. selection.push(item.id);
  6956. }
  6957. else {
  6958. // item is already selected -> deselect it
  6959. selection.splice(index, 1);
  6960. }
  6961. this.setSelection(selection);
  6962. this.controller.emit('select', {
  6963. items: this.getSelection()
  6964. });
  6965. event.stopPropagation();
  6966. }
  6967. };
  6968. /**
  6969. * Convert a position on screen (pixels) to a datetime
  6970. * @param {int} x Position on the screen in pixels
  6971. * @return {Date} time The datetime the corresponds with given position x
  6972. * @private
  6973. */
  6974. Timeline.prototype._toTime = function _toTime(x) {
  6975. var conversion = this.range.conversion(this.content.width);
  6976. return new Date(x / conversion.scale + conversion.offset);
  6977. };
  6978. /**
  6979. * Convert a datetime (Date object) into a position on the screen
  6980. * @param {Date} time A date
  6981. * @return {int} x The position on the screen in pixels which corresponds
  6982. * with the given date.
  6983. * @private
  6984. */
  6985. Timeline.prototype._toScreen = function _toScreen(time) {
  6986. var conversion = this.range.conversion(this.content.width);
  6987. return (time.valueOf() - conversion.offset) * conversion.scale;
  6988. };
  6989. (function(exports) {
  6990. /**
  6991. * Parse a text source containing data in DOT language into a JSON object.
  6992. * The object contains two lists: one with nodes and one with edges.
  6993. *
  6994. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6995. *
  6996. * @param {String} data Text containing a graph in DOT-notation
  6997. * @return {Object} graph An object containing two parameters:
  6998. * {Object[]} nodes
  6999. * {Object[]} edges
  7000. */
  7001. function parseDOT (data) {
  7002. dot = data;
  7003. return parseGraph();
  7004. }
  7005. // token types enumeration
  7006. var TOKENTYPE = {
  7007. NULL : 0,
  7008. DELIMITER : 1,
  7009. IDENTIFIER: 2,
  7010. UNKNOWN : 3
  7011. };
  7012. // map with all delimiters
  7013. var DELIMITERS = {
  7014. '{': true,
  7015. '}': true,
  7016. '[': true,
  7017. ']': true,
  7018. ';': true,
  7019. '=': true,
  7020. ',': true,
  7021. '->': true,
  7022. '--': true
  7023. };
  7024. var dot = ''; // current dot file
  7025. var index = 0; // current index in dot file
  7026. var c = ''; // current token character in expr
  7027. var token = ''; // current token
  7028. var tokenType = TOKENTYPE.NULL; // type of the token
  7029. /**
  7030. * Get the first character from the dot file.
  7031. * The character is stored into the char c. If the end of the dot file is
  7032. * reached, the function puts an empty string in c.
  7033. */
  7034. function first() {
  7035. index = 0;
  7036. c = dot.charAt(0);
  7037. }
  7038. /**
  7039. * Get the next character from the dot file.
  7040. * The character is stored into the char c. If the end of the dot file is
  7041. * reached, the function puts an empty string in c.
  7042. */
  7043. function next() {
  7044. index++;
  7045. c = dot.charAt(index);
  7046. }
  7047. /**
  7048. * Preview the next character from the dot file.
  7049. * @return {String} cNext
  7050. */
  7051. function nextPreview() {
  7052. return dot.charAt(index + 1);
  7053. }
  7054. /**
  7055. * Test whether given character is alphabetic or numeric
  7056. * @param {String} c
  7057. * @return {Boolean} isAlphaNumeric
  7058. */
  7059. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  7060. function isAlphaNumeric(c) {
  7061. return regexAlphaNumeric.test(c);
  7062. }
  7063. /**
  7064. * Merge all properties of object b into object b
  7065. * @param {Object} a
  7066. * @param {Object} b
  7067. * @return {Object} a
  7068. */
  7069. function merge (a, b) {
  7070. if (!a) {
  7071. a = {};
  7072. }
  7073. if (b) {
  7074. for (var name in b) {
  7075. if (b.hasOwnProperty(name)) {
  7076. a[name] = b[name];
  7077. }
  7078. }
  7079. }
  7080. return a;
  7081. }
  7082. /**
  7083. * Set a value in an object, where the provided parameter name can be a
  7084. * path with nested parameters. For example:
  7085. *
  7086. * var obj = {a: 2};
  7087. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  7088. *
  7089. * @param {Object} obj
  7090. * @param {String} path A parameter name or dot-separated parameter path,
  7091. * like "color.highlight.border".
  7092. * @param {*} value
  7093. */
  7094. function setValue(obj, path, value) {
  7095. var keys = path.split('.');
  7096. var o = obj;
  7097. while (keys.length) {
  7098. var key = keys.shift();
  7099. if (keys.length) {
  7100. // this isn't the end point
  7101. if (!o[key]) {
  7102. o[key] = {};
  7103. }
  7104. o = o[key];
  7105. }
  7106. else {
  7107. // this is the end point
  7108. o[key] = value;
  7109. }
  7110. }
  7111. }
  7112. /**
  7113. * Add a node to a graph object. If there is already a node with
  7114. * the same id, their attributes will be merged.
  7115. * @param {Object} graph
  7116. * @param {Object} node
  7117. */
  7118. function addNode(graph, node) {
  7119. var i, len;
  7120. var current = null;
  7121. // find root graph (in case of subgraph)
  7122. var graphs = [graph]; // list with all graphs from current graph to root graph
  7123. var root = graph;
  7124. while (root.parent) {
  7125. graphs.push(root.parent);
  7126. root = root.parent;
  7127. }
  7128. // find existing node (at root level) by its id
  7129. if (root.nodes) {
  7130. for (i = 0, len = root.nodes.length; i < len; i++) {
  7131. if (node.id === root.nodes[i].id) {
  7132. current = root.nodes[i];
  7133. break;
  7134. }
  7135. }
  7136. }
  7137. if (!current) {
  7138. // this is a new node
  7139. current = {
  7140. id: node.id
  7141. };
  7142. if (graph.node) {
  7143. // clone default attributes
  7144. current.attr = merge(current.attr, graph.node);
  7145. }
  7146. }
  7147. // add node to this (sub)graph and all its parent graphs
  7148. for (i = graphs.length - 1; i >= 0; i--) {
  7149. var g = graphs[i];
  7150. if (!g.nodes) {
  7151. g.nodes = [];
  7152. }
  7153. if (g.nodes.indexOf(current) == -1) {
  7154. g.nodes.push(current);
  7155. }
  7156. }
  7157. // merge attributes
  7158. if (node.attr) {
  7159. current.attr = merge(current.attr, node.attr);
  7160. }
  7161. }
  7162. /**
  7163. * Add an edge to a graph object
  7164. * @param {Object} graph
  7165. * @param {Object} edge
  7166. */
  7167. function addEdge(graph, edge) {
  7168. if (!graph.edges) {
  7169. graph.edges = [];
  7170. }
  7171. graph.edges.push(edge);
  7172. if (graph.edge) {
  7173. var attr = merge({}, graph.edge); // clone default attributes
  7174. edge.attr = merge(attr, edge.attr); // merge attributes
  7175. }
  7176. }
  7177. /**
  7178. * Create an edge to a graph object
  7179. * @param {Object} graph
  7180. * @param {String | Number | Object} from
  7181. * @param {String | Number | Object} to
  7182. * @param {String} type
  7183. * @param {Object | null} attr
  7184. * @return {Object} edge
  7185. */
  7186. function createEdge(graph, from, to, type, attr) {
  7187. var edge = {
  7188. from: from,
  7189. to: to,
  7190. type: type
  7191. };
  7192. if (graph.edge) {
  7193. edge.attr = merge({}, graph.edge); // clone default attributes
  7194. }
  7195. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7196. return edge;
  7197. }
  7198. /**
  7199. * Get next token in the current dot file.
  7200. * The token and token type are available as token and tokenType
  7201. */
  7202. function getToken() {
  7203. tokenType = TOKENTYPE.NULL;
  7204. token = '';
  7205. // skip over whitespaces
  7206. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7207. next();
  7208. }
  7209. do {
  7210. var isComment = false;
  7211. // skip comment
  7212. if (c == '#') {
  7213. // find the previous non-space character
  7214. var i = index - 1;
  7215. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7216. i--;
  7217. }
  7218. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7219. // the # is at the start of a line, this is indeed a line comment
  7220. while (c != '' && c != '\n') {
  7221. next();
  7222. }
  7223. isComment = true;
  7224. }
  7225. }
  7226. if (c == '/' && nextPreview() == '/') {
  7227. // skip line comment
  7228. while (c != '' && c != '\n') {
  7229. next();
  7230. }
  7231. isComment = true;
  7232. }
  7233. if (c == '/' && nextPreview() == '*') {
  7234. // skip block comment
  7235. while (c != '') {
  7236. if (c == '*' && nextPreview() == '/') {
  7237. // end of block comment found. skip these last two characters
  7238. next();
  7239. next();
  7240. break;
  7241. }
  7242. else {
  7243. next();
  7244. }
  7245. }
  7246. isComment = true;
  7247. }
  7248. // skip over whitespaces
  7249. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7250. next();
  7251. }
  7252. }
  7253. while (isComment);
  7254. // check for end of dot file
  7255. if (c == '') {
  7256. // token is still empty
  7257. tokenType = TOKENTYPE.DELIMITER;
  7258. return;
  7259. }
  7260. // check for delimiters consisting of 2 characters
  7261. var c2 = c + nextPreview();
  7262. if (DELIMITERS[c2]) {
  7263. tokenType = TOKENTYPE.DELIMITER;
  7264. token = c2;
  7265. next();
  7266. next();
  7267. return;
  7268. }
  7269. // check for delimiters consisting of 1 character
  7270. if (DELIMITERS[c]) {
  7271. tokenType = TOKENTYPE.DELIMITER;
  7272. token = c;
  7273. next();
  7274. return;
  7275. }
  7276. // check for an identifier (number or string)
  7277. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7278. if (isAlphaNumeric(c) || c == '-') {
  7279. token += c;
  7280. next();
  7281. while (isAlphaNumeric(c)) {
  7282. token += c;
  7283. next();
  7284. }
  7285. if (token == 'false') {
  7286. token = false; // convert to boolean
  7287. }
  7288. else if (token == 'true') {
  7289. token = true; // convert to boolean
  7290. }
  7291. else if (!isNaN(Number(token))) {
  7292. token = Number(token); // convert to number
  7293. }
  7294. tokenType = TOKENTYPE.IDENTIFIER;
  7295. return;
  7296. }
  7297. // check for a string enclosed by double quotes
  7298. if (c == '"') {
  7299. next();
  7300. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7301. token += c;
  7302. if (c == '"') { // skip the escape character
  7303. next();
  7304. }
  7305. next();
  7306. }
  7307. if (c != '"') {
  7308. throw newSyntaxError('End of string " expected');
  7309. }
  7310. next();
  7311. tokenType = TOKENTYPE.IDENTIFIER;
  7312. return;
  7313. }
  7314. // something unknown is found, wrong characters, a syntax error
  7315. tokenType = TOKENTYPE.UNKNOWN;
  7316. while (c != '') {
  7317. token += c;
  7318. next();
  7319. }
  7320. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7321. }
  7322. /**
  7323. * Parse a graph.
  7324. * @returns {Object} graph
  7325. */
  7326. function parseGraph() {
  7327. var graph = {};
  7328. first();
  7329. getToken();
  7330. // optional strict keyword
  7331. if (token == 'strict') {
  7332. graph.strict = true;
  7333. getToken();
  7334. }
  7335. // graph or digraph keyword
  7336. if (token == 'graph' || token == 'digraph') {
  7337. graph.type = token;
  7338. getToken();
  7339. }
  7340. // optional graph id
  7341. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7342. graph.id = token;
  7343. getToken();
  7344. }
  7345. // open angle bracket
  7346. if (token != '{') {
  7347. throw newSyntaxError('Angle bracket { expected');
  7348. }
  7349. getToken();
  7350. // statements
  7351. parseStatements(graph);
  7352. // close angle bracket
  7353. if (token != '}') {
  7354. throw newSyntaxError('Angle bracket } expected');
  7355. }
  7356. getToken();
  7357. // end of file
  7358. if (token !== '') {
  7359. throw newSyntaxError('End of file expected');
  7360. }
  7361. getToken();
  7362. // remove temporary default properties
  7363. delete graph.node;
  7364. delete graph.edge;
  7365. delete graph.graph;
  7366. return graph;
  7367. }
  7368. /**
  7369. * Parse a list with statements.
  7370. * @param {Object} graph
  7371. */
  7372. function parseStatements (graph) {
  7373. while (token !== '' && token != '}') {
  7374. parseStatement(graph);
  7375. if (token == ';') {
  7376. getToken();
  7377. }
  7378. }
  7379. }
  7380. /**
  7381. * Parse a single statement. Can be a an attribute statement, node
  7382. * statement, a series of node statements and edge statements, or a
  7383. * parameter.
  7384. * @param {Object} graph
  7385. */
  7386. function parseStatement(graph) {
  7387. // parse subgraph
  7388. var subgraph = parseSubgraph(graph);
  7389. if (subgraph) {
  7390. // edge statements
  7391. parseEdge(graph, subgraph);
  7392. return;
  7393. }
  7394. // parse an attribute statement
  7395. var attr = parseAttributeStatement(graph);
  7396. if (attr) {
  7397. return;
  7398. }
  7399. // parse node
  7400. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7401. throw newSyntaxError('Identifier expected');
  7402. }
  7403. var id = token; // id can be a string or a number
  7404. getToken();
  7405. if (token == '=') {
  7406. // id statement
  7407. getToken();
  7408. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7409. throw newSyntaxError('Identifier expected');
  7410. }
  7411. graph[id] = token;
  7412. getToken();
  7413. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7414. }
  7415. else {
  7416. parseNodeStatement(graph, id);
  7417. }
  7418. }
  7419. /**
  7420. * Parse a subgraph
  7421. * @param {Object} graph parent graph object
  7422. * @return {Object | null} subgraph
  7423. */
  7424. function parseSubgraph (graph) {
  7425. var subgraph = null;
  7426. // optional subgraph keyword
  7427. if (token == 'subgraph') {
  7428. subgraph = {};
  7429. subgraph.type = 'subgraph';
  7430. getToken();
  7431. // optional graph id
  7432. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7433. subgraph.id = token;
  7434. getToken();
  7435. }
  7436. }
  7437. // open angle bracket
  7438. if (token == '{') {
  7439. getToken();
  7440. if (!subgraph) {
  7441. subgraph = {};
  7442. }
  7443. subgraph.parent = graph;
  7444. subgraph.node = graph.node;
  7445. subgraph.edge = graph.edge;
  7446. subgraph.graph = graph.graph;
  7447. // statements
  7448. parseStatements(subgraph);
  7449. // close angle bracket
  7450. if (token != '}') {
  7451. throw newSyntaxError('Angle bracket } expected');
  7452. }
  7453. getToken();
  7454. // remove temporary default properties
  7455. delete subgraph.node;
  7456. delete subgraph.edge;
  7457. delete subgraph.graph;
  7458. delete subgraph.parent;
  7459. // register at the parent graph
  7460. if (!graph.subgraphs) {
  7461. graph.subgraphs = [];
  7462. }
  7463. graph.subgraphs.push(subgraph);
  7464. }
  7465. return subgraph;
  7466. }
  7467. /**
  7468. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7469. * Available keywords are 'node', 'edge', 'graph'.
  7470. * The previous list with default attributes will be replaced
  7471. * @param {Object} graph
  7472. * @returns {String | null} keyword Returns the name of the parsed attribute
  7473. * (node, edge, graph), or null if nothing
  7474. * is parsed.
  7475. */
  7476. function parseAttributeStatement (graph) {
  7477. // attribute statements
  7478. if (token == 'node') {
  7479. getToken();
  7480. // node attributes
  7481. graph.node = parseAttributeList();
  7482. return 'node';
  7483. }
  7484. else if (token == 'edge') {
  7485. getToken();
  7486. // edge attributes
  7487. graph.edge = parseAttributeList();
  7488. return 'edge';
  7489. }
  7490. else if (token == 'graph') {
  7491. getToken();
  7492. // graph attributes
  7493. graph.graph = parseAttributeList();
  7494. return 'graph';
  7495. }
  7496. return null;
  7497. }
  7498. /**
  7499. * parse a node statement
  7500. * @param {Object} graph
  7501. * @param {String | Number} id
  7502. */
  7503. function parseNodeStatement(graph, id) {
  7504. // node statement
  7505. var node = {
  7506. id: id
  7507. };
  7508. var attr = parseAttributeList();
  7509. if (attr) {
  7510. node.attr = attr;
  7511. }
  7512. addNode(graph, node);
  7513. // edge statements
  7514. parseEdge(graph, id);
  7515. }
  7516. /**
  7517. * Parse an edge or a series of edges
  7518. * @param {Object} graph
  7519. * @param {String | Number} from Id of the from node
  7520. */
  7521. function parseEdge(graph, from) {
  7522. while (token == '->' || token == '--') {
  7523. var to;
  7524. var type = token;
  7525. getToken();
  7526. var subgraph = parseSubgraph(graph);
  7527. if (subgraph) {
  7528. to = subgraph;
  7529. }
  7530. else {
  7531. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7532. throw newSyntaxError('Identifier or subgraph expected');
  7533. }
  7534. to = token;
  7535. addNode(graph, {
  7536. id: to
  7537. });
  7538. getToken();
  7539. }
  7540. // parse edge attributes
  7541. var attr = parseAttributeList();
  7542. // create edge
  7543. var edge = createEdge(graph, from, to, type, attr);
  7544. addEdge(graph, edge);
  7545. from = to;
  7546. }
  7547. }
  7548. /**
  7549. * Parse a set with attributes,
  7550. * for example [label="1.000", shape=solid]
  7551. * @return {Object | null} attr
  7552. */
  7553. function parseAttributeList() {
  7554. var attr = null;
  7555. while (token == '[') {
  7556. getToken();
  7557. attr = {};
  7558. while (token !== '' && token != ']') {
  7559. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7560. throw newSyntaxError('Attribute name expected');
  7561. }
  7562. var name = token;
  7563. getToken();
  7564. if (token != '=') {
  7565. throw newSyntaxError('Equal sign = expected');
  7566. }
  7567. getToken();
  7568. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7569. throw newSyntaxError('Attribute value expected');
  7570. }
  7571. var value = token;
  7572. setValue(attr, name, value); // name can be a path
  7573. getToken();
  7574. if (token ==',') {
  7575. getToken();
  7576. }
  7577. }
  7578. if (token != ']') {
  7579. throw newSyntaxError('Bracket ] expected');
  7580. }
  7581. getToken();
  7582. }
  7583. return attr;
  7584. }
  7585. /**
  7586. * Create a syntax error with extra information on current token and index.
  7587. * @param {String} message
  7588. * @returns {SyntaxError} err
  7589. */
  7590. function newSyntaxError(message) {
  7591. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7592. }
  7593. /**
  7594. * Chop off text after a maximum length
  7595. * @param {String} text
  7596. * @param {Number} maxLength
  7597. * @returns {String}
  7598. */
  7599. function chop (text, maxLength) {
  7600. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7601. }
  7602. /**
  7603. * Execute a function fn for each pair of elements in two arrays
  7604. * @param {Array | *} array1
  7605. * @param {Array | *} array2
  7606. * @param {function} fn
  7607. */
  7608. function forEach2(array1, array2, fn) {
  7609. if (array1 instanceof Array) {
  7610. array1.forEach(function (elem1) {
  7611. if (array2 instanceof Array) {
  7612. array2.forEach(function (elem2) {
  7613. fn(elem1, elem2);
  7614. });
  7615. }
  7616. else {
  7617. fn(elem1, array2);
  7618. }
  7619. });
  7620. }
  7621. else {
  7622. if (array2 instanceof Array) {
  7623. array2.forEach(function (elem2) {
  7624. fn(array1, elem2);
  7625. });
  7626. }
  7627. else {
  7628. fn(array1, array2);
  7629. }
  7630. }
  7631. }
  7632. /**
  7633. * Convert a string containing a graph in DOT language into a map containing
  7634. * with nodes and edges in the format of graph.
  7635. * @param {String} data Text containing a graph in DOT-notation
  7636. * @return {Object} graphData
  7637. */
  7638. function DOTToGraph (data) {
  7639. // parse the DOT file
  7640. var dotData = parseDOT(data);
  7641. var graphData = {
  7642. nodes: [],
  7643. edges: [],
  7644. options: {}
  7645. };
  7646. // copy the nodes
  7647. if (dotData.nodes) {
  7648. dotData.nodes.forEach(function (dotNode) {
  7649. var graphNode = {
  7650. id: dotNode.id,
  7651. label: String(dotNode.label || dotNode.id)
  7652. };
  7653. merge(graphNode, dotNode.attr);
  7654. if (graphNode.image) {
  7655. graphNode.shape = 'image';
  7656. }
  7657. graphData.nodes.push(graphNode);
  7658. });
  7659. }
  7660. // copy the edges
  7661. if (dotData.edges) {
  7662. /**
  7663. * Convert an edge in DOT format to an edge with VisGraph format
  7664. * @param {Object} dotEdge
  7665. * @returns {Object} graphEdge
  7666. */
  7667. function convertEdge(dotEdge) {
  7668. var graphEdge = {
  7669. from: dotEdge.from,
  7670. to: dotEdge.to
  7671. };
  7672. merge(graphEdge, dotEdge.attr);
  7673. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  7674. return graphEdge;
  7675. }
  7676. dotData.edges.forEach(function (dotEdge) {
  7677. var from, to;
  7678. if (dotEdge.from instanceof Object) {
  7679. from = dotEdge.from.nodes;
  7680. }
  7681. else {
  7682. from = {
  7683. id: dotEdge.from
  7684. }
  7685. }
  7686. if (dotEdge.to instanceof Object) {
  7687. to = dotEdge.to.nodes;
  7688. }
  7689. else {
  7690. to = {
  7691. id: dotEdge.to
  7692. }
  7693. }
  7694. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  7695. dotEdge.from.edges.forEach(function (subEdge) {
  7696. var graphEdge = convertEdge(subEdge);
  7697. graphData.edges.push(graphEdge);
  7698. });
  7699. }
  7700. forEach2(from, to, function (from, to) {
  7701. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  7702. var graphEdge = convertEdge(subEdge);
  7703. graphData.edges.push(graphEdge);
  7704. });
  7705. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  7706. dotEdge.to.edges.forEach(function (subEdge) {
  7707. var graphEdge = convertEdge(subEdge);
  7708. graphData.edges.push(graphEdge);
  7709. });
  7710. }
  7711. });
  7712. }
  7713. // copy the options
  7714. if (dotData.attr) {
  7715. graphData.options = dotData.attr;
  7716. }
  7717. return graphData;
  7718. }
  7719. // exports
  7720. exports.parseDOT = parseDOT;
  7721. exports.DOTToGraph = DOTToGraph;
  7722. })(typeof util !== 'undefined' ? util : exports);
  7723. /**
  7724. * Canvas shapes used by the Graph
  7725. */
  7726. if (typeof CanvasRenderingContext2D !== 'undefined') {
  7727. /**
  7728. * Draw a circle shape
  7729. */
  7730. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  7731. this.beginPath();
  7732. this.arc(x, y, r, 0, 2*Math.PI, false);
  7733. };
  7734. /**
  7735. * Draw a square shape
  7736. * @param {Number} x horizontal center
  7737. * @param {Number} y vertical center
  7738. * @param {Number} r size, width and height of the square
  7739. */
  7740. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  7741. this.beginPath();
  7742. this.rect(x - r, y - r, r * 2, r * 2);
  7743. };
  7744. /**
  7745. * Draw a triangle shape
  7746. * @param {Number} x horizontal center
  7747. * @param {Number} y vertical center
  7748. * @param {Number} r radius, half the length of the sides of the triangle
  7749. */
  7750. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  7751. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7752. this.beginPath();
  7753. var s = r * 2;
  7754. var s2 = s / 2;
  7755. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7756. var h = Math.sqrt(s * s - s2 * s2); // height
  7757. this.moveTo(x, y - (h - ir));
  7758. this.lineTo(x + s2, y + ir);
  7759. this.lineTo(x - s2, y + ir);
  7760. this.lineTo(x, y - (h - ir));
  7761. this.closePath();
  7762. };
  7763. /**
  7764. * Draw a triangle shape in downward orientation
  7765. * @param {Number} x horizontal center
  7766. * @param {Number} y vertical center
  7767. * @param {Number} r radius
  7768. */
  7769. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  7770. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7771. this.beginPath();
  7772. var s = r * 2;
  7773. var s2 = s / 2;
  7774. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7775. var h = Math.sqrt(s * s - s2 * s2); // height
  7776. this.moveTo(x, y + (h - ir));
  7777. this.lineTo(x + s2, y - ir);
  7778. this.lineTo(x - s2, y - ir);
  7779. this.lineTo(x, y + (h - ir));
  7780. this.closePath();
  7781. };
  7782. /**
  7783. * Draw a star shape, a star with 5 points
  7784. * @param {Number} x horizontal center
  7785. * @param {Number} y vertical center
  7786. * @param {Number} r radius, half the length of the sides of the triangle
  7787. */
  7788. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  7789. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  7790. this.beginPath();
  7791. for (var n = 0; n < 10; n++) {
  7792. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  7793. this.lineTo(
  7794. x + radius * Math.sin(n * 2 * Math.PI / 10),
  7795. y - radius * Math.cos(n * 2 * Math.PI / 10)
  7796. );
  7797. }
  7798. this.closePath();
  7799. };
  7800. /**
  7801. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7802. */
  7803. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7804. var r2d = Math.PI/180;
  7805. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7806. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7807. this.beginPath();
  7808. this.moveTo(x+r,y);
  7809. this.lineTo(x+w-r,y);
  7810. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7811. this.lineTo(x+w,y+h-r);
  7812. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7813. this.lineTo(x+r,y+h);
  7814. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7815. this.lineTo(x,y+r);
  7816. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7817. };
  7818. /**
  7819. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7820. */
  7821. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7822. var kappa = .5522848,
  7823. ox = (w / 2) * kappa, // control point offset horizontal
  7824. oy = (h / 2) * kappa, // control point offset vertical
  7825. xe = x + w, // x-end
  7826. ye = y + h, // y-end
  7827. xm = x + w / 2, // x-middle
  7828. ym = y + h / 2; // y-middle
  7829. this.beginPath();
  7830. this.moveTo(x, ym);
  7831. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7832. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7833. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7834. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7835. };
  7836. /**
  7837. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7838. */
  7839. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7840. var f = 1/3;
  7841. var wEllipse = w;
  7842. var hEllipse = h * f;
  7843. var kappa = .5522848,
  7844. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7845. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7846. xe = x + wEllipse, // x-end
  7847. ye = y + hEllipse, // y-end
  7848. xm = x + wEllipse / 2, // x-middle
  7849. ym = y + hEllipse / 2, // y-middle
  7850. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7851. yeb = y + h; // y-end, bottom ellipse
  7852. this.beginPath();
  7853. this.moveTo(xe, ym);
  7854. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7855. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7856. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7857. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7858. this.lineTo(xe, ymb);
  7859. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7860. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7861. this.lineTo(x, ym);
  7862. };
  7863. /**
  7864. * Draw an arrow point (no line)
  7865. */
  7866. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  7867. // tail
  7868. var xt = x - length * Math.cos(angle);
  7869. var yt = y - length * Math.sin(angle);
  7870. // inner tail
  7871. // TODO: allow to customize different shapes
  7872. var xi = x - length * 0.9 * Math.cos(angle);
  7873. var yi = y - length * 0.9 * Math.sin(angle);
  7874. // left
  7875. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  7876. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  7877. // right
  7878. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  7879. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  7880. this.beginPath();
  7881. this.moveTo(x, y);
  7882. this.lineTo(xl, yl);
  7883. this.lineTo(xi, yi);
  7884. this.lineTo(xr, yr);
  7885. this.closePath();
  7886. };
  7887. /**
  7888. * Sets up the dashedLine functionality for drawing
  7889. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  7890. * @author David Jordan
  7891. * @date 2012-08-08
  7892. */
  7893. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  7894. if (!dashArray) dashArray=[10,5];
  7895. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  7896. var dashCount = dashArray.length;
  7897. this.moveTo(x, y);
  7898. var dx = (x2-x), dy = (y2-y);
  7899. var slope = dy/dx;
  7900. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  7901. var dashIndex=0, draw=true;
  7902. while (distRemaining>=0.1){
  7903. var dashLength = dashArray[dashIndex++%dashCount];
  7904. if (dashLength > distRemaining) dashLength = distRemaining;
  7905. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  7906. if (dx<0) xStep = -xStep;
  7907. x += xStep;
  7908. y += slope*xStep;
  7909. this[draw ? 'lineTo' : 'moveTo'](x,y);
  7910. distRemaining -= dashLength;
  7911. draw = !draw;
  7912. }
  7913. };
  7914. // TODO: add diamond shape
  7915. }
  7916. /**
  7917. * @class Node
  7918. * A node. A node can be connected to other nodes via one or multiple edges.
  7919. * @param {object} properties An object containing properties for the node. All
  7920. * properties are optional, except for the id.
  7921. * {number} id Id of the node. Required
  7922. * {string} label Text label for the node
  7923. * {number} x Horizontal position of the node
  7924. * {number} y Vertical position of the node
  7925. * {string} shape Node shape, available:
  7926. * "database", "circle", "ellipse",
  7927. * "box", "image", "text", "dot",
  7928. * "star", "triangle", "triangleDown",
  7929. * "square"
  7930. * {string} image An image url
  7931. * {string} title An title text, can be HTML
  7932. * {anytype} group A group name or number
  7933. * @param {Graph.Images} imagelist A list with images. Only needed
  7934. * when the node has an image
  7935. * @param {Graph.Groups} grouplist A list with groups. Needed for
  7936. * retrieving group properties
  7937. * @param {Object} constants An object with default values for
  7938. * example for the color
  7939. *
  7940. */
  7941. function Node(properties, imagelist, grouplist, constants) {
  7942. this.selected = false;
  7943. this.edges = []; // all edges connected to this node
  7944. this.dynamicEdges = [];
  7945. this.reroutedEdges = {};
  7946. this.group = constants.nodes.group;
  7947. this.fontSize = constants.nodes.fontSize;
  7948. this.fontFace = constants.nodes.fontFace;
  7949. this.fontColor = constants.nodes.fontColor;
  7950. this.fontDrawThreshold = 3;
  7951. this.color = constants.nodes.color;
  7952. // set defaults for the properties
  7953. this.id = undefined;
  7954. this.shape = constants.nodes.shape;
  7955. this.image = constants.nodes.image;
  7956. this.x = null;
  7957. this.y = null;
  7958. this.xFixed = false;
  7959. this.yFixed = false;
  7960. this.horizontalAlignLeft = true; // these are for the navigation controls
  7961. this.verticalAlignTop = true; // these are for the navigation controls
  7962. this.radius = constants.nodes.radius;
  7963. this.baseRadiusValue = constants.nodes.radius;
  7964. this.radiusFixed = false;
  7965. this.radiusMin = constants.nodes.radiusMin;
  7966. this.radiusMax = constants.nodes.radiusMax;
  7967. this.level = -1;
  7968. this.imagelist = imagelist;
  7969. this.grouplist = grouplist;
  7970. // physics properties
  7971. this.fx = 0.0; // external force x
  7972. this.fy = 0.0; // external force y
  7973. this.vx = 0.0; // velocity x
  7974. this.vy = 0.0; // velocity y
  7975. this.minForce = constants.minForce;
  7976. this.damping = constants.physics.damping;
  7977. this.mass = 1; // kg
  7978. this.fixedData = {x:null,y:null};
  7979. this.setProperties(properties, constants);
  7980. // creating the variables for clustering
  7981. this.resetCluster();
  7982. this.dynamicEdgesLength = 0;
  7983. this.clusterSession = 0;
  7984. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  7985. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  7986. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  7987. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  7988. this.growthIndicator = 0;
  7989. // variables to tell the node about the graph.
  7990. this.graphScaleInv = 1;
  7991. this.graphScale = 1;
  7992. this.canvasTopLeft = {"x": -300, "y": -300};
  7993. this.canvasBottomRight = {"x": 300, "y": 300};
  7994. this.parentEdgeId = null;
  7995. }
  7996. /**
  7997. * (re)setting the clustering variables and objects
  7998. */
  7999. Node.prototype.resetCluster = function() {
  8000. // clustering variables
  8001. this.formationScale = undefined; // this is used to determine when to open the cluster
  8002. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  8003. this.containedNodes = {};
  8004. this.containedEdges = {};
  8005. this.clusterSessions = [];
  8006. };
  8007. /**
  8008. * Attach a edge to the node
  8009. * @param {Edge} edge
  8010. */
  8011. Node.prototype.attachEdge = function(edge) {
  8012. if (this.edges.indexOf(edge) == -1) {
  8013. this.edges.push(edge);
  8014. }
  8015. if (this.dynamicEdges.indexOf(edge) == -1) {
  8016. this.dynamicEdges.push(edge);
  8017. }
  8018. this.dynamicEdgesLength = this.dynamicEdges.length;
  8019. };
  8020. /**
  8021. * Detach a edge from the node
  8022. * @param {Edge} edge
  8023. */
  8024. Node.prototype.detachEdge = function(edge) {
  8025. var index = this.edges.indexOf(edge);
  8026. if (index != -1) {
  8027. this.edges.splice(index, 1);
  8028. this.dynamicEdges.splice(index, 1);
  8029. }
  8030. this.dynamicEdgesLength = this.dynamicEdges.length;
  8031. };
  8032. /**
  8033. * Set or overwrite properties for the node
  8034. * @param {Object} properties an object with properties
  8035. * @param {Object} constants and object with default, global properties
  8036. */
  8037. Node.prototype.setProperties = function(properties, constants) {
  8038. if (!properties) {
  8039. return;
  8040. }
  8041. this.originalLabel = undefined;
  8042. // basic properties
  8043. if (properties.id !== undefined) {this.id = properties.id;}
  8044. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  8045. if (properties.title !== undefined) {this.title = properties.title;}
  8046. if (properties.group !== undefined) {this.group = properties.group;}
  8047. if (properties.x !== undefined) {this.x = properties.x;}
  8048. if (properties.y !== undefined) {this.y = properties.y;}
  8049. if (properties.value !== undefined) {this.value = properties.value;}
  8050. if (properties.level !== undefined) {this.level = properties.level;}
  8051. // physics
  8052. if (properties.mass !== undefined) {this.mass = properties.mass;}
  8053. // navigation controls properties
  8054. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  8055. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  8056. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  8057. if (this.id === undefined) {
  8058. throw "Node must have an id";
  8059. }
  8060. // copy group properties
  8061. if (this.group) {
  8062. var groupObj = this.grouplist.get(this.group);
  8063. for (var prop in groupObj) {
  8064. if (groupObj.hasOwnProperty(prop)) {
  8065. this[prop] = groupObj[prop];
  8066. }
  8067. }
  8068. }
  8069. // individual shape properties
  8070. if (properties.shape !== undefined) {this.shape = properties.shape;}
  8071. if (properties.image !== undefined) {this.image = properties.image;}
  8072. if (properties.radius !== undefined) {this.radius = properties.radius;}
  8073. if (properties.color !== undefined) {this.color = Node.parseColor(properties.color);}
  8074. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8075. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8076. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8077. if (this.image !== undefined && this.image != "") {
  8078. if (this.imagelist) {
  8079. this.imageObj = this.imagelist.load(this.image);
  8080. }
  8081. else {
  8082. throw "No imagelist provided";
  8083. }
  8084. }
  8085. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX);
  8086. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  8087. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  8088. if (this.shape == 'image') {
  8089. this.radiusMin = constants.nodes.widthMin;
  8090. this.radiusMax = constants.nodes.widthMax;
  8091. }
  8092. // choose draw method depending on the shape
  8093. switch (this.shape) {
  8094. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  8095. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  8096. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  8097. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8098. // TODO: add diamond shape
  8099. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  8100. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  8101. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  8102. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  8103. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  8104. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  8105. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  8106. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8107. }
  8108. // reset the size of the node, this can be changed
  8109. this._reset();
  8110. };
  8111. /**
  8112. * Parse a color property into an object with border, background, and
  8113. * hightlight colors
  8114. * @param {Object | String} color
  8115. * @return {Object} colorObject
  8116. */
  8117. Node.parseColor = function(color) {
  8118. var c;
  8119. if (util.isString(color)) {
  8120. if (util.isValidHex(color)) {
  8121. var hsv = util.hexToHSV(color);
  8122. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  8123. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  8124. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  8125. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  8126. c = {
  8127. background: color,
  8128. border:darkerColorHex,
  8129. highlight: {
  8130. background:lighterColorHex,
  8131. border:darkerColorHex
  8132. }
  8133. };
  8134. }
  8135. else {
  8136. c = {
  8137. background:color,
  8138. border:color,
  8139. highlight: {
  8140. background:color,
  8141. border:color
  8142. }
  8143. };
  8144. }
  8145. }
  8146. else {
  8147. c = {};
  8148. c.background = color.background || 'white';
  8149. c.border = color.border || c.background;
  8150. if (util.isString(color.highlight)) {
  8151. c.highlight = {
  8152. border: color.highlight,
  8153. background: color.highlight
  8154. }
  8155. }
  8156. else {
  8157. c.highlight = {};
  8158. c.highlight.background = color.highlight && color.highlight.background || c.background;
  8159. c.highlight.border = color.highlight && color.highlight.border || c.border;
  8160. }
  8161. }
  8162. return c;
  8163. };
  8164. /**
  8165. * select this node
  8166. */
  8167. Node.prototype.select = function() {
  8168. this.selected = true;
  8169. this._reset();
  8170. };
  8171. /**
  8172. * unselect this node
  8173. */
  8174. Node.prototype.unselect = function() {
  8175. this.selected = false;
  8176. this._reset();
  8177. };
  8178. /**
  8179. * Reset the calculated size of the node, forces it to recalculate its size
  8180. */
  8181. Node.prototype.clearSizeCache = function() {
  8182. this._reset();
  8183. };
  8184. /**
  8185. * Reset the calculated size of the node, forces it to recalculate its size
  8186. * @private
  8187. */
  8188. Node.prototype._reset = function() {
  8189. this.width = undefined;
  8190. this.height = undefined;
  8191. };
  8192. /**
  8193. * get the title of this node.
  8194. * @return {string} title The title of the node, or undefined when no title
  8195. * has been set.
  8196. */
  8197. Node.prototype.getTitle = function() {
  8198. return this.title;
  8199. };
  8200. /**
  8201. * Calculate the distance to the border of the Node
  8202. * @param {CanvasRenderingContext2D} ctx
  8203. * @param {Number} angle Angle in radians
  8204. * @returns {number} distance Distance to the border in pixels
  8205. */
  8206. Node.prototype.distanceToBorder = function (ctx, angle) {
  8207. var borderWidth = 1;
  8208. if (!this.width) {
  8209. this.resize(ctx);
  8210. }
  8211. switch (this.shape) {
  8212. case 'circle':
  8213. case 'dot':
  8214. return this.radius + borderWidth;
  8215. case 'ellipse':
  8216. var a = this.width / 2;
  8217. var b = this.height / 2;
  8218. var w = (Math.sin(angle) * a);
  8219. var h = (Math.cos(angle) * b);
  8220. return a * b / Math.sqrt(w * w + h * h);
  8221. // TODO: implement distanceToBorder for database
  8222. // TODO: implement distanceToBorder for triangle
  8223. // TODO: implement distanceToBorder for triangleDown
  8224. case 'box':
  8225. case 'image':
  8226. case 'text':
  8227. default:
  8228. if (this.width) {
  8229. return Math.min(
  8230. Math.abs(this.width / 2 / Math.cos(angle)),
  8231. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8232. // TODO: reckon with border radius too in case of box
  8233. }
  8234. else {
  8235. return 0;
  8236. }
  8237. }
  8238. // TODO: implement calculation of distance to border for all shapes
  8239. };
  8240. /**
  8241. * Set forces acting on the node
  8242. * @param {number} fx Force in horizontal direction
  8243. * @param {number} fy Force in vertical direction
  8244. */
  8245. Node.prototype._setForce = function(fx, fy) {
  8246. this.fx = fx;
  8247. this.fy = fy;
  8248. };
  8249. /**
  8250. * Add forces acting on the node
  8251. * @param {number} fx Force in horizontal direction
  8252. * @param {number} fy Force in vertical direction
  8253. * @private
  8254. */
  8255. Node.prototype._addForce = function(fx, fy) {
  8256. this.fx += fx;
  8257. this.fy += fy;
  8258. };
  8259. /**
  8260. * Perform one discrete step for the node
  8261. * @param {number} interval Time interval in seconds
  8262. */
  8263. Node.prototype.discreteStep = function(interval) {
  8264. if (!this.xFixed) {
  8265. var dx = this.damping * this.vx; // damping force
  8266. var ax = (this.fx - dx) / this.mass; // acceleration
  8267. this.vx += ax * interval; // velocity
  8268. this.x += this.vx * interval; // position
  8269. }
  8270. if (!this.yFixed) {
  8271. var dy = this.damping * this.vy; // damping force
  8272. var ay = (this.fy - dy) / this.mass; // acceleration
  8273. this.vy += ay * interval; // velocity
  8274. this.y += this.vy * interval; // position
  8275. }
  8276. };
  8277. /**
  8278. * Perform one discrete step for the node
  8279. * @param {number} interval Time interval in seconds
  8280. */
  8281. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8282. if (!this.xFixed) {
  8283. var dx = this.damping * this.vx; // damping force
  8284. var ax = (this.fx - dx) / this.mass; // acceleration
  8285. this.vx += ax * interval; // velocity
  8286. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8287. this.x += this.vx * interval; // position
  8288. }
  8289. else {
  8290. this.fx = 0;
  8291. }
  8292. if (!this.yFixed) {
  8293. var dy = this.damping * this.vy; // damping force
  8294. var ay = (this.fy - dy) / this.mass; // acceleration
  8295. this.vy += ay * interval; // velocity
  8296. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8297. this.y += this.vy * interval; // position
  8298. }
  8299. else {
  8300. this.fy = 0;
  8301. }
  8302. };
  8303. /**
  8304. * Check if this node has a fixed x and y position
  8305. * @return {boolean} true if fixed, false if not
  8306. */
  8307. Node.prototype.isFixed = function() {
  8308. return (this.xFixed && this.yFixed);
  8309. };
  8310. /**
  8311. * Check if this node is moving
  8312. * @param {number} vmin the minimum velocity considered as "moving"
  8313. * @return {boolean} true if moving, false if it has no velocity
  8314. */
  8315. // TODO: replace this method with calculating the kinetic energy
  8316. Node.prototype.isMoving = function(vmin) {
  8317. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8318. };
  8319. /**
  8320. * check if this node is selecte
  8321. * @return {boolean} selected True if node is selected, else false
  8322. */
  8323. Node.prototype.isSelected = function() {
  8324. return this.selected;
  8325. };
  8326. /**
  8327. * Retrieve the value of the node. Can be undefined
  8328. * @return {Number} value
  8329. */
  8330. Node.prototype.getValue = function() {
  8331. return this.value;
  8332. };
  8333. /**
  8334. * Calculate the distance from the nodes location to the given location (x,y)
  8335. * @param {Number} x
  8336. * @param {Number} y
  8337. * @return {Number} value
  8338. */
  8339. Node.prototype.getDistance = function(x, y) {
  8340. var dx = this.x - x,
  8341. dy = this.y - y;
  8342. return Math.sqrt(dx * dx + dy * dy);
  8343. };
  8344. /**
  8345. * Adjust the value range of the node. The node will adjust it's radius
  8346. * based on its value.
  8347. * @param {Number} min
  8348. * @param {Number} max
  8349. */
  8350. Node.prototype.setValueRange = function(min, max) {
  8351. if (!this.radiusFixed && this.value !== undefined) {
  8352. if (max == min) {
  8353. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8354. }
  8355. else {
  8356. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8357. this.radius = (this.value - min) * scale + this.radiusMin;
  8358. }
  8359. }
  8360. this.baseRadiusValue = this.radius;
  8361. };
  8362. /**
  8363. * Draw this node in the given canvas
  8364. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8365. * @param {CanvasRenderingContext2D} ctx
  8366. */
  8367. Node.prototype.draw = function(ctx) {
  8368. throw "Draw method not initialized for node";
  8369. };
  8370. /**
  8371. * Recalculate the size of this node in the given canvas
  8372. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8373. * @param {CanvasRenderingContext2D} ctx
  8374. */
  8375. Node.prototype.resize = function(ctx) {
  8376. throw "Resize method not initialized for node";
  8377. };
  8378. /**
  8379. * Check if this object is overlapping with the provided object
  8380. * @param {Object} obj an object with parameters left, top, right, bottom
  8381. * @return {boolean} True if location is located on node
  8382. */
  8383. Node.prototype.isOverlappingWith = function(obj) {
  8384. return (this.left < obj.right &&
  8385. this.left + this.width > obj.left &&
  8386. this.top < obj.bottom &&
  8387. this.top + this.height > obj.top);
  8388. };
  8389. Node.prototype._resizeImage = function (ctx) {
  8390. // TODO: pre calculate the image size
  8391. if (!this.width || !this.height) { // undefined or 0
  8392. var width, height;
  8393. if (this.value) {
  8394. this.radius = this.baseRadiusValue;
  8395. var scale = this.imageObj.height / this.imageObj.width;
  8396. if (scale !== undefined) {
  8397. width = this.radius || this.imageObj.width;
  8398. height = this.radius * scale || this.imageObj.height;
  8399. }
  8400. else {
  8401. width = 0;
  8402. height = 0;
  8403. }
  8404. }
  8405. else {
  8406. width = this.imageObj.width;
  8407. height = this.imageObj.height;
  8408. }
  8409. this.width = width;
  8410. this.height = height;
  8411. this.growthIndicator = 0;
  8412. if (this.width > 0 && this.height > 0) {
  8413. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8414. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8415. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8416. this.growthIndicator = this.width - width;
  8417. }
  8418. }
  8419. };
  8420. Node.prototype._drawImage = function (ctx) {
  8421. this._resizeImage(ctx);
  8422. this.left = this.x - this.width / 2;
  8423. this.top = this.y - this.height / 2;
  8424. var yLabel;
  8425. if (this.imageObj.width != 0 ) {
  8426. // draw the shade
  8427. if (this.clusterSize > 1) {
  8428. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8429. lineWidth *= this.graphScaleInv;
  8430. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8431. ctx.globalAlpha = 0.5;
  8432. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8433. }
  8434. // draw the image
  8435. ctx.globalAlpha = 1.0;
  8436. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8437. yLabel = this.y + this.height / 2;
  8438. }
  8439. else {
  8440. // image still loading... just draw the label for now
  8441. yLabel = this.y;
  8442. }
  8443. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8444. };
  8445. Node.prototype._resizeBox = function (ctx) {
  8446. if (!this.width) {
  8447. var margin = 5;
  8448. var textSize = this.getTextSize(ctx);
  8449. this.width = textSize.width + 2 * margin;
  8450. this.height = textSize.height + 2 * margin;
  8451. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8452. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8453. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8454. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8455. }
  8456. };
  8457. Node.prototype._drawBox = function (ctx) {
  8458. this._resizeBox(ctx);
  8459. this.left = this.x - this.width / 2;
  8460. this.top = this.y - this.height / 2;
  8461. var clusterLineWidth = 2.5;
  8462. var selectionLineWidth = 2;
  8463. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8464. // draw the outer border
  8465. if (this.clusterSize > 1) {
  8466. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8467. ctx.lineWidth *= this.graphScaleInv;
  8468. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8469. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8470. ctx.stroke();
  8471. }
  8472. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8473. ctx.lineWidth *= this.graphScaleInv;
  8474. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8475. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8476. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8477. ctx.fill();
  8478. ctx.stroke();
  8479. this._label(ctx, this.label, this.x, this.y);
  8480. };
  8481. Node.prototype._resizeDatabase = function (ctx) {
  8482. if (!this.width) {
  8483. var margin = 5;
  8484. var textSize = this.getTextSize(ctx);
  8485. var size = textSize.width + 2 * margin;
  8486. this.width = size;
  8487. this.height = size;
  8488. // scaling used for clustering
  8489. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8490. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8491. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8492. this.growthIndicator = this.width - size;
  8493. }
  8494. };
  8495. Node.prototype._drawDatabase = function (ctx) {
  8496. this._resizeDatabase(ctx);
  8497. this.left = this.x - this.width / 2;
  8498. this.top = this.y - this.height / 2;
  8499. var clusterLineWidth = 2.5;
  8500. var selectionLineWidth = 2;
  8501. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8502. // draw the outer border
  8503. if (this.clusterSize > 1) {
  8504. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8505. ctx.lineWidth *= this.graphScaleInv;
  8506. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8507. 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);
  8508. ctx.stroke();
  8509. }
  8510. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8511. ctx.lineWidth *= this.graphScaleInv;
  8512. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8513. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8514. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8515. ctx.fill();
  8516. ctx.stroke();
  8517. this._label(ctx, this.label, this.x, this.y);
  8518. };
  8519. Node.prototype._resizeCircle = function (ctx) {
  8520. if (!this.width) {
  8521. var margin = 5;
  8522. var textSize = this.getTextSize(ctx);
  8523. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8524. this.radius = diameter / 2;
  8525. this.width = diameter;
  8526. this.height = diameter;
  8527. // scaling used for clustering
  8528. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8529. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8530. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8531. this.growthIndicator = this.radius - 0.5*diameter;
  8532. }
  8533. };
  8534. Node.prototype._drawCircle = function (ctx) {
  8535. this._resizeCircle(ctx);
  8536. this.left = this.x - this.width / 2;
  8537. this.top = this.y - this.height / 2;
  8538. var clusterLineWidth = 2.5;
  8539. var selectionLineWidth = 2;
  8540. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8541. // draw the outer border
  8542. if (this.clusterSize > 1) {
  8543. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8544. ctx.lineWidth *= this.graphScaleInv;
  8545. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8546. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8547. ctx.stroke();
  8548. }
  8549. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8550. ctx.lineWidth *= this.graphScaleInv;
  8551. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8552. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8553. ctx.circle(this.x, this.y, this.radius);
  8554. ctx.fill();
  8555. ctx.stroke();
  8556. this._label(ctx, this.label, this.x, this.y);
  8557. };
  8558. Node.prototype._resizeEllipse = function (ctx) {
  8559. if (!this.width) {
  8560. var textSize = this.getTextSize(ctx);
  8561. this.width = textSize.width * 1.5;
  8562. this.height = textSize.height * 2;
  8563. if (this.width < this.height) {
  8564. this.width = this.height;
  8565. }
  8566. var defaultSize = this.width;
  8567. // scaling used for clustering
  8568. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8569. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8570. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8571. this.growthIndicator = this.width - defaultSize;
  8572. }
  8573. };
  8574. Node.prototype._drawEllipse = function (ctx) {
  8575. this._resizeEllipse(ctx);
  8576. this.left = this.x - this.width / 2;
  8577. this.top = this.y - this.height / 2;
  8578. var clusterLineWidth = 2.5;
  8579. var selectionLineWidth = 2;
  8580. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8581. // draw the outer border
  8582. if (this.clusterSize > 1) {
  8583. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8584. ctx.lineWidth *= this.graphScaleInv;
  8585. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8586. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8587. ctx.stroke();
  8588. }
  8589. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8590. ctx.lineWidth *= this.graphScaleInv;
  8591. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8592. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8593. ctx.ellipse(this.left, this.top, this.width, this.height);
  8594. ctx.fill();
  8595. ctx.stroke();
  8596. this._label(ctx, this.label, this.x, this.y);
  8597. };
  8598. Node.prototype._drawDot = function (ctx) {
  8599. this._drawShape(ctx, 'circle');
  8600. };
  8601. Node.prototype._drawTriangle = function (ctx) {
  8602. this._drawShape(ctx, 'triangle');
  8603. };
  8604. Node.prototype._drawTriangleDown = function (ctx) {
  8605. this._drawShape(ctx, 'triangleDown');
  8606. };
  8607. Node.prototype._drawSquare = function (ctx) {
  8608. this._drawShape(ctx, 'square');
  8609. };
  8610. Node.prototype._drawStar = function (ctx) {
  8611. this._drawShape(ctx, 'star');
  8612. };
  8613. Node.prototype._resizeShape = function (ctx) {
  8614. if (!this.width) {
  8615. this.radius = this.baseRadiusValue;
  8616. var size = 2 * this.radius;
  8617. this.width = size;
  8618. this.height = size;
  8619. // scaling used for clustering
  8620. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8621. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8622. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8623. this.growthIndicator = this.width - size;
  8624. }
  8625. };
  8626. Node.prototype._drawShape = function (ctx, shape) {
  8627. this._resizeShape(ctx);
  8628. this.left = this.x - this.width / 2;
  8629. this.top = this.y - this.height / 2;
  8630. var clusterLineWidth = 2.5;
  8631. var selectionLineWidth = 2;
  8632. var radiusMultiplier = 2;
  8633. // choose draw method depending on the shape
  8634. switch (shape) {
  8635. case 'dot': radiusMultiplier = 2; break;
  8636. case 'square': radiusMultiplier = 2; break;
  8637. case 'triangle': radiusMultiplier = 3; break;
  8638. case 'triangleDown': radiusMultiplier = 3; break;
  8639. case 'star': radiusMultiplier = 4; break;
  8640. }
  8641. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8642. // draw the outer border
  8643. if (this.clusterSize > 1) {
  8644. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8645. ctx.lineWidth *= this.graphScaleInv;
  8646. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8647. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8648. ctx.stroke();
  8649. }
  8650. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8651. ctx.lineWidth *= this.graphScaleInv;
  8652. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8653. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8654. ctx[shape](this.x, this.y, this.radius);
  8655. ctx.fill();
  8656. ctx.stroke();
  8657. if (this.label) {
  8658. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8659. }
  8660. };
  8661. Node.prototype._resizeText = function (ctx) {
  8662. if (!this.width) {
  8663. var margin = 5;
  8664. var textSize = this.getTextSize(ctx);
  8665. this.width = textSize.width + 2 * margin;
  8666. this.height = textSize.height + 2 * margin;
  8667. // scaling used for clustering
  8668. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8669. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8670. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8671. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8672. }
  8673. };
  8674. Node.prototype._drawText = function (ctx) {
  8675. this._resizeText(ctx);
  8676. this.left = this.x - this.width / 2;
  8677. this.top = this.y - this.height / 2;
  8678. this._label(ctx, this.label, this.x, this.y);
  8679. };
  8680. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  8681. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  8682. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8683. ctx.fillStyle = this.fontColor || "black";
  8684. ctx.textAlign = align || "center";
  8685. ctx.textBaseline = baseline || "middle";
  8686. var lines = text.split('\n'),
  8687. lineCount = lines.length,
  8688. fontSize = (this.fontSize + 4),
  8689. yLine = y + (1 - lineCount) / 2 * fontSize;
  8690. for (var i = 0; i < lineCount; i++) {
  8691. ctx.fillText(lines[i], x, yLine);
  8692. yLine += fontSize;
  8693. }
  8694. }
  8695. };
  8696. Node.prototype.getTextSize = function(ctx) {
  8697. if (this.label !== undefined) {
  8698. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  8699. var lines = this.label.split('\n'),
  8700. height = (this.fontSize + 4) * lines.length,
  8701. width = 0;
  8702. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  8703. width = Math.max(width, ctx.measureText(lines[i]).width);
  8704. }
  8705. return {"width": width, "height": height};
  8706. }
  8707. else {
  8708. return {"width": 0, "height": 0};
  8709. }
  8710. };
  8711. /**
  8712. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  8713. * there is a safety margin of 0.3 * width;
  8714. *
  8715. * @returns {boolean}
  8716. */
  8717. Node.prototype.inArea = function() {
  8718. if (this.width !== undefined) {
  8719. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  8720. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  8721. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  8722. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  8723. }
  8724. else {
  8725. return true;
  8726. }
  8727. };
  8728. /**
  8729. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  8730. * @returns {boolean}
  8731. */
  8732. Node.prototype.inView = function() {
  8733. return (this.x >= this.canvasTopLeft.x &&
  8734. this.x < this.canvasBottomRight.x &&
  8735. this.y >= this.canvasTopLeft.y &&
  8736. this.y < this.canvasBottomRight.y);
  8737. };
  8738. /**
  8739. * This allows the zoom level of the graph to influence the rendering
  8740. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  8741. *
  8742. * @param scale
  8743. * @param canvasTopLeft
  8744. * @param canvasBottomRight
  8745. */
  8746. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  8747. this.graphScaleInv = 1.0/scale;
  8748. this.graphScale = scale;
  8749. this.canvasTopLeft = canvasTopLeft;
  8750. this.canvasBottomRight = canvasBottomRight;
  8751. };
  8752. /**
  8753. * This allows the zoom level of the graph to influence the rendering
  8754. *
  8755. * @param scale
  8756. */
  8757. Node.prototype.setScale = function(scale) {
  8758. this.graphScaleInv = 1.0/scale;
  8759. this.graphScale = scale;
  8760. };
  8761. /**
  8762. * set the velocity at 0. Is called when this node is contained in another during clustering
  8763. */
  8764. Node.prototype.clearVelocity = function() {
  8765. this.vx = 0;
  8766. this.vy = 0;
  8767. };
  8768. /**
  8769. * Basic preservation of (kinectic) energy
  8770. *
  8771. * @param massBeforeClustering
  8772. */
  8773. Node.prototype.updateVelocity = function(massBeforeClustering) {
  8774. var energyBefore = this.vx * this.vx * massBeforeClustering;
  8775. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8776. this.vx = Math.sqrt(energyBefore/this.mass);
  8777. energyBefore = this.vy * this.vy * massBeforeClustering;
  8778. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  8779. this.vy = Math.sqrt(energyBefore/this.mass);
  8780. };
  8781. /**
  8782. * @class Edge
  8783. *
  8784. * A edge connects two nodes
  8785. * @param {Object} properties Object with properties. Must contain
  8786. * At least properties from and to.
  8787. * Available properties: from (number),
  8788. * to (number), label (string, color (string),
  8789. * width (number), style (string),
  8790. * length (number), title (string)
  8791. * @param {Graph} graph A graph object, used to find and edge to
  8792. * nodes.
  8793. * @param {Object} constants An object with default values for
  8794. * example for the color
  8795. */
  8796. function Edge (properties, graph, constants) {
  8797. if (!graph) {
  8798. throw "No graph provided";
  8799. }
  8800. this.graph = graph;
  8801. // initialize constants
  8802. this.widthMin = constants.edges.widthMin;
  8803. this.widthMax = constants.edges.widthMax;
  8804. // initialize variables
  8805. this.id = undefined;
  8806. this.fromId = undefined;
  8807. this.toId = undefined;
  8808. this.style = constants.edges.style;
  8809. this.title = undefined;
  8810. this.width = constants.edges.width;
  8811. this.value = undefined;
  8812. this.length = constants.physics.springLength;
  8813. this.customLength = false;
  8814. this.selected = false;
  8815. this.smooth = constants.smoothCurves;
  8816. this.from = null; // a node
  8817. this.to = null; // a node
  8818. this.via = null; // a temp node
  8819. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  8820. // by storing the original information we can revert to the original connection when the cluser is opened.
  8821. this.originalFromId = [];
  8822. this.originalToId = [];
  8823. this.connected = false;
  8824. // Added to support dashed lines
  8825. // David Jordan
  8826. // 2012-08-08
  8827. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  8828. this.color = {color:constants.edges.color.color,
  8829. highlight:constants.edges.color.highlight};
  8830. this.widthFixed = false;
  8831. this.lengthFixed = false;
  8832. this.setProperties(properties, constants);
  8833. }
  8834. /**
  8835. * Set or overwrite properties for the edge
  8836. * @param {Object} properties an object with properties
  8837. * @param {Object} constants and object with default, global properties
  8838. */
  8839. Edge.prototype.setProperties = function(properties, constants) {
  8840. if (!properties) {
  8841. return;
  8842. }
  8843. if (properties.from !== undefined) {this.fromId = properties.from;}
  8844. if (properties.to !== undefined) {this.toId = properties.to;}
  8845. if (properties.id !== undefined) {this.id = properties.id;}
  8846. if (properties.style !== undefined) {this.style = properties.style;}
  8847. if (properties.label !== undefined) {this.label = properties.label;}
  8848. if (this.label) {
  8849. this.fontSize = constants.edges.fontSize;
  8850. this.fontFace = constants.edges.fontFace;
  8851. this.fontColor = constants.edges.fontColor;
  8852. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8853. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8854. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8855. }
  8856. if (properties.title !== undefined) {this.title = properties.title;}
  8857. if (properties.width !== undefined) {this.width = properties.width;}
  8858. if (properties.value !== undefined) {this.value = properties.value;}
  8859. if (properties.length !== undefined) {this.length = properties.length;
  8860. this.customLength = true;}
  8861. // Added to support dashed lines
  8862. // David Jordan
  8863. // 2012-08-08
  8864. if (properties.dash) {
  8865. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  8866. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  8867. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  8868. }
  8869. if (properties.color !== undefined) {
  8870. if (util.isString(properties.color)) {
  8871. this.color.color = properties.color;
  8872. this.color.highlight = properties.color;
  8873. }
  8874. else {
  8875. if (properties.color.color !== undefined) {this.color.color = properties.color.color;}
  8876. if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;}
  8877. }
  8878. }
  8879. // A node is connected when it has a from and to node.
  8880. this.connect();
  8881. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  8882. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  8883. // set draw method based on style
  8884. switch (this.style) {
  8885. case 'line': this.draw = this._drawLine; break;
  8886. case 'arrow': this.draw = this._drawArrow; break;
  8887. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  8888. case 'dash-line': this.draw = this._drawDashLine; break;
  8889. default: this.draw = this._drawLine; break;
  8890. }
  8891. };
  8892. /**
  8893. * Connect an edge to its nodes
  8894. */
  8895. Edge.prototype.connect = function () {
  8896. this.disconnect();
  8897. this.from = this.graph.nodes[this.fromId] || null;
  8898. this.to = this.graph.nodes[this.toId] || null;
  8899. this.connected = (this.from && this.to);
  8900. if (this.connected) {
  8901. this.from.attachEdge(this);
  8902. this.to.attachEdge(this);
  8903. }
  8904. else {
  8905. if (this.from) {
  8906. this.from.detachEdge(this);
  8907. }
  8908. if (this.to) {
  8909. this.to.detachEdge(this);
  8910. }
  8911. }
  8912. };
  8913. /**
  8914. * Disconnect an edge from its nodes
  8915. */
  8916. Edge.prototype.disconnect = function () {
  8917. if (this.from) {
  8918. this.from.detachEdge(this);
  8919. this.from = null;
  8920. }
  8921. if (this.to) {
  8922. this.to.detachEdge(this);
  8923. this.to = null;
  8924. }
  8925. this.connected = false;
  8926. };
  8927. /**
  8928. * get the title of this edge.
  8929. * @return {string} title The title of the edge, or undefined when no title
  8930. * has been set.
  8931. */
  8932. Edge.prototype.getTitle = function() {
  8933. return this.title;
  8934. };
  8935. /**
  8936. * Retrieve the value of the edge. Can be undefined
  8937. * @return {Number} value
  8938. */
  8939. Edge.prototype.getValue = function() {
  8940. return this.value;
  8941. };
  8942. /**
  8943. * Adjust the value range of the edge. The edge will adjust it's width
  8944. * based on its value.
  8945. * @param {Number} min
  8946. * @param {Number} max
  8947. */
  8948. Edge.prototype.setValueRange = function(min, max) {
  8949. if (!this.widthFixed && this.value !== undefined) {
  8950. var scale = (this.widthMax - this.widthMin) / (max - min);
  8951. this.width = (this.value - min) * scale + this.widthMin;
  8952. }
  8953. };
  8954. /**
  8955. * Redraw a edge
  8956. * Draw this edge in the given canvas
  8957. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8958. * @param {CanvasRenderingContext2D} ctx
  8959. */
  8960. Edge.prototype.draw = function(ctx) {
  8961. throw "Method draw not initialized in edge";
  8962. };
  8963. /**
  8964. * Check if this object is overlapping with the provided object
  8965. * @param {Object} obj an object with parameters left, top
  8966. * @return {boolean} True if location is located on the edge
  8967. */
  8968. Edge.prototype.isOverlappingWith = function(obj) {
  8969. if (this.connected == true) {
  8970. var distMax = 10;
  8971. var xFrom = this.from.x;
  8972. var yFrom = this.from.y;
  8973. var xTo = this.to.x;
  8974. var yTo = this.to.y;
  8975. var xObj = obj.left;
  8976. var yObj = obj.top;
  8977. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  8978. return (dist < distMax);
  8979. }
  8980. else {
  8981. return false
  8982. }
  8983. };
  8984. /**
  8985. * Redraw a edge as a line
  8986. * Draw this edge in the given canvas
  8987. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8988. * @param {CanvasRenderingContext2D} ctx
  8989. * @private
  8990. */
  8991. Edge.prototype._drawLine = function(ctx) {
  8992. // set style
  8993. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  8994. else {ctx.strokeStyle = this.color.color;}
  8995. ctx.lineWidth = this._getLineWidth();
  8996. if (this.from != this.to) {
  8997. // draw line
  8998. this._line(ctx);
  8999. // draw label
  9000. var point;
  9001. if (this.label) {
  9002. if (this.smooth == true) {
  9003. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9004. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9005. point = {x:midpointX, y:midpointY};
  9006. }
  9007. else {
  9008. point = this._pointOnLine(0.5);
  9009. }
  9010. this._label(ctx, this.label, point.x, point.y);
  9011. }
  9012. }
  9013. else {
  9014. var x, y;
  9015. var radius = this.length / 4;
  9016. var node = this.from;
  9017. if (!node.width) {
  9018. node.resize(ctx);
  9019. }
  9020. if (node.width > node.height) {
  9021. x = node.x + node.width / 2;
  9022. y = node.y - radius;
  9023. }
  9024. else {
  9025. x = node.x + radius;
  9026. y = node.y - node.height / 2;
  9027. }
  9028. this._circle(ctx, x, y, radius);
  9029. point = this._pointOnCircle(x, y, radius, 0.5);
  9030. this._label(ctx, this.label, point.x, point.y);
  9031. }
  9032. };
  9033. /**
  9034. * Get the line width of the edge. Depends on width and whether one of the
  9035. * connected nodes is selected.
  9036. * @return {Number} width
  9037. * @private
  9038. */
  9039. Edge.prototype._getLineWidth = function() {
  9040. if (this.selected == true) {
  9041. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  9042. }
  9043. else {
  9044. return this.width*this.graphScaleInv;
  9045. }
  9046. };
  9047. /**
  9048. * Draw a line between two nodes
  9049. * @param {CanvasRenderingContext2D} ctx
  9050. * @private
  9051. */
  9052. Edge.prototype._line = function (ctx) {
  9053. // draw a straight line
  9054. ctx.beginPath();
  9055. ctx.moveTo(this.from.x, this.from.y);
  9056. if (this.smooth == true) {
  9057. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9058. }
  9059. else {
  9060. ctx.lineTo(this.to.x, this.to.y);
  9061. }
  9062. ctx.stroke();
  9063. };
  9064. /**
  9065. * Draw a line from a node to itself, a circle
  9066. * @param {CanvasRenderingContext2D} ctx
  9067. * @param {Number} x
  9068. * @param {Number} y
  9069. * @param {Number} radius
  9070. * @private
  9071. */
  9072. Edge.prototype._circle = function (ctx, x, y, radius) {
  9073. // draw a circle
  9074. ctx.beginPath();
  9075. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9076. ctx.stroke();
  9077. };
  9078. /**
  9079. * Draw label with white background and with the middle at (x, y)
  9080. * @param {CanvasRenderingContext2D} ctx
  9081. * @param {String} text
  9082. * @param {Number} x
  9083. * @param {Number} y
  9084. * @private
  9085. */
  9086. Edge.prototype._label = function (ctx, text, x, y) {
  9087. if (text) {
  9088. // TODO: cache the calculated size
  9089. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  9090. this.fontSize + "px " + this.fontFace;
  9091. ctx.fillStyle = 'white';
  9092. var width = ctx.measureText(text).width;
  9093. var height = this.fontSize;
  9094. var left = x - width / 2;
  9095. var top = y - height / 2;
  9096. ctx.fillRect(left, top, width, height);
  9097. // draw text
  9098. ctx.fillStyle = this.fontColor || "black";
  9099. ctx.textAlign = "left";
  9100. ctx.textBaseline = "top";
  9101. ctx.fillText(text, left, top);
  9102. }
  9103. };
  9104. /**
  9105. * Redraw a edge as a dashed line
  9106. * Draw this edge in the given canvas
  9107. * @author David Jordan
  9108. * @date 2012-08-08
  9109. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9110. * @param {CanvasRenderingContext2D} ctx
  9111. * @private
  9112. */
  9113. Edge.prototype._drawDashLine = function(ctx) {
  9114. // set style
  9115. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9116. else {ctx.strokeStyle = this.color.color;}
  9117. ctx.lineWidth = this._getLineWidth();
  9118. // only firefox and chrome support this method, else we use the legacy one.
  9119. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  9120. ctx.beginPath();
  9121. ctx.moveTo(this.from.x, this.from.y);
  9122. // configure the dash pattern
  9123. var pattern = [0];
  9124. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  9125. pattern = [this.dash.length,this.dash.gap];
  9126. }
  9127. else {
  9128. pattern = [5,5];
  9129. }
  9130. // set dash settings for chrome or firefox
  9131. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9132. ctx.setLineDash(pattern);
  9133. ctx.lineDashOffset = 0;
  9134. } else { //Firefox
  9135. ctx.mozDash = pattern;
  9136. ctx.mozDashOffset = 0;
  9137. }
  9138. // draw the line
  9139. if (this.smooth == true) {
  9140. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9141. }
  9142. else {
  9143. ctx.lineTo(this.to.x, this.to.y);
  9144. }
  9145. ctx.stroke();
  9146. // restore the dash settings.
  9147. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9148. ctx.setLineDash([0]);
  9149. ctx.lineDashOffset = 0;
  9150. } else { //Firefox
  9151. ctx.mozDash = [0];
  9152. ctx.mozDashOffset = 0;
  9153. }
  9154. }
  9155. else { // unsupporting smooth lines
  9156. // draw dashed line
  9157. ctx.beginPath();
  9158. ctx.lineCap = 'round';
  9159. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9160. {
  9161. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9162. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9163. }
  9164. 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
  9165. {
  9166. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9167. [this.dash.length,this.dash.gap]);
  9168. }
  9169. else //If all else fails draw a line
  9170. {
  9171. ctx.moveTo(this.from.x, this.from.y);
  9172. ctx.lineTo(this.to.x, this.to.y);
  9173. }
  9174. ctx.stroke();
  9175. }
  9176. // draw label
  9177. if (this.label) {
  9178. var point;
  9179. if (this.smooth == true) {
  9180. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9181. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9182. point = {x:midpointX, y:midpointY};
  9183. }
  9184. else {
  9185. point = this._pointOnLine(0.5);
  9186. }
  9187. this._label(ctx, this.label, point.x, point.y);
  9188. }
  9189. };
  9190. /**
  9191. * Get a point on a line
  9192. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9193. * @return {Object} point
  9194. * @private
  9195. */
  9196. Edge.prototype._pointOnLine = function (percentage) {
  9197. return {
  9198. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9199. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9200. }
  9201. };
  9202. /**
  9203. * Get a point on a circle
  9204. * @param {Number} x
  9205. * @param {Number} y
  9206. * @param {Number} radius
  9207. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9208. * @return {Object} point
  9209. * @private
  9210. */
  9211. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9212. var angle = (percentage - 3/8) * 2 * Math.PI;
  9213. return {
  9214. x: x + radius * Math.cos(angle),
  9215. y: y - radius * Math.sin(angle)
  9216. }
  9217. };
  9218. /**
  9219. * Redraw a edge as a line with an arrow halfway the line
  9220. * Draw this edge in the given canvas
  9221. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9222. * @param {CanvasRenderingContext2D} ctx
  9223. * @private
  9224. */
  9225. Edge.prototype._drawArrowCenter = function(ctx) {
  9226. var point;
  9227. // set style
  9228. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9229. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9230. ctx.lineWidth = this._getLineWidth();
  9231. if (this.from != this.to) {
  9232. // draw line
  9233. this._line(ctx);
  9234. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9235. var length = 10 + 5 * this.width; // TODO: make customizable?
  9236. // draw an arrow halfway the line
  9237. if (this.smooth == true) {
  9238. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9239. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9240. point = {x:midpointX, y:midpointY};
  9241. }
  9242. else {
  9243. point = this._pointOnLine(0.5);
  9244. }
  9245. ctx.arrow(point.x, point.y, angle, length);
  9246. ctx.fill();
  9247. ctx.stroke();
  9248. // draw label
  9249. if (this.label) {
  9250. this._label(ctx, this.label, point.x, point.y);
  9251. }
  9252. }
  9253. else {
  9254. // draw circle
  9255. var x, y;
  9256. var radius = 0.25 * Math.max(100,this.length);
  9257. var node = this.from;
  9258. if (!node.width) {
  9259. node.resize(ctx);
  9260. }
  9261. if (node.width > node.height) {
  9262. x = node.x + node.width * 0.5;
  9263. y = node.y - radius;
  9264. }
  9265. else {
  9266. x = node.x + radius;
  9267. y = node.y - node.height * 0.5;
  9268. }
  9269. this._circle(ctx, x, y, radius);
  9270. // draw all arrows
  9271. var angle = 0.2 * Math.PI;
  9272. var length = 10 + 5 * this.width; // TODO: make customizable?
  9273. point = this._pointOnCircle(x, y, radius, 0.5);
  9274. ctx.arrow(point.x, point.y, angle, length);
  9275. ctx.fill();
  9276. ctx.stroke();
  9277. // draw label
  9278. if (this.label) {
  9279. point = this._pointOnCircle(x, y, radius, 0.5);
  9280. this._label(ctx, this.label, point.x, point.y);
  9281. }
  9282. }
  9283. };
  9284. /**
  9285. * Redraw a edge as a line with an arrow
  9286. * Draw this edge in the given canvas
  9287. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9288. * @param {CanvasRenderingContext2D} ctx
  9289. * @private
  9290. */
  9291. Edge.prototype._drawArrow = function(ctx) {
  9292. // set style
  9293. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9294. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9295. ctx.lineWidth = this._getLineWidth();
  9296. var angle, length;
  9297. //draw a line
  9298. if (this.from != this.to) {
  9299. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9300. var dx = (this.to.x - this.from.x);
  9301. var dy = (this.to.y - this.from.y);
  9302. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9303. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9304. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9305. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9306. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9307. if (this.smooth == true) {
  9308. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9309. dx = (this.to.x - this.via.x);
  9310. dy = (this.to.y - this.via.y);
  9311. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9312. }
  9313. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9314. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9315. var xTo,yTo;
  9316. if (this.smooth == true) {
  9317. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9318. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9319. }
  9320. else {
  9321. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9322. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9323. }
  9324. ctx.beginPath();
  9325. ctx.moveTo(xFrom,yFrom);
  9326. if (this.smooth == true) {
  9327. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9328. }
  9329. else {
  9330. ctx.lineTo(xTo, yTo);
  9331. }
  9332. ctx.stroke();
  9333. // draw arrow at the end of the line
  9334. length = 10 + 5 * this.width;
  9335. ctx.arrow(xTo, yTo, angle, length);
  9336. ctx.fill();
  9337. ctx.stroke();
  9338. // draw label
  9339. if (this.label) {
  9340. var point;
  9341. if (this.smooth == true) {
  9342. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9343. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9344. point = {x:midpointX, y:midpointY};
  9345. }
  9346. else {
  9347. point = this._pointOnLine(0.5);
  9348. }
  9349. this._label(ctx, this.label, point.x, point.y);
  9350. }
  9351. }
  9352. else {
  9353. // draw circle
  9354. var node = this.from;
  9355. var x, y, arrow;
  9356. var radius = 0.25 * Math.max(100,this.length);
  9357. if (!node.width) {
  9358. node.resize(ctx);
  9359. }
  9360. if (node.width > node.height) {
  9361. x = node.x + node.width * 0.5;
  9362. y = node.y - radius;
  9363. arrow = {
  9364. x: x,
  9365. y: node.y,
  9366. angle: 0.9 * Math.PI
  9367. };
  9368. }
  9369. else {
  9370. x = node.x + radius;
  9371. y = node.y - node.height * 0.5;
  9372. arrow = {
  9373. x: node.x,
  9374. y: y,
  9375. angle: 0.6 * Math.PI
  9376. };
  9377. }
  9378. ctx.beginPath();
  9379. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9380. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9381. ctx.stroke();
  9382. // draw all arrows
  9383. length = 10 + 5 * this.width; // TODO: make customizable?
  9384. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9385. ctx.fill();
  9386. ctx.stroke();
  9387. // draw label
  9388. if (this.label) {
  9389. point = this._pointOnCircle(x, y, radius, 0.5);
  9390. this._label(ctx, this.label, point.x, point.y);
  9391. }
  9392. }
  9393. };
  9394. /**
  9395. * Calculate the distance between a point (x3,y3) and a line segment from
  9396. * (x1,y1) to (x2,y2).
  9397. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9398. * @param {number} x1
  9399. * @param {number} y1
  9400. * @param {number} x2
  9401. * @param {number} y2
  9402. * @param {number} x3
  9403. * @param {number} y3
  9404. * @private
  9405. */
  9406. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9407. if (this.smooth == true) {
  9408. var minDistance = 1e9;
  9409. var i,t,x,y,dx,dy;
  9410. for (i = 0; i < 10; i++) {
  9411. t = 0.1*i;
  9412. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9413. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9414. dx = Math.abs(x3-x);
  9415. dy = Math.abs(y3-y);
  9416. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9417. }
  9418. return minDistance
  9419. }
  9420. else {
  9421. var px = x2-x1,
  9422. py = y2-y1,
  9423. something = px*px + py*py,
  9424. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9425. if (u > 1) {
  9426. u = 1;
  9427. }
  9428. else if (u < 0) {
  9429. u = 0;
  9430. }
  9431. var x = x1 + u * px,
  9432. y = y1 + u * py,
  9433. dx = x - x3,
  9434. dy = y - y3;
  9435. //# Note: If the actual distance does not matter,
  9436. //# if you only want to compare what this function
  9437. //# returns to other results of this function, you
  9438. //# can just return the squared distance instead
  9439. //# (i.e. remove the sqrt) to gain a little performance
  9440. return Math.sqrt(dx*dx + dy*dy);
  9441. }
  9442. };
  9443. /**
  9444. * This allows the zoom level of the graph to influence the rendering
  9445. *
  9446. * @param scale
  9447. */
  9448. Edge.prototype.setScale = function(scale) {
  9449. this.graphScaleInv = 1.0/scale;
  9450. };
  9451. Edge.prototype.select = function() {
  9452. this.selected = true;
  9453. };
  9454. Edge.prototype.unselect = function() {
  9455. this.selected = false;
  9456. };
  9457. Edge.prototype.positionBezierNode = function() {
  9458. if (this.via !== null) {
  9459. this.via.x = 0.5 * (this.from.x + this.to.x);
  9460. this.via.y = 0.5 * (this.from.y + this.to.y);
  9461. }
  9462. };
  9463. /**
  9464. * Popup is a class to create a popup window with some text
  9465. * @param {Element} container The container object.
  9466. * @param {Number} [x]
  9467. * @param {Number} [y]
  9468. * @param {String} [text]
  9469. */
  9470. function Popup(container, x, y, text) {
  9471. if (container) {
  9472. this.container = container;
  9473. }
  9474. else {
  9475. this.container = document.body;
  9476. }
  9477. this.x = 0;
  9478. this.y = 0;
  9479. this.padding = 5;
  9480. if (x !== undefined && y !== undefined ) {
  9481. this.setPosition(x, y);
  9482. }
  9483. if (text !== undefined) {
  9484. this.setText(text);
  9485. }
  9486. // create the frame
  9487. this.frame = document.createElement("div");
  9488. var style = this.frame.style;
  9489. style.position = "absolute";
  9490. style.visibility = "hidden";
  9491. style.border = "1px solid #666";
  9492. style.color = "black";
  9493. style.padding = this.padding + "px";
  9494. style.backgroundColor = "#FFFFC6";
  9495. style.borderRadius = "3px";
  9496. style.MozBorderRadius = "3px";
  9497. style.WebkitBorderRadius = "3px";
  9498. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9499. style.whiteSpace = "nowrap";
  9500. this.container.appendChild(this.frame);
  9501. }
  9502. /**
  9503. * @param {number} x Horizontal position of the popup window
  9504. * @param {number} y Vertical position of the popup window
  9505. */
  9506. Popup.prototype.setPosition = function(x, y) {
  9507. this.x = parseInt(x);
  9508. this.y = parseInt(y);
  9509. };
  9510. /**
  9511. * Set the text for the popup window. This can be HTML code
  9512. * @param {string} text
  9513. */
  9514. Popup.prototype.setText = function(text) {
  9515. this.frame.innerHTML = text;
  9516. };
  9517. /**
  9518. * Show the popup window
  9519. * @param {boolean} show Optional. Show or hide the window
  9520. */
  9521. Popup.prototype.show = function (show) {
  9522. if (show === undefined) {
  9523. show = true;
  9524. }
  9525. if (show) {
  9526. var height = this.frame.clientHeight;
  9527. var width = this.frame.clientWidth;
  9528. var maxHeight = this.frame.parentNode.clientHeight;
  9529. var maxWidth = this.frame.parentNode.clientWidth;
  9530. var top = (this.y - height);
  9531. if (top + height + this.padding > maxHeight) {
  9532. top = maxHeight - height - this.padding;
  9533. }
  9534. if (top < this.padding) {
  9535. top = this.padding;
  9536. }
  9537. var left = this.x;
  9538. if (left + width + this.padding > maxWidth) {
  9539. left = maxWidth - width - this.padding;
  9540. }
  9541. if (left < this.padding) {
  9542. left = this.padding;
  9543. }
  9544. this.frame.style.left = left + "px";
  9545. this.frame.style.top = top + "px";
  9546. this.frame.style.visibility = "visible";
  9547. }
  9548. else {
  9549. this.hide();
  9550. }
  9551. };
  9552. /**
  9553. * Hide the popup window
  9554. */
  9555. Popup.prototype.hide = function () {
  9556. this.frame.style.visibility = "hidden";
  9557. };
  9558. /**
  9559. * @class Groups
  9560. * This class can store groups and properties specific for groups.
  9561. */
  9562. Groups = function () {
  9563. this.clear();
  9564. this.defaultIndex = 0;
  9565. };
  9566. /**
  9567. * default constants for group colors
  9568. */
  9569. Groups.DEFAULT = [
  9570. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9571. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9572. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9573. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9574. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9575. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9576. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9577. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9578. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9579. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9580. ];
  9581. /**
  9582. * Clear all groups
  9583. */
  9584. Groups.prototype.clear = function () {
  9585. this.groups = {};
  9586. this.groups.length = function()
  9587. {
  9588. var i = 0;
  9589. for ( var p in this ) {
  9590. if (this.hasOwnProperty(p)) {
  9591. i++;
  9592. }
  9593. }
  9594. return i;
  9595. }
  9596. };
  9597. /**
  9598. * get group properties of a groupname. If groupname is not found, a new group
  9599. * is added.
  9600. * @param {*} groupname Can be a number, string, Date, etc.
  9601. * @return {Object} group The created group, containing all group properties
  9602. */
  9603. Groups.prototype.get = function (groupname) {
  9604. var group = this.groups[groupname];
  9605. if (group == undefined) {
  9606. // create new group
  9607. var index = this.defaultIndex % Groups.DEFAULT.length;
  9608. this.defaultIndex++;
  9609. group = {};
  9610. group.color = Groups.DEFAULT[index];
  9611. this.groups[groupname] = group;
  9612. }
  9613. return group;
  9614. };
  9615. /**
  9616. * Add a custom group style
  9617. * @param {String} groupname
  9618. * @param {Object} style An object containing borderColor,
  9619. * backgroundColor, etc.
  9620. * @return {Object} group The created group object
  9621. */
  9622. Groups.prototype.add = function (groupname, style) {
  9623. this.groups[groupname] = style;
  9624. if (style.color) {
  9625. style.color = Node.parseColor(style.color);
  9626. }
  9627. return style;
  9628. };
  9629. /**
  9630. * @class Images
  9631. * This class loads images and keeps them stored.
  9632. */
  9633. Images = function () {
  9634. this.images = {};
  9635. this.callback = undefined;
  9636. };
  9637. /**
  9638. * Set an onload callback function. This will be called each time an image
  9639. * is loaded
  9640. * @param {function} callback
  9641. */
  9642. Images.prototype.setOnloadCallback = function(callback) {
  9643. this.callback = callback;
  9644. };
  9645. /**
  9646. *
  9647. * @param {string} url Url of the image
  9648. * @return {Image} img The image object
  9649. */
  9650. Images.prototype.load = function(url) {
  9651. var img = this.images[url];
  9652. if (img == undefined) {
  9653. // create the image
  9654. var images = this;
  9655. img = new Image();
  9656. this.images[url] = img;
  9657. img.onload = function() {
  9658. if (images.callback) {
  9659. images.callback(this);
  9660. }
  9661. };
  9662. img.src = url;
  9663. }
  9664. return img;
  9665. };
  9666. /**
  9667. * Created by Alex on 2/6/14.
  9668. */
  9669. var physicsMixin = {
  9670. /**
  9671. * Toggling barnes Hut calculation on and off.
  9672. *
  9673. * @private
  9674. */
  9675. _toggleBarnesHut : function() {
  9676. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  9677. this._loadSelectedForceSolver();
  9678. this.moving = true;
  9679. this.start();
  9680. },
  9681. /**
  9682. * This loads the node force solver based on the barnes hut or repulsion algorithm
  9683. *
  9684. * @private
  9685. */
  9686. _loadSelectedForceSolver : function() {
  9687. // this overloads the this._calculateNodeForces
  9688. if (this.constants.physics.barnesHut.enabled == true) {
  9689. this._clearMixin(repulsionMixin);
  9690. this._clearMixin(hierarchalRepulsionMixin);
  9691. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  9692. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  9693. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  9694. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  9695. this._loadMixin(barnesHutMixin);
  9696. }
  9697. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  9698. this._clearMixin(barnesHutMixin);
  9699. this._clearMixin(repulsionMixin);
  9700. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  9701. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  9702. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  9703. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  9704. this._loadMixin(hierarchalRepulsionMixin);
  9705. }
  9706. else {
  9707. this._clearMixin(barnesHutMixin);
  9708. this._clearMixin(hierarchalRepulsionMixin);
  9709. this.barnesHutTree = undefined;
  9710. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  9711. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  9712. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  9713. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  9714. this._loadMixin(repulsionMixin);
  9715. }
  9716. },
  9717. /**
  9718. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  9719. * if there is more than one node. If it is just one node, we dont calculate anything.
  9720. *
  9721. * @private
  9722. */
  9723. _initializeForceCalculation : function() {
  9724. // stop calculation if there is only one node
  9725. if (this.nodeIndices.length == 1) {
  9726. this.nodes[this.nodeIndices[0]]._setForce(0,0);
  9727. }
  9728. else {
  9729. // if there are too many nodes on screen, we cluster without repositioning
  9730. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  9731. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  9732. }
  9733. // we now start the force calculation
  9734. this._calculateForces();
  9735. }
  9736. },
  9737. /**
  9738. * Calculate the external forces acting on the nodes
  9739. * Forces are caused by: edges, repulsing forces between nodes, gravity
  9740. * @private
  9741. */
  9742. _calculateForces : function() {
  9743. // Gravity is required to keep separated groups from floating off
  9744. // the forces are reset to zero in this loop by using _setForce instead
  9745. // of _addForce
  9746. this._calculateGravitationalForces();
  9747. this._calculateNodeForces();
  9748. if (this.constants.smoothCurves == true) {
  9749. this._calculateSpringForcesWithSupport();
  9750. }
  9751. else {
  9752. this._calculateSpringForces();
  9753. }
  9754. },
  9755. /**
  9756. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  9757. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  9758. * This function joins the datanodes and invisible (called support) nodes into one object.
  9759. * We do this so we do not contaminate this.nodes with the support nodes.
  9760. *
  9761. * @private
  9762. */
  9763. _updateCalculationNodes : function() {
  9764. if (this.constants.smoothCurves == true) {
  9765. this.calculationNodes = {};
  9766. this.calculationNodeIndices = [];
  9767. for (var nodeId in this.nodes) {
  9768. if (this.nodes.hasOwnProperty(nodeId)) {
  9769. this.calculationNodes[nodeId] = this.nodes[nodeId];
  9770. }
  9771. }
  9772. var supportNodes = this.sectors['support']['nodes'];
  9773. for (var supportNodeId in supportNodes) {
  9774. if (supportNodes.hasOwnProperty(supportNodeId)) {
  9775. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  9776. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  9777. }
  9778. else {
  9779. supportNodes[supportNodeId]._setForce(0,0);
  9780. }
  9781. }
  9782. }
  9783. for (var idx in this.calculationNodes) {
  9784. if (this.calculationNodes.hasOwnProperty(idx)) {
  9785. this.calculationNodeIndices.push(idx);
  9786. }
  9787. }
  9788. }
  9789. else {
  9790. this.calculationNodes = this.nodes;
  9791. this.calculationNodeIndices = this.nodeIndices;
  9792. }
  9793. },
  9794. /**
  9795. * this function applies the central gravity effect to keep groups from floating off
  9796. *
  9797. * @private
  9798. */
  9799. _calculateGravitationalForces : function() {
  9800. var dx, dy, distance, node, i;
  9801. var nodes = this.calculationNodes;
  9802. var gravity = this.constants.physics.centralGravity;
  9803. var gravityForce = 0;
  9804. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  9805. node = nodes[this.calculationNodeIndices[i]];
  9806. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  9807. // gravity does not apply when we are in a pocket sector
  9808. if (this._sector() == "default" && gravity != 0) {
  9809. dx = -node.x;
  9810. dy = -node.y;
  9811. distance = Math.sqrt(dx*dx + dy*dy);
  9812. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  9813. node.fx = dx * gravityForce;
  9814. node.fy = dy * gravityForce;
  9815. }
  9816. else {
  9817. node.fx = 0;
  9818. node.fy = 0;
  9819. }
  9820. }
  9821. },
  9822. /**
  9823. * this function calculates the effects of the springs in the case of unsmooth curves.
  9824. *
  9825. * @private
  9826. */
  9827. _calculateSpringForces : function() {
  9828. var edgeLength, edge, edgeId;
  9829. var dx, dy, fx, fy, springForce, length;
  9830. var edges = this.edges;
  9831. // forces caused by the edges, modelled as springs
  9832. for (edgeId in edges) {
  9833. if (edges.hasOwnProperty(edgeId)) {
  9834. edge = edges[edgeId];
  9835. if (edge.connected) {
  9836. // only calculate forces if nodes are in the same sector
  9837. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9838. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9839. // this implies that the edges between big clusters are longer
  9840. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  9841. dx = (edge.from.x - edge.to.x);
  9842. dy = (edge.from.y - edge.to.y);
  9843. length = Math.sqrt(dx * dx + dy * dy);
  9844. if (length == 0) {
  9845. length = 0.01;
  9846. }
  9847. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  9848. fx = dx * springForce;
  9849. fy = dy * springForce;
  9850. edge.from.fx += fx;
  9851. edge.from.fy += fy;
  9852. edge.to.fx -= fx;
  9853. edge.to.fy -= fy;
  9854. }
  9855. }
  9856. }
  9857. }
  9858. },
  9859. /**
  9860. * This function calculates the springforces on the nodes, accounting for the support nodes.
  9861. *
  9862. * @private
  9863. */
  9864. _calculateSpringForcesWithSupport : function() {
  9865. var edgeLength, edge, edgeId, combinedClusterSize;
  9866. var edges = this.edges;
  9867. // forces caused by the edges, modelled as springs
  9868. for (edgeId in edges) {
  9869. if (edges.hasOwnProperty(edgeId)) {
  9870. edge = edges[edgeId];
  9871. if (edge.connected) {
  9872. // only calculate forces if nodes are in the same sector
  9873. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  9874. if (edge.via != null) {
  9875. var node1 = edge.to;
  9876. var node2 = edge.via;
  9877. var node3 = edge.from;
  9878. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  9879. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  9880. // this implies that the edges between big clusters are longer
  9881. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  9882. this._calculateSpringForce(node1,node2,0.5*edgeLength);
  9883. this._calculateSpringForce(node2,node3,0.5*edgeLength);
  9884. }
  9885. }
  9886. }
  9887. }
  9888. }
  9889. },
  9890. /**
  9891. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  9892. *
  9893. * @param node1
  9894. * @param node2
  9895. * @param edgeLength
  9896. * @private
  9897. */
  9898. _calculateSpringForce : function(node1,node2,edgeLength) {
  9899. var dx, dy, fx, fy, springForce, length;
  9900. dx = (node1.x - node2.x);
  9901. dy = (node1.y - node2.y);
  9902. length = Math.sqrt(dx * dx + dy * dy);
  9903. if (length == 0) {
  9904. length = 0.01;
  9905. }
  9906. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  9907. fx = dx * springForce;
  9908. fy = dy * springForce;
  9909. node1.fx += fx;
  9910. node1.fy += fy;
  9911. node2.fx -= fx;
  9912. node2.fy -= fy;
  9913. },
  9914. /**
  9915. * Load the HTML for the physics config and bind it
  9916. * @private
  9917. */
  9918. _loadPhysicsConfiguration : function() {
  9919. if (this.physicsConfiguration === undefined) {
  9920. this.backupConstants = {};
  9921. util.copyObject(this.constants,this.backupConstants);
  9922. var hierarchicalLayoutDirections = ["LR","RL","UD","DU"];
  9923. this.physicsConfiguration = document.createElement('div');
  9924. this.physicsConfiguration.className = "PhysicsConfiguration";
  9925. this.physicsConfiguration.innerHTML = '' +
  9926. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  9927. '<tr>' +
  9928. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  9929. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>'+
  9930. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  9931. '</tr>'+
  9932. '</table>' +
  9933. '<table id="graph_BH_table" style="display:none">'+
  9934. '<tr><td><b>Barnes Hut</b></td></tr>'+
  9935. '<tr>'+
  9936. '<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>'+
  9937. '</tr>'+
  9938. '<tr>'+
  9939. '<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>'+
  9940. '</tr>'+
  9941. '<tr>'+
  9942. '<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>'+
  9943. '</tr>'+
  9944. '<tr>'+
  9945. '<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>'+
  9946. '</tr>'+
  9947. '<tr>'+
  9948. '<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>'+
  9949. '</tr>'+
  9950. '</table>'+
  9951. '<table id="graph_R_table" style="display:none">'+
  9952. '<tr><td><b>Repulsion</b></td></tr>'+
  9953. '<tr>'+
  9954. '<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>'+
  9955. '</tr>'+
  9956. '<tr>'+
  9957. '<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>'+
  9958. '</tr>'+
  9959. '<tr>'+
  9960. '<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>'+
  9961. '</tr>'+
  9962. '<tr>'+
  9963. '<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>'+
  9964. '</tr>'+
  9965. '<tr>'+
  9966. '<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>'+
  9967. '</tr>'+
  9968. '</table>'+
  9969. '<table id="graph_H_table" style="display:none">'+
  9970. '<tr><td width="150"><b>Hierarchical</b></td></tr>'+
  9971. '<tr>'+
  9972. '<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>'+
  9973. '</tr>'+
  9974. '<tr>'+
  9975. '<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>'+
  9976. '</tr>'+
  9977. '<tr>'+
  9978. '<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>'+
  9979. '</tr>'+
  9980. '<tr>'+
  9981. '<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>'+
  9982. '</tr>'+
  9983. '<tr>'+
  9984. '<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>'+
  9985. '</tr>'+
  9986. '<tr>'+
  9987. '<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>'+
  9988. '</tr>'+
  9989. '<tr>'+
  9990. '<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>'+
  9991. '</tr>'+
  9992. '<tr>'+
  9993. '<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>'+
  9994. '</tr>'+
  9995. '</table>' +
  9996. '<table><tr><td><b>Options:</b></td></tr>' +
  9997. '<tr>' +
  9998. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  9999. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  10000. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  10001. '</tr>'+
  10002. '</table>'
  10003. this.containerElement.parentElement.insertBefore(this.physicsConfiguration,this.containerElement);
  10004. this.optionsDiv = document.createElement("div");
  10005. this.optionsDiv.style.fontSize = "14px";
  10006. this.optionsDiv.style.fontFamily = "verdana";
  10007. this.containerElement.parentElement.insertBefore(this.optionsDiv,this.containerElement);
  10008. var rangeElement;
  10009. rangeElement = document.getElementById('graph_BH_gc');
  10010. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_gc',-1,"physics_barnesHut_gravitationalConstant");
  10011. rangeElement = document.getElementById('graph_BH_cg');
  10012. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_cg',1,"physics_centralGravity");
  10013. rangeElement = document.getElementById('graph_BH_sc');
  10014. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_sc',1,"physics_springConstant");
  10015. rangeElement = document.getElementById('graph_BH_sl');
  10016. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_sl',1,"physics_springLength");
  10017. rangeElement = document.getElementById('graph_BH_damp');
  10018. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_damp',1,"physics_damping");
  10019. rangeElement = document.getElementById('graph_R_nd');
  10020. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_nd',1,"physics_repulsion_nodeDistance");
  10021. rangeElement = document.getElementById('graph_R_cg');
  10022. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_cg',1,"physics_centralGravity");
  10023. rangeElement = document.getElementById('graph_R_sc');
  10024. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_sc',1,"physics_springConstant");
  10025. rangeElement = document.getElementById('graph_R_sl');
  10026. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_sl',1,"physics_springLength");
  10027. rangeElement = document.getElementById('graph_R_damp');
  10028. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_damp',1,"physics_damping");
  10029. rangeElement = document.getElementById('graph_H_nd');
  10030. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_nd',1,"physics_hierarchicalRepulsion_nodeDistance");
  10031. rangeElement = document.getElementById('graph_H_cg');
  10032. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_cg',1,"physics_centralGravity");
  10033. rangeElement = document.getElementById('graph_H_sc');
  10034. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_sc',1,"physics_springConstant");
  10035. rangeElement = document.getElementById('graph_H_sl');
  10036. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_sl',1,"physics_springLength");
  10037. rangeElement = document.getElementById('graph_H_damp');
  10038. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_damp',1,"physics_damping");
  10039. rangeElement = document.getElementById('graph_H_direction');
  10040. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_direction',hierarchicalLayoutDirections,"hierarchicalLayout_direction");
  10041. rangeElement = document.getElementById('graph_H_levsep');
  10042. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_levsep',1,"hierarchicalLayout_levelSeparation");
  10043. rangeElement = document.getElementById('graph_H_nspac');
  10044. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_nspac',1,"hierarchicalLayout_nodeSpacing");
  10045. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10046. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10047. var radioButton3 = document.getElementById("graph_physicsMethod3");
  10048. radioButton2.checked = true;
  10049. if (this.constants.physics.barnesHut.enabled) {
  10050. radioButton1.checked = true;
  10051. }
  10052. if (this.constants.hierarchicalLayout.enabled) {
  10053. radioButton3.checked = true;
  10054. }
  10055. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10056. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  10057. var graph_generateOptions = document.getElementById("graph_generateOptions");
  10058. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  10059. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  10060. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  10061. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10062. else {graph_toggleSmooth.style.background = "#FF8532";}
  10063. switchConfigurations.apply(this);
  10064. radioButton1.onchange = switchConfigurations.bind(this);
  10065. radioButton2.onchange = switchConfigurations.bind(this);
  10066. radioButton3.onchange = switchConfigurations.bind(this);
  10067. }
  10068. },
  10069. _overWriteGraphConstants : function(constantsVariableName, value) {
  10070. var nameArray = constantsVariableName.split("_");
  10071. if (nameArray.length == 1) {
  10072. this.constants[nameArray[0]] = value;
  10073. }
  10074. else if (nameArray.length == 2) {
  10075. this.constants[nameArray[0]][nameArray[1]] = value;
  10076. }
  10077. else if (nameArray.length == 3) {
  10078. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  10079. }
  10080. }
  10081. }
  10082. function graphToggleSmoothCurves () {
  10083. this.constants.smoothCurves = !this.constants.smoothCurves;
  10084. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10085. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10086. else {graph_toggleSmooth.style.background = "#FF8532";}
  10087. this._configureSmoothCurves(false);
  10088. };
  10089. function graphRepositionNodes () {
  10090. for (var nodeId in this.calculationNodes) {
  10091. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  10092. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  10093. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  10094. }
  10095. }
  10096. if (this.constants.hierarchicalLayout.enabled == true) {
  10097. this._setupHierarchicalLayout();
  10098. }
  10099. else {
  10100. this.repositionNodes();
  10101. }
  10102. this.moving = true;
  10103. this.start();
  10104. };
  10105. function graphGenerateOptions () {
  10106. var options = "No options are required, default values used."
  10107. var optionsSpecific = [];
  10108. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10109. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10110. if (radioButton1.checked == true) {
  10111. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  10112. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10113. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10114. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10115. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10116. if (optionsSpecific.length != 0) {
  10117. options = "var options = {"
  10118. options += "physics: {barnesHut: {"
  10119. for (var i = 0; i < optionsSpecific.length; i++) {
  10120. options += optionsSpecific[i];
  10121. if (i < optionsSpecific.length - 1) {
  10122. options += ", "
  10123. }
  10124. }
  10125. options += '}}'
  10126. }
  10127. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10128. if (optionsSpecific.length == 0) {options = "var options = {";}
  10129. else {options += ", "}
  10130. options += "smoothCurves: " + this.constants.smoothCurves;
  10131. }
  10132. if (options != "No options are required, default values used.") {
  10133. options += '};'
  10134. }
  10135. }
  10136. else if (radioButton2.checked == true) {
  10137. options = "var options = {"
  10138. options += "physics: {barnesHut: {enabled: false}";
  10139. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  10140. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10141. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10142. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10143. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10144. if (optionsSpecific.length != 0) {
  10145. options += ", repulsion: {"
  10146. for (var i = 0; i < optionsSpecific.length; i++) {
  10147. options += optionsSpecific[i];
  10148. if (i < optionsSpecific.length - 1) {
  10149. options += ", "
  10150. }
  10151. }
  10152. options += '}}'
  10153. }
  10154. if (optionsSpecific.length == 0) {options += "}"}
  10155. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10156. options += ", smoothCurves: " + this.constants.smoothCurves;
  10157. }
  10158. options += '};'
  10159. }
  10160. else {
  10161. options = "var options = {"
  10162. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  10163. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10164. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10165. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10166. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10167. if (optionsSpecific.length != 0) {
  10168. options += "physics: {hierarchicalRepulsion: {"
  10169. for (var i = 0; i < optionsSpecific.length; i++) {
  10170. options += optionsSpecific[i];
  10171. if (i < optionsSpecific.length - 1) {
  10172. options += ", ";
  10173. }
  10174. }
  10175. options += '}},';
  10176. }
  10177. options += 'hierarchicalLayout: {';
  10178. optionsSpecific = [];
  10179. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  10180. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  10181. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  10182. if (optionsSpecific.length != 0) {
  10183. for (var i = 0; i < optionsSpecific.length; i++) {
  10184. options += optionsSpecific[i];
  10185. if (i < optionsSpecific.length - 1) {
  10186. options += ", "
  10187. }
  10188. }
  10189. options += '}'
  10190. }
  10191. else {
  10192. options += "enabled:true}";
  10193. }
  10194. options += '};'
  10195. }
  10196. this.optionsDiv.innerHTML = options;
  10197. };
  10198. function switchConfigurations () {
  10199. var ids = ["graph_BH_table","graph_R_table","graph_H_table"]
  10200. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  10201. var tableId = "graph_" + radioButton + "_table";
  10202. var table = document.getElementById(tableId);
  10203. table.style.display = "block";
  10204. for (var i = 0; i < ids.length; i++) {
  10205. if (ids[i] != tableId) {
  10206. table = document.getElementById(ids[i]);
  10207. table.style.display = "none";
  10208. }
  10209. }
  10210. this._restoreNodes();
  10211. if (radioButton == "R") {
  10212. this.constants.hierarchicalLayout.enabled = false;
  10213. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10214. this.constants.physics.barnesHut.enabled = false;
  10215. }
  10216. else if (radioButton == "H") {
  10217. this.constants.hierarchicalLayout.enabled = true;
  10218. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10219. this.constants.physics.barnesHut.enabled = false;
  10220. this._setupHierarchicalLayout();
  10221. }
  10222. else {
  10223. this.constants.hierarchicalLayout.enabled = false;
  10224. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10225. this.constants.physics.barnesHut.enabled = true;
  10226. }
  10227. this._loadSelectedForceSolver();
  10228. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10229. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10230. else {graph_toggleSmooth.style.background = "#FF8532";}
  10231. this.moving = true;
  10232. this.start();
  10233. }
  10234. function showValueOfRange (id,map,constantsVariableName) {
  10235. var valueId = id + "_value";
  10236. var rangeValue = document.getElementById(id).value;
  10237. if (map instanceof Array) {
  10238. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  10239. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  10240. }
  10241. else {
  10242. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  10243. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  10244. }
  10245. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10246. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10247. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10248. this._setupHierarchicalLayout();
  10249. }
  10250. this.moving = true;
  10251. this.start();
  10252. };
  10253. /**
  10254. * Created by Alex on 2/10/14.
  10255. */
  10256. var hierarchalRepulsionMixin = {
  10257. /**
  10258. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10259. * This field is linearly approximated.
  10260. *
  10261. * @private
  10262. */
  10263. _calculateNodeForces : function() {
  10264. var dx, dy, distance, fx, fy, combinedClusterSize,
  10265. repulsingForce, node1, node2, i, j;
  10266. var nodes = this.calculationNodes;
  10267. var nodeIndices = this.calculationNodeIndices;
  10268. // approximation constants
  10269. var b = 5;
  10270. var a_base = 0.5*-b;
  10271. // repulsing forces between nodes
  10272. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  10273. var minimumDistance = nodeDistance;
  10274. // we loop from i over all but the last entree in the array
  10275. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10276. for (i = 0; i < nodeIndices.length-1; i++) {
  10277. node1 = nodes[nodeIndices[i]];
  10278. for (j = i+1; j < nodeIndices.length; j++) {
  10279. node2 = nodes[nodeIndices[j]];
  10280. dx = node2.x - node1.x;
  10281. dy = node2.y - node1.y;
  10282. distance = Math.sqrt(dx * dx + dy * dy);
  10283. var a = a_base / minimumDistance;
  10284. if (distance < 2*minimumDistance) {
  10285. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10286. // normalize force with
  10287. if (distance == 0) {
  10288. distance = 0.01;
  10289. }
  10290. else {
  10291. repulsingForce = repulsingForce/distance;
  10292. }
  10293. fx = dx * repulsingForce;
  10294. fy = dy * repulsingForce;
  10295. node1.fx -= fx;
  10296. node1.fy -= fy;
  10297. node2.fx += fx;
  10298. node2.fy += fy;
  10299. }
  10300. }
  10301. }
  10302. }
  10303. }
  10304. /**
  10305. * Created by Alex on 2/10/14.
  10306. */
  10307. var barnesHutMixin = {
  10308. /**
  10309. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10310. * The Barnes Hut method is used to speed up this N-body simulation.
  10311. *
  10312. * @private
  10313. */
  10314. _calculateNodeForces : function() {
  10315. var node;
  10316. var nodes = this.calculationNodes;
  10317. var nodeIndices = this.calculationNodeIndices;
  10318. var nodeCount = nodeIndices.length;
  10319. this._formBarnesHutTree(nodes,nodeIndices);
  10320. var barnesHutTree = this.barnesHutTree;
  10321. // place the nodes one by one recursively
  10322. for (var i = 0; i < nodeCount; i++) {
  10323. node = nodes[nodeIndices[i]];
  10324. // starting with root is irrelevant, it never passes the BarnesHut condition
  10325. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10326. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10327. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10328. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10329. }
  10330. },
  10331. /**
  10332. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10333. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10334. *
  10335. * @param parentBranch
  10336. * @param node
  10337. * @private
  10338. */
  10339. _getForceContribution : function(parentBranch,node) {
  10340. // we get no force contribution from an empty region
  10341. if (parentBranch.childrenCount > 0) {
  10342. var dx,dy,distance;
  10343. // get the distance from the center of mass to the node.
  10344. dx = parentBranch.centerOfMass.x - node.x;
  10345. dy = parentBranch.centerOfMass.y - node.y;
  10346. distance = Math.sqrt(dx * dx + dy * dy);
  10347. // BarnesHut condition
  10348. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10349. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10350. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10351. // duplicate code to reduce function calls to speed up program
  10352. if (distance == 0) {
  10353. distance = 0.1*Math.random();
  10354. dx = distance;
  10355. }
  10356. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10357. var fx = dx * gravityForce;
  10358. var fy = dy * gravityForce;
  10359. node.fx += fx;
  10360. node.fy += fy;
  10361. }
  10362. else {
  10363. // Did not pass the condition, go into children if available
  10364. if (parentBranch.childrenCount == 4) {
  10365. this._getForceContribution(parentBranch.children.NW,node);
  10366. this._getForceContribution(parentBranch.children.NE,node);
  10367. this._getForceContribution(parentBranch.children.SW,node);
  10368. this._getForceContribution(parentBranch.children.SE,node);
  10369. }
  10370. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10371. if (parentBranch.children.data.id != node.id) { // if it is not self
  10372. // duplicate code to reduce function calls to speed up program
  10373. if (distance == 0) {
  10374. distance = 0.5*Math.random();
  10375. dx = distance;
  10376. }
  10377. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10378. var fx = dx * gravityForce;
  10379. var fy = dy * gravityForce;
  10380. node.fx += fx;
  10381. node.fy += fy;
  10382. }
  10383. }
  10384. }
  10385. }
  10386. },
  10387. /**
  10388. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10389. *
  10390. * @param nodes
  10391. * @param nodeIndices
  10392. * @private
  10393. */
  10394. _formBarnesHutTree : function(nodes,nodeIndices) {
  10395. var node;
  10396. var nodeCount = nodeIndices.length;
  10397. var minX = Number.MAX_VALUE,
  10398. minY = Number.MAX_VALUE,
  10399. maxX =-Number.MAX_VALUE,
  10400. maxY =-Number.MAX_VALUE;
  10401. // get the range of the nodes
  10402. for (var i = 0; i < nodeCount; i++) {
  10403. var x = nodes[nodeIndices[i]].x;
  10404. var y = nodes[nodeIndices[i]].y;
  10405. if (x < minX) { minX = x; }
  10406. if (x > maxX) { maxX = x; }
  10407. if (y < minY) { minY = y; }
  10408. if (y > maxY) { maxY = y; }
  10409. }
  10410. // make the range a square
  10411. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10412. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10413. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10414. var minimumTreeSize = 1e-5;
  10415. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10416. var halfRootSize = 0.5 * rootSize;
  10417. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10418. // construct the barnesHutTree
  10419. var barnesHutTree = {root:{
  10420. centerOfMass:{x:0,y:0}, // Center of Mass
  10421. mass:0,
  10422. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10423. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10424. size: rootSize,
  10425. calcSize: 1 / rootSize,
  10426. children: {data:null},
  10427. maxWidth: 0,
  10428. level: 0,
  10429. childrenCount: 4
  10430. }};
  10431. this._splitBranch(barnesHutTree.root);
  10432. // place the nodes one by one recursively
  10433. for (i = 0; i < nodeCount; i++) {
  10434. node = nodes[nodeIndices[i]];
  10435. this._placeInTree(barnesHutTree.root,node);
  10436. }
  10437. // make global
  10438. this.barnesHutTree = barnesHutTree
  10439. },
  10440. _updateBranchMass : function(parentBranch, node) {
  10441. var totalMass = parentBranch.mass + node.mass;
  10442. var totalMassInv = 1/totalMass;
  10443. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10444. parentBranch.centerOfMass.x *= totalMassInv;
  10445. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10446. parentBranch.centerOfMass.y *= totalMassInv;
  10447. parentBranch.mass = totalMass;
  10448. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10449. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10450. },
  10451. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10452. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10453. // update the mass of the branch.
  10454. this._updateBranchMass(parentBranch,node);
  10455. }
  10456. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10457. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10458. this._placeInRegion(parentBranch,node,"NW");
  10459. }
  10460. else { // in SW
  10461. this._placeInRegion(parentBranch,node,"SW");
  10462. }
  10463. }
  10464. else { // in NE or SE
  10465. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10466. this._placeInRegion(parentBranch,node,"NE");
  10467. }
  10468. else { // in SE
  10469. this._placeInRegion(parentBranch,node,"SE");
  10470. }
  10471. }
  10472. },
  10473. _placeInRegion : function(parentBranch,node,region) {
  10474. switch (parentBranch.children[region].childrenCount) {
  10475. case 0: // place node here
  10476. parentBranch.children[region].children.data = node;
  10477. parentBranch.children[region].childrenCount = 1;
  10478. this._updateBranchMass(parentBranch.children[region],node);
  10479. break;
  10480. case 1: // convert into children
  10481. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10482. // we move one node a pixel and we do not put it in the tree.
  10483. if (parentBranch.children[region].children.data.x == node.x &&
  10484. parentBranch.children[region].children.data.y == node.y) {
  10485. node.x += Math.random();
  10486. node.y += Math.random();
  10487. }
  10488. else {
  10489. this._splitBranch(parentBranch.children[region]);
  10490. this._placeInTree(parentBranch.children[region],node);
  10491. }
  10492. break;
  10493. case 4: // place in branch
  10494. this._placeInTree(parentBranch.children[region],node);
  10495. break;
  10496. }
  10497. },
  10498. /**
  10499. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10500. * after the split is complete.
  10501. *
  10502. * @param parentBranch
  10503. * @private
  10504. */
  10505. _splitBranch : function(parentBranch) {
  10506. // if the branch is filled with a node, replace the node in the new subset.
  10507. var containedNode = null;
  10508. if (parentBranch.childrenCount == 1) {
  10509. containedNode = parentBranch.children.data;
  10510. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10511. }
  10512. parentBranch.childrenCount = 4;
  10513. parentBranch.children.data = null;
  10514. this._insertRegion(parentBranch,"NW");
  10515. this._insertRegion(parentBranch,"NE");
  10516. this._insertRegion(parentBranch,"SW");
  10517. this._insertRegion(parentBranch,"SE");
  10518. if (containedNode != null) {
  10519. this._placeInTree(parentBranch,containedNode);
  10520. }
  10521. },
  10522. /**
  10523. * This function subdivides the region into four new segments.
  10524. * Specifically, this inserts a single new segment.
  10525. * It fills the children section of the parentBranch
  10526. *
  10527. * @param parentBranch
  10528. * @param region
  10529. * @param parentRange
  10530. * @private
  10531. */
  10532. _insertRegion : function(parentBranch, region) {
  10533. var minX,maxX,minY,maxY;
  10534. var childSize = 0.5 * parentBranch.size;
  10535. switch (region) {
  10536. case "NW":
  10537. minX = parentBranch.range.minX;
  10538. maxX = parentBranch.range.minX + childSize;
  10539. minY = parentBranch.range.minY;
  10540. maxY = parentBranch.range.minY + childSize;
  10541. break;
  10542. case "NE":
  10543. minX = parentBranch.range.minX + childSize;
  10544. maxX = parentBranch.range.maxX;
  10545. minY = parentBranch.range.minY;
  10546. maxY = parentBranch.range.minY + childSize;
  10547. break;
  10548. case "SW":
  10549. minX = parentBranch.range.minX;
  10550. maxX = parentBranch.range.minX + childSize;
  10551. minY = parentBranch.range.minY + childSize;
  10552. maxY = parentBranch.range.maxY;
  10553. break;
  10554. case "SE":
  10555. minX = parentBranch.range.minX + childSize;
  10556. maxX = parentBranch.range.maxX;
  10557. minY = parentBranch.range.minY + childSize;
  10558. maxY = parentBranch.range.maxY;
  10559. break;
  10560. }
  10561. parentBranch.children[region] = {
  10562. centerOfMass:{x:0,y:0},
  10563. mass:0,
  10564. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10565. size: 0.5 * parentBranch.size,
  10566. calcSize: 2 * parentBranch.calcSize,
  10567. children: {data:null},
  10568. maxWidth: 0,
  10569. level: parentBranch.level+1,
  10570. childrenCount: 0
  10571. };
  10572. },
  10573. /**
  10574. * This function is for debugging purposed, it draws the tree.
  10575. *
  10576. * @param ctx
  10577. * @param color
  10578. * @private
  10579. */
  10580. _drawTree : function(ctx,color) {
  10581. if (this.barnesHutTree !== undefined) {
  10582. ctx.lineWidth = 1;
  10583. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10584. }
  10585. },
  10586. /**
  10587. * This function is for debugging purposes. It draws the branches recursively.
  10588. *
  10589. * @param branch
  10590. * @param ctx
  10591. * @param color
  10592. * @private
  10593. */
  10594. _drawBranch : function(branch,ctx,color) {
  10595. if (color === undefined) {
  10596. color = "#FF0000";
  10597. }
  10598. if (branch.childrenCount == 4) {
  10599. this._drawBranch(branch.children.NW,ctx);
  10600. this._drawBranch(branch.children.NE,ctx);
  10601. this._drawBranch(branch.children.SE,ctx);
  10602. this._drawBranch(branch.children.SW,ctx);
  10603. }
  10604. ctx.strokeStyle = color;
  10605. ctx.beginPath();
  10606. ctx.moveTo(branch.range.minX,branch.range.minY);
  10607. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10608. ctx.stroke();
  10609. ctx.beginPath();
  10610. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10611. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10612. ctx.stroke();
  10613. ctx.beginPath();
  10614. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10615. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10616. ctx.stroke();
  10617. ctx.beginPath();
  10618. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10619. ctx.lineTo(branch.range.minX,branch.range.minY);
  10620. ctx.stroke();
  10621. /*
  10622. if (branch.mass > 0) {
  10623. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  10624. ctx.stroke();
  10625. }
  10626. */
  10627. }
  10628. };
  10629. /**
  10630. * Created by Alex on 2/10/14.
  10631. */
  10632. var repulsionMixin = {
  10633. /**
  10634. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10635. * This field is linearly approximated.
  10636. *
  10637. * @private
  10638. */
  10639. _calculateNodeForces : function() {
  10640. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  10641. repulsingForce, node1, node2, i, j;
  10642. var nodes = this.calculationNodes;
  10643. var nodeIndices = this.calculationNodeIndices;
  10644. // approximation constants
  10645. var a_base = -2/3;
  10646. var b = 4/3;
  10647. // repulsing forces between nodes
  10648. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10649. var minimumDistance = nodeDistance;
  10650. // we loop from i over all but the last entree in the array
  10651. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10652. for (i = 0; i < nodeIndices.length-1; i++) {
  10653. node1 = nodes[nodeIndices[i]];
  10654. for (j = i+1; j < nodeIndices.length; j++) {
  10655. node2 = nodes[nodeIndices[j]];
  10656. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  10657. dx = node2.x - node1.x;
  10658. dy = node2.y - node1.y;
  10659. distance = Math.sqrt(dx * dx + dy * dy);
  10660. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  10661. var a = a_base / minimumDistance;
  10662. if (distance < 2*minimumDistance) {
  10663. if (distance < 0.5*minimumDistance) {
  10664. repulsingForce = 1.0;
  10665. }
  10666. else {
  10667. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10668. }
  10669. // amplify the repulsion for clusters.
  10670. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  10671. repulsingForce = repulsingForce/distance;
  10672. fx = dx * repulsingForce;
  10673. fy = dy * repulsingForce;
  10674. node1.fx -= fx;
  10675. node1.fy -= fy;
  10676. node2.fx += fx;
  10677. node2.fy += fy;
  10678. }
  10679. }
  10680. }
  10681. }
  10682. }
  10683. var HierarchicalLayoutMixin = {
  10684. /**
  10685. * This is the main function to layout the nodes in a hierarchical way.
  10686. * It checks if the node details are supplied correctly
  10687. *
  10688. * @private
  10689. */
  10690. _setupHierarchicalLayout : function() {
  10691. if (this.constants.hierarchicalLayout.enabled == true) {
  10692. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  10693. this.constants.hierarchicalLayout.levelSeparation *= -1;
  10694. }
  10695. else {
  10696. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  10697. }
  10698. // get the size of the largest hubs and check if the user has defined a level for a node.
  10699. var hubsize = 0;
  10700. var node, nodeId;
  10701. var definedLevel = false;
  10702. var undefinedLevel = false;
  10703. for (nodeId in this.nodes) {
  10704. if (this.nodes.hasOwnProperty(nodeId)) {
  10705. node = this.nodes[nodeId];
  10706. if (node.level != -1) {
  10707. definedLevel = true;
  10708. }
  10709. else {
  10710. undefinedLevel = true;
  10711. }
  10712. if (hubsize < node.edges.length) {
  10713. hubsize = node.edges.length;
  10714. }
  10715. }
  10716. }
  10717. // if the user defined some levels but not all, alert and run without hierarchical layout
  10718. if (undefinedLevel == true && definedLevel == true) {
  10719. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.")
  10720. this.zoomExtent(true,this.constants.clustering.enabled);
  10721. if (!this.constants.clustering.enabled) {
  10722. this.start();
  10723. }
  10724. }
  10725. else {
  10726. // setup the system to use hierarchical method.
  10727. this._changeConstants();
  10728. // define levels if undefined by the users. Based on hubsize
  10729. if (undefinedLevel == true) {
  10730. this._determineLevels(hubsize);
  10731. }
  10732. // check the distribution of the nodes per level.
  10733. var distribution = this._getDistribution();
  10734. // place the nodes on the canvas. This also stablilizes the system.
  10735. this._placeNodesByHierarchy(distribution);
  10736. // start the simulation.
  10737. this.start();
  10738. }
  10739. }
  10740. },
  10741. /**
  10742. * This function places the nodes on the canvas based on the hierarchial distribution.
  10743. *
  10744. * @param {Object} distribution | obtained by the function this._getDistribution()
  10745. * @private
  10746. */
  10747. _placeNodesByHierarchy : function(distribution) {
  10748. var nodeId, node;
  10749. // start placing all the level 0 nodes first. Then recursively position their branches.
  10750. for (nodeId in distribution[0].nodes) {
  10751. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  10752. node = distribution[0].nodes[nodeId];
  10753. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10754. if (node.xFixed) {
  10755. node.x = distribution[0].minPos;
  10756. node.xFixed = false;
  10757. distribution[0].minPos += distribution[0].nodeSpacing;
  10758. }
  10759. }
  10760. else {
  10761. if (node.yFixed) {
  10762. node.y = distribution[0].minPos;
  10763. node.yFixed = false;
  10764. distribution[0].minPos += distribution[0].nodeSpacing;
  10765. }
  10766. }
  10767. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  10768. }
  10769. }
  10770. // stabilize the system after positioning. This function calls zoomExtent.
  10771. this._stabilize();
  10772. },
  10773. /**
  10774. * This function get the distribution of levels based on hubsize
  10775. *
  10776. * @returns {Object}
  10777. * @private
  10778. */
  10779. _getDistribution : function() {
  10780. var distribution = {};
  10781. var nodeId, node;
  10782. // 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.
  10783. // the fix of X is removed after the x value has been set.
  10784. for (nodeId in this.nodes) {
  10785. if (this.nodes.hasOwnProperty(nodeId)) {
  10786. node = this.nodes[nodeId];
  10787. node.xFixed = true;
  10788. node.yFixed = true;
  10789. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10790. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10791. }
  10792. else {
  10793. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10794. }
  10795. if (!distribution.hasOwnProperty(node.level)) {
  10796. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  10797. }
  10798. distribution[node.level].amount += 1;
  10799. distribution[node.level].nodes[node.id] = node;
  10800. }
  10801. }
  10802. // determine the largest amount of nodes of all levels
  10803. var maxCount = 0;
  10804. for (var level in distribution) {
  10805. if (distribution.hasOwnProperty(level)) {
  10806. if (maxCount < distribution[level].amount) {
  10807. maxCount = distribution[level].amount;
  10808. }
  10809. }
  10810. }
  10811. // set the initial position and spacing of each nodes accordingly
  10812. for (var level in distribution) {
  10813. if (distribution.hasOwnProperty(level)) {
  10814. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  10815. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  10816. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  10817. }
  10818. }
  10819. return distribution;
  10820. },
  10821. /**
  10822. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  10823. *
  10824. * @param hubsize
  10825. * @private
  10826. */
  10827. _determineLevels : function(hubsize) {
  10828. var nodeId, node;
  10829. // determine hubs
  10830. for (nodeId in this.nodes) {
  10831. if (this.nodes.hasOwnProperty(nodeId)) {
  10832. node = this.nodes[nodeId];
  10833. if (node.edges.length == hubsize) {
  10834. node.level = 0;
  10835. }
  10836. }
  10837. }
  10838. // branch from hubs
  10839. for (nodeId in this.nodes) {
  10840. if (this.nodes.hasOwnProperty(nodeId)) {
  10841. node = this.nodes[nodeId];
  10842. if (node.level == 0) {
  10843. this._setLevel(1,node.edges,node.id);
  10844. }
  10845. }
  10846. }
  10847. },
  10848. /**
  10849. * Since hierarchical layout does not support:
  10850. * - smooth curves (based on the physics),
  10851. * - clustering (based on dynamic node counts)
  10852. *
  10853. * We disable both features so there will be no problems.
  10854. *
  10855. * @private
  10856. */
  10857. _changeConstants : function() {
  10858. this.constants.clustering.enabled = false;
  10859. this.constants.physics.barnesHut.enabled = false;
  10860. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10861. this._loadSelectedForceSolver();
  10862. this.constants.smoothCurves = false;
  10863. this._configureSmoothCurves();
  10864. },
  10865. /**
  10866. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  10867. * on a X position that ensures there will be no overlap.
  10868. *
  10869. * @param edges
  10870. * @param parentId
  10871. * @param distribution
  10872. * @param parentLevel
  10873. * @private
  10874. */
  10875. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  10876. for (var i = 0; i < edges.length; i++) {
  10877. var childNode = null;
  10878. if (edges[i].toId == parentId) {
  10879. childNode = edges[i].from;
  10880. }
  10881. else {
  10882. childNode = edges[i].to;
  10883. }
  10884. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  10885. var nodeMoved = false;
  10886. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10887. if (childNode.xFixed && childNode.level > parentLevel) {
  10888. childNode.xFixed = false;
  10889. childNode.x = distribution[childNode.level].minPos;
  10890. nodeMoved = true;
  10891. }
  10892. }
  10893. else {
  10894. if (childNode.yFixed && childNode.level > parentLevel) {
  10895. childNode.yFixed = false;
  10896. childNode.y = distribution[childNode.level].minPos;
  10897. nodeMoved = true;
  10898. }
  10899. }
  10900. if (nodeMoved == true) {
  10901. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  10902. if (childNode.edges.length > 1) {
  10903. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  10904. }
  10905. }
  10906. }
  10907. },
  10908. /**
  10909. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  10910. *
  10911. * @param level
  10912. * @param edges
  10913. * @param parentId
  10914. * @private
  10915. */
  10916. _setLevel : function(level, edges, parentId) {
  10917. for (var i = 0; i < edges.length; i++) {
  10918. var childNode = null;
  10919. if (edges[i].toId == parentId) {
  10920. childNode = edges[i].from;
  10921. }
  10922. else {
  10923. childNode = edges[i].to;
  10924. }
  10925. if (childNode.level == -1 || childNode.level > level) {
  10926. childNode.level = level;
  10927. if (edges.length > 1) {
  10928. this._setLevel(level+1, childNode.edges, childNode.id);
  10929. }
  10930. }
  10931. }
  10932. },
  10933. /**
  10934. * Unfix nodes
  10935. *
  10936. * @private
  10937. */
  10938. _restoreNodes : function() {
  10939. for (nodeId in this.nodes) {
  10940. if (this.nodes.hasOwnProperty(nodeId)) {
  10941. this.nodes[nodeId].xFixed = false;
  10942. this.nodes[nodeId].yFixed = false;
  10943. }
  10944. }
  10945. }
  10946. };
  10947. /**
  10948. * Created by Alex on 2/4/14.
  10949. */
  10950. var manipulationMixin = {
  10951. /**
  10952. * clears the toolbar div element of children
  10953. *
  10954. * @private
  10955. */
  10956. _clearManipulatorBar : function() {
  10957. while (this.manipulationDiv.hasChildNodes()) {
  10958. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  10959. }
  10960. },
  10961. /**
  10962. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  10963. * these functions to their original functionality, we saved them in this.cachedFunctions.
  10964. * This function restores these functions to their original function.
  10965. *
  10966. * @private
  10967. */
  10968. _restoreOverloadedFunctions : function() {
  10969. for (var functionName in this.cachedFunctions) {
  10970. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  10971. this[functionName] = this.cachedFunctions[functionName];
  10972. }
  10973. }
  10974. },
  10975. /**
  10976. * Enable or disable edit-mode.
  10977. *
  10978. * @private
  10979. */
  10980. _toggleEditMode : function() {
  10981. this.editMode = !this.editMode;
  10982. var toolbar = document.getElementById("graph-manipulationDiv");
  10983. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  10984. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  10985. if (this.editMode == true) {
  10986. toolbar.style.display="block";
  10987. closeDiv.style.display="block";
  10988. editModeDiv.style.display="none";
  10989. closeDiv.onclick = this._toggleEditMode.bind(this);
  10990. }
  10991. else {
  10992. toolbar.style.display="none";
  10993. closeDiv.style.display="none";
  10994. editModeDiv.style.display="block";
  10995. closeDiv.onclick = null;
  10996. }
  10997. this._createManipulatorBar()
  10998. },
  10999. /**
  11000. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  11001. *
  11002. * @private
  11003. */
  11004. _createManipulatorBar : function() {
  11005. // remove bound functions
  11006. if (this.boundFunction) {
  11007. this.off('select', this.boundFunction);
  11008. }
  11009. // restore overloaded functions
  11010. this._restoreOverloadedFunctions();
  11011. // resume calculation
  11012. this.freezeSimulation = false;
  11013. // reset global variables
  11014. this.blockConnectingEdgeSelection = false;
  11015. this.forceAppendSelection = false
  11016. if (this.editMode == true) {
  11017. while (this.manipulationDiv.hasChildNodes()) {
  11018. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11019. }
  11020. // add the icons to the manipulator div
  11021. this.manipulationDiv.innerHTML = "" +
  11022. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  11023. "<span class='graph-manipulationLabel'>Add Node</span></span>" +
  11024. "<div class='graph-seperatorLine'></div>" +
  11025. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  11026. "<span class='graph-manipulationLabel'>Add Link</span></span>";
  11027. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11028. this.manipulationDiv.innerHTML += "" +
  11029. "<div class='graph-seperatorLine'></div>" +
  11030. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  11031. "<span class='graph-manipulationLabel'>Edit Node</span></span>";
  11032. }
  11033. if (this._selectionIsEmpty() == false) {
  11034. this.manipulationDiv.innerHTML += "" +
  11035. "<div class='graph-seperatorLine'></div>" +
  11036. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  11037. "<span class='graph-manipulationLabel'>Delete selected</span></span>";
  11038. }
  11039. // bind the icons
  11040. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  11041. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  11042. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  11043. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  11044. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11045. var editButton = document.getElementById("graph-manipulate-editNode");
  11046. editButton.onclick = this._editNode.bind(this);
  11047. }
  11048. if (this._selectionIsEmpty() == false) {
  11049. var deleteButton = document.getElementById("graph-manipulate-delete");
  11050. deleteButton.onclick = this._deleteSelected.bind(this);
  11051. }
  11052. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11053. closeDiv.onclick = this._toggleEditMode.bind(this);
  11054. this.boundFunction = this._createManipulatorBar.bind(this);
  11055. this.on('select', this.boundFunction);
  11056. }
  11057. else {
  11058. this.editModeDiv.innerHTML = "" +
  11059. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  11060. "<span class='graph-manipulationLabel'>Edit</span></span>"
  11061. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  11062. editModeButton.onclick = this._toggleEditMode.bind(this);
  11063. }
  11064. },
  11065. /**
  11066. * Create the toolbar for adding Nodes
  11067. *
  11068. * @private
  11069. */
  11070. _createAddNodeToolbar : function() {
  11071. // clear the toolbar
  11072. this._clearManipulatorBar();
  11073. if (this.boundFunction) {
  11074. this.off('select', this.boundFunction);
  11075. }
  11076. // create the toolbar contents
  11077. this.manipulationDiv.innerHTML = "" +
  11078. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11079. "<span class='graph-manipulationLabel'>Back</span></span>" +
  11080. "<div class='graph-seperatorLine'></div>" +
  11081. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11082. "<span class='graph-manipulationLabel'>Click in an empty space to place a new node</span></span>";
  11083. // bind the icon
  11084. var backButton = document.getElementById("graph-manipulate-back");
  11085. backButton.onclick = this._createManipulatorBar.bind(this);
  11086. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11087. this.boundFunction = this._addNode.bind(this);
  11088. this.on('select', this.boundFunction);
  11089. },
  11090. /**
  11091. * create the toolbar to connect nodes
  11092. *
  11093. * @private
  11094. */
  11095. _createAddEdgeToolbar : function() {
  11096. // clear the toolbar
  11097. this._clearManipulatorBar();
  11098. this._unselectAll(true);
  11099. this.freezeSimulation = true;
  11100. if (this.boundFunction) {
  11101. this.off('select', this.boundFunction);
  11102. }
  11103. this._unselectAll();
  11104. this.forceAppendSelection = false;
  11105. this.blockConnectingEdgeSelection = true;
  11106. this.manipulationDiv.innerHTML = "" +
  11107. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11108. "<span class='graph-manipulationLabel'>Back</span></span>" +
  11109. "<div class='graph-seperatorLine'></div>" +
  11110. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11111. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>Click on a node and drag the edge to another node to connect them.</span></span>";
  11112. // bind the icon
  11113. var backButton = document.getElementById("graph-manipulate-back");
  11114. backButton.onclick = this._createManipulatorBar.bind(this);
  11115. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11116. this.boundFunction = this._handleConnect.bind(this);
  11117. this.on('select', this.boundFunction);
  11118. // temporarily overload functions
  11119. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  11120. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  11121. this._handleTouch = this._handleConnect;
  11122. this._handleOnRelease = this._finishConnect;
  11123. // redraw to show the unselect
  11124. this._redraw();
  11125. },
  11126. /**
  11127. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11128. * to walk the user through the process.
  11129. *
  11130. * @private
  11131. */
  11132. _handleConnect : function(pointer) {
  11133. if (this._getSelectedNodeCount() == 0) {
  11134. var node = this._getNodeAt(pointer);
  11135. if (node != null) {
  11136. if (node.clusterSize > 1) {
  11137. alert("Cannot create edges to a cluster.")
  11138. }
  11139. else {
  11140. this._selectObject(node,false);
  11141. // create a node the temporary line can look at
  11142. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11143. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11144. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11145. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11146. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11147. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11148. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11149. // create a temporary edge
  11150. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11151. this.edges['connectionEdge'].from = node;
  11152. this.edges['connectionEdge'].connected = true;
  11153. this.edges['connectionEdge'].smooth = true;
  11154. this.edges['connectionEdge'].selected = true;
  11155. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11156. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11157. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11158. this._handleOnDrag = function(event) {
  11159. var pointer = this._getPointer(event.gesture.center);
  11160. this.sectors['support']['nodes']['targetNode'].x = this._canvasToX(pointer.x);
  11161. this.sectors['support']['nodes']['targetNode'].y = this._canvasToY(pointer.y);
  11162. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._canvasToX(pointer.x) + this.edges['connectionEdge'].from.x);
  11163. this.sectors['support']['nodes']['targetViaNode'].y = this._canvasToY(pointer.y);
  11164. };
  11165. this.moving = true;
  11166. this.start();
  11167. }
  11168. }
  11169. }
  11170. },
  11171. _finishConnect : function(pointer) {
  11172. if (this._getSelectedNodeCount() == 1) {
  11173. // restore the drag function
  11174. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11175. delete this.cachedFunctions["_handleOnDrag"];
  11176. // remember the edge id
  11177. var connectFromId = this.edges['connectionEdge'].fromId;
  11178. // remove the temporary nodes and edge
  11179. delete this.edges['connectionEdge']
  11180. delete this.sectors['support']['nodes']['targetNode'];
  11181. delete this.sectors['support']['nodes']['targetViaNode'];
  11182. var node = this._getNodeAt(pointer);
  11183. if (node != null) {
  11184. if (node.clusterSize > 1) {
  11185. alert("Cannot create edges to a cluster.")
  11186. }
  11187. else {
  11188. this._createEdge(connectFromId,node.id);
  11189. this._createManipulatorBar();
  11190. }
  11191. }
  11192. this._unselectAll();
  11193. }
  11194. },
  11195. /**
  11196. * Adds a node on the specified location
  11197. *
  11198. * @param {Object} pointer
  11199. */
  11200. _addNode : function() {
  11201. if (this._selectionIsEmpty() && this.editMode == true) {
  11202. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11203. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  11204. if (this.triggerFunctions.add) {
  11205. if (this.triggerFunctions.add.length == 2) {
  11206. var me = this;
  11207. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11208. me.nodesData.add(finalizedData);
  11209. me._createManipulatorBar();
  11210. me.moving = true;
  11211. me.start();
  11212. });
  11213. }
  11214. else {
  11215. alert("The function for add does not support two arguments (data,callback).");
  11216. this._createManipulatorBar();
  11217. this.moving = true;
  11218. this.start();
  11219. }
  11220. }
  11221. else {
  11222. this.nodesData.add(defaultData);
  11223. this._createManipulatorBar();
  11224. this.moving = true;
  11225. this.start();
  11226. }
  11227. }
  11228. },
  11229. /**
  11230. * connect two nodes with a new edge.
  11231. *
  11232. * @private
  11233. */
  11234. _createEdge : function(sourceNodeId,targetNodeId) {
  11235. if (this.editMode == true) {
  11236. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11237. if (this.triggerFunctions.connect) {
  11238. if (this.triggerFunctions.connect.length == 2) {
  11239. var me = this;
  11240. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11241. me.edgesData.add(finalizedData)
  11242. me.moving = true;
  11243. me.start();
  11244. });
  11245. }
  11246. else {
  11247. alert("The function for connect does not support two arguments (data,callback).");
  11248. this.moving = true;
  11249. this.start();
  11250. }
  11251. }
  11252. else {
  11253. this.edgesData.add(defaultData)
  11254. this.moving = true;
  11255. this.start();
  11256. }
  11257. }
  11258. },
  11259. /**
  11260. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11261. *
  11262. * @private
  11263. */
  11264. _editNode : function() {
  11265. if (this.triggerFunctions.edit && this.editMode == true) {
  11266. var node = this._getSelectedNode();
  11267. var data = {id:node.id,
  11268. label: node.label,
  11269. group: node.group,
  11270. shape: node.shape,
  11271. color: {
  11272. background:node.color.background,
  11273. border:node.color.border,
  11274. highlight: {
  11275. background:node.color.highlight.background,
  11276. border:node.color.highlight.border
  11277. }
  11278. }};
  11279. if (this.triggerFunctions.edit.length == 2) {
  11280. var me = this;
  11281. this.triggerFunctions.edit(data, function (finalizedData) {
  11282. me.nodesData.update(finalizedData);
  11283. me._createManipulatorBar();
  11284. me.moving = true;
  11285. me.start();
  11286. });
  11287. }
  11288. else {
  11289. alert("The function for edit does not support two arguments (data, callback).")
  11290. }
  11291. }
  11292. else {
  11293. alert("No edit function has been bound to this button.")
  11294. }
  11295. },
  11296. /**
  11297. * delete everything in the selection
  11298. *
  11299. * @private
  11300. */
  11301. _deleteSelected : function() {
  11302. if (!this._selectionIsEmpty() && this.editMode == true) {
  11303. if (!this._clusterInSelection()) {
  11304. var selectedNodes = this.getSelectedNodes();
  11305. var selectedEdges = this.getSelectedEdges();
  11306. if (this.triggerFunctions.delete) {
  11307. var me = this;
  11308. var data = {nodes: selectedNodes, edges: selectedEdges};
  11309. if (this.triggerFunctions.delete.length = 2) {
  11310. this.triggerFunctions.delete(data, function (finalizedData) {
  11311. me.edgesData.remove(finalizedData.edges);
  11312. me.nodesData.remove(finalizedData.nodes);
  11313. this._unselectAll();
  11314. me.moving = true;
  11315. me.start();
  11316. });
  11317. }
  11318. else {
  11319. alert("The function for edit does not support two arguments (data, callback).")
  11320. }
  11321. }
  11322. else {
  11323. this.edgesData.remove(selectedEdges);
  11324. this.nodesData.remove(selectedNodes);
  11325. this._unselectAll();
  11326. this.moving = true;
  11327. this.start();
  11328. }
  11329. }
  11330. else {
  11331. alert("Clusters cannot be deleted.");
  11332. }
  11333. }
  11334. }
  11335. };
  11336. /**
  11337. * Creation of the SectorMixin var.
  11338. *
  11339. * This contains all the functions the Graph object can use to employ the sector system.
  11340. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11341. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11342. *
  11343. * Alex de Mulder
  11344. * 21-01-2013
  11345. */
  11346. var SectorMixin = {
  11347. /**
  11348. * This function is only called by the setData function of the Graph object.
  11349. * This loads the global references into the active sector. This initializes the sector.
  11350. *
  11351. * @private
  11352. */
  11353. _putDataInSector : function() {
  11354. this.sectors["active"][this._sector()].nodes = this.nodes;
  11355. this.sectors["active"][this._sector()].edges = this.edges;
  11356. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11357. },
  11358. /**
  11359. * /**
  11360. * This function sets the global references to nodes, edges and nodeIndices back to
  11361. * those of the supplied (active) sector. If a type is defined, do the specific type
  11362. *
  11363. * @param {String} sectorId
  11364. * @param {String} [sectorType] | "active" or "frozen"
  11365. * @private
  11366. */
  11367. _switchToSector : function(sectorId, sectorType) {
  11368. if (sectorType === undefined || sectorType == "active") {
  11369. this._switchToActiveSector(sectorId);
  11370. }
  11371. else {
  11372. this._switchToFrozenSector(sectorId);
  11373. }
  11374. },
  11375. /**
  11376. * This function sets the global references to nodes, edges and nodeIndices back to
  11377. * those of the supplied active sector.
  11378. *
  11379. * @param sectorId
  11380. * @private
  11381. */
  11382. _switchToActiveSector : function(sectorId) {
  11383. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11384. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11385. this.edges = this.sectors["active"][sectorId]["edges"];
  11386. },
  11387. /**
  11388. * This function sets the global references to nodes, edges and nodeIndices back to
  11389. * those of the supplied active sector.
  11390. *
  11391. * @param sectorId
  11392. * @private
  11393. */
  11394. _switchToSupportSector : function() {
  11395. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11396. this.nodes = this.sectors["support"]["nodes"];
  11397. this.edges = this.sectors["support"]["edges"];
  11398. },
  11399. /**
  11400. * This function sets the global references to nodes, edges and nodeIndices back to
  11401. * those of the supplied frozen sector.
  11402. *
  11403. * @param sectorId
  11404. * @private
  11405. */
  11406. _switchToFrozenSector : function(sectorId) {
  11407. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11408. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11409. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11410. },
  11411. /**
  11412. * This function sets the global references to nodes, edges and nodeIndices back to
  11413. * those of the currently active sector.
  11414. *
  11415. * @private
  11416. */
  11417. _loadLatestSector : function() {
  11418. this._switchToSector(this._sector());
  11419. },
  11420. /**
  11421. * This function returns the currently active sector Id
  11422. *
  11423. * @returns {String}
  11424. * @private
  11425. */
  11426. _sector : function() {
  11427. return this.activeSector[this.activeSector.length-1];
  11428. },
  11429. /**
  11430. * This function returns the previously active sector Id
  11431. *
  11432. * @returns {String}
  11433. * @private
  11434. */
  11435. _previousSector : function() {
  11436. if (this.activeSector.length > 1) {
  11437. return this.activeSector[this.activeSector.length-2];
  11438. }
  11439. else {
  11440. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11441. }
  11442. },
  11443. /**
  11444. * We add the active sector at the end of the this.activeSector array
  11445. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11446. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11447. *
  11448. * @param newId
  11449. * @private
  11450. */
  11451. _setActiveSector : function(newId) {
  11452. this.activeSector.push(newId);
  11453. },
  11454. /**
  11455. * We remove the currently active sector id from the active sector stack. This happens when
  11456. * we reactivate the previously active sector
  11457. *
  11458. * @private
  11459. */
  11460. _forgetLastSector : function() {
  11461. this.activeSector.pop();
  11462. },
  11463. /**
  11464. * This function creates a new active sector with the supplied newId. This newId
  11465. * is the expanding node id.
  11466. *
  11467. * @param {String} newId | Id of the new active sector
  11468. * @private
  11469. */
  11470. _createNewSector : function(newId) {
  11471. // create the new sector
  11472. this.sectors["active"][newId] = {"nodes":{},
  11473. "edges":{},
  11474. "nodeIndices":[],
  11475. "formationScale": this.scale,
  11476. "drawingNode": undefined};
  11477. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11478. this.sectors["active"][newId]['drawingNode'] = new Node(
  11479. {id:newId,
  11480. color: {
  11481. background: "#eaefef",
  11482. border: "495c5e"
  11483. }
  11484. },{},{},this.constants);
  11485. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11486. },
  11487. /**
  11488. * This function removes the currently active sector. This is called when we create a new
  11489. * active sector.
  11490. *
  11491. * @param {String} sectorId | Id of the active sector that will be removed
  11492. * @private
  11493. */
  11494. _deleteActiveSector : function(sectorId) {
  11495. delete this.sectors["active"][sectorId];
  11496. },
  11497. /**
  11498. * This function removes the currently active sector. This is called when we reactivate
  11499. * the previously active sector.
  11500. *
  11501. * @param {String} sectorId | Id of the active sector that will be removed
  11502. * @private
  11503. */
  11504. _deleteFrozenSector : function(sectorId) {
  11505. delete this.sectors["frozen"][sectorId];
  11506. },
  11507. /**
  11508. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11509. * We copy the references, then delete the active entree.
  11510. *
  11511. * @param sectorId
  11512. * @private
  11513. */
  11514. _freezeSector : function(sectorId) {
  11515. // we move the set references from the active to the frozen stack.
  11516. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11517. // we have moved the sector data into the frozen set, we now remove it from the active set
  11518. this._deleteActiveSector(sectorId);
  11519. },
  11520. /**
  11521. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11522. * object to the "active" object.
  11523. *
  11524. * @param sectorId
  11525. * @private
  11526. */
  11527. _activateSector : function(sectorId) {
  11528. // we move the set references from the frozen to the active stack.
  11529. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11530. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11531. this._deleteFrozenSector(sectorId);
  11532. },
  11533. /**
  11534. * This function merges the data from the currently active sector with a frozen sector. This is used
  11535. * in the process of reverting back to the previously active sector.
  11536. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11537. * upon the creation of a new active sector.
  11538. *
  11539. * @param sectorId
  11540. * @private
  11541. */
  11542. _mergeThisWithFrozen : function(sectorId) {
  11543. // copy all nodes
  11544. for (var nodeId in this.nodes) {
  11545. if (this.nodes.hasOwnProperty(nodeId)) {
  11546. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11547. }
  11548. }
  11549. // copy all edges (if not fully clustered, else there are no edges)
  11550. for (var edgeId in this.edges) {
  11551. if (this.edges.hasOwnProperty(edgeId)) {
  11552. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11553. }
  11554. }
  11555. // merge the nodeIndices
  11556. for (var i = 0; i < this.nodeIndices.length; i++) {
  11557. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11558. }
  11559. },
  11560. /**
  11561. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11562. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11563. *
  11564. * @private
  11565. */
  11566. _collapseThisToSingleCluster : function() {
  11567. this.clusterToFit(1,false);
  11568. },
  11569. /**
  11570. * We create a new active sector from the node that we want to open.
  11571. *
  11572. * @param node
  11573. * @private
  11574. */
  11575. _addSector : function(node) {
  11576. // this is the currently active sector
  11577. var sector = this._sector();
  11578. // // this should allow me to select nodes from a frozen set.
  11579. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11580. // console.log("the node is part of the active sector");
  11581. // }
  11582. // else {
  11583. // console.log("I dont know what the fuck happened!!");
  11584. // }
  11585. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11586. delete this.nodes[node.id];
  11587. var unqiueIdentifier = util.randomUUID();
  11588. // we fully freeze the currently active sector
  11589. this._freezeSector(sector);
  11590. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11591. this._createNewSector(unqiueIdentifier);
  11592. // we add the active sector to the sectors array to be able to revert these steps later on
  11593. this._setActiveSector(unqiueIdentifier);
  11594. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11595. this._switchToSector(this._sector());
  11596. // finally we add the node we removed from our previous active sector to the new active sector
  11597. this.nodes[node.id] = node;
  11598. },
  11599. /**
  11600. * We close the sector that is currently open and revert back to the one before.
  11601. * If the active sector is the "default" sector, nothing happens.
  11602. *
  11603. * @private
  11604. */
  11605. _collapseSector : function() {
  11606. // the currently active sector
  11607. var sector = this._sector();
  11608. // we cannot collapse the default sector
  11609. if (sector != "default") {
  11610. if ((this.nodeIndices.length == 1) ||
  11611. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11612. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11613. var previousSector = this._previousSector();
  11614. // we collapse the sector back to a single cluster
  11615. this._collapseThisToSingleCluster();
  11616. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  11617. // This previous sector is the one we will reactivate
  11618. this._mergeThisWithFrozen(previousSector);
  11619. // the previously active (frozen) sector now has all the data from the currently active sector.
  11620. // we can now delete the active sector.
  11621. this._deleteActiveSector(sector);
  11622. // we activate the previously active (and currently frozen) sector.
  11623. this._activateSector(previousSector);
  11624. // we load the references from the newly active sector into the global references
  11625. this._switchToSector(previousSector);
  11626. // we forget the previously active sector because we reverted to the one before
  11627. this._forgetLastSector();
  11628. // finally, we update the node index list.
  11629. this._updateNodeIndexList();
  11630. // we refresh the list with calulation nodes and calculation node indices.
  11631. this._updateCalculationNodes();
  11632. }
  11633. }
  11634. },
  11635. /**
  11636. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11637. *
  11638. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11639. * | we dont pass the function itself because then the "this" is the window object
  11640. * | instead of the Graph object
  11641. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11642. * @private
  11643. */
  11644. _doInAllActiveSectors : function(runFunction,argument) {
  11645. if (argument === undefined) {
  11646. for (var sector in this.sectors["active"]) {
  11647. if (this.sectors["active"].hasOwnProperty(sector)) {
  11648. // switch the global references to those of this sector
  11649. this._switchToActiveSector(sector);
  11650. this[runFunction]();
  11651. }
  11652. }
  11653. }
  11654. else {
  11655. for (var sector in this.sectors["active"]) {
  11656. if (this.sectors["active"].hasOwnProperty(sector)) {
  11657. // switch the global references to those of this sector
  11658. this._switchToActiveSector(sector);
  11659. var args = Array.prototype.splice.call(arguments, 1);
  11660. if (args.length > 1) {
  11661. this[runFunction](args[0],args[1]);
  11662. }
  11663. else {
  11664. this[runFunction](argument);
  11665. }
  11666. }
  11667. }
  11668. }
  11669. // we revert the global references back to our active sector
  11670. this._loadLatestSector();
  11671. },
  11672. /**
  11673. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11674. *
  11675. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11676. * | we dont pass the function itself because then the "this" is the window object
  11677. * | instead of the Graph object
  11678. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11679. * @private
  11680. */
  11681. _doInSupportSector : function(runFunction,argument) {
  11682. if (argument === undefined) {
  11683. this._switchToSupportSector();
  11684. this[runFunction]();
  11685. }
  11686. else {
  11687. this._switchToSupportSector();
  11688. var args = Array.prototype.splice.call(arguments, 1);
  11689. if (args.length > 1) {
  11690. this[runFunction](args[0],args[1]);
  11691. }
  11692. else {
  11693. this[runFunction](argument);
  11694. }
  11695. }
  11696. // we revert the global references back to our active sector
  11697. this._loadLatestSector();
  11698. },
  11699. /**
  11700. * This runs a function in all frozen sectors. This is used in the _redraw().
  11701. *
  11702. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11703. * | we don't pass the function itself because then the "this" is the window object
  11704. * | instead of the Graph object
  11705. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11706. * @private
  11707. */
  11708. _doInAllFrozenSectors : function(runFunction,argument) {
  11709. if (argument === undefined) {
  11710. for (var sector in this.sectors["frozen"]) {
  11711. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11712. // switch the global references to those of this sector
  11713. this._switchToFrozenSector(sector);
  11714. this[runFunction]();
  11715. }
  11716. }
  11717. }
  11718. else {
  11719. for (var sector in this.sectors["frozen"]) {
  11720. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11721. // switch the global references to those of this sector
  11722. this._switchToFrozenSector(sector);
  11723. var args = Array.prototype.splice.call(arguments, 1);
  11724. if (args.length > 1) {
  11725. this[runFunction](args[0],args[1]);
  11726. }
  11727. else {
  11728. this[runFunction](argument);
  11729. }
  11730. }
  11731. }
  11732. }
  11733. this._loadLatestSector();
  11734. },
  11735. /**
  11736. * This runs a function in all sectors. This is used in the _redraw().
  11737. *
  11738. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11739. * | we don't pass the function itself because then the "this" is the window object
  11740. * | instead of the Graph object
  11741. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11742. * @private
  11743. */
  11744. _doInAllSectors : function(runFunction,argument) {
  11745. var args = Array.prototype.splice.call(arguments, 1);
  11746. if (argument === undefined) {
  11747. this._doInAllActiveSectors(runFunction);
  11748. this._doInAllFrozenSectors(runFunction);
  11749. }
  11750. else {
  11751. if (args.length > 1) {
  11752. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  11753. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  11754. }
  11755. else {
  11756. this._doInAllActiveSectors(runFunction,argument);
  11757. this._doInAllFrozenSectors(runFunction,argument);
  11758. }
  11759. }
  11760. },
  11761. /**
  11762. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  11763. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  11764. *
  11765. * @private
  11766. */
  11767. _clearNodeIndexList : function() {
  11768. var sector = this._sector();
  11769. this.sectors["active"][sector]["nodeIndices"] = [];
  11770. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  11771. },
  11772. /**
  11773. * Draw the encompassing sector node
  11774. *
  11775. * @param ctx
  11776. * @param sectorType
  11777. * @private
  11778. */
  11779. _drawSectorNodes : function(ctx,sectorType) {
  11780. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11781. for (var sector in this.sectors[sectorType]) {
  11782. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  11783. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  11784. this._switchToSector(sector,sectorType);
  11785. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  11786. for (var nodeId in this.nodes) {
  11787. if (this.nodes.hasOwnProperty(nodeId)) {
  11788. node = this.nodes[nodeId];
  11789. node.resize(ctx);
  11790. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  11791. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  11792. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  11793. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  11794. }
  11795. }
  11796. node = this.sectors[sectorType][sector]["drawingNode"];
  11797. node.x = 0.5 * (maxX + minX);
  11798. node.y = 0.5 * (maxY + minY);
  11799. node.width = 2 * (node.x - minX);
  11800. node.height = 2 * (node.y - minY);
  11801. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  11802. node.setScale(this.scale);
  11803. node._drawCircle(ctx);
  11804. }
  11805. }
  11806. }
  11807. },
  11808. _drawAllSectorNodes : function(ctx) {
  11809. this._drawSectorNodes(ctx,"frozen");
  11810. this._drawSectorNodes(ctx,"active");
  11811. this._loadLatestSector();
  11812. }
  11813. };
  11814. /**
  11815. * Creation of the ClusterMixin var.
  11816. *
  11817. * This contains all the functions the Graph object can use to employ clustering
  11818. *
  11819. * Alex de Mulder
  11820. * 21-01-2013
  11821. */
  11822. var ClusterMixin = {
  11823. /**
  11824. * This is only called in the constructor of the graph object
  11825. *
  11826. */
  11827. startWithClustering : function() {
  11828. // cluster if the data set is big
  11829. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  11830. // updates the lables after clustering
  11831. this.updateLabels();
  11832. // this is called here because if clusterin is disabled, the start and stabilize are called in
  11833. // the setData function.
  11834. if (this.stabilize) {
  11835. this._stabilize();
  11836. }
  11837. this.start();
  11838. },
  11839. /**
  11840. * This function clusters until the initialMaxNodes has been reached
  11841. *
  11842. * @param {Number} maxNumberOfNodes
  11843. * @param {Boolean} reposition
  11844. */
  11845. clusterToFit : function(maxNumberOfNodes, reposition) {
  11846. var numberOfNodes = this.nodeIndices.length;
  11847. var maxLevels = 50;
  11848. var level = 0;
  11849. // we first cluster the hubs, then we pull in the outliers, repeat
  11850. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  11851. if (level % 3 == 0) {
  11852. this.forceAggregateHubs(true);
  11853. this.normalizeClusterLevels();
  11854. }
  11855. else {
  11856. this.increaseClusterLevel(); // this also includes a cluster normalization
  11857. }
  11858. numberOfNodes = this.nodeIndices.length;
  11859. level += 1;
  11860. }
  11861. // after the clustering we reposition the nodes to reduce the initial chaos
  11862. if (level > 0 && reposition == true) {
  11863. this.repositionNodes();
  11864. }
  11865. this._updateCalculationNodes();
  11866. },
  11867. /**
  11868. * This function can be called to open up a specific cluster. It is only called by
  11869. * It will unpack the cluster back one level.
  11870. *
  11871. * @param node | Node object: cluster to open.
  11872. */
  11873. openCluster : function(node) {
  11874. var isMovingBeforeClustering = this.moving;
  11875. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  11876. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  11877. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  11878. this._addSector(node);
  11879. var level = 0;
  11880. // we decluster until we reach a decent number of nodes
  11881. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  11882. this.decreaseClusterLevel();
  11883. level += 1;
  11884. }
  11885. }
  11886. else {
  11887. this._expandClusterNode(node,false,true);
  11888. // update the index list, dynamic edges and labels
  11889. this._updateNodeIndexList();
  11890. this._updateDynamicEdges();
  11891. this._updateCalculationNodes();
  11892. this.updateLabels();
  11893. }
  11894. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11895. if (this.moving != isMovingBeforeClustering) {
  11896. this.start();
  11897. }
  11898. },
  11899. /**
  11900. * This calls the updateClustes with default arguments
  11901. */
  11902. updateClustersDefault : function() {
  11903. if (this.constants.clustering.enabled == true) {
  11904. this.updateClusters(0,false,false);
  11905. }
  11906. },
  11907. /**
  11908. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  11909. * be clustered with their connected node. This can be repeated as many times as needed.
  11910. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  11911. */
  11912. increaseClusterLevel : function() {
  11913. this.updateClusters(-1,false,true);
  11914. },
  11915. /**
  11916. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  11917. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  11918. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  11919. */
  11920. decreaseClusterLevel : function() {
  11921. this.updateClusters(1,false,true);
  11922. },
  11923. /**
  11924. * This is the main clustering function. It clusters and declusters on zoom or forced
  11925. * This function clusters on zoom, it can be called with a predefined zoom direction
  11926. * If out, check if we can form clusters, if in, check if we can open clusters.
  11927. * This function is only called from _zoom()
  11928. *
  11929. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  11930. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  11931. * @param {Boolean} force | enabled or disable forcing
  11932. *
  11933. */
  11934. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  11935. var isMovingBeforeClustering = this.moving;
  11936. var amountOfNodes = this.nodeIndices.length;
  11937. // on zoom out collapse the sector if the scale is at the level the sector was made
  11938. if (this.previousScale > this.scale && zoomDirection == 0) {
  11939. this._collapseSector();
  11940. }
  11941. // check if we zoom in or out
  11942. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  11943. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  11944. // outer nodes determines if it is being clustered
  11945. this._formClusters(force);
  11946. }
  11947. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  11948. if (force == true) {
  11949. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  11950. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  11951. this._openClusters(recursive,force);
  11952. }
  11953. else {
  11954. // if a cluster takes up a set percentage of the active window
  11955. this._openClustersBySize();
  11956. }
  11957. }
  11958. this._updateNodeIndexList();
  11959. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  11960. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  11961. this._aggregateHubs(force);
  11962. this._updateNodeIndexList();
  11963. }
  11964. // we now reduce chains.
  11965. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  11966. this.handleChains();
  11967. this._updateNodeIndexList();
  11968. }
  11969. this.previousScale = this.scale;
  11970. // rest of the update the index list, dynamic edges and labels
  11971. this._updateDynamicEdges();
  11972. this.updateLabels();
  11973. // if a cluster was formed, we increase the clusterSession
  11974. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  11975. this.clusterSession += 1;
  11976. // if clusters have been made, we normalize the cluster level
  11977. this.normalizeClusterLevels();
  11978. }
  11979. if (doNotStart == false || doNotStart === undefined) {
  11980. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  11981. if (this.moving != isMovingBeforeClustering) {
  11982. this.start();
  11983. }
  11984. }
  11985. this._updateCalculationNodes();
  11986. },
  11987. /**
  11988. * This function handles the chains. It is called on every updateClusters().
  11989. */
  11990. handleChains : function() {
  11991. // after clustering we check how many chains there are
  11992. var chainPercentage = this._getChainFraction();
  11993. if (chainPercentage > this.constants.clustering.chainThreshold) {
  11994. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  11995. }
  11996. },
  11997. /**
  11998. * this functions starts clustering by hubs
  11999. * The minimum hub threshold is set globally
  12000. *
  12001. * @private
  12002. */
  12003. _aggregateHubs : function(force) {
  12004. this._getHubSize();
  12005. this._formClustersByHub(force,false);
  12006. },
  12007. /**
  12008. * This function is fired by keypress. It forces hubs to form.
  12009. *
  12010. */
  12011. forceAggregateHubs : function(doNotStart) {
  12012. var isMovingBeforeClustering = this.moving;
  12013. var amountOfNodes = this.nodeIndices.length;
  12014. this._aggregateHubs(true);
  12015. // update the index list, dynamic edges and labels
  12016. this._updateNodeIndexList();
  12017. this._updateDynamicEdges();
  12018. this.updateLabels();
  12019. // if a cluster was formed, we increase the clusterSession
  12020. if (this.nodeIndices.length != amountOfNodes) {
  12021. this.clusterSession += 1;
  12022. }
  12023. if (doNotStart == false || doNotStart === undefined) {
  12024. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12025. if (this.moving != isMovingBeforeClustering) {
  12026. this.start();
  12027. }
  12028. }
  12029. },
  12030. /**
  12031. * If a cluster takes up more than a set percentage of the screen, open the cluster
  12032. *
  12033. * @private
  12034. */
  12035. _openClustersBySize : function() {
  12036. for (var nodeId in this.nodes) {
  12037. if (this.nodes.hasOwnProperty(nodeId)) {
  12038. var node = this.nodes[nodeId];
  12039. if (node.inView() == true) {
  12040. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  12041. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  12042. this.openCluster(node);
  12043. }
  12044. }
  12045. }
  12046. }
  12047. },
  12048. /**
  12049. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  12050. * has to be opened based on the current zoom level.
  12051. *
  12052. * @private
  12053. */
  12054. _openClusters : function(recursive,force) {
  12055. for (var i = 0; i < this.nodeIndices.length; i++) {
  12056. var node = this.nodes[this.nodeIndices[i]];
  12057. this._expandClusterNode(node,recursive,force);
  12058. this._updateCalculationNodes();
  12059. }
  12060. },
  12061. /**
  12062. * This function checks if a node has to be opened. This is done by checking the zoom level.
  12063. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  12064. * This recursive behaviour is optional and can be set by the recursive argument.
  12065. *
  12066. * @param {Node} parentNode | to check for cluster and expand
  12067. * @param {Boolean} recursive | enabled or disable recursive calling
  12068. * @param {Boolean} force | enabled or disable forcing
  12069. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  12070. * @private
  12071. */
  12072. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  12073. // first check if node is a cluster
  12074. if (parentNode.clusterSize > 1) {
  12075. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  12076. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  12077. openAll = true;
  12078. }
  12079. recursive = openAll ? true : recursive;
  12080. // if the last child has been added on a smaller scale than current scale decluster
  12081. if (parentNode.formationScale < this.scale || force == true) {
  12082. // we will check if any of the contained child nodes should be removed from the cluster
  12083. for (var containedNodeId in parentNode.containedNodes) {
  12084. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  12085. var childNode = parentNode.containedNodes[containedNodeId];
  12086. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  12087. // the largest cluster is the one that comes from outside
  12088. if (force == true) {
  12089. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  12090. || openAll) {
  12091. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12092. }
  12093. }
  12094. else {
  12095. if (this._nodeInActiveArea(parentNode)) {
  12096. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12097. }
  12098. }
  12099. }
  12100. }
  12101. }
  12102. }
  12103. },
  12104. /**
  12105. * ONLY CALLED FROM _expandClusterNode
  12106. *
  12107. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  12108. * the child node from the parent contained_node object and put it back into the global nodes object.
  12109. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  12110. *
  12111. * @param {Node} parentNode | the parent node
  12112. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  12113. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  12114. * With force and recursive both true, the entire cluster is unpacked
  12115. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  12116. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  12117. * @private
  12118. */
  12119. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  12120. var childNode = parentNode.containedNodes[containedNodeId];
  12121. // if child node has been added on smaller scale than current, kick out
  12122. if (childNode.formationScale < this.scale || force == true) {
  12123. // unselect all selected items
  12124. this._unselectAll();
  12125. // put the child node back in the global nodes object
  12126. this.nodes[containedNodeId] = childNode;
  12127. // release the contained edges from this childNode back into the global edges
  12128. this._releaseContainedEdges(parentNode,childNode);
  12129. // reconnect rerouted edges to the childNode
  12130. this._connectEdgeBackToChild(parentNode,childNode);
  12131. // validate all edges in dynamicEdges
  12132. this._validateEdges(parentNode);
  12133. // undo the changes from the clustering operation on the parent node
  12134. parentNode.mass -= childNode.mass;
  12135. parentNode.clusterSize -= childNode.clusterSize;
  12136. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12137. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12138. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12139. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12140. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12141. // remove node from the list
  12142. delete parentNode.containedNodes[containedNodeId];
  12143. // check if there are other childs with this clusterSession in the parent.
  12144. var othersPresent = false;
  12145. for (var childNodeId in parentNode.containedNodes) {
  12146. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12147. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12148. othersPresent = true;
  12149. break;
  12150. }
  12151. }
  12152. }
  12153. // if there are no others, remove the cluster session from the list
  12154. if (othersPresent == false) {
  12155. parentNode.clusterSessions.pop();
  12156. }
  12157. this._repositionBezierNodes(childNode);
  12158. // this._repositionBezierNodes(parentNode);
  12159. // remove the clusterSession from the child node
  12160. childNode.clusterSession = 0;
  12161. // recalculate the size of the node on the next time the node is rendered
  12162. parentNode.clearSizeCache();
  12163. // restart the simulation to reorganise all nodes
  12164. this.moving = true;
  12165. }
  12166. // check if a further expansion step is possible if recursivity is enabled
  12167. if (recursive == true) {
  12168. this._expandClusterNode(childNode,recursive,force,openAll);
  12169. }
  12170. },
  12171. /**
  12172. * position the bezier nodes at the center of the edges
  12173. *
  12174. * @param node
  12175. * @private
  12176. */
  12177. _repositionBezierNodes : function(node) {
  12178. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12179. node.dynamicEdges[i].positionBezierNode();
  12180. }
  12181. },
  12182. /**
  12183. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12184. * This function is called only from updateClusters()
  12185. * forceLevelCollapse ignores the length of the edge and collapses one level
  12186. * This means that a node with only one edge will be clustered with its connected node
  12187. *
  12188. * @private
  12189. * @param {Boolean} force
  12190. */
  12191. _formClusters : function(force) {
  12192. if (force == false) {
  12193. this._formClustersByZoom();
  12194. }
  12195. else {
  12196. this._forceClustersByZoom();
  12197. }
  12198. },
  12199. /**
  12200. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12201. *
  12202. * @private
  12203. */
  12204. _formClustersByZoom : function() {
  12205. var dx,dy,length,
  12206. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12207. // check if any edges are shorter than minLength and start the clustering
  12208. // the clustering favours the node with the larger mass
  12209. for (var edgeId in this.edges) {
  12210. if (this.edges.hasOwnProperty(edgeId)) {
  12211. var edge = this.edges[edgeId];
  12212. if (edge.connected) {
  12213. if (edge.toId != edge.fromId) {
  12214. dx = (edge.to.x - edge.from.x);
  12215. dy = (edge.to.y - edge.from.y);
  12216. length = Math.sqrt(dx * dx + dy * dy);
  12217. if (length < minLength) {
  12218. // first check which node is larger
  12219. var parentNode = edge.from;
  12220. var childNode = edge.to;
  12221. if (edge.to.mass > edge.from.mass) {
  12222. parentNode = edge.to;
  12223. childNode = edge.from;
  12224. }
  12225. if (childNode.dynamicEdgesLength == 1) {
  12226. this._addToCluster(parentNode,childNode,false);
  12227. }
  12228. else if (parentNode.dynamicEdgesLength == 1) {
  12229. this._addToCluster(childNode,parentNode,false);
  12230. }
  12231. }
  12232. }
  12233. }
  12234. }
  12235. }
  12236. },
  12237. /**
  12238. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12239. * connected node.
  12240. *
  12241. * @private
  12242. */
  12243. _forceClustersByZoom : function() {
  12244. for (var nodeId in this.nodes) {
  12245. // another node could have absorbed this child.
  12246. if (this.nodes.hasOwnProperty(nodeId)) {
  12247. var childNode = this.nodes[nodeId];
  12248. // the edges can be swallowed by another decrease
  12249. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12250. var edge = childNode.dynamicEdges[0];
  12251. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12252. // group to the largest node
  12253. if (childNode.id != parentNode.id) {
  12254. if (parentNode.mass > childNode.mass) {
  12255. this._addToCluster(parentNode,childNode,true);
  12256. }
  12257. else {
  12258. this._addToCluster(childNode,parentNode,true);
  12259. }
  12260. }
  12261. }
  12262. }
  12263. }
  12264. },
  12265. /**
  12266. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12267. * This function clusters a node to its smallest connected neighbour.
  12268. *
  12269. * @param node
  12270. * @private
  12271. */
  12272. _clusterToSmallestNeighbour : function(node) {
  12273. var smallestNeighbour = -1;
  12274. var smallestNeighbourNode = null;
  12275. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12276. if (node.dynamicEdges[i] !== undefined) {
  12277. var neighbour = null;
  12278. if (node.dynamicEdges[i].fromId != node.id) {
  12279. neighbour = node.dynamicEdges[i].from;
  12280. }
  12281. else if (node.dynamicEdges[i].toId != node.id) {
  12282. neighbour = node.dynamicEdges[i].to;
  12283. }
  12284. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12285. smallestNeighbour = neighbour.clusterSessions.length;
  12286. smallestNeighbourNode = neighbour;
  12287. }
  12288. }
  12289. }
  12290. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12291. this._addToCluster(neighbour, node, true);
  12292. }
  12293. },
  12294. /**
  12295. * This function forms clusters from hubs, it loops over all nodes
  12296. *
  12297. * @param {Boolean} force | Disregard zoom level
  12298. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12299. * @private
  12300. */
  12301. _formClustersByHub : function(force, onlyEqual) {
  12302. // we loop over all nodes in the list
  12303. for (var nodeId in this.nodes) {
  12304. // we check if it is still available since it can be used by the clustering in this loop
  12305. if (this.nodes.hasOwnProperty(nodeId)) {
  12306. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12307. }
  12308. }
  12309. },
  12310. /**
  12311. * This function forms a cluster from a specific preselected hub node
  12312. *
  12313. * @param {Node} hubNode | the node we will cluster as a hub
  12314. * @param {Boolean} force | Disregard zoom level
  12315. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12316. * @param {Number} [absorptionSizeOffset] |
  12317. * @private
  12318. */
  12319. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12320. if (absorptionSizeOffset === undefined) {
  12321. absorptionSizeOffset = 0;
  12322. }
  12323. // we decide if the node is a hub
  12324. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12325. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12326. // initialize variables
  12327. var dx,dy,length;
  12328. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12329. var allowCluster = false;
  12330. // we create a list of edges because the dynamicEdges change over the course of this loop
  12331. var edgesIdarray = [];
  12332. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12333. for (var j = 0; j < amountOfInitialEdges; j++) {
  12334. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12335. }
  12336. // if the hub clustering is not forces, we check if one of the edges connected
  12337. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12338. if (force == false) {
  12339. allowCluster = false;
  12340. for (j = 0; j < amountOfInitialEdges; j++) {
  12341. var edge = this.edges[edgesIdarray[j]];
  12342. if (edge !== undefined) {
  12343. if (edge.connected) {
  12344. if (edge.toId != edge.fromId) {
  12345. dx = (edge.to.x - edge.from.x);
  12346. dy = (edge.to.y - edge.from.y);
  12347. length = Math.sqrt(dx * dx + dy * dy);
  12348. if (length < minLength) {
  12349. allowCluster = true;
  12350. break;
  12351. }
  12352. }
  12353. }
  12354. }
  12355. }
  12356. }
  12357. // start the clustering if allowed
  12358. if ((!force && allowCluster) || force) {
  12359. // we loop over all edges INITIALLY connected to this hub
  12360. for (j = 0; j < amountOfInitialEdges; j++) {
  12361. edge = this.edges[edgesIdarray[j]];
  12362. // the edge can be clustered by this function in a previous loop
  12363. if (edge !== undefined) {
  12364. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12365. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12366. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12367. (childNode.id != hubNode.id)) {
  12368. this._addToCluster(hubNode,childNode,force);
  12369. }
  12370. }
  12371. }
  12372. }
  12373. }
  12374. },
  12375. /**
  12376. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12377. *
  12378. * @param {Node} parentNode | this is the node that will house the child node
  12379. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12380. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12381. * @private
  12382. */
  12383. _addToCluster : function(parentNode, childNode, force) {
  12384. // join child node in the parent node
  12385. parentNode.containedNodes[childNode.id] = childNode;
  12386. // manage all the edges connected to the child and parent nodes
  12387. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12388. var edge = childNode.dynamicEdges[i];
  12389. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12390. this._addToContainedEdges(parentNode,childNode,edge);
  12391. }
  12392. else {
  12393. this._connectEdgeToCluster(parentNode,childNode,edge);
  12394. }
  12395. }
  12396. // a contained node has no dynamic edges.
  12397. childNode.dynamicEdges = [];
  12398. // remove circular edges from clusters
  12399. this._containCircularEdgesFromNode(parentNode,childNode);
  12400. // remove the childNode from the global nodes object
  12401. delete this.nodes[childNode.id];
  12402. // update the properties of the child and parent
  12403. var massBefore = parentNode.mass;
  12404. childNode.clusterSession = this.clusterSession;
  12405. parentNode.mass += childNode.mass;
  12406. parentNode.clusterSize += childNode.clusterSize;
  12407. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12408. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12409. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12410. parentNode.clusterSessions.push(this.clusterSession);
  12411. }
  12412. // forced clusters only open from screen size and double tap
  12413. if (force == true) {
  12414. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12415. parentNode.formationScale = 0;
  12416. }
  12417. else {
  12418. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12419. }
  12420. // recalculate the size of the node on the next time the node is rendered
  12421. parentNode.clearSizeCache();
  12422. // set the pop-out scale for the childnode
  12423. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12424. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12425. childNode.clearVelocity();
  12426. // the mass has altered, preservation of energy dictates the velocity to be updated
  12427. parentNode.updateVelocity(massBefore);
  12428. // restart the simulation to reorganise all nodes
  12429. this.moving = true;
  12430. },
  12431. /**
  12432. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12433. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12434. * It has to be called if a level is collapsed. It is called by _formClusters().
  12435. * @private
  12436. */
  12437. _updateDynamicEdges : function() {
  12438. for (var i = 0; i < this.nodeIndices.length; i++) {
  12439. var node = this.nodes[this.nodeIndices[i]];
  12440. node.dynamicEdgesLength = node.dynamicEdges.length;
  12441. // this corrects for multiple edges pointing at the same other node
  12442. var correction = 0;
  12443. if (node.dynamicEdgesLength > 1) {
  12444. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12445. var edgeToId = node.dynamicEdges[j].toId;
  12446. var edgeFromId = node.dynamicEdges[j].fromId;
  12447. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12448. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12449. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12450. correction += 1;
  12451. }
  12452. }
  12453. }
  12454. }
  12455. node.dynamicEdgesLength -= correction;
  12456. }
  12457. },
  12458. /**
  12459. * This adds an edge from the childNode to the contained edges of the parent node
  12460. *
  12461. * @param parentNode | Node object
  12462. * @param childNode | Node object
  12463. * @param edge | Edge object
  12464. * @private
  12465. */
  12466. _addToContainedEdges : function(parentNode, childNode, edge) {
  12467. // create an array object if it does not yet exist for this childNode
  12468. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12469. parentNode.containedEdges[childNode.id] = []
  12470. }
  12471. // add this edge to the list
  12472. parentNode.containedEdges[childNode.id].push(edge);
  12473. // remove the edge from the global edges object
  12474. delete this.edges[edge.id];
  12475. // remove the edge from the parent object
  12476. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12477. if (parentNode.dynamicEdges[i].id == edge.id) {
  12478. parentNode.dynamicEdges.splice(i,1);
  12479. break;
  12480. }
  12481. }
  12482. },
  12483. /**
  12484. * This function connects an edge that was connected to a child node to the parent node.
  12485. * It keeps track of which nodes it has been connected to with the originalId array.
  12486. *
  12487. * @param {Node} parentNode | Node object
  12488. * @param {Node} childNode | Node object
  12489. * @param {Edge} edge | Edge object
  12490. * @private
  12491. */
  12492. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12493. // handle circular edges
  12494. if (edge.toId == edge.fromId) {
  12495. this._addToContainedEdges(parentNode, childNode, edge);
  12496. }
  12497. else {
  12498. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12499. edge.originalToId.push(childNode.id);
  12500. edge.to = parentNode;
  12501. edge.toId = parentNode.id;
  12502. }
  12503. else { // edge connected to other node with the "from" side
  12504. edge.originalFromId.push(childNode.id);
  12505. edge.from = parentNode;
  12506. edge.fromId = parentNode.id;
  12507. }
  12508. this._addToReroutedEdges(parentNode,childNode,edge);
  12509. }
  12510. },
  12511. /**
  12512. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12513. * these edges inside of the cluster.
  12514. *
  12515. * @param parentNode
  12516. * @param childNode
  12517. * @private
  12518. */
  12519. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12520. // manage all the edges connected to the child and parent nodes
  12521. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12522. var edge = parentNode.dynamicEdges[i];
  12523. // handle circular edges
  12524. if (edge.toId == edge.fromId) {
  12525. this._addToContainedEdges(parentNode, childNode, edge);
  12526. }
  12527. }
  12528. },
  12529. /**
  12530. * This adds an edge from the childNode to the rerouted edges of the parent node
  12531. *
  12532. * @param parentNode | Node object
  12533. * @param childNode | Node object
  12534. * @param edge | Edge object
  12535. * @private
  12536. */
  12537. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12538. // create an array object if it does not yet exist for this childNode
  12539. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12540. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12541. parentNode.reroutedEdges[childNode.id] = [];
  12542. }
  12543. parentNode.reroutedEdges[childNode.id].push(edge);
  12544. // this edge becomes part of the dynamicEdges of the cluster node
  12545. parentNode.dynamicEdges.push(edge);
  12546. },
  12547. /**
  12548. * This function connects an edge that was connected to a cluster node back to the child node.
  12549. *
  12550. * @param parentNode | Node object
  12551. * @param childNode | Node object
  12552. * @private
  12553. */
  12554. _connectEdgeBackToChild : function(parentNode, childNode) {
  12555. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12556. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12557. var edge = parentNode.reroutedEdges[childNode.id][i];
  12558. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12559. edge.originalFromId.pop();
  12560. edge.fromId = childNode.id;
  12561. edge.from = childNode;
  12562. }
  12563. else {
  12564. edge.originalToId.pop();
  12565. edge.toId = childNode.id;
  12566. edge.to = childNode;
  12567. }
  12568. // append this edge to the list of edges connecting to the childnode
  12569. childNode.dynamicEdges.push(edge);
  12570. // remove the edge from the parent object
  12571. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12572. if (parentNode.dynamicEdges[j].id == edge.id) {
  12573. parentNode.dynamicEdges.splice(j,1);
  12574. break;
  12575. }
  12576. }
  12577. }
  12578. // remove the entry from the rerouted edges
  12579. delete parentNode.reroutedEdges[childNode.id];
  12580. }
  12581. },
  12582. /**
  12583. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12584. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12585. * parentNode
  12586. *
  12587. * @param parentNode | Node object
  12588. * @private
  12589. */
  12590. _validateEdges : function(parentNode) {
  12591. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12592. var edge = parentNode.dynamicEdges[i];
  12593. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12594. parentNode.dynamicEdges.splice(i,1);
  12595. }
  12596. }
  12597. },
  12598. /**
  12599. * This function released the contained edges back into the global domain and puts them back into the
  12600. * dynamic edges of both parent and child.
  12601. *
  12602. * @param {Node} parentNode |
  12603. * @param {Node} childNode |
  12604. * @private
  12605. */
  12606. _releaseContainedEdges : function(parentNode, childNode) {
  12607. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12608. var edge = parentNode.containedEdges[childNode.id][i];
  12609. // put the edge back in the global edges object
  12610. this.edges[edge.id] = edge;
  12611. // put the edge back in the dynamic edges of the child and parent
  12612. childNode.dynamicEdges.push(edge);
  12613. parentNode.dynamicEdges.push(edge);
  12614. }
  12615. // remove the entry from the contained edges
  12616. delete parentNode.containedEdges[childNode.id];
  12617. },
  12618. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  12619. /**
  12620. * This updates the node labels for all nodes (for debugging purposes)
  12621. */
  12622. updateLabels : function() {
  12623. var nodeId;
  12624. // update node labels
  12625. for (nodeId in this.nodes) {
  12626. if (this.nodes.hasOwnProperty(nodeId)) {
  12627. var node = this.nodes[nodeId];
  12628. if (node.clusterSize > 1) {
  12629. node.label = "[".concat(String(node.clusterSize),"]");
  12630. }
  12631. }
  12632. }
  12633. // update node labels
  12634. for (nodeId in this.nodes) {
  12635. if (this.nodes.hasOwnProperty(nodeId)) {
  12636. node = this.nodes[nodeId];
  12637. if (node.clusterSize == 1) {
  12638. if (node.originalLabel !== undefined) {
  12639. node.label = node.originalLabel;
  12640. }
  12641. else {
  12642. node.label = String(node.id);
  12643. }
  12644. }
  12645. }
  12646. }
  12647. // /* Debug Override */
  12648. // for (nodeId in this.nodes) {
  12649. // if (this.nodes.hasOwnProperty(nodeId)) {
  12650. // node = this.nodes[nodeId];
  12651. // node.label = String(node.level);
  12652. // }
  12653. // }
  12654. },
  12655. /**
  12656. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  12657. * if the rest of the nodes are already a few cluster levels in.
  12658. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  12659. * clustered enough to the clusterToSmallestNeighbours function.
  12660. */
  12661. normalizeClusterLevels : function() {
  12662. var maxLevel = 0;
  12663. var minLevel = 1e9;
  12664. var clusterLevel = 0;
  12665. // we loop over all nodes in the list
  12666. for (var nodeId in this.nodes) {
  12667. if (this.nodes.hasOwnProperty(nodeId)) {
  12668. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  12669. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  12670. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  12671. }
  12672. }
  12673. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  12674. var amountOfNodes = this.nodeIndices.length;
  12675. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  12676. // we loop over all nodes in the list
  12677. for (var nodeId in this.nodes) {
  12678. if (this.nodes.hasOwnProperty(nodeId)) {
  12679. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  12680. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  12681. }
  12682. }
  12683. }
  12684. this._updateNodeIndexList();
  12685. this._updateDynamicEdges();
  12686. // if a cluster was formed, we increase the clusterSession
  12687. if (this.nodeIndices.length != amountOfNodes) {
  12688. this.clusterSession += 1;
  12689. }
  12690. }
  12691. },
  12692. /**
  12693. * This function determines if the cluster we want to decluster is in the active area
  12694. * this means around the zoom center
  12695. *
  12696. * @param {Node} node
  12697. * @returns {boolean}
  12698. * @private
  12699. */
  12700. _nodeInActiveArea : function(node) {
  12701. return (
  12702. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12703. &&
  12704. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12705. )
  12706. },
  12707. /**
  12708. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  12709. * It puts large clusters away from the center and randomizes the order.
  12710. *
  12711. */
  12712. repositionNodes : function() {
  12713. for (var i = 0; i < this.nodeIndices.length; i++) {
  12714. var node = this.nodes[this.nodeIndices[i]];
  12715. if ((node.xFixed == false || node.yFixed == false)) {
  12716. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.mass);
  12717. var angle = 2 * Math.PI * Math.random();
  12718. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  12719. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  12720. this._repositionBezierNodes(node);
  12721. }
  12722. }
  12723. },
  12724. /**
  12725. * We determine how many connections denote an important hub.
  12726. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  12727. *
  12728. * @private
  12729. */
  12730. _getHubSize : function() {
  12731. var average = 0;
  12732. var averageSquared = 0;
  12733. var hubCounter = 0;
  12734. var largestHub = 0;
  12735. for (var i = 0; i < this.nodeIndices.length; i++) {
  12736. var node = this.nodes[this.nodeIndices[i]];
  12737. if (node.dynamicEdgesLength > largestHub) {
  12738. largestHub = node.dynamicEdgesLength;
  12739. }
  12740. average += node.dynamicEdgesLength;
  12741. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  12742. hubCounter += 1;
  12743. }
  12744. average = average / hubCounter;
  12745. averageSquared = averageSquared / hubCounter;
  12746. var variance = averageSquared - Math.pow(average,2);
  12747. var standardDeviation = Math.sqrt(variance);
  12748. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  12749. // always have at least one to cluster
  12750. if (this.hubThreshold > largestHub) {
  12751. this.hubThreshold = largestHub;
  12752. }
  12753. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  12754. // console.log("hubThreshold:",this.hubThreshold);
  12755. },
  12756. /**
  12757. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12758. * with this amount we can cluster specifically on these chains.
  12759. *
  12760. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  12761. * @private
  12762. */
  12763. _reduceAmountOfChains : function(fraction) {
  12764. this.hubThreshold = 2;
  12765. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  12766. for (var nodeId in this.nodes) {
  12767. if (this.nodes.hasOwnProperty(nodeId)) {
  12768. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12769. if (reduceAmount > 0) {
  12770. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  12771. reduceAmount -= 1;
  12772. }
  12773. }
  12774. }
  12775. }
  12776. },
  12777. /**
  12778. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12779. * with this amount we can cluster specifically on these chains.
  12780. *
  12781. * @private
  12782. */
  12783. _getChainFraction : function() {
  12784. var chains = 0;
  12785. var total = 0;
  12786. for (var nodeId in this.nodes) {
  12787. if (this.nodes.hasOwnProperty(nodeId)) {
  12788. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12789. chains += 1;
  12790. }
  12791. total += 1;
  12792. }
  12793. }
  12794. return chains/total;
  12795. }
  12796. };
  12797. var SelectionMixin = {
  12798. /**
  12799. * This function can be called from the _doInAllSectors function
  12800. *
  12801. * @param object
  12802. * @param overlappingNodes
  12803. * @private
  12804. */
  12805. _getNodesOverlappingWith : function(object, overlappingNodes) {
  12806. var nodes = this.nodes;
  12807. for (var nodeId in nodes) {
  12808. if (nodes.hasOwnProperty(nodeId)) {
  12809. if (nodes[nodeId].isOverlappingWith(object)) {
  12810. overlappingNodes.push(nodeId);
  12811. }
  12812. }
  12813. }
  12814. },
  12815. /**
  12816. * retrieve all nodes overlapping with given object
  12817. * @param {Object} object An object with parameters left, top, right, bottom
  12818. * @return {Number[]} An array with id's of the overlapping nodes
  12819. * @private
  12820. */
  12821. _getAllNodesOverlappingWith : function (object) {
  12822. var overlappingNodes = [];
  12823. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  12824. return overlappingNodes;
  12825. },
  12826. /**
  12827. * Return a position object in canvasspace from a single point in screenspace
  12828. *
  12829. * @param pointer
  12830. * @returns {{left: number, top: number, right: number, bottom: number}}
  12831. * @private
  12832. */
  12833. _pointerToPositionObject : function(pointer) {
  12834. var x = this._canvasToX(pointer.x);
  12835. var y = this._canvasToY(pointer.y);
  12836. return {left: x,
  12837. top: y,
  12838. right: x,
  12839. bottom: y};
  12840. },
  12841. /**
  12842. * Get the top node at the a specific point (like a click)
  12843. *
  12844. * @param {{x: Number, y: Number}} pointer
  12845. * @return {Node | null} node
  12846. * @private
  12847. */
  12848. _getNodeAt : function (pointer) {
  12849. // we first check if this is an navigation controls element
  12850. var positionObject = this._pointerToPositionObject(pointer);
  12851. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  12852. // if there are overlapping nodes, select the last one, this is the
  12853. // one which is drawn on top of the others
  12854. if (overlappingNodes.length > 0) {
  12855. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  12856. }
  12857. else {
  12858. return null;
  12859. }
  12860. },
  12861. /**
  12862. * retrieve all edges overlapping with given object, selector is around center
  12863. * @param {Object} object An object with parameters left, top, right, bottom
  12864. * @return {Number[]} An array with id's of the overlapping nodes
  12865. * @private
  12866. */
  12867. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  12868. var edges = this.edges;
  12869. for (var edgeId in edges) {
  12870. if (edges.hasOwnProperty(edgeId)) {
  12871. if (edges[edgeId].isOverlappingWith(object)) {
  12872. overlappingEdges.push(edgeId);
  12873. }
  12874. }
  12875. }
  12876. },
  12877. /**
  12878. * retrieve all nodes overlapping with given object
  12879. * @param {Object} object An object with parameters left, top, right, bottom
  12880. * @return {Number[]} An array with id's of the overlapping nodes
  12881. * @private
  12882. */
  12883. _getAllEdgesOverlappingWith : function (object) {
  12884. var overlappingEdges = [];
  12885. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  12886. return overlappingEdges;
  12887. },
  12888. /**
  12889. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  12890. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  12891. *
  12892. * @param pointer
  12893. * @returns {null}
  12894. * @private
  12895. */
  12896. _getEdgeAt : function(pointer) {
  12897. var positionObject = this._pointerToPositionObject(pointer);
  12898. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  12899. if (overlappingEdges.length > 0) {
  12900. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  12901. }
  12902. else {
  12903. return null;
  12904. }
  12905. },
  12906. /**
  12907. * Add object to the selection array.
  12908. *
  12909. * @param obj
  12910. * @private
  12911. */
  12912. _addToSelection : function(obj) {
  12913. if (obj instanceof Node) {
  12914. this.selectionObj.nodes[obj.id] = obj;
  12915. }
  12916. else {
  12917. this.selectionObj.edges[obj.id] = obj;
  12918. }
  12919. },
  12920. /**
  12921. * Remove a single option from selection.
  12922. *
  12923. * @param {Object} obj
  12924. * @private
  12925. */
  12926. _removeFromSelection : function(obj) {
  12927. if (obj instanceof Node) {
  12928. delete this.selectionObj.nodes[obj.id];
  12929. }
  12930. else {
  12931. delete this.selectionObj.edges[obj.id];
  12932. }
  12933. },
  12934. /**
  12935. * Unselect all. The selectionObj is useful for this.
  12936. *
  12937. * @param {Boolean} [doNotTrigger] | ignore trigger
  12938. * @private
  12939. */
  12940. _unselectAll : function(doNotTrigger) {
  12941. if (doNotTrigger === undefined) {
  12942. doNotTrigger = false;
  12943. }
  12944. for(var nodeId in this.selectionObj.nodes) {
  12945. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12946. this.selectionObj.nodes[nodeId].unselect();
  12947. }
  12948. }
  12949. for(var edgeId in this.selectionObj.edges) {
  12950. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  12951. this.selectionObj.edges[edgeId].unselect();;
  12952. }
  12953. }
  12954. this.selectionObj = {nodes:{},edges:{}};
  12955. if (doNotTrigger == false) {
  12956. this.emit('select', this.getSelection());
  12957. }
  12958. },
  12959. /**
  12960. * Unselect all clusters. The selectionObj is useful for this.
  12961. *
  12962. * @param {Boolean} [doNotTrigger] | ignore trigger
  12963. * @private
  12964. */
  12965. _unselectClusters : function(doNotTrigger) {
  12966. if (doNotTrigger === undefined) {
  12967. doNotTrigger = false;
  12968. }
  12969. for (var nodeId in this.selectionObj.nodes) {
  12970. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12971. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  12972. this.selectionObj.nodes[nodeId].unselect();
  12973. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  12974. }
  12975. }
  12976. }
  12977. if (doNotTrigger == false) {
  12978. this.emit('select', this.getSelection());
  12979. }
  12980. },
  12981. /**
  12982. * return the number of selected nodes
  12983. *
  12984. * @returns {number}
  12985. * @private
  12986. */
  12987. _getSelectedNodeCount : function() {
  12988. var count = 0;
  12989. for (var nodeId in this.selectionObj.nodes) {
  12990. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  12991. count += 1;
  12992. }
  12993. }
  12994. return count;
  12995. },
  12996. /**
  12997. * return the number of selected nodes
  12998. *
  12999. * @returns {number}
  13000. * @private
  13001. */
  13002. _getSelectedNode : function() {
  13003. for (var nodeId in this.selectionObj.nodes) {
  13004. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13005. return this.selectionObj.nodes[nodeId];
  13006. }
  13007. }
  13008. return null;
  13009. },
  13010. /**
  13011. * return the number of selected edges
  13012. *
  13013. * @returns {number}
  13014. * @private
  13015. */
  13016. _getSelectedEdgeCount : function() {
  13017. var count = 0;
  13018. for (var edgeId in this.selectionObj.edges) {
  13019. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13020. count += 1;
  13021. }
  13022. }
  13023. return count;
  13024. },
  13025. /**
  13026. * return the number of selected objects.
  13027. *
  13028. * @returns {number}
  13029. * @private
  13030. */
  13031. _getSelectedObjectCount : function() {
  13032. var count = 0;
  13033. for(var nodeId in this.selectionObj.nodes) {
  13034. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13035. count += 1;
  13036. }
  13037. }
  13038. for(var edgeId in this.selectionObj.edges) {
  13039. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13040. count += 1;
  13041. }
  13042. }
  13043. return count;
  13044. },
  13045. /**
  13046. * Check if anything is selected
  13047. *
  13048. * @returns {boolean}
  13049. * @private
  13050. */
  13051. _selectionIsEmpty : function() {
  13052. for(var nodeId in this.selectionObj.nodes) {
  13053. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13054. return false;
  13055. }
  13056. }
  13057. for(var edgeId in this.selectionObj.edges) {
  13058. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13059. return false;
  13060. }
  13061. }
  13062. return true;
  13063. },
  13064. /**
  13065. * check if one of the selected nodes is a cluster.
  13066. *
  13067. * @returns {boolean}
  13068. * @private
  13069. */
  13070. _clusterInSelection : function() {
  13071. for(var nodeId in this.selectionObj.nodes) {
  13072. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13073. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13074. return true;
  13075. }
  13076. }
  13077. }
  13078. return false;
  13079. },
  13080. /**
  13081. * select the edges connected to the node that is being selected
  13082. *
  13083. * @param {Node} node
  13084. * @private
  13085. */
  13086. _selectConnectedEdges : function(node) {
  13087. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13088. var edge = node.dynamicEdges[i];
  13089. edge.select();
  13090. this._addToSelection(edge);
  13091. }
  13092. },
  13093. /**
  13094. * unselect the edges connected to the node that is being selected
  13095. *
  13096. * @param {Node} node
  13097. * @private
  13098. */
  13099. _unselectConnectedEdges : function(node) {
  13100. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13101. var edge = node.dynamicEdges[i];
  13102. edge.unselect();
  13103. this._removeFromSelection(edge);
  13104. }
  13105. },
  13106. /**
  13107. * This is called when someone clicks on a node. either select or deselect it.
  13108. * If there is an existing selection and we don't want to append to it, clear the existing selection
  13109. *
  13110. * @param {Node || Edge} object
  13111. * @param {Boolean} append
  13112. * @param {Boolean} [doNotTrigger] | ignore trigger
  13113. * @private
  13114. */
  13115. _selectObject : function(object, append, doNotTrigger) {
  13116. if (doNotTrigger === undefined) {
  13117. doNotTrigger = false;
  13118. }
  13119. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  13120. this._unselectAll(true);
  13121. }
  13122. if (object.selected == false) {
  13123. object.select();
  13124. this._addToSelection(object);
  13125. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  13126. this._selectConnectedEdges(object);
  13127. }
  13128. }
  13129. else {
  13130. object.unselect();
  13131. this._removeFromSelection(object);
  13132. }
  13133. if (doNotTrigger == false) {
  13134. this.emit('select', this.getSelection());
  13135. }
  13136. },
  13137. /**
  13138. * handles the selection part of the touch, only for navigation controls elements;
  13139. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13140. * This is the most responsive solution
  13141. *
  13142. * @param {Object} pointer
  13143. * @private
  13144. */
  13145. _handleTouch : function(pointer) {
  13146. },
  13147. /**
  13148. * handles the selection part of the tap;
  13149. *
  13150. * @param {Object} pointer
  13151. * @private
  13152. */
  13153. _handleTap : function(pointer) {
  13154. var node = this._getNodeAt(pointer);
  13155. if (node != null) {
  13156. this._selectObject(node,false);
  13157. }
  13158. else {
  13159. var edge = this._getEdgeAt(pointer);
  13160. if (edge != null) {
  13161. this._selectObject(edge,false);
  13162. }
  13163. else {
  13164. this._unselectAll();
  13165. }
  13166. }
  13167. this.emit("click", this.getSelection());
  13168. this._redraw();
  13169. },
  13170. /**
  13171. * handles the selection part of the double tap and opens a cluster if needed
  13172. *
  13173. * @param {Object} pointer
  13174. * @private
  13175. */
  13176. _handleDoubleTap : function(pointer) {
  13177. var node = this._getNodeAt(pointer);
  13178. if (node != null && node !== undefined) {
  13179. // we reset the areaCenter here so the opening of the node will occur
  13180. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  13181. "y" : this._canvasToY(pointer.y)};
  13182. this.openCluster(node);
  13183. }
  13184. this.emit("doubleClick", this.getSelection());
  13185. },
  13186. /**
  13187. * Handle the onHold selection part
  13188. *
  13189. * @param pointer
  13190. * @private
  13191. */
  13192. _handleOnHold : function(pointer) {
  13193. var node = this._getNodeAt(pointer);
  13194. if (node != null) {
  13195. this._selectObject(node,true);
  13196. }
  13197. else {
  13198. var edge = this._getEdgeAt(pointer);
  13199. if (edge != null) {
  13200. this._selectObject(edge,true);
  13201. }
  13202. }
  13203. this._redraw();
  13204. },
  13205. /**
  13206. * handle the onRelease event. These functions are here for the navigation controls module.
  13207. *
  13208. * @private
  13209. */
  13210. _handleOnRelease : function(pointer) {
  13211. },
  13212. /**
  13213. *
  13214. * retrieve the currently selected objects
  13215. * @return {Number[] | String[]} selection An array with the ids of the
  13216. * selected nodes.
  13217. */
  13218. getSelection : function() {
  13219. var nodeIds = this.getSelectedNodes();
  13220. var edgeIds = this.getSelectedEdges();
  13221. return {nodes:nodeIds, edges:edgeIds};
  13222. },
  13223. /**
  13224. *
  13225. * retrieve the currently selected nodes
  13226. * @return {String} selection An array with the ids of the
  13227. * selected nodes.
  13228. */
  13229. getSelectedNodes : function() {
  13230. var idArray = [];
  13231. for(var nodeId in this.selectionObj.nodes) {
  13232. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13233. idArray.push(nodeId);
  13234. }
  13235. }
  13236. return idArray
  13237. },
  13238. /**
  13239. *
  13240. * retrieve the currently selected edges
  13241. * @return {Array} selection An array with the ids of the
  13242. * selected nodes.
  13243. */
  13244. getSelectedEdges : function() {
  13245. var idArray = [];
  13246. for(var edgeId in this.selectionObj.edges) {
  13247. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13248. idArray.push(edgeId);
  13249. }
  13250. }
  13251. return idArray;
  13252. },
  13253. /**
  13254. * select zero or more nodes
  13255. * @param {Number[] | String[]} selection An array with the ids of the
  13256. * selected nodes.
  13257. */
  13258. setSelection : function(selection) {
  13259. var i, iMax, id;
  13260. if (!selection || (selection.length == undefined))
  13261. throw 'Selection must be an array with ids';
  13262. // first unselect any selected node
  13263. this._unselectAll(true);
  13264. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13265. id = selection[i];
  13266. var node = this.nodes[id];
  13267. if (!node) {
  13268. throw new RangeError('Node with id "' + id + '" not found');
  13269. }
  13270. this._selectObject(node,true,true);
  13271. }
  13272. this.redraw();
  13273. },
  13274. /**
  13275. * Validate the selection: remove ids of nodes which no longer exist
  13276. * @private
  13277. */
  13278. _updateSelection : function () {
  13279. for(var nodeId in this.selectionObj.nodes) {
  13280. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13281. if (!this.nodes.hasOwnProperty(nodeId)) {
  13282. delete this.selectionObj.nodes[nodeId];
  13283. }
  13284. }
  13285. }
  13286. for(var edgeId in this.selectionObj.edges) {
  13287. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13288. if (!this.edges.hasOwnProperty(edgeId)) {
  13289. delete this.selectionObj.edges[edgeId];
  13290. }
  13291. }
  13292. }
  13293. }
  13294. };
  13295. /**
  13296. * Created by Alex on 1/22/14.
  13297. */
  13298. var NavigationMixin = {
  13299. _cleanNavigation : function() {
  13300. // clean up previosu navigation items
  13301. var wrapper = document.getElementById('graph-navigation_wrapper');
  13302. if (wrapper != null) {
  13303. this.containerElement.removeChild(wrapper);
  13304. }
  13305. document.onmouseup = null;
  13306. },
  13307. /**
  13308. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13309. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13310. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13311. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13312. *
  13313. * @private
  13314. */
  13315. _loadNavigationElements : function() {
  13316. this._cleanNavigation();
  13317. this.navigationDivs = {};
  13318. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13319. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  13320. this.navigationDivs['wrapper'] = document.createElement('div');
  13321. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13322. this.navigationDivs['wrapper'].style.position = "absolute";
  13323. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  13324. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  13325. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13326. for (var i = 0; i < navigationDivs.length; i++) {
  13327. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13328. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13329. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13330. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13331. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13332. }
  13333. document.onmouseup = this._stopMovement.bind(this);
  13334. },
  13335. /**
  13336. * this stops all movement induced by the navigation buttons
  13337. *
  13338. * @private
  13339. */
  13340. _stopMovement : function() {
  13341. this._xStopMoving();
  13342. this._yStopMoving();
  13343. this._stopZoom();
  13344. },
  13345. /**
  13346. * stops the actions performed by page up and down etc.
  13347. *
  13348. * @param event
  13349. * @private
  13350. */
  13351. _preventDefault : function(event) {
  13352. if (event !== undefined) {
  13353. if (event.preventDefault) {
  13354. event.preventDefault();
  13355. } else {
  13356. event.returnValue = false;
  13357. }
  13358. }
  13359. },
  13360. /**
  13361. * move the screen up
  13362. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13363. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13364. * To avoid this behaviour, we do the translation in the start loop.
  13365. *
  13366. * @private
  13367. */
  13368. _moveUp : function(event) {
  13369. this.yIncrement = this.constants.keyboard.speed.y;
  13370. this.start(); // if there is no node movement, the calculation wont be done
  13371. this._preventDefault(event);
  13372. if (this.navigationDivs) {
  13373. this.navigationDivs['up'].className += " active";
  13374. }
  13375. },
  13376. /**
  13377. * move the screen down
  13378. * @private
  13379. */
  13380. _moveDown : function(event) {
  13381. this.yIncrement = -this.constants.keyboard.speed.y;
  13382. this.start(); // if there is no node movement, the calculation wont be done
  13383. this._preventDefault(event);
  13384. if (this.navigationDivs) {
  13385. this.navigationDivs['down'].className += " active";
  13386. }
  13387. },
  13388. /**
  13389. * move the screen left
  13390. * @private
  13391. */
  13392. _moveLeft : function(event) {
  13393. this.xIncrement = this.constants.keyboard.speed.x;
  13394. this.start(); // if there is no node movement, the calculation wont be done
  13395. this._preventDefault(event);
  13396. if (this.navigationDivs) {
  13397. this.navigationDivs['left'].className += " active";
  13398. }
  13399. },
  13400. /**
  13401. * move the screen right
  13402. * @private
  13403. */
  13404. _moveRight : function(event) {
  13405. this.xIncrement = -this.constants.keyboard.speed.y;
  13406. this.start(); // if there is no node movement, the calculation wont be done
  13407. this._preventDefault(event);
  13408. if (this.navigationDivs) {
  13409. this.navigationDivs['right'].className += " active";
  13410. }
  13411. },
  13412. /**
  13413. * Zoom in, using the same method as the movement.
  13414. * @private
  13415. */
  13416. _zoomIn : function(event) {
  13417. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13418. this.start(); // if there is no node movement, the calculation wont be done
  13419. this._preventDefault(event);
  13420. if (this.navigationDivs) {
  13421. this.navigationDivs['zoomIn'].className += " active";
  13422. }
  13423. },
  13424. /**
  13425. * Zoom out
  13426. * @private
  13427. */
  13428. _zoomOut : function() {
  13429. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13430. this.start(); // if there is no node movement, the calculation wont be done
  13431. this._preventDefault(event);
  13432. if (this.navigationDivs) {
  13433. this.navigationDivs['zoomOut'].className += " active";
  13434. }
  13435. },
  13436. /**
  13437. * Stop zooming and unhighlight the zoom controls
  13438. * @private
  13439. */
  13440. _stopZoom : function() {
  13441. this.zoomIncrement = 0;
  13442. if (this.navigationDivs) {
  13443. this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active","");
  13444. this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active","");
  13445. }
  13446. },
  13447. /**
  13448. * Stop moving in the Y direction and unHighlight the up and down
  13449. * @private
  13450. */
  13451. _yStopMoving : function() {
  13452. this.yIncrement = 0;
  13453. if (this.navigationDivs) {
  13454. this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active","");
  13455. this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active","");
  13456. }
  13457. },
  13458. /**
  13459. * Stop moving in the X direction and unHighlight left and right.
  13460. * @private
  13461. */
  13462. _xStopMoving : function() {
  13463. this.xIncrement = 0;
  13464. if (this.navigationDivs) {
  13465. this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active","");
  13466. this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active","");
  13467. }
  13468. }
  13469. };
  13470. /**
  13471. * Created by Alex on 2/10/14.
  13472. */
  13473. var graphMixinLoaders = {
  13474. /**
  13475. * Load a mixin into the graph object
  13476. *
  13477. * @param {Object} sourceVariable | this object has to contain functions.
  13478. * @private
  13479. */
  13480. _loadMixin : function(sourceVariable) {
  13481. for (var mixinFunction in sourceVariable) {
  13482. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13483. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13484. }
  13485. }
  13486. },
  13487. /**
  13488. * removes a mixin from the graph object.
  13489. *
  13490. * @param {Object} sourceVariable | this object has to contain functions.
  13491. * @private
  13492. */
  13493. _clearMixin : function(sourceVariable) {
  13494. for (var mixinFunction in sourceVariable) {
  13495. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13496. Graph.prototype[mixinFunction] = undefined;
  13497. }
  13498. }
  13499. },
  13500. /**
  13501. * Mixin the physics system and initialize the parameters required.
  13502. *
  13503. * @private
  13504. */
  13505. _loadPhysicsSystem : function() {
  13506. this._loadMixin(physicsMixin);
  13507. this._loadSelectedForceSolver();
  13508. if (this.constants.configurePhysics == true) {
  13509. this._loadPhysicsConfiguration();
  13510. }
  13511. },
  13512. /**
  13513. * Mixin the cluster system and initialize the parameters required.
  13514. *
  13515. * @private
  13516. */
  13517. _loadClusterSystem : function() {
  13518. this.clusterSession = 0;
  13519. this.hubThreshold = 5;
  13520. this._loadMixin(ClusterMixin);
  13521. },
  13522. /**
  13523. * Mixin the sector system and initialize the parameters required
  13524. *
  13525. * @private
  13526. */
  13527. _loadSectorSystem : function() {
  13528. this.sectors = { },
  13529. this.activeSector = ["default"];
  13530. this.sectors["active"] = { },
  13531. this.sectors["active"]["default"] = {"nodes":{},
  13532. "edges":{},
  13533. "nodeIndices":[],
  13534. "formationScale": 1.0,
  13535. "drawingNode": undefined };
  13536. this.sectors["frozen"] = {},
  13537. this.sectors["support"] = {"nodes":{},
  13538. "edges":{},
  13539. "nodeIndices":[],
  13540. "formationScale": 1.0,
  13541. "drawingNode": undefined };
  13542. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13543. this._loadMixin(SectorMixin);
  13544. },
  13545. /**
  13546. * Mixin the selection system and initialize the parameters required
  13547. *
  13548. * @private
  13549. */
  13550. _loadSelectionSystem : function() {
  13551. this.selectionObj = {nodes:{},edges:{}};
  13552. this._loadMixin(SelectionMixin);
  13553. },
  13554. /**
  13555. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13556. *
  13557. * @private
  13558. */
  13559. _loadManipulationSystem : function() {
  13560. // reset global variables -- these are used by the selection of nodes and edges.
  13561. this.blockConnectingEdgeSelection = false;
  13562. this.forceAppendSelection = false
  13563. if (this.constants.dataManipulation.enabled == true) {
  13564. // load the manipulator HTML elements. All styling done in css.
  13565. if (this.manipulationDiv === undefined) {
  13566. this.manipulationDiv = document.createElement('div');
  13567. this.manipulationDiv.className = 'graph-manipulationDiv';
  13568. this.manipulationDiv.id = 'graph-manipulationDiv';
  13569. if (this.editMode == true) {
  13570. this.manipulationDiv.style.display = "block";
  13571. }
  13572. else {
  13573. this.manipulationDiv.style.display = "none";
  13574. }
  13575. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13576. }
  13577. if (this.editModeDiv === undefined) {
  13578. this.editModeDiv = document.createElement('div');
  13579. this.editModeDiv.className = 'graph-manipulation-editMode';
  13580. this.editModeDiv.id = 'graph-manipulation-editMode';
  13581. if (this.editMode == true) {
  13582. this.editModeDiv.style.display = "none";
  13583. }
  13584. else {
  13585. this.editModeDiv.style.display = "block";
  13586. }
  13587. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13588. }
  13589. if (this.closeDiv === undefined) {
  13590. this.closeDiv = document.createElement('div');
  13591. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13592. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13593. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13594. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13595. }
  13596. // load the manipulation functions
  13597. this._loadMixin(manipulationMixin);
  13598. // create the manipulator toolbar
  13599. this._createManipulatorBar();
  13600. }
  13601. else {
  13602. if (this.manipulationDiv !== undefined) {
  13603. // removes all the bindings and overloads
  13604. this._createManipulatorBar();
  13605. // remove the manipulation divs
  13606. this.containerElement.removeChild(this.manipulationDiv);
  13607. this.containerElement.removeChild(this.editModeDiv);
  13608. this.containerElement.removeChild(this.closeDiv);
  13609. this.manipulationDiv = undefined;
  13610. this.editModeDiv = undefined;
  13611. this.closeDiv = undefined;
  13612. // remove the mixin functions
  13613. this._clearMixin(manipulationMixin);
  13614. }
  13615. }
  13616. },
  13617. /**
  13618. * Mixin the navigation (User Interface) system and initialize the parameters required
  13619. *
  13620. * @private
  13621. */
  13622. _loadNavigationControls : function() {
  13623. this._loadMixin(NavigationMixin);
  13624. // the clean function removes the button divs, this is done to remove the bindings.
  13625. this._cleanNavigation();
  13626. if (this.constants.navigation.enabled == true) {
  13627. this._loadNavigationElements();
  13628. }
  13629. },
  13630. /**
  13631. * Mixin the hierarchical layout system.
  13632. *
  13633. * @private
  13634. */
  13635. _loadHierarchySystem : function() {
  13636. this._loadMixin(HierarchicalLayoutMixin);
  13637. }
  13638. }
  13639. /**
  13640. * @constructor Graph
  13641. * Create a graph visualization, displaying nodes and edges.
  13642. *
  13643. * @param {Element} container The DOM element in which the Graph will
  13644. * be created. Normally a div element.
  13645. * @param {Object} data An object containing parameters
  13646. * {Array} nodes
  13647. * {Array} edges
  13648. * @param {Object} options Options
  13649. */
  13650. function Graph (container, data, options) {
  13651. this._initializeMixinLoaders();
  13652. // create variables and set default values
  13653. this.containerElement = container;
  13654. this.width = '100%';
  13655. this.height = '100%';
  13656. // render and calculation settings
  13657. this.renderRefreshRate = 60; // hz (fps)
  13658. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  13659. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  13660. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  13661. this.physicsDiscreteStepsize = 0.65; // discrete stepsize of the simulation
  13662. this.stabilize = true; // stabilize before displaying the graph
  13663. this.selectable = true;
  13664. // these functions are triggered when the dataset is edited
  13665. this.triggerFunctions = {add:null,edit:null,connect:null,delete:null};
  13666. // set constant values
  13667. this.constants = {
  13668. nodes: {
  13669. radiusMin: 5,
  13670. radiusMax: 20,
  13671. radius: 5,
  13672. shape: 'ellipse',
  13673. image: undefined,
  13674. widthMin: 16, // px
  13675. widthMax: 64, // px
  13676. fixed: false,
  13677. fontColor: 'black',
  13678. fontSize: 14, // px
  13679. fontFace: 'verdana',
  13680. level: -1,
  13681. color: {
  13682. border: '#2B7CE9',
  13683. background: '#97C2FC',
  13684. highlight: {
  13685. border: '#2B7CE9',
  13686. background: '#D2E5FF'
  13687. }
  13688. },
  13689. borderColor: '#2B7CE9',
  13690. backgroundColor: '#97C2FC',
  13691. highlightColor: '#D2E5FF',
  13692. group: undefined
  13693. },
  13694. edges: {
  13695. widthMin: 1,
  13696. widthMax: 15,
  13697. width: 1,
  13698. style: 'line',
  13699. color: {
  13700. color:'#848484',
  13701. highlight:'#848484'
  13702. },
  13703. fontColor: '#343434',
  13704. fontSize: 14, // px
  13705. fontFace: 'arial',
  13706. dash: {
  13707. length: 10,
  13708. gap: 5,
  13709. altLength: undefined
  13710. }
  13711. },
  13712. configurePhysics:false,
  13713. physics: {
  13714. barnesHut: {
  13715. enabled: true,
  13716. theta: 1 / 0.6, // inverted to save time during calculation
  13717. gravitationalConstant: -2000,
  13718. centralGravity: 0.3,
  13719. springLength: 95,
  13720. springConstant: 0.04,
  13721. damping: 0.09
  13722. },
  13723. repulsion: {
  13724. centralGravity: 0.1,
  13725. springLength: 200,
  13726. springConstant: 0.05,
  13727. nodeDistance: 100,
  13728. damping: 0.09
  13729. },
  13730. hierarchicalRepulsion: {
  13731. enabled: false,
  13732. centralGravity: 0.0,
  13733. springLength: 100,
  13734. springConstant: 0.01,
  13735. nodeDistance: 60,
  13736. damping: 0.09
  13737. },
  13738. damping: null,
  13739. centralGravity: null,
  13740. springLength: null,
  13741. springConstant: null
  13742. },
  13743. clustering: { // Per Node in Cluster = PNiC
  13744. enabled: false, // (Boolean) | global on/off switch for clustering.
  13745. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  13746. 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
  13747. 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
  13748. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  13749. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  13750. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  13751. 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.
  13752. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  13753. maxFontSize: 1000,
  13754. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  13755. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  13756. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  13757. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  13758. height: 1, // (px PNiC) | growth of the height per node in cluster.
  13759. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  13760. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  13761. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  13762. clusterLevelDifference: 2
  13763. },
  13764. navigation: {
  13765. enabled: false
  13766. },
  13767. keyboard: {
  13768. enabled: false,
  13769. speed: {x: 10, y: 10, zoom: 0.02}
  13770. },
  13771. dataManipulation: {
  13772. enabled: false,
  13773. initiallyVisible: false
  13774. },
  13775. hierarchicalLayout: {
  13776. enabled:false,
  13777. levelSeparation: 150,
  13778. nodeSpacing: 100,
  13779. direction: "UD" // UD, DU, LR, RL
  13780. },
  13781. freezeForStabilization: false,
  13782. smoothCurves: true,
  13783. maxVelocity: 10,
  13784. minVelocity: 0.1, // px/s
  13785. stabilizationIterations: 1000 // maximum number of iteration to stabilize
  13786. };
  13787. this.editMode = this.constants.dataManipulation.initiallyVisible;
  13788. // Node variables
  13789. var graph = this;
  13790. this.groups = new Groups(); // object with groups
  13791. this.images = new Images(); // object with images
  13792. this.images.setOnloadCallback(function () {
  13793. graph._redraw();
  13794. });
  13795. // keyboard navigation variables
  13796. this.xIncrement = 0;
  13797. this.yIncrement = 0;
  13798. this.zoomIncrement = 0;
  13799. // loading all the mixins:
  13800. // load the force calculation functions, grouped under the physics system.
  13801. this._loadPhysicsSystem();
  13802. // create a frame and canvas
  13803. this._create();
  13804. // load the sector system. (mandatory, fully integrated with Graph)
  13805. this._loadSectorSystem();
  13806. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  13807. this._loadClusterSystem();
  13808. // load the selection system. (mandatory, required by Graph)
  13809. this._loadSelectionSystem();
  13810. // load the selection system. (mandatory, required by Graph)
  13811. this._loadHierarchySystem();
  13812. // apply options
  13813. this.setOptions(options);
  13814. // other vars
  13815. this.freezeSimulation = false;// freeze the simulation
  13816. this.cachedFunctions = {};
  13817. // containers for nodes and edges
  13818. this.calculationNodes = {};
  13819. this.calculationNodeIndices = [];
  13820. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  13821. this.nodes = {}; // object with Node objects
  13822. this.edges = {}; // object with Edge objects
  13823. // position and scale variables and objects
  13824. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  13825. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13826. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13827. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  13828. this.scale = 1; // defining the global scale variable in the constructor
  13829. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  13830. // datasets or dataviews
  13831. this.nodesData = null; // A DataSet or DataView
  13832. this.edgesData = null; // A DataSet or DataView
  13833. // create event listeners used to subscribe on the DataSets of the nodes and edges
  13834. this.nodesListeners = {
  13835. 'add': function (event, params) {
  13836. graph._addNodes(params.items);
  13837. graph.start();
  13838. },
  13839. 'update': function (event, params) {
  13840. graph._updateNodes(params.items);
  13841. graph.start();
  13842. },
  13843. 'remove': function (event, params) {
  13844. graph._removeNodes(params.items);
  13845. graph.start();
  13846. }
  13847. };
  13848. this.edgesListeners = {
  13849. 'add': function (event, params) {
  13850. graph._addEdges(params.items);
  13851. graph.start();
  13852. },
  13853. 'update': function (event, params) {
  13854. graph._updateEdges(params.items);
  13855. graph.start();
  13856. },
  13857. 'remove': function (event, params) {
  13858. graph._removeEdges(params.items);
  13859. graph.start();
  13860. }
  13861. };
  13862. // properties for the animation
  13863. this.moving = true;
  13864. this.timer = undefined; // Scheduling function. Is definded in this.start();
  13865. // load data (the disable start variable will be the same as the enabled clustering)
  13866. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  13867. // hierarchical layout
  13868. if (this.constants.hierarchicalLayout.enabled == true) {
  13869. this._setupHierarchicalLayout();
  13870. }
  13871. else {
  13872. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  13873. if (this.stabilize == false) {
  13874. this.zoomExtent(true,this.constants.clustering.enabled);
  13875. }
  13876. }
  13877. // if clustering is disabled, the simulation will have started in the setData function
  13878. if (this.constants.clustering.enabled) {
  13879. this.startWithClustering();
  13880. }
  13881. }
  13882. // Extend Graph with an Emitter mixin
  13883. Emitter(Graph.prototype);
  13884. /**
  13885. * Get the script path where the vis.js library is located
  13886. *
  13887. * @returns {string | null} path Path or null when not found. Path does not
  13888. * end with a slash.
  13889. * @private
  13890. */
  13891. Graph.prototype._getScriptPath = function() {
  13892. var scripts = document.getElementsByTagName( 'script' );
  13893. // find script named vis.js or vis.min.js
  13894. for (var i = 0; i < scripts.length; i++) {
  13895. var src = scripts[i].src;
  13896. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  13897. if (match) {
  13898. // return path without the script name
  13899. return src.substring(0, src.length - match[0].length);
  13900. }
  13901. }
  13902. return null;
  13903. };
  13904. /**
  13905. * Find the center position of the graph
  13906. * @private
  13907. */
  13908. Graph.prototype._getRange = function() {
  13909. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  13910. for (var nodeId in this.nodes) {
  13911. if (this.nodes.hasOwnProperty(nodeId)) {
  13912. node = this.nodes[nodeId];
  13913. if (minX > (node.x)) {minX = node.x;}
  13914. if (maxX < (node.x)) {maxX = node.x;}
  13915. if (minY > (node.y)) {minY = node.y;}
  13916. if (maxY < (node.y)) {maxY = node.y;}
  13917. }
  13918. }
  13919. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  13920. minY = 0, maxY = 0, minX = 0, maxX = 0;
  13921. }
  13922. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13923. };
  13924. /**
  13925. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13926. * @returns {{x: number, y: number}}
  13927. * @private
  13928. */
  13929. Graph.prototype._findCenter = function(range) {
  13930. return {x: (0.5 * (range.maxX + range.minX)),
  13931. y: (0.5 * (range.maxY + range.minY))};
  13932. };
  13933. /**
  13934. * center the graph
  13935. *
  13936. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13937. */
  13938. Graph.prototype._centerGraph = function(range) {
  13939. var center = this._findCenter(range);
  13940. center.x *= this.scale;
  13941. center.y *= this.scale;
  13942. center.x -= 0.5 * this.frame.canvas.clientWidth;
  13943. center.y -= 0.5 * this.frame.canvas.clientHeight;
  13944. this._setTranslation(-center.x,-center.y); // set at 0,0
  13945. };
  13946. /**
  13947. * This function zooms out to fit all data on screen based on amount of nodes
  13948. *
  13949. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  13950. */
  13951. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  13952. if (initialZoom === undefined) {
  13953. initialZoom = false;
  13954. }
  13955. if (disableStart === undefined) {
  13956. disableStart = false;
  13957. }
  13958. var range = this._getRange();
  13959. var zoomLevel;
  13960. if (initialZoom == true) {
  13961. var numberOfNodes = this.nodeIndices.length;
  13962. if (this.constants.smoothCurves == true) {
  13963. if (this.constants.clustering.enabled == true &&
  13964. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  13965. 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.
  13966. }
  13967. else {
  13968. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13969. }
  13970. }
  13971. else {
  13972. if (this.constants.clustering.enabled == true &&
  13973. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  13974. 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.
  13975. }
  13976. else {
  13977. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  13978. }
  13979. }
  13980. // correct for larger canvasses.
  13981. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  13982. zoomLevel *= factor;
  13983. }
  13984. else {
  13985. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  13986. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  13987. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  13988. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  13989. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  13990. }
  13991. if (zoomLevel > 1.0) {
  13992. zoomLevel = 1.0;
  13993. }
  13994. this._setScale(zoomLevel);
  13995. this._centerGraph(range);
  13996. if (disableStart == false) {
  13997. this.moving = true;
  13998. this.start();
  13999. }
  14000. };
  14001. /**
  14002. * Update the this.nodeIndices with the most recent node index list
  14003. * @private
  14004. */
  14005. Graph.prototype._updateNodeIndexList = function() {
  14006. this._clearNodeIndexList();
  14007. for (var idx in this.nodes) {
  14008. if (this.nodes.hasOwnProperty(idx)) {
  14009. this.nodeIndices.push(idx);
  14010. }
  14011. }
  14012. };
  14013. /**
  14014. * Set nodes and edges, and optionally options as well.
  14015. *
  14016. * @param {Object} data Object containing parameters:
  14017. * {Array | DataSet | DataView} [nodes] Array with nodes
  14018. * {Array | DataSet | DataView} [edges] Array with edges
  14019. * {String} [dot] String containing data in DOT format
  14020. * {Options} [options] Object with options
  14021. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  14022. */
  14023. Graph.prototype.setData = function(data, disableStart) {
  14024. if (disableStart === undefined) {
  14025. disableStart = false;
  14026. }
  14027. if (data && data.dot && (data.nodes || data.edges)) {
  14028. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  14029. ' parameter pair "nodes" and "edges", but not both.');
  14030. }
  14031. // set options
  14032. this.setOptions(data && data.options);
  14033. // set all data
  14034. if (data && data.dot) {
  14035. // parse DOT file
  14036. if(data && data.dot) {
  14037. var dotData = vis.util.DOTToGraph(data.dot);
  14038. this.setData(dotData);
  14039. return;
  14040. }
  14041. }
  14042. else {
  14043. this._setNodes(data && data.nodes);
  14044. this._setEdges(data && data.edges);
  14045. }
  14046. this._putDataInSector();
  14047. if (!disableStart) {
  14048. // find a stable position or start animating to a stable position
  14049. if (this.stabilize) {
  14050. this._stabilize();
  14051. }
  14052. this.start();
  14053. }
  14054. };
  14055. /**
  14056. * Set options
  14057. * @param {Object} options
  14058. */
  14059. Graph.prototype.setOptions = function (options) {
  14060. if (options) {
  14061. var prop;
  14062. // retrieve parameter values
  14063. if (options.width !== undefined) {this.width = options.width;}
  14064. if (options.height !== undefined) {this.height = options.height;}
  14065. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14066. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14067. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14068. if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;}
  14069. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14070. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  14071. if (options.onAdd) {
  14072. this.triggerFunctions.add = options.onAdd;
  14073. }
  14074. if (options.onEdit) {
  14075. this.triggerFunctions.edit = options.onEdit;
  14076. }
  14077. if (options.onConnect) {
  14078. this.triggerFunctions.connect = options.onConnect;
  14079. }
  14080. if (options.onDelete) {
  14081. this.triggerFunctions.delete = options.onDelete;
  14082. }
  14083. if (options.physics) {
  14084. if (options.physics.barnesHut) {
  14085. this.constants.physics.barnesHut.enabled = true;
  14086. for (prop in options.physics.barnesHut) {
  14087. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14088. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14089. }
  14090. }
  14091. }
  14092. if (options.physics.repulsion) {
  14093. this.constants.physics.barnesHut.enabled = false;
  14094. for (prop in options.physics.repulsion) {
  14095. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14096. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14097. }
  14098. }
  14099. }
  14100. }
  14101. if (options.hierarchicalLayout) {
  14102. this.constants.hierarchicalLayout.enabled = true;
  14103. for (prop in options.hierarchicalLayout) {
  14104. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14105. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14106. }
  14107. }
  14108. }
  14109. else if (options.hierarchicalLayout !== undefined) {
  14110. this.constants.hierarchicalLayout.enabled = false;
  14111. }
  14112. if (options.clustering) {
  14113. this.constants.clustering.enabled = true;
  14114. for (prop in options.clustering) {
  14115. if (options.clustering.hasOwnProperty(prop)) {
  14116. this.constants.clustering[prop] = options.clustering[prop];
  14117. }
  14118. }
  14119. }
  14120. else if (options.clustering !== undefined) {
  14121. this.constants.clustering.enabled = false;
  14122. }
  14123. if (options.navigation) {
  14124. this.constants.navigation.enabled = true;
  14125. for (prop in options.navigation) {
  14126. if (options.navigation.hasOwnProperty(prop)) {
  14127. this.constants.navigation[prop] = options.navigation[prop];
  14128. }
  14129. }
  14130. }
  14131. else if (options.navigation !== undefined) {
  14132. this.constants.navigation.enabled = false;
  14133. }
  14134. if (options.keyboard) {
  14135. this.constants.keyboard.enabled = true;
  14136. for (prop in options.keyboard) {
  14137. if (options.keyboard.hasOwnProperty(prop)) {
  14138. this.constants.keyboard[prop] = options.keyboard[prop];
  14139. }
  14140. }
  14141. }
  14142. else if (options.keyboard !== undefined) {
  14143. this.constants.keyboard.enabled = false;
  14144. }
  14145. if (options.dataManipulation) {
  14146. this.constants.dataManipulation.enabled = true;
  14147. for (prop in options.dataManipulation) {
  14148. if (options.dataManipulation.hasOwnProperty(prop)) {
  14149. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14150. }
  14151. }
  14152. }
  14153. else if (options.dataManipulation !== undefined) {
  14154. this.constants.dataManipulation.enabled = false;
  14155. }
  14156. // TODO: work out these options and document them
  14157. if (options.edges) {
  14158. for (prop in options.edges) {
  14159. if (options.edges.hasOwnProperty(prop)) {
  14160. if (typeof options.edges[prop] != "object") {
  14161. this.constants.edges[prop] = options.edges[prop];
  14162. }
  14163. }
  14164. }
  14165. if (options.edges.color !== undefined) {
  14166. if (util.isString(options.edges.color)) {
  14167. this.constants.edges.color.color = options.edges.color;
  14168. this.constants.edges.color.highlight = options.edges.color;
  14169. }
  14170. else {
  14171. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  14172. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  14173. }
  14174. }
  14175. if (!options.edges.fontColor) {
  14176. if (options.edges.color !== undefined) {
  14177. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  14178. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  14179. }
  14180. }
  14181. // Added to support dashed lines
  14182. // David Jordan
  14183. // 2012-08-08
  14184. if (options.edges.dash) {
  14185. if (options.edges.dash.length !== undefined) {
  14186. this.constants.edges.dash.length = options.edges.dash.length;
  14187. }
  14188. if (options.edges.dash.gap !== undefined) {
  14189. this.constants.edges.dash.gap = options.edges.dash.gap;
  14190. }
  14191. if (options.edges.dash.altLength !== undefined) {
  14192. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14193. }
  14194. }
  14195. }
  14196. if (options.nodes) {
  14197. for (prop in options.nodes) {
  14198. if (options.nodes.hasOwnProperty(prop)) {
  14199. this.constants.nodes[prop] = options.nodes[prop];
  14200. }
  14201. }
  14202. if (options.nodes.color) {
  14203. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  14204. }
  14205. /*
  14206. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14207. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14208. */
  14209. }
  14210. if (options.groups) {
  14211. for (var groupname in options.groups) {
  14212. if (options.groups.hasOwnProperty(groupname)) {
  14213. var group = options.groups[groupname];
  14214. this.groups.add(groupname, group);
  14215. }
  14216. }
  14217. }
  14218. }
  14219. // (Re)loading the mixins that can be enabled or disabled in the options.
  14220. // load the force calculation functions, grouped under the physics system.
  14221. this._loadPhysicsSystem();
  14222. // load the navigation system.
  14223. this._loadNavigationControls();
  14224. // load the data manipulation system
  14225. this._loadManipulationSystem();
  14226. // configure the smooth curves
  14227. this._configureSmoothCurves();
  14228. // bind keys. If disabled, this will not do anything;
  14229. this._createKeyBinds();
  14230. this.setSize(this.width, this.height);
  14231. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14232. this._setScale(1);
  14233. this._redraw();
  14234. };
  14235. /**
  14236. * Create the main frame for the Graph.
  14237. * This function is executed once when a Graph object is created. The frame
  14238. * contains a canvas, and this canvas contains all objects like the axis and
  14239. * nodes.
  14240. * @private
  14241. */
  14242. Graph.prototype._create = function () {
  14243. // remove all elements from the container element.
  14244. while (this.containerElement.hasChildNodes()) {
  14245. this.containerElement.removeChild(this.containerElement.firstChild);
  14246. }
  14247. this.frame = document.createElement('div');
  14248. this.frame.className = 'graph-frame';
  14249. this.frame.style.position = 'relative';
  14250. this.frame.style.overflow = 'hidden';
  14251. this.frame.style.zIndex = "1";
  14252. // create the graph canvas (HTML canvas element)
  14253. this.frame.canvas = document.createElement( 'canvas' );
  14254. this.frame.canvas.style.position = 'relative';
  14255. this.frame.appendChild(this.frame.canvas);
  14256. if (!this.frame.canvas.getContext) {
  14257. var noCanvas = document.createElement( 'DIV' );
  14258. noCanvas.style.color = 'red';
  14259. noCanvas.style.fontWeight = 'bold' ;
  14260. noCanvas.style.padding = '10px';
  14261. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14262. this.frame.canvas.appendChild(noCanvas);
  14263. }
  14264. var me = this;
  14265. this.drag = {};
  14266. this.pinch = {};
  14267. this.hammer = Hammer(this.frame.canvas, {
  14268. prevent_default: true
  14269. });
  14270. this.hammer.on('tap', me._onTap.bind(me) );
  14271. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14272. this.hammer.on('hold', me._onHold.bind(me) );
  14273. this.hammer.on('pinch', me._onPinch.bind(me) );
  14274. this.hammer.on('touch', me._onTouch.bind(me) );
  14275. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14276. this.hammer.on('drag', me._onDrag.bind(me) );
  14277. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14278. this.hammer.on('release', me._onRelease.bind(me) );
  14279. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14280. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14281. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14282. // add the frame to the container element
  14283. this.containerElement.appendChild(this.frame);
  14284. };
  14285. /**
  14286. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14287. * @private
  14288. */
  14289. Graph.prototype._createKeyBinds = function() {
  14290. var me = this;
  14291. this.mousetrap = mousetrap;
  14292. this.mousetrap.reset();
  14293. if (this.constants.keyboard.enabled == true) {
  14294. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14295. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14296. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14297. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14298. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14299. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14300. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14301. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14302. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14303. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14304. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14305. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14306. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14307. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14308. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14309. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14310. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14311. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14312. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14313. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14314. }
  14315. if (this.constants.dataManipulation.enabled == true) {
  14316. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14317. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14318. }
  14319. };
  14320. /**
  14321. * Get the pointer location from a touch location
  14322. * @param {{pageX: Number, pageY: Number}} touch
  14323. * @return {{x: Number, y: Number}} pointer
  14324. * @private
  14325. */
  14326. Graph.prototype._getPointer = function (touch) {
  14327. return {
  14328. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14329. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14330. };
  14331. };
  14332. /**
  14333. * On start of a touch gesture, store the pointer
  14334. * @param event
  14335. * @private
  14336. */
  14337. Graph.prototype._onTouch = function (event) {
  14338. this.drag.pointer = this._getPointer(event.gesture.center);
  14339. this.drag.pinched = false;
  14340. this.pinch.scale = this._getScale();
  14341. this._handleTouch(this.drag.pointer);
  14342. };
  14343. /**
  14344. * handle drag start event
  14345. * @private
  14346. */
  14347. Graph.prototype._onDragStart = function () {
  14348. this._handleDragStart();
  14349. };
  14350. /**
  14351. * This function is called by _onDragStart.
  14352. * It is separated out because we can then overload it for the datamanipulation system.
  14353. *
  14354. * @private
  14355. */
  14356. Graph.prototype._handleDragStart = function() {
  14357. var drag = this.drag;
  14358. var node = this._getNodeAt(drag.pointer);
  14359. // note: drag.pointer is set in _onTouch to get the initial touch location
  14360. drag.dragging = true;
  14361. drag.selection = [];
  14362. drag.translation = this._getTranslation();
  14363. drag.nodeId = null;
  14364. if (node != null) {
  14365. drag.nodeId = node.id;
  14366. // select the clicked node if not yet selected
  14367. if (!node.isSelected()) {
  14368. this._selectObject(node,false);
  14369. }
  14370. // create an array with the selected nodes and their original location and status
  14371. for (var objectId in this.selectionObj.nodes) {
  14372. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  14373. var object = this.selectionObj.nodes[objectId];
  14374. var s = {
  14375. id: object.id,
  14376. node: object,
  14377. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14378. x: object.x,
  14379. y: object.y,
  14380. xFixed: object.xFixed,
  14381. yFixed: object.yFixed
  14382. };
  14383. object.xFixed = true;
  14384. object.yFixed = true;
  14385. drag.selection.push(s);
  14386. }
  14387. }
  14388. }
  14389. };
  14390. /**
  14391. * handle drag event
  14392. * @private
  14393. */
  14394. Graph.prototype._onDrag = function (event) {
  14395. this._handleOnDrag(event)
  14396. };
  14397. /**
  14398. * This function is called by _onDrag.
  14399. * It is separated out because we can then overload it for the datamanipulation system.
  14400. *
  14401. * @private
  14402. */
  14403. Graph.prototype._handleOnDrag = function(event) {
  14404. if (this.drag.pinched) {
  14405. return;
  14406. }
  14407. var pointer = this._getPointer(event.gesture.center);
  14408. var me = this,
  14409. drag = this.drag,
  14410. selection = drag.selection;
  14411. if (selection && selection.length) {
  14412. // calculate delta's and new location
  14413. var deltaX = pointer.x - drag.pointer.x,
  14414. deltaY = pointer.y - drag.pointer.y;
  14415. // update position of all selected nodes
  14416. selection.forEach(function (s) {
  14417. var node = s.node;
  14418. if (!s.xFixed) {
  14419. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14420. }
  14421. if (!s.yFixed) {
  14422. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14423. }
  14424. });
  14425. // start _animationStep if not yet running
  14426. if (!this.moving) {
  14427. this.moving = true;
  14428. this.start();
  14429. }
  14430. }
  14431. else {
  14432. // move the graph
  14433. var diffX = pointer.x - this.drag.pointer.x;
  14434. var diffY = pointer.y - this.drag.pointer.y;
  14435. this._setTranslation(
  14436. this.drag.translation.x + diffX,
  14437. this.drag.translation.y + diffY);
  14438. this._redraw();
  14439. this.moved = true;
  14440. }
  14441. };
  14442. /**
  14443. * handle drag start event
  14444. * @private
  14445. */
  14446. Graph.prototype._onDragEnd = function () {
  14447. this.drag.dragging = false;
  14448. var selection = this.drag.selection;
  14449. if (selection) {
  14450. selection.forEach(function (s) {
  14451. // restore original xFixed and yFixed
  14452. s.node.xFixed = s.xFixed;
  14453. s.node.yFixed = s.yFixed;
  14454. });
  14455. }
  14456. };
  14457. /**
  14458. * handle tap/click event: select/unselect a node
  14459. * @private
  14460. */
  14461. Graph.prototype._onTap = function (event) {
  14462. var pointer = this._getPointer(event.gesture.center);
  14463. this.pointerPosition = pointer;
  14464. this._handleTap(pointer);
  14465. };
  14466. /**
  14467. * handle doubletap event
  14468. * @private
  14469. */
  14470. Graph.prototype._onDoubleTap = function (event) {
  14471. var pointer = this._getPointer(event.gesture.center);
  14472. this._handleDoubleTap(pointer);
  14473. };
  14474. /**
  14475. * handle long tap event: multi select nodes
  14476. * @private
  14477. */
  14478. Graph.prototype._onHold = function (event) {
  14479. var pointer = this._getPointer(event.gesture.center);
  14480. this.pointerPosition = pointer;
  14481. this._handleOnHold(pointer);
  14482. };
  14483. /**
  14484. * handle the release of the screen
  14485. *
  14486. * @private
  14487. */
  14488. Graph.prototype._onRelease = function (event) {
  14489. var pointer = this._getPointer(event.gesture.center);
  14490. this._handleOnRelease(pointer);
  14491. };
  14492. /**
  14493. * Handle pinch event
  14494. * @param event
  14495. * @private
  14496. */
  14497. Graph.prototype._onPinch = function (event) {
  14498. var pointer = this._getPointer(event.gesture.center);
  14499. this.drag.pinched = true;
  14500. if (!('scale' in this.pinch)) {
  14501. this.pinch.scale = 1;
  14502. }
  14503. // TODO: enabled moving while pinching?
  14504. var scale = this.pinch.scale * event.gesture.scale;
  14505. this._zoom(scale, pointer)
  14506. };
  14507. /**
  14508. * Zoom the graph in or out
  14509. * @param {Number} scale a number around 1, and between 0.01 and 10
  14510. * @param {{x: Number, y: Number}} pointer Position on screen
  14511. * @return {Number} appliedScale scale is limited within the boundaries
  14512. * @private
  14513. */
  14514. Graph.prototype._zoom = function(scale, pointer) {
  14515. var scaleOld = this._getScale();
  14516. if (scale < 0.00001) {
  14517. scale = 0.00001;
  14518. }
  14519. if (scale > 10) {
  14520. scale = 10;
  14521. }
  14522. // + this.frame.canvas.clientHeight / 2
  14523. var translation = this._getTranslation();
  14524. var scaleFrac = scale / scaleOld;
  14525. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14526. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14527. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  14528. "y" : this._canvasToY(pointer.y)};
  14529. this._setScale(scale);
  14530. this._setTranslation(tx, ty);
  14531. this.updateClustersDefault();
  14532. this._redraw();
  14533. return scale;
  14534. };
  14535. /**
  14536. * Event handler for mouse wheel event, used to zoom the timeline
  14537. * See http://adomas.org/javascript-mouse-wheel/
  14538. * https://github.com/EightMedia/hammer.js/issues/256
  14539. * @param {MouseEvent} event
  14540. * @private
  14541. */
  14542. Graph.prototype._onMouseWheel = function(event) {
  14543. // retrieve delta
  14544. var delta = 0;
  14545. if (event.wheelDelta) { /* IE/Opera. */
  14546. delta = event.wheelDelta/120;
  14547. } else if (event.detail) { /* Mozilla case. */
  14548. // In Mozilla, sign of delta is different than in IE.
  14549. // Also, delta is multiple of 3.
  14550. delta = -event.detail/3;
  14551. }
  14552. // If delta is nonzero, handle it.
  14553. // Basically, delta is now positive if wheel was scrolled up,
  14554. // and negative, if wheel was scrolled down.
  14555. if (delta) {
  14556. // calculate the new scale
  14557. var scale = this._getScale();
  14558. var zoom = delta / 10;
  14559. if (delta < 0) {
  14560. zoom = zoom / (1 - zoom);
  14561. }
  14562. scale *= (1 + zoom);
  14563. // calculate the pointer location
  14564. var gesture = util.fakeGesture(this, event);
  14565. var pointer = this._getPointer(gesture.center);
  14566. // apply the new scale
  14567. this._zoom(scale, pointer);
  14568. }
  14569. // Prevent default actions caused by mouse wheel.
  14570. event.preventDefault();
  14571. };
  14572. /**
  14573. * Mouse move handler for checking whether the title moves over a node with a title.
  14574. * @param {Event} event
  14575. * @private
  14576. */
  14577. Graph.prototype._onMouseMoveTitle = function (event) {
  14578. var gesture = util.fakeGesture(this, event);
  14579. var pointer = this._getPointer(gesture.center);
  14580. // check if the previously selected node is still selected
  14581. if (this.popupNode) {
  14582. this._checkHidePopup(pointer);
  14583. }
  14584. // start a timeout that will check if the mouse is positioned above
  14585. // an element
  14586. var me = this;
  14587. var checkShow = function() {
  14588. me._checkShowPopup(pointer);
  14589. };
  14590. if (this.popupTimer) {
  14591. clearInterval(this.popupTimer); // stop any running calculationTimer
  14592. }
  14593. if (!this.drag.dragging) {
  14594. this.popupTimer = setTimeout(checkShow, 300);
  14595. }
  14596. };
  14597. /**
  14598. * Check if there is an element on the given position in the graph
  14599. * (a node or edge). If so, and if this element has a title,
  14600. * show a popup window with its title.
  14601. *
  14602. * @param {{x:Number, y:Number}} pointer
  14603. * @private
  14604. */
  14605. Graph.prototype._checkShowPopup = function (pointer) {
  14606. var obj = {
  14607. left: this._canvasToX(pointer.x),
  14608. top: this._canvasToY(pointer.y),
  14609. right: this._canvasToX(pointer.x),
  14610. bottom: this._canvasToY(pointer.y)
  14611. };
  14612. var id;
  14613. var lastPopupNode = this.popupNode;
  14614. if (this.popupNode == undefined) {
  14615. // search the nodes for overlap, select the top one in case of multiple nodes
  14616. var nodes = this.nodes;
  14617. for (id in nodes) {
  14618. if (nodes.hasOwnProperty(id)) {
  14619. var node = nodes[id];
  14620. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14621. this.popupNode = node;
  14622. break;
  14623. }
  14624. }
  14625. }
  14626. }
  14627. if (this.popupNode === undefined) {
  14628. // search the edges for overlap
  14629. var edges = this.edges;
  14630. for (id in edges) {
  14631. if (edges.hasOwnProperty(id)) {
  14632. var edge = edges[id];
  14633. if (edge.connected && (edge.getTitle() !== undefined) &&
  14634. edge.isOverlappingWith(obj)) {
  14635. this.popupNode = edge;
  14636. break;
  14637. }
  14638. }
  14639. }
  14640. }
  14641. if (this.popupNode) {
  14642. // show popup message window
  14643. if (this.popupNode != lastPopupNode) {
  14644. var me = this;
  14645. if (!me.popup) {
  14646. me.popup = new Popup(me.frame);
  14647. }
  14648. // adjust a small offset such that the mouse cursor is located in the
  14649. // bottom left location of the popup, and you can easily move over the
  14650. // popup area
  14651. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14652. me.popup.setText(me.popupNode.getTitle());
  14653. me.popup.show();
  14654. }
  14655. }
  14656. else {
  14657. if (this.popup) {
  14658. this.popup.hide();
  14659. }
  14660. }
  14661. };
  14662. /**
  14663. * Check if the popup must be hided, which is the case when the mouse is no
  14664. * longer hovering on the object
  14665. * @param {{x:Number, y:Number}} pointer
  14666. * @private
  14667. */
  14668. Graph.prototype._checkHidePopup = function (pointer) {
  14669. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  14670. this.popupNode = undefined;
  14671. if (this.popup) {
  14672. this.popup.hide();
  14673. }
  14674. }
  14675. };
  14676. /**
  14677. * Set a new size for the graph
  14678. * @param {string} width Width in pixels or percentage (for example '800px'
  14679. * or '50%')
  14680. * @param {string} height Height in pixels or percentage (for example '400px'
  14681. * or '30%')
  14682. */
  14683. Graph.prototype.setSize = function(width, height) {
  14684. this.frame.style.width = width;
  14685. this.frame.style.height = height;
  14686. this.frame.canvas.style.width = '100%';
  14687. this.frame.canvas.style.height = '100%';
  14688. this.frame.canvas.width = this.frame.canvas.clientWidth;
  14689. this.frame.canvas.height = this.frame.canvas.clientHeight;
  14690. if (this.manipulationDiv !== undefined) {
  14691. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  14692. }
  14693. if (this.navigationDivs !== undefined) {
  14694. if (this.navigationDivs['wrapper'] !== undefined) {
  14695. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  14696. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  14697. }
  14698. }
  14699. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  14700. };
  14701. /**
  14702. * Set a data set with nodes for the graph
  14703. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14704. * @private
  14705. */
  14706. Graph.prototype._setNodes = function(nodes) {
  14707. var oldNodesData = this.nodesData;
  14708. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14709. this.nodesData = nodes;
  14710. }
  14711. else if (nodes instanceof Array) {
  14712. this.nodesData = new DataSet();
  14713. this.nodesData.add(nodes);
  14714. }
  14715. else if (!nodes) {
  14716. this.nodesData = new DataSet();
  14717. }
  14718. else {
  14719. throw new TypeError('Array or DataSet expected');
  14720. }
  14721. if (oldNodesData) {
  14722. // unsubscribe from old dataset
  14723. util.forEach(this.nodesListeners, function (callback, event) {
  14724. oldNodesData.off(event, callback);
  14725. });
  14726. }
  14727. // remove drawn nodes
  14728. this.nodes = {};
  14729. if (this.nodesData) {
  14730. // subscribe to new dataset
  14731. var me = this;
  14732. util.forEach(this.nodesListeners, function (callback, event) {
  14733. me.nodesData.on(event, callback);
  14734. });
  14735. // draw all new nodes
  14736. var ids = this.nodesData.getIds();
  14737. this._addNodes(ids);
  14738. }
  14739. this._updateSelection();
  14740. };
  14741. /**
  14742. * Add nodes
  14743. * @param {Number[] | String[]} ids
  14744. * @private
  14745. */
  14746. Graph.prototype._addNodes = function(ids) {
  14747. var id;
  14748. for (var i = 0, len = ids.length; i < len; i++) {
  14749. id = ids[i];
  14750. var data = this.nodesData.get(id);
  14751. var node = new Node(data, this.images, this.groups, this.constants);
  14752. this.nodes[id] = node; // note: this may replace an existing node
  14753. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  14754. var radius = 10 * 0.1*ids.length;
  14755. var angle = 2 * Math.PI * Math.random();
  14756. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  14757. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  14758. }
  14759. this.moving = true;
  14760. }
  14761. this._updateNodeIndexList();
  14762. this._updateCalculationNodes();
  14763. this._reconnectEdges();
  14764. this._updateValueRange(this.nodes);
  14765. this.updateLabels();
  14766. };
  14767. /**
  14768. * Update existing nodes, or create them when not yet existing
  14769. * @param {Number[] | String[]} ids
  14770. * @private
  14771. */
  14772. Graph.prototype._updateNodes = function(ids) {
  14773. var nodes = this.nodes,
  14774. nodesData = this.nodesData;
  14775. for (var i = 0, len = ids.length; i < len; i++) {
  14776. var id = ids[i];
  14777. var node = nodes[id];
  14778. var data = nodesData.get(id);
  14779. if (node) {
  14780. // update node
  14781. node.setProperties(data, this.constants);
  14782. }
  14783. else {
  14784. // create node
  14785. node = new Node(properties, this.images, this.groups, this.constants);
  14786. nodes[id] = node;
  14787. if (!node.isFixed()) {
  14788. this.moving = true;
  14789. }
  14790. }
  14791. }
  14792. this._updateNodeIndexList();
  14793. this._reconnectEdges();
  14794. this._updateValueRange(nodes);
  14795. };
  14796. /**
  14797. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  14798. * @param {Number[] | String[]} ids
  14799. * @private
  14800. */
  14801. Graph.prototype._removeNodes = function(ids) {
  14802. var nodes = this.nodes;
  14803. for (var i = 0, len = ids.length; i < len; i++) {
  14804. var id = ids[i];
  14805. delete nodes[id];
  14806. }
  14807. this._updateNodeIndexList();
  14808. this._updateCalculationNodes();
  14809. this._reconnectEdges();
  14810. this._updateSelection();
  14811. this._updateValueRange(nodes);
  14812. };
  14813. /**
  14814. * Load edges by reading the data table
  14815. * @param {Array | DataSet | DataView} edges The data containing the edges.
  14816. * @private
  14817. * @private
  14818. */
  14819. Graph.prototype._setEdges = function(edges) {
  14820. var oldEdgesData = this.edgesData;
  14821. if (edges instanceof DataSet || edges instanceof DataView) {
  14822. this.edgesData = edges;
  14823. }
  14824. else if (edges instanceof Array) {
  14825. this.edgesData = new DataSet();
  14826. this.edgesData.add(edges);
  14827. }
  14828. else if (!edges) {
  14829. this.edgesData = new DataSet();
  14830. }
  14831. else {
  14832. throw new TypeError('Array or DataSet expected');
  14833. }
  14834. if (oldEdgesData) {
  14835. // unsubscribe from old dataset
  14836. util.forEach(this.edgesListeners, function (callback, event) {
  14837. oldEdgesData.off(event, callback);
  14838. });
  14839. }
  14840. // remove drawn edges
  14841. this.edges = {};
  14842. if (this.edgesData) {
  14843. // subscribe to new dataset
  14844. var me = this;
  14845. util.forEach(this.edgesListeners, function (callback, event) {
  14846. me.edgesData.on(event, callback);
  14847. });
  14848. // draw all new nodes
  14849. var ids = this.edgesData.getIds();
  14850. this._addEdges(ids);
  14851. }
  14852. this._reconnectEdges();
  14853. };
  14854. /**
  14855. * Add edges
  14856. * @param {Number[] | String[]} ids
  14857. * @private
  14858. */
  14859. Graph.prototype._addEdges = function (ids) {
  14860. var edges = this.edges,
  14861. edgesData = this.edgesData;
  14862. for (var i = 0, len = ids.length; i < len; i++) {
  14863. var id = ids[i];
  14864. var oldEdge = edges[id];
  14865. if (oldEdge) {
  14866. oldEdge.disconnect();
  14867. }
  14868. var data = edgesData.get(id, {"showInternalIds" : true});
  14869. edges[id] = new Edge(data, this, this.constants);
  14870. }
  14871. this.moving = true;
  14872. this._updateValueRange(edges);
  14873. this._createBezierNodes();
  14874. this._updateCalculationNodes();
  14875. };
  14876. /**
  14877. * Update existing edges, or create them when not yet existing
  14878. * @param {Number[] | String[]} ids
  14879. * @private
  14880. */
  14881. Graph.prototype._updateEdges = function (ids) {
  14882. var edges = this.edges,
  14883. edgesData = this.edgesData;
  14884. for (var i = 0, len = ids.length; i < len; i++) {
  14885. var id = ids[i];
  14886. var data = edgesData.get(id);
  14887. var edge = edges[id];
  14888. if (edge) {
  14889. // update edge
  14890. edge.disconnect();
  14891. edge.setProperties(data, this.constants);
  14892. edge.connect();
  14893. }
  14894. else {
  14895. // create edge
  14896. edge = new Edge(data, this, this.constants);
  14897. this.edges[id] = edge;
  14898. }
  14899. }
  14900. this._createBezierNodes();
  14901. this.moving = true;
  14902. this._updateValueRange(edges);
  14903. };
  14904. /**
  14905. * Remove existing edges. Non existing ids will be ignored
  14906. * @param {Number[] | String[]} ids
  14907. * @private
  14908. */
  14909. Graph.prototype._removeEdges = function (ids) {
  14910. var edges = this.edges;
  14911. for (var i = 0, len = ids.length; i < len; i++) {
  14912. var id = ids[i];
  14913. var edge = edges[id];
  14914. if (edge) {
  14915. if (edge.via != null) {
  14916. delete this.sectors['support']['nodes'][edge.via.id];
  14917. }
  14918. edge.disconnect();
  14919. delete edges[id];
  14920. }
  14921. }
  14922. this.moving = true;
  14923. this._updateValueRange(edges);
  14924. this._updateCalculationNodes();
  14925. };
  14926. /**
  14927. * Reconnect all edges
  14928. * @private
  14929. */
  14930. Graph.prototype._reconnectEdges = function() {
  14931. var id,
  14932. nodes = this.nodes,
  14933. edges = this.edges;
  14934. for (id in nodes) {
  14935. if (nodes.hasOwnProperty(id)) {
  14936. nodes[id].edges = [];
  14937. }
  14938. }
  14939. for (id in edges) {
  14940. if (edges.hasOwnProperty(id)) {
  14941. var edge = edges[id];
  14942. edge.from = null;
  14943. edge.to = null;
  14944. edge.connect();
  14945. }
  14946. }
  14947. };
  14948. /**
  14949. * Update the values of all object in the given array according to the current
  14950. * value range of the objects in the array.
  14951. * @param {Object} obj An object containing a set of Edges or Nodes
  14952. * The objects must have a method getValue() and
  14953. * setValueRange(min, max).
  14954. * @private
  14955. */
  14956. Graph.prototype._updateValueRange = function(obj) {
  14957. var id;
  14958. // determine the range of the objects
  14959. var valueMin = undefined;
  14960. var valueMax = undefined;
  14961. for (id in obj) {
  14962. if (obj.hasOwnProperty(id)) {
  14963. var value = obj[id].getValue();
  14964. if (value !== undefined) {
  14965. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  14966. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  14967. }
  14968. }
  14969. }
  14970. // adjust the range of all objects
  14971. if (valueMin !== undefined && valueMax !== undefined) {
  14972. for (id in obj) {
  14973. if (obj.hasOwnProperty(id)) {
  14974. obj[id].setValueRange(valueMin, valueMax);
  14975. }
  14976. }
  14977. }
  14978. };
  14979. /**
  14980. * Redraw the graph with the current data
  14981. * chart will be resized too.
  14982. */
  14983. Graph.prototype.redraw = function() {
  14984. this.setSize(this.width, this.height);
  14985. this._redraw();
  14986. };
  14987. /**
  14988. * Redraw the graph with the current data
  14989. * @private
  14990. */
  14991. Graph.prototype._redraw = function() {
  14992. var ctx = this.frame.canvas.getContext('2d');
  14993. // clear the canvas
  14994. var w = this.frame.canvas.width;
  14995. var h = this.frame.canvas.height;
  14996. ctx.clearRect(0, 0, w, h);
  14997. // set scaling and translation
  14998. ctx.save();
  14999. ctx.translate(this.translation.x, this.translation.y);
  15000. ctx.scale(this.scale, this.scale);
  15001. this.canvasTopLeft = {
  15002. "x": this._canvasToX(0),
  15003. "y": this._canvasToY(0)
  15004. };
  15005. this.canvasBottomRight = {
  15006. "x": this._canvasToX(this.frame.canvas.clientWidth),
  15007. "y": this._canvasToY(this.frame.canvas.clientHeight)
  15008. };
  15009. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15010. this._doInAllSectors("_drawEdges",ctx);
  15011. this._doInAllSectors("_drawNodes",ctx,false);
  15012. // this._doInSupportSector("_drawNodes",ctx,true);
  15013. // this._drawTree(ctx,"#F00F0F");
  15014. // restore original scaling and translation
  15015. ctx.restore();
  15016. };
  15017. /**
  15018. * Set the translation of the graph
  15019. * @param {Number} offsetX Horizontal offset
  15020. * @param {Number} offsetY Vertical offset
  15021. * @private
  15022. */
  15023. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15024. if (this.translation === undefined) {
  15025. this.translation = {
  15026. x: 0,
  15027. y: 0
  15028. };
  15029. }
  15030. if (offsetX !== undefined) {
  15031. this.translation.x = offsetX;
  15032. }
  15033. if (offsetY !== undefined) {
  15034. this.translation.y = offsetY;
  15035. }
  15036. };
  15037. /**
  15038. * Get the translation of the graph
  15039. * @return {Object} translation An object with parameters x and y, both a number
  15040. * @private
  15041. */
  15042. Graph.prototype._getTranslation = function() {
  15043. return {
  15044. x: this.translation.x,
  15045. y: this.translation.y
  15046. };
  15047. };
  15048. /**
  15049. * Scale the graph
  15050. * @param {Number} scale Scaling factor 1.0 is unscaled
  15051. * @private
  15052. */
  15053. Graph.prototype._setScale = function(scale) {
  15054. this.scale = scale;
  15055. };
  15056. /**
  15057. * Get the current scale of the graph
  15058. * @return {Number} scale Scaling factor 1.0 is unscaled
  15059. * @private
  15060. */
  15061. Graph.prototype._getScale = function() {
  15062. return this.scale;
  15063. };
  15064. /**
  15065. * Convert a horizontal point on the HTML canvas to the x-value of the model
  15066. * @param {number} x
  15067. * @returns {number}
  15068. * @private
  15069. */
  15070. Graph.prototype._canvasToX = function(x) {
  15071. return (x - this.translation.x) / this.scale;
  15072. };
  15073. /**
  15074. * Convert an x-value in the model to a horizontal point on the HTML canvas
  15075. * @param {number} x
  15076. * @returns {number}
  15077. * @private
  15078. */
  15079. Graph.prototype._xToCanvas = function(x) {
  15080. return x * this.scale + this.translation.x;
  15081. };
  15082. /**
  15083. * Convert a vertical point on the HTML canvas to the y-value of the model
  15084. * @param {number} y
  15085. * @returns {number}
  15086. * @private
  15087. */
  15088. Graph.prototype._canvasToY = function(y) {
  15089. return (y - this.translation.y) / this.scale;
  15090. };
  15091. /**
  15092. * Convert an y-value in the model to a vertical point on the HTML canvas
  15093. * @param {number} y
  15094. * @returns {number}
  15095. * @private
  15096. */
  15097. Graph.prototype._yToCanvas = function(y) {
  15098. return y * this.scale + this.translation.y ;
  15099. };
  15100. /**
  15101. * Redraw all nodes
  15102. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15103. * @param {CanvasRenderingContext2D} ctx
  15104. * @param {Boolean} [alwaysShow]
  15105. * @private
  15106. */
  15107. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  15108. if (alwaysShow === undefined) {
  15109. alwaysShow = false;
  15110. }
  15111. // first draw the unselected nodes
  15112. var nodes = this.nodes;
  15113. var selected = [];
  15114. for (var id in nodes) {
  15115. if (nodes.hasOwnProperty(id)) {
  15116. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15117. if (nodes[id].isSelected()) {
  15118. selected.push(id);
  15119. }
  15120. else {
  15121. if (nodes[id].inArea() || alwaysShow) {
  15122. nodes[id].draw(ctx);
  15123. }
  15124. }
  15125. }
  15126. }
  15127. // draw the selected nodes on top
  15128. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15129. if (nodes[selected[s]].inArea() || alwaysShow) {
  15130. nodes[selected[s]].draw(ctx);
  15131. }
  15132. }
  15133. };
  15134. /**
  15135. * Redraw all edges
  15136. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15137. * @param {CanvasRenderingContext2D} ctx
  15138. * @private
  15139. */
  15140. Graph.prototype._drawEdges = function(ctx) {
  15141. var edges = this.edges;
  15142. for (var id in edges) {
  15143. if (edges.hasOwnProperty(id)) {
  15144. var edge = edges[id];
  15145. edge.setScale(this.scale);
  15146. if (edge.connected) {
  15147. edges[id].draw(ctx);
  15148. }
  15149. }
  15150. }
  15151. };
  15152. /**
  15153. * Find a stable position for all nodes
  15154. * @private
  15155. */
  15156. Graph.prototype._stabilize = function() {
  15157. if (this.constants.freezeForStabilization == true) {
  15158. this._freezeDefinedNodes();
  15159. }
  15160. // find stable position
  15161. var count = 0;
  15162. while (this.moving && count < this.constants.stabilizationIterations) {
  15163. this._physicsTick();
  15164. count++;
  15165. }
  15166. this.zoomExtent(false,true);
  15167. if (this.constants.freezeForStabilization == true) {
  15168. this._restoreFrozenNodes();
  15169. }
  15170. this.emit("stabilized",{iterations:count});
  15171. };
  15172. Graph.prototype._freezeDefinedNodes = function() {
  15173. var nodes = this.nodes;
  15174. for (var id in nodes) {
  15175. if (nodes.hasOwnProperty(id)) {
  15176. if (nodes[id].x != null && nodes[id].y != null) {
  15177. nodes[id].fixedData.x = nodes[id].xFixed;
  15178. nodes[id].fixedData.y = nodes[id].yFixed;
  15179. nodes[id].xFixed = true;
  15180. nodes[id].yFixed = true;
  15181. }
  15182. }
  15183. }
  15184. };
  15185. Graph.prototype._restoreFrozenNodes = function() {
  15186. var nodes = this.nodes;
  15187. for (var id in nodes) {
  15188. if (nodes.hasOwnProperty(id)) {
  15189. if (nodes[id].fixedData.x != null) {
  15190. nodes[id].xFixed = nodes[id].fixedData.x;
  15191. nodes[id].yFixed = nodes[id].fixedData.y;
  15192. }
  15193. }
  15194. }
  15195. };
  15196. /**
  15197. * Check if any of the nodes is still moving
  15198. * @param {number} vmin the minimum velocity considered as 'moving'
  15199. * @return {boolean} true if moving, false if non of the nodes is moving
  15200. * @private
  15201. */
  15202. Graph.prototype._isMoving = function(vmin) {
  15203. var nodes = this.nodes;
  15204. for (var id in nodes) {
  15205. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15206. return true;
  15207. }
  15208. }
  15209. return false;
  15210. };
  15211. /**
  15212. * /**
  15213. * Perform one discrete step for all nodes
  15214. *
  15215. * @private
  15216. */
  15217. Graph.prototype._discreteStepNodes = function() {
  15218. var interval = this.physicsDiscreteStepsize;
  15219. var nodes = this.nodes;
  15220. var nodeId;
  15221. var nodesPresent = false;
  15222. if (this.constants.maxVelocity > 0) {
  15223. for (nodeId in nodes) {
  15224. if (nodes.hasOwnProperty(nodeId)) {
  15225. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15226. nodesPresent = true;
  15227. }
  15228. }
  15229. }
  15230. else {
  15231. for (nodeId in nodes) {
  15232. if (nodes.hasOwnProperty(nodeId)) {
  15233. nodes[nodeId].discreteStep(interval);
  15234. nodesPresent = true;
  15235. }
  15236. }
  15237. }
  15238. if (nodesPresent == true) {
  15239. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15240. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15241. this.moving = true;
  15242. }
  15243. else {
  15244. this.moving = this._isMoving(vminCorrected);
  15245. }
  15246. }
  15247. };
  15248. Graph.prototype._physicsTick = function() {
  15249. if (!this.freezeSimulation) {
  15250. if (this.moving) {
  15251. this._doInAllActiveSectors("_initializeForceCalculation");
  15252. this._doInAllActiveSectors("_discreteStepNodes");
  15253. if (this.constants.smoothCurves) {
  15254. this._doInSupportSector("_discreteStepNodes");
  15255. }
  15256. this._findCenter(this._getRange())
  15257. }
  15258. }
  15259. };
  15260. /**
  15261. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15262. * It reschedules itself at the beginning of the function
  15263. *
  15264. * @private
  15265. */
  15266. Graph.prototype._animationStep = function() {
  15267. // reset the timer so a new scheduled animation step can be set
  15268. this.timer = undefined;
  15269. // handle the keyboad movement
  15270. this._handleNavigation();
  15271. // this schedules a new animation step
  15272. this.start();
  15273. // start the physics simulation
  15274. var calculationTime = Date.now();
  15275. var maxSteps = 1;
  15276. this._physicsTick();
  15277. var timeRequired = Date.now() - calculationTime;
  15278. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  15279. this._physicsTick();
  15280. timeRequired = Date.now() - calculationTime;
  15281. maxSteps++;
  15282. }
  15283. // start the rendering process
  15284. var renderTime = Date.now();
  15285. this._redraw();
  15286. this.renderTime = Date.now() - renderTime;
  15287. };
  15288. if (typeof window !== 'undefined') {
  15289. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15290. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15291. }
  15292. /**
  15293. * Schedule a animation step with the refreshrate interval.
  15294. *
  15295. * @poram {Boolean} runCalculationStep
  15296. */
  15297. Graph.prototype.start = function() {
  15298. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15299. if (!this.timer) {
  15300. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15301. }
  15302. }
  15303. else {
  15304. this._redraw();
  15305. }
  15306. };
  15307. /**
  15308. * Move the graph according to the keyboard presses.
  15309. *
  15310. * @private
  15311. */
  15312. Graph.prototype._handleNavigation = function() {
  15313. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15314. var translation = this._getTranslation();
  15315. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15316. }
  15317. if (this.zoomIncrement != 0) {
  15318. var center = {
  15319. x: this.frame.canvas.clientWidth / 2,
  15320. y: this.frame.canvas.clientHeight / 2
  15321. };
  15322. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15323. }
  15324. };
  15325. /**
  15326. * Freeze the _animationStep
  15327. */
  15328. Graph.prototype.toggleFreeze = function() {
  15329. if (this.freezeSimulation == false) {
  15330. this.freezeSimulation = true;
  15331. }
  15332. else {
  15333. this.freezeSimulation = false;
  15334. this.start();
  15335. }
  15336. };
  15337. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15338. if (disableStart === undefined) {
  15339. disableStart = true;
  15340. }
  15341. if (this.constants.smoothCurves == true) {
  15342. this._createBezierNodes();
  15343. }
  15344. else {
  15345. // delete the support nodes
  15346. this.sectors['support']['nodes'] = {};
  15347. for (var edgeId in this.edges) {
  15348. if (this.edges.hasOwnProperty(edgeId)) {
  15349. this.edges[edgeId].smooth = false;
  15350. this.edges[edgeId].via = null;
  15351. }
  15352. }
  15353. }
  15354. this._updateCalculationNodes();
  15355. if (!disableStart) {
  15356. this.moving = true;
  15357. this.start();
  15358. }
  15359. };
  15360. Graph.prototype._createBezierNodes = function() {
  15361. if (this.constants.smoothCurves == true) {
  15362. for (var edgeId in this.edges) {
  15363. if (this.edges.hasOwnProperty(edgeId)) {
  15364. var edge = this.edges[edgeId];
  15365. if (edge.via == null) {
  15366. edge.smooth = true;
  15367. var nodeId = "edgeId:".concat(edge.id);
  15368. this.sectors['support']['nodes'][nodeId] = new Node(
  15369. {id:nodeId,
  15370. mass:1,
  15371. shape:'circle',
  15372. image:"",
  15373. internalMultiplier:1
  15374. },{},{},this.constants);
  15375. edge.via = this.sectors['support']['nodes'][nodeId];
  15376. edge.via.parentEdgeId = edge.id;
  15377. edge.positionBezierNode();
  15378. }
  15379. }
  15380. }
  15381. }
  15382. };
  15383. Graph.prototype._initializeMixinLoaders = function () {
  15384. for (var mixinFunction in graphMixinLoaders) {
  15385. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15386. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15387. }
  15388. }
  15389. };
  15390. /**
  15391. * Load the XY positions of the nodes into the dataset.
  15392. */
  15393. Graph.prototype.storePosition = function() {
  15394. var dataArray = [];
  15395. for (var nodeId in this.nodes) {
  15396. if (this.nodes.hasOwnProperty(nodeId)) {
  15397. var node = this.nodes[nodeId];
  15398. var allowedToMoveX = !this.nodes.xFixed;
  15399. var allowedToMoveY = !this.nodes.yFixed;
  15400. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  15401. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15402. }
  15403. }
  15404. }
  15405. this.nodesData.update(dataArray);
  15406. };
  15407. /**
  15408. * vis.js module exports
  15409. */
  15410. var vis = {
  15411. util: util,
  15412. Controller: Controller,
  15413. DataSet: DataSet,
  15414. DataView: DataView,
  15415. Range: Range,
  15416. Stack: Stack,
  15417. TimeStep: TimeStep,
  15418. components: {
  15419. items: {
  15420. Item: Item,
  15421. ItemBox: ItemBox,
  15422. ItemPoint: ItemPoint,
  15423. ItemRange: ItemRange
  15424. },
  15425. Component: Component,
  15426. Panel: Panel,
  15427. RootPanel: RootPanel,
  15428. ItemSet: ItemSet,
  15429. TimeAxis: TimeAxis
  15430. },
  15431. graph: {
  15432. Node: Node,
  15433. Edge: Edge,
  15434. Popup: Popup,
  15435. Groups: Groups,
  15436. Images: Images
  15437. },
  15438. Timeline: Timeline,
  15439. Graph: Graph
  15440. };
  15441. /**
  15442. * CommonJS module exports
  15443. */
  15444. if (typeof exports !== 'undefined') {
  15445. exports = vis;
  15446. }
  15447. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15448. module.exports = vis;
  15449. }
  15450. /**
  15451. * AMD module exports
  15452. */
  15453. if (typeof(define) === 'function') {
  15454. define(function () {
  15455. return vis;
  15456. });
  15457. }
  15458. /**
  15459. * Window exports
  15460. */
  15461. if (typeof window !== 'undefined') {
  15462. // attach the module to the window, load as a regular javascript file
  15463. window['vis'] = vis;
  15464. }
  15465. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15466. /**
  15467. * Expose `Emitter`.
  15468. */
  15469. module.exports = Emitter;
  15470. /**
  15471. * Initialize a new `Emitter`.
  15472. *
  15473. * @api public
  15474. */
  15475. function Emitter(obj) {
  15476. if (obj) return mixin(obj);
  15477. };
  15478. /**
  15479. * Mixin the emitter properties.
  15480. *
  15481. * @param {Object} obj
  15482. * @return {Object}
  15483. * @api private
  15484. */
  15485. function mixin(obj) {
  15486. for (var key in Emitter.prototype) {
  15487. obj[key] = Emitter.prototype[key];
  15488. }
  15489. return obj;
  15490. }
  15491. /**
  15492. * Listen on the given `event` with `fn`.
  15493. *
  15494. * @param {String} event
  15495. * @param {Function} fn
  15496. * @return {Emitter}
  15497. * @api public
  15498. */
  15499. Emitter.prototype.on =
  15500. Emitter.prototype.addEventListener = function(event, fn){
  15501. this._callbacks = this._callbacks || {};
  15502. (this._callbacks[event] = this._callbacks[event] || [])
  15503. .push(fn);
  15504. return this;
  15505. };
  15506. /**
  15507. * Adds an `event` listener that will be invoked a single
  15508. * time then automatically removed.
  15509. *
  15510. * @param {String} event
  15511. * @param {Function} fn
  15512. * @return {Emitter}
  15513. * @api public
  15514. */
  15515. Emitter.prototype.once = function(event, fn){
  15516. var self = this;
  15517. this._callbacks = this._callbacks || {};
  15518. function on() {
  15519. self.off(event, on);
  15520. fn.apply(this, arguments);
  15521. }
  15522. on.fn = fn;
  15523. this.on(event, on);
  15524. return this;
  15525. };
  15526. /**
  15527. * Remove the given callback for `event` or all
  15528. * registered callbacks.
  15529. *
  15530. * @param {String} event
  15531. * @param {Function} fn
  15532. * @return {Emitter}
  15533. * @api public
  15534. */
  15535. Emitter.prototype.off =
  15536. Emitter.prototype.removeListener =
  15537. Emitter.prototype.removeAllListeners =
  15538. Emitter.prototype.removeEventListener = function(event, fn){
  15539. this._callbacks = this._callbacks || {};
  15540. // all
  15541. if (0 == arguments.length) {
  15542. this._callbacks = {};
  15543. return this;
  15544. }
  15545. // specific event
  15546. var callbacks = this._callbacks[event];
  15547. if (!callbacks) return this;
  15548. // remove all handlers
  15549. if (1 == arguments.length) {
  15550. delete this._callbacks[event];
  15551. return this;
  15552. }
  15553. // remove specific handler
  15554. var cb;
  15555. for (var i = 0; i < callbacks.length; i++) {
  15556. cb = callbacks[i];
  15557. if (cb === fn || cb.fn === fn) {
  15558. callbacks.splice(i, 1);
  15559. break;
  15560. }
  15561. }
  15562. return this;
  15563. };
  15564. /**
  15565. * Emit `event` with the given args.
  15566. *
  15567. * @param {String} event
  15568. * @param {Mixed} ...
  15569. * @return {Emitter}
  15570. */
  15571. Emitter.prototype.emit = function(event){
  15572. this._callbacks = this._callbacks || {};
  15573. var args = [].slice.call(arguments, 1)
  15574. , callbacks = this._callbacks[event];
  15575. if (callbacks) {
  15576. callbacks = callbacks.slice(0);
  15577. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15578. callbacks[i].apply(this, args);
  15579. }
  15580. }
  15581. return this;
  15582. };
  15583. /**
  15584. * Return array of callbacks for `event`.
  15585. *
  15586. * @param {String} event
  15587. * @return {Array}
  15588. * @api public
  15589. */
  15590. Emitter.prototype.listeners = function(event){
  15591. this._callbacks = this._callbacks || {};
  15592. return this._callbacks[event] || [];
  15593. };
  15594. /**
  15595. * Check if this emitter has `event` handlers.
  15596. *
  15597. * @param {String} event
  15598. * @return {Boolean}
  15599. * @api public
  15600. */
  15601. Emitter.prototype.hasListeners = function(event){
  15602. return !! this.listeners(event).length;
  15603. };
  15604. },{}],3:[function(require,module,exports){
  15605. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15606. * http://eightmedia.github.com/hammer.js
  15607. *
  15608. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  15609. * Licensed under the MIT license */
  15610. (function(window, undefined) {
  15611. 'use strict';
  15612. /**
  15613. * Hammer
  15614. * use this to create instances
  15615. * @param {HTMLElement} element
  15616. * @param {Object} options
  15617. * @returns {Hammer.Instance}
  15618. * @constructor
  15619. */
  15620. var Hammer = function(element, options) {
  15621. return new Hammer.Instance(element, options || {});
  15622. };
  15623. // default settings
  15624. Hammer.defaults = {
  15625. // add styles and attributes to the element to prevent the browser from doing
  15626. // its native behavior. this doesnt prevent the scrolling, but cancels
  15627. // the contextmenu, tap highlighting etc
  15628. // set to false to disable this
  15629. stop_browser_behavior: {
  15630. // this also triggers onselectstart=false for IE
  15631. userSelect: 'none',
  15632. // this makes the element blocking in IE10 >, you could experiment with the value
  15633. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  15634. touchAction: 'none',
  15635. touchCallout: 'none',
  15636. contentZooming: 'none',
  15637. userDrag: 'none',
  15638. tapHighlightColor: 'rgba(0,0,0,0)'
  15639. }
  15640. // more settings are defined per gesture at gestures.js
  15641. };
  15642. // detect touchevents
  15643. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  15644. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  15645. // dont use mouseevents on mobile devices
  15646. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  15647. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  15648. // eventtypes per touchevent (start, move, end)
  15649. // are filled by Hammer.event.determineEventTypes on setup
  15650. Hammer.EVENT_TYPES = {};
  15651. // direction defines
  15652. Hammer.DIRECTION_DOWN = 'down';
  15653. Hammer.DIRECTION_LEFT = 'left';
  15654. Hammer.DIRECTION_UP = 'up';
  15655. Hammer.DIRECTION_RIGHT = 'right';
  15656. // pointer type
  15657. Hammer.POINTER_MOUSE = 'mouse';
  15658. Hammer.POINTER_TOUCH = 'touch';
  15659. Hammer.POINTER_PEN = 'pen';
  15660. // touch event defines
  15661. Hammer.EVENT_START = 'start';
  15662. Hammer.EVENT_MOVE = 'move';
  15663. Hammer.EVENT_END = 'end';
  15664. // hammer document where the base events are added at
  15665. Hammer.DOCUMENT = document;
  15666. // plugins namespace
  15667. Hammer.plugins = {};
  15668. // if the window events are set...
  15669. Hammer.READY = false;
  15670. /**
  15671. * setup events to detect gestures on the document
  15672. */
  15673. function setup() {
  15674. if(Hammer.READY) {
  15675. return;
  15676. }
  15677. // find what eventtypes we add listeners to
  15678. Hammer.event.determineEventTypes();
  15679. // Register all gestures inside Hammer.gestures
  15680. for(var name in Hammer.gestures) {
  15681. if(Hammer.gestures.hasOwnProperty(name)) {
  15682. Hammer.detection.register(Hammer.gestures[name]);
  15683. }
  15684. }
  15685. // Add touch events on the document
  15686. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  15687. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  15688. // Hammer is ready...!
  15689. Hammer.READY = true;
  15690. }
  15691. /**
  15692. * create new hammer instance
  15693. * all methods should return the instance itself, so it is chainable.
  15694. * @param {HTMLElement} element
  15695. * @param {Object} [options={}]
  15696. * @returns {Hammer.Instance}
  15697. * @constructor
  15698. */
  15699. Hammer.Instance = function(element, options) {
  15700. var self = this;
  15701. // setup HammerJS window events and register all gestures
  15702. // this also sets up the default options
  15703. setup();
  15704. this.element = element;
  15705. // start/stop detection option
  15706. this.enabled = true;
  15707. // merge options
  15708. this.options = Hammer.utils.extend(
  15709. Hammer.utils.extend({}, Hammer.defaults),
  15710. options || {});
  15711. // add some css to the element to prevent the browser from doing its native behavoir
  15712. if(this.options.stop_browser_behavior) {
  15713. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  15714. }
  15715. // start detection on touchstart
  15716. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  15717. if(self.enabled) {
  15718. Hammer.detection.startDetect(self, ev);
  15719. }
  15720. });
  15721. // return instance
  15722. return this;
  15723. };
  15724. Hammer.Instance.prototype = {
  15725. /**
  15726. * bind events to the instance
  15727. * @param {String} gesture
  15728. * @param {Function} handler
  15729. * @returns {Hammer.Instance}
  15730. */
  15731. on: function onEvent(gesture, handler){
  15732. var gestures = gesture.split(' ');
  15733. for(var t=0; t<gestures.length; t++) {
  15734. this.element.addEventListener(gestures[t], handler, false);
  15735. }
  15736. return this;
  15737. },
  15738. /**
  15739. * unbind events to the instance
  15740. * @param {String} gesture
  15741. * @param {Function} handler
  15742. * @returns {Hammer.Instance}
  15743. */
  15744. off: function offEvent(gesture, handler){
  15745. var gestures = gesture.split(' ');
  15746. for(var t=0; t<gestures.length; t++) {
  15747. this.element.removeEventListener(gestures[t], handler, false);
  15748. }
  15749. return this;
  15750. },
  15751. /**
  15752. * trigger gesture event
  15753. * @param {String} gesture
  15754. * @param {Object} eventData
  15755. * @returns {Hammer.Instance}
  15756. */
  15757. trigger: function triggerEvent(gesture, eventData){
  15758. // create DOM event
  15759. var event = Hammer.DOCUMENT.createEvent('Event');
  15760. event.initEvent(gesture, true, true);
  15761. event.gesture = eventData;
  15762. // trigger on the target if it is in the instance element,
  15763. // this is for event delegation tricks
  15764. var element = this.element;
  15765. if(Hammer.utils.hasParent(eventData.target, element)) {
  15766. element = eventData.target;
  15767. }
  15768. element.dispatchEvent(event);
  15769. return this;
  15770. },
  15771. /**
  15772. * enable of disable hammer.js detection
  15773. * @param {Boolean} state
  15774. * @returns {Hammer.Instance}
  15775. */
  15776. enable: function enable(state) {
  15777. this.enabled = state;
  15778. return this;
  15779. }
  15780. };
  15781. /**
  15782. * this holds the last move event,
  15783. * used to fix empty touchend issue
  15784. * see the onTouch event for an explanation
  15785. * @type {Object}
  15786. */
  15787. var last_move_event = null;
  15788. /**
  15789. * when the mouse is hold down, this is true
  15790. * @type {Boolean}
  15791. */
  15792. var enable_detect = false;
  15793. /**
  15794. * when touch events have been fired, this is true
  15795. * @type {Boolean}
  15796. */
  15797. var touch_triggered = false;
  15798. Hammer.event = {
  15799. /**
  15800. * simple addEventListener
  15801. * @param {HTMLElement} element
  15802. * @param {String} type
  15803. * @param {Function} handler
  15804. */
  15805. bindDom: function(element, type, handler) {
  15806. var types = type.split(' ');
  15807. for(var t=0; t<types.length; t++) {
  15808. element.addEventListener(types[t], handler, false);
  15809. }
  15810. },
  15811. /**
  15812. * touch events with mouse fallback
  15813. * @param {HTMLElement} element
  15814. * @param {String} eventType like Hammer.EVENT_MOVE
  15815. * @param {Function} handler
  15816. */
  15817. onTouch: function onTouch(element, eventType, handler) {
  15818. var self = this;
  15819. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  15820. var sourceEventType = ev.type.toLowerCase();
  15821. // onmouseup, but when touchend has been fired we do nothing.
  15822. // this is for touchdevices which also fire a mouseup on touchend
  15823. if(sourceEventType.match(/mouse/) && touch_triggered) {
  15824. return;
  15825. }
  15826. // mousebutton must be down or a touch event
  15827. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  15828. sourceEventType.match(/pointerdown/) || // pointerevents touch
  15829. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  15830. ){
  15831. enable_detect = true;
  15832. }
  15833. // we are in a touch event, set the touch triggered bool to true,
  15834. // this for the conflicts that may occur on ios and android
  15835. if(sourceEventType.match(/touch|pointer/)) {
  15836. touch_triggered = true;
  15837. }
  15838. // count the total touches on the screen
  15839. var count_touches = 0;
  15840. // when touch has been triggered in this detection session
  15841. // and we are now handling a mouse event, we stop that to prevent conflicts
  15842. if(enable_detect) {
  15843. // update pointerevent
  15844. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  15845. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15846. }
  15847. // touch
  15848. else if(sourceEventType.match(/touch/)) {
  15849. count_touches = ev.touches.length;
  15850. }
  15851. // mouse
  15852. else if(!touch_triggered) {
  15853. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  15854. }
  15855. // if we are in a end event, but when we remove one touch and
  15856. // we still have enough, set eventType to move
  15857. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  15858. eventType = Hammer.EVENT_MOVE;
  15859. }
  15860. // no touches, force the end event
  15861. else if(!count_touches) {
  15862. eventType = Hammer.EVENT_END;
  15863. }
  15864. // because touchend has no touches, and we often want to use these in our gestures,
  15865. // we send the last move event as our eventData in touchend
  15866. if(!count_touches && last_move_event !== null) {
  15867. ev = last_move_event;
  15868. }
  15869. // store the last move event
  15870. else {
  15871. last_move_event = ev;
  15872. }
  15873. // trigger the handler
  15874. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  15875. // remove pointerevent from list
  15876. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  15877. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15878. }
  15879. }
  15880. //debug(sourceEventType +" "+ eventType);
  15881. // on the end we reset everything
  15882. if(!count_touches) {
  15883. last_move_event = null;
  15884. enable_detect = false;
  15885. touch_triggered = false;
  15886. Hammer.PointerEvent.reset();
  15887. }
  15888. });
  15889. },
  15890. /**
  15891. * we have different events for each device/browser
  15892. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  15893. */
  15894. determineEventTypes: function determineEventTypes() {
  15895. // determine the eventtype we want to set
  15896. var types;
  15897. // pointerEvents magic
  15898. if(Hammer.HAS_POINTEREVENTS) {
  15899. types = Hammer.PointerEvent.getEvents();
  15900. }
  15901. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  15902. else if(Hammer.NO_MOUSEEVENTS) {
  15903. types = [
  15904. 'touchstart',
  15905. 'touchmove',
  15906. 'touchend touchcancel'];
  15907. }
  15908. // for non pointer events browsers and mixed browsers,
  15909. // like chrome on windows8 touch laptop
  15910. else {
  15911. types = [
  15912. 'touchstart mousedown',
  15913. 'touchmove mousemove',
  15914. 'touchend touchcancel mouseup'];
  15915. }
  15916. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  15917. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  15918. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  15919. },
  15920. /**
  15921. * create touchlist depending on the event
  15922. * @param {Object} ev
  15923. * @param {String} eventType used by the fakemultitouch plugin
  15924. */
  15925. getTouchList: function getTouchList(ev/*, eventType*/) {
  15926. // get the fake pointerEvent touchlist
  15927. if(Hammer.HAS_POINTEREVENTS) {
  15928. return Hammer.PointerEvent.getTouchList();
  15929. }
  15930. // get the touchlist
  15931. else if(ev.touches) {
  15932. return ev.touches;
  15933. }
  15934. // make fake touchlist from mouse position
  15935. else {
  15936. return [{
  15937. identifier: 1,
  15938. pageX: ev.pageX,
  15939. pageY: ev.pageY,
  15940. target: ev.target
  15941. }];
  15942. }
  15943. },
  15944. /**
  15945. * collect event data for Hammer js
  15946. * @param {HTMLElement} element
  15947. * @param {String} eventType like Hammer.EVENT_MOVE
  15948. * @param {Object} eventData
  15949. */
  15950. collectEventData: function collectEventData(element, eventType, ev) {
  15951. var touches = this.getTouchList(ev, eventType);
  15952. // find out pointerType
  15953. var pointerType = Hammer.POINTER_TOUCH;
  15954. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  15955. pointerType = Hammer.POINTER_MOUSE;
  15956. }
  15957. return {
  15958. center : Hammer.utils.getCenter(touches),
  15959. timeStamp : new Date().getTime(),
  15960. target : ev.target,
  15961. touches : touches,
  15962. eventType : eventType,
  15963. pointerType : pointerType,
  15964. srcEvent : ev,
  15965. /**
  15966. * prevent the browser default actions
  15967. * mostly used to disable scrolling of the browser
  15968. */
  15969. preventDefault: function() {
  15970. if(this.srcEvent.preventManipulation) {
  15971. this.srcEvent.preventManipulation();
  15972. }
  15973. if(this.srcEvent.preventDefault) {
  15974. this.srcEvent.preventDefault();
  15975. }
  15976. },
  15977. /**
  15978. * stop bubbling the event up to its parents
  15979. */
  15980. stopPropagation: function() {
  15981. this.srcEvent.stopPropagation();
  15982. },
  15983. /**
  15984. * immediately stop gesture detection
  15985. * might be useful after a swipe was detected
  15986. * @return {*}
  15987. */
  15988. stopDetect: function() {
  15989. return Hammer.detection.stopDetect();
  15990. }
  15991. };
  15992. }
  15993. };
  15994. Hammer.PointerEvent = {
  15995. /**
  15996. * holds all pointers
  15997. * @type {Object}
  15998. */
  15999. pointers: {},
  16000. /**
  16001. * get a list of pointers
  16002. * @returns {Array} touchlist
  16003. */
  16004. getTouchList: function() {
  16005. var self = this;
  16006. var touchlist = [];
  16007. // we can use forEach since pointerEvents only is in IE10
  16008. Object.keys(self.pointers).sort().forEach(function(id) {
  16009. touchlist.push(self.pointers[id]);
  16010. });
  16011. return touchlist;
  16012. },
  16013. /**
  16014. * update the position of a pointer
  16015. * @param {String} type Hammer.EVENT_END
  16016. * @param {Object} pointerEvent
  16017. */
  16018. updatePointer: function(type, pointerEvent) {
  16019. if(type == Hammer.EVENT_END) {
  16020. this.pointers = {};
  16021. }
  16022. else {
  16023. pointerEvent.identifier = pointerEvent.pointerId;
  16024. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16025. }
  16026. return Object.keys(this.pointers).length;
  16027. },
  16028. /**
  16029. * check if ev matches pointertype
  16030. * @param {String} pointerType Hammer.POINTER_MOUSE
  16031. * @param {PointerEvent} ev
  16032. */
  16033. matchType: function(pointerType, ev) {
  16034. if(!ev.pointerType) {
  16035. return false;
  16036. }
  16037. var types = {};
  16038. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16039. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16040. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16041. return types[pointerType];
  16042. },
  16043. /**
  16044. * get events
  16045. */
  16046. getEvents: function() {
  16047. return [
  16048. 'pointerdown MSPointerDown',
  16049. 'pointermove MSPointerMove',
  16050. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16051. ];
  16052. },
  16053. /**
  16054. * reset the list
  16055. */
  16056. reset: function() {
  16057. this.pointers = {};
  16058. }
  16059. };
  16060. Hammer.utils = {
  16061. /**
  16062. * extend method,
  16063. * also used for cloning when dest is an empty object
  16064. * @param {Object} dest
  16065. * @param {Object} src
  16066. * @parm {Boolean} merge do a merge
  16067. * @returns {Object} dest
  16068. */
  16069. extend: function extend(dest, src, merge) {
  16070. for (var key in src) {
  16071. if(dest[key] !== undefined && merge) {
  16072. continue;
  16073. }
  16074. dest[key] = src[key];
  16075. }
  16076. return dest;
  16077. },
  16078. /**
  16079. * find if a node is in the given parent
  16080. * used for event delegation tricks
  16081. * @param {HTMLElement} node
  16082. * @param {HTMLElement} parent
  16083. * @returns {boolean} has_parent
  16084. */
  16085. hasParent: function(node, parent) {
  16086. while(node){
  16087. if(node == parent) {
  16088. return true;
  16089. }
  16090. node = node.parentNode;
  16091. }
  16092. return false;
  16093. },
  16094. /**
  16095. * get the center of all the touches
  16096. * @param {Array} touches
  16097. * @returns {Object} center
  16098. */
  16099. getCenter: function getCenter(touches) {
  16100. var valuesX = [], valuesY = [];
  16101. for(var t= 0,len=touches.length; t<len; t++) {
  16102. valuesX.push(touches[t].pageX);
  16103. valuesY.push(touches[t].pageY);
  16104. }
  16105. return {
  16106. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  16107. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  16108. };
  16109. },
  16110. /**
  16111. * calculate the velocity between two points
  16112. * @param {Number} delta_time
  16113. * @param {Number} delta_x
  16114. * @param {Number} delta_y
  16115. * @returns {Object} velocity
  16116. */
  16117. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  16118. return {
  16119. x: Math.abs(delta_x / delta_time) || 0,
  16120. y: Math.abs(delta_y / delta_time) || 0
  16121. };
  16122. },
  16123. /**
  16124. * calculate the angle between two coordinates
  16125. * @param {Touch} touch1
  16126. * @param {Touch} touch2
  16127. * @returns {Number} angle
  16128. */
  16129. getAngle: function getAngle(touch1, touch2) {
  16130. var y = touch2.pageY - touch1.pageY,
  16131. x = touch2.pageX - touch1.pageX;
  16132. return Math.atan2(y, x) * 180 / Math.PI;
  16133. },
  16134. /**
  16135. * angle to direction define
  16136. * @param {Touch} touch1
  16137. * @param {Touch} touch2
  16138. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  16139. */
  16140. getDirection: function getDirection(touch1, touch2) {
  16141. var x = Math.abs(touch1.pageX - touch2.pageX),
  16142. y = Math.abs(touch1.pageY - touch2.pageY);
  16143. if(x >= y) {
  16144. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16145. }
  16146. else {
  16147. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16148. }
  16149. },
  16150. /**
  16151. * calculate the distance between two touches
  16152. * @param {Touch} touch1
  16153. * @param {Touch} touch2
  16154. * @returns {Number} distance
  16155. */
  16156. getDistance: function getDistance(touch1, touch2) {
  16157. var x = touch2.pageX - touch1.pageX,
  16158. y = touch2.pageY - touch1.pageY;
  16159. return Math.sqrt((x*x) + (y*y));
  16160. },
  16161. /**
  16162. * calculate the scale factor between two touchLists (fingers)
  16163. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16164. * @param {Array} start
  16165. * @param {Array} end
  16166. * @returns {Number} scale
  16167. */
  16168. getScale: function getScale(start, end) {
  16169. // need two fingers...
  16170. if(start.length >= 2 && end.length >= 2) {
  16171. return this.getDistance(end[0], end[1]) /
  16172. this.getDistance(start[0], start[1]);
  16173. }
  16174. return 1;
  16175. },
  16176. /**
  16177. * calculate the rotation degrees between two touchLists (fingers)
  16178. * @param {Array} start
  16179. * @param {Array} end
  16180. * @returns {Number} rotation
  16181. */
  16182. getRotation: function getRotation(start, end) {
  16183. // need two fingers
  16184. if(start.length >= 2 && end.length >= 2) {
  16185. return this.getAngle(end[1], end[0]) -
  16186. this.getAngle(start[1], start[0]);
  16187. }
  16188. return 0;
  16189. },
  16190. /**
  16191. * boolean if the direction is vertical
  16192. * @param {String} direction
  16193. * @returns {Boolean} is_vertical
  16194. */
  16195. isVertical: function isVertical(direction) {
  16196. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16197. },
  16198. /**
  16199. * stop browser default behavior with css props
  16200. * @param {HtmlElement} element
  16201. * @param {Object} css_props
  16202. */
  16203. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16204. var prop,
  16205. vendors = ['webkit','khtml','moz','ms','o',''];
  16206. if(!css_props || !element.style) {
  16207. return;
  16208. }
  16209. // with css properties for modern browsers
  16210. for(var i = 0; i < vendors.length; i++) {
  16211. for(var p in css_props) {
  16212. if(css_props.hasOwnProperty(p)) {
  16213. prop = p;
  16214. // vender prefix at the property
  16215. if(vendors[i]) {
  16216. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16217. }
  16218. // set the style
  16219. element.style[prop] = css_props[p];
  16220. }
  16221. }
  16222. }
  16223. // also the disable onselectstart
  16224. if(css_props.userSelect == 'none') {
  16225. element.onselectstart = function() {
  16226. return false;
  16227. };
  16228. }
  16229. }
  16230. };
  16231. Hammer.detection = {
  16232. // contains all registred Hammer.gestures in the correct order
  16233. gestures: [],
  16234. // data of the current Hammer.gesture detection session
  16235. current: null,
  16236. // the previous Hammer.gesture session data
  16237. // is a full clone of the previous gesture.current object
  16238. previous: null,
  16239. // when this becomes true, no gestures are fired
  16240. stopped: false,
  16241. /**
  16242. * start Hammer.gesture detection
  16243. * @param {Hammer.Instance} inst
  16244. * @param {Object} eventData
  16245. */
  16246. startDetect: function startDetect(inst, eventData) {
  16247. // already busy with a Hammer.gesture detection on an element
  16248. if(this.current) {
  16249. return;
  16250. }
  16251. this.stopped = false;
  16252. this.current = {
  16253. inst : inst, // reference to HammerInstance we're working for
  16254. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16255. lastEvent : false, // last eventData
  16256. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16257. };
  16258. this.detect(eventData);
  16259. },
  16260. /**
  16261. * Hammer.gesture detection
  16262. * @param {Object} eventData
  16263. * @param {Object} eventData
  16264. */
  16265. detect: function detect(eventData) {
  16266. if(!this.current || this.stopped) {
  16267. return;
  16268. }
  16269. // extend event data with calculations about scale, distance etc
  16270. eventData = this.extendEventData(eventData);
  16271. // instance options
  16272. var inst_options = this.current.inst.options;
  16273. // call Hammer.gesture handlers
  16274. for(var g=0,len=this.gestures.length; g<len; g++) {
  16275. var gesture = this.gestures[g];
  16276. // only when the instance options have enabled this gesture
  16277. if(!this.stopped && inst_options[gesture.name] !== false) {
  16278. // if a handler returns false, we stop with the detection
  16279. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16280. this.stopDetect();
  16281. break;
  16282. }
  16283. }
  16284. }
  16285. // store as previous event event
  16286. if(this.current) {
  16287. this.current.lastEvent = eventData;
  16288. }
  16289. // endevent, but not the last touch, so dont stop
  16290. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16291. this.stopDetect();
  16292. }
  16293. return eventData;
  16294. },
  16295. /**
  16296. * clear the Hammer.gesture vars
  16297. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16298. * to stop other Hammer.gestures from being fired
  16299. */
  16300. stopDetect: function stopDetect() {
  16301. // clone current data to the store as the previous gesture
  16302. // used for the double tap gesture, since this is an other gesture detect session
  16303. this.previous = Hammer.utils.extend({}, this.current);
  16304. // reset the current
  16305. this.current = null;
  16306. // stopped!
  16307. this.stopped = true;
  16308. },
  16309. /**
  16310. * extend eventData for Hammer.gestures
  16311. * @param {Object} ev
  16312. * @returns {Object} ev
  16313. */
  16314. extendEventData: function extendEventData(ev) {
  16315. var startEv = this.current.startEvent;
  16316. // if the touches change, set the new touches over the startEvent touches
  16317. // this because touchevents don't have all the touches on touchstart, or the
  16318. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16319. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16320. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16321. // extend 1 level deep to get the touchlist with the touch objects
  16322. startEv.touches = [];
  16323. for(var i=0,len=ev.touches.length; i<len; i++) {
  16324. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16325. }
  16326. }
  16327. var delta_time = ev.timeStamp - startEv.timeStamp,
  16328. delta_x = ev.center.pageX - startEv.center.pageX,
  16329. delta_y = ev.center.pageY - startEv.center.pageY,
  16330. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16331. Hammer.utils.extend(ev, {
  16332. deltaTime : delta_time,
  16333. deltaX : delta_x,
  16334. deltaY : delta_y,
  16335. velocityX : velocity.x,
  16336. velocityY : velocity.y,
  16337. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16338. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16339. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16340. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16341. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16342. startEvent : startEv
  16343. });
  16344. return ev;
  16345. },
  16346. /**
  16347. * register new gesture
  16348. * @param {Object} gesture object, see gestures.js for documentation
  16349. * @returns {Array} gestures
  16350. */
  16351. register: function register(gesture) {
  16352. // add an enable gesture options if there is no given
  16353. var options = gesture.defaults || {};
  16354. if(options[gesture.name] === undefined) {
  16355. options[gesture.name] = true;
  16356. }
  16357. // extend Hammer default options with the Hammer.gesture options
  16358. Hammer.utils.extend(Hammer.defaults, options, true);
  16359. // set its index
  16360. gesture.index = gesture.index || 1000;
  16361. // add Hammer.gesture to the list
  16362. this.gestures.push(gesture);
  16363. // sort the list by index
  16364. this.gestures.sort(function(a, b) {
  16365. if (a.index < b.index) {
  16366. return -1;
  16367. }
  16368. if (a.index > b.index) {
  16369. return 1;
  16370. }
  16371. return 0;
  16372. });
  16373. return this.gestures;
  16374. }
  16375. };
  16376. Hammer.gestures = Hammer.gestures || {};
  16377. /**
  16378. * Custom gestures
  16379. * ==============================
  16380. *
  16381. * Gesture object
  16382. * --------------------
  16383. * The object structure of a gesture:
  16384. *
  16385. * { name: 'mygesture',
  16386. * index: 1337,
  16387. * defaults: {
  16388. * mygesture_option: true
  16389. * }
  16390. * handler: function(type, ev, inst) {
  16391. * // trigger gesture event
  16392. * inst.trigger(this.name, ev);
  16393. * }
  16394. * }
  16395. * @param {String} name
  16396. * this should be the name of the gesture, lowercase
  16397. * it is also being used to disable/enable the gesture per instance config.
  16398. *
  16399. * @param {Number} [index=1000]
  16400. * the index of the gesture, where it is going to be in the stack of gestures detection
  16401. * like when you build an gesture that depends on the drag gesture, it is a good
  16402. * idea to place it after the index of the drag gesture.
  16403. *
  16404. * @param {Object} [defaults={}]
  16405. * the default settings of the gesture. these are added to the instance settings,
  16406. * and can be overruled per instance. you can also add the name of the gesture,
  16407. * but this is also added by default (and set to true).
  16408. *
  16409. * @param {Function} handler
  16410. * this handles the gesture detection of your custom gesture and receives the
  16411. * following arguments:
  16412. *
  16413. * @param {Object} eventData
  16414. * event data containing the following properties:
  16415. * timeStamp {Number} time the event occurred
  16416. * target {HTMLElement} target element
  16417. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16418. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16419. * center {Object} center position of the touches. contains pageX and pageY
  16420. * deltaTime {Number} the total time of the touches in the screen
  16421. * deltaX {Number} the delta on x axis we haved moved
  16422. * deltaY {Number} the delta on y axis we haved moved
  16423. * velocityX {Number} the velocity on the x
  16424. * velocityY {Number} the velocity on y
  16425. * angle {Number} the angle we are moving
  16426. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16427. * distance {Number} the distance we haved moved
  16428. * scale {Number} scaling of the touches, needs 2 touches
  16429. * rotation {Number} rotation of the touches, needs 2 touches *
  16430. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16431. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16432. * startEvent {Object} contains the same properties as above,
  16433. * but from the first touch. this is used to calculate
  16434. * distances, deltaTime, scaling etc
  16435. *
  16436. * @param {Hammer.Instance} inst
  16437. * the instance we are doing the detection for. you can get the options from
  16438. * the inst.options object and trigger the gesture event by calling inst.trigger
  16439. *
  16440. *
  16441. * Handle gestures
  16442. * --------------------
  16443. * inside the handler you can get/set Hammer.detection.current. This is the current
  16444. * detection session. It has the following properties
  16445. * @param {String} name
  16446. * contains the name of the gesture we have detected. it has not a real function,
  16447. * only to check in other gestures if something is detected.
  16448. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16449. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16450. *
  16451. * @readonly
  16452. * @param {Hammer.Instance} inst
  16453. * the instance we do the detection for
  16454. *
  16455. * @readonly
  16456. * @param {Object} startEvent
  16457. * contains the properties of the first gesture detection in this session.
  16458. * Used for calculations about timing, distance, etc.
  16459. *
  16460. * @readonly
  16461. * @param {Object} lastEvent
  16462. * contains all the properties of the last gesture detect in this session.
  16463. *
  16464. * after the gesture detection session has been completed (user has released the screen)
  16465. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16466. * this is usefull for gestures like doubletap, where you need to know if the
  16467. * previous gesture was a tap
  16468. *
  16469. * options that have been set by the instance can be received by calling inst.options
  16470. *
  16471. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16472. * The first param is the name of your gesture, the second the event argument
  16473. *
  16474. *
  16475. * Register gestures
  16476. * --------------------
  16477. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16478. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16479. * manually and pass your gesture object as a param
  16480. *
  16481. */
  16482. /**
  16483. * Hold
  16484. * Touch stays at the same place for x time
  16485. * @events hold
  16486. */
  16487. Hammer.gestures.Hold = {
  16488. name: 'hold',
  16489. index: 10,
  16490. defaults: {
  16491. hold_timeout : 500,
  16492. hold_threshold : 1
  16493. },
  16494. timer: null,
  16495. handler: function holdGesture(ev, inst) {
  16496. switch(ev.eventType) {
  16497. case Hammer.EVENT_START:
  16498. // clear any running timers
  16499. clearTimeout(this.timer);
  16500. // set the gesture so we can check in the timeout if it still is
  16501. Hammer.detection.current.name = this.name;
  16502. // set timer and if after the timeout it still is hold,
  16503. // we trigger the hold event
  16504. this.timer = setTimeout(function() {
  16505. if(Hammer.detection.current.name == 'hold') {
  16506. inst.trigger('hold', ev);
  16507. }
  16508. }, inst.options.hold_timeout);
  16509. break;
  16510. // when you move or end we clear the timer
  16511. case Hammer.EVENT_MOVE:
  16512. if(ev.distance > inst.options.hold_threshold) {
  16513. clearTimeout(this.timer);
  16514. }
  16515. break;
  16516. case Hammer.EVENT_END:
  16517. clearTimeout(this.timer);
  16518. break;
  16519. }
  16520. }
  16521. };
  16522. /**
  16523. * Tap/DoubleTap
  16524. * Quick touch at a place or double at the same place
  16525. * @events tap, doubletap
  16526. */
  16527. Hammer.gestures.Tap = {
  16528. name: 'tap',
  16529. index: 100,
  16530. defaults: {
  16531. tap_max_touchtime : 250,
  16532. tap_max_distance : 10,
  16533. tap_always : true,
  16534. doubletap_distance : 20,
  16535. doubletap_interval : 300
  16536. },
  16537. handler: function tapGesture(ev, inst) {
  16538. if(ev.eventType == Hammer.EVENT_END) {
  16539. // previous gesture, for the double tap since these are two different gesture detections
  16540. var prev = Hammer.detection.previous,
  16541. did_doubletap = false;
  16542. // when the touchtime is higher then the max touch time
  16543. // or when the moving distance is too much
  16544. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16545. ev.distance > inst.options.tap_max_distance) {
  16546. return;
  16547. }
  16548. // check if double tap
  16549. if(prev && prev.name == 'tap' &&
  16550. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16551. ev.distance < inst.options.doubletap_distance) {
  16552. inst.trigger('doubletap', ev);
  16553. did_doubletap = true;
  16554. }
  16555. // do a single tap
  16556. if(!did_doubletap || inst.options.tap_always) {
  16557. Hammer.detection.current.name = 'tap';
  16558. inst.trigger(Hammer.detection.current.name, ev);
  16559. }
  16560. }
  16561. }
  16562. };
  16563. /**
  16564. * Swipe
  16565. * triggers swipe events when the end velocity is above the threshold
  16566. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16567. */
  16568. Hammer.gestures.Swipe = {
  16569. name: 'swipe',
  16570. index: 40,
  16571. defaults: {
  16572. // set 0 for unlimited, but this can conflict with transform
  16573. swipe_max_touches : 1,
  16574. swipe_velocity : 0.7
  16575. },
  16576. handler: function swipeGesture(ev, inst) {
  16577. if(ev.eventType == Hammer.EVENT_END) {
  16578. // max touches
  16579. if(inst.options.swipe_max_touches > 0 &&
  16580. ev.touches.length > inst.options.swipe_max_touches) {
  16581. return;
  16582. }
  16583. // when the distance we moved is too small we skip this gesture
  16584. // or we can be already in dragging
  16585. if(ev.velocityX > inst.options.swipe_velocity ||
  16586. ev.velocityY > inst.options.swipe_velocity) {
  16587. // trigger swipe events
  16588. inst.trigger(this.name, ev);
  16589. inst.trigger(this.name + ev.direction, ev);
  16590. }
  16591. }
  16592. }
  16593. };
  16594. /**
  16595. * Drag
  16596. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16597. * moving left and right is a good practice. When all the drag events are blocking
  16598. * you disable scrolling on that area.
  16599. * @events drag, drapleft, dragright, dragup, dragdown
  16600. */
  16601. Hammer.gestures.Drag = {
  16602. name: 'drag',
  16603. index: 50,
  16604. defaults: {
  16605. drag_min_distance : 10,
  16606. // set 0 for unlimited, but this can conflict with transform
  16607. drag_max_touches : 1,
  16608. // prevent default browser behavior when dragging occurs
  16609. // be careful with it, it makes the element a blocking element
  16610. // when you are using the drag gesture, it is a good practice to set this true
  16611. drag_block_horizontal : false,
  16612. drag_block_vertical : false,
  16613. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  16614. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  16615. drag_lock_to_axis : false,
  16616. // drag lock only kicks in when distance > drag_lock_min_distance
  16617. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  16618. drag_lock_min_distance : 25
  16619. },
  16620. triggered: false,
  16621. handler: function dragGesture(ev, inst) {
  16622. // current gesture isnt drag, but dragged is true
  16623. // this means an other gesture is busy. now call dragend
  16624. if(Hammer.detection.current.name != this.name && this.triggered) {
  16625. inst.trigger(this.name +'end', ev);
  16626. this.triggered = false;
  16627. return;
  16628. }
  16629. // max touches
  16630. if(inst.options.drag_max_touches > 0 &&
  16631. ev.touches.length > inst.options.drag_max_touches) {
  16632. return;
  16633. }
  16634. switch(ev.eventType) {
  16635. case Hammer.EVENT_START:
  16636. this.triggered = false;
  16637. break;
  16638. case Hammer.EVENT_MOVE:
  16639. // when the distance we moved is too small we skip this gesture
  16640. // or we can be already in dragging
  16641. if(ev.distance < inst.options.drag_min_distance &&
  16642. Hammer.detection.current.name != this.name) {
  16643. return;
  16644. }
  16645. // we are dragging!
  16646. Hammer.detection.current.name = this.name;
  16647. // lock drag to axis?
  16648. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  16649. ev.drag_locked_to_axis = true;
  16650. }
  16651. var last_direction = Hammer.detection.current.lastEvent.direction;
  16652. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  16653. // keep direction on the axis that the drag gesture started on
  16654. if(Hammer.utils.isVertical(last_direction)) {
  16655. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16656. }
  16657. else {
  16658. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16659. }
  16660. }
  16661. // first time, trigger dragstart event
  16662. if(!this.triggered) {
  16663. inst.trigger(this.name +'start', ev);
  16664. this.triggered = true;
  16665. }
  16666. // trigger normal event
  16667. inst.trigger(this.name, ev);
  16668. // direction event, like dragdown
  16669. inst.trigger(this.name + ev.direction, ev);
  16670. // block the browser events
  16671. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  16672. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  16673. ev.preventDefault();
  16674. }
  16675. break;
  16676. case Hammer.EVENT_END:
  16677. // trigger dragend
  16678. if(this.triggered) {
  16679. inst.trigger(this.name +'end', ev);
  16680. }
  16681. this.triggered = false;
  16682. break;
  16683. }
  16684. }
  16685. };
  16686. /**
  16687. * Transform
  16688. * User want to scale or rotate with 2 fingers
  16689. * @events transform, pinch, pinchin, pinchout, rotate
  16690. */
  16691. Hammer.gestures.Transform = {
  16692. name: 'transform',
  16693. index: 45,
  16694. defaults: {
  16695. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  16696. transform_min_scale : 0.01,
  16697. // rotation in degrees
  16698. transform_min_rotation : 1,
  16699. // prevent default browser behavior when two touches are on the screen
  16700. // but it makes the element a blocking element
  16701. // when you are using the transform gesture, it is a good practice to set this true
  16702. transform_always_block : false
  16703. },
  16704. triggered: false,
  16705. handler: function transformGesture(ev, inst) {
  16706. // current gesture isnt drag, but dragged is true
  16707. // this means an other gesture is busy. now call dragend
  16708. if(Hammer.detection.current.name != this.name && this.triggered) {
  16709. inst.trigger(this.name +'end', ev);
  16710. this.triggered = false;
  16711. return;
  16712. }
  16713. // atleast multitouch
  16714. if(ev.touches.length < 2) {
  16715. return;
  16716. }
  16717. // prevent default when two fingers are on the screen
  16718. if(inst.options.transform_always_block) {
  16719. ev.preventDefault();
  16720. }
  16721. switch(ev.eventType) {
  16722. case Hammer.EVENT_START:
  16723. this.triggered = false;
  16724. break;
  16725. case Hammer.EVENT_MOVE:
  16726. var scale_threshold = Math.abs(1-ev.scale);
  16727. var rotation_threshold = Math.abs(ev.rotation);
  16728. // when the distance we moved is too small we skip this gesture
  16729. // or we can be already in dragging
  16730. if(scale_threshold < inst.options.transform_min_scale &&
  16731. rotation_threshold < inst.options.transform_min_rotation) {
  16732. return;
  16733. }
  16734. // we are transforming!
  16735. Hammer.detection.current.name = this.name;
  16736. // first time, trigger dragstart event
  16737. if(!this.triggered) {
  16738. inst.trigger(this.name +'start', ev);
  16739. this.triggered = true;
  16740. }
  16741. inst.trigger(this.name, ev); // basic transform event
  16742. // trigger rotate event
  16743. if(rotation_threshold > inst.options.transform_min_rotation) {
  16744. inst.trigger('rotate', ev);
  16745. }
  16746. // trigger pinch event
  16747. if(scale_threshold > inst.options.transform_min_scale) {
  16748. inst.trigger('pinch', ev);
  16749. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  16750. }
  16751. break;
  16752. case Hammer.EVENT_END:
  16753. // trigger dragend
  16754. if(this.triggered) {
  16755. inst.trigger(this.name +'end', ev);
  16756. }
  16757. this.triggered = false;
  16758. break;
  16759. }
  16760. }
  16761. };
  16762. /**
  16763. * Touch
  16764. * Called as first, tells the user has touched the screen
  16765. * @events touch
  16766. */
  16767. Hammer.gestures.Touch = {
  16768. name: 'touch',
  16769. index: -Infinity,
  16770. defaults: {
  16771. // call preventDefault at touchstart, and makes the element blocking by
  16772. // disabling the scrolling of the page, but it improves gestures like
  16773. // transforming and dragging.
  16774. // be careful with using this, it can be very annoying for users to be stuck
  16775. // on the page
  16776. prevent_default: false,
  16777. // disable mouse events, so only touch (or pen!) input triggers events
  16778. prevent_mouseevents: false
  16779. },
  16780. handler: function touchGesture(ev, inst) {
  16781. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  16782. ev.stopDetect();
  16783. return;
  16784. }
  16785. if(inst.options.prevent_default) {
  16786. ev.preventDefault();
  16787. }
  16788. if(ev.eventType == Hammer.EVENT_START) {
  16789. inst.trigger(this.name, ev);
  16790. }
  16791. }
  16792. };
  16793. /**
  16794. * Release
  16795. * Called as last, tells the user has released the screen
  16796. * @events release
  16797. */
  16798. Hammer.gestures.Release = {
  16799. name: 'release',
  16800. index: Infinity,
  16801. handler: function releaseGesture(ev, inst) {
  16802. if(ev.eventType == Hammer.EVENT_END) {
  16803. inst.trigger(this.name, ev);
  16804. }
  16805. }
  16806. };
  16807. // node export
  16808. if(typeof module === 'object' && typeof module.exports === 'object'){
  16809. module.exports = Hammer;
  16810. }
  16811. // just window export
  16812. else {
  16813. window.Hammer = Hammer;
  16814. // requireJS module definition
  16815. if(typeof window.define === 'function' && window.define.amd) {
  16816. window.define('hammer', [], function() {
  16817. return Hammer;
  16818. });
  16819. }
  16820. }
  16821. })(this);
  16822. },{}],4:[function(require,module,exports){
  16823. //! moment.js
  16824. //! version : 2.5.1
  16825. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  16826. //! license : MIT
  16827. //! momentjs.com
  16828. (function (undefined) {
  16829. /************************************
  16830. Constants
  16831. ************************************/
  16832. var moment,
  16833. VERSION = "2.5.1",
  16834. global = this,
  16835. round = Math.round,
  16836. i,
  16837. YEAR = 0,
  16838. MONTH = 1,
  16839. DATE = 2,
  16840. HOUR = 3,
  16841. MINUTE = 4,
  16842. SECOND = 5,
  16843. MILLISECOND = 6,
  16844. // internal storage for language config files
  16845. languages = {},
  16846. // moment internal properties
  16847. momentProperties = {
  16848. _isAMomentObject: null,
  16849. _i : null,
  16850. _f : null,
  16851. _l : null,
  16852. _strict : null,
  16853. _isUTC : null,
  16854. _offset : null, // optional. Combine with _isUTC
  16855. _pf : null,
  16856. _lang : null // optional
  16857. },
  16858. // check for nodeJS
  16859. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  16860. // ASP.NET json date format regex
  16861. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  16862. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  16863. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  16864. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  16865. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  16866. // format tokens
  16867. 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,
  16868. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  16869. // parsing token regexes
  16870. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  16871. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  16872. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  16873. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  16874. parseTokenDigits = /\d+/, // nonzero number of digits
  16875. 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.
  16876. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  16877. parseTokenT = /T/i, // T (ISO separator)
  16878. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  16879. //strict parsing regexes
  16880. parseTokenOneDigit = /\d/, // 0 - 9
  16881. parseTokenTwoDigits = /\d\d/, // 00 - 99
  16882. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  16883. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  16884. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  16885. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  16886. // iso 8601 regex
  16887. // 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)
  16888. 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)?)?$/,
  16889. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  16890. isoDates = [
  16891. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  16892. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  16893. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  16894. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  16895. ['YYYY-DDD', /\d{4}-\d{3}/]
  16896. ],
  16897. // iso time formats and regexes
  16898. isoTimes = [
  16899. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  16900. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  16901. ['HH:mm', /(T| )\d\d:\d\d/],
  16902. ['HH', /(T| )\d\d/]
  16903. ],
  16904. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  16905. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  16906. // getter and setter names
  16907. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  16908. unitMillisecondFactors = {
  16909. 'Milliseconds' : 1,
  16910. 'Seconds' : 1e3,
  16911. 'Minutes' : 6e4,
  16912. 'Hours' : 36e5,
  16913. 'Days' : 864e5,
  16914. 'Months' : 2592e6,
  16915. 'Years' : 31536e6
  16916. },
  16917. unitAliases = {
  16918. ms : 'millisecond',
  16919. s : 'second',
  16920. m : 'minute',
  16921. h : 'hour',
  16922. d : 'day',
  16923. D : 'date',
  16924. w : 'week',
  16925. W : 'isoWeek',
  16926. M : 'month',
  16927. y : 'year',
  16928. DDD : 'dayOfYear',
  16929. e : 'weekday',
  16930. E : 'isoWeekday',
  16931. gg: 'weekYear',
  16932. GG: 'isoWeekYear'
  16933. },
  16934. camelFunctions = {
  16935. dayofyear : 'dayOfYear',
  16936. isoweekday : 'isoWeekday',
  16937. isoweek : 'isoWeek',
  16938. weekyear : 'weekYear',
  16939. isoweekyear : 'isoWeekYear'
  16940. },
  16941. // format function strings
  16942. formatFunctions = {},
  16943. // tokens to ordinalize and pad
  16944. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  16945. paddedTokens = 'M D H h m s w W'.split(' '),
  16946. formatTokenFunctions = {
  16947. M : function () {
  16948. return this.month() + 1;
  16949. },
  16950. MMM : function (format) {
  16951. return this.lang().monthsShort(this, format);
  16952. },
  16953. MMMM : function (format) {
  16954. return this.lang().months(this, format);
  16955. },
  16956. D : function () {
  16957. return this.date();
  16958. },
  16959. DDD : function () {
  16960. return this.dayOfYear();
  16961. },
  16962. d : function () {
  16963. return this.day();
  16964. },
  16965. dd : function (format) {
  16966. return this.lang().weekdaysMin(this, format);
  16967. },
  16968. ddd : function (format) {
  16969. return this.lang().weekdaysShort(this, format);
  16970. },
  16971. dddd : function (format) {
  16972. return this.lang().weekdays(this, format);
  16973. },
  16974. w : function () {
  16975. return this.week();
  16976. },
  16977. W : function () {
  16978. return this.isoWeek();
  16979. },
  16980. YY : function () {
  16981. return leftZeroFill(this.year() % 100, 2);
  16982. },
  16983. YYYY : function () {
  16984. return leftZeroFill(this.year(), 4);
  16985. },
  16986. YYYYY : function () {
  16987. return leftZeroFill(this.year(), 5);
  16988. },
  16989. YYYYYY : function () {
  16990. var y = this.year(), sign = y >= 0 ? '+' : '-';
  16991. return sign + leftZeroFill(Math.abs(y), 6);
  16992. },
  16993. gg : function () {
  16994. return leftZeroFill(this.weekYear() % 100, 2);
  16995. },
  16996. gggg : function () {
  16997. return leftZeroFill(this.weekYear(), 4);
  16998. },
  16999. ggggg : function () {
  17000. return leftZeroFill(this.weekYear(), 5);
  17001. },
  17002. GG : function () {
  17003. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17004. },
  17005. GGGG : function () {
  17006. return leftZeroFill(this.isoWeekYear(), 4);
  17007. },
  17008. GGGGG : function () {
  17009. return leftZeroFill(this.isoWeekYear(), 5);
  17010. },
  17011. e : function () {
  17012. return this.weekday();
  17013. },
  17014. E : function () {
  17015. return this.isoWeekday();
  17016. },
  17017. a : function () {
  17018. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17019. },
  17020. A : function () {
  17021. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17022. },
  17023. H : function () {
  17024. return this.hours();
  17025. },
  17026. h : function () {
  17027. return this.hours() % 12 || 12;
  17028. },
  17029. m : function () {
  17030. return this.minutes();
  17031. },
  17032. s : function () {
  17033. return this.seconds();
  17034. },
  17035. S : function () {
  17036. return toInt(this.milliseconds() / 100);
  17037. },
  17038. SS : function () {
  17039. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17040. },
  17041. SSS : function () {
  17042. return leftZeroFill(this.milliseconds(), 3);
  17043. },
  17044. SSSS : function () {
  17045. return leftZeroFill(this.milliseconds(), 3);
  17046. },
  17047. Z : function () {
  17048. var a = -this.zone(),
  17049. b = "+";
  17050. if (a < 0) {
  17051. a = -a;
  17052. b = "-";
  17053. }
  17054. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  17055. },
  17056. ZZ : function () {
  17057. var a = -this.zone(),
  17058. b = "+";
  17059. if (a < 0) {
  17060. a = -a;
  17061. b = "-";
  17062. }
  17063. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  17064. },
  17065. z : function () {
  17066. return this.zoneAbbr();
  17067. },
  17068. zz : function () {
  17069. return this.zoneName();
  17070. },
  17071. X : function () {
  17072. return this.unix();
  17073. },
  17074. Q : function () {
  17075. return this.quarter();
  17076. }
  17077. },
  17078. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  17079. function defaultParsingFlags() {
  17080. // We need to deep clone this object, and es5 standard is not very
  17081. // helpful.
  17082. return {
  17083. empty : false,
  17084. unusedTokens : [],
  17085. unusedInput : [],
  17086. overflow : -2,
  17087. charsLeftOver : 0,
  17088. nullInput : false,
  17089. invalidMonth : null,
  17090. invalidFormat : false,
  17091. userInvalidated : false,
  17092. iso: false
  17093. };
  17094. }
  17095. function padToken(func, count) {
  17096. return function (a) {
  17097. return leftZeroFill(func.call(this, a), count);
  17098. };
  17099. }
  17100. function ordinalizeToken(func, period) {
  17101. return function (a) {
  17102. return this.lang().ordinal(func.call(this, a), period);
  17103. };
  17104. }
  17105. while (ordinalizeTokens.length) {
  17106. i = ordinalizeTokens.pop();
  17107. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  17108. }
  17109. while (paddedTokens.length) {
  17110. i = paddedTokens.pop();
  17111. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  17112. }
  17113. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  17114. /************************************
  17115. Constructors
  17116. ************************************/
  17117. function Language() {
  17118. }
  17119. // Moment prototype object
  17120. function Moment(config) {
  17121. checkOverflow(config);
  17122. extend(this, config);
  17123. }
  17124. // Duration Constructor
  17125. function Duration(duration) {
  17126. var normalizedInput = normalizeObjectUnits(duration),
  17127. years = normalizedInput.year || 0,
  17128. months = normalizedInput.month || 0,
  17129. weeks = normalizedInput.week || 0,
  17130. days = normalizedInput.day || 0,
  17131. hours = normalizedInput.hour || 0,
  17132. minutes = normalizedInput.minute || 0,
  17133. seconds = normalizedInput.second || 0,
  17134. milliseconds = normalizedInput.millisecond || 0;
  17135. // representation for dateAddRemove
  17136. this._milliseconds = +milliseconds +
  17137. seconds * 1e3 + // 1000
  17138. minutes * 6e4 + // 1000 * 60
  17139. hours * 36e5; // 1000 * 60 * 60
  17140. // Because of dateAddRemove treats 24 hours as different from a
  17141. // day when working around DST, we need to store them separately
  17142. this._days = +days +
  17143. weeks * 7;
  17144. // It is impossible translate months into days without knowing
  17145. // which months you are are talking about, so we have to store
  17146. // it separately.
  17147. this._months = +months +
  17148. years * 12;
  17149. this._data = {};
  17150. this._bubble();
  17151. }
  17152. /************************************
  17153. Helpers
  17154. ************************************/
  17155. function extend(a, b) {
  17156. for (var i in b) {
  17157. if (b.hasOwnProperty(i)) {
  17158. a[i] = b[i];
  17159. }
  17160. }
  17161. if (b.hasOwnProperty("toString")) {
  17162. a.toString = b.toString;
  17163. }
  17164. if (b.hasOwnProperty("valueOf")) {
  17165. a.valueOf = b.valueOf;
  17166. }
  17167. return a;
  17168. }
  17169. function cloneMoment(m) {
  17170. var result = {}, i;
  17171. for (i in m) {
  17172. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17173. result[i] = m[i];
  17174. }
  17175. }
  17176. return result;
  17177. }
  17178. function absRound(number) {
  17179. if (number < 0) {
  17180. return Math.ceil(number);
  17181. } else {
  17182. return Math.floor(number);
  17183. }
  17184. }
  17185. // left zero fill a number
  17186. // see http://jsperf.com/left-zero-filling for performance comparison
  17187. function leftZeroFill(number, targetLength, forceSign) {
  17188. var output = '' + Math.abs(number),
  17189. sign = number >= 0;
  17190. while (output.length < targetLength) {
  17191. output = '0' + output;
  17192. }
  17193. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17194. }
  17195. // helper function for _.addTime and _.subtractTime
  17196. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  17197. var milliseconds = duration._milliseconds,
  17198. days = duration._days,
  17199. months = duration._months,
  17200. minutes,
  17201. hours;
  17202. if (milliseconds) {
  17203. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17204. }
  17205. // store the minutes and hours so we can restore them
  17206. if (days || months) {
  17207. minutes = mom.minute();
  17208. hours = mom.hour();
  17209. }
  17210. if (days) {
  17211. mom.date(mom.date() + days * isAdding);
  17212. }
  17213. if (months) {
  17214. mom.month(mom.month() + months * isAdding);
  17215. }
  17216. if (milliseconds && !ignoreUpdateOffset) {
  17217. moment.updateOffset(mom);
  17218. }
  17219. // restore the minutes and hours after possibly changing dst
  17220. if (days || months) {
  17221. mom.minute(minutes);
  17222. mom.hour(hours);
  17223. }
  17224. }
  17225. // check if is an array
  17226. function isArray(input) {
  17227. return Object.prototype.toString.call(input) === '[object Array]';
  17228. }
  17229. function isDate(input) {
  17230. return Object.prototype.toString.call(input) === '[object Date]' ||
  17231. input instanceof Date;
  17232. }
  17233. // compare two arrays, return the number of differences
  17234. function compareArrays(array1, array2, dontConvert) {
  17235. var len = Math.min(array1.length, array2.length),
  17236. lengthDiff = Math.abs(array1.length - array2.length),
  17237. diffs = 0,
  17238. i;
  17239. for (i = 0; i < len; i++) {
  17240. if ((dontConvert && array1[i] !== array2[i]) ||
  17241. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17242. diffs++;
  17243. }
  17244. }
  17245. return diffs + lengthDiff;
  17246. }
  17247. function normalizeUnits(units) {
  17248. if (units) {
  17249. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17250. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17251. }
  17252. return units;
  17253. }
  17254. function normalizeObjectUnits(inputObject) {
  17255. var normalizedInput = {},
  17256. normalizedProp,
  17257. prop;
  17258. for (prop in inputObject) {
  17259. if (inputObject.hasOwnProperty(prop)) {
  17260. normalizedProp = normalizeUnits(prop);
  17261. if (normalizedProp) {
  17262. normalizedInput[normalizedProp] = inputObject[prop];
  17263. }
  17264. }
  17265. }
  17266. return normalizedInput;
  17267. }
  17268. function makeList(field) {
  17269. var count, setter;
  17270. if (field.indexOf('week') === 0) {
  17271. count = 7;
  17272. setter = 'day';
  17273. }
  17274. else if (field.indexOf('month') === 0) {
  17275. count = 12;
  17276. setter = 'month';
  17277. }
  17278. else {
  17279. return;
  17280. }
  17281. moment[field] = function (format, index) {
  17282. var i, getter,
  17283. method = moment.fn._lang[field],
  17284. results = [];
  17285. if (typeof format === 'number') {
  17286. index = format;
  17287. format = undefined;
  17288. }
  17289. getter = function (i) {
  17290. var m = moment().utc().set(setter, i);
  17291. return method.call(moment.fn._lang, m, format || '');
  17292. };
  17293. if (index != null) {
  17294. return getter(index);
  17295. }
  17296. else {
  17297. for (i = 0; i < count; i++) {
  17298. results.push(getter(i));
  17299. }
  17300. return results;
  17301. }
  17302. };
  17303. }
  17304. function toInt(argumentForCoercion) {
  17305. var coercedNumber = +argumentForCoercion,
  17306. value = 0;
  17307. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17308. if (coercedNumber >= 0) {
  17309. value = Math.floor(coercedNumber);
  17310. } else {
  17311. value = Math.ceil(coercedNumber);
  17312. }
  17313. }
  17314. return value;
  17315. }
  17316. function daysInMonth(year, month) {
  17317. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17318. }
  17319. function daysInYear(year) {
  17320. return isLeapYear(year) ? 366 : 365;
  17321. }
  17322. function isLeapYear(year) {
  17323. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17324. }
  17325. function checkOverflow(m) {
  17326. var overflow;
  17327. if (m._a && m._pf.overflow === -2) {
  17328. overflow =
  17329. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17330. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17331. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17332. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17333. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17334. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17335. -1;
  17336. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17337. overflow = DATE;
  17338. }
  17339. m._pf.overflow = overflow;
  17340. }
  17341. }
  17342. function isValid(m) {
  17343. if (m._isValid == null) {
  17344. m._isValid = !isNaN(m._d.getTime()) &&
  17345. m._pf.overflow < 0 &&
  17346. !m._pf.empty &&
  17347. !m._pf.invalidMonth &&
  17348. !m._pf.nullInput &&
  17349. !m._pf.invalidFormat &&
  17350. !m._pf.userInvalidated;
  17351. if (m._strict) {
  17352. m._isValid = m._isValid &&
  17353. m._pf.charsLeftOver === 0 &&
  17354. m._pf.unusedTokens.length === 0;
  17355. }
  17356. }
  17357. return m._isValid;
  17358. }
  17359. function normalizeLanguage(key) {
  17360. return key ? key.toLowerCase().replace('_', '-') : key;
  17361. }
  17362. // Return a moment from input, that is local/utc/zone equivalent to model.
  17363. function makeAs(input, model) {
  17364. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17365. moment(input).local();
  17366. }
  17367. /************************************
  17368. Languages
  17369. ************************************/
  17370. extend(Language.prototype, {
  17371. set : function (config) {
  17372. var prop, i;
  17373. for (i in config) {
  17374. prop = config[i];
  17375. if (typeof prop === 'function') {
  17376. this[i] = prop;
  17377. } else {
  17378. this['_' + i] = prop;
  17379. }
  17380. }
  17381. },
  17382. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17383. months : function (m) {
  17384. return this._months[m.month()];
  17385. },
  17386. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17387. monthsShort : function (m) {
  17388. return this._monthsShort[m.month()];
  17389. },
  17390. monthsParse : function (monthName) {
  17391. var i, mom, regex;
  17392. if (!this._monthsParse) {
  17393. this._monthsParse = [];
  17394. }
  17395. for (i = 0; i < 12; i++) {
  17396. // make the regex if we don't have it already
  17397. if (!this._monthsParse[i]) {
  17398. mom = moment.utc([2000, i]);
  17399. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17400. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17401. }
  17402. // test the regex
  17403. if (this._monthsParse[i].test(monthName)) {
  17404. return i;
  17405. }
  17406. }
  17407. },
  17408. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17409. weekdays : function (m) {
  17410. return this._weekdays[m.day()];
  17411. },
  17412. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17413. weekdaysShort : function (m) {
  17414. return this._weekdaysShort[m.day()];
  17415. },
  17416. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17417. weekdaysMin : function (m) {
  17418. return this._weekdaysMin[m.day()];
  17419. },
  17420. weekdaysParse : function (weekdayName) {
  17421. var i, mom, regex;
  17422. if (!this._weekdaysParse) {
  17423. this._weekdaysParse = [];
  17424. }
  17425. for (i = 0; i < 7; i++) {
  17426. // make the regex if we don't have it already
  17427. if (!this._weekdaysParse[i]) {
  17428. mom = moment([2000, 1]).day(i);
  17429. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17430. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17431. }
  17432. // test the regex
  17433. if (this._weekdaysParse[i].test(weekdayName)) {
  17434. return i;
  17435. }
  17436. }
  17437. },
  17438. _longDateFormat : {
  17439. LT : "h:mm A",
  17440. L : "MM/DD/YYYY",
  17441. LL : "MMMM D YYYY",
  17442. LLL : "MMMM D YYYY LT",
  17443. LLLL : "dddd, MMMM D YYYY LT"
  17444. },
  17445. longDateFormat : function (key) {
  17446. var output = this._longDateFormat[key];
  17447. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17448. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17449. return val.slice(1);
  17450. });
  17451. this._longDateFormat[key] = output;
  17452. }
  17453. return output;
  17454. },
  17455. isPM : function (input) {
  17456. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17457. // Using charAt should be more compatible.
  17458. return ((input + '').toLowerCase().charAt(0) === 'p');
  17459. },
  17460. _meridiemParse : /[ap]\.?m?\.?/i,
  17461. meridiem : function (hours, minutes, isLower) {
  17462. if (hours > 11) {
  17463. return isLower ? 'pm' : 'PM';
  17464. } else {
  17465. return isLower ? 'am' : 'AM';
  17466. }
  17467. },
  17468. _calendar : {
  17469. sameDay : '[Today at] LT',
  17470. nextDay : '[Tomorrow at] LT',
  17471. nextWeek : 'dddd [at] LT',
  17472. lastDay : '[Yesterday at] LT',
  17473. lastWeek : '[Last] dddd [at] LT',
  17474. sameElse : 'L'
  17475. },
  17476. calendar : function (key, mom) {
  17477. var output = this._calendar[key];
  17478. return typeof output === 'function' ? output.apply(mom) : output;
  17479. },
  17480. _relativeTime : {
  17481. future : "in %s",
  17482. past : "%s ago",
  17483. s : "a few seconds",
  17484. m : "a minute",
  17485. mm : "%d minutes",
  17486. h : "an hour",
  17487. hh : "%d hours",
  17488. d : "a day",
  17489. dd : "%d days",
  17490. M : "a month",
  17491. MM : "%d months",
  17492. y : "a year",
  17493. yy : "%d years"
  17494. },
  17495. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17496. var output = this._relativeTime[string];
  17497. return (typeof output === 'function') ?
  17498. output(number, withoutSuffix, string, isFuture) :
  17499. output.replace(/%d/i, number);
  17500. },
  17501. pastFuture : function (diff, output) {
  17502. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17503. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17504. },
  17505. ordinal : function (number) {
  17506. return this._ordinal.replace("%d", number);
  17507. },
  17508. _ordinal : "%d",
  17509. preparse : function (string) {
  17510. return string;
  17511. },
  17512. postformat : function (string) {
  17513. return string;
  17514. },
  17515. week : function (mom) {
  17516. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17517. },
  17518. _week : {
  17519. dow : 0, // Sunday is the first day of the week.
  17520. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17521. },
  17522. _invalidDate: 'Invalid date',
  17523. invalidDate: function () {
  17524. return this._invalidDate;
  17525. }
  17526. });
  17527. // Loads a language definition into the `languages` cache. The function
  17528. // takes a key and optionally values. If not in the browser and no values
  17529. // are provided, it will load the language file module. As a convenience,
  17530. // this function also returns the language values.
  17531. function loadLang(key, values) {
  17532. values.abbr = key;
  17533. if (!languages[key]) {
  17534. languages[key] = new Language();
  17535. }
  17536. languages[key].set(values);
  17537. return languages[key];
  17538. }
  17539. // Remove a language from the `languages` cache. Mostly useful in tests.
  17540. function unloadLang(key) {
  17541. delete languages[key];
  17542. }
  17543. // Determines which language definition to use and returns it.
  17544. //
  17545. // With no parameters, it will return the global language. If you
  17546. // pass in a language key, such as 'en', it will return the
  17547. // definition for 'en', so long as 'en' has already been loaded using
  17548. // moment.lang.
  17549. function getLangDefinition(key) {
  17550. var i = 0, j, lang, next, split,
  17551. get = function (k) {
  17552. if (!languages[k] && hasModule) {
  17553. try {
  17554. require('./lang/' + k);
  17555. } catch (e) { }
  17556. }
  17557. return languages[k];
  17558. };
  17559. if (!key) {
  17560. return moment.fn._lang;
  17561. }
  17562. if (!isArray(key)) {
  17563. //short-circuit everything else
  17564. lang = get(key);
  17565. if (lang) {
  17566. return lang;
  17567. }
  17568. key = [key];
  17569. }
  17570. //pick the language from the array
  17571. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17572. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17573. while (i < key.length) {
  17574. split = normalizeLanguage(key[i]).split('-');
  17575. j = split.length;
  17576. next = normalizeLanguage(key[i + 1]);
  17577. next = next ? next.split('-') : null;
  17578. while (j > 0) {
  17579. lang = get(split.slice(0, j).join('-'));
  17580. if (lang) {
  17581. return lang;
  17582. }
  17583. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17584. //the next array item is better than a shallower substring of this one
  17585. break;
  17586. }
  17587. j--;
  17588. }
  17589. i++;
  17590. }
  17591. return moment.fn._lang;
  17592. }
  17593. /************************************
  17594. Formatting
  17595. ************************************/
  17596. function removeFormattingTokens(input) {
  17597. if (input.match(/\[[\s\S]/)) {
  17598. return input.replace(/^\[|\]$/g, "");
  17599. }
  17600. return input.replace(/\\/g, "");
  17601. }
  17602. function makeFormatFunction(format) {
  17603. var array = format.match(formattingTokens), i, length;
  17604. for (i = 0, length = array.length; i < length; i++) {
  17605. if (formatTokenFunctions[array[i]]) {
  17606. array[i] = formatTokenFunctions[array[i]];
  17607. } else {
  17608. array[i] = removeFormattingTokens(array[i]);
  17609. }
  17610. }
  17611. return function (mom) {
  17612. var output = "";
  17613. for (i = 0; i < length; i++) {
  17614. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  17615. }
  17616. return output;
  17617. };
  17618. }
  17619. // format date using native date object
  17620. function formatMoment(m, format) {
  17621. if (!m.isValid()) {
  17622. return m.lang().invalidDate();
  17623. }
  17624. format = expandFormat(format, m.lang());
  17625. if (!formatFunctions[format]) {
  17626. formatFunctions[format] = makeFormatFunction(format);
  17627. }
  17628. return formatFunctions[format](m);
  17629. }
  17630. function expandFormat(format, lang) {
  17631. var i = 5;
  17632. function replaceLongDateFormatTokens(input) {
  17633. return lang.longDateFormat(input) || input;
  17634. }
  17635. localFormattingTokens.lastIndex = 0;
  17636. while (i >= 0 && localFormattingTokens.test(format)) {
  17637. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  17638. localFormattingTokens.lastIndex = 0;
  17639. i -= 1;
  17640. }
  17641. return format;
  17642. }
  17643. /************************************
  17644. Parsing
  17645. ************************************/
  17646. // get the regex to find the next token
  17647. function getParseRegexForToken(token, config) {
  17648. var a, strict = config._strict;
  17649. switch (token) {
  17650. case 'DDDD':
  17651. return parseTokenThreeDigits;
  17652. case 'YYYY':
  17653. case 'GGGG':
  17654. case 'gggg':
  17655. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  17656. case 'Y':
  17657. case 'G':
  17658. case 'g':
  17659. return parseTokenSignedNumber;
  17660. case 'YYYYYY':
  17661. case 'YYYYY':
  17662. case 'GGGGG':
  17663. case 'ggggg':
  17664. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  17665. case 'S':
  17666. if (strict) { return parseTokenOneDigit; }
  17667. /* falls through */
  17668. case 'SS':
  17669. if (strict) { return parseTokenTwoDigits; }
  17670. /* falls through */
  17671. case 'SSS':
  17672. if (strict) { return parseTokenThreeDigits; }
  17673. /* falls through */
  17674. case 'DDD':
  17675. return parseTokenOneToThreeDigits;
  17676. case 'MMM':
  17677. case 'MMMM':
  17678. case 'dd':
  17679. case 'ddd':
  17680. case 'dddd':
  17681. return parseTokenWord;
  17682. case 'a':
  17683. case 'A':
  17684. return getLangDefinition(config._l)._meridiemParse;
  17685. case 'X':
  17686. return parseTokenTimestampMs;
  17687. case 'Z':
  17688. case 'ZZ':
  17689. return parseTokenTimezone;
  17690. case 'T':
  17691. return parseTokenT;
  17692. case 'SSSS':
  17693. return parseTokenDigits;
  17694. case 'MM':
  17695. case 'DD':
  17696. case 'YY':
  17697. case 'GG':
  17698. case 'gg':
  17699. case 'HH':
  17700. case 'hh':
  17701. case 'mm':
  17702. case 'ss':
  17703. case 'ww':
  17704. case 'WW':
  17705. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  17706. case 'M':
  17707. case 'D':
  17708. case 'd':
  17709. case 'H':
  17710. case 'h':
  17711. case 'm':
  17712. case 's':
  17713. case 'w':
  17714. case 'W':
  17715. case 'e':
  17716. case 'E':
  17717. return parseTokenOneOrTwoDigits;
  17718. default :
  17719. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  17720. return a;
  17721. }
  17722. }
  17723. function timezoneMinutesFromString(string) {
  17724. string = string || "";
  17725. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  17726. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  17727. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  17728. minutes = +(parts[1] * 60) + toInt(parts[2]);
  17729. return parts[0] === '+' ? -minutes : minutes;
  17730. }
  17731. // function to convert string input to date
  17732. function addTimeToArrayFromToken(token, input, config) {
  17733. var a, datePartArray = config._a;
  17734. switch (token) {
  17735. // MONTH
  17736. case 'M' : // fall through to MM
  17737. case 'MM' :
  17738. if (input != null) {
  17739. datePartArray[MONTH] = toInt(input) - 1;
  17740. }
  17741. break;
  17742. case 'MMM' : // fall through to MMMM
  17743. case 'MMMM' :
  17744. a = getLangDefinition(config._l).monthsParse(input);
  17745. // if we didn't find a month name, mark the date as invalid.
  17746. if (a != null) {
  17747. datePartArray[MONTH] = a;
  17748. } else {
  17749. config._pf.invalidMonth = input;
  17750. }
  17751. break;
  17752. // DAY OF MONTH
  17753. case 'D' : // fall through to DD
  17754. case 'DD' :
  17755. if (input != null) {
  17756. datePartArray[DATE] = toInt(input);
  17757. }
  17758. break;
  17759. // DAY OF YEAR
  17760. case 'DDD' : // fall through to DDDD
  17761. case 'DDDD' :
  17762. if (input != null) {
  17763. config._dayOfYear = toInt(input);
  17764. }
  17765. break;
  17766. // YEAR
  17767. case 'YY' :
  17768. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  17769. break;
  17770. case 'YYYY' :
  17771. case 'YYYYY' :
  17772. case 'YYYYYY' :
  17773. datePartArray[YEAR] = toInt(input);
  17774. break;
  17775. // AM / PM
  17776. case 'a' : // fall through to A
  17777. case 'A' :
  17778. config._isPm = getLangDefinition(config._l).isPM(input);
  17779. break;
  17780. // 24 HOUR
  17781. case 'H' : // fall through to hh
  17782. case 'HH' : // fall through to hh
  17783. case 'h' : // fall through to hh
  17784. case 'hh' :
  17785. datePartArray[HOUR] = toInt(input);
  17786. break;
  17787. // MINUTE
  17788. case 'm' : // fall through to mm
  17789. case 'mm' :
  17790. datePartArray[MINUTE] = toInt(input);
  17791. break;
  17792. // SECOND
  17793. case 's' : // fall through to ss
  17794. case 'ss' :
  17795. datePartArray[SECOND] = toInt(input);
  17796. break;
  17797. // MILLISECOND
  17798. case 'S' :
  17799. case 'SS' :
  17800. case 'SSS' :
  17801. case 'SSSS' :
  17802. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  17803. break;
  17804. // UNIX TIMESTAMP WITH MS
  17805. case 'X':
  17806. config._d = new Date(parseFloat(input) * 1000);
  17807. break;
  17808. // TIMEZONE
  17809. case 'Z' : // fall through to ZZ
  17810. case 'ZZ' :
  17811. config._useUTC = true;
  17812. config._tzm = timezoneMinutesFromString(input);
  17813. break;
  17814. case 'w':
  17815. case 'ww':
  17816. case 'W':
  17817. case 'WW':
  17818. case 'd':
  17819. case 'dd':
  17820. case 'ddd':
  17821. case 'dddd':
  17822. case 'e':
  17823. case 'E':
  17824. token = token.substr(0, 1);
  17825. /* falls through */
  17826. case 'gg':
  17827. case 'gggg':
  17828. case 'GG':
  17829. case 'GGGG':
  17830. case 'GGGGG':
  17831. token = token.substr(0, 2);
  17832. if (input) {
  17833. config._w = config._w || {};
  17834. config._w[token] = input;
  17835. }
  17836. break;
  17837. }
  17838. }
  17839. // convert an array to a date.
  17840. // the array should mirror the parameters below
  17841. // note: all values past the year are optional and will default to the lowest possible value.
  17842. // [year, month, day , hour, minute, second, millisecond]
  17843. function dateFromConfig(config) {
  17844. var i, date, input = [], currentDate,
  17845. yearToUse, fixYear, w, temp, lang, weekday, week;
  17846. if (config._d) {
  17847. return;
  17848. }
  17849. currentDate = currentDateArray(config);
  17850. //compute day of the year from weeks and weekdays
  17851. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  17852. fixYear = function (val) {
  17853. var int_val = parseInt(val, 10);
  17854. return val ?
  17855. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  17856. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  17857. };
  17858. w = config._w;
  17859. if (w.GG != null || w.W != null || w.E != null) {
  17860. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  17861. }
  17862. else {
  17863. lang = getLangDefinition(config._l);
  17864. weekday = w.d != null ? parseWeekday(w.d, lang) :
  17865. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  17866. week = parseInt(w.w, 10) || 1;
  17867. //if we're parsing 'd', then the low day numbers may be next week
  17868. if (w.d != null && weekday < lang._week.dow) {
  17869. week++;
  17870. }
  17871. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  17872. }
  17873. config._a[YEAR] = temp.year;
  17874. config._dayOfYear = temp.dayOfYear;
  17875. }
  17876. //if the day of the year is set, figure out what it is
  17877. if (config._dayOfYear) {
  17878. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  17879. if (config._dayOfYear > daysInYear(yearToUse)) {
  17880. config._pf._overflowDayOfYear = true;
  17881. }
  17882. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  17883. config._a[MONTH] = date.getUTCMonth();
  17884. config._a[DATE] = date.getUTCDate();
  17885. }
  17886. // Default to current date.
  17887. // * if no year, month, day of month are given, default to today
  17888. // * if day of month is given, default month and year
  17889. // * if month is given, default only year
  17890. // * if year is given, don't default anything
  17891. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  17892. config._a[i] = input[i] = currentDate[i];
  17893. }
  17894. // Zero out whatever was not defaulted, including time
  17895. for (; i < 7; i++) {
  17896. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  17897. }
  17898. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  17899. input[HOUR] += toInt((config._tzm || 0) / 60);
  17900. input[MINUTE] += toInt((config._tzm || 0) % 60);
  17901. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  17902. }
  17903. function dateFromObject(config) {
  17904. var normalizedInput;
  17905. if (config._d) {
  17906. return;
  17907. }
  17908. normalizedInput = normalizeObjectUnits(config._i);
  17909. config._a = [
  17910. normalizedInput.year,
  17911. normalizedInput.month,
  17912. normalizedInput.day,
  17913. normalizedInput.hour,
  17914. normalizedInput.minute,
  17915. normalizedInput.second,
  17916. normalizedInput.millisecond
  17917. ];
  17918. dateFromConfig(config);
  17919. }
  17920. function currentDateArray(config) {
  17921. var now = new Date();
  17922. if (config._useUTC) {
  17923. return [
  17924. now.getUTCFullYear(),
  17925. now.getUTCMonth(),
  17926. now.getUTCDate()
  17927. ];
  17928. } else {
  17929. return [now.getFullYear(), now.getMonth(), now.getDate()];
  17930. }
  17931. }
  17932. // date from string and format string
  17933. function makeDateFromStringAndFormat(config) {
  17934. config._a = [];
  17935. config._pf.empty = true;
  17936. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  17937. var lang = getLangDefinition(config._l),
  17938. string = '' + config._i,
  17939. i, parsedInput, tokens, token, skipped,
  17940. stringLength = string.length,
  17941. totalParsedInputLength = 0;
  17942. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  17943. for (i = 0; i < tokens.length; i++) {
  17944. token = tokens[i];
  17945. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  17946. if (parsedInput) {
  17947. skipped = string.substr(0, string.indexOf(parsedInput));
  17948. if (skipped.length > 0) {
  17949. config._pf.unusedInput.push(skipped);
  17950. }
  17951. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  17952. totalParsedInputLength += parsedInput.length;
  17953. }
  17954. // don't parse if it's not a known token
  17955. if (formatTokenFunctions[token]) {
  17956. if (parsedInput) {
  17957. config._pf.empty = false;
  17958. }
  17959. else {
  17960. config._pf.unusedTokens.push(token);
  17961. }
  17962. addTimeToArrayFromToken(token, parsedInput, config);
  17963. }
  17964. else if (config._strict && !parsedInput) {
  17965. config._pf.unusedTokens.push(token);
  17966. }
  17967. }
  17968. // add remaining unparsed input length to the string
  17969. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  17970. if (string.length > 0) {
  17971. config._pf.unusedInput.push(string);
  17972. }
  17973. // handle am pm
  17974. if (config._isPm && config._a[HOUR] < 12) {
  17975. config._a[HOUR] += 12;
  17976. }
  17977. // if is 12 am, change hours to 0
  17978. if (config._isPm === false && config._a[HOUR] === 12) {
  17979. config._a[HOUR] = 0;
  17980. }
  17981. dateFromConfig(config);
  17982. checkOverflow(config);
  17983. }
  17984. function unescapeFormat(s) {
  17985. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  17986. return p1 || p2 || p3 || p4;
  17987. });
  17988. }
  17989. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  17990. function regexpEscape(s) {
  17991. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  17992. }
  17993. // date from string and array of format strings
  17994. function makeDateFromStringAndArray(config) {
  17995. var tempConfig,
  17996. bestMoment,
  17997. scoreToBeat,
  17998. i,
  17999. currentScore;
  18000. if (config._f.length === 0) {
  18001. config._pf.invalidFormat = true;
  18002. config._d = new Date(NaN);
  18003. return;
  18004. }
  18005. for (i = 0; i < config._f.length; i++) {
  18006. currentScore = 0;
  18007. tempConfig = extend({}, config);
  18008. tempConfig._pf = defaultParsingFlags();
  18009. tempConfig._f = config._f[i];
  18010. makeDateFromStringAndFormat(tempConfig);
  18011. if (!isValid(tempConfig)) {
  18012. continue;
  18013. }
  18014. // if there is any input that was not parsed add a penalty for that format
  18015. currentScore += tempConfig._pf.charsLeftOver;
  18016. //or tokens
  18017. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18018. tempConfig._pf.score = currentScore;
  18019. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18020. scoreToBeat = currentScore;
  18021. bestMoment = tempConfig;
  18022. }
  18023. }
  18024. extend(config, bestMoment || tempConfig);
  18025. }
  18026. // date from iso format
  18027. function makeDateFromString(config) {
  18028. var i, l,
  18029. string = config._i,
  18030. match = isoRegex.exec(string);
  18031. if (match) {
  18032. config._pf.iso = true;
  18033. for (i = 0, l = isoDates.length; i < l; i++) {
  18034. if (isoDates[i][1].exec(string)) {
  18035. // match[5] should be "T" or undefined
  18036. config._f = isoDates[i][0] + (match[6] || " ");
  18037. break;
  18038. }
  18039. }
  18040. for (i = 0, l = isoTimes.length; i < l; i++) {
  18041. if (isoTimes[i][1].exec(string)) {
  18042. config._f += isoTimes[i][0];
  18043. break;
  18044. }
  18045. }
  18046. if (string.match(parseTokenTimezone)) {
  18047. config._f += "Z";
  18048. }
  18049. makeDateFromStringAndFormat(config);
  18050. }
  18051. else {
  18052. config._d = new Date(string);
  18053. }
  18054. }
  18055. function makeDateFromInput(config) {
  18056. var input = config._i,
  18057. matched = aspNetJsonRegex.exec(input);
  18058. if (input === undefined) {
  18059. config._d = new Date();
  18060. } else if (matched) {
  18061. config._d = new Date(+matched[1]);
  18062. } else if (typeof input === 'string') {
  18063. makeDateFromString(config);
  18064. } else if (isArray(input)) {
  18065. config._a = input.slice(0);
  18066. dateFromConfig(config);
  18067. } else if (isDate(input)) {
  18068. config._d = new Date(+input);
  18069. } else if (typeof(input) === 'object') {
  18070. dateFromObject(config);
  18071. } else {
  18072. config._d = new Date(input);
  18073. }
  18074. }
  18075. function makeDate(y, m, d, h, M, s, ms) {
  18076. //can't just apply() to create a date:
  18077. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  18078. var date = new Date(y, m, d, h, M, s, ms);
  18079. //the date constructor doesn't accept years < 1970
  18080. if (y < 1970) {
  18081. date.setFullYear(y);
  18082. }
  18083. return date;
  18084. }
  18085. function makeUTCDate(y) {
  18086. var date = new Date(Date.UTC.apply(null, arguments));
  18087. if (y < 1970) {
  18088. date.setUTCFullYear(y);
  18089. }
  18090. return date;
  18091. }
  18092. function parseWeekday(input, language) {
  18093. if (typeof input === 'string') {
  18094. if (!isNaN(input)) {
  18095. input = parseInt(input, 10);
  18096. }
  18097. else {
  18098. input = language.weekdaysParse(input);
  18099. if (typeof input !== 'number') {
  18100. return null;
  18101. }
  18102. }
  18103. }
  18104. return input;
  18105. }
  18106. /************************************
  18107. Relative Time
  18108. ************************************/
  18109. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  18110. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  18111. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  18112. }
  18113. function relativeTime(milliseconds, withoutSuffix, lang) {
  18114. var seconds = round(Math.abs(milliseconds) / 1000),
  18115. minutes = round(seconds / 60),
  18116. hours = round(minutes / 60),
  18117. days = round(hours / 24),
  18118. years = round(days / 365),
  18119. args = seconds < 45 && ['s', seconds] ||
  18120. minutes === 1 && ['m'] ||
  18121. minutes < 45 && ['mm', minutes] ||
  18122. hours === 1 && ['h'] ||
  18123. hours < 22 && ['hh', hours] ||
  18124. days === 1 && ['d'] ||
  18125. days <= 25 && ['dd', days] ||
  18126. days <= 45 && ['M'] ||
  18127. days < 345 && ['MM', round(days / 30)] ||
  18128. years === 1 && ['y'] || ['yy', years];
  18129. args[2] = withoutSuffix;
  18130. args[3] = milliseconds > 0;
  18131. args[4] = lang;
  18132. return substituteTimeAgo.apply({}, args);
  18133. }
  18134. /************************************
  18135. Week of Year
  18136. ************************************/
  18137. // firstDayOfWeek 0 = sun, 6 = sat
  18138. // the day of the week that starts the week
  18139. // (usually sunday or monday)
  18140. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18141. // the first week is the week that contains the first
  18142. // of this day of the week
  18143. // (eg. ISO weeks use thursday (4))
  18144. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18145. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18146. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18147. adjustedMoment;
  18148. if (daysToDayOfWeek > end) {
  18149. daysToDayOfWeek -= 7;
  18150. }
  18151. if (daysToDayOfWeek < end - 7) {
  18152. daysToDayOfWeek += 7;
  18153. }
  18154. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18155. return {
  18156. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18157. year: adjustedMoment.year()
  18158. };
  18159. }
  18160. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18161. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18162. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18163. weekday = weekday != null ? weekday : firstDayOfWeek;
  18164. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18165. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18166. return {
  18167. year: dayOfYear > 0 ? year : year - 1,
  18168. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18169. };
  18170. }
  18171. /************************************
  18172. Top Level Functions
  18173. ************************************/
  18174. function makeMoment(config) {
  18175. var input = config._i,
  18176. format = config._f;
  18177. if (input === null) {
  18178. return moment.invalid({nullInput: true});
  18179. }
  18180. if (typeof input === 'string') {
  18181. config._i = input = getLangDefinition().preparse(input);
  18182. }
  18183. if (moment.isMoment(input)) {
  18184. config = cloneMoment(input);
  18185. config._d = new Date(+input._d);
  18186. } else if (format) {
  18187. if (isArray(format)) {
  18188. makeDateFromStringAndArray(config);
  18189. } else {
  18190. makeDateFromStringAndFormat(config);
  18191. }
  18192. } else {
  18193. makeDateFromInput(config);
  18194. }
  18195. return new Moment(config);
  18196. }
  18197. moment = function (input, format, lang, strict) {
  18198. var c;
  18199. if (typeof(lang) === "boolean") {
  18200. strict = lang;
  18201. lang = undefined;
  18202. }
  18203. // object construction must be done this way.
  18204. // https://github.com/moment/moment/issues/1423
  18205. c = {};
  18206. c._isAMomentObject = true;
  18207. c._i = input;
  18208. c._f = format;
  18209. c._l = lang;
  18210. c._strict = strict;
  18211. c._isUTC = false;
  18212. c._pf = defaultParsingFlags();
  18213. return makeMoment(c);
  18214. };
  18215. // creating with utc
  18216. moment.utc = function (input, format, lang, strict) {
  18217. var c;
  18218. if (typeof(lang) === "boolean") {
  18219. strict = lang;
  18220. lang = undefined;
  18221. }
  18222. // object construction must be done this way.
  18223. // https://github.com/moment/moment/issues/1423
  18224. c = {};
  18225. c._isAMomentObject = true;
  18226. c._useUTC = true;
  18227. c._isUTC = true;
  18228. c._l = lang;
  18229. c._i = input;
  18230. c._f = format;
  18231. c._strict = strict;
  18232. c._pf = defaultParsingFlags();
  18233. return makeMoment(c).utc();
  18234. };
  18235. // creating with unix timestamp (in seconds)
  18236. moment.unix = function (input) {
  18237. return moment(input * 1000);
  18238. };
  18239. // duration
  18240. moment.duration = function (input, key) {
  18241. var duration = input,
  18242. // matching against regexp is expensive, do it on demand
  18243. match = null,
  18244. sign,
  18245. ret,
  18246. parseIso;
  18247. if (moment.isDuration(input)) {
  18248. duration = {
  18249. ms: input._milliseconds,
  18250. d: input._days,
  18251. M: input._months
  18252. };
  18253. } else if (typeof input === 'number') {
  18254. duration = {};
  18255. if (key) {
  18256. duration[key] = input;
  18257. } else {
  18258. duration.milliseconds = input;
  18259. }
  18260. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18261. sign = (match[1] === "-") ? -1 : 1;
  18262. duration = {
  18263. y: 0,
  18264. d: toInt(match[DATE]) * sign,
  18265. h: toInt(match[HOUR]) * sign,
  18266. m: toInt(match[MINUTE]) * sign,
  18267. s: toInt(match[SECOND]) * sign,
  18268. ms: toInt(match[MILLISECOND]) * sign
  18269. };
  18270. } else if (!!(match = isoDurationRegex.exec(input))) {
  18271. sign = (match[1] === "-") ? -1 : 1;
  18272. parseIso = function (inp) {
  18273. // We'd normally use ~~inp for this, but unfortunately it also
  18274. // converts floats to ints.
  18275. // inp may be undefined, so careful calling replace on it.
  18276. var res = inp && parseFloat(inp.replace(',', '.'));
  18277. // apply sign while we're at it
  18278. return (isNaN(res) ? 0 : res) * sign;
  18279. };
  18280. duration = {
  18281. y: parseIso(match[2]),
  18282. M: parseIso(match[3]),
  18283. d: parseIso(match[4]),
  18284. h: parseIso(match[5]),
  18285. m: parseIso(match[6]),
  18286. s: parseIso(match[7]),
  18287. w: parseIso(match[8])
  18288. };
  18289. }
  18290. ret = new Duration(duration);
  18291. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18292. ret._lang = input._lang;
  18293. }
  18294. return ret;
  18295. };
  18296. // version number
  18297. moment.version = VERSION;
  18298. // default format
  18299. moment.defaultFormat = isoFormat;
  18300. // This function will be called whenever a moment is mutated.
  18301. // It is intended to keep the offset in sync with the timezone.
  18302. moment.updateOffset = function () {};
  18303. // This function will load languages and then set the global language. If
  18304. // no arguments are passed in, it will simply return the current global
  18305. // language key.
  18306. moment.lang = function (key, values) {
  18307. var r;
  18308. if (!key) {
  18309. return moment.fn._lang._abbr;
  18310. }
  18311. if (values) {
  18312. loadLang(normalizeLanguage(key), values);
  18313. } else if (values === null) {
  18314. unloadLang(key);
  18315. key = 'en';
  18316. } else if (!languages[key]) {
  18317. getLangDefinition(key);
  18318. }
  18319. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18320. return r._abbr;
  18321. };
  18322. // returns language data
  18323. moment.langData = function (key) {
  18324. if (key && key._lang && key._lang._abbr) {
  18325. key = key._lang._abbr;
  18326. }
  18327. return getLangDefinition(key);
  18328. };
  18329. // compare moment object
  18330. moment.isMoment = function (obj) {
  18331. return obj instanceof Moment ||
  18332. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18333. };
  18334. // for typechecking Duration objects
  18335. moment.isDuration = function (obj) {
  18336. return obj instanceof Duration;
  18337. };
  18338. for (i = lists.length - 1; i >= 0; --i) {
  18339. makeList(lists[i]);
  18340. }
  18341. moment.normalizeUnits = function (units) {
  18342. return normalizeUnits(units);
  18343. };
  18344. moment.invalid = function (flags) {
  18345. var m = moment.utc(NaN);
  18346. if (flags != null) {
  18347. extend(m._pf, flags);
  18348. }
  18349. else {
  18350. m._pf.userInvalidated = true;
  18351. }
  18352. return m;
  18353. };
  18354. moment.parseZone = function (input) {
  18355. return moment(input).parseZone();
  18356. };
  18357. /************************************
  18358. Moment Prototype
  18359. ************************************/
  18360. extend(moment.fn = Moment.prototype, {
  18361. clone : function () {
  18362. return moment(this);
  18363. },
  18364. valueOf : function () {
  18365. return +this._d + ((this._offset || 0) * 60000);
  18366. },
  18367. unix : function () {
  18368. return Math.floor(+this / 1000);
  18369. },
  18370. toString : function () {
  18371. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18372. },
  18373. toDate : function () {
  18374. return this._offset ? new Date(+this) : this._d;
  18375. },
  18376. toISOString : function () {
  18377. var m = moment(this).utc();
  18378. if (0 < m.year() && m.year() <= 9999) {
  18379. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18380. } else {
  18381. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18382. }
  18383. },
  18384. toArray : function () {
  18385. var m = this;
  18386. return [
  18387. m.year(),
  18388. m.month(),
  18389. m.date(),
  18390. m.hours(),
  18391. m.minutes(),
  18392. m.seconds(),
  18393. m.milliseconds()
  18394. ];
  18395. },
  18396. isValid : function () {
  18397. return isValid(this);
  18398. },
  18399. isDSTShifted : function () {
  18400. if (this._a) {
  18401. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18402. }
  18403. return false;
  18404. },
  18405. parsingFlags : function () {
  18406. return extend({}, this._pf);
  18407. },
  18408. invalidAt: function () {
  18409. return this._pf.overflow;
  18410. },
  18411. utc : function () {
  18412. return this.zone(0);
  18413. },
  18414. local : function () {
  18415. this.zone(0);
  18416. this._isUTC = false;
  18417. return this;
  18418. },
  18419. format : function (inputString) {
  18420. var output = formatMoment(this, inputString || moment.defaultFormat);
  18421. return this.lang().postformat(output);
  18422. },
  18423. add : function (input, val) {
  18424. var dur;
  18425. // switch args to support add('s', 1) and add(1, 's')
  18426. if (typeof input === 'string') {
  18427. dur = moment.duration(+val, input);
  18428. } else {
  18429. dur = moment.duration(input, val);
  18430. }
  18431. addOrSubtractDurationFromMoment(this, dur, 1);
  18432. return this;
  18433. },
  18434. subtract : function (input, val) {
  18435. var dur;
  18436. // switch args to support subtract('s', 1) and subtract(1, 's')
  18437. if (typeof input === 'string') {
  18438. dur = moment.duration(+val, input);
  18439. } else {
  18440. dur = moment.duration(input, val);
  18441. }
  18442. addOrSubtractDurationFromMoment(this, dur, -1);
  18443. return this;
  18444. },
  18445. diff : function (input, units, asFloat) {
  18446. var that = makeAs(input, this),
  18447. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18448. diff, output;
  18449. units = normalizeUnits(units);
  18450. if (units === 'year' || units === 'month') {
  18451. // average number of days in the months in the given dates
  18452. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18453. // difference in months
  18454. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18455. // adjust by taking difference in days, average number of days
  18456. // and dst in the given months.
  18457. output += ((this - moment(this).startOf('month')) -
  18458. (that - moment(that).startOf('month'))) / diff;
  18459. // same as above but with zones, to negate all dst
  18460. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18461. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18462. if (units === 'year') {
  18463. output = output / 12;
  18464. }
  18465. } else {
  18466. diff = (this - that);
  18467. output = units === 'second' ? diff / 1e3 : // 1000
  18468. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18469. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18470. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18471. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18472. diff;
  18473. }
  18474. return asFloat ? output : absRound(output);
  18475. },
  18476. from : function (time, withoutSuffix) {
  18477. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18478. },
  18479. fromNow : function (withoutSuffix) {
  18480. return this.from(moment(), withoutSuffix);
  18481. },
  18482. calendar : function () {
  18483. // We want to compare the start of today, vs this.
  18484. // Getting start-of-today depends on whether we're zone'd or not.
  18485. var sod = makeAs(moment(), this).startOf('day'),
  18486. diff = this.diff(sod, 'days', true),
  18487. format = diff < -6 ? 'sameElse' :
  18488. diff < -1 ? 'lastWeek' :
  18489. diff < 0 ? 'lastDay' :
  18490. diff < 1 ? 'sameDay' :
  18491. diff < 2 ? 'nextDay' :
  18492. diff < 7 ? 'nextWeek' : 'sameElse';
  18493. return this.format(this.lang().calendar(format, this));
  18494. },
  18495. isLeapYear : function () {
  18496. return isLeapYear(this.year());
  18497. },
  18498. isDST : function () {
  18499. return (this.zone() < this.clone().month(0).zone() ||
  18500. this.zone() < this.clone().month(5).zone());
  18501. },
  18502. day : function (input) {
  18503. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18504. if (input != null) {
  18505. input = parseWeekday(input, this.lang());
  18506. return this.add({ d : input - day });
  18507. } else {
  18508. return day;
  18509. }
  18510. },
  18511. month : function (input) {
  18512. var utc = this._isUTC ? 'UTC' : '',
  18513. dayOfMonth;
  18514. if (input != null) {
  18515. if (typeof input === 'string') {
  18516. input = this.lang().monthsParse(input);
  18517. if (typeof input !== 'number') {
  18518. return this;
  18519. }
  18520. }
  18521. dayOfMonth = this.date();
  18522. this.date(1);
  18523. this._d['set' + utc + 'Month'](input);
  18524. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  18525. moment.updateOffset(this);
  18526. return this;
  18527. } else {
  18528. return this._d['get' + utc + 'Month']();
  18529. }
  18530. },
  18531. startOf: function (units) {
  18532. units = normalizeUnits(units);
  18533. // the following switch intentionally omits break keywords
  18534. // to utilize falling through the cases.
  18535. switch (units) {
  18536. case 'year':
  18537. this.month(0);
  18538. /* falls through */
  18539. case 'month':
  18540. this.date(1);
  18541. /* falls through */
  18542. case 'week':
  18543. case 'isoWeek':
  18544. case 'day':
  18545. this.hours(0);
  18546. /* falls through */
  18547. case 'hour':
  18548. this.minutes(0);
  18549. /* falls through */
  18550. case 'minute':
  18551. this.seconds(0);
  18552. /* falls through */
  18553. case 'second':
  18554. this.milliseconds(0);
  18555. /* falls through */
  18556. }
  18557. // weeks are a special case
  18558. if (units === 'week') {
  18559. this.weekday(0);
  18560. } else if (units === 'isoWeek') {
  18561. this.isoWeekday(1);
  18562. }
  18563. return this;
  18564. },
  18565. endOf: function (units) {
  18566. units = normalizeUnits(units);
  18567. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18568. },
  18569. isAfter: function (input, units) {
  18570. units = typeof units !== 'undefined' ? units : 'millisecond';
  18571. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18572. },
  18573. isBefore: function (input, units) {
  18574. units = typeof units !== 'undefined' ? units : 'millisecond';
  18575. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18576. },
  18577. isSame: function (input, units) {
  18578. units = units || 'ms';
  18579. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18580. },
  18581. min: function (other) {
  18582. other = moment.apply(null, arguments);
  18583. return other < this ? this : other;
  18584. },
  18585. max: function (other) {
  18586. other = moment.apply(null, arguments);
  18587. return other > this ? this : other;
  18588. },
  18589. zone : function (input) {
  18590. var offset = this._offset || 0;
  18591. if (input != null) {
  18592. if (typeof input === "string") {
  18593. input = timezoneMinutesFromString(input);
  18594. }
  18595. if (Math.abs(input) < 16) {
  18596. input = input * 60;
  18597. }
  18598. this._offset = input;
  18599. this._isUTC = true;
  18600. if (offset !== input) {
  18601. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  18602. }
  18603. } else {
  18604. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18605. }
  18606. return this;
  18607. },
  18608. zoneAbbr : function () {
  18609. return this._isUTC ? "UTC" : "";
  18610. },
  18611. zoneName : function () {
  18612. return this._isUTC ? "Coordinated Universal Time" : "";
  18613. },
  18614. parseZone : function () {
  18615. if (this._tzm) {
  18616. this.zone(this._tzm);
  18617. } else if (typeof this._i === 'string') {
  18618. this.zone(this._i);
  18619. }
  18620. return this;
  18621. },
  18622. hasAlignedHourOffset : function (input) {
  18623. if (!input) {
  18624. input = 0;
  18625. }
  18626. else {
  18627. input = moment(input).zone();
  18628. }
  18629. return (this.zone() - input) % 60 === 0;
  18630. },
  18631. daysInMonth : function () {
  18632. return daysInMonth(this.year(), this.month());
  18633. },
  18634. dayOfYear : function (input) {
  18635. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  18636. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  18637. },
  18638. quarter : function () {
  18639. return Math.ceil((this.month() + 1.0) / 3.0);
  18640. },
  18641. weekYear : function (input) {
  18642. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  18643. return input == null ? year : this.add("y", (input - year));
  18644. },
  18645. isoWeekYear : function (input) {
  18646. var year = weekOfYear(this, 1, 4).year;
  18647. return input == null ? year : this.add("y", (input - year));
  18648. },
  18649. week : function (input) {
  18650. var week = this.lang().week(this);
  18651. return input == null ? week : this.add("d", (input - week) * 7);
  18652. },
  18653. isoWeek : function (input) {
  18654. var week = weekOfYear(this, 1, 4).week;
  18655. return input == null ? week : this.add("d", (input - week) * 7);
  18656. },
  18657. weekday : function (input) {
  18658. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  18659. return input == null ? weekday : this.add("d", input - weekday);
  18660. },
  18661. isoWeekday : function (input) {
  18662. // behaves the same as moment#day except
  18663. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  18664. // as a setter, sunday should belong to the previous week.
  18665. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  18666. },
  18667. get : function (units) {
  18668. units = normalizeUnits(units);
  18669. return this[units]();
  18670. },
  18671. set : function (units, value) {
  18672. units = normalizeUnits(units);
  18673. if (typeof this[units] === 'function') {
  18674. this[units](value);
  18675. }
  18676. return this;
  18677. },
  18678. // If passed a language key, it will set the language for this
  18679. // instance. Otherwise, it will return the language configuration
  18680. // variables for this instance.
  18681. lang : function (key) {
  18682. if (key === undefined) {
  18683. return this._lang;
  18684. } else {
  18685. this._lang = getLangDefinition(key);
  18686. return this;
  18687. }
  18688. }
  18689. });
  18690. // helper for adding shortcuts
  18691. function makeGetterAndSetter(name, key) {
  18692. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  18693. var utc = this._isUTC ? 'UTC' : '';
  18694. if (input != null) {
  18695. this._d['set' + utc + key](input);
  18696. moment.updateOffset(this);
  18697. return this;
  18698. } else {
  18699. return this._d['get' + utc + key]();
  18700. }
  18701. };
  18702. }
  18703. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  18704. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  18705. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  18706. }
  18707. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  18708. makeGetterAndSetter('year', 'FullYear');
  18709. // add plural methods
  18710. moment.fn.days = moment.fn.day;
  18711. moment.fn.months = moment.fn.month;
  18712. moment.fn.weeks = moment.fn.week;
  18713. moment.fn.isoWeeks = moment.fn.isoWeek;
  18714. // add aliased format methods
  18715. moment.fn.toJSON = moment.fn.toISOString;
  18716. /************************************
  18717. Duration Prototype
  18718. ************************************/
  18719. extend(moment.duration.fn = Duration.prototype, {
  18720. _bubble : function () {
  18721. var milliseconds = this._milliseconds,
  18722. days = this._days,
  18723. months = this._months,
  18724. data = this._data,
  18725. seconds, minutes, hours, years;
  18726. // The following code bubbles up values, see the tests for
  18727. // examples of what that means.
  18728. data.milliseconds = milliseconds % 1000;
  18729. seconds = absRound(milliseconds / 1000);
  18730. data.seconds = seconds % 60;
  18731. minutes = absRound(seconds / 60);
  18732. data.minutes = minutes % 60;
  18733. hours = absRound(minutes / 60);
  18734. data.hours = hours % 24;
  18735. days += absRound(hours / 24);
  18736. data.days = days % 30;
  18737. months += absRound(days / 30);
  18738. data.months = months % 12;
  18739. years = absRound(months / 12);
  18740. data.years = years;
  18741. },
  18742. weeks : function () {
  18743. return absRound(this.days() / 7);
  18744. },
  18745. valueOf : function () {
  18746. return this._milliseconds +
  18747. this._days * 864e5 +
  18748. (this._months % 12) * 2592e6 +
  18749. toInt(this._months / 12) * 31536e6;
  18750. },
  18751. humanize : function (withSuffix) {
  18752. var difference = +this,
  18753. output = relativeTime(difference, !withSuffix, this.lang());
  18754. if (withSuffix) {
  18755. output = this.lang().pastFuture(difference, output);
  18756. }
  18757. return this.lang().postformat(output);
  18758. },
  18759. add : function (input, val) {
  18760. // supports only 2.0-style add(1, 's') or add(moment)
  18761. var dur = moment.duration(input, val);
  18762. this._milliseconds += dur._milliseconds;
  18763. this._days += dur._days;
  18764. this._months += dur._months;
  18765. this._bubble();
  18766. return this;
  18767. },
  18768. subtract : function (input, val) {
  18769. var dur = moment.duration(input, val);
  18770. this._milliseconds -= dur._milliseconds;
  18771. this._days -= dur._days;
  18772. this._months -= dur._months;
  18773. this._bubble();
  18774. return this;
  18775. },
  18776. get : function (units) {
  18777. units = normalizeUnits(units);
  18778. return this[units.toLowerCase() + 's']();
  18779. },
  18780. as : function (units) {
  18781. units = normalizeUnits(units);
  18782. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  18783. },
  18784. lang : moment.fn.lang,
  18785. toIsoString : function () {
  18786. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  18787. var years = Math.abs(this.years()),
  18788. months = Math.abs(this.months()),
  18789. days = Math.abs(this.days()),
  18790. hours = Math.abs(this.hours()),
  18791. minutes = Math.abs(this.minutes()),
  18792. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  18793. if (!this.asSeconds()) {
  18794. // this is the same as C#'s (Noda) and python (isodate)...
  18795. // but not other JS (goog.date)
  18796. return 'P0D';
  18797. }
  18798. return (this.asSeconds() < 0 ? '-' : '') +
  18799. 'P' +
  18800. (years ? years + 'Y' : '') +
  18801. (months ? months + 'M' : '') +
  18802. (days ? days + 'D' : '') +
  18803. ((hours || minutes || seconds) ? 'T' : '') +
  18804. (hours ? hours + 'H' : '') +
  18805. (minutes ? minutes + 'M' : '') +
  18806. (seconds ? seconds + 'S' : '');
  18807. }
  18808. });
  18809. function makeDurationGetter(name) {
  18810. moment.duration.fn[name] = function () {
  18811. return this._data[name];
  18812. };
  18813. }
  18814. function makeDurationAsGetter(name, factor) {
  18815. moment.duration.fn['as' + name] = function () {
  18816. return +this / factor;
  18817. };
  18818. }
  18819. for (i in unitMillisecondFactors) {
  18820. if (unitMillisecondFactors.hasOwnProperty(i)) {
  18821. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  18822. makeDurationGetter(i.toLowerCase());
  18823. }
  18824. }
  18825. makeDurationAsGetter('Weeks', 6048e5);
  18826. moment.duration.fn.asMonths = function () {
  18827. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  18828. };
  18829. /************************************
  18830. Default Lang
  18831. ************************************/
  18832. // Set default language, other languages will inherit from English.
  18833. moment.lang('en', {
  18834. ordinal : function (number) {
  18835. var b = number % 10,
  18836. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  18837. (b === 1) ? 'st' :
  18838. (b === 2) ? 'nd' :
  18839. (b === 3) ? 'rd' : 'th';
  18840. return number + output;
  18841. }
  18842. });
  18843. /* EMBED_LANGUAGES */
  18844. /************************************
  18845. Exposing Moment
  18846. ************************************/
  18847. function makeGlobal(deprecate) {
  18848. var warned = false, local_moment = moment;
  18849. /*global ender:false */
  18850. if (typeof ender !== 'undefined') {
  18851. return;
  18852. }
  18853. // here, `this` means `window` in the browser, or `global` on the server
  18854. // add `moment` as a global object via a string identifier,
  18855. // for Closure Compiler "advanced" mode
  18856. if (deprecate) {
  18857. global.moment = function () {
  18858. if (!warned && console && console.warn) {
  18859. warned = true;
  18860. console.warn(
  18861. "Accessing Moment through the global scope is " +
  18862. "deprecated, and will be removed in an upcoming " +
  18863. "release.");
  18864. }
  18865. return local_moment.apply(null, arguments);
  18866. };
  18867. extend(global.moment, local_moment);
  18868. } else {
  18869. global['moment'] = moment;
  18870. }
  18871. }
  18872. // CommonJS module is defined
  18873. if (hasModule) {
  18874. module.exports = moment;
  18875. makeGlobal(true);
  18876. } else if (typeof define === "function" && define.amd) {
  18877. define("moment", function (require, exports, module) {
  18878. if (module.config && module.config() && module.config().noGlobal !== true) {
  18879. // If user provided noGlobal, he is aware of global
  18880. makeGlobal(module.config().noGlobal === undefined);
  18881. }
  18882. return moment;
  18883. });
  18884. } else {
  18885. makeGlobal();
  18886. }
  18887. }).call(this);
  18888. },{}],5:[function(require,module,exports){
  18889. /**
  18890. * Copyright 2012 Craig Campbell
  18891. *
  18892. * Licensed under the Apache License, Version 2.0 (the "License");
  18893. * you may not use this file except in compliance with the License.
  18894. * You may obtain a copy of the License at
  18895. *
  18896. * http://www.apache.org/licenses/LICENSE-2.0
  18897. *
  18898. * Unless required by applicable law or agreed to in writing, software
  18899. * distributed under the License is distributed on an "AS IS" BASIS,
  18900. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18901. * See the License for the specific language governing permissions and
  18902. * limitations under the License.
  18903. *
  18904. * Mousetrap is a simple keyboard shortcut library for Javascript with
  18905. * no external dependencies
  18906. *
  18907. * @version 1.1.2
  18908. * @url craig.is/killing/mice
  18909. */
  18910. /**
  18911. * mapping of special keycodes to their corresponding keys
  18912. *
  18913. * everything in this dictionary cannot use keypress events
  18914. * so it has to be here to map to the correct keycodes for
  18915. * keyup/keydown events
  18916. *
  18917. * @type {Object}
  18918. */
  18919. var _MAP = {
  18920. 8: 'backspace',
  18921. 9: 'tab',
  18922. 13: 'enter',
  18923. 16: 'shift',
  18924. 17: 'ctrl',
  18925. 18: 'alt',
  18926. 20: 'capslock',
  18927. 27: 'esc',
  18928. 32: 'space',
  18929. 33: 'pageup',
  18930. 34: 'pagedown',
  18931. 35: 'end',
  18932. 36: 'home',
  18933. 37: 'left',
  18934. 38: 'up',
  18935. 39: 'right',
  18936. 40: 'down',
  18937. 45: 'ins',
  18938. 46: 'del',
  18939. 91: 'meta',
  18940. 93: 'meta',
  18941. 224: 'meta'
  18942. },
  18943. /**
  18944. * mapping for special characters so they can support
  18945. *
  18946. * this dictionary is only used incase you want to bind a
  18947. * keyup or keydown event to one of these keys
  18948. *
  18949. * @type {Object}
  18950. */
  18951. _KEYCODE_MAP = {
  18952. 106: '*',
  18953. 107: '+',
  18954. 109: '-',
  18955. 110: '.',
  18956. 111 : '/',
  18957. 186: ';',
  18958. 187: '=',
  18959. 188: ',',
  18960. 189: '-',
  18961. 190: '.',
  18962. 191: '/',
  18963. 192: '`',
  18964. 219: '[',
  18965. 220: '\\',
  18966. 221: ']',
  18967. 222: '\''
  18968. },
  18969. /**
  18970. * this is a mapping of keys that require shift on a US keypad
  18971. * back to the non shift equivelents
  18972. *
  18973. * this is so you can use keyup events with these keys
  18974. *
  18975. * note that this will only work reliably on US keyboards
  18976. *
  18977. * @type {Object}
  18978. */
  18979. _SHIFT_MAP = {
  18980. '~': '`',
  18981. '!': '1',
  18982. '@': '2',
  18983. '#': '3',
  18984. '$': '4',
  18985. '%': '5',
  18986. '^': '6',
  18987. '&': '7',
  18988. '*': '8',
  18989. '(': '9',
  18990. ')': '0',
  18991. '_': '-',
  18992. '+': '=',
  18993. ':': ';',
  18994. '\"': '\'',
  18995. '<': ',',
  18996. '>': '.',
  18997. '?': '/',
  18998. '|': '\\'
  18999. },
  19000. /**
  19001. * this is a list of special strings you can use to map
  19002. * to modifier keys when you specify your keyboard shortcuts
  19003. *
  19004. * @type {Object}
  19005. */
  19006. _SPECIAL_ALIASES = {
  19007. 'option': 'alt',
  19008. 'command': 'meta',
  19009. 'return': 'enter',
  19010. 'escape': 'esc'
  19011. },
  19012. /**
  19013. * variable to store the flipped version of _MAP from above
  19014. * needed to check if we should use keypress or not when no action
  19015. * is specified
  19016. *
  19017. * @type {Object|undefined}
  19018. */
  19019. _REVERSE_MAP,
  19020. /**
  19021. * a list of all the callbacks setup via Mousetrap.bind()
  19022. *
  19023. * @type {Object}
  19024. */
  19025. _callbacks = {},
  19026. /**
  19027. * direct map of string combinations to callbacks used for trigger()
  19028. *
  19029. * @type {Object}
  19030. */
  19031. _direct_map = {},
  19032. /**
  19033. * keeps track of what level each sequence is at since multiple
  19034. * sequences can start out with the same sequence
  19035. *
  19036. * @type {Object}
  19037. */
  19038. _sequence_levels = {},
  19039. /**
  19040. * variable to store the setTimeout call
  19041. *
  19042. * @type {null|number}
  19043. */
  19044. _reset_timer,
  19045. /**
  19046. * temporary state where we will ignore the next keyup
  19047. *
  19048. * @type {boolean|string}
  19049. */
  19050. _ignore_next_keyup = false,
  19051. /**
  19052. * are we currently inside of a sequence?
  19053. * type of action ("keyup" or "keydown" or "keypress") or false
  19054. *
  19055. * @type {boolean|string}
  19056. */
  19057. _inside_sequence = false;
  19058. /**
  19059. * loop through the f keys, f1 to f19 and add them to the map
  19060. * programatically
  19061. */
  19062. for (var i = 1; i < 20; ++i) {
  19063. _MAP[111 + i] = 'f' + i;
  19064. }
  19065. /**
  19066. * loop through to map numbers on the numeric keypad
  19067. */
  19068. for (i = 0; i <= 9; ++i) {
  19069. _MAP[i + 96] = i;
  19070. }
  19071. /**
  19072. * cross browser add event method
  19073. *
  19074. * @param {Element|HTMLDocument} object
  19075. * @param {string} type
  19076. * @param {Function} callback
  19077. * @returns void
  19078. */
  19079. function _addEvent(object, type, callback) {
  19080. if (object.addEventListener) {
  19081. return object.addEventListener(type, callback, false);
  19082. }
  19083. object.attachEvent('on' + type, callback);
  19084. }
  19085. /**
  19086. * takes the event and returns the key character
  19087. *
  19088. * @param {Event} e
  19089. * @return {string}
  19090. */
  19091. function _characterFromEvent(e) {
  19092. // for keypress events we should return the character as is
  19093. if (e.type == 'keypress') {
  19094. return String.fromCharCode(e.which);
  19095. }
  19096. // for non keypress events the special maps are needed
  19097. if (_MAP[e.which]) {
  19098. return _MAP[e.which];
  19099. }
  19100. if (_KEYCODE_MAP[e.which]) {
  19101. return _KEYCODE_MAP[e.which];
  19102. }
  19103. // if it is not in the special map
  19104. return String.fromCharCode(e.which).toLowerCase();
  19105. }
  19106. /**
  19107. * should we stop this event before firing off callbacks
  19108. *
  19109. * @param {Event} e
  19110. * @return {boolean}
  19111. */
  19112. function _stop(e) {
  19113. var element = e.target || e.srcElement,
  19114. tag_name = element.tagName;
  19115. // if the element has the class "mousetrap" then no need to stop
  19116. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19117. return false;
  19118. }
  19119. // stop for input, select, and textarea
  19120. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19121. }
  19122. /**
  19123. * checks if two arrays are equal
  19124. *
  19125. * @param {Array} modifiers1
  19126. * @param {Array} modifiers2
  19127. * @returns {boolean}
  19128. */
  19129. function _modifiersMatch(modifiers1, modifiers2) {
  19130. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19131. }
  19132. /**
  19133. * resets all sequence counters except for the ones passed in
  19134. *
  19135. * @param {Object} do_not_reset
  19136. * @returns void
  19137. */
  19138. function _resetSequences(do_not_reset) {
  19139. do_not_reset = do_not_reset || {};
  19140. var active_sequences = false,
  19141. key;
  19142. for (key in _sequence_levels) {
  19143. if (do_not_reset[key]) {
  19144. active_sequences = true;
  19145. continue;
  19146. }
  19147. _sequence_levels[key] = 0;
  19148. }
  19149. if (!active_sequences) {
  19150. _inside_sequence = false;
  19151. }
  19152. }
  19153. /**
  19154. * finds all callbacks that match based on the keycode, modifiers,
  19155. * and action
  19156. *
  19157. * @param {string} character
  19158. * @param {Array} modifiers
  19159. * @param {string} action
  19160. * @param {boolean=} remove - should we remove any matches
  19161. * @param {string=} combination
  19162. * @returns {Array}
  19163. */
  19164. function _getMatches(character, modifiers, action, remove, combination) {
  19165. var i,
  19166. callback,
  19167. matches = [];
  19168. // if there are no events related to this keycode
  19169. if (!_callbacks[character]) {
  19170. return [];
  19171. }
  19172. // if a modifier key is coming up on its own we should allow it
  19173. if (action == 'keyup' && _isModifier(character)) {
  19174. modifiers = [character];
  19175. }
  19176. // loop through all callbacks for the key that was pressed
  19177. // and see if any of them match
  19178. for (i = 0; i < _callbacks[character].length; ++i) {
  19179. callback = _callbacks[character][i];
  19180. // if this is a sequence but it is not at the right level
  19181. // then move onto the next match
  19182. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19183. continue;
  19184. }
  19185. // if the action we are looking for doesn't match the action we got
  19186. // then we should keep going
  19187. if (action != callback.action) {
  19188. continue;
  19189. }
  19190. // if this is a keypress event that means that we need to only
  19191. // look at the character, otherwise check the modifiers as
  19192. // well
  19193. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19194. // remove is used so if you change your mind and call bind a
  19195. // second time with a new function the first one is overwritten
  19196. if (remove && callback.combo == combination) {
  19197. _callbacks[character].splice(i, 1);
  19198. }
  19199. matches.push(callback);
  19200. }
  19201. }
  19202. return matches;
  19203. }
  19204. /**
  19205. * takes a key event and figures out what the modifiers are
  19206. *
  19207. * @param {Event} e
  19208. * @returns {Array}
  19209. */
  19210. function _eventModifiers(e) {
  19211. var modifiers = [];
  19212. if (e.shiftKey) {
  19213. modifiers.push('shift');
  19214. }
  19215. if (e.altKey) {
  19216. modifiers.push('alt');
  19217. }
  19218. if (e.ctrlKey) {
  19219. modifiers.push('ctrl');
  19220. }
  19221. if (e.metaKey) {
  19222. modifiers.push('meta');
  19223. }
  19224. return modifiers;
  19225. }
  19226. /**
  19227. * actually calls the callback function
  19228. *
  19229. * if your callback function returns false this will use the jquery
  19230. * convention - prevent default and stop propogation on the event
  19231. *
  19232. * @param {Function} callback
  19233. * @param {Event} e
  19234. * @returns void
  19235. */
  19236. function _fireCallback(callback, e) {
  19237. if (callback(e) === false) {
  19238. if (e.preventDefault) {
  19239. e.preventDefault();
  19240. }
  19241. if (e.stopPropagation) {
  19242. e.stopPropagation();
  19243. }
  19244. e.returnValue = false;
  19245. e.cancelBubble = true;
  19246. }
  19247. }
  19248. /**
  19249. * handles a character key event
  19250. *
  19251. * @param {string} character
  19252. * @param {Event} e
  19253. * @returns void
  19254. */
  19255. function _handleCharacter(character, e) {
  19256. // if this event should not happen stop here
  19257. if (_stop(e)) {
  19258. return;
  19259. }
  19260. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19261. i,
  19262. do_not_reset = {},
  19263. processed_sequence_callback = false;
  19264. // loop through matching callbacks for this key event
  19265. for (i = 0; i < callbacks.length; ++i) {
  19266. // fire for all sequence callbacks
  19267. // this is because if for example you have multiple sequences
  19268. // bound such as "g i" and "g t" they both need to fire the
  19269. // callback for matching g cause otherwise you can only ever
  19270. // match the first one
  19271. if (callbacks[i].seq) {
  19272. processed_sequence_callback = true;
  19273. // keep a list of which sequences were matches for later
  19274. do_not_reset[callbacks[i].seq] = 1;
  19275. _fireCallback(callbacks[i].callback, e);
  19276. continue;
  19277. }
  19278. // if there were no sequence matches but we are still here
  19279. // that means this is a regular match so we should fire that
  19280. if (!processed_sequence_callback && !_inside_sequence) {
  19281. _fireCallback(callbacks[i].callback, e);
  19282. }
  19283. }
  19284. // if you are inside of a sequence and the key you are pressing
  19285. // is not a modifier key then we should reset all sequences
  19286. // that were not matched by this key event
  19287. if (e.type == _inside_sequence && !_isModifier(character)) {
  19288. _resetSequences(do_not_reset);
  19289. }
  19290. }
  19291. /**
  19292. * handles a keydown event
  19293. *
  19294. * @param {Event} e
  19295. * @returns void
  19296. */
  19297. function _handleKey(e) {
  19298. // normalize e.which for key events
  19299. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19300. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19301. var character = _characterFromEvent(e);
  19302. // no character found then stop
  19303. if (!character) {
  19304. return;
  19305. }
  19306. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19307. _ignore_next_keyup = false;
  19308. return;
  19309. }
  19310. _handleCharacter(character, e);
  19311. }
  19312. /**
  19313. * determines if the keycode specified is a modifier key or not
  19314. *
  19315. * @param {string} key
  19316. * @returns {boolean}
  19317. */
  19318. function _isModifier(key) {
  19319. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19320. }
  19321. /**
  19322. * called to set a 1 second timeout on the specified sequence
  19323. *
  19324. * this is so after each key press in the sequence you have 1 second
  19325. * to press the next key before you have to start over
  19326. *
  19327. * @returns void
  19328. */
  19329. function _resetSequenceTimer() {
  19330. clearTimeout(_reset_timer);
  19331. _reset_timer = setTimeout(_resetSequences, 1000);
  19332. }
  19333. /**
  19334. * reverses the map lookup so that we can look for specific keys
  19335. * to see what can and can't use keypress
  19336. *
  19337. * @return {Object}
  19338. */
  19339. function _getReverseMap() {
  19340. if (!_REVERSE_MAP) {
  19341. _REVERSE_MAP = {};
  19342. for (var key in _MAP) {
  19343. // pull out the numeric keypad from here cause keypress should
  19344. // be able to detect the keys from the character
  19345. if (key > 95 && key < 112) {
  19346. continue;
  19347. }
  19348. if (_MAP.hasOwnProperty(key)) {
  19349. _REVERSE_MAP[_MAP[key]] = key;
  19350. }
  19351. }
  19352. }
  19353. return _REVERSE_MAP;
  19354. }
  19355. /**
  19356. * picks the best action based on the key combination
  19357. *
  19358. * @param {string} key - character for key
  19359. * @param {Array} modifiers
  19360. * @param {string=} action passed in
  19361. */
  19362. function _pickBestAction(key, modifiers, action) {
  19363. // if no action was picked in we should try to pick the one
  19364. // that we think would work best for this key
  19365. if (!action) {
  19366. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19367. }
  19368. // modifier keys don't work as expected with keypress,
  19369. // switch to keydown
  19370. if (action == 'keypress' && modifiers.length) {
  19371. action = 'keydown';
  19372. }
  19373. return action;
  19374. }
  19375. /**
  19376. * binds a key sequence to an event
  19377. *
  19378. * @param {string} combo - combo specified in bind call
  19379. * @param {Array} keys
  19380. * @param {Function} callback
  19381. * @param {string=} action
  19382. * @returns void
  19383. */
  19384. function _bindSequence(combo, keys, callback, action) {
  19385. // start off by adding a sequence level record for this combination
  19386. // and setting the level to 0
  19387. _sequence_levels[combo] = 0;
  19388. // if there is no action pick the best one for the first key
  19389. // in the sequence
  19390. if (!action) {
  19391. action = _pickBestAction(keys[0], []);
  19392. }
  19393. /**
  19394. * callback to increase the sequence level for this sequence and reset
  19395. * all other sequences that were active
  19396. *
  19397. * @param {Event} e
  19398. * @returns void
  19399. */
  19400. var _increaseSequence = function(e) {
  19401. _inside_sequence = action;
  19402. ++_sequence_levels[combo];
  19403. _resetSequenceTimer();
  19404. },
  19405. /**
  19406. * wraps the specified callback inside of another function in order
  19407. * to reset all sequence counters as soon as this sequence is done
  19408. *
  19409. * @param {Event} e
  19410. * @returns void
  19411. */
  19412. _callbackAndReset = function(e) {
  19413. _fireCallback(callback, e);
  19414. // we should ignore the next key up if the action is key down
  19415. // or keypress. this is so if you finish a sequence and
  19416. // release the key the final key will not trigger a keyup
  19417. if (action !== 'keyup') {
  19418. _ignore_next_keyup = _characterFromEvent(e);
  19419. }
  19420. // weird race condition if a sequence ends with the key
  19421. // another sequence begins with
  19422. setTimeout(_resetSequences, 10);
  19423. },
  19424. i;
  19425. // loop through keys one at a time and bind the appropriate callback
  19426. // function. for any key leading up to the final one it should
  19427. // increase the sequence. after the final, it should reset all sequences
  19428. for (i = 0; i < keys.length; ++i) {
  19429. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19430. }
  19431. }
  19432. /**
  19433. * binds a single keyboard combination
  19434. *
  19435. * @param {string} combination
  19436. * @param {Function} callback
  19437. * @param {string=} action
  19438. * @param {string=} sequence_name - name of sequence if part of sequence
  19439. * @param {number=} level - what part of the sequence the command is
  19440. * @returns void
  19441. */
  19442. function _bindSingle(combination, callback, action, sequence_name, level) {
  19443. // make sure multiple spaces in a row become a single space
  19444. combination = combination.replace(/\s+/g, ' ');
  19445. var sequence = combination.split(' '),
  19446. i,
  19447. key,
  19448. keys,
  19449. modifiers = [];
  19450. // if this pattern is a sequence of keys then run through this method
  19451. // to reprocess each pattern one key at a time
  19452. if (sequence.length > 1) {
  19453. return _bindSequence(combination, sequence, callback, action);
  19454. }
  19455. // take the keys from this pattern and figure out what the actual
  19456. // pattern is all about
  19457. keys = combination === '+' ? ['+'] : combination.split('+');
  19458. for (i = 0; i < keys.length; ++i) {
  19459. key = keys[i];
  19460. // normalize key names
  19461. if (_SPECIAL_ALIASES[key]) {
  19462. key = _SPECIAL_ALIASES[key];
  19463. }
  19464. // if this is not a keypress event then we should
  19465. // be smart about using shift keys
  19466. // this will only work for US keyboards however
  19467. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19468. key = _SHIFT_MAP[key];
  19469. modifiers.push('shift');
  19470. }
  19471. // if this key is a modifier then add it to the list of modifiers
  19472. if (_isModifier(key)) {
  19473. modifiers.push(key);
  19474. }
  19475. }
  19476. // depending on what the key combination is
  19477. // we will try to pick the best event for it
  19478. action = _pickBestAction(key, modifiers, action);
  19479. // make sure to initialize array if this is the first time
  19480. // a callback is added for this key
  19481. if (!_callbacks[key]) {
  19482. _callbacks[key] = [];
  19483. }
  19484. // remove an existing match if there is one
  19485. _getMatches(key, modifiers, action, !sequence_name, combination);
  19486. // add this call back to the array
  19487. // if it is a sequence put it at the beginning
  19488. // if not put it at the end
  19489. //
  19490. // this is important because the way these are processed expects
  19491. // the sequence ones to come first
  19492. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19493. callback: callback,
  19494. modifiers: modifiers,
  19495. action: action,
  19496. seq: sequence_name,
  19497. level: level,
  19498. combo: combination
  19499. });
  19500. }
  19501. /**
  19502. * binds multiple combinations to the same callback
  19503. *
  19504. * @param {Array} combinations
  19505. * @param {Function} callback
  19506. * @param {string|undefined} action
  19507. * @returns void
  19508. */
  19509. function _bindMultiple(combinations, callback, action) {
  19510. for (var i = 0; i < combinations.length; ++i) {
  19511. _bindSingle(combinations[i], callback, action);
  19512. }
  19513. }
  19514. // start!
  19515. _addEvent(document, 'keypress', _handleKey);
  19516. _addEvent(document, 'keydown', _handleKey);
  19517. _addEvent(document, 'keyup', _handleKey);
  19518. var mousetrap = {
  19519. /**
  19520. * binds an event to mousetrap
  19521. *
  19522. * can be a single key, a combination of keys separated with +,
  19523. * a comma separated list of keys, an array of keys, or
  19524. * a sequence of keys separated by spaces
  19525. *
  19526. * be sure to list the modifier keys first to make sure that the
  19527. * correct key ends up getting bound (the last key in the pattern)
  19528. *
  19529. * @param {string|Array} keys
  19530. * @param {Function} callback
  19531. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19532. * @returns void
  19533. */
  19534. bind: function(keys, callback, action) {
  19535. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19536. _direct_map[keys + ':' + action] = callback;
  19537. return this;
  19538. },
  19539. /**
  19540. * unbinds an event to mousetrap
  19541. *
  19542. * the unbinding sets the callback function of the specified key combo
  19543. * to an empty function and deletes the corresponding key in the
  19544. * _direct_map dict.
  19545. *
  19546. * the keycombo+action has to be exactly the same as
  19547. * it was defined in the bind method
  19548. *
  19549. * TODO: actually remove this from the _callbacks dictionary instead
  19550. * of binding an empty function
  19551. *
  19552. * @param {string|Array} keys
  19553. * @param {string} action
  19554. * @returns void
  19555. */
  19556. unbind: function(keys, action) {
  19557. if (_direct_map[keys + ':' + action]) {
  19558. delete _direct_map[keys + ':' + action];
  19559. this.bind(keys, function() {}, action);
  19560. }
  19561. return this;
  19562. },
  19563. /**
  19564. * triggers an event that has already been bound
  19565. *
  19566. * @param {string} keys
  19567. * @param {string=} action
  19568. * @returns void
  19569. */
  19570. trigger: function(keys, action) {
  19571. _direct_map[keys + ':' + action]();
  19572. return this;
  19573. },
  19574. /**
  19575. * resets the library back to its initial state. this is useful
  19576. * if you want to clear out the current keyboard shortcuts and bind
  19577. * new ones - for example if you switch to another page
  19578. *
  19579. * @returns void
  19580. */
  19581. reset: function() {
  19582. _callbacks = {};
  19583. _direct_map = {};
  19584. return this;
  19585. }
  19586. };
  19587. module.exports = mousetrap;
  19588. },{}]},{},[1])
  19589. (1)
  19590. });