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.

22563 lines
655 KiB

  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.7.0-SNAPSHOT
  8. * @date 2014-03-05
  9. *
  10. * @license
  11. * Copyright (C) 2011-2014 Almende B.V, http://almende.com
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  14. * use this file except in compliance with the License. You may obtain a copy
  15. * of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  22. * License for the specific language governing permissions and limitations under
  23. * the License.
  24. */
  25. !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.vis=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  26. /**
  27. * vis.js module imports
  28. */
  29. // Try to load dependencies from the global window object.
  30. // If not available there, load via require.
  31. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment');
  32. var Emitter = require('emitter-component');
  33. var Hammer;
  34. if (typeof window !== 'undefined') {
  35. // load hammer.js only when running in a browser (where window is available)
  36. Hammer = window['Hammer'] || require('hammerjs');
  37. }
  38. else {
  39. Hammer = function () {
  40. throw Error('hammer.js is only available in a browser, not in node.js.');
  41. }
  42. }
  43. var mousetrap;
  44. if (typeof window !== 'undefined') {
  45. // load mousetrap.js only when running in a browser (where window is available)
  46. mousetrap = window['mousetrap'] || require('mousetrap');
  47. }
  48. else {
  49. mousetrap = function () {
  50. throw Error('mouseTrap is only available in a browser, not in node.js.');
  51. }
  52. }
  53. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  54. // it here in that case.
  55. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  56. if(!Array.prototype.indexOf) {
  57. Array.prototype.indexOf = function(obj){
  58. for(var i = 0; i < this.length; i++){
  59. if(this[i] == obj){
  60. return i;
  61. }
  62. }
  63. return -1;
  64. };
  65. try {
  66. console.log("Warning: Ancient browser detected. Please update your browser");
  67. }
  68. catch (err) {
  69. }
  70. }
  71. // Internet Explorer 8 and older does not support Array.forEach, so we define
  72. // it here in that case.
  73. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  74. if (!Array.prototype.forEach) {
  75. Array.prototype.forEach = function(fn, scope) {
  76. for(var i = 0, len = this.length; i < len; ++i) {
  77. fn.call(scope || this, this[i], i, this);
  78. }
  79. }
  80. }
  81. // Internet Explorer 8 and older does not support Array.map, so we define it
  82. // here in that case.
  83. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  84. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  85. // Reference: http://es5.github.com/#x15.4.4.19
  86. if (!Array.prototype.map) {
  87. Array.prototype.map = function(callback, thisArg) {
  88. var T, A, k;
  89. if (this == null) {
  90. throw new TypeError(" this is null or not defined");
  91. }
  92. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  93. var O = Object(this);
  94. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  95. // 3. Let len be ToUint32(lenValue).
  96. var len = O.length >>> 0;
  97. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  98. // See: http://es5.github.com/#x9.11
  99. if (typeof callback !== "function") {
  100. throw new TypeError(callback + " is not a function");
  101. }
  102. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  103. if (thisArg) {
  104. T = thisArg;
  105. }
  106. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  107. // the standard built-in constructor with that name and len is the value of len.
  108. A = new Array(len);
  109. // 7. Let k be 0
  110. k = 0;
  111. // 8. Repeat, while k < len
  112. while(k < len) {
  113. var kValue, mappedValue;
  114. // a. Let Pk be ToString(k).
  115. // This is implicit for LHS operands of the in operator
  116. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  117. // This step can be combined with c
  118. // c. If kPresent is true, then
  119. if (k in O) {
  120. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  121. kValue = O[ k ];
  122. // ii. Let mappedValue be the result of calling the Call internal method of callback
  123. // with T as the this value and argument list containing kValue, k, and O.
  124. mappedValue = callback.call(T, kValue, k, O);
  125. // iii. Call the DefineOwnProperty internal method of A with arguments
  126. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  127. // and false.
  128. // In browsers that support Object.defineProperty, use the following:
  129. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  130. // For best browser support, use the following:
  131. A[ k ] = mappedValue;
  132. }
  133. // d. Increase k by 1.
  134. k++;
  135. }
  136. // 9. return A
  137. return A;
  138. };
  139. }
  140. // Internet Explorer 8 and older does not support Array.filter, so we define it
  141. // here in that case.
  142. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  143. if (!Array.prototype.filter) {
  144. Array.prototype.filter = function(fun /*, thisp */) {
  145. "use strict";
  146. if (this == null) {
  147. throw new TypeError();
  148. }
  149. var t = Object(this);
  150. var len = t.length >>> 0;
  151. if (typeof fun != "function") {
  152. throw new TypeError();
  153. }
  154. var res = [];
  155. var thisp = arguments[1];
  156. for (var i = 0; i < len; i++) {
  157. if (i in t) {
  158. var val = t[i]; // in case fun mutates this
  159. if (fun.call(thisp, val, i, t))
  160. res.push(val);
  161. }
  162. }
  163. return res;
  164. };
  165. }
  166. // Internet Explorer 8 and older does not support Object.keys, so we define it
  167. // here in that case.
  168. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  169. if (!Object.keys) {
  170. Object.keys = (function () {
  171. var hasOwnProperty = Object.prototype.hasOwnProperty,
  172. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  173. dontEnums = [
  174. 'toString',
  175. 'toLocaleString',
  176. 'valueOf',
  177. 'hasOwnProperty',
  178. 'isPrototypeOf',
  179. 'propertyIsEnumerable',
  180. 'constructor'
  181. ],
  182. dontEnumsLength = dontEnums.length;
  183. return function (obj) {
  184. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  185. throw new TypeError('Object.keys called on non-object');
  186. }
  187. var result = [];
  188. for (var prop in obj) {
  189. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  190. }
  191. if (hasDontEnumBug) {
  192. for (var i=0; i < dontEnumsLength; i++) {
  193. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  194. }
  195. }
  196. return result;
  197. }
  198. })()
  199. }
  200. // Internet Explorer 8 and older does not support Array.isArray,
  201. // so we define it here in that case.
  202. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  203. if(!Array.isArray) {
  204. Array.isArray = function (vArg) {
  205. return Object.prototype.toString.call(vArg) === "[object Array]";
  206. };
  207. }
  208. // Internet Explorer 8 and older does not support Function.bind,
  209. // so we define it here in that case.
  210. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  211. if (!Function.prototype.bind) {
  212. Function.prototype.bind = function (oThis) {
  213. if (typeof this !== "function") {
  214. // closest thing possible to the ECMAScript 5 internal IsCallable function
  215. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  216. }
  217. var aArgs = Array.prototype.slice.call(arguments, 1),
  218. fToBind = this,
  219. fNOP = function () {},
  220. fBound = function () {
  221. return fToBind.apply(this instanceof fNOP && oThis
  222. ? this
  223. : oThis,
  224. aArgs.concat(Array.prototype.slice.call(arguments)));
  225. };
  226. fNOP.prototype = this.prototype;
  227. fBound.prototype = new fNOP();
  228. return fBound;
  229. };
  230. }
  231. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  232. if (!Object.create) {
  233. Object.create = function (o) {
  234. if (arguments.length > 1) {
  235. throw new Error('Object.create implementation only accepts the first parameter.');
  236. }
  237. function F() {}
  238. F.prototype = o;
  239. return new F();
  240. };
  241. }
  242. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  243. if (!Function.prototype.bind) {
  244. Function.prototype.bind = function (oThis) {
  245. if (typeof this !== "function") {
  246. // closest thing possible to the ECMAScript 5 internal IsCallable function
  247. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  248. }
  249. var aArgs = Array.prototype.slice.call(arguments, 1),
  250. fToBind = this,
  251. fNOP = function () {},
  252. fBound = function () {
  253. return fToBind.apply(this instanceof fNOP && oThis
  254. ? this
  255. : oThis,
  256. aArgs.concat(Array.prototype.slice.call(arguments)));
  257. };
  258. fNOP.prototype = this.prototype;
  259. fBound.prototype = new fNOP();
  260. return fBound;
  261. };
  262. }
  263. /**
  264. * utility functions
  265. */
  266. var util = {};
  267. /**
  268. * Test whether given object is a number
  269. * @param {*} object
  270. * @return {Boolean} isNumber
  271. */
  272. util.isNumber = function isNumber(object) {
  273. return (object instanceof Number || typeof object == 'number');
  274. };
  275. /**
  276. * Test whether given object is a string
  277. * @param {*} object
  278. * @return {Boolean} isString
  279. */
  280. util.isString = function isString(object) {
  281. return (object instanceof String || typeof object == 'string');
  282. };
  283. /**
  284. * Test whether given object is a Date, or a String containing a Date
  285. * @param {Date | String} object
  286. * @return {Boolean} isDate
  287. */
  288. util.isDate = function isDate(object) {
  289. if (object instanceof Date) {
  290. return true;
  291. }
  292. else if (util.isString(object)) {
  293. // test whether this string contains a date
  294. var match = ASPDateRegex.exec(object);
  295. if (match) {
  296. return true;
  297. }
  298. else if (!isNaN(Date.parse(object))) {
  299. return true;
  300. }
  301. }
  302. return false;
  303. };
  304. /**
  305. * Test whether given object is an instance of google.visualization.DataTable
  306. * @param {*} object
  307. * @return {Boolean} isDataTable
  308. */
  309. util.isDataTable = function isDataTable(object) {
  310. return (typeof (google) !== 'undefined') &&
  311. (google.visualization) &&
  312. (google.visualization.DataTable) &&
  313. (object instanceof google.visualization.DataTable);
  314. };
  315. /**
  316. * Create a semi UUID
  317. * source: http://stackoverflow.com/a/105074/1262753
  318. * @return {String} uuid
  319. */
  320. util.randomUUID = function randomUUID () {
  321. var S4 = function () {
  322. return Math.floor(
  323. Math.random() * 0x10000 /* 65536 */
  324. ).toString(16);
  325. };
  326. return (
  327. S4() + S4() + '-' +
  328. S4() + '-' +
  329. S4() + '-' +
  330. S4() + '-' +
  331. S4() + S4() + S4()
  332. );
  333. };
  334. /**
  335. * Extend object a with the properties of object b or a series of objects
  336. * Only properties with defined values are copied
  337. * @param {Object} a
  338. * @param {... Object} b
  339. * @return {Object} a
  340. */
  341. util.extend = function (a, b) {
  342. for (var i = 1, len = arguments.length; i < len; i++) {
  343. var other = arguments[i];
  344. for (var prop in other) {
  345. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  346. a[prop] = other[prop];
  347. }
  348. }
  349. }
  350. return a;
  351. };
  352. /**
  353. * Convert an object to another type
  354. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  355. * @param {String | undefined} type Name of the type. Available types:
  356. * 'Boolean', 'Number', 'String',
  357. * 'Date', 'Moment', ISODate', 'ASPDate'.
  358. * @return {*} object
  359. * @throws Error
  360. */
  361. util.convert = function convert(object, type) {
  362. var match;
  363. if (object === undefined) {
  364. return undefined;
  365. }
  366. if (object === null) {
  367. return null;
  368. }
  369. if (!type) {
  370. return object;
  371. }
  372. if (!(typeof type === 'string') && !(type instanceof String)) {
  373. throw new Error('Type must be a string');
  374. }
  375. //noinspection FallthroughInSwitchStatementJS
  376. switch (type) {
  377. case 'boolean':
  378. case 'Boolean':
  379. return Boolean(object);
  380. case 'number':
  381. case 'Number':
  382. return Number(object.valueOf());
  383. case 'string':
  384. case 'String':
  385. return String(object);
  386. case 'Date':
  387. if (util.isNumber(object)) {
  388. return new Date(object);
  389. }
  390. if (object instanceof Date) {
  391. return new Date(object.valueOf());
  392. }
  393. else if (moment.isMoment(object)) {
  394. return new Date(object.valueOf());
  395. }
  396. if (util.isString(object)) {
  397. match = ASPDateRegex.exec(object);
  398. if (match) {
  399. // object is an ASP date
  400. return new Date(Number(match[1])); // parse number
  401. }
  402. else {
  403. return moment(object).toDate(); // parse string
  404. }
  405. }
  406. else {
  407. throw new Error(
  408. 'Cannot convert object of type ' + util.getType(object) +
  409. ' to type Date');
  410. }
  411. case 'Moment':
  412. if (util.isNumber(object)) {
  413. return moment(object);
  414. }
  415. if (object instanceof Date) {
  416. return moment(object.valueOf());
  417. }
  418. else if (moment.isMoment(object)) {
  419. return moment(object);
  420. }
  421. if (util.isString(object)) {
  422. match = ASPDateRegex.exec(object);
  423. if (match) {
  424. // object is an ASP date
  425. return moment(Number(match[1])); // parse number
  426. }
  427. else {
  428. return moment(object); // parse string
  429. }
  430. }
  431. else {
  432. throw new Error(
  433. 'Cannot convert object of type ' + util.getType(object) +
  434. ' to type Date');
  435. }
  436. case 'ISODate':
  437. if (util.isNumber(object)) {
  438. return new Date(object);
  439. }
  440. else if (object instanceof Date) {
  441. return object.toISOString();
  442. }
  443. else if (moment.isMoment(object)) {
  444. return object.toDate().toISOString();
  445. }
  446. else if (util.isString(object)) {
  447. match = ASPDateRegex.exec(object);
  448. if (match) {
  449. // object is an ASP date
  450. return new Date(Number(match[1])).toISOString(); // parse number
  451. }
  452. else {
  453. return new Date(object).toISOString(); // parse string
  454. }
  455. }
  456. else {
  457. throw new Error(
  458. 'Cannot convert object of type ' + util.getType(object) +
  459. ' to type ISODate');
  460. }
  461. case 'ASPDate':
  462. if (util.isNumber(object)) {
  463. return '/Date(' + object + ')/';
  464. }
  465. else if (object instanceof Date) {
  466. return '/Date(' + object.valueOf() + ')/';
  467. }
  468. else if (util.isString(object)) {
  469. match = ASPDateRegex.exec(object);
  470. var value;
  471. if (match) {
  472. // object is an ASP date
  473. value = new Date(Number(match[1])).valueOf(); // parse number
  474. }
  475. else {
  476. value = new Date(object).valueOf(); // parse string
  477. }
  478. return '/Date(' + value + ')/';
  479. }
  480. else {
  481. throw new Error(
  482. 'Cannot convert object of type ' + util.getType(object) +
  483. ' to type ASPDate');
  484. }
  485. default:
  486. throw new Error('Cannot convert object of type ' + util.getType(object) +
  487. ' to type "' + type + '"');
  488. }
  489. };
  490. // parse ASP.Net Date pattern,
  491. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  492. // code from http://momentjs.com/
  493. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  494. /**
  495. * Get the type of an object, for example util.getType([]) returns 'Array'
  496. * @param {*} object
  497. * @return {String} type
  498. */
  499. util.getType = function getType(object) {
  500. var type = typeof object;
  501. if (type == 'object') {
  502. if (object == null) {
  503. return 'null';
  504. }
  505. if (object instanceof Boolean) {
  506. return 'Boolean';
  507. }
  508. if (object instanceof Number) {
  509. return 'Number';
  510. }
  511. if (object instanceof String) {
  512. return 'String';
  513. }
  514. if (object instanceof Array) {
  515. return 'Array';
  516. }
  517. if (object instanceof Date) {
  518. return 'Date';
  519. }
  520. return 'Object';
  521. }
  522. else if (type == 'number') {
  523. return 'Number';
  524. }
  525. else if (type == 'boolean') {
  526. return 'Boolean';
  527. }
  528. else if (type == 'string') {
  529. return 'String';
  530. }
  531. return type;
  532. };
  533. /**
  534. * Retrieve the absolute left value of a DOM element
  535. * @param {Element} elem A dom element, for example a div
  536. * @return {number} left The absolute left position of this element
  537. * in the browser page.
  538. */
  539. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  540. var doc = document.documentElement;
  541. var body = document.body;
  542. var left = elem.offsetLeft;
  543. var e = elem.offsetParent;
  544. while (e != null && e != body && e != doc) {
  545. left += e.offsetLeft;
  546. left -= e.scrollLeft;
  547. e = e.offsetParent;
  548. }
  549. return left;
  550. };
  551. /**
  552. * Retrieve the absolute top value of a DOM element
  553. * @param {Element} elem A dom element, for example a div
  554. * @return {number} top The absolute top position of this element
  555. * in the browser page.
  556. */
  557. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  558. var doc = document.documentElement;
  559. var body = document.body;
  560. var top = elem.offsetTop;
  561. var e = elem.offsetParent;
  562. while (e != null && e != body && e != doc) {
  563. top += e.offsetTop;
  564. top -= e.scrollTop;
  565. e = e.offsetParent;
  566. }
  567. return top;
  568. };
  569. /**
  570. * Get the absolute, vertical mouse position from an event.
  571. * @param {Event} event
  572. * @return {Number} pageY
  573. */
  574. util.getPageY = function getPageY (event) {
  575. if ('pageY' in event) {
  576. return event.pageY;
  577. }
  578. else {
  579. var clientY;
  580. if (('targetTouches' in event) && event.targetTouches.length) {
  581. clientY = event.targetTouches[0].clientY;
  582. }
  583. else {
  584. clientY = event.clientY;
  585. }
  586. var doc = document.documentElement;
  587. var body = document.body;
  588. return clientY +
  589. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  590. ( doc && doc.clientTop || body && body.clientTop || 0 );
  591. }
  592. };
  593. /**
  594. * Get the absolute, horizontal mouse position from an event.
  595. * @param {Event} event
  596. * @return {Number} pageX
  597. */
  598. util.getPageX = function getPageX (event) {
  599. if ('pageY' in event) {
  600. return event.pageX;
  601. }
  602. else {
  603. var clientX;
  604. if (('targetTouches' in event) && event.targetTouches.length) {
  605. clientX = event.targetTouches[0].clientX;
  606. }
  607. else {
  608. clientX = event.clientX;
  609. }
  610. var doc = document.documentElement;
  611. var body = document.body;
  612. return clientX +
  613. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  614. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  615. }
  616. };
  617. /**
  618. * add a className to the given elements style
  619. * @param {Element} elem
  620. * @param {String} className
  621. */
  622. util.addClassName = function addClassName(elem, className) {
  623. var classes = elem.className.split(' ');
  624. if (classes.indexOf(className) == -1) {
  625. classes.push(className); // add the class to the array
  626. elem.className = classes.join(' ');
  627. }
  628. };
  629. /**
  630. * add a className to the given elements style
  631. * @param {Element} elem
  632. * @param {String} className
  633. */
  634. util.removeClassName = function removeClassname(elem, className) {
  635. var classes = elem.className.split(' ');
  636. var index = classes.indexOf(className);
  637. if (index != -1) {
  638. classes.splice(index, 1); // remove the class from the array
  639. elem.className = classes.join(' ');
  640. }
  641. };
  642. /**
  643. * For each method for both arrays and objects.
  644. * In case of an array, the built-in Array.forEach() is applied.
  645. * In case of an Object, the method loops over all properties of the object.
  646. * @param {Object | Array} object An Object or Array
  647. * @param {function} callback Callback method, called for each item in
  648. * the object or array with three parameters:
  649. * callback(value, index, object)
  650. */
  651. util.forEach = function forEach (object, callback) {
  652. var i,
  653. len;
  654. if (object instanceof Array) {
  655. // array
  656. for (i = 0, len = object.length; i < len; i++) {
  657. callback(object[i], i, object);
  658. }
  659. }
  660. else {
  661. // object
  662. for (i in object) {
  663. if (object.hasOwnProperty(i)) {
  664. callback(object[i], i, object);
  665. }
  666. }
  667. }
  668. };
  669. /**
  670. * Update a property in an object
  671. * @param {Object} object
  672. * @param {String} key
  673. * @param {*} value
  674. * @return {Boolean} changed
  675. */
  676. util.updateProperty = function updateProp (object, key, value) {
  677. if (object[key] !== value) {
  678. object[key] = value;
  679. return true;
  680. }
  681. else {
  682. return false;
  683. }
  684. };
  685. /**
  686. * Add and event listener. Works for all browsers
  687. * @param {Element} element An html element
  688. * @param {string} action The action, for example "click",
  689. * without the prefix "on"
  690. * @param {function} listener The callback function to be executed
  691. * @param {boolean} [useCapture]
  692. */
  693. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  694. if (element.addEventListener) {
  695. if (useCapture === undefined)
  696. useCapture = false;
  697. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  698. action = "DOMMouseScroll"; // For Firefox
  699. }
  700. element.addEventListener(action, listener, useCapture);
  701. } else {
  702. element.attachEvent("on" + action, listener); // IE browsers
  703. }
  704. };
  705. /**
  706. * Remove an event listener from an element
  707. * @param {Element} element An html dom element
  708. * @param {string} action The name of the event, for example "mousedown"
  709. * @param {function} listener The listener function
  710. * @param {boolean} [useCapture]
  711. */
  712. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  713. if (element.removeEventListener) {
  714. // non-IE browsers
  715. if (useCapture === undefined)
  716. useCapture = false;
  717. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  718. action = "DOMMouseScroll"; // For Firefox
  719. }
  720. element.removeEventListener(action, listener, useCapture);
  721. } else {
  722. // IE browsers
  723. element.detachEvent("on" + action, listener);
  724. }
  725. };
  726. /**
  727. * Get HTML element which is the target of the event
  728. * @param {Event} event
  729. * @return {Element} target element
  730. */
  731. util.getTarget = function getTarget(event) {
  732. // code from http://www.quirksmode.org/js/events_properties.html
  733. if (!event) {
  734. event = window.event;
  735. }
  736. var target;
  737. if (event.target) {
  738. target = event.target;
  739. }
  740. else if (event.srcElement) {
  741. target = event.srcElement;
  742. }
  743. if (target.nodeType != undefined && target.nodeType == 3) {
  744. // defeat Safari bug
  745. target = target.parentNode;
  746. }
  747. return target;
  748. };
  749. /**
  750. * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
  751. * @param {Element} element
  752. * @param {Event} event
  753. */
  754. util.fakeGesture = function fakeGesture (element, event) {
  755. var eventType = null;
  756. // for hammer.js 1.0.5
  757. var gesture = Hammer.event.collectEventData(this, eventType, event);
  758. // for hammer.js 1.0.6
  759. //var touches = Hammer.event.getTouchList(event, eventType);
  760. // var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
  761. // on IE in standards mode, no touches are recognized by hammer.js,
  762. // resulting in NaN values for center.pageX and center.pageY
  763. if (isNaN(gesture.center.pageX)) {
  764. gesture.center.pageX = event.pageX;
  765. }
  766. if (isNaN(gesture.center.pageY)) {
  767. gesture.center.pageY = event.pageY;
  768. }
  769. return gesture;
  770. };
  771. util.option = {};
  772. /**
  773. * Convert a value into a boolean
  774. * @param {Boolean | function | undefined} value
  775. * @param {Boolean} [defaultValue]
  776. * @returns {Boolean} bool
  777. */
  778. util.option.asBoolean = function (value, defaultValue) {
  779. if (typeof value == 'function') {
  780. value = value();
  781. }
  782. if (value != null) {
  783. return (value != false);
  784. }
  785. return defaultValue || null;
  786. };
  787. /**
  788. * Convert a value into a number
  789. * @param {Boolean | function | undefined} value
  790. * @param {Number} [defaultValue]
  791. * @returns {Number} number
  792. */
  793. util.option.asNumber = function (value, defaultValue) {
  794. if (typeof value == 'function') {
  795. value = value();
  796. }
  797. if (value != null) {
  798. return Number(value) || defaultValue || null;
  799. }
  800. return defaultValue || null;
  801. };
  802. /**
  803. * Convert a value into a string
  804. * @param {String | function | undefined} value
  805. * @param {String} [defaultValue]
  806. * @returns {String} str
  807. */
  808. util.option.asString = function (value, defaultValue) {
  809. if (typeof value == 'function') {
  810. value = value();
  811. }
  812. if (value != null) {
  813. return String(value);
  814. }
  815. return defaultValue || null;
  816. };
  817. /**
  818. * Convert a size or location into a string with pixels or a percentage
  819. * @param {String | Number | function | undefined} value
  820. * @param {String} [defaultValue]
  821. * @returns {String} size
  822. */
  823. util.option.asSize = function (value, defaultValue) {
  824. if (typeof value == 'function') {
  825. value = value();
  826. }
  827. if (util.isString(value)) {
  828. return value;
  829. }
  830. else if (util.isNumber(value)) {
  831. return value + 'px';
  832. }
  833. else {
  834. return defaultValue || null;
  835. }
  836. };
  837. /**
  838. * Convert a value into a DOM element
  839. * @param {HTMLElement | function | undefined} value
  840. * @param {HTMLElement} [defaultValue]
  841. * @returns {HTMLElement | null} dom
  842. */
  843. util.option.asElement = function (value, defaultValue) {
  844. if (typeof value == 'function') {
  845. value = value();
  846. }
  847. return value || defaultValue || null;
  848. };
  849. util.GiveDec = function GiveDec(Hex)
  850. {
  851. if(Hex == "A")
  852. Value = 10;
  853. else
  854. if(Hex == "B")
  855. Value = 11;
  856. else
  857. if(Hex == "C")
  858. Value = 12;
  859. else
  860. if(Hex == "D")
  861. Value = 13;
  862. else
  863. if(Hex == "E")
  864. Value = 14;
  865. else
  866. if(Hex == "F")
  867. Value = 15;
  868. else
  869. Value = eval(Hex)
  870. return Value;
  871. }
  872. util.GiveHex = function GiveHex(Dec)
  873. {
  874. if(Dec == 10)
  875. Value = "A";
  876. else
  877. if(Dec == 11)
  878. Value = "B";
  879. else
  880. if(Dec == 12)
  881. Value = "C";
  882. else
  883. if(Dec == 13)
  884. Value = "D";
  885. else
  886. if(Dec == 14)
  887. Value = "E";
  888. else
  889. if(Dec == 15)
  890. Value = "F";
  891. else
  892. Value = "" + Dec;
  893. return Value;
  894. }
  895. /**
  896. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  897. *
  898. * @param {String} hex
  899. * @returns {{r: *, g: *, b: *}}
  900. */
  901. util.hexToRGB = function hexToRGB(hex) {
  902. hex = hex.replace("#","").toUpperCase();
  903. var a = util.GiveDec(hex.substring(0, 1));
  904. var b = util.GiveDec(hex.substring(1, 2));
  905. var c = util.GiveDec(hex.substring(2, 3));
  906. var d = util.GiveDec(hex.substring(3, 4));
  907. var e = util.GiveDec(hex.substring(4, 5));
  908. var f = util.GiveDec(hex.substring(5, 6));
  909. var r = (a * 16) + b;
  910. var g = (c * 16) + d;
  911. var b = (e * 16) + f;
  912. return {r:r,g:g,b:b};
  913. };
  914. util.RGBToHex = function RGBToHex(red,green,blue) {
  915. var a = util.GiveHex(Math.floor(red / 16));
  916. var b = util.GiveHex(red % 16);
  917. var c = util.GiveHex(Math.floor(green / 16));
  918. var d = util.GiveHex(green % 16);
  919. var e = util.GiveHex(Math.floor(blue / 16));
  920. var f = util.GiveHex(blue % 16);
  921. var hex = a + b + c + d + e + f;
  922. return "#" + hex;
  923. };
  924. /**
  925. * http://www.javascripter.net/faq/rgb2hsv.htm
  926. *
  927. * @param red
  928. * @param green
  929. * @param blue
  930. * @returns {*}
  931. * @constructor
  932. */
  933. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  934. red=red/255; green=green/255; blue=blue/255;
  935. var minRGB = Math.min(red,Math.min(green,blue));
  936. var maxRGB = Math.max(red,Math.max(green,blue));
  937. // Black-gray-white
  938. if (minRGB == maxRGB) {
  939. return {h:0,s:0,v:minRGB};
  940. }
  941. // Colors other than black-gray-white:
  942. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  943. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  944. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  945. var saturation = (maxRGB - minRGB)/maxRGB;
  946. var value = maxRGB;
  947. return {h:hue,s:saturation,v:value};
  948. };
  949. /**
  950. * https://gist.github.com/mjijackson/5311256
  951. * @param hue
  952. * @param saturation
  953. * @param value
  954. * @returns {{r: number, g: number, b: number}}
  955. * @constructor
  956. */
  957. util.HSVToRGB = function HSVToRGB(h, s, v) {
  958. var r, g, b;
  959. var i = Math.floor(h * 6);
  960. var f = h * 6 - i;
  961. var p = v * (1 - s);
  962. var q = v * (1 - f * s);
  963. var t = v * (1 - (1 - f) * s);
  964. switch (i % 6) {
  965. case 0: r = v, g = t, b = p; break;
  966. case 1: r = q, g = v, b = p; break;
  967. case 2: r = p, g = v, b = t; break;
  968. case 3: r = p, g = q, b = v; break;
  969. case 4: r = t, g = p, b = v; break;
  970. case 5: r = v, g = p, b = q; break;
  971. }
  972. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  973. };
  974. util.HSVToHex = function HSVToHex(h,s,v) {
  975. var rgb = util.HSVToRGB(h,s,v);
  976. return util.RGBToHex(rgb.r,rgb.g,rgb.b);
  977. }
  978. util.hexToHSV = function hexToHSV(hex) {
  979. var rgb = util.hexToRGB(hex);
  980. return util.RGBToHSV(rgb.r,rgb.g,rgb.b);
  981. }
  982. util.isValidHex = function isValidHex(hex) {
  983. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  984. return isOk;
  985. }
  986. /**
  987. * DataSet
  988. *
  989. * Usage:
  990. * var dataSet = new DataSet({
  991. * fieldId: '_id',
  992. * convert: {
  993. * // ...
  994. * }
  995. * });
  996. *
  997. * dataSet.add(item);
  998. * dataSet.add(data);
  999. * dataSet.update(item);
  1000. * dataSet.update(data);
  1001. * dataSet.remove(id);
  1002. * dataSet.remove(ids);
  1003. * var data = dataSet.get();
  1004. * var data = dataSet.get(id);
  1005. * var data = dataSet.get(ids);
  1006. * var data = dataSet.get(ids, options, data);
  1007. * dataSet.clear();
  1008. *
  1009. * A data set can:
  1010. * - add/remove/update data
  1011. * - gives triggers upon changes in the data
  1012. * - can import/export data in various data formats
  1013. *
  1014. * @param {Object} [options] Available options:
  1015. * {String} fieldId Field name of the id in the
  1016. * items, 'id' by default.
  1017. * {Object.<String, String} convert
  1018. * A map with field names as key,
  1019. * and the field type as value.
  1020. * @constructor DataSet
  1021. */
  1022. // TODO: add a DataSet constructor DataSet(data, options)
  1023. function DataSet (options) {
  1024. this.id = util.randomUUID();
  1025. this.options = options || {};
  1026. this.data = {}; // map with data indexed by id
  1027. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1028. this.convert = {}; // field types by field name
  1029. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1030. if (this.options.convert) {
  1031. for (var field in this.options.convert) {
  1032. if (this.options.convert.hasOwnProperty(field)) {
  1033. var value = this.options.convert[field];
  1034. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1035. this.convert[field] = 'Date';
  1036. }
  1037. else {
  1038. this.convert[field] = value;
  1039. }
  1040. }
  1041. }
  1042. }
  1043. // event subscribers
  1044. this.subscribers = {};
  1045. this.internalIds = {}; // internally generated id's
  1046. }
  1047. /**
  1048. * Subscribe to an event, add an event listener
  1049. * @param {String} event Event name. Available events: 'put', 'update',
  1050. * 'remove'
  1051. * @param {function} callback Callback method. Called with three parameters:
  1052. * {String} event
  1053. * {Object | null} params
  1054. * {String | Number} senderId
  1055. */
  1056. DataSet.prototype.on = function on (event, callback) {
  1057. var subscribers = this.subscribers[event];
  1058. if (!subscribers) {
  1059. subscribers = [];
  1060. this.subscribers[event] = subscribers;
  1061. }
  1062. subscribers.push({
  1063. callback: callback
  1064. });
  1065. };
  1066. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1067. DataSet.prototype.subscribe = DataSet.prototype.on;
  1068. /**
  1069. * Unsubscribe from an event, remove an event listener
  1070. * @param {String} event
  1071. * @param {function} callback
  1072. */
  1073. DataSet.prototype.off = function off(event, callback) {
  1074. var subscribers = this.subscribers[event];
  1075. if (subscribers) {
  1076. this.subscribers[event] = subscribers.filter(function (listener) {
  1077. return (listener.callback != callback);
  1078. });
  1079. }
  1080. };
  1081. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1082. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1083. /**
  1084. * Trigger an event
  1085. * @param {String} event
  1086. * @param {Object | null} params
  1087. * @param {String} [senderId] Optional id of the sender.
  1088. * @private
  1089. */
  1090. DataSet.prototype._trigger = function (event, params, senderId) {
  1091. if (event == '*') {
  1092. throw new Error('Cannot trigger event *');
  1093. }
  1094. var subscribers = [];
  1095. if (event in this.subscribers) {
  1096. subscribers = subscribers.concat(this.subscribers[event]);
  1097. }
  1098. if ('*' in this.subscribers) {
  1099. subscribers = subscribers.concat(this.subscribers['*']);
  1100. }
  1101. for (var i = 0; i < subscribers.length; i++) {
  1102. var subscriber = subscribers[i];
  1103. if (subscriber.callback) {
  1104. subscriber.callback(event, params, senderId || null);
  1105. }
  1106. }
  1107. };
  1108. /**
  1109. * Add data.
  1110. * Adding an item will fail when there already is an item with the same id.
  1111. * @param {Object | Array | DataTable} data
  1112. * @param {String} [senderId] Optional sender id
  1113. * @return {Array} addedIds Array with the ids of the added items
  1114. */
  1115. DataSet.prototype.add = function (data, senderId) {
  1116. var addedIds = [],
  1117. id,
  1118. me = this;
  1119. if (data instanceof Array) {
  1120. // Array
  1121. for (var i = 0, len = data.length; i < len; i++) {
  1122. id = me._addItem(data[i]);
  1123. addedIds.push(id);
  1124. }
  1125. }
  1126. else if (util.isDataTable(data)) {
  1127. // Google DataTable
  1128. var columns = this._getColumnNames(data);
  1129. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1130. var item = {};
  1131. for (var col = 0, cols = columns.length; col < cols; col++) {
  1132. var field = columns[col];
  1133. item[field] = data.getValue(row, col);
  1134. }
  1135. id = me._addItem(item);
  1136. addedIds.push(id);
  1137. }
  1138. }
  1139. else if (data instanceof Object) {
  1140. // Single item
  1141. id = me._addItem(data);
  1142. addedIds.push(id);
  1143. }
  1144. else {
  1145. throw new Error('Unknown dataType');
  1146. }
  1147. if (addedIds.length) {
  1148. this._trigger('add', {items: addedIds}, senderId);
  1149. }
  1150. return addedIds;
  1151. };
  1152. /**
  1153. * Update existing items. When an item does not exist, it will be created
  1154. * @param {Object | Array | DataTable} data
  1155. * @param {String} [senderId] Optional sender id
  1156. * @return {Array} updatedIds The ids of the added or updated items
  1157. */
  1158. DataSet.prototype.update = function (data, senderId) {
  1159. var addedIds = [],
  1160. updatedIds = [],
  1161. me = this,
  1162. fieldId = me.fieldId;
  1163. var addOrUpdate = function (item) {
  1164. var id = item[fieldId];
  1165. if (me.data[id]) {
  1166. // update item
  1167. id = me._updateItem(item);
  1168. updatedIds.push(id);
  1169. }
  1170. else {
  1171. // add new item
  1172. id = me._addItem(item);
  1173. addedIds.push(id);
  1174. }
  1175. };
  1176. if (data instanceof Array) {
  1177. // Array
  1178. for (var i = 0, len = data.length; i < len; i++) {
  1179. addOrUpdate(data[i]);
  1180. }
  1181. }
  1182. else if (util.isDataTable(data)) {
  1183. // Google DataTable
  1184. var columns = this._getColumnNames(data);
  1185. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1186. var item = {};
  1187. for (var col = 0, cols = columns.length; col < cols; col++) {
  1188. var field = columns[col];
  1189. item[field] = data.getValue(row, col);
  1190. }
  1191. addOrUpdate(item);
  1192. }
  1193. }
  1194. else if (data instanceof Object) {
  1195. // Single item
  1196. addOrUpdate(data);
  1197. }
  1198. else {
  1199. throw new Error('Unknown dataType');
  1200. }
  1201. if (addedIds.length) {
  1202. this._trigger('add', {items: addedIds}, senderId);
  1203. }
  1204. if (updatedIds.length) {
  1205. this._trigger('update', {items: updatedIds}, senderId);
  1206. }
  1207. return addedIds.concat(updatedIds);
  1208. };
  1209. /**
  1210. * Get a data item or multiple items.
  1211. *
  1212. * Usage:
  1213. *
  1214. * get()
  1215. * get(options: Object)
  1216. * get(options: Object, data: Array | DataTable)
  1217. *
  1218. * get(id: Number | String)
  1219. * get(id: Number | String, options: Object)
  1220. * get(id: Number | String, options: Object, data: Array | DataTable)
  1221. *
  1222. * get(ids: Number[] | String[])
  1223. * get(ids: Number[] | String[], options: Object)
  1224. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1225. *
  1226. * Where:
  1227. *
  1228. * {Number | String} id The id of an item
  1229. * {Number[] | String{}} ids An array with ids of items
  1230. * {Object} options An Object with options. Available options:
  1231. * {String} [type] Type of data to be returned. Can
  1232. * be 'DataTable' or 'Array' (default)
  1233. * {Object.<String, String>} [convert]
  1234. * {String[]} [fields] field names to be returned
  1235. * {function} [filter] filter items
  1236. * {String | function} [order] Order the items by
  1237. * a field name or custom sort function.
  1238. * {Array | DataTable} [data] If provided, items will be appended to this
  1239. * array or table. Required in case of Google
  1240. * DataTable.
  1241. *
  1242. * @throws Error
  1243. */
  1244. DataSet.prototype.get = function (args) {
  1245. var me = this;
  1246. var globalShowInternalIds = this.showInternalIds;
  1247. // parse the arguments
  1248. var id, ids, options, data;
  1249. var firstType = util.getType(arguments[0]);
  1250. if (firstType == 'String' || firstType == 'Number') {
  1251. // get(id [, options] [, data])
  1252. id = arguments[0];
  1253. options = arguments[1];
  1254. data = arguments[2];
  1255. }
  1256. else if (firstType == 'Array') {
  1257. // get(ids [, options] [, data])
  1258. ids = arguments[0];
  1259. options = arguments[1];
  1260. data = arguments[2];
  1261. }
  1262. else {
  1263. // get([, options] [, data])
  1264. options = arguments[0];
  1265. data = arguments[1];
  1266. }
  1267. // determine the return type
  1268. var type;
  1269. if (options && options.type) {
  1270. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1271. if (data && (type != util.getType(data))) {
  1272. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1273. 'does not correspond with specified options.type (' + options.type + ')');
  1274. }
  1275. if (type == 'DataTable' && !util.isDataTable(data)) {
  1276. throw new Error('Parameter "data" must be a DataTable ' +
  1277. 'when options.type is "DataTable"');
  1278. }
  1279. }
  1280. else if (data) {
  1281. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1282. }
  1283. else {
  1284. type = 'Array';
  1285. }
  1286. // we allow the setting of this value for a single get request.
  1287. if (options != undefined) {
  1288. if (options.showInternalIds != undefined) {
  1289. this.showInternalIds = options.showInternalIds;
  1290. }
  1291. }
  1292. // build options
  1293. var convert = options && options.convert || this.options.convert;
  1294. var filter = options && options.filter;
  1295. var items = [], item, itemId, i, len;
  1296. // convert items
  1297. if (id != undefined) {
  1298. // return a single item
  1299. item = me._getItem(id, convert);
  1300. if (filter && !filter(item)) {
  1301. item = null;
  1302. }
  1303. }
  1304. else if (ids != undefined) {
  1305. // return a subset of items
  1306. for (i = 0, len = ids.length; i < len; i++) {
  1307. item = me._getItem(ids[i], convert);
  1308. if (!filter || filter(item)) {
  1309. items.push(item);
  1310. }
  1311. }
  1312. }
  1313. else {
  1314. // return all items
  1315. for (itemId in this.data) {
  1316. if (this.data.hasOwnProperty(itemId)) {
  1317. item = me._getItem(itemId, convert);
  1318. if (!filter || filter(item)) {
  1319. items.push(item);
  1320. }
  1321. }
  1322. }
  1323. }
  1324. // restore the global value of showInternalIds
  1325. this.showInternalIds = globalShowInternalIds;
  1326. // order the results
  1327. if (options && options.order && id == undefined) {
  1328. this._sort(items, options.order);
  1329. }
  1330. // filter fields of the items
  1331. if (options && options.fields) {
  1332. var fields = options.fields;
  1333. if (id != undefined) {
  1334. item = this._filterFields(item, fields);
  1335. }
  1336. else {
  1337. for (i = 0, len = items.length; i < len; i++) {
  1338. items[i] = this._filterFields(items[i], fields);
  1339. }
  1340. }
  1341. }
  1342. // return the results
  1343. if (type == 'DataTable') {
  1344. var columns = this._getColumnNames(data);
  1345. if (id != undefined) {
  1346. // append a single item to the data table
  1347. me._appendRow(data, columns, item);
  1348. }
  1349. else {
  1350. // copy the items to the provided data table
  1351. for (i = 0, len = items.length; i < len; i++) {
  1352. me._appendRow(data, columns, items[i]);
  1353. }
  1354. }
  1355. return data;
  1356. }
  1357. else {
  1358. // return an array
  1359. if (id != undefined) {
  1360. // a single item
  1361. return item;
  1362. }
  1363. else {
  1364. // multiple items
  1365. if (data) {
  1366. // copy the items to the provided array
  1367. for (i = 0, len = items.length; i < len; i++) {
  1368. data.push(items[i]);
  1369. }
  1370. return data;
  1371. }
  1372. else {
  1373. // just return our array
  1374. return items;
  1375. }
  1376. }
  1377. }
  1378. };
  1379. /**
  1380. * Get ids of all items or from a filtered set of items.
  1381. * @param {Object} [options] An Object with options. Available options:
  1382. * {function} [filter] filter items
  1383. * {String | function} [order] Order the items by
  1384. * a field name or custom sort function.
  1385. * @return {Array} ids
  1386. */
  1387. DataSet.prototype.getIds = function (options) {
  1388. var data = this.data,
  1389. filter = options && options.filter,
  1390. order = options && options.order,
  1391. convert = options && options.convert || this.options.convert,
  1392. i,
  1393. len,
  1394. id,
  1395. item,
  1396. items,
  1397. ids = [];
  1398. if (filter) {
  1399. // get filtered items
  1400. if (order) {
  1401. // create ordered list
  1402. items = [];
  1403. for (id in data) {
  1404. if (data.hasOwnProperty(id)) {
  1405. item = this._getItem(id, convert);
  1406. if (filter(item)) {
  1407. items.push(item);
  1408. }
  1409. }
  1410. }
  1411. this._sort(items, order);
  1412. for (i = 0, len = items.length; i < len; i++) {
  1413. ids[i] = items[i][this.fieldId];
  1414. }
  1415. }
  1416. else {
  1417. // create unordered list
  1418. for (id in data) {
  1419. if (data.hasOwnProperty(id)) {
  1420. item = this._getItem(id, convert);
  1421. if (filter(item)) {
  1422. ids.push(item[this.fieldId]);
  1423. }
  1424. }
  1425. }
  1426. }
  1427. }
  1428. else {
  1429. // get all items
  1430. if (order) {
  1431. // create an ordered list
  1432. items = [];
  1433. for (id in data) {
  1434. if (data.hasOwnProperty(id)) {
  1435. items.push(data[id]);
  1436. }
  1437. }
  1438. this._sort(items, order);
  1439. for (i = 0, len = items.length; i < len; i++) {
  1440. ids[i] = items[i][this.fieldId];
  1441. }
  1442. }
  1443. else {
  1444. // create unordered list
  1445. for (id in data) {
  1446. if (data.hasOwnProperty(id)) {
  1447. item = data[id];
  1448. ids.push(item[this.fieldId]);
  1449. }
  1450. }
  1451. }
  1452. }
  1453. return ids;
  1454. };
  1455. /**
  1456. * Execute a callback function for every item in the dataset.
  1457. * The order of the items is not determined.
  1458. * @param {function} callback
  1459. * @param {Object} [options] Available options:
  1460. * {Object.<String, String>} [convert]
  1461. * {String[]} [fields] filter fields
  1462. * {function} [filter] filter items
  1463. * {String | function} [order] Order the items by
  1464. * a field name or custom sort function.
  1465. */
  1466. DataSet.prototype.forEach = function (callback, options) {
  1467. var filter = options && options.filter,
  1468. convert = options && options.convert || this.options.convert,
  1469. data = this.data,
  1470. item,
  1471. id;
  1472. if (options && options.order) {
  1473. // execute forEach on ordered list
  1474. var items = this.get(options);
  1475. for (var i = 0, len = items.length; i < len; i++) {
  1476. item = items[i];
  1477. id = item[this.fieldId];
  1478. callback(item, id);
  1479. }
  1480. }
  1481. else {
  1482. // unordered
  1483. for (id in data) {
  1484. if (data.hasOwnProperty(id)) {
  1485. item = this._getItem(id, convert);
  1486. if (!filter || filter(item)) {
  1487. callback(item, id);
  1488. }
  1489. }
  1490. }
  1491. }
  1492. };
  1493. /**
  1494. * Map every item in the dataset.
  1495. * @param {function} callback
  1496. * @param {Object} [options] Available options:
  1497. * {Object.<String, String>} [convert]
  1498. * {String[]} [fields] filter fields
  1499. * {function} [filter] filter items
  1500. * {String | function} [order] Order the items by
  1501. * a field name or custom sort function.
  1502. * @return {Object[]} mappedItems
  1503. */
  1504. DataSet.prototype.map = function (callback, options) {
  1505. var filter = options && options.filter,
  1506. convert = options && options.convert || this.options.convert,
  1507. mappedItems = [],
  1508. data = this.data,
  1509. item;
  1510. // convert and filter items
  1511. for (var id in data) {
  1512. if (data.hasOwnProperty(id)) {
  1513. item = this._getItem(id, convert);
  1514. if (!filter || filter(item)) {
  1515. mappedItems.push(callback(item, id));
  1516. }
  1517. }
  1518. }
  1519. // order items
  1520. if (options && options.order) {
  1521. this._sort(mappedItems, options.order);
  1522. }
  1523. return mappedItems;
  1524. };
  1525. /**
  1526. * Filter the fields of an item
  1527. * @param {Object} item
  1528. * @param {String[]} fields Field names
  1529. * @return {Object} filteredItem
  1530. * @private
  1531. */
  1532. DataSet.prototype._filterFields = function (item, fields) {
  1533. var filteredItem = {};
  1534. for (var field in item) {
  1535. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1536. filteredItem[field] = item[field];
  1537. }
  1538. }
  1539. return filteredItem;
  1540. };
  1541. /**
  1542. * Sort the provided array with items
  1543. * @param {Object[]} items
  1544. * @param {String | function} order A field name or custom sort function.
  1545. * @private
  1546. */
  1547. DataSet.prototype._sort = function (items, order) {
  1548. if (util.isString(order)) {
  1549. // order by provided field name
  1550. var name = order; // field name
  1551. items.sort(function (a, b) {
  1552. var av = a[name];
  1553. var bv = b[name];
  1554. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1555. });
  1556. }
  1557. else if (typeof order === 'function') {
  1558. // order by sort function
  1559. items.sort(order);
  1560. }
  1561. // TODO: extend order by an Object {field:String, direction:String}
  1562. // where direction can be 'asc' or 'desc'
  1563. else {
  1564. throw new TypeError('Order must be a function or a string');
  1565. }
  1566. };
  1567. /**
  1568. * Remove an object by pointer or by id
  1569. * @param {String | Number | Object | Array} id Object or id, or an array with
  1570. * objects or ids to be removed
  1571. * @param {String} [senderId] Optional sender id
  1572. * @return {Array} removedIds
  1573. */
  1574. DataSet.prototype.remove = function (id, senderId) {
  1575. var removedIds = [],
  1576. i, len, removedId;
  1577. if (id instanceof Array) {
  1578. for (i = 0, len = id.length; i < len; i++) {
  1579. removedId = this._remove(id[i]);
  1580. if (removedId != null) {
  1581. removedIds.push(removedId);
  1582. }
  1583. }
  1584. }
  1585. else {
  1586. removedId = this._remove(id);
  1587. if (removedId != null) {
  1588. removedIds.push(removedId);
  1589. }
  1590. }
  1591. if (removedIds.length) {
  1592. this._trigger('remove', {items: removedIds}, senderId);
  1593. }
  1594. return removedIds;
  1595. };
  1596. /**
  1597. * Remove an item by its id
  1598. * @param {Number | String | Object} id id or item
  1599. * @returns {Number | String | null} id
  1600. * @private
  1601. */
  1602. DataSet.prototype._remove = function (id) {
  1603. if (util.isNumber(id) || util.isString(id)) {
  1604. if (this.data[id]) {
  1605. delete this.data[id];
  1606. delete this.internalIds[id];
  1607. return id;
  1608. }
  1609. }
  1610. else if (id instanceof Object) {
  1611. var itemId = id[this.fieldId];
  1612. if (itemId && this.data[itemId]) {
  1613. delete this.data[itemId];
  1614. delete this.internalIds[itemId];
  1615. return itemId;
  1616. }
  1617. }
  1618. return null;
  1619. };
  1620. /**
  1621. * Clear the data
  1622. * @param {String} [senderId] Optional sender id
  1623. * @return {Array} removedIds The ids of all removed items
  1624. */
  1625. DataSet.prototype.clear = function (senderId) {
  1626. var ids = Object.keys(this.data);
  1627. this.data = {};
  1628. this.internalIds = {};
  1629. this._trigger('remove', {items: ids}, senderId);
  1630. return ids;
  1631. };
  1632. /**
  1633. * Find the item with maximum value of a specified field
  1634. * @param {String} field
  1635. * @return {Object | null} item Item containing max value, or null if no items
  1636. */
  1637. DataSet.prototype.max = function (field) {
  1638. var data = this.data,
  1639. max = null,
  1640. maxField = null;
  1641. for (var id in data) {
  1642. if (data.hasOwnProperty(id)) {
  1643. var item = data[id];
  1644. var itemField = item[field];
  1645. if (itemField != null && (!max || itemField > maxField)) {
  1646. max = item;
  1647. maxField = itemField;
  1648. }
  1649. }
  1650. }
  1651. return max;
  1652. };
  1653. /**
  1654. * Find the item with minimum value of a specified field
  1655. * @param {String} field
  1656. * @return {Object | null} item Item containing max value, or null if no items
  1657. */
  1658. DataSet.prototype.min = function (field) {
  1659. var data = this.data,
  1660. min = null,
  1661. minField = null;
  1662. for (var id in data) {
  1663. if (data.hasOwnProperty(id)) {
  1664. var item = data[id];
  1665. var itemField = item[field];
  1666. if (itemField != null && (!min || itemField < minField)) {
  1667. min = item;
  1668. minField = itemField;
  1669. }
  1670. }
  1671. }
  1672. return min;
  1673. };
  1674. /**
  1675. * Find all distinct values of a specified field
  1676. * @param {String} field
  1677. * @return {Array} values Array containing all distinct values. If the data
  1678. * items do not contain the specified field, an array
  1679. * containing a single value undefined is returned.
  1680. * The returned array is unordered.
  1681. */
  1682. DataSet.prototype.distinct = function (field) {
  1683. var data = this.data,
  1684. values = [],
  1685. fieldType = this.options.convert[field],
  1686. count = 0;
  1687. for (var prop in data) {
  1688. if (data.hasOwnProperty(prop)) {
  1689. var item = data[prop];
  1690. var value = util.convert(item[field], fieldType);
  1691. var exists = false;
  1692. for (var i = 0; i < count; i++) {
  1693. if (values[i] == value) {
  1694. exists = true;
  1695. break;
  1696. }
  1697. }
  1698. if (!exists) {
  1699. values[count] = value;
  1700. count++;
  1701. }
  1702. }
  1703. }
  1704. return values;
  1705. };
  1706. /**
  1707. * Add a single item. Will fail when an item with the same id already exists.
  1708. * @param {Object} item
  1709. * @return {String} id
  1710. * @private
  1711. */
  1712. DataSet.prototype._addItem = function (item) {
  1713. var id = item[this.fieldId];
  1714. if (id != undefined) {
  1715. // check whether this id is already taken
  1716. if (this.data[id]) {
  1717. // item already exists
  1718. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1719. }
  1720. }
  1721. else {
  1722. // generate an id
  1723. id = util.randomUUID();
  1724. item[this.fieldId] = id;
  1725. this.internalIds[id] = item;
  1726. }
  1727. var d = {};
  1728. for (var field in item) {
  1729. if (item.hasOwnProperty(field)) {
  1730. var fieldType = this.convert[field]; // type may be undefined
  1731. d[field] = util.convert(item[field], fieldType);
  1732. }
  1733. }
  1734. this.data[id] = d;
  1735. return id;
  1736. };
  1737. /**
  1738. * Get an item. Fields can be converted to a specific type
  1739. * @param {String} id
  1740. * @param {Object.<String, String>} [convert] field types to convert
  1741. * @return {Object | null} item
  1742. * @private
  1743. */
  1744. DataSet.prototype._getItem = function (id, convert) {
  1745. var field, value;
  1746. // get the item from the dataset
  1747. var raw = this.data[id];
  1748. if (!raw) {
  1749. return null;
  1750. }
  1751. // convert the items field types
  1752. var converted = {},
  1753. fieldId = this.fieldId,
  1754. internalIds = this.internalIds;
  1755. if (convert) {
  1756. for (field in raw) {
  1757. if (raw.hasOwnProperty(field)) {
  1758. value = raw[field];
  1759. // output all fields, except internal ids
  1760. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1761. converted[field] = util.convert(value, convert[field]);
  1762. }
  1763. }
  1764. }
  1765. }
  1766. else {
  1767. // no field types specified, no converting needed
  1768. for (field in raw) {
  1769. if (raw.hasOwnProperty(field)) {
  1770. value = raw[field];
  1771. // output all fields, except internal ids
  1772. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1773. converted[field] = value;
  1774. }
  1775. }
  1776. }
  1777. }
  1778. return converted;
  1779. };
  1780. /**
  1781. * Update a single item: merge with existing item.
  1782. * Will fail when the item has no id, or when there does not exist an item
  1783. * with the same id.
  1784. * @param {Object} item
  1785. * @return {String} id
  1786. * @private
  1787. */
  1788. DataSet.prototype._updateItem = function (item) {
  1789. var id = item[this.fieldId];
  1790. if (id == undefined) {
  1791. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1792. }
  1793. var d = this.data[id];
  1794. if (!d) {
  1795. // item doesn't exist
  1796. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1797. }
  1798. // merge with current item
  1799. for (var field in item) {
  1800. if (item.hasOwnProperty(field)) {
  1801. var fieldType = this.convert[field]; // type may be undefined
  1802. d[field] = util.convert(item[field], fieldType);
  1803. }
  1804. }
  1805. return id;
  1806. };
  1807. /**
  1808. * check if an id is an internal or external id
  1809. * @param id
  1810. * @returns {boolean}
  1811. * @private
  1812. */
  1813. DataSet.prototype.isInternalId = function(id) {
  1814. return (id in this.internalIds);
  1815. };
  1816. /**
  1817. * Get an array with the column names of a Google DataTable
  1818. * @param {DataTable} dataTable
  1819. * @return {String[]} columnNames
  1820. * @private
  1821. */
  1822. DataSet.prototype._getColumnNames = function (dataTable) {
  1823. var columns = [];
  1824. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1825. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1826. }
  1827. return columns;
  1828. };
  1829. /**
  1830. * Append an item as a row to the dataTable
  1831. * @param dataTable
  1832. * @param columns
  1833. * @param item
  1834. * @private
  1835. */
  1836. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1837. var row = dataTable.addRow();
  1838. for (var col = 0, cols = columns.length; col < cols; col++) {
  1839. var field = columns[col];
  1840. dataTable.setValue(row, col, item[field]);
  1841. }
  1842. };
  1843. /**
  1844. * DataView
  1845. *
  1846. * a dataview offers a filtered view on a dataset or an other dataview.
  1847. *
  1848. * @param {DataSet | DataView} data
  1849. * @param {Object} [options] Available options: see method get
  1850. *
  1851. * @constructor DataView
  1852. */
  1853. function DataView (data, options) {
  1854. this.id = util.randomUUID();
  1855. this.data = null;
  1856. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1857. this.options = options || {};
  1858. this.fieldId = 'id'; // name of the field containing id
  1859. this.subscribers = {}; // event subscribers
  1860. var me = this;
  1861. this.listener = function () {
  1862. me._onEvent.apply(me, arguments);
  1863. };
  1864. this.setData(data);
  1865. }
  1866. // TODO: implement a function .config() to dynamically update things like configured filter
  1867. // and trigger changes accordingly
  1868. /**
  1869. * Set a data source for the view
  1870. * @param {DataSet | DataView} data
  1871. */
  1872. DataView.prototype.setData = function (data) {
  1873. var ids, dataItems, i, len;
  1874. if (this.data) {
  1875. // unsubscribe from current dataset
  1876. if (this.data.unsubscribe) {
  1877. this.data.unsubscribe('*', this.listener);
  1878. }
  1879. // trigger a remove of all items in memory
  1880. ids = [];
  1881. for (var id in this.ids) {
  1882. if (this.ids.hasOwnProperty(id)) {
  1883. ids.push(id);
  1884. }
  1885. }
  1886. this.ids = {};
  1887. this._trigger('remove', {items: ids});
  1888. }
  1889. this.data = data;
  1890. if (this.data) {
  1891. // update fieldId
  1892. this.fieldId = this.options.fieldId ||
  1893. (this.data && this.data.options && this.data.options.fieldId) ||
  1894. 'id';
  1895. // trigger an add of all added items
  1896. ids = this.data.getIds({filter: this.options && this.options.filter});
  1897. for (i = 0, len = ids.length; i < len; i++) {
  1898. id = ids[i];
  1899. this.ids[id] = true;
  1900. }
  1901. this._trigger('add', {items: ids});
  1902. // subscribe to new dataset
  1903. if (this.data.on) {
  1904. this.data.on('*', this.listener);
  1905. }
  1906. }
  1907. };
  1908. /**
  1909. * Get data from the data view
  1910. *
  1911. * Usage:
  1912. *
  1913. * get()
  1914. * get(options: Object)
  1915. * get(options: Object, data: Array | DataTable)
  1916. *
  1917. * get(id: Number)
  1918. * get(id: Number, options: Object)
  1919. * get(id: Number, options: Object, data: Array | DataTable)
  1920. *
  1921. * get(ids: Number[])
  1922. * get(ids: Number[], options: Object)
  1923. * get(ids: Number[], options: Object, data: Array | DataTable)
  1924. *
  1925. * Where:
  1926. *
  1927. * {Number | String} id The id of an item
  1928. * {Number[] | String{}} ids An array with ids of items
  1929. * {Object} options An Object with options. Available options:
  1930. * {String} [type] Type of data to be returned. Can
  1931. * be 'DataTable' or 'Array' (default)
  1932. * {Object.<String, String>} [convert]
  1933. * {String[]} [fields] field names to be returned
  1934. * {function} [filter] filter items
  1935. * {String | function} [order] Order the items by
  1936. * a field name or custom sort function.
  1937. * {Array | DataTable} [data] If provided, items will be appended to this
  1938. * array or table. Required in case of Google
  1939. * DataTable.
  1940. * @param args
  1941. */
  1942. DataView.prototype.get = function (args) {
  1943. var me = this;
  1944. // parse the arguments
  1945. var ids, options, data;
  1946. var firstType = util.getType(arguments[0]);
  1947. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  1948. // get(id(s) [, options] [, data])
  1949. ids = arguments[0]; // can be a single id or an array with ids
  1950. options = arguments[1];
  1951. data = arguments[2];
  1952. }
  1953. else {
  1954. // get([, options] [, data])
  1955. options = arguments[0];
  1956. data = arguments[1];
  1957. }
  1958. // extend the options with the default options and provided options
  1959. var viewOptions = util.extend({}, this.options, options);
  1960. // create a combined filter method when needed
  1961. if (this.options.filter && options && options.filter) {
  1962. viewOptions.filter = function (item) {
  1963. return me.options.filter(item) && options.filter(item);
  1964. }
  1965. }
  1966. // build up the call to the linked data set
  1967. var getArguments = [];
  1968. if (ids != undefined) {
  1969. getArguments.push(ids);
  1970. }
  1971. getArguments.push(viewOptions);
  1972. getArguments.push(data);
  1973. return this.data && this.data.get.apply(this.data, getArguments);
  1974. };
  1975. /**
  1976. * Get ids of all items or from a filtered set of items.
  1977. * @param {Object} [options] An Object with options. Available options:
  1978. * {function} [filter] filter items
  1979. * {String | function} [order] Order the items by
  1980. * a field name or custom sort function.
  1981. * @return {Array} ids
  1982. */
  1983. DataView.prototype.getIds = function (options) {
  1984. var ids;
  1985. if (this.data) {
  1986. var defaultFilter = this.options.filter;
  1987. var filter;
  1988. if (options && options.filter) {
  1989. if (defaultFilter) {
  1990. filter = function (item) {
  1991. return defaultFilter(item) && options.filter(item);
  1992. }
  1993. }
  1994. else {
  1995. filter = options.filter;
  1996. }
  1997. }
  1998. else {
  1999. filter = defaultFilter;
  2000. }
  2001. ids = this.data.getIds({
  2002. filter: filter,
  2003. order: options && options.order
  2004. });
  2005. }
  2006. else {
  2007. ids = [];
  2008. }
  2009. return ids;
  2010. };
  2011. /**
  2012. * Event listener. Will propagate all events from the connected data set to
  2013. * the subscribers of the DataView, but will filter the items and only trigger
  2014. * when there are changes in the filtered data set.
  2015. * @param {String} event
  2016. * @param {Object | null} params
  2017. * @param {String} senderId
  2018. * @private
  2019. */
  2020. DataView.prototype._onEvent = function (event, params, senderId) {
  2021. var i, len, id, item,
  2022. ids = params && params.items,
  2023. data = this.data,
  2024. added = [],
  2025. updated = [],
  2026. removed = [];
  2027. if (ids && data) {
  2028. switch (event) {
  2029. case 'add':
  2030. // filter the ids of the added items
  2031. for (i = 0, len = ids.length; i < len; i++) {
  2032. id = ids[i];
  2033. item = this.get(id);
  2034. if (item) {
  2035. this.ids[id] = true;
  2036. added.push(id);
  2037. }
  2038. }
  2039. break;
  2040. case 'update':
  2041. // determine the event from the views viewpoint: an updated
  2042. // item can be added, updated, or removed from this view.
  2043. for (i = 0, len = ids.length; i < len; i++) {
  2044. id = ids[i];
  2045. item = this.get(id);
  2046. if (item) {
  2047. if (this.ids[id]) {
  2048. updated.push(id);
  2049. }
  2050. else {
  2051. this.ids[id] = true;
  2052. added.push(id);
  2053. }
  2054. }
  2055. else {
  2056. if (this.ids[id]) {
  2057. delete this.ids[id];
  2058. removed.push(id);
  2059. }
  2060. else {
  2061. // nothing interesting for me :-(
  2062. }
  2063. }
  2064. }
  2065. break;
  2066. case 'remove':
  2067. // filter the ids of the removed items
  2068. for (i = 0, len = ids.length; i < len; i++) {
  2069. id = ids[i];
  2070. if (this.ids[id]) {
  2071. delete this.ids[id];
  2072. removed.push(id);
  2073. }
  2074. }
  2075. break;
  2076. }
  2077. if (added.length) {
  2078. this._trigger('add', {items: added}, senderId);
  2079. }
  2080. if (updated.length) {
  2081. this._trigger('update', {items: updated}, senderId);
  2082. }
  2083. if (removed.length) {
  2084. this._trigger('remove', {items: removed}, senderId);
  2085. }
  2086. }
  2087. };
  2088. // copy subscription functionality from DataSet
  2089. DataView.prototype.on = DataSet.prototype.on;
  2090. DataView.prototype.off = DataSet.prototype.off;
  2091. DataView.prototype._trigger = DataSet.prototype._trigger;
  2092. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2093. DataView.prototype.subscribe = DataView.prototype.on;
  2094. DataView.prototype.unsubscribe = DataView.prototype.off;
  2095. /**
  2096. * @constructor TimeStep
  2097. * The class TimeStep is an iterator for dates. You provide a start date and an
  2098. * end date. The class itself determines the best scale (step size) based on the
  2099. * provided start Date, end Date, and minimumStep.
  2100. *
  2101. * If minimumStep is provided, the step size is chosen as close as possible
  2102. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2103. * provided, the scale is set to 1 DAY.
  2104. * The minimumStep should correspond with the onscreen size of about 6 characters
  2105. *
  2106. * Alternatively, you can set a scale by hand.
  2107. * After creation, you can initialize the class by executing first(). Then you
  2108. * can iterate from the start date to the end date via next(). You can check if
  2109. * the end date is reached with the function hasNext(). After each step, you can
  2110. * retrieve the current date via getCurrent().
  2111. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2112. * days, to years.
  2113. *
  2114. * Version: 1.2
  2115. *
  2116. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2117. * or new Date(2010, 9, 21, 23, 45, 00)
  2118. * @param {Date} [end] The end date
  2119. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2120. */
  2121. TimeStep = function(start, end, minimumStep) {
  2122. // variables
  2123. this.current = new Date();
  2124. this._start = new Date();
  2125. this._end = new Date();
  2126. this.autoScale = true;
  2127. this.scale = TimeStep.SCALE.DAY;
  2128. this.step = 1;
  2129. // initialize the range
  2130. this.setRange(start, end, minimumStep);
  2131. };
  2132. /// enum scale
  2133. TimeStep.SCALE = {
  2134. MILLISECOND: 1,
  2135. SECOND: 2,
  2136. MINUTE: 3,
  2137. HOUR: 4,
  2138. DAY: 5,
  2139. WEEKDAY: 6,
  2140. MONTH: 7,
  2141. YEAR: 8
  2142. };
  2143. /**
  2144. * Set a new range
  2145. * If minimumStep is provided, the step size is chosen as close as possible
  2146. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2147. * provided, the scale is set to 1 DAY.
  2148. * The minimumStep should correspond with the onscreen size of about 6 characters
  2149. * @param {Date} [start] The start date and time.
  2150. * @param {Date} [end] The end date and time.
  2151. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2152. */
  2153. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2154. if (!(start instanceof Date) || !(end instanceof Date)) {
  2155. throw "No legal start or end date in method setRange";
  2156. }
  2157. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2158. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2159. if (this.autoScale) {
  2160. this.setMinimumStep(minimumStep);
  2161. }
  2162. };
  2163. /**
  2164. * Set the range iterator to the start date.
  2165. */
  2166. TimeStep.prototype.first = function() {
  2167. this.current = new Date(this._start.valueOf());
  2168. this.roundToMinor();
  2169. };
  2170. /**
  2171. * Round the current date to the first minor date value
  2172. * This must be executed once when the current date is set to start Date
  2173. */
  2174. TimeStep.prototype.roundToMinor = function() {
  2175. // round to floor
  2176. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2177. //noinspection FallthroughInSwitchStatementJS
  2178. switch (this.scale) {
  2179. case TimeStep.SCALE.YEAR:
  2180. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2181. this.current.setMonth(0);
  2182. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2183. case TimeStep.SCALE.DAY: // intentional fall through
  2184. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2185. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2186. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2187. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2188. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2189. }
  2190. if (this.step != 1) {
  2191. // round down to the first minor value that is a multiple of the current step size
  2192. switch (this.scale) {
  2193. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2194. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2195. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2196. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2197. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2198. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2199. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2200. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2201. default: break;
  2202. }
  2203. }
  2204. };
  2205. /**
  2206. * Check if the there is a next step
  2207. * @return {boolean} true if the current date has not passed the end date
  2208. */
  2209. TimeStep.prototype.hasNext = function () {
  2210. return (this.current.valueOf() <= this._end.valueOf());
  2211. };
  2212. /**
  2213. * Do the next step
  2214. */
  2215. TimeStep.prototype.next = function() {
  2216. var prev = this.current.valueOf();
  2217. // Two cases, needed to prevent issues with switching daylight savings
  2218. // (end of March and end of October)
  2219. if (this.current.getMonth() < 6) {
  2220. switch (this.scale) {
  2221. case TimeStep.SCALE.MILLISECOND:
  2222. this.current = new Date(this.current.valueOf() + this.step); break;
  2223. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2224. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2225. case TimeStep.SCALE.HOUR:
  2226. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2227. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2228. var h = this.current.getHours();
  2229. this.current.setHours(h - (h % this.step));
  2230. break;
  2231. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2232. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2233. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2234. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2235. default: break;
  2236. }
  2237. }
  2238. else {
  2239. switch (this.scale) {
  2240. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2241. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2242. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2243. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2244. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2245. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2246. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2247. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2248. default: break;
  2249. }
  2250. }
  2251. if (this.step != 1) {
  2252. // round down to the correct major value
  2253. switch (this.scale) {
  2254. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2255. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2256. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2257. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2258. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2259. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2260. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2261. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2262. default: break;
  2263. }
  2264. }
  2265. // safety mechanism: if current time is still unchanged, move to the end
  2266. if (this.current.valueOf() == prev) {
  2267. this.current = new Date(this._end.valueOf());
  2268. }
  2269. };
  2270. /**
  2271. * Get the current datetime
  2272. * @return {Date} current The current date
  2273. */
  2274. TimeStep.prototype.getCurrent = function() {
  2275. return this.current;
  2276. };
  2277. /**
  2278. * Set a custom scale. Autoscaling will be disabled.
  2279. * For example setScale(SCALE.MINUTES, 5) will result
  2280. * in minor steps of 5 minutes, and major steps of an hour.
  2281. *
  2282. * @param {TimeStep.SCALE} newScale
  2283. * A scale. Choose from SCALE.MILLISECOND,
  2284. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2285. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2286. * SCALE.YEAR.
  2287. * @param {Number} newStep A step size, by default 1. Choose for
  2288. * example 1, 2, 5, or 10.
  2289. */
  2290. TimeStep.prototype.setScale = function(newScale, newStep) {
  2291. this.scale = newScale;
  2292. if (newStep > 0) {
  2293. this.step = newStep;
  2294. }
  2295. this.autoScale = false;
  2296. };
  2297. /**
  2298. * Enable or disable autoscaling
  2299. * @param {boolean} enable If true, autoascaling is set true
  2300. */
  2301. TimeStep.prototype.setAutoScale = function (enable) {
  2302. this.autoScale = enable;
  2303. };
  2304. /**
  2305. * Automatically determine the scale that bests fits the provided minimum step
  2306. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2307. */
  2308. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2309. if (minimumStep == undefined) {
  2310. return;
  2311. }
  2312. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2313. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2314. var stepDay = (1000 * 60 * 60 * 24);
  2315. var stepHour = (1000 * 60 * 60);
  2316. var stepMinute = (1000 * 60);
  2317. var stepSecond = (1000);
  2318. var stepMillisecond= (1);
  2319. // find the smallest step that is larger than the provided minimumStep
  2320. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2321. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2322. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2323. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2324. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2325. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2326. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2327. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2328. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2329. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2330. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2331. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2332. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2333. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2334. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2335. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2336. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2337. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2338. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2339. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2340. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2341. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2342. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2343. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2344. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2345. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2346. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2347. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2348. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2349. };
  2350. /**
  2351. * Snap a date to a rounded value.
  2352. * The snap intervals are dependent on the current scale and step.
  2353. * @param {Date} date the date to be snapped.
  2354. * @return {Date} snappedDate
  2355. */
  2356. TimeStep.prototype.snap = function(date) {
  2357. var clone = new Date(date.valueOf());
  2358. if (this.scale == TimeStep.SCALE.YEAR) {
  2359. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2360. clone.setFullYear(Math.round(year / this.step) * this.step);
  2361. clone.setMonth(0);
  2362. clone.setDate(0);
  2363. clone.setHours(0);
  2364. clone.setMinutes(0);
  2365. clone.setSeconds(0);
  2366. clone.setMilliseconds(0);
  2367. }
  2368. else if (this.scale == TimeStep.SCALE.MONTH) {
  2369. if (clone.getDate() > 15) {
  2370. clone.setDate(1);
  2371. clone.setMonth(clone.getMonth() + 1);
  2372. // important: first set Date to 1, after that change the month.
  2373. }
  2374. else {
  2375. clone.setDate(1);
  2376. }
  2377. clone.setHours(0);
  2378. clone.setMinutes(0);
  2379. clone.setSeconds(0);
  2380. clone.setMilliseconds(0);
  2381. }
  2382. else if (this.scale == TimeStep.SCALE.DAY ||
  2383. this.scale == TimeStep.SCALE.WEEKDAY) {
  2384. //noinspection FallthroughInSwitchStatementJS
  2385. switch (this.step) {
  2386. case 5:
  2387. case 2:
  2388. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2389. default:
  2390. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2391. }
  2392. clone.setMinutes(0);
  2393. clone.setSeconds(0);
  2394. clone.setMilliseconds(0);
  2395. }
  2396. else if (this.scale == TimeStep.SCALE.HOUR) {
  2397. switch (this.step) {
  2398. case 4:
  2399. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2400. default:
  2401. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2402. }
  2403. clone.setSeconds(0);
  2404. clone.setMilliseconds(0);
  2405. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2406. //noinspection FallthroughInSwitchStatementJS
  2407. switch (this.step) {
  2408. case 15:
  2409. case 10:
  2410. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2411. clone.setSeconds(0);
  2412. break;
  2413. case 5:
  2414. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2415. default:
  2416. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2417. }
  2418. clone.setMilliseconds(0);
  2419. }
  2420. else if (this.scale == TimeStep.SCALE.SECOND) {
  2421. //noinspection FallthroughInSwitchStatementJS
  2422. switch (this.step) {
  2423. case 15:
  2424. case 10:
  2425. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2426. clone.setMilliseconds(0);
  2427. break;
  2428. case 5:
  2429. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2430. default:
  2431. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2432. }
  2433. }
  2434. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2435. var step = this.step > 5 ? this.step / 2 : 1;
  2436. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2437. }
  2438. return clone;
  2439. };
  2440. /**
  2441. * Check if the current value is a major value (for example when the step
  2442. * is DAY, a major value is each first day of the MONTH)
  2443. * @return {boolean} true if current date is major, else false.
  2444. */
  2445. TimeStep.prototype.isMajor = function() {
  2446. switch (this.scale) {
  2447. case TimeStep.SCALE.MILLISECOND:
  2448. return (this.current.getMilliseconds() == 0);
  2449. case TimeStep.SCALE.SECOND:
  2450. return (this.current.getSeconds() == 0);
  2451. case TimeStep.SCALE.MINUTE:
  2452. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2453. // Note: this is no bug. Major label is equal for both minute and hour scale
  2454. case TimeStep.SCALE.HOUR:
  2455. return (this.current.getHours() == 0);
  2456. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2457. case TimeStep.SCALE.DAY:
  2458. return (this.current.getDate() == 1);
  2459. case TimeStep.SCALE.MONTH:
  2460. return (this.current.getMonth() == 0);
  2461. case TimeStep.SCALE.YEAR:
  2462. return false;
  2463. default:
  2464. return false;
  2465. }
  2466. };
  2467. /**
  2468. * Returns formatted text for the minor axislabel, depending on the current
  2469. * date and the scale. For example when scale is MINUTE, the current time is
  2470. * formatted as "hh:mm".
  2471. * @param {Date} [date] custom date. if not provided, current date is taken
  2472. */
  2473. TimeStep.prototype.getLabelMinor = function(date) {
  2474. if (date == undefined) {
  2475. date = this.current;
  2476. }
  2477. switch (this.scale) {
  2478. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2479. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2480. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2481. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2482. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2483. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2484. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2485. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2486. default: return '';
  2487. }
  2488. };
  2489. /**
  2490. * Returns formatted text for the major axis label, depending on the current
  2491. * date and the scale. For example when scale is MINUTE, the major scale is
  2492. * hours, and the hour will be formatted as "hh".
  2493. * @param {Date} [date] custom date. if not provided, current date is taken
  2494. */
  2495. TimeStep.prototype.getLabelMajor = function(date) {
  2496. if (date == undefined) {
  2497. date = this.current;
  2498. }
  2499. //noinspection FallthroughInSwitchStatementJS
  2500. switch (this.scale) {
  2501. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2502. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2503. case TimeStep.SCALE.MINUTE:
  2504. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2505. case TimeStep.SCALE.WEEKDAY:
  2506. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2507. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2508. case TimeStep.SCALE.YEAR: return '';
  2509. default: return '';
  2510. }
  2511. };
  2512. /**
  2513. * @constructor Stack
  2514. * Stacks items on top of each other.
  2515. * @param {ItemSet} itemset
  2516. * @param {Object} [options]
  2517. */
  2518. function Stack (itemset, options) {
  2519. this.itemset = itemset;
  2520. this.options = options || {};
  2521. this.defaultOptions = {
  2522. order: function (a, b) {
  2523. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  2524. // Order: ranges over non-ranges, ranged ordered by width, and
  2525. // lastly ordered by start.
  2526. if (a instanceof ItemRange) {
  2527. if (b instanceof ItemRange) {
  2528. var aInt = (a.data.end - a.data.start);
  2529. var bInt = (b.data.end - b.data.start);
  2530. return (aInt - bInt) || (a.data.start - b.data.start);
  2531. }
  2532. else {
  2533. return -1;
  2534. }
  2535. }
  2536. else {
  2537. if (b instanceof ItemRange) {
  2538. return 1;
  2539. }
  2540. else {
  2541. return (a.data.start - b.data.start);
  2542. }
  2543. }
  2544. },
  2545. margin: {
  2546. item: 10
  2547. }
  2548. };
  2549. this.ordered = []; // ordered items
  2550. }
  2551. /**
  2552. * Set options for the stack
  2553. * @param {Object} options Available options:
  2554. * {ItemSet} itemset
  2555. * {Number} margin
  2556. * {function} order Stacking order
  2557. */
  2558. Stack.prototype.setOptions = function setOptions (options) {
  2559. util.extend(this.options, options);
  2560. // TODO: register on data changes at the connected itemset, and update the changed part only and immediately
  2561. };
  2562. /**
  2563. * Stack the items such that they don't overlap. The items will have a minimal
  2564. * distance equal to options.margin.item.
  2565. */
  2566. Stack.prototype.update = function update() {
  2567. this._order();
  2568. this._stack();
  2569. };
  2570. /**
  2571. * Order the items. If a custom order function has been provided via the options,
  2572. * then this will be used.
  2573. * @private
  2574. */
  2575. Stack.prototype._order = function _order () {
  2576. var items = this.itemset.items;
  2577. if (!items) {
  2578. throw new Error('Cannot stack items: ItemSet does not contain items');
  2579. }
  2580. // TODO: store the sorted items, to have less work later on
  2581. var ordered = [];
  2582. var index = 0;
  2583. // items is a map (no array)
  2584. util.forEach(items, function (item) {
  2585. if (item.visible) {
  2586. ordered[index] = item;
  2587. index++;
  2588. }
  2589. });
  2590. //if a customer stack order function exists, use it.
  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. ordered.sort(order);
  2596. this.ordered = ordered;
  2597. };
  2598. /**
  2599. * Adjust vertical positions of the events such that they don't overlap each
  2600. * other.
  2601. * @private
  2602. */
  2603. Stack.prototype._stack = function _stack () {
  2604. var i,
  2605. iMax,
  2606. ordered = this.ordered,
  2607. options = this.options,
  2608. orientation = options.orientation || this.defaultOptions.orientation,
  2609. axisOnTop = (orientation == 'top'),
  2610. margin;
  2611. if (options.margin && options.margin.item !== undefined) {
  2612. margin = options.margin.item;
  2613. }
  2614. else {
  2615. margin = this.defaultOptions.margin.item
  2616. }
  2617. // calculate new, non-overlapping positions
  2618. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  2619. var item = ordered[i];
  2620. var collidingItem = null;
  2621. do {
  2622. // TODO: optimize checking for overlap. when there is a gap without items,
  2623. // you only need to check for items from the next item on, not from zero
  2624. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  2625. if (collidingItem != null) {
  2626. // There is a collision. Reposition the event above the colliding element
  2627. if (axisOnTop) {
  2628. item.top = collidingItem.top + collidingItem.height + margin;
  2629. }
  2630. else {
  2631. item.top = collidingItem.top - item.height - margin;
  2632. }
  2633. }
  2634. } while (collidingItem);
  2635. }
  2636. };
  2637. /**
  2638. * Check if the destiny position of given item overlaps with any
  2639. * of the other items from index itemStart to itemEnd.
  2640. * @param {Array} items Array with items
  2641. * @param {int} itemIndex Number of the item to be checked for overlap
  2642. * @param {int} itemStart First item to be checked.
  2643. * @param {int} itemEnd Last item to be checked.
  2644. * @return {Object | null} colliding item, or undefined when no collisions
  2645. * @param {Number} margin A minimum required margin.
  2646. * If margin is provided, the two items will be
  2647. * marked colliding when they overlap or
  2648. * when the margin between the two is smaller than
  2649. * the requested margin.
  2650. */
  2651. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  2652. itemStart, itemEnd, margin) {
  2653. var collision = this.collision;
  2654. // we loop from end to start, as we suppose that the chance of a
  2655. // collision is larger for items at the end, so check these first.
  2656. var a = items[itemIndex];
  2657. for (var i = itemEnd; i >= itemStart; i--) {
  2658. var b = items[i];
  2659. if (collision(a, b, margin)) {
  2660. if (i != itemIndex) {
  2661. return b;
  2662. }
  2663. }
  2664. }
  2665. return null;
  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 = setTimeout(function () {
  3193. reflowTimer = null;
  3194. me.reflow();
  3195. }, 0);
  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 = setTimeout(function () {
  3212. repaintTimer = null;
  3213. me.repaint();
  3214. }, 0);
  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. this.repaint();
  3325. }
  3326. // TODO: limit the number of nested reflows/repaints, prevent loop
  3327. };
  3328. /**
  3329. * Prototype for visual components
  3330. */
  3331. function Component () {
  3332. this.id = null;
  3333. this.parent = null;
  3334. this.depends = null;
  3335. this.controller = null;
  3336. this.options = null;
  3337. this.frame = null; // main DOM element
  3338. this.top = 0;
  3339. this.left = 0;
  3340. this.width = 0;
  3341. this.height = 0;
  3342. }
  3343. /**
  3344. * Set parameters for the frame. Parameters will be merged in current parameter
  3345. * set.
  3346. * @param {Object} options Available parameters:
  3347. * {String | function} [className]
  3348. * {String | Number | function} [left]
  3349. * {String | Number | function} [top]
  3350. * {String | Number | function} [width]
  3351. * {String | Number | function} [height]
  3352. */
  3353. Component.prototype.setOptions = function setOptions(options) {
  3354. if (options) {
  3355. util.extend(this.options, options);
  3356. if (this.controller) {
  3357. this.requestRepaint();
  3358. this.requestReflow();
  3359. }
  3360. }
  3361. };
  3362. /**
  3363. * Get an option value by name
  3364. * The function will first check this.options object, and else will check
  3365. * this.defaultOptions.
  3366. * @param {String} name
  3367. * @return {*} value
  3368. */
  3369. Component.prototype.getOption = function getOption(name) {
  3370. var value;
  3371. if (this.options) {
  3372. value = this.options[name];
  3373. }
  3374. if (value === undefined && this.defaultOptions) {
  3375. value = this.defaultOptions[name];
  3376. }
  3377. return value;
  3378. };
  3379. /**
  3380. * Set controller for this component, or remove current controller by passing
  3381. * null as parameter value.
  3382. * @param {Controller | null} controller
  3383. */
  3384. Component.prototype.setController = function setController (controller) {
  3385. this.controller = controller || null;
  3386. };
  3387. /**
  3388. * Get controller of this component
  3389. * @return {Controller} controller
  3390. */
  3391. Component.prototype.getController = function getController () {
  3392. return this.controller;
  3393. };
  3394. /**
  3395. * Get the container element of the component, which can be used by a child to
  3396. * add its own widgets. Not all components do have a container for childs, in
  3397. * that case null is returned.
  3398. * @returns {HTMLElement | null} container
  3399. */
  3400. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3401. Component.prototype.getContainer = function getContainer() {
  3402. // should be implemented by the component
  3403. return null;
  3404. };
  3405. /**
  3406. * Get the frame element of the component, the outer HTML DOM element.
  3407. * @returns {HTMLElement | null} frame
  3408. */
  3409. Component.prototype.getFrame = function getFrame() {
  3410. return this.frame;
  3411. };
  3412. /**
  3413. * Repaint the component
  3414. * @return {Boolean} changed
  3415. */
  3416. Component.prototype.repaint = function repaint() {
  3417. // should be implemented by the component
  3418. return false;
  3419. };
  3420. /**
  3421. * Reflow the component
  3422. * @return {Boolean} resized
  3423. */
  3424. Component.prototype.reflow = function reflow() {
  3425. // should be implemented by the component
  3426. return false;
  3427. };
  3428. /**
  3429. * Hide the component from the DOM
  3430. * @return {Boolean} changed
  3431. */
  3432. Component.prototype.hide = function hide() {
  3433. if (this.frame && this.frame.parentNode) {
  3434. this.frame.parentNode.removeChild(this.frame);
  3435. return true;
  3436. }
  3437. else {
  3438. return false;
  3439. }
  3440. };
  3441. /**
  3442. * Show the component in the DOM (when not already visible).
  3443. * A repaint will be executed when the component is not visible
  3444. * @return {Boolean} changed
  3445. */
  3446. Component.prototype.show = function show() {
  3447. if (!this.frame || !this.frame.parentNode) {
  3448. return this.repaint();
  3449. }
  3450. else {
  3451. return false;
  3452. }
  3453. };
  3454. /**
  3455. * Request a repaint. The controller will schedule a repaint
  3456. */
  3457. Component.prototype.requestRepaint = function requestRepaint() {
  3458. if (this.controller) {
  3459. this.controller.emit('request-repaint');
  3460. }
  3461. else {
  3462. throw new Error('Cannot request a repaint: no controller configured');
  3463. // TODO: just do a repaint when no parent is configured?
  3464. }
  3465. };
  3466. /**
  3467. * Request a reflow. The controller will schedule a reflow
  3468. */
  3469. Component.prototype.requestReflow = function requestReflow() {
  3470. if (this.controller) {
  3471. this.controller.emit('request-reflow');
  3472. }
  3473. else {
  3474. throw new Error('Cannot request a reflow: no controller configured');
  3475. // TODO: just do a reflow when no parent is configured?
  3476. }
  3477. };
  3478. /**
  3479. * A panel can contain components
  3480. * @param {Component} [parent]
  3481. * @param {Component[]} [depends] Components on which this components depends
  3482. * (except for the parent)
  3483. * @param {Object} [options] Available parameters:
  3484. * {String | Number | function} [left]
  3485. * {String | Number | function} [top]
  3486. * {String | Number | function} [width]
  3487. * {String | Number | function} [height]
  3488. * {String | function} [className]
  3489. * @constructor Panel
  3490. * @extends Component
  3491. */
  3492. function Panel(parent, depends, options) {
  3493. this.id = util.randomUUID();
  3494. this.parent = parent;
  3495. this.depends = depends;
  3496. this.options = options || {};
  3497. }
  3498. Panel.prototype = new Component();
  3499. /**
  3500. * Set options. Will extend the current options.
  3501. * @param {Object} [options] Available parameters:
  3502. * {String | function} [className]
  3503. * {String | Number | function} [left]
  3504. * {String | Number | function} [top]
  3505. * {String | Number | function} [width]
  3506. * {String | Number | function} [height]
  3507. */
  3508. Panel.prototype.setOptions = Component.prototype.setOptions;
  3509. /**
  3510. * Get the container element of the panel, which can be used by a child to
  3511. * add its own widgets.
  3512. * @returns {HTMLElement} container
  3513. */
  3514. Panel.prototype.getContainer = function () {
  3515. return this.frame;
  3516. };
  3517. /**
  3518. * Repaint the component
  3519. * @return {Boolean} changed
  3520. */
  3521. Panel.prototype.repaint = function () {
  3522. var changed = 0,
  3523. update = util.updateProperty,
  3524. asSize = util.option.asSize,
  3525. options = this.options,
  3526. frame = this.frame;
  3527. if (!frame) {
  3528. frame = document.createElement('div');
  3529. frame.className = 'vpanel';
  3530. var className = options.className;
  3531. if (className) {
  3532. if (typeof className == 'function') {
  3533. util.addClassName(frame, String(className()));
  3534. }
  3535. else {
  3536. util.addClassName(frame, String(className));
  3537. }
  3538. }
  3539. this.frame = frame;
  3540. changed += 1;
  3541. }
  3542. if (!frame.parentNode) {
  3543. if (!this.parent) {
  3544. throw new Error('Cannot repaint panel: no parent attached');
  3545. }
  3546. var parentContainer = this.parent.getContainer();
  3547. if (!parentContainer) {
  3548. throw new Error('Cannot repaint panel: parent has no container element');
  3549. }
  3550. parentContainer.appendChild(frame);
  3551. changed += 1;
  3552. }
  3553. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3554. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3555. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3556. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3557. return (changed > 0);
  3558. };
  3559. /**
  3560. * Reflow the component
  3561. * @return {Boolean} resized
  3562. */
  3563. Panel.prototype.reflow = function () {
  3564. var changed = 0,
  3565. update = util.updateProperty,
  3566. frame = this.frame;
  3567. if (frame) {
  3568. changed += update(this, 'top', frame.offsetTop);
  3569. changed += update(this, 'left', frame.offsetLeft);
  3570. changed += update(this, 'width', frame.offsetWidth);
  3571. changed += update(this, 'height', frame.offsetHeight);
  3572. }
  3573. else {
  3574. changed += 1;
  3575. }
  3576. return (changed > 0);
  3577. };
  3578. /**
  3579. * A root panel can hold components. The root panel must be initialized with
  3580. * a DOM element as container.
  3581. * @param {HTMLElement} container
  3582. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3583. * @constructor RootPanel
  3584. * @extends Panel
  3585. */
  3586. function RootPanel(container, options) {
  3587. this.id = util.randomUUID();
  3588. this.container = container;
  3589. // create functions to be used as DOM event listeners
  3590. var me = this;
  3591. this.hammer = null;
  3592. // create listeners for all interesting events, these events will be emitted
  3593. // via the controller
  3594. var events = [
  3595. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3596. 'dragstart', 'drag', 'dragend',
  3597. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3598. ];
  3599. this.listeners = {};
  3600. events.forEach(function (event) {
  3601. me.listeners[event] = function () {
  3602. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3603. me.controller.emit.apply(me.controller, args);
  3604. };
  3605. });
  3606. this.options = options || {};
  3607. this.defaultOptions = {
  3608. autoResize: true
  3609. };
  3610. }
  3611. RootPanel.prototype = new Panel();
  3612. /**
  3613. * Set options. Will extend the current options.
  3614. * @param {Object} [options] Available parameters:
  3615. * {String | function} [className]
  3616. * {String | Number | function} [left]
  3617. * {String | Number | function} [top]
  3618. * {String | Number | function} [width]
  3619. * {String | Number | function} [height]
  3620. * {Boolean | function} [autoResize]
  3621. */
  3622. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3623. /**
  3624. * Repaint the component
  3625. * @return {Boolean} changed
  3626. */
  3627. RootPanel.prototype.repaint = function () {
  3628. var changed = 0,
  3629. update = util.updateProperty,
  3630. asSize = util.option.asSize,
  3631. options = this.options,
  3632. frame = this.frame;
  3633. if (!frame) {
  3634. frame = document.createElement('div');
  3635. this.frame = frame;
  3636. this._registerListeners();
  3637. changed += 1;
  3638. }
  3639. if (!frame.parentNode) {
  3640. if (!this.container) {
  3641. throw new Error('Cannot repaint root panel: no container attached');
  3642. }
  3643. this.container.appendChild(frame);
  3644. changed += 1;
  3645. }
  3646. frame.className = 'vis timeline rootpanel ' + options.orientation +
  3647. (options.editable ? ' editable' : '');
  3648. var className = options.className;
  3649. if (className) {
  3650. util.addClassName(frame, util.option.asString(className));
  3651. }
  3652. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3653. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3654. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3655. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3656. this._updateWatch();
  3657. return (changed > 0);
  3658. };
  3659. /**
  3660. * Reflow the component
  3661. * @return {Boolean} resized
  3662. */
  3663. RootPanel.prototype.reflow = function () {
  3664. var changed = 0,
  3665. update = util.updateProperty,
  3666. frame = this.frame;
  3667. if (frame) {
  3668. changed += update(this, 'top', frame.offsetTop);
  3669. changed += update(this, 'left', frame.offsetLeft);
  3670. changed += update(this, 'width', frame.offsetWidth);
  3671. changed += update(this, 'height', frame.offsetHeight);
  3672. }
  3673. else {
  3674. changed += 1;
  3675. }
  3676. return (changed > 0);
  3677. };
  3678. /**
  3679. * Update watching for resize, depending on the current option
  3680. * @private
  3681. */
  3682. RootPanel.prototype._updateWatch = function () {
  3683. var autoResize = this.getOption('autoResize');
  3684. if (autoResize) {
  3685. this._watch();
  3686. }
  3687. else {
  3688. this._unwatch();
  3689. }
  3690. };
  3691. /**
  3692. * Watch for changes in the size of the frame. On resize, the Panel will
  3693. * automatically redraw itself.
  3694. * @private
  3695. */
  3696. RootPanel.prototype._watch = function () {
  3697. var me = this;
  3698. this._unwatch();
  3699. var checkSize = function () {
  3700. var autoResize = me.getOption('autoResize');
  3701. if (!autoResize) {
  3702. // stop watching when the option autoResize is changed to false
  3703. me._unwatch();
  3704. return;
  3705. }
  3706. if (me.frame) {
  3707. // check whether the frame is resized
  3708. if ((me.frame.clientWidth != me.width) ||
  3709. (me.frame.clientHeight != me.height)) {
  3710. me.requestReflow();
  3711. }
  3712. }
  3713. };
  3714. // TODO: automatically cleanup the event listener when the frame is deleted
  3715. util.addEventListener(window, 'resize', checkSize);
  3716. this.watchTimer = setInterval(checkSize, 1000);
  3717. };
  3718. /**
  3719. * Stop watching for a resize of the frame.
  3720. * @private
  3721. */
  3722. RootPanel.prototype._unwatch = function () {
  3723. if (this.watchTimer) {
  3724. clearInterval(this.watchTimer);
  3725. this.watchTimer = undefined;
  3726. }
  3727. // TODO: remove event listener on window.resize
  3728. };
  3729. /**
  3730. * Set controller for this component, or remove current controller by passing
  3731. * null as parameter value.
  3732. * @param {Controller | null} controller
  3733. */
  3734. RootPanel.prototype.setController = function setController (controller) {
  3735. this.controller = controller || null;
  3736. if (this.controller) {
  3737. this._registerListeners();
  3738. }
  3739. else {
  3740. this._unregisterListeners();
  3741. }
  3742. };
  3743. /**
  3744. * Register event emitters emitted by the rootpanel
  3745. * @private
  3746. */
  3747. RootPanel.prototype._registerListeners = function () {
  3748. if (this.frame && this.controller && !this.hammer) {
  3749. this.hammer = Hammer(this.frame, {
  3750. prevent_default: true
  3751. });
  3752. for (var event in this.listeners) {
  3753. if (this.listeners.hasOwnProperty(event)) {
  3754. this.hammer.on(event, this.listeners[event]);
  3755. }
  3756. }
  3757. }
  3758. };
  3759. /**
  3760. * Unregister event emitters from the rootpanel
  3761. * @private
  3762. */
  3763. RootPanel.prototype._unregisterListeners = function () {
  3764. if (this.hammer) {
  3765. for (var event in this.listeners) {
  3766. if (this.listeners.hasOwnProperty(event)) {
  3767. this.hammer.off(event, this.listeners[event]);
  3768. }
  3769. }
  3770. this.hammer = null;
  3771. }
  3772. };
  3773. /**
  3774. * A horizontal time axis
  3775. * @param {Component} parent
  3776. * @param {Component[]} [depends] Components on which this components depends
  3777. * (except for the parent)
  3778. * @param {Object} [options] See TimeAxis.setOptions for the available
  3779. * options.
  3780. * @constructor TimeAxis
  3781. * @extends Component
  3782. */
  3783. function TimeAxis (parent, depends, options) {
  3784. this.id = util.randomUUID();
  3785. this.parent = parent;
  3786. this.depends = depends;
  3787. this.dom = {
  3788. majorLines: [],
  3789. majorTexts: [],
  3790. minorLines: [],
  3791. minorTexts: [],
  3792. redundant: {
  3793. majorLines: [],
  3794. majorTexts: [],
  3795. minorLines: [],
  3796. minorTexts: []
  3797. }
  3798. };
  3799. this.props = {
  3800. range: {
  3801. start: 0,
  3802. end: 0,
  3803. minimumStep: 0
  3804. },
  3805. lineTop: 0
  3806. };
  3807. this.options = options || {};
  3808. this.defaultOptions = {
  3809. orientation: 'bottom', // supported: 'top', 'bottom'
  3810. // TODO: implement timeaxis orientations 'left' and 'right'
  3811. showMinorLabels: true,
  3812. showMajorLabels: true
  3813. };
  3814. this.conversion = null;
  3815. this.range = null;
  3816. }
  3817. TimeAxis.prototype = new Component();
  3818. // TODO: comment options
  3819. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3820. /**
  3821. * Set a range (start and end)
  3822. * @param {Range | Object} range A Range or an object containing start and end.
  3823. */
  3824. TimeAxis.prototype.setRange = function (range) {
  3825. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3826. throw new TypeError('Range must be an instance of Range, ' +
  3827. 'or an object containing start and end.');
  3828. }
  3829. this.range = range;
  3830. };
  3831. /**
  3832. * Convert a position on screen (pixels) to a datetime
  3833. * @param {int} x Position on the screen in pixels
  3834. * @return {Date} time The datetime the corresponds with given position x
  3835. */
  3836. TimeAxis.prototype.toTime = function(x) {
  3837. var conversion = this.conversion;
  3838. return new Date(x / conversion.scale + conversion.offset);
  3839. };
  3840. /**
  3841. * Convert a datetime (Date object) into a position on the screen
  3842. * @param {Date} time A date
  3843. * @return {int} x The position on the screen in pixels which corresponds
  3844. * with the given date.
  3845. * @private
  3846. */
  3847. TimeAxis.prototype.toScreen = function(time) {
  3848. var conversion = this.conversion;
  3849. return (time.valueOf() - conversion.offset) * conversion.scale;
  3850. };
  3851. /**
  3852. * Repaint the component
  3853. * @return {Boolean} changed
  3854. */
  3855. TimeAxis.prototype.repaint = function () {
  3856. var changed = 0,
  3857. update = util.updateProperty,
  3858. asSize = util.option.asSize,
  3859. options = this.options,
  3860. orientation = this.getOption('orientation'),
  3861. props = this.props,
  3862. step = this.step;
  3863. var frame = this.frame;
  3864. if (!frame) {
  3865. frame = document.createElement('div');
  3866. this.frame = frame;
  3867. changed += 1;
  3868. }
  3869. frame.className = 'axis';
  3870. // TODO: custom className?
  3871. if (!frame.parentNode) {
  3872. if (!this.parent) {
  3873. throw new Error('Cannot repaint time axis: no parent attached');
  3874. }
  3875. var parentContainer = this.parent.getContainer();
  3876. if (!parentContainer) {
  3877. throw new Error('Cannot repaint time axis: parent has no container element');
  3878. }
  3879. parentContainer.appendChild(frame);
  3880. changed += 1;
  3881. }
  3882. var parent = frame.parentNode;
  3883. if (parent) {
  3884. var beforeChild = frame.nextSibling;
  3885. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3886. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3887. (this.props.parentHeight - this.height) + 'px' :
  3888. '0px';
  3889. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3890. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3891. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3892. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3893. // get characters width and height
  3894. this._repaintMeasureChars();
  3895. if (this.step) {
  3896. this._repaintStart();
  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());
  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());
  3915. }
  3916. this._repaintMajorLine(x);
  3917. }
  3918. else {
  3919. this._repaintMinorLine(x);
  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 * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3928. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3929. this._repaintMajorText(0, leftText);
  3930. }
  3931. }
  3932. this._repaintEnd();
  3933. }
  3934. this._repaintLine();
  3935. // put frame online again
  3936. if (beforeChild) {
  3937. parent.insertBefore(frame, beforeChild);
  3938. }
  3939. else {
  3940. parent.appendChild(frame)
  3941. }
  3942. }
  3943. return (changed > 0);
  3944. };
  3945. /**
  3946. * Start a repaint. Move all DOM elements to a redundant list, where they
  3947. * can be picked for re-use, or can be cleaned up in the end
  3948. * @private
  3949. */
  3950. TimeAxis.prototype._repaintStart = function () {
  3951. var dom = this.dom,
  3952. redundant = dom.redundant;
  3953. redundant.majorLines = dom.majorLines;
  3954. redundant.majorTexts = dom.majorTexts;
  3955. redundant.minorLines = dom.minorLines;
  3956. redundant.minorTexts = dom.minorTexts;
  3957. dom.majorLines = [];
  3958. dom.majorTexts = [];
  3959. dom.minorLines = [];
  3960. dom.minorTexts = [];
  3961. };
  3962. /**
  3963. * End a repaint. Cleanup leftover DOM elements in the redundant list
  3964. * @private
  3965. */
  3966. TimeAxis.prototype._repaintEnd = function () {
  3967. util.forEach(this.dom.redundant, function (arr) {
  3968. while (arr.length) {
  3969. var elem = arr.pop();
  3970. if (elem && elem.parentNode) {
  3971. elem.parentNode.removeChild(elem);
  3972. }
  3973. }
  3974. });
  3975. };
  3976. /**
  3977. * Create a minor label for the axis at position x
  3978. * @param {Number} x
  3979. * @param {String} text
  3980. * @private
  3981. */
  3982. TimeAxis.prototype._repaintMinorText = function (x, text) {
  3983. // reuse redundant label
  3984. var label = this.dom.redundant.minorTexts.shift();
  3985. if (!label) {
  3986. // create new label
  3987. var content = document.createTextNode('');
  3988. label = document.createElement('div');
  3989. label.appendChild(content);
  3990. label.className = 'text minor';
  3991. this.frame.appendChild(label);
  3992. }
  3993. this.dom.minorTexts.push(label);
  3994. label.childNodes[0].nodeValue = text;
  3995. label.style.left = x + 'px';
  3996. label.style.top = this.props.minorLabelTop + 'px';
  3997. //label.title = title; // TODO: this is a heavy operation
  3998. };
  3999. /**
  4000. * Create a Major label for the axis at position x
  4001. * @param {Number} x
  4002. * @param {String} text
  4003. * @private
  4004. */
  4005. TimeAxis.prototype._repaintMajorText = function (x, text) {
  4006. // reuse redundant label
  4007. var label = this.dom.redundant.majorTexts.shift();
  4008. if (!label) {
  4009. // create label
  4010. var content = document.createTextNode(text);
  4011. label = document.createElement('div');
  4012. label.className = 'text major';
  4013. label.appendChild(content);
  4014. this.frame.appendChild(label);
  4015. }
  4016. this.dom.majorTexts.push(label);
  4017. label.childNodes[0].nodeValue = text;
  4018. label.style.top = this.props.majorLabelTop + 'px';
  4019. label.style.left = x + 'px';
  4020. //label.title = title; // TODO: this is a heavy operation
  4021. };
  4022. /**
  4023. * Create a minor line for the axis at position x
  4024. * @param {Number} x
  4025. * @private
  4026. */
  4027. TimeAxis.prototype._repaintMinorLine = function (x) {
  4028. // reuse redundant line
  4029. var line = this.dom.redundant.minorLines.shift();
  4030. if (!line) {
  4031. // create vertical line
  4032. line = document.createElement('div');
  4033. line.className = 'grid vertical minor';
  4034. this.frame.appendChild(line);
  4035. }
  4036. this.dom.minorLines.push(line);
  4037. var props = this.props;
  4038. line.style.top = props.minorLineTop + 'px';
  4039. line.style.height = props.minorLineHeight + 'px';
  4040. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  4041. };
  4042. /**
  4043. * Create a Major line for the axis at position x
  4044. * @param {Number} x
  4045. * @private
  4046. */
  4047. TimeAxis.prototype._repaintMajorLine = function (x) {
  4048. // reuse redundant line
  4049. var line = this.dom.redundant.majorLines.shift();
  4050. if (!line) {
  4051. // create vertical line
  4052. line = document.createElement('DIV');
  4053. line.className = 'grid vertical major';
  4054. this.frame.appendChild(line);
  4055. }
  4056. this.dom.majorLines.push(line);
  4057. var props = this.props;
  4058. line.style.top = props.majorLineTop + 'px';
  4059. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4060. line.style.height = props.majorLineHeight + 'px';
  4061. };
  4062. /**
  4063. * Repaint the horizontal line for the axis
  4064. * @private
  4065. */
  4066. TimeAxis.prototype._repaintLine = function() {
  4067. var line = this.dom.line,
  4068. frame = this.frame,
  4069. options = this.options;
  4070. // line before all axis elements
  4071. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4072. if (line) {
  4073. // put this line at the end of all childs
  4074. frame.removeChild(line);
  4075. frame.appendChild(line);
  4076. }
  4077. else {
  4078. // create the axis line
  4079. line = document.createElement('div');
  4080. line.className = 'grid horizontal major';
  4081. frame.appendChild(line);
  4082. this.dom.line = line;
  4083. }
  4084. line.style.top = this.props.lineTop + 'px';
  4085. }
  4086. else {
  4087. if (line && line.parentElement) {
  4088. frame.removeChild(line.line);
  4089. delete this.dom.line;
  4090. }
  4091. }
  4092. };
  4093. /**
  4094. * Create characters used to determine the size of text on the axis
  4095. * @private
  4096. */
  4097. TimeAxis.prototype._repaintMeasureChars = function () {
  4098. // calculate the width and height of a single character
  4099. // this is used to calculate the step size, and also the positioning of the
  4100. // axis
  4101. var dom = this.dom,
  4102. text;
  4103. if (!dom.measureCharMinor) {
  4104. text = document.createTextNode('0');
  4105. var measureCharMinor = document.createElement('DIV');
  4106. measureCharMinor.className = 'text minor measure';
  4107. measureCharMinor.appendChild(text);
  4108. this.frame.appendChild(measureCharMinor);
  4109. dom.measureCharMinor = measureCharMinor;
  4110. }
  4111. if (!dom.measureCharMajor) {
  4112. text = document.createTextNode('0');
  4113. var measureCharMajor = document.createElement('DIV');
  4114. measureCharMajor.className = 'text major measure';
  4115. measureCharMajor.appendChild(text);
  4116. this.frame.appendChild(measureCharMajor);
  4117. dom.measureCharMajor = measureCharMajor;
  4118. }
  4119. };
  4120. /**
  4121. * Reflow the component
  4122. * @return {Boolean} resized
  4123. */
  4124. TimeAxis.prototype.reflow = function () {
  4125. var changed = 0,
  4126. update = util.updateProperty,
  4127. frame = this.frame,
  4128. range = this.range;
  4129. if (!range) {
  4130. throw new Error('Cannot repaint time axis: no range configured');
  4131. }
  4132. if (frame) {
  4133. changed += update(this, 'top', frame.offsetTop);
  4134. changed += update(this, 'left', frame.offsetLeft);
  4135. // calculate size of a character
  4136. var props = this.props,
  4137. showMinorLabels = this.getOption('showMinorLabels'),
  4138. showMajorLabels = this.getOption('showMajorLabels'),
  4139. measureCharMinor = this.dom.measureCharMinor,
  4140. measureCharMajor = this.dom.measureCharMajor;
  4141. if (measureCharMinor) {
  4142. props.minorCharHeight = measureCharMinor.clientHeight;
  4143. props.minorCharWidth = measureCharMinor.clientWidth;
  4144. }
  4145. if (measureCharMajor) {
  4146. props.majorCharHeight = measureCharMajor.clientHeight;
  4147. props.majorCharWidth = measureCharMajor.clientWidth;
  4148. }
  4149. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4150. if (parentHeight != props.parentHeight) {
  4151. props.parentHeight = parentHeight;
  4152. changed += 1;
  4153. }
  4154. switch (this.getOption('orientation')) {
  4155. case 'bottom':
  4156. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4157. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4158. props.minorLabelTop = 0;
  4159. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4160. props.minorLineTop = -this.top;
  4161. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4162. props.minorLineWidth = 1; // TODO: really calculate width
  4163. props.majorLineTop = -this.top;
  4164. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4165. props.majorLineWidth = 1; // TODO: really calculate width
  4166. props.lineTop = 0;
  4167. break;
  4168. case 'top':
  4169. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4170. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4171. props.majorLabelTop = 0;
  4172. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4173. props.minorLineTop = props.minorLabelTop;
  4174. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4175. props.minorLineWidth = 1; // TODO: really calculate width
  4176. props.majorLineTop = 0;
  4177. props.majorLineHeight = Math.max(parentHeight - this.top);
  4178. props.majorLineWidth = 1; // TODO: really calculate width
  4179. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4180. break;
  4181. default:
  4182. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4183. }
  4184. var height = props.minorLabelHeight + props.majorLabelHeight;
  4185. changed += update(this, 'width', frame.offsetWidth);
  4186. changed += update(this, 'height', height);
  4187. // calculate range and step
  4188. this._updateConversion();
  4189. var start = util.convert(range.start, 'Number'),
  4190. end = util.convert(range.end, 'Number'),
  4191. minimumStep = this.toTime((props.minorCharWidth || 10) * 5).valueOf()
  4192. -this.toTime(0).valueOf();
  4193. this.step = new TimeStep(new Date(start), new Date(end), minimumStep);
  4194. changed += update(props.range, 'start', start);
  4195. changed += update(props.range, 'end', end);
  4196. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4197. }
  4198. return (changed > 0);
  4199. };
  4200. /**
  4201. * Calculate the scale and offset to convert a position on screen to the
  4202. * corresponding date and vice versa.
  4203. * After the method _updateConversion is executed once, the methods toTime
  4204. * and toScreen can be used.
  4205. * @private
  4206. */
  4207. TimeAxis.prototype._updateConversion = function() {
  4208. var range = this.range;
  4209. if (!range) {
  4210. throw new Error('No range configured');
  4211. }
  4212. if (range.conversion) {
  4213. this.conversion = range.conversion(this.width);
  4214. }
  4215. else {
  4216. this.conversion = Range.conversion(range.start, range.end, this.width);
  4217. }
  4218. };
  4219. /**
  4220. * Snap a date to a rounded value.
  4221. * The snap intervals are dependent on the current scale and step.
  4222. * @param {Date} date the date to be snapped.
  4223. * @return {Date} snappedDate
  4224. */
  4225. TimeAxis.prototype.snap = function snap (date) {
  4226. return this.step.snap(date);
  4227. };
  4228. /**
  4229. * A current time bar
  4230. * @param {Component} parent
  4231. * @param {Component[]} [depends] Components on which this components depends
  4232. * (except for the parent)
  4233. * @param {Object} [options] Available parameters:
  4234. * {Boolean} [showCurrentTime]
  4235. * @constructor CurrentTime
  4236. * @extends Component
  4237. */
  4238. function CurrentTime (parent, depends, options) {
  4239. this.id = util.randomUUID();
  4240. this.parent = parent;
  4241. this.depends = depends;
  4242. this.options = options || {};
  4243. this.defaultOptions = {
  4244. showCurrentTime: false
  4245. };
  4246. }
  4247. CurrentTime.prototype = new Component();
  4248. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  4249. /**
  4250. * Get the container element of the bar, which can be used by a child to
  4251. * add its own widgets.
  4252. * @returns {HTMLElement} container
  4253. */
  4254. CurrentTime.prototype.getContainer = function () {
  4255. return this.frame;
  4256. };
  4257. /**
  4258. * Repaint the component
  4259. * @return {Boolean} changed
  4260. */
  4261. CurrentTime.prototype.repaint = function () {
  4262. var bar = this.frame,
  4263. parent = this.parent,
  4264. parentContainer = parent.parent.getContainer();
  4265. if (!parent) {
  4266. throw new Error('Cannot repaint bar: no parent attached');
  4267. }
  4268. if (!parentContainer) {
  4269. throw new Error('Cannot repaint bar: parent has no container element');
  4270. }
  4271. if (!this.getOption('showCurrentTime')) {
  4272. if (bar) {
  4273. parentContainer.removeChild(bar);
  4274. delete this.frame;
  4275. }
  4276. return false;
  4277. }
  4278. if (!bar) {
  4279. bar = document.createElement('div');
  4280. bar.className = 'currenttime';
  4281. bar.style.position = 'absolute';
  4282. bar.style.top = '0px';
  4283. bar.style.height = '100%';
  4284. parentContainer.appendChild(bar);
  4285. this.frame = bar;
  4286. }
  4287. if (!parent.conversion) {
  4288. parent._updateConversion();
  4289. }
  4290. var now = new Date();
  4291. var x = parent.toScreen(now);
  4292. bar.style.left = x + 'px';
  4293. bar.title = 'Current time: ' + now;
  4294. // start a timer to adjust for the new time
  4295. if (this.currentTimeTimer !== undefined) {
  4296. clearTimeout(this.currentTimeTimer);
  4297. delete this.currentTimeTimer;
  4298. }
  4299. var timeline = this;
  4300. var interval = 1 / parent.conversion.scale / 2;
  4301. if (interval < 30) {
  4302. interval = 30;
  4303. }
  4304. this.currentTimeTimer = setTimeout(function() {
  4305. timeline.repaint();
  4306. }, interval);
  4307. return false;
  4308. };
  4309. /**
  4310. * A custom time bar
  4311. * @param {Component} parent
  4312. * @param {Component[]} [depends] Components on which this components depends
  4313. * (except for the parent)
  4314. * @param {Object} [options] Available parameters:
  4315. * {Boolean} [showCustomTime]
  4316. * @constructor CustomTime
  4317. * @extends Component
  4318. */
  4319. function CustomTime (parent, depends, options) {
  4320. this.id = util.randomUUID();
  4321. this.parent = parent;
  4322. this.depends = depends;
  4323. this.options = options || {};
  4324. this.defaultOptions = {
  4325. showCustomTime: false
  4326. };
  4327. this.customTime = new Date();
  4328. this.eventParams = {}; // stores state parameters while dragging the bar
  4329. }
  4330. CustomTime.prototype = new Component();
  4331. Emitter(CustomTime.prototype);
  4332. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4333. /**
  4334. * Get the container element of the bar, which can be used by a child to
  4335. * add its own widgets.
  4336. * @returns {HTMLElement} container
  4337. */
  4338. CustomTime.prototype.getContainer = function () {
  4339. return this.frame;
  4340. };
  4341. /**
  4342. * Repaint the component
  4343. * @return {Boolean} changed
  4344. */
  4345. CustomTime.prototype.repaint = function () {
  4346. var bar = this.frame,
  4347. parent = this.parent;
  4348. if (!parent) {
  4349. throw new Error('Cannot repaint bar: no parent attached');
  4350. }
  4351. var parentContainer = parent.parent.getContainer();
  4352. if (!parentContainer) {
  4353. throw new Error('Cannot repaint bar: parent has no container element');
  4354. }
  4355. if (!this.getOption('showCustomTime')) {
  4356. if (bar) {
  4357. parentContainer.removeChild(bar);
  4358. delete this.frame;
  4359. }
  4360. return false;
  4361. }
  4362. if (!bar) {
  4363. bar = document.createElement('div');
  4364. bar.className = 'customtime';
  4365. bar.style.position = 'absolute';
  4366. bar.style.top = '0px';
  4367. bar.style.height = '100%';
  4368. parentContainer.appendChild(bar);
  4369. var drag = document.createElement('div');
  4370. drag.style.position = 'relative';
  4371. drag.style.top = '0px';
  4372. drag.style.left = '-10px';
  4373. drag.style.height = '100%';
  4374. drag.style.width = '20px';
  4375. bar.appendChild(drag);
  4376. this.frame = bar;
  4377. // attach event listeners
  4378. this.hammer = Hammer(bar, {
  4379. prevent_default: true
  4380. });
  4381. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4382. this.hammer.on('drag', this._onDrag.bind(this));
  4383. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4384. }
  4385. if (!parent.conversion) {
  4386. parent._updateConversion();
  4387. }
  4388. var x = parent.toScreen(this.customTime);
  4389. bar.style.left = x + 'px';
  4390. bar.title = 'Time: ' + this.customTime;
  4391. return false;
  4392. };
  4393. /**
  4394. * Set custom time.
  4395. * @param {Date} time
  4396. */
  4397. CustomTime.prototype.setCustomTime = function(time) {
  4398. this.customTime = new Date(time.valueOf());
  4399. this.repaint();
  4400. };
  4401. /**
  4402. * Retrieve the current custom time.
  4403. * @return {Date} customTime
  4404. */
  4405. CustomTime.prototype.getCustomTime = function() {
  4406. return new Date(this.customTime.valueOf());
  4407. };
  4408. /**
  4409. * Start moving horizontally
  4410. * @param {Event} event
  4411. * @private
  4412. */
  4413. CustomTime.prototype._onDragStart = function(event) {
  4414. this.eventParams.customTime = this.customTime;
  4415. event.stopPropagation();
  4416. event.preventDefault();
  4417. };
  4418. /**
  4419. * Perform moving operating.
  4420. * @param {Event} event
  4421. * @private
  4422. */
  4423. CustomTime.prototype._onDrag = function (event) {
  4424. var deltaX = event.gesture.deltaX,
  4425. x = this.parent.toScreen(this.eventParams.customTime) + deltaX,
  4426. time = this.parent.toTime(x);
  4427. this.setCustomTime(time);
  4428. // fire a timechange event
  4429. if (this.controller) {
  4430. this.controller.emit('timechange', {
  4431. time: this.customTime
  4432. })
  4433. }
  4434. event.stopPropagation();
  4435. event.preventDefault();
  4436. };
  4437. /**
  4438. * Stop moving operating.
  4439. * @param {event} event
  4440. * @private
  4441. */
  4442. CustomTime.prototype._onDragEnd = function (event) {
  4443. // fire a timechanged event
  4444. if (this.controller) {
  4445. this.controller.emit('timechanged', {
  4446. time: this.customTime
  4447. })
  4448. }
  4449. event.stopPropagation();
  4450. event.preventDefault();
  4451. };
  4452. /**
  4453. * An ItemSet holds a set of items and ranges which can be displayed in a
  4454. * range. The width is determined by the parent of the ItemSet, and the height
  4455. * is determined by the size of the items.
  4456. * @param {Component} parent
  4457. * @param {Component[]} [depends] Components on which this components depends
  4458. * (except for the parent)
  4459. * @param {Object} [options] See ItemSet.setOptions for the available
  4460. * options.
  4461. * @constructor ItemSet
  4462. * @extends Panel
  4463. */
  4464. // TODO: improve performance by replacing all Array.forEach with a for loop
  4465. function ItemSet(parent, depends, options) {
  4466. this.id = util.randomUUID();
  4467. this.parent = parent;
  4468. this.depends = depends;
  4469. // event listeners
  4470. this.eventListeners = {
  4471. dragstart: this._onDragStart.bind(this),
  4472. drag: this._onDrag.bind(this),
  4473. dragend: this._onDragEnd.bind(this)
  4474. };
  4475. // one options object is shared by this itemset and all its items
  4476. this.options = options || {};
  4477. this.defaultOptions = {
  4478. type: 'box',
  4479. align: 'center',
  4480. orientation: 'bottom',
  4481. margin: {
  4482. axis: 20,
  4483. item: 10
  4484. },
  4485. padding: 5
  4486. };
  4487. this.dom = {};
  4488. var me = this;
  4489. this.itemsData = null; // DataSet
  4490. this.range = null; // Range or Object {start: number, end: number}
  4491. // data change listeners
  4492. this.listeners = {
  4493. 'add': function (event, params, senderId) {
  4494. if (senderId != me.id) {
  4495. me._onAdd(params.items);
  4496. }
  4497. },
  4498. 'update': function (event, params, senderId) {
  4499. if (senderId != me.id) {
  4500. me._onUpdate(params.items);
  4501. }
  4502. },
  4503. 'remove': function (event, params, senderId) {
  4504. if (senderId != me.id) {
  4505. me._onRemove(params.items);
  4506. }
  4507. }
  4508. };
  4509. this.items = {}; // object with an Item for every data item
  4510. this.selection = []; // list with the ids of all selected nodes
  4511. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4512. this.stack = new Stack(this, Object.create(this.options));
  4513. this.conversion = null;
  4514. this.touchParams = {}; // stores properties while dragging
  4515. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4516. }
  4517. ItemSet.prototype = new Panel();
  4518. // available item types will be registered here
  4519. ItemSet.types = {
  4520. box: ItemBox,
  4521. range: ItemRange,
  4522. rangeoverflow: ItemRangeOverflow,
  4523. point: ItemPoint
  4524. };
  4525. /**
  4526. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4527. * @param {Object} [options] The following options are available:
  4528. * {String | function} [className]
  4529. * class name for the itemset
  4530. * {String} [type]
  4531. * Default type for the items. Choose from 'box'
  4532. * (default), 'point', or 'range'. The default
  4533. * Style can be overwritten by individual items.
  4534. * {String} align
  4535. * Alignment for the items, only applicable for
  4536. * ItemBox. Choose 'center' (default), 'left', or
  4537. * 'right'.
  4538. * {String} orientation
  4539. * Orientation of the item set. Choose 'top' or
  4540. * 'bottom' (default).
  4541. * {Number} margin.axis
  4542. * Margin between the axis and the items in pixels.
  4543. * Default is 20.
  4544. * {Number} margin.item
  4545. * Margin between items in pixels. Default is 10.
  4546. * {Number} padding
  4547. * Padding of the contents of an item in pixels.
  4548. * Must correspond with the items css. Default is 5.
  4549. * {Function} snap
  4550. * Function to let items snap to nice dates when
  4551. * dragging items.
  4552. */
  4553. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4554. /**
  4555. * Set controller for this component
  4556. * @param {Controller | null} controller
  4557. */
  4558. ItemSet.prototype.setController = function setController (controller) {
  4559. var event;
  4560. // unregister old event listeners
  4561. if (this.controller) {
  4562. for (event in this.eventListeners) {
  4563. if (this.eventListeners.hasOwnProperty(event)) {
  4564. this.controller.off(event, this.eventListeners[event]);
  4565. }
  4566. }
  4567. }
  4568. this.controller = controller || null;
  4569. // register new event listeners
  4570. if (this.controller) {
  4571. for (event in this.eventListeners) {
  4572. if (this.eventListeners.hasOwnProperty(event)) {
  4573. this.controller.on(event, this.eventListeners[event]);
  4574. }
  4575. }
  4576. }
  4577. };
  4578. // attach event listeners for dragging items to the controller
  4579. (function (me) {
  4580. var _controller = null;
  4581. var _onDragStart = null;
  4582. var _onDrag = null;
  4583. var _onDragEnd = null;
  4584. Object.defineProperty(me, 'controller', {
  4585. get: function () {
  4586. return _controller;
  4587. },
  4588. set: function (controller) {
  4589. }
  4590. });
  4591. }) (this);
  4592. /**
  4593. * Set range (start and end).
  4594. * @param {Range | Object} range A Range or an object containing start and end.
  4595. */
  4596. ItemSet.prototype.setRange = function setRange(range) {
  4597. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4598. throw new TypeError('Range must be an instance of Range, ' +
  4599. 'or an object containing start and end.');
  4600. }
  4601. this.range = range;
  4602. };
  4603. /**
  4604. * Set selected items by their id. Replaces the current selection
  4605. * Unknown id's are silently ignored.
  4606. * @param {Array} [ids] An array with zero or more id's of the items to be
  4607. * selected. If ids is an empty array, all items will be
  4608. * unselected.
  4609. */
  4610. ItemSet.prototype.setSelection = function setSelection(ids) {
  4611. var i, ii, id, item, selection;
  4612. if (ids) {
  4613. if (!Array.isArray(ids)) {
  4614. throw new TypeError('Array expected');
  4615. }
  4616. // unselect currently selected items
  4617. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4618. id = this.selection[i];
  4619. item = this.items[id];
  4620. if (item) item.unselect();
  4621. }
  4622. // select items
  4623. this.selection = [];
  4624. for (i = 0, ii = ids.length; i < ii; i++) {
  4625. id = ids[i];
  4626. item = this.items[id];
  4627. if (item) {
  4628. this.selection.push(id);
  4629. item.select();
  4630. }
  4631. }
  4632. if (this.controller) {
  4633. this.requestRepaint();
  4634. }
  4635. }
  4636. };
  4637. /**
  4638. * Get the selected items by their id
  4639. * @return {Array} ids The ids of the selected items
  4640. */
  4641. ItemSet.prototype.getSelection = function getSelection() {
  4642. return this.selection.concat([]);
  4643. };
  4644. /**
  4645. * Deselect a selected item
  4646. * @param {String | Number} id
  4647. * @private
  4648. */
  4649. ItemSet.prototype._deselect = function _deselect(id) {
  4650. var selection = this.selection;
  4651. for (var i = 0, ii = selection.length; i < ii; i++) {
  4652. if (selection[i] == id) { // non-strict comparison!
  4653. selection.splice(i, 1);
  4654. break;
  4655. }
  4656. }
  4657. };
  4658. /**
  4659. * Repaint the component
  4660. * @return {Boolean} changed
  4661. */
  4662. ItemSet.prototype.repaint = function repaint() {
  4663. var changed = 0,
  4664. update = util.updateProperty,
  4665. asSize = util.option.asSize,
  4666. options = this.options,
  4667. orientation = this.getOption('orientation'),
  4668. defaultOptions = this.defaultOptions,
  4669. frame = this.frame;
  4670. if (!frame) {
  4671. frame = document.createElement('div');
  4672. frame.className = 'itemset';
  4673. frame['timeline-itemset'] = this;
  4674. var className = options.className;
  4675. if (className) {
  4676. util.addClassName(frame, util.option.asString(className));
  4677. }
  4678. // create background panel
  4679. var background = document.createElement('div');
  4680. background.className = 'background';
  4681. frame.appendChild(background);
  4682. this.dom.background = background;
  4683. // create foreground panel
  4684. var foreground = document.createElement('div');
  4685. foreground.className = 'foreground';
  4686. frame.appendChild(foreground);
  4687. this.dom.foreground = foreground;
  4688. // create axis panel
  4689. var axis = document.createElement('div');
  4690. axis.className = 'itemset-axis';
  4691. //frame.appendChild(axis);
  4692. this.dom.axis = axis;
  4693. this.frame = frame;
  4694. changed += 1;
  4695. }
  4696. if (!this.parent) {
  4697. throw new Error('Cannot repaint itemset: no parent attached');
  4698. }
  4699. var parentContainer = this.parent.getContainer();
  4700. if (!parentContainer) {
  4701. throw new Error('Cannot repaint itemset: parent has no container element');
  4702. }
  4703. if (!frame.parentNode) {
  4704. parentContainer.appendChild(frame);
  4705. changed += 1;
  4706. }
  4707. if (!this.dom.axis.parentNode) {
  4708. parentContainer.appendChild(this.dom.axis);
  4709. changed += 1;
  4710. }
  4711. // reposition frame
  4712. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4713. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4714. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4715. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4716. // reposition axis
  4717. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4718. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4719. if (orientation == 'bottom') {
  4720. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4721. }
  4722. else { // orientation == 'top'
  4723. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4724. }
  4725. this._updateConversion();
  4726. var me = this,
  4727. queue = this.queue,
  4728. itemsData = this.itemsData,
  4729. items = this.items,
  4730. dataOptions = {
  4731. // TODO: cleanup
  4732. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  4733. };
  4734. // show/hide added/changed/removed items
  4735. for (var id in queue) {
  4736. if (queue.hasOwnProperty(id)) {
  4737. var entry = queue[id],
  4738. item = items[id],
  4739. action = entry.action;
  4740. //noinspection FallthroughInSwitchStatementJS
  4741. switch (action) {
  4742. case 'add':
  4743. case 'update':
  4744. var itemData = itemsData && itemsData.get(id, dataOptions);
  4745. if (itemData) {
  4746. var type = itemData.type ||
  4747. (itemData.start && itemData.end && 'range') ||
  4748. options.type ||
  4749. 'box';
  4750. var constructor = ItemSet.types[type];
  4751. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4752. if (item) {
  4753. // update item
  4754. if (!constructor || !(item instanceof constructor)) {
  4755. // item type has changed, hide and delete the item
  4756. changed += item.hide();
  4757. item = null;
  4758. }
  4759. else {
  4760. item.data = itemData; // TODO: create a method item.setData ?
  4761. changed++;
  4762. }
  4763. }
  4764. if (!item) {
  4765. // create item
  4766. if (constructor) {
  4767. item = new constructor(me, itemData, options, defaultOptions);
  4768. item.id = entry.id; // we take entry.id, as id itself is stringified
  4769. changed++;
  4770. }
  4771. else {
  4772. throw new TypeError('Unknown item type "' + type + '"');
  4773. }
  4774. }
  4775. // force a repaint (not only a reposition)
  4776. item.repaint();
  4777. items[id] = item;
  4778. }
  4779. // update queue
  4780. delete queue[id];
  4781. break;
  4782. case 'remove':
  4783. if (item) {
  4784. // remove the item from the set selected items
  4785. if (item.selected) {
  4786. me._deselect(id);
  4787. }
  4788. // remove DOM of the item
  4789. changed += item.hide();
  4790. }
  4791. // update lists
  4792. delete items[id];
  4793. delete queue[id];
  4794. break;
  4795. default:
  4796. console.log('Error: unknown action "' + action + '"');
  4797. }
  4798. }
  4799. }
  4800. // reposition all items. Show items only when in the visible area
  4801. util.forEach(this.items, function (item) {
  4802. if (item.visible) {
  4803. changed += item.show();
  4804. item.reposition();
  4805. }
  4806. else {
  4807. changed += item.hide();
  4808. }
  4809. });
  4810. return (changed > 0);
  4811. };
  4812. /**
  4813. * Get the foreground container element
  4814. * @return {HTMLElement} foreground
  4815. */
  4816. ItemSet.prototype.getForeground = function getForeground() {
  4817. return this.dom.foreground;
  4818. };
  4819. /**
  4820. * Get the background container element
  4821. * @return {HTMLElement} background
  4822. */
  4823. ItemSet.prototype.getBackground = function getBackground() {
  4824. return this.dom.background;
  4825. };
  4826. /**
  4827. * Get the axis container element
  4828. * @return {HTMLElement} axis
  4829. */
  4830. ItemSet.prototype.getAxis = function getAxis() {
  4831. return this.dom.axis;
  4832. };
  4833. /**
  4834. * Reflow the component
  4835. * @return {Boolean} resized
  4836. */
  4837. ItemSet.prototype.reflow = function reflow () {
  4838. var changed = 0,
  4839. options = this.options,
  4840. marginAxis = options.margin && options.margin.axis || this.defaultOptions.margin.axis,
  4841. marginItem = options.margin && options.margin.item || this.defaultOptions.margin.item,
  4842. update = util.updateProperty,
  4843. asNumber = util.option.asNumber,
  4844. asSize = util.option.asSize,
  4845. frame = this.frame;
  4846. if (frame) {
  4847. this._updateConversion();
  4848. util.forEach(this.items, function (item) {
  4849. changed += item.reflow();
  4850. });
  4851. // TODO: stack.update should be triggered via an event, in stack itself
  4852. // TODO: only update the stack when there are changed items
  4853. this.stack.update();
  4854. var maxHeight = asNumber(options.maxHeight);
  4855. var fixedHeight = (asSize(options.height) != null);
  4856. var height;
  4857. if (fixedHeight) {
  4858. height = frame.offsetHeight;
  4859. }
  4860. else {
  4861. // height is not specified, determine the height from the height and positioned items
  4862. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4863. if (visibleItems.length) {
  4864. var min = visibleItems[0].top;
  4865. var max = visibleItems[0].top + visibleItems[0].height;
  4866. util.forEach(visibleItems, function (item) {
  4867. min = Math.min(min, item.top);
  4868. max = Math.max(max, (item.top + item.height));
  4869. });
  4870. height = (max - min) + marginAxis + marginItem;
  4871. }
  4872. else {
  4873. height = marginAxis + marginItem;
  4874. }
  4875. }
  4876. if (maxHeight != null) {
  4877. height = Math.min(height, maxHeight);
  4878. }
  4879. changed += update(this, 'height', height);
  4880. // calculate height from items
  4881. changed += update(this, 'top', frame.offsetTop);
  4882. changed += update(this, 'left', frame.offsetLeft);
  4883. changed += update(this, 'width', frame.offsetWidth);
  4884. }
  4885. else {
  4886. changed += 1;
  4887. }
  4888. return (changed > 0);
  4889. };
  4890. /**
  4891. * Hide this component from the DOM
  4892. * @return {Boolean} changed
  4893. */
  4894. ItemSet.prototype.hide = function hide() {
  4895. var changed = false;
  4896. // remove the DOM
  4897. if (this.frame && this.frame.parentNode) {
  4898. this.frame.parentNode.removeChild(this.frame);
  4899. changed = true;
  4900. }
  4901. if (this.dom.axis && this.dom.axis.parentNode) {
  4902. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4903. changed = true;
  4904. }
  4905. return changed;
  4906. };
  4907. /**
  4908. * Set items
  4909. * @param {vis.DataSet | null} items
  4910. */
  4911. ItemSet.prototype.setItems = function setItems(items) {
  4912. var me = this,
  4913. ids,
  4914. oldItemsData = this.itemsData;
  4915. // replace the dataset
  4916. if (!items) {
  4917. this.itemsData = null;
  4918. }
  4919. else if (items instanceof DataSet || items instanceof DataView) {
  4920. this.itemsData = items;
  4921. }
  4922. else {
  4923. throw new TypeError('Data must be an instance of DataSet');
  4924. }
  4925. if (oldItemsData) {
  4926. // unsubscribe from old dataset
  4927. util.forEach(this.listeners, function (callback, event) {
  4928. oldItemsData.unsubscribe(event, callback);
  4929. });
  4930. // remove all drawn items
  4931. ids = oldItemsData.getIds();
  4932. this._onRemove(ids);
  4933. }
  4934. if (this.itemsData) {
  4935. // subscribe to new dataset
  4936. var id = this.id;
  4937. util.forEach(this.listeners, function (callback, event) {
  4938. me.itemsData.on(event, callback, id);
  4939. });
  4940. // draw all new items
  4941. ids = this.itemsData.getIds();
  4942. this._onAdd(ids);
  4943. }
  4944. };
  4945. /**
  4946. * Get the current items items
  4947. * @returns {vis.DataSet | null}
  4948. */
  4949. ItemSet.prototype.getItems = function getItems() {
  4950. return this.itemsData;
  4951. };
  4952. /**
  4953. * Remove an item by its id
  4954. * @param {String | Number} id
  4955. */
  4956. ItemSet.prototype.removeItem = function removeItem (id) {
  4957. var item = this.itemsData.get(id),
  4958. dataset = this._myDataSet();
  4959. if (item) {
  4960. // confirm deletion
  4961. this.options.onRemove(item, function (item) {
  4962. if (item) {
  4963. dataset.remove(item);
  4964. }
  4965. });
  4966. }
  4967. };
  4968. /**
  4969. * Handle updated items
  4970. * @param {Number[]} ids
  4971. * @private
  4972. */
  4973. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4974. this._toQueue('update', ids);
  4975. };
  4976. /**
  4977. * Handle changed items
  4978. * @param {Number[]} ids
  4979. * @private
  4980. */
  4981. ItemSet.prototype._onAdd = function _onAdd(ids) {
  4982. this._toQueue('add', ids);
  4983. };
  4984. /**
  4985. * Handle removed items
  4986. * @param {Number[]} ids
  4987. * @private
  4988. */
  4989. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4990. this._toQueue('remove', ids);
  4991. };
  4992. /**
  4993. * Put items in the queue to be added/updated/remove
  4994. * @param {String} action can be 'add', 'update', 'remove'
  4995. * @param {Number[]} ids
  4996. */
  4997. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  4998. var queue = this.queue;
  4999. ids.forEach(function (id) {
  5000. queue[id] = {
  5001. id: id,
  5002. action: action
  5003. };
  5004. });
  5005. if (this.controller) {
  5006. //this.requestReflow();
  5007. this.requestRepaint();
  5008. }
  5009. };
  5010. /**
  5011. * Calculate the scale and offset to convert a position on screen to the
  5012. * corresponding date and vice versa.
  5013. * After the method _updateConversion is executed once, the methods toTime
  5014. * and toScreen can be used.
  5015. * @private
  5016. */
  5017. ItemSet.prototype._updateConversion = function _updateConversion() {
  5018. var range = this.range;
  5019. if (!range) {
  5020. throw new Error('No range configured');
  5021. }
  5022. if (range.conversion) {
  5023. this.conversion = range.conversion(this.width);
  5024. }
  5025. else {
  5026. this.conversion = Range.conversion(range.start, range.end, this.width);
  5027. }
  5028. };
  5029. /**
  5030. * Convert a position on screen (pixels) to a datetime
  5031. * Before this method can be used, the method _updateConversion must be
  5032. * executed once.
  5033. * @param {int} x Position on the screen in pixels
  5034. * @return {Date} time The datetime the corresponds with given position x
  5035. */
  5036. ItemSet.prototype.toTime = function toTime(x) {
  5037. var conversion = this.conversion;
  5038. return new Date(x / conversion.scale + conversion.offset);
  5039. };
  5040. /**
  5041. * Convert a datetime (Date object) into a position on the screen
  5042. * Before this method can be used, the method _updateConversion must be
  5043. * executed once.
  5044. * @param {Date} time A date
  5045. * @return {int} x The position on the screen in pixels which corresponds
  5046. * with the given date.
  5047. */
  5048. ItemSet.prototype.toScreen = function toScreen(time) {
  5049. var conversion = this.conversion;
  5050. return (time.valueOf() - conversion.offset) * conversion.scale;
  5051. };
  5052. /**
  5053. * Start dragging the selected events
  5054. * @param {Event} event
  5055. * @private
  5056. */
  5057. ItemSet.prototype._onDragStart = function (event) {
  5058. if (!this.options.editable) {
  5059. return;
  5060. }
  5061. var item = ItemSet.itemFromTarget(event),
  5062. me = this;
  5063. if (item && item.selected) {
  5064. var dragLeftItem = event.target.dragLeftItem;
  5065. var dragRightItem = event.target.dragRightItem;
  5066. if (dragLeftItem) {
  5067. this.touchParams.itemProps = [{
  5068. item: dragLeftItem,
  5069. start: item.data.start.valueOf()
  5070. }];
  5071. }
  5072. else if (dragRightItem) {
  5073. this.touchParams.itemProps = [{
  5074. item: dragRightItem,
  5075. end: item.data.end.valueOf()
  5076. }];
  5077. }
  5078. else {
  5079. this.touchParams.itemProps = this.getSelection().map(function (id) {
  5080. var item = me.items[id];
  5081. var props = {
  5082. item: item
  5083. };
  5084. if ('start' in item.data) {
  5085. props.start = item.data.start.valueOf()
  5086. }
  5087. if ('end' in item.data) {
  5088. props.end = item.data.end.valueOf()
  5089. }
  5090. return props;
  5091. });
  5092. }
  5093. event.stopPropagation();
  5094. }
  5095. };
  5096. /**
  5097. * Drag selected items
  5098. * @param {Event} event
  5099. * @private
  5100. */
  5101. ItemSet.prototype._onDrag = function (event) {
  5102. if (this.touchParams.itemProps) {
  5103. var snap = this.options.snap || null,
  5104. deltaX = event.gesture.deltaX,
  5105. offset = deltaX / this.conversion.scale;
  5106. // move
  5107. this.touchParams.itemProps.forEach(function (props) {
  5108. if ('start' in props) {
  5109. var start = new Date(props.start + offset);
  5110. props.item.data.start = snap ? snap(start) : start;
  5111. }
  5112. if ('end' in props) {
  5113. var end = new Date(props.end + offset);
  5114. props.item.data.end = snap ? snap(end) : end;
  5115. }
  5116. });
  5117. // TODO: implement onMoving handler
  5118. // TODO: implement dragging from one group to another
  5119. this.requestReflow();
  5120. event.stopPropagation();
  5121. }
  5122. };
  5123. /**
  5124. * End of dragging selected items
  5125. * @param {Event} event
  5126. * @private
  5127. */
  5128. ItemSet.prototype._onDragEnd = function (event) {
  5129. if (this.touchParams.itemProps) {
  5130. // prepare a change set for the changed items
  5131. var changes = [],
  5132. me = this,
  5133. dataset = this._myDataSet(),
  5134. type;
  5135. this.touchParams.itemProps.forEach(function (props) {
  5136. var id = props.item.id,
  5137. item = me.itemsData.get(id);
  5138. var changed = false;
  5139. if ('start' in props.item.data) {
  5140. changed = (props.start != props.item.data.start.valueOf());
  5141. item.start = util.convert(props.item.data.start, dataset.convert['start']);
  5142. }
  5143. if ('end' in props.item.data) {
  5144. changed = changed || (props.end != props.item.data.end.valueOf());
  5145. item.end = util.convert(props.item.data.end, dataset.convert['end']);
  5146. }
  5147. // only apply changes when start or end is actually changed
  5148. if (changed) {
  5149. me.options.onMove(item, function (item) {
  5150. if (item) {
  5151. // apply changes
  5152. changes.push(item);
  5153. }
  5154. else {
  5155. // restore original values
  5156. if ('start' in props) props.item.data.start = props.start;
  5157. if ('end' in props) props.item.data.end = props.end;
  5158. me.requestReflow();
  5159. }
  5160. });
  5161. }
  5162. });
  5163. this.touchParams.itemProps = null;
  5164. // apply the changes to the data (if there are changes)
  5165. if (changes.length) {
  5166. dataset.update(changes);
  5167. }
  5168. event.stopPropagation();
  5169. }
  5170. };
  5171. /**
  5172. * Find an item from an event target:
  5173. * searches for the attribute 'timeline-item' in the event target's element tree
  5174. * @param {Event} event
  5175. * @return {Item | null} item
  5176. */
  5177. ItemSet.itemFromTarget = function itemFromTarget (event) {
  5178. var target = event.target;
  5179. while (target) {
  5180. if (target.hasOwnProperty('timeline-item')) {
  5181. return target['timeline-item'];
  5182. }
  5183. target = target.parentNode;
  5184. }
  5185. return null;
  5186. };
  5187. /**
  5188. * Find the ItemSet from an event target:
  5189. * searches for the attribute 'timeline-itemset' in the event target's element tree
  5190. * @param {Event} event
  5191. * @return {ItemSet | null} item
  5192. */
  5193. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  5194. var target = event.target;
  5195. while (target) {
  5196. if (target.hasOwnProperty('timeline-itemset')) {
  5197. return target['timeline-itemset'];
  5198. }
  5199. target = target.parentNode;
  5200. }
  5201. return null;
  5202. };
  5203. /**
  5204. * Find the DataSet to which this ItemSet is connected
  5205. * @returns {null | DataSet} dataset
  5206. * @private
  5207. */
  5208. ItemSet.prototype._myDataSet = function _myDataSet() {
  5209. // find the root DataSet
  5210. var dataset = this.itemsData;
  5211. while (dataset instanceof DataView) {
  5212. dataset = dataset.data;
  5213. }
  5214. return dataset;
  5215. };
  5216. /**
  5217. * @constructor Item
  5218. * @param {ItemSet} parent
  5219. * @param {Object} data Object containing (optional) parameters type,
  5220. * start, end, content, group, className.
  5221. * @param {Object} [options] Options to set initial property values
  5222. * @param {Object} [defaultOptions] default options
  5223. * // TODO: describe available options
  5224. */
  5225. function Item (parent, data, options, defaultOptions) {
  5226. this.parent = parent;
  5227. this.data = data;
  5228. this.dom = null;
  5229. this.options = options || {};
  5230. this.defaultOptions = defaultOptions || {};
  5231. this.selected = false;
  5232. this.visible = false;
  5233. this.top = 0;
  5234. this.left = 0;
  5235. this.width = 0;
  5236. this.height = 0;
  5237. this.offset = 0;
  5238. }
  5239. /**
  5240. * Select current item
  5241. */
  5242. Item.prototype.select = function select() {
  5243. this.selected = true;
  5244. if (this.visible) this.repaint();
  5245. };
  5246. /**
  5247. * Unselect current item
  5248. */
  5249. Item.prototype.unselect = function unselect() {
  5250. this.selected = false;
  5251. if (this.visible) this.repaint();
  5252. };
  5253. /**
  5254. * Show the Item in the DOM (when not already visible)
  5255. * @return {Boolean} changed
  5256. */
  5257. Item.prototype.show = function show() {
  5258. return false;
  5259. };
  5260. /**
  5261. * Hide the Item from the DOM (when visible)
  5262. * @return {Boolean} changed
  5263. */
  5264. Item.prototype.hide = function hide() {
  5265. return false;
  5266. };
  5267. /**
  5268. * Repaint the item
  5269. * @return {Boolean} changed
  5270. */
  5271. Item.prototype.repaint = function repaint() {
  5272. // should be implemented by the item
  5273. return false;
  5274. };
  5275. /**
  5276. * Reflow the item
  5277. * @return {Boolean} resized
  5278. */
  5279. Item.prototype.reflow = function reflow() {
  5280. // should be implemented by the item
  5281. return false;
  5282. };
  5283. /**
  5284. * Give the item a display offset in pixels
  5285. * @param {Number} offset Offset on screen in pixels
  5286. */
  5287. Item.prototype.setOffset = function setOffset(offset) {
  5288. this.offset = offset;
  5289. };
  5290. /**
  5291. * Repaint a delete button on the top right of the item when the item is selected
  5292. * @param {HTMLElement} anchor
  5293. * @private
  5294. */
  5295. Item.prototype._repaintDeleteButton = function (anchor) {
  5296. if (this.selected && this.options.editable && !this.dom.deleteButton) {
  5297. // create and show button
  5298. var parent = this.parent;
  5299. var id = this.id;
  5300. var deleteButton = document.createElement('div');
  5301. deleteButton.className = 'delete';
  5302. deleteButton.title = 'Delete this item';
  5303. Hammer(deleteButton, {
  5304. preventDefault: true
  5305. }).on('tap', function (event) {
  5306. parent.removeItem(id);
  5307. event.stopPropagation();
  5308. });
  5309. anchor.appendChild(deleteButton);
  5310. this.dom.deleteButton = deleteButton;
  5311. }
  5312. else if (!this.selected && this.dom.deleteButton) {
  5313. // remove button
  5314. if (this.dom.deleteButton.parentNode) {
  5315. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5316. }
  5317. this.dom.deleteButton = null;
  5318. }
  5319. };
  5320. /**
  5321. * @constructor ItemBox
  5322. * @extends Item
  5323. * @param {ItemSet} parent
  5324. * @param {Object} data Object containing parameters start
  5325. * content, className.
  5326. * @param {Object} [options] Options to set initial property values
  5327. * @param {Object} [defaultOptions] default options
  5328. * // TODO: describe available options
  5329. */
  5330. function ItemBox (parent, data, options, defaultOptions) {
  5331. this.props = {
  5332. dot: {
  5333. left: 0,
  5334. top: 0,
  5335. width: 0,
  5336. height: 0
  5337. },
  5338. line: {
  5339. top: 0,
  5340. left: 0,
  5341. width: 0,
  5342. height: 0
  5343. }
  5344. };
  5345. Item.call(this, parent, data, options, defaultOptions);
  5346. }
  5347. ItemBox.prototype = new Item (null, null);
  5348. /**
  5349. * Repaint the item
  5350. * @return {Boolean} changed
  5351. */
  5352. ItemBox.prototype.repaint = function repaint() {
  5353. // TODO: make an efficient repaint
  5354. var changed = false;
  5355. var dom = this.dom;
  5356. if (!dom) {
  5357. this._create();
  5358. dom = this.dom;
  5359. changed = true;
  5360. }
  5361. if (dom) {
  5362. if (!this.parent) {
  5363. throw new Error('Cannot repaint item: no parent attached');
  5364. }
  5365. if (!dom.box.parentNode) {
  5366. var foreground = this.parent.getForeground();
  5367. if (!foreground) {
  5368. throw new Error('Cannot repaint time axis: ' +
  5369. 'parent has no foreground container element');
  5370. }
  5371. foreground.appendChild(dom.box);
  5372. changed = true;
  5373. }
  5374. if (!dom.line.parentNode) {
  5375. var background = this.parent.getBackground();
  5376. if (!background) {
  5377. throw new Error('Cannot repaint time axis: ' +
  5378. 'parent has no background container element');
  5379. }
  5380. background.appendChild(dom.line);
  5381. changed = true;
  5382. }
  5383. if (!dom.dot.parentNode) {
  5384. var axis = this.parent.getAxis();
  5385. if (!background) {
  5386. throw new Error('Cannot repaint time axis: ' +
  5387. 'parent has no axis container element');
  5388. }
  5389. axis.appendChild(dom.dot);
  5390. changed = true;
  5391. }
  5392. this._repaintDeleteButton(dom.box);
  5393. // update contents
  5394. if (this.data.content != this.content) {
  5395. this.content = this.data.content;
  5396. if (this.content instanceof Element) {
  5397. dom.content.innerHTML = '';
  5398. dom.content.appendChild(this.content);
  5399. }
  5400. else if (this.data.content != undefined) {
  5401. dom.content.innerHTML = this.content;
  5402. }
  5403. else {
  5404. throw new Error('Property "content" missing in item ' + this.data.id);
  5405. }
  5406. changed = true;
  5407. }
  5408. // update class
  5409. var className = (this.data.className? ' ' + this.data.className : '') +
  5410. (this.selected ? ' selected' : '');
  5411. if (this.className != className) {
  5412. this.className = className;
  5413. dom.box.className = 'item box' + className;
  5414. dom.line.className = 'item line' + className;
  5415. dom.dot.className = 'item dot' + className;
  5416. changed = true;
  5417. }
  5418. }
  5419. return changed;
  5420. };
  5421. /**
  5422. * Show the item in the DOM (when not already visible). The items DOM will
  5423. * be created when needed.
  5424. * @return {Boolean} changed
  5425. */
  5426. ItemBox.prototype.show = function show() {
  5427. if (!this.dom || !this.dom.box.parentNode) {
  5428. return this.repaint();
  5429. }
  5430. else {
  5431. return false;
  5432. }
  5433. };
  5434. /**
  5435. * Hide the item from the DOM (when visible)
  5436. * @return {Boolean} changed
  5437. */
  5438. ItemBox.prototype.hide = function hide() {
  5439. var changed = false,
  5440. dom = this.dom;
  5441. if (dom) {
  5442. if (dom.box.parentNode) {
  5443. dom.box.parentNode.removeChild(dom.box);
  5444. changed = true;
  5445. }
  5446. if (dom.line.parentNode) {
  5447. dom.line.parentNode.removeChild(dom.line);
  5448. }
  5449. if (dom.dot.parentNode) {
  5450. dom.dot.parentNode.removeChild(dom.dot);
  5451. }
  5452. }
  5453. return changed;
  5454. };
  5455. /**
  5456. * Reflow the item: calculate its actual size and position from the DOM
  5457. * @return {boolean} resized returns true if the axis is resized
  5458. * @override
  5459. */
  5460. ItemBox.prototype.reflow = function reflow() {
  5461. var changed = 0,
  5462. update,
  5463. dom,
  5464. props,
  5465. options,
  5466. margin,
  5467. start,
  5468. align,
  5469. orientation,
  5470. top,
  5471. left,
  5472. data,
  5473. range;
  5474. if (this.data.start == undefined) {
  5475. throw new Error('Property "start" missing in item ' + this.data.id);
  5476. }
  5477. data = this.data;
  5478. range = this.parent && this.parent.range;
  5479. if (data && range) {
  5480. // TODO: account for the width of the item
  5481. var interval = (range.end - range.start);
  5482. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  5483. }
  5484. else {
  5485. this.visible = false;
  5486. }
  5487. if (this.visible) {
  5488. dom = this.dom;
  5489. if (dom) {
  5490. update = util.updateProperty;
  5491. props = this.props;
  5492. options = this.options;
  5493. start = this.parent.toScreen(this.data.start) + this.offset;
  5494. align = options.align || this.defaultOptions.align;
  5495. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5496. orientation = options.orientation || this.defaultOptions.orientation;
  5497. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5498. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5499. changed += update(props.line, 'width', dom.line.offsetWidth);
  5500. changed += update(props.line, 'height', dom.line.offsetHeight);
  5501. changed += update(props.line, 'top', dom.line.offsetTop);
  5502. changed += update(this, 'width', dom.box.offsetWidth);
  5503. changed += update(this, 'height', dom.box.offsetHeight);
  5504. if (align == 'right') {
  5505. left = start - this.width;
  5506. }
  5507. else if (align == 'left') {
  5508. left = start;
  5509. }
  5510. else {
  5511. // default or 'center'
  5512. left = start - this.width / 2;
  5513. }
  5514. changed += update(this, 'left', left);
  5515. changed += update(props.line, 'left', start - props.line.width / 2);
  5516. changed += update(props.dot, 'left', start - props.dot.width / 2);
  5517. changed += update(props.dot, 'top', -props.dot.height / 2);
  5518. if (orientation == 'top') {
  5519. top = margin;
  5520. changed += update(this, 'top', top);
  5521. }
  5522. else {
  5523. // default or 'bottom'
  5524. var parentHeight = this.parent.height;
  5525. top = parentHeight - this.height - margin;
  5526. changed += update(this, 'top', top);
  5527. }
  5528. }
  5529. else {
  5530. changed += 1;
  5531. }
  5532. }
  5533. return (changed > 0);
  5534. };
  5535. /**
  5536. * Create an items DOM
  5537. * @private
  5538. */
  5539. ItemBox.prototype._create = function _create() {
  5540. var dom = this.dom;
  5541. if (!dom) {
  5542. this.dom = dom = {};
  5543. // create the box
  5544. dom.box = document.createElement('DIV');
  5545. // className is updated in repaint()
  5546. // contents box (inside the background box). used for making margins
  5547. dom.content = document.createElement('DIV');
  5548. dom.content.className = 'content';
  5549. dom.box.appendChild(dom.content);
  5550. // line to axis
  5551. dom.line = document.createElement('DIV');
  5552. dom.line.className = 'line';
  5553. // dot on axis
  5554. dom.dot = document.createElement('DIV');
  5555. dom.dot.className = 'dot';
  5556. // attach this item as attribute
  5557. dom.box['timeline-item'] = this;
  5558. }
  5559. };
  5560. /**
  5561. * Reposition the item, recalculate its left, top, and width, using the current
  5562. * range and size of the items itemset
  5563. * @override
  5564. */
  5565. ItemBox.prototype.reposition = function reposition() {
  5566. var dom = this.dom,
  5567. props = this.props,
  5568. orientation = this.options.orientation || this.defaultOptions.orientation;
  5569. if (dom) {
  5570. var box = dom.box,
  5571. line = dom.line,
  5572. dot = dom.dot;
  5573. box.style.left = this.left + 'px';
  5574. box.style.top = this.top + 'px';
  5575. line.style.left = props.line.left + 'px';
  5576. if (orientation == 'top') {
  5577. line.style.top = 0 + 'px';
  5578. line.style.height = this.top + 'px';
  5579. }
  5580. else {
  5581. // orientation 'bottom'
  5582. line.style.top = (this.top + this.height) + 'px';
  5583. line.style.height = Math.max(this.parent.height - this.top - this.height +
  5584. this.props.dot.height / 2, 0) + 'px';
  5585. }
  5586. dot.style.left = props.dot.left + 'px';
  5587. dot.style.top = props.dot.top + 'px';
  5588. }
  5589. };
  5590. /**
  5591. * @constructor ItemPoint
  5592. * @extends Item
  5593. * @param {ItemSet} parent
  5594. * @param {Object} data Object containing parameters start
  5595. * content, className.
  5596. * @param {Object} [options] Options to set initial property values
  5597. * @param {Object} [defaultOptions] default options
  5598. * // TODO: describe available options
  5599. */
  5600. function ItemPoint (parent, data, options, defaultOptions) {
  5601. this.props = {
  5602. dot: {
  5603. top: 0,
  5604. width: 0,
  5605. height: 0
  5606. },
  5607. content: {
  5608. height: 0,
  5609. marginLeft: 0
  5610. }
  5611. };
  5612. Item.call(this, parent, data, options, defaultOptions);
  5613. }
  5614. ItemPoint.prototype = new Item (null, null);
  5615. /**
  5616. * Repaint the item
  5617. * @return {Boolean} changed
  5618. */
  5619. ItemPoint.prototype.repaint = function repaint() {
  5620. // TODO: make an efficient repaint
  5621. var changed = false;
  5622. var dom = this.dom;
  5623. if (!dom) {
  5624. this._create();
  5625. dom = this.dom;
  5626. changed = true;
  5627. }
  5628. if (dom) {
  5629. if (!this.parent) {
  5630. throw new Error('Cannot repaint item: no parent attached');
  5631. }
  5632. var foreground = this.parent.getForeground();
  5633. if (!foreground) {
  5634. throw new Error('Cannot repaint time axis: ' +
  5635. 'parent has no foreground container element');
  5636. }
  5637. if (!dom.point.parentNode) {
  5638. foreground.appendChild(dom.point);
  5639. foreground.appendChild(dom.point);
  5640. changed = true;
  5641. }
  5642. // update contents
  5643. if (this.data.content != this.content) {
  5644. this.content = this.data.content;
  5645. if (this.content instanceof Element) {
  5646. dom.content.innerHTML = '';
  5647. dom.content.appendChild(this.content);
  5648. }
  5649. else if (this.data.content != undefined) {
  5650. dom.content.innerHTML = this.content;
  5651. }
  5652. else {
  5653. throw new Error('Property "content" missing in item ' + this.data.id);
  5654. }
  5655. changed = true;
  5656. }
  5657. this._repaintDeleteButton(dom.point);
  5658. // update class
  5659. var className = (this.data.className? ' ' + this.data.className : '') +
  5660. (this.selected ? ' selected' : '');
  5661. if (this.className != className) {
  5662. this.className = className;
  5663. dom.point.className = 'item point' + className;
  5664. changed = true;
  5665. }
  5666. }
  5667. return changed;
  5668. };
  5669. /**
  5670. * Show the item in the DOM (when not already visible). The items DOM will
  5671. * be created when needed.
  5672. * @return {Boolean} changed
  5673. */
  5674. ItemPoint.prototype.show = function show() {
  5675. if (!this.dom || !this.dom.point.parentNode) {
  5676. return this.repaint();
  5677. }
  5678. else {
  5679. return false;
  5680. }
  5681. };
  5682. /**
  5683. * Hide the item from the DOM (when visible)
  5684. * @return {Boolean} changed
  5685. */
  5686. ItemPoint.prototype.hide = function hide() {
  5687. var changed = false,
  5688. dom = this.dom;
  5689. if (dom) {
  5690. if (dom.point.parentNode) {
  5691. dom.point.parentNode.removeChild(dom.point);
  5692. changed = true;
  5693. }
  5694. }
  5695. return changed;
  5696. };
  5697. /**
  5698. * Reflow the item: calculate its actual size from the DOM
  5699. * @return {boolean} resized returns true if the axis is resized
  5700. * @override
  5701. */
  5702. ItemPoint.prototype.reflow = function reflow() {
  5703. var changed = 0,
  5704. update,
  5705. dom,
  5706. props,
  5707. options,
  5708. margin,
  5709. orientation,
  5710. start,
  5711. top,
  5712. data,
  5713. range;
  5714. if (this.data.start == undefined) {
  5715. throw new Error('Property "start" missing in item ' + this.data.id);
  5716. }
  5717. data = this.data;
  5718. range = this.parent && this.parent.range;
  5719. if (data && range) {
  5720. // TODO: account for the width of the item
  5721. var interval = (range.end - range.start);
  5722. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  5723. }
  5724. else {
  5725. this.visible = false;
  5726. }
  5727. if (this.visible) {
  5728. dom = this.dom;
  5729. if (dom) {
  5730. update = util.updateProperty;
  5731. props = this.props;
  5732. options = this.options;
  5733. orientation = options.orientation || this.defaultOptions.orientation;
  5734. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5735. start = this.parent.toScreen(this.data.start) + this.offset;
  5736. changed += update(this, 'width', dom.point.offsetWidth);
  5737. changed += update(this, 'height', dom.point.offsetHeight);
  5738. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5739. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5740. changed += update(props.content, 'height', dom.content.offsetHeight);
  5741. if (orientation == 'top') {
  5742. top = margin;
  5743. }
  5744. else {
  5745. // default or 'bottom'
  5746. var parentHeight = this.parent.height;
  5747. top = Math.max(parentHeight - this.height - margin, 0);
  5748. }
  5749. changed += update(this, 'top', top);
  5750. changed += update(this, 'left', start - props.dot.width / 2);
  5751. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5752. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5753. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5754. }
  5755. else {
  5756. changed += 1;
  5757. }
  5758. }
  5759. return (changed > 0);
  5760. };
  5761. /**
  5762. * Create an items DOM
  5763. * @private
  5764. */
  5765. ItemPoint.prototype._create = function _create() {
  5766. var dom = this.dom;
  5767. if (!dom) {
  5768. this.dom = dom = {};
  5769. // background box
  5770. dom.point = document.createElement('div');
  5771. // className is updated in repaint()
  5772. // contents box, right from the dot
  5773. dom.content = document.createElement('div');
  5774. dom.content.className = 'content';
  5775. dom.point.appendChild(dom.content);
  5776. // dot at start
  5777. dom.dot = document.createElement('div');
  5778. dom.dot.className = 'dot';
  5779. dom.point.appendChild(dom.dot);
  5780. // attach this item as attribute
  5781. dom.point['timeline-item'] = this;
  5782. }
  5783. };
  5784. /**
  5785. * Reposition the item, recalculate its left, top, and width, using the current
  5786. * range and size of the items itemset
  5787. * @override
  5788. */
  5789. ItemPoint.prototype.reposition = function reposition() {
  5790. var dom = this.dom,
  5791. props = this.props;
  5792. if (dom) {
  5793. dom.point.style.top = this.top + 'px';
  5794. dom.point.style.left = this.left + 'px';
  5795. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5796. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5797. dom.dot.style.top = props.dot.top + 'px';
  5798. }
  5799. };
  5800. /**
  5801. * @constructor ItemRange
  5802. * @extends Item
  5803. * @param {ItemSet} parent
  5804. * @param {Object} data Object containing parameters start, end
  5805. * content, className.
  5806. * @param {Object} [options] Options to set initial property values
  5807. * @param {Object} [defaultOptions] default options
  5808. * // TODO: describe available options
  5809. */
  5810. function ItemRange (parent, data, options, defaultOptions) {
  5811. this.props = {
  5812. content: {
  5813. left: 0,
  5814. width: 0
  5815. }
  5816. };
  5817. Item.call(this, parent, data, options, defaultOptions);
  5818. }
  5819. ItemRange.prototype = new Item (null, null);
  5820. /**
  5821. * Repaint the item
  5822. * @return {Boolean} changed
  5823. */
  5824. ItemRange.prototype.repaint = function repaint() {
  5825. // TODO: make an efficient repaint
  5826. var changed = false;
  5827. var dom = this.dom;
  5828. if (!dom) {
  5829. this._create();
  5830. dom = this.dom;
  5831. changed = true;
  5832. }
  5833. if (dom) {
  5834. if (!this.parent) {
  5835. throw new Error('Cannot repaint item: no parent attached');
  5836. }
  5837. var foreground = this.parent.getForeground();
  5838. if (!foreground) {
  5839. throw new Error('Cannot repaint time axis: ' +
  5840. 'parent has no foreground container element');
  5841. }
  5842. if (!dom.box.parentNode) {
  5843. foreground.appendChild(dom.box);
  5844. changed = true;
  5845. }
  5846. // update content
  5847. if (this.data.content != this.content) {
  5848. this.content = this.data.content;
  5849. if (this.content instanceof Element) {
  5850. dom.content.innerHTML = '';
  5851. dom.content.appendChild(this.content);
  5852. }
  5853. else if (this.data.content != undefined) {
  5854. dom.content.innerHTML = this.content;
  5855. }
  5856. else {
  5857. throw new Error('Property "content" missing in item ' + this.data.id);
  5858. }
  5859. changed = true;
  5860. }
  5861. this._repaintDeleteButton(dom.box);
  5862. this._repaintDragLeft();
  5863. this._repaintDragRight();
  5864. // update class
  5865. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5866. (this.selected ? ' selected' : '');
  5867. if (this.className != className) {
  5868. this.className = className;
  5869. dom.box.className = 'item range' + className;
  5870. changed = true;
  5871. }
  5872. }
  5873. return changed;
  5874. };
  5875. /**
  5876. * Show the item in the DOM (when not already visible). The items DOM will
  5877. * be created when needed.
  5878. * @return {Boolean} changed
  5879. */
  5880. ItemRange.prototype.show = function show() {
  5881. if (!this.dom || !this.dom.box.parentNode) {
  5882. return this.repaint();
  5883. }
  5884. else {
  5885. return false;
  5886. }
  5887. };
  5888. /**
  5889. * Hide the item from the DOM (when visible)
  5890. * @return {Boolean} changed
  5891. */
  5892. ItemRange.prototype.hide = function hide() {
  5893. var changed = false,
  5894. dom = this.dom;
  5895. if (dom) {
  5896. if (dom.box.parentNode) {
  5897. dom.box.parentNode.removeChild(dom.box);
  5898. changed = true;
  5899. }
  5900. }
  5901. return changed;
  5902. };
  5903. /**
  5904. * Reflow the item: calculate its actual size from the DOM
  5905. * @return {boolean} resized returns true if the axis is resized
  5906. * @override
  5907. */
  5908. ItemRange.prototype.reflow = function reflow() {
  5909. var changed = 0,
  5910. dom,
  5911. props,
  5912. options,
  5913. margin,
  5914. padding,
  5915. parent,
  5916. start,
  5917. end,
  5918. data,
  5919. range,
  5920. update,
  5921. box,
  5922. parentWidth,
  5923. contentLeft,
  5924. orientation,
  5925. top;
  5926. if (this.data.start == undefined) {
  5927. throw new Error('Property "start" missing in item ' + this.data.id);
  5928. }
  5929. if (this.data.end == undefined) {
  5930. throw new Error('Property "end" missing in item ' + this.data.id);
  5931. }
  5932. data = this.data;
  5933. range = this.parent && this.parent.range;
  5934. if (data && range) {
  5935. // TODO: account for the width of the item. Take some margin
  5936. this.visible = (data.start < range.end) && (data.end > range.start);
  5937. }
  5938. else {
  5939. this.visible = false;
  5940. }
  5941. if (this.visible) {
  5942. dom = this.dom;
  5943. if (dom) {
  5944. props = this.props;
  5945. options = this.options;
  5946. parent = this.parent;
  5947. start = parent.toScreen(this.data.start) + this.offset;
  5948. end = parent.toScreen(this.data.end) + this.offset;
  5949. update = util.updateProperty;
  5950. box = dom.box;
  5951. parentWidth = parent.width;
  5952. orientation = options.orientation || this.defaultOptions.orientation;
  5953. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5954. padding = options.padding || this.defaultOptions.padding;
  5955. changed += update(props.content, 'width', dom.content.offsetWidth);
  5956. changed += update(this, 'height', box.offsetHeight);
  5957. // limit the width of the this, as browsers cannot draw very wide divs
  5958. if (start < -parentWidth) {
  5959. start = -parentWidth;
  5960. }
  5961. if (end > 2 * parentWidth) {
  5962. end = 2 * parentWidth;
  5963. }
  5964. // when range exceeds left of the window, position the contents at the left of the visible area
  5965. if (start < 0) {
  5966. contentLeft = Math.min(-start,
  5967. (end - start - props.content.width - 2 * padding));
  5968. // TODO: remove the need for options.padding. it's terrible.
  5969. }
  5970. else {
  5971. contentLeft = 0;
  5972. }
  5973. changed += update(props.content, 'left', contentLeft);
  5974. if (orientation == 'top') {
  5975. top = margin;
  5976. changed += update(this, 'top', top);
  5977. }
  5978. else {
  5979. // default or 'bottom'
  5980. top = parent.height - this.height - margin;
  5981. changed += update(this, 'top', top);
  5982. }
  5983. changed += update(this, 'left', start);
  5984. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  5985. }
  5986. else {
  5987. changed += 1;
  5988. }
  5989. }
  5990. return (changed > 0);
  5991. };
  5992. /**
  5993. * Create an items DOM
  5994. * @private
  5995. */
  5996. ItemRange.prototype._create = function _create() {
  5997. var dom = this.dom;
  5998. if (!dom) {
  5999. this.dom = dom = {};
  6000. // background box
  6001. dom.box = document.createElement('div');
  6002. // className is updated in repaint()
  6003. // contents box
  6004. dom.content = document.createElement('div');
  6005. dom.content.className = 'content';
  6006. dom.box.appendChild(dom.content);
  6007. // attach this item as attribute
  6008. dom.box['timeline-item'] = this;
  6009. }
  6010. };
  6011. /**
  6012. * Reposition the item, recalculate its left, top, and width, using the current
  6013. * range and size of the items itemset
  6014. * @override
  6015. */
  6016. ItemRange.prototype.reposition = function reposition() {
  6017. var dom = this.dom,
  6018. props = this.props;
  6019. if (dom) {
  6020. dom.box.style.top = this.top + 'px';
  6021. dom.box.style.left = this.left + 'px';
  6022. dom.box.style.width = this.width + 'px';
  6023. dom.content.style.left = props.content.left + 'px';
  6024. }
  6025. };
  6026. /**
  6027. * Repaint a drag area on the left side of the range when the range is selected
  6028. * @private
  6029. */
  6030. ItemRange.prototype._repaintDragLeft = function () {
  6031. if (this.selected && this.options.editable && !this.dom.dragLeft) {
  6032. // create and show drag area
  6033. var dragLeft = document.createElement('div');
  6034. dragLeft.className = 'drag-left';
  6035. dragLeft.dragLeftItem = this;
  6036. // TODO: this should be redundant?
  6037. Hammer(dragLeft, {
  6038. preventDefault: true
  6039. }).on('drag', function () {
  6040. //console.log('drag left')
  6041. });
  6042. this.dom.box.appendChild(dragLeft);
  6043. this.dom.dragLeft = dragLeft;
  6044. }
  6045. else if (!this.selected && this.dom.dragLeft) {
  6046. // delete drag area
  6047. if (this.dom.dragLeft.parentNode) {
  6048. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  6049. }
  6050. this.dom.dragLeft = null;
  6051. }
  6052. };
  6053. /**
  6054. * Repaint a drag area on the right side of the range when the range is selected
  6055. * @private
  6056. */
  6057. ItemRange.prototype._repaintDragRight = function () {
  6058. if (this.selected && this.options.editable && !this.dom.dragRight) {
  6059. // create and show drag area
  6060. var dragRight = document.createElement('div');
  6061. dragRight.className = 'drag-right';
  6062. dragRight.dragRightItem = this;
  6063. // TODO: this should be redundant?
  6064. Hammer(dragRight, {
  6065. preventDefault: true
  6066. }).on('drag', function () {
  6067. //console.log('drag right')
  6068. });
  6069. this.dom.box.appendChild(dragRight);
  6070. this.dom.dragRight = dragRight;
  6071. }
  6072. else if (!this.selected && this.dom.dragRight) {
  6073. // delete drag area
  6074. if (this.dom.dragRight.parentNode) {
  6075. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  6076. }
  6077. this.dom.dragRight = null;
  6078. }
  6079. };
  6080. /**
  6081. * @constructor ItemRangeOverflow
  6082. * @extends ItemRange
  6083. * @param {ItemSet} parent
  6084. * @param {Object} data Object containing parameters start, end
  6085. * content, className.
  6086. * @param {Object} [options] Options to set initial property values
  6087. * @param {Object} [defaultOptions] default options
  6088. * // TODO: describe available options
  6089. */
  6090. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  6091. this.props = {
  6092. content: {
  6093. left: 0,
  6094. width: 0
  6095. }
  6096. };
  6097. // define a private property _width, which is the with of the range box
  6098. // adhering to the ranges start and end date. The property width has a
  6099. // getter which returns the max of border width and content width
  6100. this._width = 0;
  6101. Object.defineProperty(this, 'width', {
  6102. get: function () {
  6103. return (this.props.content && this._width < this.props.content.width) ?
  6104. this.props.content.width :
  6105. this._width;
  6106. },
  6107. set: function (width) {
  6108. this._width = width;
  6109. }
  6110. });
  6111. ItemRange.call(this, parent, data, options, defaultOptions);
  6112. }
  6113. ItemRangeOverflow.prototype = new ItemRange (null, null);
  6114. /**
  6115. * Repaint the item
  6116. * @return {Boolean} changed
  6117. */
  6118. ItemRangeOverflow.prototype.repaint = function repaint() {
  6119. // TODO: make an efficient repaint
  6120. var changed = false;
  6121. var dom = this.dom;
  6122. if (!dom) {
  6123. this._create();
  6124. dom = this.dom;
  6125. changed = true;
  6126. }
  6127. if (dom) {
  6128. if (!this.parent) {
  6129. throw new Error('Cannot repaint item: no parent attached');
  6130. }
  6131. var foreground = this.parent.getForeground();
  6132. if (!foreground) {
  6133. throw new Error('Cannot repaint time axis: ' +
  6134. 'parent has no foreground container element');
  6135. }
  6136. if (!dom.box.parentNode) {
  6137. foreground.appendChild(dom.box);
  6138. changed = true;
  6139. }
  6140. // update content
  6141. if (this.data.content != this.content) {
  6142. this.content = this.data.content;
  6143. if (this.content instanceof Element) {
  6144. dom.content.innerHTML = '';
  6145. dom.content.appendChild(this.content);
  6146. }
  6147. else if (this.data.content != undefined) {
  6148. dom.content.innerHTML = this.content;
  6149. }
  6150. else {
  6151. throw new Error('Property "content" missing in item ' + this.id);
  6152. }
  6153. changed = true;
  6154. }
  6155. this._repaintDeleteButton(dom.box);
  6156. this._repaintDragLeft();
  6157. this._repaintDragRight();
  6158. // update class
  6159. var className = (this.data.className? ' ' + this.data.className : '') +
  6160. (this.selected ? ' selected' : '');
  6161. if (this.className != className) {
  6162. this.className = className;
  6163. dom.box.className = 'item rangeoverflow' + className;
  6164. changed = true;
  6165. }
  6166. }
  6167. return changed;
  6168. };
  6169. /**
  6170. * Reposition the item, recalculate its left, top, and width, using the current
  6171. * range and size of the items itemset
  6172. * @override
  6173. */
  6174. ItemRangeOverflow.prototype.reposition = function reposition() {
  6175. var dom = this.dom,
  6176. props = this.props;
  6177. if (dom) {
  6178. dom.box.style.top = this.top + 'px';
  6179. dom.box.style.left = this.left + 'px';
  6180. dom.box.style.width = this._width + 'px';
  6181. dom.content.style.left = props.content.left + 'px';
  6182. }
  6183. };
  6184. /**
  6185. * @constructor Group
  6186. * @param {GroupSet} parent
  6187. * @param {Number | String} groupId
  6188. * @param {Object} [options] Options to set initial property values
  6189. * // TODO: describe available options
  6190. * @extends Component
  6191. */
  6192. function Group (parent, groupId, options) {
  6193. this.id = util.randomUUID();
  6194. this.parent = parent;
  6195. this.groupId = groupId;
  6196. this.itemset = null; // ItemSet
  6197. this.options = options || {};
  6198. this.options.top = 0;
  6199. this.props = {
  6200. label: {
  6201. width: 0,
  6202. height: 0
  6203. }
  6204. };
  6205. this.top = 0;
  6206. this.left = 0;
  6207. this.width = 0;
  6208. this.height = 0;
  6209. }
  6210. Group.prototype = new Component();
  6211. // TODO: comment
  6212. Group.prototype.setOptions = Component.prototype.setOptions;
  6213. /**
  6214. * Get the container element of the panel, which can be used by a child to
  6215. * add its own widgets.
  6216. * @returns {HTMLElement} container
  6217. */
  6218. Group.prototype.getContainer = function () {
  6219. return this.parent.getContainer();
  6220. };
  6221. /**
  6222. * Set item set for the group. The group will create a view on the itemset,
  6223. * filtered by the groups id.
  6224. * @param {DataSet | DataView} items
  6225. */
  6226. Group.prototype.setItems = function setItems(items) {
  6227. if (this.itemset) {
  6228. // remove current item set
  6229. this.itemset.hide();
  6230. this.itemset.setItems();
  6231. this.parent.controller.remove(this.itemset);
  6232. this.itemset = null;
  6233. }
  6234. if (items) {
  6235. var groupId = this.groupId;
  6236. var itemsetOptions = Object.create(this.options);
  6237. this.itemset = new ItemSet(this, null, itemsetOptions);
  6238. this.itemset.setRange(this.parent.range);
  6239. this.view = new DataView(items, {
  6240. filter: function (item) {
  6241. return item.group == groupId;
  6242. }
  6243. });
  6244. this.itemset.setItems(this.view);
  6245. this.parent.controller.add(this.itemset);
  6246. }
  6247. };
  6248. /**
  6249. * Set selected items by their id. Replaces the current selection.
  6250. * Unknown id's are silently ignored.
  6251. * @param {Array} [ids] An array with zero or more id's of the items to be
  6252. * selected. If ids is an empty array, all items will be
  6253. * unselected.
  6254. */
  6255. Group.prototype.setSelection = function setSelection(ids) {
  6256. if (this.itemset) this.itemset.setSelection(ids);
  6257. };
  6258. /**
  6259. * Get the selected items by their id
  6260. * @return {Array} ids The ids of the selected items
  6261. */
  6262. Group.prototype.getSelection = function getSelection() {
  6263. return this.itemset ? this.itemset.getSelection() : [];
  6264. };
  6265. /**
  6266. * Repaint the item
  6267. * @return {Boolean} changed
  6268. */
  6269. Group.prototype.repaint = function repaint() {
  6270. return false;
  6271. };
  6272. /**
  6273. * Reflow the item
  6274. * @return {Boolean} resized
  6275. */
  6276. Group.prototype.reflow = function reflow() {
  6277. var changed = 0,
  6278. update = util.updateProperty;
  6279. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  6280. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  6281. // TODO: reckon with the height of the group label
  6282. if (this.label) {
  6283. var inner = this.label.firstChild;
  6284. changed += update(this.props.label, 'width', inner.clientWidth);
  6285. changed += update(this.props.label, 'height', inner.clientHeight);
  6286. }
  6287. else {
  6288. changed += update(this.props.label, 'width', 0);
  6289. changed += update(this.props.label, 'height', 0);
  6290. }
  6291. return (changed > 0);
  6292. };
  6293. /**
  6294. * An GroupSet holds a set of groups
  6295. * @param {Component} parent
  6296. * @param {Component[]} [depends] Components on which this components depends
  6297. * (except for the parent)
  6298. * @param {Object} [options] See GroupSet.setOptions for the available
  6299. * options.
  6300. * @constructor GroupSet
  6301. * @extends Panel
  6302. */
  6303. function GroupSet(parent, depends, options) {
  6304. this.id = util.randomUUID();
  6305. this.parent = parent;
  6306. this.depends = depends;
  6307. this.options = options || {};
  6308. this.range = null; // Range or Object {start: number, end: number}
  6309. this.itemsData = null; // DataSet with items
  6310. this.groupsData = null; // DataSet with groups
  6311. this.groups = {}; // map with groups
  6312. this.dom = {};
  6313. this.props = {
  6314. labels: {
  6315. width: 0
  6316. }
  6317. };
  6318. // TODO: implement right orientation of the labels
  6319. // changes in groups are queued key/value map containing id/action
  6320. this.queue = {};
  6321. var me = this;
  6322. this.listeners = {
  6323. 'add': function (event, params) {
  6324. me._onAdd(params.items);
  6325. },
  6326. 'update': function (event, params) {
  6327. me._onUpdate(params.items);
  6328. },
  6329. 'remove': function (event, params) {
  6330. me._onRemove(params.items);
  6331. }
  6332. };
  6333. }
  6334. GroupSet.prototype = new Panel();
  6335. /**
  6336. * Set options for the GroupSet. Existing options will be extended/overwritten.
  6337. * @param {Object} [options] The following options are available:
  6338. * {String | function} groupsOrder
  6339. * TODO: describe options
  6340. */
  6341. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  6342. GroupSet.prototype.setRange = function (range) {
  6343. // TODO: implement setRange
  6344. };
  6345. /**
  6346. * Set items
  6347. * @param {vis.DataSet | null} items
  6348. */
  6349. GroupSet.prototype.setItems = function setItems(items) {
  6350. this.itemsData = items;
  6351. for (var id in this.groups) {
  6352. if (this.groups.hasOwnProperty(id)) {
  6353. var group = this.groups[id];
  6354. group.setItems(items);
  6355. }
  6356. }
  6357. };
  6358. /**
  6359. * Get items
  6360. * @return {vis.DataSet | null} items
  6361. */
  6362. GroupSet.prototype.getItems = function getItems() {
  6363. return this.itemsData;
  6364. };
  6365. /**
  6366. * Set range (start and end).
  6367. * @param {Range | Object} range A Range or an object containing start and end.
  6368. */
  6369. GroupSet.prototype.setRange = function setRange(range) {
  6370. this.range = range;
  6371. };
  6372. /**
  6373. * Set groups
  6374. * @param {vis.DataSet} groups
  6375. */
  6376. GroupSet.prototype.setGroups = function setGroups(groups) {
  6377. var me = this,
  6378. ids;
  6379. // unsubscribe from current dataset
  6380. if (this.groupsData) {
  6381. util.forEach(this.listeners, function (callback, event) {
  6382. me.groupsData.unsubscribe(event, callback);
  6383. });
  6384. // remove all drawn groups
  6385. ids = this.groupsData.getIds();
  6386. this._onRemove(ids);
  6387. }
  6388. // replace the dataset
  6389. if (!groups) {
  6390. this.groupsData = null;
  6391. }
  6392. else if (groups instanceof DataSet) {
  6393. this.groupsData = groups;
  6394. }
  6395. else {
  6396. this.groupsData = new DataSet({
  6397. convert: {
  6398. start: 'Date',
  6399. end: 'Date'
  6400. }
  6401. });
  6402. this.groupsData.add(groups);
  6403. }
  6404. if (this.groupsData) {
  6405. // subscribe to new dataset
  6406. var id = this.id;
  6407. util.forEach(this.listeners, function (callback, event) {
  6408. me.groupsData.on(event, callback, id);
  6409. });
  6410. // draw all new groups
  6411. ids = this.groupsData.getIds();
  6412. this._onAdd(ids);
  6413. }
  6414. };
  6415. /**
  6416. * Get groups
  6417. * @return {vis.DataSet | null} groups
  6418. */
  6419. GroupSet.prototype.getGroups = function getGroups() {
  6420. return this.groupsData;
  6421. };
  6422. /**
  6423. * Set selected items by their id. Replaces the current selection.
  6424. * Unknown id's are silently ignored.
  6425. * @param {Array} [ids] An array with zero or more id's of the items to be
  6426. * selected. If ids is an empty array, all items will be
  6427. * unselected.
  6428. */
  6429. GroupSet.prototype.setSelection = function setSelection(ids) {
  6430. var selection = [],
  6431. groups = this.groups;
  6432. // iterate over each of the groups
  6433. for (var id in groups) {
  6434. if (groups.hasOwnProperty(id)) {
  6435. var group = groups[id];
  6436. group.setSelection(ids);
  6437. }
  6438. }
  6439. return selection;
  6440. };
  6441. /**
  6442. * Get the selected items by their id
  6443. * @return {Array} ids The ids of the selected items
  6444. */
  6445. GroupSet.prototype.getSelection = function getSelection() {
  6446. var selection = [],
  6447. groups = this.groups;
  6448. // iterate over each of the groups
  6449. for (var id in groups) {
  6450. if (groups.hasOwnProperty(id)) {
  6451. var group = groups[id];
  6452. selection = selection.concat(group.getSelection());
  6453. }
  6454. }
  6455. return selection;
  6456. };
  6457. /**
  6458. * Repaint the component
  6459. * @return {Boolean} changed
  6460. */
  6461. GroupSet.prototype.repaint = function repaint() {
  6462. var changed = 0,
  6463. i, id, group, label,
  6464. update = util.updateProperty,
  6465. asSize = util.option.asSize,
  6466. asElement = util.option.asElement,
  6467. options = this.options,
  6468. frame = this.dom.frame,
  6469. labels = this.dom.labels,
  6470. labelSet = this.dom.labelSet;
  6471. // create frame
  6472. if (!this.parent) {
  6473. throw new Error('Cannot repaint groupset: no parent attached');
  6474. }
  6475. var parentContainer = this.parent.getContainer();
  6476. if (!parentContainer) {
  6477. throw new Error('Cannot repaint groupset: parent has no container element');
  6478. }
  6479. if (!frame) {
  6480. frame = document.createElement('div');
  6481. frame.className = 'groupset';
  6482. frame['timeline-groupset'] = this;
  6483. this.dom.frame = frame;
  6484. var className = options.className;
  6485. if (className) {
  6486. util.addClassName(frame, util.option.asString(className));
  6487. }
  6488. changed += 1;
  6489. }
  6490. if (!frame.parentNode) {
  6491. parentContainer.appendChild(frame);
  6492. changed += 1;
  6493. }
  6494. // create labels
  6495. var labelContainer = asElement(options.labelContainer);
  6496. if (!labelContainer) {
  6497. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  6498. }
  6499. if (!labels) {
  6500. labels = document.createElement('div');
  6501. labels.className = 'labels';
  6502. this.dom.labels = labels;
  6503. }
  6504. if (!labelSet) {
  6505. labelSet = document.createElement('div');
  6506. labelSet.className = 'label-set';
  6507. labels.appendChild(labelSet);
  6508. this.dom.labelSet = labelSet;
  6509. }
  6510. if (!labels.parentNode || labels.parentNode != labelContainer) {
  6511. if (labels.parentNode) {
  6512. labels.parentNode.removeChild(labels.parentNode);
  6513. }
  6514. labelContainer.appendChild(labels);
  6515. }
  6516. // reposition frame
  6517. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  6518. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6519. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6520. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6521. // reposition labels
  6522. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  6523. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  6524. var me = this,
  6525. queue = this.queue,
  6526. groups = this.groups,
  6527. groupsData = this.groupsData;
  6528. // show/hide added/changed/removed groups
  6529. var ids = Object.keys(queue);
  6530. if (ids.length) {
  6531. ids.forEach(function (id) {
  6532. var action = queue[id];
  6533. var group = groups[id];
  6534. //noinspection FallthroughInSwitchStatementJS
  6535. switch (action) {
  6536. case 'add':
  6537. case 'update':
  6538. if (!group) {
  6539. var groupOptions = Object.create(me.options);
  6540. util.extend(groupOptions, {
  6541. height: null,
  6542. maxHeight: null
  6543. });
  6544. group = new Group(me, id, groupOptions);
  6545. group.setItems(me.itemsData); // attach items data
  6546. groups[id] = group;
  6547. me.controller.add(group);
  6548. }
  6549. // TODO: update group data
  6550. group.data = groupsData.get(id);
  6551. delete queue[id];
  6552. break;
  6553. case 'remove':
  6554. if (group) {
  6555. group.setItems(); // detach items data
  6556. delete groups[id];
  6557. me.controller.remove(group);
  6558. }
  6559. // update lists
  6560. delete queue[id];
  6561. break;
  6562. default:
  6563. console.log('Error: unknown action "' + action + '"');
  6564. }
  6565. });
  6566. // the groupset depends on each of the groups
  6567. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  6568. // TODO: apply dependencies of the groupset
  6569. // update the top positions of the groups in the correct order
  6570. var orderedGroups = this.groupsData.getIds({
  6571. order: this.options.groupOrder
  6572. });
  6573. for (i = 0; i < orderedGroups.length; i++) {
  6574. (function (group, prevGroup) {
  6575. var top = 0;
  6576. if (prevGroup) {
  6577. top = function () {
  6578. // TODO: top must reckon with options.maxHeight
  6579. return prevGroup.top + prevGroup.height;
  6580. }
  6581. }
  6582. group.setOptions({
  6583. top: top
  6584. });
  6585. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  6586. }
  6587. // (re)create the labels
  6588. while (labelSet.firstChild) {
  6589. labelSet.removeChild(labelSet.firstChild);
  6590. }
  6591. for (i = 0; i < orderedGroups.length; i++) {
  6592. id = orderedGroups[i];
  6593. label = this._createLabel(id);
  6594. labelSet.appendChild(label);
  6595. }
  6596. changed++;
  6597. }
  6598. // reposition the labels
  6599. // TODO: labels are not displayed correctly when orientation=='top'
  6600. // TODO: width of labelPanel is not immediately updated on a change in groups
  6601. for (id in groups) {
  6602. if (groups.hasOwnProperty(id)) {
  6603. group = groups[id];
  6604. label = group.label;
  6605. if (label) {
  6606. label.style.top = group.top + 'px';
  6607. label.style.height = group.height + 'px';
  6608. }
  6609. }
  6610. }
  6611. return (changed > 0);
  6612. };
  6613. /**
  6614. * Create a label for group with given id
  6615. * @param {Number} id
  6616. * @return {Element} label
  6617. * @private
  6618. */
  6619. GroupSet.prototype._createLabel = function(id) {
  6620. var group = this.groups[id];
  6621. var label = document.createElement('div');
  6622. label.className = 'vlabel';
  6623. var inner = document.createElement('div');
  6624. inner.className = 'inner';
  6625. label.appendChild(inner);
  6626. var content = group.data && group.data.content;
  6627. if (content instanceof Element) {
  6628. inner.appendChild(content);
  6629. }
  6630. else if (content != undefined) {
  6631. inner.innerHTML = content;
  6632. }
  6633. var className = group.data && group.data.className;
  6634. if (className) {
  6635. util.addClassName(label, className);
  6636. }
  6637. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  6638. return label;
  6639. };
  6640. /**
  6641. * Get container element
  6642. * @return {HTMLElement} container
  6643. */
  6644. GroupSet.prototype.getContainer = function getContainer() {
  6645. return this.dom.frame;
  6646. };
  6647. /**
  6648. * Get the width of the group labels
  6649. * @return {Number} width
  6650. */
  6651. GroupSet.prototype.getLabelsWidth = function getContainer() {
  6652. return this.props.labels.width;
  6653. };
  6654. /**
  6655. * Reflow the component
  6656. * @return {Boolean} resized
  6657. */
  6658. GroupSet.prototype.reflow = function reflow() {
  6659. var changed = 0,
  6660. id, group,
  6661. options = this.options,
  6662. update = util.updateProperty,
  6663. asNumber = util.option.asNumber,
  6664. asSize = util.option.asSize,
  6665. frame = this.dom.frame;
  6666. if (frame) {
  6667. var maxHeight = asNumber(options.maxHeight);
  6668. var fixedHeight = (asSize(options.height) != null);
  6669. var height;
  6670. if (fixedHeight) {
  6671. height = frame.offsetHeight;
  6672. }
  6673. else {
  6674. // height is not specified, calculate the sum of the height of all groups
  6675. height = 0;
  6676. for (id in this.groups) {
  6677. if (this.groups.hasOwnProperty(id)) {
  6678. group = this.groups[id];
  6679. height += group.height;
  6680. }
  6681. }
  6682. }
  6683. if (maxHeight != null) {
  6684. height = Math.min(height, maxHeight);
  6685. }
  6686. changed += update(this, 'height', height);
  6687. changed += update(this, 'top', frame.offsetTop);
  6688. changed += update(this, 'left', frame.offsetLeft);
  6689. changed += update(this, 'width', frame.offsetWidth);
  6690. }
  6691. // calculate the maximum width of the labels
  6692. var width = 0;
  6693. for (id in this.groups) {
  6694. if (this.groups.hasOwnProperty(id)) {
  6695. group = this.groups[id];
  6696. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  6697. width = Math.max(width, labelWidth);
  6698. }
  6699. }
  6700. changed += update(this.props.labels, 'width', width);
  6701. return (changed > 0);
  6702. };
  6703. /**
  6704. * Hide the component from the DOM
  6705. * @return {Boolean} changed
  6706. */
  6707. GroupSet.prototype.hide = function hide() {
  6708. if (this.dom.frame && this.dom.frame.parentNode) {
  6709. this.dom.frame.parentNode.removeChild(this.dom.frame);
  6710. return true;
  6711. }
  6712. else {
  6713. return false;
  6714. }
  6715. };
  6716. /**
  6717. * Show the component in the DOM (when not already visible).
  6718. * A repaint will be executed when the component is not visible
  6719. * @return {Boolean} changed
  6720. */
  6721. GroupSet.prototype.show = function show() {
  6722. if (!this.dom.frame || !this.dom.frame.parentNode) {
  6723. return this.repaint();
  6724. }
  6725. else {
  6726. return false;
  6727. }
  6728. };
  6729. /**
  6730. * Handle updated groups
  6731. * @param {Number[]} ids
  6732. * @private
  6733. */
  6734. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  6735. this._toQueue(ids, 'update');
  6736. };
  6737. /**
  6738. * Handle changed groups
  6739. * @param {Number[]} ids
  6740. * @private
  6741. */
  6742. GroupSet.prototype._onAdd = function _onAdd(ids) {
  6743. this._toQueue(ids, 'add');
  6744. };
  6745. /**
  6746. * Handle removed groups
  6747. * @param {Number[]} ids
  6748. * @private
  6749. */
  6750. GroupSet.prototype._onRemove = function _onRemove(ids) {
  6751. this._toQueue(ids, 'remove');
  6752. };
  6753. /**
  6754. * Put groups in the queue to be added/updated/remove
  6755. * @param {Number[]} ids
  6756. * @param {String} action can be 'add', 'update', 'remove'
  6757. */
  6758. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  6759. var queue = this.queue;
  6760. ids.forEach(function (id) {
  6761. queue[id] = action;
  6762. });
  6763. if (this.controller) {
  6764. //this.requestReflow();
  6765. this.requestRepaint();
  6766. }
  6767. };
  6768. /**
  6769. * Find the Group from an event target:
  6770. * searches for the attribute 'timeline-groupset' in the event target's element
  6771. * tree, then finds the right group in this groupset
  6772. * @param {Event} event
  6773. * @return {Group | null} group
  6774. */
  6775. GroupSet.groupFromTarget = function groupFromTarget (event) {
  6776. var groupset,
  6777. target = event.target;
  6778. while (target) {
  6779. if (target.hasOwnProperty('timeline-groupset')) {
  6780. groupset = target['timeline-groupset'];
  6781. break;
  6782. }
  6783. target = target.parentNode;
  6784. }
  6785. if (groupset) {
  6786. for (var groupId in groupset.groups) {
  6787. if (groupset.groups.hasOwnProperty(groupId)) {
  6788. var group = groupset.groups[groupId];
  6789. if (group.itemset && ItemSet.itemSetFromTarget(event) == group.itemset) {
  6790. return group;
  6791. }
  6792. }
  6793. }
  6794. }
  6795. return null;
  6796. };
  6797. /**
  6798. * Create a timeline visualization
  6799. * @param {HTMLElement} container
  6800. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6801. * @param {Object} [options] See Timeline.setOptions for the available options.
  6802. * @constructor
  6803. */
  6804. function Timeline (container, items, options) {
  6805. var me = this;
  6806. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6807. this.options = {
  6808. orientation: 'bottom',
  6809. autoResize: true,
  6810. editable: false,
  6811. selectable: true,
  6812. snap: null, // will be specified after timeaxis is created
  6813. min: null,
  6814. max: null,
  6815. zoomMin: 10, // milliseconds
  6816. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6817. // moveable: true, // TODO: option moveable
  6818. // zoomable: true, // TODO: option zoomable
  6819. showMinorLabels: true,
  6820. showMajorLabels: true,
  6821. showCurrentTime: false,
  6822. showCustomTime: false,
  6823. onAdd: function (item, callback) {
  6824. callback(item);
  6825. },
  6826. onUpdate: function (item, callback) {
  6827. callback(item);
  6828. },
  6829. onMove: function (item, callback) {
  6830. callback(item);
  6831. },
  6832. onRemove: function (item, callback) {
  6833. callback(item);
  6834. }
  6835. };
  6836. // controller
  6837. this.controller = new Controller();
  6838. // root panel
  6839. if (!container) {
  6840. throw new Error('No container element provided');
  6841. }
  6842. var rootOptions = Object.create(this.options);
  6843. rootOptions.height = function () {
  6844. // TODO: change to height
  6845. if (me.options.height) {
  6846. // fixed height
  6847. return me.options.height;
  6848. }
  6849. else {
  6850. // auto height
  6851. return (me.timeaxis.height + me.content.height) + 'px';
  6852. }
  6853. };
  6854. this.rootPanel = new RootPanel(container, rootOptions);
  6855. this.controller.add(this.rootPanel);
  6856. // single select (or unselect) when tapping an item
  6857. this.controller.on('tap', this._onSelectItem.bind(this));
  6858. // multi select when holding mouse/touch, or on ctrl+click
  6859. this.controller.on('hold', this._onMultiSelectItem.bind(this));
  6860. // add item on doubletap
  6861. this.controller.on('doubletap', this._onAddItem.bind(this));
  6862. // item panel
  6863. var itemOptions = Object.create(this.options);
  6864. itemOptions.left = function () {
  6865. return me.labelPanel.width;
  6866. };
  6867. itemOptions.width = function () {
  6868. return me.rootPanel.width - me.labelPanel.width;
  6869. };
  6870. itemOptions.top = null;
  6871. itemOptions.height = null;
  6872. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  6873. this.controller.add(this.itemPanel);
  6874. // label panel
  6875. var labelOptions = Object.create(this.options);
  6876. labelOptions.top = null;
  6877. labelOptions.left = null;
  6878. labelOptions.height = null;
  6879. labelOptions.width = function () {
  6880. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  6881. return me.content.getLabelsWidth();
  6882. }
  6883. else {
  6884. return 0;
  6885. }
  6886. };
  6887. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  6888. this.controller.add(this.labelPanel);
  6889. // range
  6890. var rangeOptions = Object.create(this.options);
  6891. this.range = new Range(rangeOptions);
  6892. this.range.setRange(
  6893. now.clone().add('days', -3).valueOf(),
  6894. now.clone().add('days', 4).valueOf()
  6895. );
  6896. this.range.subscribe(this.controller, this.rootPanel, 'move', 'horizontal');
  6897. this.range.subscribe(this.controller, this.rootPanel, 'zoom', 'horizontal');
  6898. this.range.on('rangechange', function (properties) {
  6899. var force = true;
  6900. me.controller.emit('rangechange', properties);
  6901. me.controller.emit('request-reflow', force);
  6902. });
  6903. this.range.on('rangechanged', function (properties) {
  6904. var force = true;
  6905. me.controller.emit('rangechanged', properties);
  6906. me.controller.emit('request-reflow', force);
  6907. });
  6908. // time axis
  6909. var timeaxisOptions = Object.create(rootOptions);
  6910. timeaxisOptions.range = this.range;
  6911. timeaxisOptions.left = null;
  6912. timeaxisOptions.top = null;
  6913. timeaxisOptions.width = '100%';
  6914. timeaxisOptions.height = null;
  6915. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6916. this.timeaxis.setRange(this.range);
  6917. this.controller.add(this.timeaxis);
  6918. this.options.snap = this.timeaxis.snap.bind(this.timeaxis);
  6919. // current time bar
  6920. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  6921. this.controller.add(this.currenttime);
  6922. // custom time bar
  6923. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  6924. this.controller.add(this.customtime);
  6925. // create groupset
  6926. this.setGroups(null);
  6927. this.itemsData = null; // DataSet
  6928. this.groupsData = null; // DataSet
  6929. // apply options
  6930. if (options) {
  6931. this.setOptions(options);
  6932. }
  6933. // create itemset and groupset
  6934. if (items) {
  6935. this.setItems(items);
  6936. }
  6937. }
  6938. /**
  6939. * Add an event listener to the timeline
  6940. * @param {String} event Available events: select, rangechange, rangechanged,
  6941. * timechange, timechanged
  6942. * @param {function} callback
  6943. */
  6944. Timeline.prototype.on = function on (event, callback) {
  6945. this.controller.on(event, callback);
  6946. };
  6947. /**
  6948. * Add an event listener from the timeline
  6949. * @param {String} event
  6950. * @param {function} callback
  6951. */
  6952. Timeline.prototype.off = function off (event, callback) {
  6953. this.controller.off(event, callback);
  6954. };
  6955. /**
  6956. * Set options
  6957. * @param {Object} options TODO: describe the available options
  6958. */
  6959. Timeline.prototype.setOptions = function (options) {
  6960. util.extend(this.options, options);
  6961. // force update of range (apply new min/max etc.)
  6962. // both start and end are optional
  6963. this.range.setRange(options.start, options.end);
  6964. if ('editable' in options || 'selectable' in options) {
  6965. if (this.options.selectable) {
  6966. // force update of selection
  6967. this.setSelection(this.getSelection());
  6968. }
  6969. else {
  6970. // remove selection
  6971. this.setSelection([]);
  6972. }
  6973. }
  6974. // validate the callback functions
  6975. var validateCallback = (function (fn) {
  6976. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  6977. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  6978. }
  6979. }).bind(this);
  6980. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  6981. this.controller.reflow();
  6982. this.controller.repaint();
  6983. };
  6984. /**
  6985. * Set a custom time bar
  6986. * @param {Date} time
  6987. */
  6988. Timeline.prototype.setCustomTime = function (time) {
  6989. if (!this.customtime) {
  6990. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  6991. }
  6992. this.customtime.setCustomTime(time);
  6993. };
  6994. /**
  6995. * Retrieve the current custom time.
  6996. * @return {Date} customTime
  6997. */
  6998. Timeline.prototype.getCustomTime = function() {
  6999. if (!this.customtime) {
  7000. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  7001. }
  7002. return this.customtime.getCustomTime();
  7003. };
  7004. /**
  7005. * Set items
  7006. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  7007. */
  7008. Timeline.prototype.setItems = function(items) {
  7009. var initialLoad = (this.itemsData == null);
  7010. // convert to type DataSet when needed
  7011. var newDataSet;
  7012. if (!items) {
  7013. newDataSet = null;
  7014. }
  7015. else if (items instanceof DataSet) {
  7016. newDataSet = items;
  7017. }
  7018. if (!(items instanceof DataSet)) {
  7019. newDataSet = new DataSet({
  7020. convert: {
  7021. start: 'Date',
  7022. end: 'Date'
  7023. }
  7024. });
  7025. newDataSet.add(items);
  7026. }
  7027. // set items
  7028. this.itemsData = newDataSet;
  7029. this.content.setItems(newDataSet);
  7030. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  7031. // apply the data range as range
  7032. var dataRange = this.getItemRange();
  7033. // add 5% space on both sides
  7034. var start = dataRange.min;
  7035. var end = dataRange.max;
  7036. if (start != null && end != null) {
  7037. var interval = (end.valueOf() - start.valueOf());
  7038. if (interval <= 0) {
  7039. // prevent an empty interval
  7040. interval = 24 * 60 * 60 * 1000; // 1 day
  7041. }
  7042. start = new Date(start.valueOf() - interval * 0.05);
  7043. end = new Date(end.valueOf() + interval * 0.05);
  7044. }
  7045. // override specified start and/or end date
  7046. if (this.options.start != undefined) {
  7047. start = util.convert(this.options.start, 'Date');
  7048. }
  7049. if (this.options.end != undefined) {
  7050. end = util.convert(this.options.end, 'Date');
  7051. }
  7052. // apply range if there is a min or max available
  7053. if (start != null || end != null) {
  7054. this.range.setRange(start, end);
  7055. }
  7056. }
  7057. };
  7058. /**
  7059. * Set groups
  7060. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  7061. */
  7062. Timeline.prototype.setGroups = function(groups) {
  7063. var me = this;
  7064. this.groupsData = groups;
  7065. // switch content type between ItemSet or GroupSet when needed
  7066. var Type = this.groupsData ? GroupSet : ItemSet;
  7067. if (!(this.content instanceof Type)) {
  7068. // remove old content set
  7069. if (this.content) {
  7070. this.content.hide();
  7071. if (this.content.setItems) {
  7072. this.content.setItems(); // disconnect from items
  7073. }
  7074. if (this.content.setGroups) {
  7075. this.content.setGroups(); // disconnect from groups
  7076. }
  7077. this.controller.remove(this.content);
  7078. }
  7079. // create new content set
  7080. var options = Object.create(this.options);
  7081. util.extend(options, {
  7082. top: function () {
  7083. if (me.options.orientation == 'top') {
  7084. return me.timeaxis.height;
  7085. }
  7086. else {
  7087. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  7088. }
  7089. },
  7090. left: null,
  7091. width: '100%',
  7092. height: function () {
  7093. if (me.options.height) {
  7094. // fixed height
  7095. return me.itemPanel.height - me.timeaxis.height;
  7096. }
  7097. else {
  7098. // auto height
  7099. return null;
  7100. }
  7101. },
  7102. maxHeight: function () {
  7103. // TODO: change maxHeight to be a css string like '100%' or '300px'
  7104. if (me.options.maxHeight) {
  7105. if (!util.isNumber(me.options.maxHeight)) {
  7106. throw new TypeError('Number expected for property maxHeight');
  7107. }
  7108. return me.options.maxHeight - me.timeaxis.height;
  7109. }
  7110. else {
  7111. return null;
  7112. }
  7113. },
  7114. labelContainer: function () {
  7115. return me.labelPanel.getContainer();
  7116. }
  7117. });
  7118. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  7119. if (this.content.setRange) {
  7120. this.content.setRange(this.range);
  7121. }
  7122. if (this.content.setItems) {
  7123. this.content.setItems(this.itemsData);
  7124. }
  7125. if (this.content.setGroups) {
  7126. this.content.setGroups(this.groupsData);
  7127. }
  7128. this.controller.add(this.content);
  7129. }
  7130. };
  7131. /**
  7132. * Get the data range of the item set.
  7133. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  7134. * When no minimum is found, min==null
  7135. * When no maximum is found, max==null
  7136. */
  7137. Timeline.prototype.getItemRange = function getItemRange() {
  7138. // calculate min from start filed
  7139. var itemsData = this.itemsData,
  7140. min = null,
  7141. max = null;
  7142. if (itemsData) {
  7143. // calculate the minimum value of the field 'start'
  7144. var minItem = itemsData.min('start');
  7145. min = minItem ? minItem.start.valueOf() : null;
  7146. // calculate maximum value of fields 'start' and 'end'
  7147. var maxStartItem = itemsData.max('start');
  7148. if (maxStartItem) {
  7149. max = maxStartItem.start.valueOf();
  7150. }
  7151. var maxEndItem = itemsData.max('end');
  7152. if (maxEndItem) {
  7153. if (max == null) {
  7154. max = maxEndItem.end.valueOf();
  7155. }
  7156. else {
  7157. max = Math.max(max, maxEndItem.end.valueOf());
  7158. }
  7159. }
  7160. }
  7161. return {
  7162. min: (min != null) ? new Date(min) : null,
  7163. max: (max != null) ? new Date(max) : null
  7164. };
  7165. };
  7166. /**
  7167. * Set selected items by their id. Replaces the current selection
  7168. * Unknown id's are silently ignored.
  7169. * @param {Array} [ids] An array with zero or more id's of the items to be
  7170. * selected. If ids is an empty array, all items will be
  7171. * unselected.
  7172. */
  7173. Timeline.prototype.setSelection = function setSelection (ids) {
  7174. if (this.content) this.content.setSelection(ids);
  7175. };
  7176. /**
  7177. * Get the selected items by their id
  7178. * @return {Array} ids The ids of the selected items
  7179. */
  7180. Timeline.prototype.getSelection = function getSelection() {
  7181. return this.content ? this.content.getSelection() : [];
  7182. };
  7183. /**
  7184. * Set the visible window. Both parameters are optional, you can change only
  7185. * start or only end.
  7186. * @param {Date | Number | String} [start] Start date of visible window
  7187. * @param {Date | Number | String} [end] End date of visible window
  7188. */
  7189. Timeline.prototype.setWindow = function setWindow(start, end) {
  7190. this.range.setRange(start, end);
  7191. };
  7192. /**
  7193. * Get the visible window
  7194. * @return {{start: Date, end: Date}} Visible range
  7195. */
  7196. Timeline.prototype.getWindow = function setWindow() {
  7197. var range = this.range.getRange();
  7198. return {
  7199. start: new Date(range.start),
  7200. end: new Date(range.end)
  7201. };
  7202. };
  7203. /**
  7204. * Handle selecting/deselecting an item when tapping it
  7205. * @param {Event} event
  7206. * @private
  7207. */
  7208. // TODO: move this function to ItemSet
  7209. Timeline.prototype._onSelectItem = function (event) {
  7210. if (!this.options.selectable) return;
  7211. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  7212. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  7213. if (ctrlKey || shiftKey) {
  7214. this._onMultiSelectItem(event);
  7215. return;
  7216. }
  7217. var item = ItemSet.itemFromTarget(event);
  7218. var selection = item ? [item.id] : [];
  7219. this.setSelection(selection);
  7220. this.controller.emit('select', {
  7221. items: this.getSelection()
  7222. });
  7223. event.stopPropagation();
  7224. };
  7225. /**
  7226. * Handle creation and updates of an item on double tap
  7227. * @param event
  7228. * @private
  7229. */
  7230. Timeline.prototype._onAddItem = function (event) {
  7231. if (!this.options.selectable) return;
  7232. if (!this.options.editable) return;
  7233. var me = this,
  7234. item = ItemSet.itemFromTarget(event);
  7235. if (item) {
  7236. // update item
  7237. // execute async handler to update the item (or cancel it)
  7238. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  7239. this.options.onUpdate(itemData, function (itemData) {
  7240. if (itemData) {
  7241. me.itemsData.update(itemData);
  7242. }
  7243. });
  7244. }
  7245. else {
  7246. // add item
  7247. var xAbs = vis.util.getAbsoluteLeft(this.rootPanel.frame);
  7248. var x = event.gesture.center.pageX - xAbs;
  7249. var newItem = {
  7250. start: this.timeaxis.snap(this._toTime(x)),
  7251. content: 'new item'
  7252. };
  7253. var id = util.randomUUID();
  7254. newItem[this.itemsData.fieldId] = id;
  7255. var group = GroupSet.groupFromTarget(event);
  7256. if (group) {
  7257. newItem.group = group.groupId;
  7258. }
  7259. // execute async handler to customize (or cancel) adding an item
  7260. this.options.onAdd(newItem, function (item) {
  7261. if (item) {
  7262. me.itemsData.add(newItem);
  7263. // select the created item after it is repainted
  7264. me.controller.once('repaint', function () {
  7265. me.setSelection([id]);
  7266. me.controller.emit('select', {
  7267. items: me.getSelection()
  7268. });
  7269. }.bind(me));
  7270. }
  7271. });
  7272. }
  7273. };
  7274. /**
  7275. * Handle selecting/deselecting multiple items when holding an item
  7276. * @param {Event} event
  7277. * @private
  7278. */
  7279. // TODO: move this function to ItemSet
  7280. Timeline.prototype._onMultiSelectItem = function (event) {
  7281. if (!this.options.selectable) return;
  7282. var selection,
  7283. item = ItemSet.itemFromTarget(event);
  7284. if (item) {
  7285. // multi select items
  7286. selection = this.getSelection(); // current selection
  7287. var index = selection.indexOf(item.id);
  7288. if (index == -1) {
  7289. // item is not yet selected -> select it
  7290. selection.push(item.id);
  7291. }
  7292. else {
  7293. // item is already selected -> deselect it
  7294. selection.splice(index, 1);
  7295. }
  7296. this.setSelection(selection);
  7297. this.controller.emit('select', {
  7298. items: this.getSelection()
  7299. });
  7300. event.stopPropagation();
  7301. }
  7302. };
  7303. /**
  7304. * Convert a position on screen (pixels) to a datetime
  7305. * @param {int} x Position on the screen in pixels
  7306. * @return {Date} time The datetime the corresponds with given position x
  7307. * @private
  7308. */
  7309. Timeline.prototype._toTime = function _toTime(x) {
  7310. var conversion = this.range.conversion(this.content.width);
  7311. return new Date(x / conversion.scale + conversion.offset);
  7312. };
  7313. /**
  7314. * Convert a datetime (Date object) into a position on the screen
  7315. * @param {Date} time A date
  7316. * @return {int} x The position on the screen in pixels which corresponds
  7317. * with the given date.
  7318. * @private
  7319. */
  7320. Timeline.prototype._toScreen = function _toScreen(time) {
  7321. var conversion = this.range.conversion(this.content.width);
  7322. return (time.valueOf() - conversion.offset) * conversion.scale;
  7323. };
  7324. (function(exports) {
  7325. /**
  7326. * Parse a text source containing data in DOT language into a JSON object.
  7327. * The object contains two lists: one with nodes and one with edges.
  7328. *
  7329. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  7330. *
  7331. * @param {String} data Text containing a graph in DOT-notation
  7332. * @return {Object} graph An object containing two parameters:
  7333. * {Object[]} nodes
  7334. * {Object[]} edges
  7335. */
  7336. function parseDOT (data) {
  7337. dot = data;
  7338. return parseGraph();
  7339. }
  7340. // token types enumeration
  7341. var TOKENTYPE = {
  7342. NULL : 0,
  7343. DELIMITER : 1,
  7344. IDENTIFIER: 2,
  7345. UNKNOWN : 3
  7346. };
  7347. // map with all delimiters
  7348. var DELIMITERS = {
  7349. '{': true,
  7350. '}': true,
  7351. '[': true,
  7352. ']': true,
  7353. ';': true,
  7354. '=': true,
  7355. ',': true,
  7356. '->': true,
  7357. '--': true
  7358. };
  7359. var dot = ''; // current dot file
  7360. var index = 0; // current index in dot file
  7361. var c = ''; // current token character in expr
  7362. var token = ''; // current token
  7363. var tokenType = TOKENTYPE.NULL; // type of the token
  7364. /**
  7365. * Get the first character from the dot file.
  7366. * The character is stored into the char c. If the end of the dot file is
  7367. * reached, the function puts an empty string in c.
  7368. */
  7369. function first() {
  7370. index = 0;
  7371. c = dot.charAt(0);
  7372. }
  7373. /**
  7374. * Get the next character from the dot file.
  7375. * The character is stored into the char c. If the end of the dot file is
  7376. * reached, the function puts an empty string in c.
  7377. */
  7378. function next() {
  7379. index++;
  7380. c = dot.charAt(index);
  7381. }
  7382. /**
  7383. * Preview the next character from the dot file.
  7384. * @return {String} cNext
  7385. */
  7386. function nextPreview() {
  7387. return dot.charAt(index + 1);
  7388. }
  7389. /**
  7390. * Test whether given character is alphabetic or numeric
  7391. * @param {String} c
  7392. * @return {Boolean} isAlphaNumeric
  7393. */
  7394. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  7395. function isAlphaNumeric(c) {
  7396. return regexAlphaNumeric.test(c);
  7397. }
  7398. /**
  7399. * Merge all properties of object b into object b
  7400. * @param {Object} a
  7401. * @param {Object} b
  7402. * @return {Object} a
  7403. */
  7404. function merge (a, b) {
  7405. if (!a) {
  7406. a = {};
  7407. }
  7408. if (b) {
  7409. for (var name in b) {
  7410. if (b.hasOwnProperty(name)) {
  7411. a[name] = b[name];
  7412. }
  7413. }
  7414. }
  7415. return a;
  7416. }
  7417. /**
  7418. * Set a value in an object, where the provided parameter name can be a
  7419. * path with nested parameters. For example:
  7420. *
  7421. * var obj = {a: 2};
  7422. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  7423. *
  7424. * @param {Object} obj
  7425. * @param {String} path A parameter name or dot-separated parameter path,
  7426. * like "color.highlight.border".
  7427. * @param {*} value
  7428. */
  7429. function setValue(obj, path, value) {
  7430. var keys = path.split('.');
  7431. var o = obj;
  7432. while (keys.length) {
  7433. var key = keys.shift();
  7434. if (keys.length) {
  7435. // this isn't the end point
  7436. if (!o[key]) {
  7437. o[key] = {};
  7438. }
  7439. o = o[key];
  7440. }
  7441. else {
  7442. // this is the end point
  7443. o[key] = value;
  7444. }
  7445. }
  7446. }
  7447. /**
  7448. * Add a node to a graph object. If there is already a node with
  7449. * the same id, their attributes will be merged.
  7450. * @param {Object} graph
  7451. * @param {Object} node
  7452. */
  7453. function addNode(graph, node) {
  7454. var i, len;
  7455. var current = null;
  7456. // find root graph (in case of subgraph)
  7457. var graphs = [graph]; // list with all graphs from current graph to root graph
  7458. var root = graph;
  7459. while (root.parent) {
  7460. graphs.push(root.parent);
  7461. root = root.parent;
  7462. }
  7463. // find existing node (at root level) by its id
  7464. if (root.nodes) {
  7465. for (i = 0, len = root.nodes.length; i < len; i++) {
  7466. if (node.id === root.nodes[i].id) {
  7467. current = root.nodes[i];
  7468. break;
  7469. }
  7470. }
  7471. }
  7472. if (!current) {
  7473. // this is a new node
  7474. current = {
  7475. id: node.id
  7476. };
  7477. if (graph.node) {
  7478. // clone default attributes
  7479. current.attr = merge(current.attr, graph.node);
  7480. }
  7481. }
  7482. // add node to this (sub)graph and all its parent graphs
  7483. for (i = graphs.length - 1; i >= 0; i--) {
  7484. var g = graphs[i];
  7485. if (!g.nodes) {
  7486. g.nodes = [];
  7487. }
  7488. if (g.nodes.indexOf(current) == -1) {
  7489. g.nodes.push(current);
  7490. }
  7491. }
  7492. // merge attributes
  7493. if (node.attr) {
  7494. current.attr = merge(current.attr, node.attr);
  7495. }
  7496. }
  7497. /**
  7498. * Add an edge to a graph object
  7499. * @param {Object} graph
  7500. * @param {Object} edge
  7501. */
  7502. function addEdge(graph, edge) {
  7503. if (!graph.edges) {
  7504. graph.edges = [];
  7505. }
  7506. graph.edges.push(edge);
  7507. if (graph.edge) {
  7508. var attr = merge({}, graph.edge); // clone default attributes
  7509. edge.attr = merge(attr, edge.attr); // merge attributes
  7510. }
  7511. }
  7512. /**
  7513. * Create an edge to a graph object
  7514. * @param {Object} graph
  7515. * @param {String | Number | Object} from
  7516. * @param {String | Number | Object} to
  7517. * @param {String} type
  7518. * @param {Object | null} attr
  7519. * @return {Object} edge
  7520. */
  7521. function createEdge(graph, from, to, type, attr) {
  7522. var edge = {
  7523. from: from,
  7524. to: to,
  7525. type: type
  7526. };
  7527. if (graph.edge) {
  7528. edge.attr = merge({}, graph.edge); // clone default attributes
  7529. }
  7530. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7531. return edge;
  7532. }
  7533. /**
  7534. * Get next token in the current dot file.
  7535. * The token and token type are available as token and tokenType
  7536. */
  7537. function getToken() {
  7538. tokenType = TOKENTYPE.NULL;
  7539. token = '';
  7540. // skip over whitespaces
  7541. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7542. next();
  7543. }
  7544. do {
  7545. var isComment = false;
  7546. // skip comment
  7547. if (c == '#') {
  7548. // find the previous non-space character
  7549. var i = index - 1;
  7550. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7551. i--;
  7552. }
  7553. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7554. // the # is at the start of a line, this is indeed a line comment
  7555. while (c != '' && c != '\n') {
  7556. next();
  7557. }
  7558. isComment = true;
  7559. }
  7560. }
  7561. if (c == '/' && nextPreview() == '/') {
  7562. // skip line comment
  7563. while (c != '' && c != '\n') {
  7564. next();
  7565. }
  7566. isComment = true;
  7567. }
  7568. if (c == '/' && nextPreview() == '*') {
  7569. // skip block comment
  7570. while (c != '') {
  7571. if (c == '*' && nextPreview() == '/') {
  7572. // end of block comment found. skip these last two characters
  7573. next();
  7574. next();
  7575. break;
  7576. }
  7577. else {
  7578. next();
  7579. }
  7580. }
  7581. isComment = true;
  7582. }
  7583. // skip over whitespaces
  7584. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7585. next();
  7586. }
  7587. }
  7588. while (isComment);
  7589. // check for end of dot file
  7590. if (c == '') {
  7591. // token is still empty
  7592. tokenType = TOKENTYPE.DELIMITER;
  7593. return;
  7594. }
  7595. // check for delimiters consisting of 2 characters
  7596. var c2 = c + nextPreview();
  7597. if (DELIMITERS[c2]) {
  7598. tokenType = TOKENTYPE.DELIMITER;
  7599. token = c2;
  7600. next();
  7601. next();
  7602. return;
  7603. }
  7604. // check for delimiters consisting of 1 character
  7605. if (DELIMITERS[c]) {
  7606. tokenType = TOKENTYPE.DELIMITER;
  7607. token = c;
  7608. next();
  7609. return;
  7610. }
  7611. // check for an identifier (number or string)
  7612. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7613. if (isAlphaNumeric(c) || c == '-') {
  7614. token += c;
  7615. next();
  7616. while (isAlphaNumeric(c)) {
  7617. token += c;
  7618. next();
  7619. }
  7620. if (token == 'false') {
  7621. token = false; // convert to boolean
  7622. }
  7623. else if (token == 'true') {
  7624. token = true; // convert to boolean
  7625. }
  7626. else if (!isNaN(Number(token))) {
  7627. token = Number(token); // convert to number
  7628. }
  7629. tokenType = TOKENTYPE.IDENTIFIER;
  7630. return;
  7631. }
  7632. // check for a string enclosed by double quotes
  7633. if (c == '"') {
  7634. next();
  7635. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7636. token += c;
  7637. if (c == '"') { // skip the escape character
  7638. next();
  7639. }
  7640. next();
  7641. }
  7642. if (c != '"') {
  7643. throw newSyntaxError('End of string " expected');
  7644. }
  7645. next();
  7646. tokenType = TOKENTYPE.IDENTIFIER;
  7647. return;
  7648. }
  7649. // something unknown is found, wrong characters, a syntax error
  7650. tokenType = TOKENTYPE.UNKNOWN;
  7651. while (c != '') {
  7652. token += c;
  7653. next();
  7654. }
  7655. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7656. }
  7657. /**
  7658. * Parse a graph.
  7659. * @returns {Object} graph
  7660. */
  7661. function parseGraph() {
  7662. var graph = {};
  7663. first();
  7664. getToken();
  7665. // optional strict keyword
  7666. if (token == 'strict') {
  7667. graph.strict = true;
  7668. getToken();
  7669. }
  7670. // graph or digraph keyword
  7671. if (token == 'graph' || token == 'digraph') {
  7672. graph.type = token;
  7673. getToken();
  7674. }
  7675. // optional graph id
  7676. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7677. graph.id = token;
  7678. getToken();
  7679. }
  7680. // open angle bracket
  7681. if (token != '{') {
  7682. throw newSyntaxError('Angle bracket { expected');
  7683. }
  7684. getToken();
  7685. // statements
  7686. parseStatements(graph);
  7687. // close angle bracket
  7688. if (token != '}') {
  7689. throw newSyntaxError('Angle bracket } expected');
  7690. }
  7691. getToken();
  7692. // end of file
  7693. if (token !== '') {
  7694. throw newSyntaxError('End of file expected');
  7695. }
  7696. getToken();
  7697. // remove temporary default properties
  7698. delete graph.node;
  7699. delete graph.edge;
  7700. delete graph.graph;
  7701. return graph;
  7702. }
  7703. /**
  7704. * Parse a list with statements.
  7705. * @param {Object} graph
  7706. */
  7707. function parseStatements (graph) {
  7708. while (token !== '' && token != '}') {
  7709. parseStatement(graph);
  7710. if (token == ';') {
  7711. getToken();
  7712. }
  7713. }
  7714. }
  7715. /**
  7716. * Parse a single statement. Can be a an attribute statement, node
  7717. * statement, a series of node statements and edge statements, or a
  7718. * parameter.
  7719. * @param {Object} graph
  7720. */
  7721. function parseStatement(graph) {
  7722. // parse subgraph
  7723. var subgraph = parseSubgraph(graph);
  7724. if (subgraph) {
  7725. // edge statements
  7726. parseEdge(graph, subgraph);
  7727. return;
  7728. }
  7729. // parse an attribute statement
  7730. var attr = parseAttributeStatement(graph);
  7731. if (attr) {
  7732. return;
  7733. }
  7734. // parse node
  7735. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7736. throw newSyntaxError('Identifier expected');
  7737. }
  7738. var id = token; // id can be a string or a number
  7739. getToken();
  7740. if (token == '=') {
  7741. // id statement
  7742. getToken();
  7743. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7744. throw newSyntaxError('Identifier expected');
  7745. }
  7746. graph[id] = token;
  7747. getToken();
  7748. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7749. }
  7750. else {
  7751. parseNodeStatement(graph, id);
  7752. }
  7753. }
  7754. /**
  7755. * Parse a subgraph
  7756. * @param {Object} graph parent graph object
  7757. * @return {Object | null} subgraph
  7758. */
  7759. function parseSubgraph (graph) {
  7760. var subgraph = null;
  7761. // optional subgraph keyword
  7762. if (token == 'subgraph') {
  7763. subgraph = {};
  7764. subgraph.type = 'subgraph';
  7765. getToken();
  7766. // optional graph id
  7767. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7768. subgraph.id = token;
  7769. getToken();
  7770. }
  7771. }
  7772. // open angle bracket
  7773. if (token == '{') {
  7774. getToken();
  7775. if (!subgraph) {
  7776. subgraph = {};
  7777. }
  7778. subgraph.parent = graph;
  7779. subgraph.node = graph.node;
  7780. subgraph.edge = graph.edge;
  7781. subgraph.graph = graph.graph;
  7782. // statements
  7783. parseStatements(subgraph);
  7784. // close angle bracket
  7785. if (token != '}') {
  7786. throw newSyntaxError('Angle bracket } expected');
  7787. }
  7788. getToken();
  7789. // remove temporary default properties
  7790. delete subgraph.node;
  7791. delete subgraph.edge;
  7792. delete subgraph.graph;
  7793. delete subgraph.parent;
  7794. // register at the parent graph
  7795. if (!graph.subgraphs) {
  7796. graph.subgraphs = [];
  7797. }
  7798. graph.subgraphs.push(subgraph);
  7799. }
  7800. return subgraph;
  7801. }
  7802. /**
  7803. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7804. * Available keywords are 'node', 'edge', 'graph'.
  7805. * The previous list with default attributes will be replaced
  7806. * @param {Object} graph
  7807. * @returns {String | null} keyword Returns the name of the parsed attribute
  7808. * (node, edge, graph), or null if nothing
  7809. * is parsed.
  7810. */
  7811. function parseAttributeStatement (graph) {
  7812. // attribute statements
  7813. if (token == 'node') {
  7814. getToken();
  7815. // node attributes
  7816. graph.node = parseAttributeList();
  7817. return 'node';
  7818. }
  7819. else if (token == 'edge') {
  7820. getToken();
  7821. // edge attributes
  7822. graph.edge = parseAttributeList();
  7823. return 'edge';
  7824. }
  7825. else if (token == 'graph') {
  7826. getToken();
  7827. // graph attributes
  7828. graph.graph = parseAttributeList();
  7829. return 'graph';
  7830. }
  7831. return null;
  7832. }
  7833. /**
  7834. * parse a node statement
  7835. * @param {Object} graph
  7836. * @param {String | Number} id
  7837. */
  7838. function parseNodeStatement(graph, id) {
  7839. // node statement
  7840. var node = {
  7841. id: id
  7842. };
  7843. var attr = parseAttributeList();
  7844. if (attr) {
  7845. node.attr = attr;
  7846. }
  7847. addNode(graph, node);
  7848. // edge statements
  7849. parseEdge(graph, id);
  7850. }
  7851. /**
  7852. * Parse an edge or a series of edges
  7853. * @param {Object} graph
  7854. * @param {String | Number} from Id of the from node
  7855. */
  7856. function parseEdge(graph, from) {
  7857. while (token == '->' || token == '--') {
  7858. var to;
  7859. var type = token;
  7860. getToken();
  7861. var subgraph = parseSubgraph(graph);
  7862. if (subgraph) {
  7863. to = subgraph;
  7864. }
  7865. else {
  7866. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7867. throw newSyntaxError('Identifier or subgraph expected');
  7868. }
  7869. to = token;
  7870. addNode(graph, {
  7871. id: to
  7872. });
  7873. getToken();
  7874. }
  7875. // parse edge attributes
  7876. var attr = parseAttributeList();
  7877. // create edge
  7878. var edge = createEdge(graph, from, to, type, attr);
  7879. addEdge(graph, edge);
  7880. from = to;
  7881. }
  7882. }
  7883. /**
  7884. * Parse a set with attributes,
  7885. * for example [label="1.000", shape=solid]
  7886. * @return {Object | null} attr
  7887. */
  7888. function parseAttributeList() {
  7889. var attr = null;
  7890. while (token == '[') {
  7891. getToken();
  7892. attr = {};
  7893. while (token !== '' && token != ']') {
  7894. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7895. throw newSyntaxError('Attribute name expected');
  7896. }
  7897. var name = token;
  7898. getToken();
  7899. if (token != '=') {
  7900. throw newSyntaxError('Equal sign = expected');
  7901. }
  7902. getToken();
  7903. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7904. throw newSyntaxError('Attribute value expected');
  7905. }
  7906. var value = token;
  7907. setValue(attr, name, value); // name can be a path
  7908. getToken();
  7909. if (token ==',') {
  7910. getToken();
  7911. }
  7912. }
  7913. if (token != ']') {
  7914. throw newSyntaxError('Bracket ] expected');
  7915. }
  7916. getToken();
  7917. }
  7918. return attr;
  7919. }
  7920. /**
  7921. * Create a syntax error with extra information on current token and index.
  7922. * @param {String} message
  7923. * @returns {SyntaxError} err
  7924. */
  7925. function newSyntaxError(message) {
  7926. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7927. }
  7928. /**
  7929. * Chop off text after a maximum length
  7930. * @param {String} text
  7931. * @param {Number} maxLength
  7932. * @returns {String}
  7933. */
  7934. function chop (text, maxLength) {
  7935. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  7936. }
  7937. /**
  7938. * Execute a function fn for each pair of elements in two arrays
  7939. * @param {Array | *} array1
  7940. * @param {Array | *} array2
  7941. * @param {function} fn
  7942. */
  7943. function forEach2(array1, array2, fn) {
  7944. if (array1 instanceof Array) {
  7945. array1.forEach(function (elem1) {
  7946. if (array2 instanceof Array) {
  7947. array2.forEach(function (elem2) {
  7948. fn(elem1, elem2);
  7949. });
  7950. }
  7951. else {
  7952. fn(elem1, array2);
  7953. }
  7954. });
  7955. }
  7956. else {
  7957. if (array2 instanceof Array) {
  7958. array2.forEach(function (elem2) {
  7959. fn(array1, elem2);
  7960. });
  7961. }
  7962. else {
  7963. fn(array1, array2);
  7964. }
  7965. }
  7966. }
  7967. /**
  7968. * Convert a string containing a graph in DOT language into a map containing
  7969. * with nodes and edges in the format of graph.
  7970. * @param {String} data Text containing a graph in DOT-notation
  7971. * @return {Object} graphData
  7972. */
  7973. function DOTToGraph (data) {
  7974. // parse the DOT file
  7975. var dotData = parseDOT(data);
  7976. var graphData = {
  7977. nodes: [],
  7978. edges: [],
  7979. options: {}
  7980. };
  7981. // copy the nodes
  7982. if (dotData.nodes) {
  7983. dotData.nodes.forEach(function (dotNode) {
  7984. var graphNode = {
  7985. id: dotNode.id,
  7986. label: String(dotNode.label || dotNode.id)
  7987. };
  7988. merge(graphNode, dotNode.attr);
  7989. if (graphNode.image) {
  7990. graphNode.shape = 'image';
  7991. }
  7992. graphData.nodes.push(graphNode);
  7993. });
  7994. }
  7995. // copy the edges
  7996. if (dotData.edges) {
  7997. /**
  7998. * Convert an edge in DOT format to an edge with VisGraph format
  7999. * @param {Object} dotEdge
  8000. * @returns {Object} graphEdge
  8001. */
  8002. function convertEdge(dotEdge) {
  8003. var graphEdge = {
  8004. from: dotEdge.from,
  8005. to: dotEdge.to
  8006. };
  8007. merge(graphEdge, dotEdge.attr);
  8008. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  8009. return graphEdge;
  8010. }
  8011. dotData.edges.forEach(function (dotEdge) {
  8012. var from, to;
  8013. if (dotEdge.from instanceof Object) {
  8014. from = dotEdge.from.nodes;
  8015. }
  8016. else {
  8017. from = {
  8018. id: dotEdge.from
  8019. }
  8020. }
  8021. if (dotEdge.to instanceof Object) {
  8022. to = dotEdge.to.nodes;
  8023. }
  8024. else {
  8025. to = {
  8026. id: dotEdge.to
  8027. }
  8028. }
  8029. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  8030. dotEdge.from.edges.forEach(function (subEdge) {
  8031. var graphEdge = convertEdge(subEdge);
  8032. graphData.edges.push(graphEdge);
  8033. });
  8034. }
  8035. forEach2(from, to, function (from, to) {
  8036. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  8037. var graphEdge = convertEdge(subEdge);
  8038. graphData.edges.push(graphEdge);
  8039. });
  8040. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  8041. dotEdge.to.edges.forEach(function (subEdge) {
  8042. var graphEdge = convertEdge(subEdge);
  8043. graphData.edges.push(graphEdge);
  8044. });
  8045. }
  8046. });
  8047. }
  8048. // copy the options
  8049. if (dotData.attr) {
  8050. graphData.options = dotData.attr;
  8051. }
  8052. return graphData;
  8053. }
  8054. // exports
  8055. exports.parseDOT = parseDOT;
  8056. exports.DOTToGraph = DOTToGraph;
  8057. })(typeof util !== 'undefined' ? util : exports);
  8058. /**
  8059. * Canvas shapes used by the Graph
  8060. */
  8061. if (typeof CanvasRenderingContext2D !== 'undefined') {
  8062. /**
  8063. * Draw a circle shape
  8064. */
  8065. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  8066. this.beginPath();
  8067. this.arc(x, y, r, 0, 2*Math.PI, false);
  8068. };
  8069. /**
  8070. * Draw a square shape
  8071. * @param {Number} x horizontal center
  8072. * @param {Number} y vertical center
  8073. * @param {Number} r size, width and height of the square
  8074. */
  8075. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  8076. this.beginPath();
  8077. this.rect(x - r, y - r, r * 2, r * 2);
  8078. };
  8079. /**
  8080. * Draw a triangle shape
  8081. * @param {Number} x horizontal center
  8082. * @param {Number} y vertical center
  8083. * @param {Number} r radius, half the length of the sides of the triangle
  8084. */
  8085. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  8086. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8087. this.beginPath();
  8088. var s = r * 2;
  8089. var s2 = s / 2;
  8090. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8091. var h = Math.sqrt(s * s - s2 * s2); // height
  8092. this.moveTo(x, y - (h - ir));
  8093. this.lineTo(x + s2, y + ir);
  8094. this.lineTo(x - s2, y + ir);
  8095. this.lineTo(x, y - (h - ir));
  8096. this.closePath();
  8097. };
  8098. /**
  8099. * Draw a triangle shape in downward orientation
  8100. * @param {Number} x horizontal center
  8101. * @param {Number} y vertical center
  8102. * @param {Number} r radius
  8103. */
  8104. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  8105. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8106. this.beginPath();
  8107. var s = r * 2;
  8108. var s2 = s / 2;
  8109. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8110. var h = Math.sqrt(s * s - s2 * s2); // height
  8111. this.moveTo(x, y + (h - ir));
  8112. this.lineTo(x + s2, y - ir);
  8113. this.lineTo(x - s2, y - ir);
  8114. this.lineTo(x, y + (h - ir));
  8115. this.closePath();
  8116. };
  8117. /**
  8118. * Draw a star shape, a star with 5 points
  8119. * @param {Number} x horizontal center
  8120. * @param {Number} y vertical center
  8121. * @param {Number} r radius, half the length of the sides of the triangle
  8122. */
  8123. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  8124. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  8125. this.beginPath();
  8126. for (var n = 0; n < 10; n++) {
  8127. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  8128. this.lineTo(
  8129. x + radius * Math.sin(n * 2 * Math.PI / 10),
  8130. y - radius * Math.cos(n * 2 * Math.PI / 10)
  8131. );
  8132. }
  8133. this.closePath();
  8134. };
  8135. /**
  8136. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  8137. */
  8138. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  8139. var r2d = Math.PI/180;
  8140. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  8141. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  8142. this.beginPath();
  8143. this.moveTo(x+r,y);
  8144. this.lineTo(x+w-r,y);
  8145. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  8146. this.lineTo(x+w,y+h-r);
  8147. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  8148. this.lineTo(x+r,y+h);
  8149. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  8150. this.lineTo(x,y+r);
  8151. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  8152. };
  8153. /**
  8154. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8155. */
  8156. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  8157. var kappa = .5522848,
  8158. ox = (w / 2) * kappa, // control point offset horizontal
  8159. oy = (h / 2) * kappa, // control point offset vertical
  8160. xe = x + w, // x-end
  8161. ye = y + h, // y-end
  8162. xm = x + w / 2, // x-middle
  8163. ym = y + h / 2; // y-middle
  8164. this.beginPath();
  8165. this.moveTo(x, ym);
  8166. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8167. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8168. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8169. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8170. };
  8171. /**
  8172. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8173. */
  8174. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  8175. var f = 1/3;
  8176. var wEllipse = w;
  8177. var hEllipse = h * f;
  8178. var kappa = .5522848,
  8179. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  8180. oy = (hEllipse / 2) * kappa, // control point offset vertical
  8181. xe = x + wEllipse, // x-end
  8182. ye = y + hEllipse, // y-end
  8183. xm = x + wEllipse / 2, // x-middle
  8184. ym = y + hEllipse / 2, // y-middle
  8185. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  8186. yeb = y + h; // y-end, bottom ellipse
  8187. this.beginPath();
  8188. this.moveTo(xe, ym);
  8189. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8190. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8191. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8192. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8193. this.lineTo(xe, ymb);
  8194. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  8195. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  8196. this.lineTo(x, ym);
  8197. };
  8198. /**
  8199. * Draw an arrow point (no line)
  8200. */
  8201. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  8202. // tail
  8203. var xt = x - length * Math.cos(angle);
  8204. var yt = y - length * Math.sin(angle);
  8205. // inner tail
  8206. // TODO: allow to customize different shapes
  8207. var xi = x - length * 0.9 * Math.cos(angle);
  8208. var yi = y - length * 0.9 * Math.sin(angle);
  8209. // left
  8210. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  8211. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  8212. // right
  8213. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  8214. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  8215. this.beginPath();
  8216. this.moveTo(x, y);
  8217. this.lineTo(xl, yl);
  8218. this.lineTo(xi, yi);
  8219. this.lineTo(xr, yr);
  8220. this.closePath();
  8221. };
  8222. /**
  8223. * Sets up the dashedLine functionality for drawing
  8224. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  8225. * @author David Jordan
  8226. * @date 2012-08-08
  8227. */
  8228. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  8229. if (!dashArray) dashArray=[10,5];
  8230. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  8231. var dashCount = dashArray.length;
  8232. this.moveTo(x, y);
  8233. var dx = (x2-x), dy = (y2-y);
  8234. var slope = dy/dx;
  8235. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  8236. var dashIndex=0, draw=true;
  8237. while (distRemaining>=0.1){
  8238. var dashLength = dashArray[dashIndex++%dashCount];
  8239. if (dashLength > distRemaining) dashLength = distRemaining;
  8240. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  8241. if (dx<0) xStep = -xStep;
  8242. x += xStep;
  8243. y += slope*xStep;
  8244. this[draw ? 'lineTo' : 'moveTo'](x,y);
  8245. distRemaining -= dashLength;
  8246. draw = !draw;
  8247. }
  8248. };
  8249. // TODO: add diamond shape
  8250. }
  8251. /**
  8252. * @class Node
  8253. * A node. A node can be connected to other nodes via one or multiple edges.
  8254. * @param {object} properties An object containing properties for the node. All
  8255. * properties are optional, except for the id.
  8256. * {number} id Id of the node. Required
  8257. * {string} label Text label for the node
  8258. * {number} x Horizontal position of the node
  8259. * {number} y Vertical position of the node
  8260. * {string} shape Node shape, available:
  8261. * "database", "circle", "ellipse",
  8262. * "box", "image", "text", "dot",
  8263. * "star", "triangle", "triangleDown",
  8264. * "square"
  8265. * {string} image An image url
  8266. * {string} title An title text, can be HTML
  8267. * {anytype} group A group name or number
  8268. * @param {Graph.Images} imagelist A list with images. Only needed
  8269. * when the node has an image
  8270. * @param {Graph.Groups} grouplist A list with groups. Needed for
  8271. * retrieving group properties
  8272. * @param {Object} constants An object with default values for
  8273. * example for the color
  8274. *
  8275. */
  8276. function Node(properties, imagelist, grouplist, constants) {
  8277. this.selected = false;
  8278. this.edges = []; // all edges connected to this node
  8279. this.dynamicEdges = [];
  8280. this.reroutedEdges = {};
  8281. this.group = constants.nodes.group;
  8282. this.fontSize = constants.nodes.fontSize;
  8283. this.fontFace = constants.nodes.fontFace;
  8284. this.fontColor = constants.nodes.fontColor;
  8285. this.fontDrawThreshold = 3;
  8286. this.color = constants.nodes.color;
  8287. // set defaults for the properties
  8288. this.id = undefined;
  8289. this.shape = constants.nodes.shape;
  8290. this.image = constants.nodes.image;
  8291. this.x = 0;
  8292. this.y = 0;
  8293. this.xFixed = false;
  8294. this.yFixed = false;
  8295. this.horizontalAlignLeft = true; // these are for the navigation controls
  8296. this.verticalAlignTop = true; // these are for the navigation controls
  8297. this.radius = constants.nodes.radius;
  8298. this.baseRadiusValue = constants.nodes.radius;
  8299. this.radiusFixed = false;
  8300. this.radiusMin = constants.nodes.radiusMin;
  8301. this.radiusMax = constants.nodes.radiusMax;
  8302. this.level = -1;
  8303. this.imagelist = imagelist;
  8304. this.grouplist = grouplist;
  8305. // physics properties
  8306. this.fx = 0.0; // external force x
  8307. this.fy = 0.0; // external force y
  8308. this.vx = 0.0; // velocity x
  8309. this.vy = 0.0; // velocity y
  8310. this.minForce = constants.minForce;
  8311. this.damping = constants.physics.damping;
  8312. this.mass = 1; // kg
  8313. this.setProperties(properties, constants);
  8314. // creating the variables for clustering
  8315. this.resetCluster();
  8316. this.dynamicEdgesLength = 0;
  8317. this.clusterSession = 0;
  8318. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  8319. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  8320. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  8321. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  8322. this.growthIndicator = 0;
  8323. // variables to tell the node about the graph.
  8324. this.graphScaleInv = 1;
  8325. this.graphScale = 1;
  8326. this.canvasTopLeft = {"x": -300, "y": -300};
  8327. this.canvasBottomRight = {"x": 300, "y": 300};
  8328. this.parentEdgeId = null;
  8329. }
  8330. /**
  8331. * (re)setting the clustering variables and objects
  8332. */
  8333. Node.prototype.resetCluster = function() {
  8334. // clustering variables
  8335. this.formationScale = undefined; // this is used to determine when to open the cluster
  8336. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  8337. this.containedNodes = {};
  8338. this.containedEdges = {};
  8339. this.clusterSessions = [];
  8340. };
  8341. /**
  8342. * Attach a edge to the node
  8343. * @param {Edge} edge
  8344. */
  8345. Node.prototype.attachEdge = function(edge) {
  8346. if (this.edges.indexOf(edge) == -1) {
  8347. this.edges.push(edge);
  8348. }
  8349. if (this.dynamicEdges.indexOf(edge) == -1) {
  8350. this.dynamicEdges.push(edge);
  8351. }
  8352. this.dynamicEdgesLength = this.dynamicEdges.length;
  8353. };
  8354. /**
  8355. * Detach a edge from the node
  8356. * @param {Edge} edge
  8357. */
  8358. Node.prototype.detachEdge = function(edge) {
  8359. var index = this.edges.indexOf(edge);
  8360. if (index != -1) {
  8361. this.edges.splice(index, 1);
  8362. this.dynamicEdges.splice(index, 1);
  8363. }
  8364. this.dynamicEdgesLength = this.dynamicEdges.length;
  8365. };
  8366. /**
  8367. * Set or overwrite properties for the node
  8368. * @param {Object} properties an object with properties
  8369. * @param {Object} constants and object with default, global properties
  8370. */
  8371. Node.prototype.setProperties = function(properties, constants) {
  8372. if (!properties) {
  8373. return;
  8374. }
  8375. this.originalLabel = undefined;
  8376. // basic properties
  8377. if (properties.id !== undefined) {this.id = properties.id;}
  8378. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  8379. if (properties.title !== undefined) {this.title = properties.title;}
  8380. if (properties.group !== undefined) {this.group = properties.group;}
  8381. if (properties.x !== undefined) {this.x = properties.x;}
  8382. if (properties.y !== undefined) {this.y = properties.y;}
  8383. if (properties.value !== undefined) {this.value = properties.value;}
  8384. if (properties.level !== undefined) {this.level = properties.level;}
  8385. // physics
  8386. if (properties.internalMultiplier !== undefined) {this.internalMultiplier = properties.internalMultiplier;}
  8387. if (properties.damping !== undefined) {this.dampingBase = properties.damping;}
  8388. if (properties.mass !== undefined) {this.mass = properties.mass;}
  8389. // navigation controls properties
  8390. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  8391. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  8392. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  8393. if (this.id === undefined) {
  8394. throw "Node must have an id";
  8395. }
  8396. // copy group properties
  8397. if (this.group) {
  8398. var groupObj = this.grouplist.get(this.group);
  8399. for (var prop in groupObj) {
  8400. if (groupObj.hasOwnProperty(prop)) {
  8401. this[prop] = groupObj[prop];
  8402. }
  8403. }
  8404. }
  8405. // individual shape properties
  8406. if (properties.shape !== undefined) {this.shape = properties.shape;}
  8407. if (properties.image !== undefined) {this.image = properties.image;}
  8408. if (properties.radius !== undefined) {this.radius = properties.radius;}
  8409. if (properties.color !== undefined) {this.color = Node.parseColor(properties.color);}
  8410. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8411. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8412. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8413. if (this.image !== undefined) {
  8414. if (this.imagelist) {
  8415. this.imageObj = this.imagelist.load(this.image);
  8416. }
  8417. else {
  8418. throw "No imagelist provided";
  8419. }
  8420. }
  8421. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMove);
  8422. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMove);
  8423. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  8424. if (this.shape == 'image') {
  8425. this.radiusMin = constants.nodes.widthMin;
  8426. this.radiusMax = constants.nodes.widthMax;
  8427. }
  8428. // choose draw method depending on the shape
  8429. switch (this.shape) {
  8430. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  8431. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  8432. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  8433. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8434. // TODO: add diamond shape
  8435. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  8436. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  8437. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  8438. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  8439. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  8440. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  8441. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  8442. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8443. }
  8444. // reset the size of the node, this can be changed
  8445. this._reset();
  8446. };
  8447. /**
  8448. * Parse a color property into an object with border, background, and
  8449. * hightlight colors
  8450. * @param {Object | String} color
  8451. * @return {Object} colorObject
  8452. */
  8453. Node.parseColor = function(color) {
  8454. var c;
  8455. if (util.isString(color)) {
  8456. if (util.isValidHex(color)) {
  8457. var hsv = util.hexToHSV(color);
  8458. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  8459. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  8460. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  8461. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  8462. c = {
  8463. background: color,
  8464. border:darkerColorHex,
  8465. highlight: {
  8466. background:lighterColorHex,
  8467. border:darkerColorHex
  8468. }
  8469. };
  8470. }
  8471. else {
  8472. c = {
  8473. background:color,
  8474. border:color,
  8475. highlight: {
  8476. background:color,
  8477. border:color
  8478. }
  8479. };
  8480. }
  8481. }
  8482. else {
  8483. c = {};
  8484. c.background = color.background || 'white';
  8485. c.border = color.border || c.background;
  8486. if (util.isString(color.highlight)) {
  8487. c.highlight = {
  8488. border: color.highlight,
  8489. background: color.highlight
  8490. }
  8491. }
  8492. else {
  8493. c.highlight = {};
  8494. c.highlight.background = color.highlight && color.highlight.background || c.background;
  8495. c.highlight.border = color.highlight && color.highlight.border || c.border;
  8496. }
  8497. }
  8498. return c;
  8499. };
  8500. /**
  8501. * select this node
  8502. */
  8503. Node.prototype.select = function() {
  8504. this.selected = true;
  8505. this._reset();
  8506. };
  8507. /**
  8508. * unselect this node
  8509. */
  8510. Node.prototype.unselect = function() {
  8511. this.selected = false;
  8512. this._reset();
  8513. };
  8514. /**
  8515. * Reset the calculated size of the node, forces it to recalculate its size
  8516. */
  8517. Node.prototype.clearSizeCache = function() {
  8518. this._reset();
  8519. };
  8520. /**
  8521. * Reset the calculated size of the node, forces it to recalculate its size
  8522. * @private
  8523. */
  8524. Node.prototype._reset = function() {
  8525. this.width = undefined;
  8526. this.height = undefined;
  8527. };
  8528. /**
  8529. * get the title of this node.
  8530. * @return {string} title The title of the node, or undefined when no title
  8531. * has been set.
  8532. */
  8533. Node.prototype.getTitle = function() {
  8534. return this.title;
  8535. };
  8536. /**
  8537. * Calculate the distance to the border of the Node
  8538. * @param {CanvasRenderingContext2D} ctx
  8539. * @param {Number} angle Angle in radians
  8540. * @returns {number} distance Distance to the border in pixels
  8541. */
  8542. Node.prototype.distanceToBorder = function (ctx, angle) {
  8543. var borderWidth = 1;
  8544. if (!this.width) {
  8545. this.resize(ctx);
  8546. }
  8547. switch (this.shape) {
  8548. case 'circle':
  8549. case 'dot':
  8550. return this.radius + borderWidth;
  8551. case 'ellipse':
  8552. var a = this.width / 2;
  8553. var b = this.height / 2;
  8554. var w = (Math.sin(angle) * a);
  8555. var h = (Math.cos(angle) * b);
  8556. return a * b / Math.sqrt(w * w + h * h);
  8557. // TODO: implement distanceToBorder for database
  8558. // TODO: implement distanceToBorder for triangle
  8559. // TODO: implement distanceToBorder for triangleDown
  8560. case 'box':
  8561. case 'image':
  8562. case 'text':
  8563. default:
  8564. if (this.width) {
  8565. return Math.min(
  8566. Math.abs(this.width / 2 / Math.cos(angle)),
  8567. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8568. // TODO: reckon with border radius too in case of box
  8569. }
  8570. else {
  8571. return 0;
  8572. }
  8573. }
  8574. // TODO: implement calculation of distance to border for all shapes
  8575. };
  8576. /**
  8577. * Set forces acting on the node
  8578. * @param {number} fx Force in horizontal direction
  8579. * @param {number} fy Force in vertical direction
  8580. */
  8581. Node.prototype._setForce = function(fx, fy) {
  8582. this.fx = fx;
  8583. this.fy = fy;
  8584. };
  8585. /**
  8586. * Add forces acting on the node
  8587. * @param {number} fx Force in horizontal direction
  8588. * @param {number} fy Force in vertical direction
  8589. * @private
  8590. */
  8591. Node.prototype._addForce = function(fx, fy) {
  8592. this.fx += fx;
  8593. this.fy += fy;
  8594. };
  8595. /**
  8596. * Perform one discrete step for the node
  8597. * @param {number} interval Time interval in seconds
  8598. */
  8599. Node.prototype.discreteStep = function(interval) {
  8600. if (!this.xFixed) {
  8601. var dx = this.damping * this.vx; // damping force
  8602. var ax = (this.fx - dx) / this.mass; // acceleration
  8603. this.vx += ax * interval; // velocity
  8604. this.x += this.vx * interval; // position
  8605. }
  8606. if (!this.yFixed) {
  8607. var dy = this.damping * this.vy; // damping force
  8608. var ay = (this.fy - dy) / this.mass; // acceleration
  8609. this.vy += ay * interval; // velocity
  8610. this.y += this.vy * interval; // position
  8611. }
  8612. };
  8613. /**
  8614. * Perform one discrete step for the node
  8615. * @param {number} interval Time interval in seconds
  8616. */
  8617. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8618. if (!this.xFixed) {
  8619. var dx = this.damping * this.vx; // damping force
  8620. var ax = (this.fx - dx) / this.mass; // acceleration
  8621. this.vx += ax * interval; // velocity
  8622. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8623. this.x += this.vx * interval; // position
  8624. }
  8625. if (!this.yFixed) {
  8626. var dy = this.damping * this.vy; // damping force
  8627. var ay = (this.fy - dy) / this.mass; // acceleration
  8628. this.vy += ay * interval; // velocity
  8629. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8630. this.y += this.vy * interval; // position
  8631. }
  8632. };
  8633. /**
  8634. * Check if this node has a fixed x and y position
  8635. * @return {boolean} true if fixed, false if not
  8636. */
  8637. Node.prototype.isFixed = function() {
  8638. return (this.xFixed && this.yFixed);
  8639. };
  8640. /**
  8641. * Check if this node is moving
  8642. * @param {number} vmin the minimum velocity considered as "moving"
  8643. * @return {boolean} true if moving, false if it has no velocity
  8644. */
  8645. // TODO: replace this method with calculating the kinetic energy
  8646. Node.prototype.isMoving = function(vmin) {
  8647. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8648. };
  8649. /**
  8650. * check if this node is selecte
  8651. * @return {boolean} selected True if node is selected, else false
  8652. */
  8653. Node.prototype.isSelected = function() {
  8654. return this.selected;
  8655. };
  8656. /**
  8657. * Retrieve the value of the node. Can be undefined
  8658. * @return {Number} value
  8659. */
  8660. Node.prototype.getValue = function() {
  8661. return this.value;
  8662. };
  8663. /**
  8664. * Calculate the distance from the nodes location to the given location (x,y)
  8665. * @param {Number} x
  8666. * @param {Number} y
  8667. * @return {Number} value
  8668. */
  8669. Node.prototype.getDistance = function(x, y) {
  8670. var dx = this.x - x,
  8671. dy = this.y - y;
  8672. return Math.sqrt(dx * dx + dy * dy);
  8673. };
  8674. /**
  8675. * Adjust the value range of the node. The node will adjust it's radius
  8676. * based on its value.
  8677. * @param {Number} min
  8678. * @param {Number} max
  8679. */
  8680. Node.prototype.setValueRange = function(min, max) {
  8681. if (!this.radiusFixed && this.value !== undefined) {
  8682. if (max == min) {
  8683. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8684. }
  8685. else {
  8686. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8687. this.radius = (this.value - min) * scale + this.radiusMin;
  8688. }
  8689. }
  8690. this.baseRadiusValue = this.radius;
  8691. };
  8692. /**
  8693. * Draw this node in the given canvas
  8694. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8695. * @param {CanvasRenderingContext2D} ctx
  8696. */
  8697. Node.prototype.draw = function(ctx) {
  8698. throw "Draw method not initialized for node";
  8699. };
  8700. /**
  8701. * Recalculate the size of this node in the given canvas
  8702. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8703. * @param {CanvasRenderingContext2D} ctx
  8704. */
  8705. Node.prototype.resize = function(ctx) {
  8706. throw "Resize method not initialized for node";
  8707. };
  8708. /**
  8709. * Check if this object is overlapping with the provided object
  8710. * @param {Object} obj an object with parameters left, top, right, bottom
  8711. * @return {boolean} True if location is located on node
  8712. */
  8713. Node.prototype.isOverlappingWith = function(obj) {
  8714. return (this.left < obj.right &&
  8715. this.left + this.width > obj.left &&
  8716. this.top < obj.bottom &&
  8717. this.top + this.height > obj.top);
  8718. };
  8719. Node.prototype._resizeImage = function (ctx) {
  8720. // TODO: pre calculate the image size
  8721. if (!this.width || !this.height) { // undefined or 0
  8722. var width, height;
  8723. if (this.value) {
  8724. this.radius = this.baseRadiusValue;
  8725. var scale = this.imageObj.height / this.imageObj.width;
  8726. if (scale !== undefined) {
  8727. width = this.radius || this.imageObj.width;
  8728. height = this.radius * scale || this.imageObj.height;
  8729. }
  8730. else {
  8731. width = 0;
  8732. height = 0;
  8733. }
  8734. }
  8735. else {
  8736. width = this.imageObj.width;
  8737. height = this.imageObj.height;
  8738. }
  8739. this.width = width;
  8740. this.height = height;
  8741. this.growthIndicator = 0;
  8742. if (this.width > 0 && this.height > 0) {
  8743. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8744. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8745. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8746. this.growthIndicator = this.width - width;
  8747. }
  8748. }
  8749. };
  8750. Node.prototype._drawImage = function (ctx) {
  8751. this._resizeImage(ctx);
  8752. this.left = this.x - this.width / 2;
  8753. this.top = this.y - this.height / 2;
  8754. var yLabel;
  8755. if (this.imageObj.width != 0 ) {
  8756. // draw the shade
  8757. if (this.clusterSize > 1) {
  8758. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8759. lineWidth *= this.graphScaleInv;
  8760. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8761. ctx.globalAlpha = 0.5;
  8762. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8763. }
  8764. // draw the image
  8765. ctx.globalAlpha = 1.0;
  8766. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8767. yLabel = this.y + this.height / 2;
  8768. }
  8769. else {
  8770. // image still loading... just draw the label for now
  8771. yLabel = this.y;
  8772. }
  8773. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8774. };
  8775. Node.prototype._resizeBox = function (ctx) {
  8776. if (!this.width) {
  8777. var margin = 5;
  8778. var textSize = this.getTextSize(ctx);
  8779. this.width = textSize.width + 2 * margin;
  8780. this.height = textSize.height + 2 * margin;
  8781. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8782. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8783. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8784. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8785. }
  8786. };
  8787. Node.prototype._drawBox = function (ctx) {
  8788. this._resizeBox(ctx);
  8789. this.left = this.x - this.width / 2;
  8790. this.top = this.y - this.height / 2;
  8791. var clusterLineWidth = 2.5;
  8792. var selectionLineWidth = 2;
  8793. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8794. // draw the outer border
  8795. if (this.clusterSize > 1) {
  8796. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8797. ctx.lineWidth *= this.graphScaleInv;
  8798. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8799. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8800. ctx.stroke();
  8801. }
  8802. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8803. ctx.lineWidth *= this.graphScaleInv;
  8804. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8805. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8806. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8807. ctx.fill();
  8808. ctx.stroke();
  8809. this._label(ctx, this.label, this.x, this.y);
  8810. };
  8811. Node.prototype._resizeDatabase = function (ctx) {
  8812. if (!this.width) {
  8813. var margin = 5;
  8814. var textSize = this.getTextSize(ctx);
  8815. var size = textSize.width + 2 * margin;
  8816. this.width = size;
  8817. this.height = size;
  8818. // scaling used for clustering
  8819. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8820. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8821. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8822. this.growthIndicator = this.width - size;
  8823. }
  8824. };
  8825. Node.prototype._drawDatabase = function (ctx) {
  8826. this._resizeDatabase(ctx);
  8827. this.left = this.x - this.width / 2;
  8828. this.top = this.y - this.height / 2;
  8829. var clusterLineWidth = 2.5;
  8830. var selectionLineWidth = 2;
  8831. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8832. // draw the outer border
  8833. if (this.clusterSize > 1) {
  8834. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8835. ctx.lineWidth *= this.graphScaleInv;
  8836. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8837. 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);
  8838. ctx.stroke();
  8839. }
  8840. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8841. ctx.lineWidth *= this.graphScaleInv;
  8842. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8843. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8844. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8845. ctx.fill();
  8846. ctx.stroke();
  8847. this._label(ctx, this.label, this.x, this.y);
  8848. };
  8849. Node.prototype._resizeCircle = function (ctx) {
  8850. if (!this.width) {
  8851. var margin = 5;
  8852. var textSize = this.getTextSize(ctx);
  8853. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8854. this.radius = diameter / 2;
  8855. this.width = diameter;
  8856. this.height = diameter;
  8857. // scaling used for clustering
  8858. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8859. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8860. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8861. this.growthIndicator = this.radius - 0.5*diameter;
  8862. }
  8863. };
  8864. Node.prototype._drawCircle = function (ctx) {
  8865. this._resizeCircle(ctx);
  8866. this.left = this.x - this.width / 2;
  8867. this.top = this.y - this.height / 2;
  8868. var clusterLineWidth = 2.5;
  8869. var selectionLineWidth = 2;
  8870. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8871. // draw the outer border
  8872. if (this.clusterSize > 1) {
  8873. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8874. ctx.lineWidth *= this.graphScaleInv;
  8875. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8876. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8877. ctx.stroke();
  8878. }
  8879. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8880. ctx.lineWidth *= this.graphScaleInv;
  8881. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8882. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8883. ctx.circle(this.x, this.y, this.radius);
  8884. ctx.fill();
  8885. ctx.stroke();
  8886. this._label(ctx, this.label, this.x, this.y);
  8887. };
  8888. Node.prototype._resizeEllipse = function (ctx) {
  8889. if (!this.width) {
  8890. var textSize = this.getTextSize(ctx);
  8891. this.width = textSize.width * 1.5;
  8892. this.height = textSize.height * 2;
  8893. if (this.width < this.height) {
  8894. this.width = this.height;
  8895. }
  8896. var defaultSize = this.width;
  8897. // scaling used for clustering
  8898. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8899. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8900. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8901. this.growthIndicator = this.width - defaultSize;
  8902. }
  8903. };
  8904. Node.prototype._drawEllipse = function (ctx) {
  8905. this._resizeEllipse(ctx);
  8906. this.left = this.x - this.width / 2;
  8907. this.top = this.y - this.height / 2;
  8908. var clusterLineWidth = 2.5;
  8909. var selectionLineWidth = 2;
  8910. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8911. // draw the outer border
  8912. if (this.clusterSize > 1) {
  8913. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8914. ctx.lineWidth *= this.graphScaleInv;
  8915. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8916. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8917. ctx.stroke();
  8918. }
  8919. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8920. ctx.lineWidth *= this.graphScaleInv;
  8921. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8922. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8923. ctx.ellipse(this.left, this.top, this.width, this.height);
  8924. ctx.fill();
  8925. ctx.stroke();
  8926. this._label(ctx, this.label, this.x, this.y);
  8927. };
  8928. Node.prototype._drawDot = function (ctx) {
  8929. this._drawShape(ctx, 'circle');
  8930. };
  8931. Node.prototype._drawTriangle = function (ctx) {
  8932. this._drawShape(ctx, 'triangle');
  8933. };
  8934. Node.prototype._drawTriangleDown = function (ctx) {
  8935. this._drawShape(ctx, 'triangleDown');
  8936. };
  8937. Node.prototype._drawSquare = function (ctx) {
  8938. this._drawShape(ctx, 'square');
  8939. };
  8940. Node.prototype._drawStar = function (ctx) {
  8941. this._drawShape(ctx, 'star');
  8942. };
  8943. Node.prototype._resizeShape = function (ctx) {
  8944. if (!this.width) {
  8945. this.radius = this.baseRadiusValue;
  8946. var size = 2 * this.radius;
  8947. this.width = size;
  8948. this.height = size;
  8949. // scaling used for clustering
  8950. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8951. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8952. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8953. this.growthIndicator = this.width - size;
  8954. }
  8955. };
  8956. Node.prototype._drawShape = function (ctx, shape) {
  8957. this._resizeShape(ctx);
  8958. this.left = this.x - this.width / 2;
  8959. this.top = this.y - this.height / 2;
  8960. var clusterLineWidth = 2.5;
  8961. var selectionLineWidth = 2;
  8962. var radiusMultiplier = 2;
  8963. // choose draw method depending on the shape
  8964. switch (shape) {
  8965. case 'dot': radiusMultiplier = 2; break;
  8966. case 'square': radiusMultiplier = 2; break;
  8967. case 'triangle': radiusMultiplier = 3; break;
  8968. case 'triangleDown': radiusMultiplier = 3; break;
  8969. case 'star': radiusMultiplier = 4; break;
  8970. }
  8971. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8972. // draw the outer border
  8973. if (this.clusterSize > 1) {
  8974. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8975. ctx.lineWidth *= this.graphScaleInv;
  8976. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8977. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8978. ctx.stroke();
  8979. }
  8980. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8981. ctx.lineWidth *= this.graphScaleInv;
  8982. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8983. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8984. ctx[shape](this.x, this.y, this.radius);
  8985. ctx.fill();
  8986. ctx.stroke();
  8987. if (this.label) {
  8988. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  8989. }
  8990. };
  8991. Node.prototype._resizeText = function (ctx) {
  8992. if (!this.width) {
  8993. var margin = 5;
  8994. var textSize = this.getTextSize(ctx);
  8995. this.width = textSize.width + 2 * margin;
  8996. this.height = textSize.height + 2 * margin;
  8997. // scaling used for clustering
  8998. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8999. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  9000. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  9001. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  9002. }
  9003. };
  9004. Node.prototype._drawText = function (ctx) {
  9005. this._resizeText(ctx);
  9006. this.left = this.x - this.width / 2;
  9007. this.top = this.y - this.height / 2;
  9008. this._label(ctx, this.label, this.x, this.y);
  9009. };
  9010. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  9011. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  9012. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9013. ctx.fillStyle = this.fontColor || "black";
  9014. ctx.textAlign = align || "center";
  9015. ctx.textBaseline = baseline || "middle";
  9016. var lines = text.split('\n'),
  9017. lineCount = lines.length,
  9018. fontSize = (this.fontSize + 4),
  9019. yLine = y + (1 - lineCount) / 2 * fontSize;
  9020. for (var i = 0; i < lineCount; i++) {
  9021. ctx.fillText(lines[i], x, yLine);
  9022. yLine += fontSize;
  9023. }
  9024. }
  9025. };
  9026. Node.prototype.getTextSize = function(ctx) {
  9027. if (this.label !== undefined) {
  9028. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9029. var lines = this.label.split('\n'),
  9030. height = (this.fontSize + 4) * lines.length,
  9031. width = 0;
  9032. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  9033. width = Math.max(width, ctx.measureText(lines[i]).width);
  9034. }
  9035. return {"width": width, "height": height};
  9036. }
  9037. else {
  9038. return {"width": 0, "height": 0};
  9039. }
  9040. };
  9041. /**
  9042. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  9043. * there is a safety margin of 0.3 * width;
  9044. *
  9045. * @returns {boolean}
  9046. */
  9047. Node.prototype.inArea = function() {
  9048. if (this.width !== undefined) {
  9049. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  9050. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  9051. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  9052. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  9053. }
  9054. else {
  9055. return true;
  9056. }
  9057. };
  9058. /**
  9059. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  9060. * @returns {boolean}
  9061. */
  9062. Node.prototype.inView = function() {
  9063. return (this.x >= this.canvasTopLeft.x &&
  9064. this.x < this.canvasBottomRight.x &&
  9065. this.y >= this.canvasTopLeft.y &&
  9066. this.y < this.canvasBottomRight.y);
  9067. };
  9068. /**
  9069. * This allows the zoom level of the graph to influence the rendering
  9070. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  9071. *
  9072. * @param scale
  9073. * @param canvasTopLeft
  9074. * @param canvasBottomRight
  9075. */
  9076. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  9077. this.graphScaleInv = 1.0/scale;
  9078. this.graphScale = scale;
  9079. this.canvasTopLeft = canvasTopLeft;
  9080. this.canvasBottomRight = canvasBottomRight;
  9081. };
  9082. /**
  9083. * This allows the zoom level of the graph to influence the rendering
  9084. *
  9085. * @param scale
  9086. */
  9087. Node.prototype.setScale = function(scale) {
  9088. this.graphScaleInv = 1.0/scale;
  9089. this.graphScale = scale;
  9090. };
  9091. /**
  9092. * set the velocity at 0. Is called when this node is contained in another during clustering
  9093. */
  9094. Node.prototype.clearVelocity = function() {
  9095. this.vx = 0;
  9096. this.vy = 0;
  9097. };
  9098. /**
  9099. * Basic preservation of (kinectic) energy
  9100. *
  9101. * @param massBeforeClustering
  9102. */
  9103. Node.prototype.updateVelocity = function(massBeforeClustering) {
  9104. var energyBefore = this.vx * this.vx * massBeforeClustering;
  9105. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9106. this.vx = Math.sqrt(energyBefore/this.mass);
  9107. energyBefore = this.vy * this.vy * massBeforeClustering;
  9108. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9109. this.vy = Math.sqrt(energyBefore/this.mass);
  9110. };
  9111. /**
  9112. * @class Edge
  9113. *
  9114. * A edge connects two nodes
  9115. * @param {Object} properties Object with properties. Must contain
  9116. * At least properties from and to.
  9117. * Available properties: from (number),
  9118. * to (number), label (string, color (string),
  9119. * width (number), style (string),
  9120. * length (number), title (string)
  9121. * @param {Graph} graph A graph object, used to find and edge to
  9122. * nodes.
  9123. * @param {Object} constants An object with default values for
  9124. * example for the color
  9125. */
  9126. function Edge (properties, graph, constants) {
  9127. if (!graph) {
  9128. throw "No graph provided";
  9129. }
  9130. this.graph = graph;
  9131. // initialize constants
  9132. this.widthMin = constants.edges.widthMin;
  9133. this.widthMax = constants.edges.widthMax;
  9134. // initialize variables
  9135. this.id = undefined;
  9136. this.fromId = undefined;
  9137. this.toId = undefined;
  9138. this.style = constants.edges.style;
  9139. this.title = undefined;
  9140. this.width = constants.edges.width;
  9141. this.value = undefined;
  9142. this.length = constants.physics.springLength;
  9143. this.customLength = false;
  9144. this.selected = false;
  9145. this.smooth = constants.smoothCurves;
  9146. this.from = null; // a node
  9147. this.to = null; // a node
  9148. this.via = null; // a temp node
  9149. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  9150. // by storing the original information we can revert to the original connection when the cluser is opened.
  9151. this.originalFromId = [];
  9152. this.originalToId = [];
  9153. this.connected = false;
  9154. // Added to support dashed lines
  9155. // David Jordan
  9156. // 2012-08-08
  9157. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  9158. this.color = constants.edges.color;
  9159. this.widthFixed = false;
  9160. this.lengthFixed = false;
  9161. this.setProperties(properties, constants);
  9162. }
  9163. /**
  9164. * Set or overwrite properties for the edge
  9165. * @param {Object} properties an object with properties
  9166. * @param {Object} constants and object with default, global properties
  9167. */
  9168. Edge.prototype.setProperties = function(properties, constants) {
  9169. if (!properties) {
  9170. return;
  9171. }
  9172. if (properties.from !== undefined) {this.fromId = properties.from;}
  9173. if (properties.to !== undefined) {this.toId = properties.to;}
  9174. if (properties.id !== undefined) {this.id = properties.id;}
  9175. if (properties.style !== undefined) {this.style = properties.style;}
  9176. if (properties.label !== undefined) {this.label = properties.label;}
  9177. if (this.label) {
  9178. this.fontSize = constants.edges.fontSize;
  9179. this.fontFace = constants.edges.fontFace;
  9180. this.fontColor = constants.edges.fontColor;
  9181. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  9182. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  9183. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  9184. }
  9185. if (properties.title !== undefined) {this.title = properties.title;}
  9186. if (properties.width !== undefined) {this.width = properties.width;}
  9187. if (properties.value !== undefined) {this.value = properties.value;}
  9188. if (properties.length !== undefined) {this.length = properties.length;
  9189. this.customLength = true;}
  9190. // Added to support dashed lines
  9191. // David Jordan
  9192. // 2012-08-08
  9193. if (properties.dash) {
  9194. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  9195. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  9196. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  9197. }
  9198. if (properties.color !== undefined) {this.color = properties.color;}
  9199. // A node is connected when it has a from and to node.
  9200. this.connect();
  9201. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  9202. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  9203. // set draw method based on style
  9204. switch (this.style) {
  9205. case 'line': this.draw = this._drawLine; break;
  9206. case 'arrow': this.draw = this._drawArrow; break;
  9207. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  9208. case 'dash-line': this.draw = this._drawDashLine; break;
  9209. default: this.draw = this._drawLine; break;
  9210. }
  9211. };
  9212. /**
  9213. * Connect an edge to its nodes
  9214. */
  9215. Edge.prototype.connect = function () {
  9216. this.disconnect();
  9217. this.from = this.graph.nodes[this.fromId] || null;
  9218. this.to = this.graph.nodes[this.toId] || null;
  9219. this.connected = (this.from && this.to);
  9220. if (this.connected) {
  9221. this.from.attachEdge(this);
  9222. this.to.attachEdge(this);
  9223. }
  9224. else {
  9225. if (this.from) {
  9226. this.from.detachEdge(this);
  9227. }
  9228. if (this.to) {
  9229. this.to.detachEdge(this);
  9230. }
  9231. }
  9232. };
  9233. /**
  9234. * Disconnect an edge from its nodes
  9235. */
  9236. Edge.prototype.disconnect = function () {
  9237. if (this.from) {
  9238. this.from.detachEdge(this);
  9239. this.from = null;
  9240. }
  9241. if (this.to) {
  9242. this.to.detachEdge(this);
  9243. this.to = null;
  9244. }
  9245. this.connected = false;
  9246. };
  9247. /**
  9248. * get the title of this edge.
  9249. * @return {string} title The title of the edge, or undefined when no title
  9250. * has been set.
  9251. */
  9252. Edge.prototype.getTitle = function() {
  9253. return this.title;
  9254. };
  9255. /**
  9256. * Retrieve the value of the edge. Can be undefined
  9257. * @return {Number} value
  9258. */
  9259. Edge.prototype.getValue = function() {
  9260. return this.value;
  9261. };
  9262. /**
  9263. * Adjust the value range of the edge. The edge will adjust it's width
  9264. * based on its value.
  9265. * @param {Number} min
  9266. * @param {Number} max
  9267. */
  9268. Edge.prototype.setValueRange = function(min, max) {
  9269. if (!this.widthFixed && this.value !== undefined) {
  9270. var scale = (this.widthMax - this.widthMin) / (max - min);
  9271. this.width = (this.value - min) * scale + this.widthMin;
  9272. }
  9273. };
  9274. /**
  9275. * Redraw a edge
  9276. * Draw this edge in the given canvas
  9277. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9278. * @param {CanvasRenderingContext2D} ctx
  9279. */
  9280. Edge.prototype.draw = function(ctx) {
  9281. throw "Method draw not initialized in edge";
  9282. };
  9283. /**
  9284. * Check if this object is overlapping with the provided object
  9285. * @param {Object} obj an object with parameters left, top
  9286. * @return {boolean} True if location is located on the edge
  9287. */
  9288. Edge.prototype.isOverlappingWith = function(obj) {
  9289. var distMax = 10;
  9290. var xFrom = this.from.x;
  9291. var yFrom = this.from.y;
  9292. var xTo = this.to.x;
  9293. var yTo = this.to.y;
  9294. var xObj = obj.left;
  9295. var yObj = obj.top;
  9296. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  9297. return (dist < distMax);
  9298. };
  9299. /**
  9300. * Redraw a edge as a line
  9301. * Draw this edge in the given canvas
  9302. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9303. * @param {CanvasRenderingContext2D} ctx
  9304. * @private
  9305. */
  9306. Edge.prototype._drawLine = function(ctx) {
  9307. // set style
  9308. ctx.strokeStyle = this.color;
  9309. ctx.lineWidth = this._getLineWidth();
  9310. if (this.from != this.to) {
  9311. // draw line
  9312. this._line(ctx);
  9313. // draw label
  9314. var point;
  9315. if (this.label) {
  9316. if (this.smooth == true) {
  9317. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9318. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9319. point = {x:midpointX, y:midpointY};
  9320. }
  9321. else {
  9322. point = this._pointOnLine(0.5);
  9323. }
  9324. this._label(ctx, this.label, point.x, point.y);
  9325. }
  9326. }
  9327. else {
  9328. var x, y;
  9329. var radius = this.length / 4;
  9330. var node = this.from;
  9331. if (!node.width) {
  9332. node.resize(ctx);
  9333. }
  9334. if (node.width > node.height) {
  9335. x = node.x + node.width / 2;
  9336. y = node.y - radius;
  9337. }
  9338. else {
  9339. x = node.x + radius;
  9340. y = node.y - node.height / 2;
  9341. }
  9342. this._circle(ctx, x, y, radius);
  9343. point = this._pointOnCircle(x, y, radius, 0.5);
  9344. this._label(ctx, this.label, point.x, point.y);
  9345. }
  9346. };
  9347. /**
  9348. * Get the line width of the edge. Depends on width and whether one of the
  9349. * connected nodes is selected.
  9350. * @return {Number} width
  9351. * @private
  9352. */
  9353. Edge.prototype._getLineWidth = function() {
  9354. if (this.selected == true) {
  9355. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  9356. }
  9357. else {
  9358. return this.width*this.graphScaleInv;
  9359. }
  9360. };
  9361. /**
  9362. * Draw a line between two nodes
  9363. * @param {CanvasRenderingContext2D} ctx
  9364. * @private
  9365. */
  9366. Edge.prototype._line = function (ctx) {
  9367. // draw a straight line
  9368. ctx.beginPath();
  9369. ctx.moveTo(this.from.x, this.from.y);
  9370. if (this.smooth == true) {
  9371. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9372. }
  9373. else {
  9374. ctx.lineTo(this.to.x, this.to.y);
  9375. }
  9376. ctx.stroke();
  9377. };
  9378. /**
  9379. * Draw a line from a node to itself, a circle
  9380. * @param {CanvasRenderingContext2D} ctx
  9381. * @param {Number} x
  9382. * @param {Number} y
  9383. * @param {Number} radius
  9384. * @private
  9385. */
  9386. Edge.prototype._circle = function (ctx, x, y, radius) {
  9387. // draw a circle
  9388. ctx.beginPath();
  9389. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9390. ctx.stroke();
  9391. };
  9392. /**
  9393. * Draw label with white background and with the middle at (x, y)
  9394. * @param {CanvasRenderingContext2D} ctx
  9395. * @param {String} text
  9396. * @param {Number} x
  9397. * @param {Number} y
  9398. * @private
  9399. */
  9400. Edge.prototype._label = function (ctx, text, x, y) {
  9401. if (text) {
  9402. // TODO: cache the calculated size
  9403. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  9404. this.fontSize + "px " + this.fontFace;
  9405. ctx.fillStyle = 'white';
  9406. var width = ctx.measureText(text).width;
  9407. var height = this.fontSize;
  9408. var left = x - width / 2;
  9409. var top = y - height / 2;
  9410. ctx.fillRect(left, top, width, height);
  9411. // draw text
  9412. ctx.fillStyle = this.fontColor || "black";
  9413. ctx.textAlign = "left";
  9414. ctx.textBaseline = "top";
  9415. ctx.fillText(text, left, top);
  9416. }
  9417. };
  9418. /**
  9419. * Redraw a edge as a dashed line
  9420. * Draw this edge in the given canvas
  9421. * @author David Jordan
  9422. * @date 2012-08-08
  9423. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9424. * @param {CanvasRenderingContext2D} ctx
  9425. * @private
  9426. */
  9427. Edge.prototype._drawDashLine = function(ctx) {
  9428. // set style
  9429. ctx.strokeStyle = this.color;
  9430. ctx.lineWidth = this._getLineWidth();
  9431. // only firefox and chrome support this method, else we use the legacy one.
  9432. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  9433. ctx.beginPath();
  9434. ctx.moveTo(this.from.x, this.from.y);
  9435. // configure the dash pattern
  9436. var pattern = [0];
  9437. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  9438. pattern = [this.dash.length,this.dash.gap];
  9439. }
  9440. else {
  9441. pattern = [5,5];
  9442. }
  9443. // set dash settings for chrome or firefox
  9444. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9445. ctx.setLineDash(pattern);
  9446. ctx.lineDashOffset = 0;
  9447. } else { //Firefox
  9448. ctx.mozDash = pattern;
  9449. ctx.mozDashOffset = 0;
  9450. }
  9451. // draw the line
  9452. if (this.smooth == true) {
  9453. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9454. }
  9455. else {
  9456. ctx.lineTo(this.to.x, this.to.y);
  9457. }
  9458. ctx.stroke();
  9459. // restore the dash settings.
  9460. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9461. ctx.setLineDash([0]);
  9462. ctx.lineDashOffset = 0;
  9463. } else { //Firefox
  9464. ctx.mozDash = [0];
  9465. ctx.mozDashOffset = 0;
  9466. }
  9467. }
  9468. else { // unsupporting smooth lines
  9469. // draw dashed line
  9470. ctx.beginPath();
  9471. ctx.lineCap = 'round';
  9472. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9473. {
  9474. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9475. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9476. }
  9477. 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
  9478. {
  9479. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9480. [this.dash.length,this.dash.gap]);
  9481. }
  9482. else //If all else fails draw a line
  9483. {
  9484. ctx.moveTo(this.from.x, this.from.y);
  9485. ctx.lineTo(this.to.x, this.to.y);
  9486. }
  9487. ctx.stroke();
  9488. }
  9489. // draw label
  9490. if (this.label) {
  9491. var point;
  9492. if (this.smooth == true) {
  9493. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9494. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9495. point = {x:midpointX, y:midpointY};
  9496. }
  9497. else {
  9498. point = this._pointOnLine(0.5);
  9499. }
  9500. this._label(ctx, this.label, point.x, point.y);
  9501. }
  9502. };
  9503. /**
  9504. * Get a point on a line
  9505. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9506. * @return {Object} point
  9507. * @private
  9508. */
  9509. Edge.prototype._pointOnLine = function (percentage) {
  9510. return {
  9511. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9512. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9513. }
  9514. };
  9515. /**
  9516. * Get a point on a circle
  9517. * @param {Number} x
  9518. * @param {Number} y
  9519. * @param {Number} radius
  9520. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9521. * @return {Object} point
  9522. * @private
  9523. */
  9524. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9525. var angle = (percentage - 3/8) * 2 * Math.PI;
  9526. return {
  9527. x: x + radius * Math.cos(angle),
  9528. y: y - radius * Math.sin(angle)
  9529. }
  9530. };
  9531. /**
  9532. * Redraw a edge as a line with an arrow halfway the line
  9533. * Draw this edge in the given canvas
  9534. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9535. * @param {CanvasRenderingContext2D} ctx
  9536. * @private
  9537. */
  9538. Edge.prototype._drawArrowCenter = function(ctx) {
  9539. var point;
  9540. // set style
  9541. ctx.strokeStyle = this.color;
  9542. ctx.fillStyle = this.color;
  9543. ctx.lineWidth = this._getLineWidth();
  9544. if (this.from != this.to) {
  9545. // draw line
  9546. this._line(ctx);
  9547. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9548. var length = 10 + 5 * this.width; // TODO: make customizable?
  9549. // draw an arrow halfway the line
  9550. if (this.smooth == true) {
  9551. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9552. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9553. point = {x:midpointX, y:midpointY};
  9554. }
  9555. else {
  9556. point = this._pointOnLine(0.5);
  9557. }
  9558. ctx.arrow(point.x, point.y, angle, length);
  9559. ctx.fill();
  9560. ctx.stroke();
  9561. // draw label
  9562. if (this.label) {
  9563. this._label(ctx, this.label, point.x, point.y);
  9564. }
  9565. }
  9566. else {
  9567. // draw circle
  9568. var x, y;
  9569. var radius = 0.25 * Math.max(100,this.length);
  9570. var node = this.from;
  9571. if (!node.width) {
  9572. node.resize(ctx);
  9573. }
  9574. if (node.width > node.height) {
  9575. x = node.x + node.width * 0.5;
  9576. y = node.y - radius;
  9577. }
  9578. else {
  9579. x = node.x + radius;
  9580. y = node.y - node.height * 0.5;
  9581. }
  9582. this._circle(ctx, x, y, radius);
  9583. // draw all arrows
  9584. var angle = 0.2 * Math.PI;
  9585. var length = 10 + 5 * this.width; // TODO: make customizable?
  9586. point = this._pointOnCircle(x, y, radius, 0.5);
  9587. ctx.arrow(point.x, point.y, angle, length);
  9588. ctx.fill();
  9589. ctx.stroke();
  9590. // draw label
  9591. if (this.label) {
  9592. point = this._pointOnCircle(x, y, radius, 0.5);
  9593. this._label(ctx, this.label, point.x, point.y);
  9594. }
  9595. }
  9596. };
  9597. /**
  9598. * Redraw a edge as a line with an arrow
  9599. * Draw this edge in the given canvas
  9600. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9601. * @param {CanvasRenderingContext2D} ctx
  9602. * @private
  9603. */
  9604. Edge.prototype._drawArrow = function(ctx) {
  9605. // set style
  9606. ctx.strokeStyle = this.color;
  9607. ctx.fillStyle = this.color;
  9608. ctx.lineWidth = this._getLineWidth();
  9609. var angle, length;
  9610. //draw a line
  9611. if (this.from != this.to) {
  9612. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9613. var dx = (this.to.x - this.from.x);
  9614. var dy = (this.to.y - this.from.y);
  9615. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9616. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9617. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9618. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9619. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9620. if (this.smooth == true) {
  9621. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9622. dx = (this.to.x - this.via.x);
  9623. dy = (this.to.y - this.via.y);
  9624. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9625. }
  9626. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9627. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9628. var xTo,yTo;
  9629. if (this.smooth == true) {
  9630. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9631. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9632. }
  9633. else {
  9634. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9635. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9636. }
  9637. ctx.beginPath();
  9638. ctx.moveTo(xFrom,yFrom);
  9639. if (this.smooth == true) {
  9640. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9641. }
  9642. else {
  9643. ctx.lineTo(xTo, yTo);
  9644. }
  9645. ctx.stroke();
  9646. // draw arrow at the end of the line
  9647. length = 10 + 5 * this.width;
  9648. ctx.arrow(xTo, yTo, angle, length);
  9649. ctx.fill();
  9650. ctx.stroke();
  9651. // draw label
  9652. if (this.label) {
  9653. var point;
  9654. if (this.smooth == true) {
  9655. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9656. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9657. point = {x:midpointX, y:midpointY};
  9658. }
  9659. else {
  9660. point = this._pointOnLine(0.5);
  9661. }
  9662. this._label(ctx, this.label, point.x, point.y);
  9663. }
  9664. }
  9665. else {
  9666. // draw circle
  9667. var node = this.from;
  9668. var x, y, arrow;
  9669. var radius = 0.25 * Math.max(100,this.length);
  9670. if (!node.width) {
  9671. node.resize(ctx);
  9672. }
  9673. if (node.width > node.height) {
  9674. x = node.x + node.width * 0.5;
  9675. y = node.y - radius;
  9676. arrow = {
  9677. x: x,
  9678. y: node.y,
  9679. angle: 0.9 * Math.PI
  9680. };
  9681. }
  9682. else {
  9683. x = node.x + radius;
  9684. y = node.y - node.height * 0.5;
  9685. arrow = {
  9686. x: node.x,
  9687. y: y,
  9688. angle: 0.6 * Math.PI
  9689. };
  9690. }
  9691. ctx.beginPath();
  9692. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9693. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9694. ctx.stroke();
  9695. // draw all arrows
  9696. length = 10 + 5 * this.width; // TODO: make customizable?
  9697. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9698. ctx.fill();
  9699. ctx.stroke();
  9700. // draw label
  9701. if (this.label) {
  9702. point = this._pointOnCircle(x, y, radius, 0.5);
  9703. this._label(ctx, this.label, point.x, point.y);
  9704. }
  9705. }
  9706. };
  9707. /**
  9708. * Calculate the distance between a point (x3,y3) and a line segment from
  9709. * (x1,y1) to (x2,y2).
  9710. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9711. * @param {number} x1
  9712. * @param {number} y1
  9713. * @param {number} x2
  9714. * @param {number} y2
  9715. * @param {number} x3
  9716. * @param {number} y3
  9717. * @private
  9718. */
  9719. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9720. if (this.smooth == true) {
  9721. var minDistance = 1e9;
  9722. var i,t,x,y,dx,dy;
  9723. for (i = 0; i < 10; i++) {
  9724. t = 0.1*i;
  9725. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9726. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9727. dx = Math.abs(x3-x);
  9728. dy = Math.abs(y3-y);
  9729. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9730. }
  9731. return minDistance
  9732. }
  9733. else {
  9734. var px = x2-x1,
  9735. py = y2-y1,
  9736. something = px*px + py*py,
  9737. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9738. if (u > 1) {
  9739. u = 1;
  9740. }
  9741. else if (u < 0) {
  9742. u = 0;
  9743. }
  9744. var x = x1 + u * px,
  9745. y = y1 + u * py,
  9746. dx = x - x3,
  9747. dy = y - y3;
  9748. //# Note: If the actual distance does not matter,
  9749. //# if you only want to compare what this function
  9750. //# returns to other results of this function, you
  9751. //# can just return the squared distance instead
  9752. //# (i.e. remove the sqrt) to gain a little performance
  9753. return Math.sqrt(dx*dx + dy*dy);
  9754. }
  9755. };
  9756. /**
  9757. * This allows the zoom level of the graph to influence the rendering
  9758. *
  9759. * @param scale
  9760. */
  9761. Edge.prototype.setScale = function(scale) {
  9762. this.graphScaleInv = 1.0/scale;
  9763. };
  9764. Edge.prototype.select = function() {
  9765. this.selected = true;
  9766. };
  9767. Edge.prototype.unselect = function() {
  9768. this.selected = false;
  9769. };
  9770. Edge.prototype.positionBezierNode = function() {
  9771. if (this.via !== null) {
  9772. this.via.x = 0.5 * (this.from.x + this.to.x);
  9773. this.via.y = 0.5 * (this.from.y + this.to.y);
  9774. }
  9775. };
  9776. /**
  9777. * Popup is a class to create a popup window with some text
  9778. * @param {Element} container The container object.
  9779. * @param {Number} [x]
  9780. * @param {Number} [y]
  9781. * @param {String} [text]
  9782. */
  9783. function Popup(container, x, y, text) {
  9784. if (container) {
  9785. this.container = container;
  9786. }
  9787. else {
  9788. this.container = document.body;
  9789. }
  9790. this.x = 0;
  9791. this.y = 0;
  9792. this.padding = 5;
  9793. if (x !== undefined && y !== undefined ) {
  9794. this.setPosition(x, y);
  9795. }
  9796. if (text !== undefined) {
  9797. this.setText(text);
  9798. }
  9799. // create the frame
  9800. this.frame = document.createElement("div");
  9801. var style = this.frame.style;
  9802. style.position = "absolute";
  9803. style.visibility = "hidden";
  9804. style.border = "1px solid #666";
  9805. style.color = "black";
  9806. style.padding = this.padding + "px";
  9807. style.backgroundColor = "#FFFFC6";
  9808. style.borderRadius = "3px";
  9809. style.MozBorderRadius = "3px";
  9810. style.WebkitBorderRadius = "3px";
  9811. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9812. style.whiteSpace = "nowrap";
  9813. this.container.appendChild(this.frame);
  9814. }
  9815. /**
  9816. * @param {number} x Horizontal position of the popup window
  9817. * @param {number} y Vertical position of the popup window
  9818. */
  9819. Popup.prototype.setPosition = function(x, y) {
  9820. this.x = parseInt(x);
  9821. this.y = parseInt(y);
  9822. };
  9823. /**
  9824. * Set the text for the popup window. This can be HTML code
  9825. * @param {string} text
  9826. */
  9827. Popup.prototype.setText = function(text) {
  9828. this.frame.innerHTML = text;
  9829. };
  9830. /**
  9831. * Show the popup window
  9832. * @param {boolean} show Optional. Show or hide the window
  9833. */
  9834. Popup.prototype.show = function (show) {
  9835. if (show === undefined) {
  9836. show = true;
  9837. }
  9838. if (show) {
  9839. var height = this.frame.clientHeight;
  9840. var width = this.frame.clientWidth;
  9841. var maxHeight = this.frame.parentNode.clientHeight;
  9842. var maxWidth = this.frame.parentNode.clientWidth;
  9843. var top = (this.y - height);
  9844. if (top + height + this.padding > maxHeight) {
  9845. top = maxHeight - height - this.padding;
  9846. }
  9847. if (top < this.padding) {
  9848. top = this.padding;
  9849. }
  9850. var left = this.x;
  9851. if (left + width + this.padding > maxWidth) {
  9852. left = maxWidth - width - this.padding;
  9853. }
  9854. if (left < this.padding) {
  9855. left = this.padding;
  9856. }
  9857. this.frame.style.left = left + "px";
  9858. this.frame.style.top = top + "px";
  9859. this.frame.style.visibility = "visible";
  9860. }
  9861. else {
  9862. this.hide();
  9863. }
  9864. };
  9865. /**
  9866. * Hide the popup window
  9867. */
  9868. Popup.prototype.hide = function () {
  9869. this.frame.style.visibility = "hidden";
  9870. };
  9871. /**
  9872. * @class Groups
  9873. * This class can store groups and properties specific for groups.
  9874. */
  9875. Groups = function () {
  9876. this.clear();
  9877. this.defaultIndex = 0;
  9878. };
  9879. /**
  9880. * default constants for group colors
  9881. */
  9882. Groups.DEFAULT = [
  9883. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9884. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9885. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9886. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9887. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9888. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9889. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9890. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9891. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9892. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9893. ];
  9894. /**
  9895. * Clear all groups
  9896. */
  9897. Groups.prototype.clear = function () {
  9898. this.groups = {};
  9899. this.groups.length = function()
  9900. {
  9901. var i = 0;
  9902. for ( var p in this ) {
  9903. if (this.hasOwnProperty(p)) {
  9904. i++;
  9905. }
  9906. }
  9907. return i;
  9908. }
  9909. };
  9910. /**
  9911. * get group properties of a groupname. If groupname is not found, a new group
  9912. * is added.
  9913. * @param {*} groupname Can be a number, string, Date, etc.
  9914. * @return {Object} group The created group, containing all group properties
  9915. */
  9916. Groups.prototype.get = function (groupname) {
  9917. var group = this.groups[groupname];
  9918. if (group == undefined) {
  9919. // create new group
  9920. var index = this.defaultIndex % Groups.DEFAULT.length;
  9921. this.defaultIndex++;
  9922. group = {};
  9923. group.color = Groups.DEFAULT[index];
  9924. this.groups[groupname] = group;
  9925. }
  9926. return group;
  9927. };
  9928. /**
  9929. * Add a custom group style
  9930. * @param {String} groupname
  9931. * @param {Object} style An object containing borderColor,
  9932. * backgroundColor, etc.
  9933. * @return {Object} group The created group object
  9934. */
  9935. Groups.prototype.add = function (groupname, style) {
  9936. this.groups[groupname] = style;
  9937. if (style.color) {
  9938. style.color = Node.parseColor(style.color);
  9939. }
  9940. return style;
  9941. };
  9942. /**
  9943. * @class Images
  9944. * This class loads images and keeps them stored.
  9945. */
  9946. Images = function () {
  9947. this.images = {};
  9948. this.callback = undefined;
  9949. };
  9950. /**
  9951. * Set an onload callback function. This will be called each time an image
  9952. * is loaded
  9953. * @param {function} callback
  9954. */
  9955. Images.prototype.setOnloadCallback = function(callback) {
  9956. this.callback = callback;
  9957. };
  9958. /**
  9959. *
  9960. * @param {string} url Url of the image
  9961. * @return {Image} img The image object
  9962. */
  9963. Images.prototype.load = function(url) {
  9964. var img = this.images[url];
  9965. if (img == undefined) {
  9966. // create the image
  9967. var images = this;
  9968. img = new Image();
  9969. this.images[url] = img;
  9970. img.onload = function() {
  9971. if (images.callback) {
  9972. images.callback(this);
  9973. }
  9974. };
  9975. img.src = url;
  9976. }
  9977. return img;
  9978. };
  9979. /**
  9980. * Created by Alex on 2/6/14.
  9981. */
  9982. var physicsMixin = {
  9983. /**
  9984. * Toggling barnes Hut calculation on and off.
  9985. *
  9986. * @private
  9987. */
  9988. _toggleBarnesHut : function() {
  9989. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  9990. this._loadSelectedForceSolver();
  9991. this.moving = true;
  9992. this.start();
  9993. },
  9994. /**
  9995. * This loads the node force solver based on the barnes hut or repulsion algorithm
  9996. *
  9997. * @private
  9998. */
  9999. _loadSelectedForceSolver : function() {
  10000. // this overloads the this._calculateNodeForces
  10001. if (this.constants.physics.barnesHut.enabled == true) {
  10002. this._clearMixin(repulsionMixin);
  10003. this._clearMixin(hierarchalRepulsionMixin);
  10004. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  10005. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  10006. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  10007. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  10008. this._loadMixin(barnesHutMixin);
  10009. }
  10010. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  10011. this._clearMixin(barnesHutMixin);
  10012. this._clearMixin(repulsionMixin);
  10013. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  10014. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  10015. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  10016. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  10017. this._loadMixin(hierarchalRepulsionMixin);
  10018. }
  10019. else {
  10020. this._clearMixin(barnesHutMixin);
  10021. this._clearMixin(hierarchalRepulsionMixin);
  10022. this.barnesHutTree = undefined;
  10023. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  10024. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  10025. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  10026. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  10027. this._loadMixin(repulsionMixin);
  10028. }
  10029. },
  10030. /**
  10031. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  10032. * if there is more than one node. If it is just one node, we dont calculate anything.
  10033. *
  10034. * @private
  10035. */
  10036. _initializeForceCalculation : function() {
  10037. // stop calculation if there is only one node
  10038. if (this.nodeIndices.length == 1) {
  10039. this.nodes[this.nodeIndices[0]]._setForce(0,0);
  10040. }
  10041. else {
  10042. // if there are too many nodes on screen, we cluster without repositioning
  10043. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  10044. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  10045. }
  10046. // we now start the force calculation
  10047. this._calculateForces();
  10048. }
  10049. },
  10050. /**
  10051. * Calculate the external forces acting on the nodes
  10052. * Forces are caused by: edges, repulsing forces between nodes, gravity
  10053. * @private
  10054. */
  10055. _calculateForces : function() {
  10056. // Gravity is required to keep separated groups from floating off
  10057. // the forces are reset to zero in this loop by using _setForce instead
  10058. // of _addForce
  10059. this._calculateGravitationalForces();
  10060. this._calculateNodeForces();
  10061. if (this.constants.smoothCurves == true) {
  10062. this._calculateSpringForcesWithSupport();
  10063. }
  10064. else {
  10065. this._calculateSpringForces();
  10066. }
  10067. },
  10068. /**
  10069. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  10070. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  10071. * This function joins the datanodes and invisible (called support) nodes into one object.
  10072. * We do this so we do not contaminate this.nodes with the support nodes.
  10073. *
  10074. * @private
  10075. */
  10076. _updateCalculationNodes : function() {
  10077. if (this.constants.smoothCurves == true) {
  10078. this.calculationNodes = {};
  10079. this.calculationNodeIndices = [];
  10080. for (var nodeId in this.nodes) {
  10081. if (this.nodes.hasOwnProperty(nodeId)) {
  10082. this.calculationNodes[nodeId] = this.nodes[nodeId];
  10083. }
  10084. }
  10085. var supportNodes = this.sectors['support']['nodes'];
  10086. for (var supportNodeId in supportNodes) {
  10087. if (supportNodes.hasOwnProperty(supportNodeId)) {
  10088. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  10089. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  10090. }
  10091. else {
  10092. supportNodes[supportNodeId]._setForce(0,0);
  10093. }
  10094. }
  10095. }
  10096. for (var idx in this.calculationNodes) {
  10097. if (this.calculationNodes.hasOwnProperty(idx)) {
  10098. this.calculationNodeIndices.push(idx);
  10099. }
  10100. }
  10101. }
  10102. else {
  10103. this.calculationNodes = this.nodes;
  10104. this.calculationNodeIndices = this.nodeIndices;
  10105. }
  10106. },
  10107. /**
  10108. * this function applies the central gravity effect to keep groups from floating off
  10109. *
  10110. * @private
  10111. */
  10112. _calculateGravitationalForces : function() {
  10113. var dx, dy, distance, node, i;
  10114. var nodes = this.calculationNodes;
  10115. var gravity = this.constants.physics.centralGravity;
  10116. var gravityForce = 0;
  10117. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  10118. node = nodes[this.calculationNodeIndices[i]];
  10119. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  10120. // gravity does not apply when we are in a pocket sector
  10121. if (this._sector() == "default" && gravity != 0) {
  10122. dx = -node.x;
  10123. dy = -node.y;
  10124. distance = Math.sqrt(dx*dx + dy*dy);
  10125. gravityForce = gravity / distance;
  10126. node.fx = dx * gravityForce;
  10127. node.fy = dy * gravityForce;
  10128. }
  10129. else {
  10130. node.fx = 0;
  10131. node.fy = 0;
  10132. }
  10133. }
  10134. },
  10135. /**
  10136. * this function calculates the effects of the springs in the case of unsmooth curves.
  10137. *
  10138. * @private
  10139. */
  10140. _calculateSpringForces : function() {
  10141. var edgeLength, edge, edgeId;
  10142. var dx, dy, fx, fy, springForce, length;
  10143. var edges = this.edges;
  10144. // forces caused by the edges, modelled as springs
  10145. for (edgeId in edges) {
  10146. if (edges.hasOwnProperty(edgeId)) {
  10147. edge = edges[edgeId];
  10148. if (edge.connected) {
  10149. // only calculate forces if nodes are in the same sector
  10150. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10151. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  10152. // this implies that the edges between big clusters are longer
  10153. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  10154. dx = (edge.from.x - edge.to.x);
  10155. dy = (edge.from.y - edge.to.y);
  10156. length = Math.sqrt(dx * dx + dy * dy);
  10157. if (length == 0) {
  10158. length = 0.01;
  10159. }
  10160. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10161. fx = dx * springForce;
  10162. fy = dy * springForce;
  10163. edge.from.fx += fx;
  10164. edge.from.fy += fy;
  10165. edge.to.fx -= fx;
  10166. edge.to.fy -= fy;
  10167. }
  10168. }
  10169. }
  10170. }
  10171. },
  10172. /**
  10173. * This function calculates the springforces on the nodes, accounting for the support nodes.
  10174. *
  10175. * @private
  10176. */
  10177. _calculateSpringForcesWithSupport : function() {
  10178. var edgeLength, edge, edgeId, combinedClusterSize;
  10179. var edges = this.edges;
  10180. // forces caused by the edges, modelled as springs
  10181. for (edgeId in edges) {
  10182. if (edges.hasOwnProperty(edgeId)) {
  10183. edge = edges[edgeId];
  10184. if (edge.connected) {
  10185. // only calculate forces if nodes are in the same sector
  10186. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10187. if (edge.via != null) {
  10188. var node1 = edge.to;
  10189. var node2 = edge.via;
  10190. var node3 = edge.from;
  10191. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  10192. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  10193. // this implies that the edges between big clusters are longer
  10194. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  10195. this._calculateSpringForce(node1,node2,0.5*edgeLength);
  10196. this._calculateSpringForce(node2,node3,0.5*edgeLength);
  10197. }
  10198. }
  10199. }
  10200. }
  10201. }
  10202. },
  10203. /**
  10204. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  10205. *
  10206. * @param node1
  10207. * @param node2
  10208. * @param edgeLength
  10209. * @private
  10210. */
  10211. _calculateSpringForce : function(node1,node2,edgeLength) {
  10212. var dx, dy, fx, fy, springForce, length;
  10213. dx = (node1.x - node2.x);
  10214. dy = (node1.y - node2.y);
  10215. length = Math.sqrt(dx * dx + dy * dy);
  10216. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10217. if (length == 0) {
  10218. length = 0.01;
  10219. }
  10220. fx = dx * springForce;
  10221. fy = dy * springForce;
  10222. node1.fx += fx;
  10223. node1.fy += fy;
  10224. node2.fx -= fx;
  10225. node2.fy -= fy;
  10226. },
  10227. /**
  10228. * Load the HTML for the physics config and bind it
  10229. * @private
  10230. */
  10231. _loadPhysicsConfiguration : function() {
  10232. if (this.physicsConfiguration === undefined) {
  10233. var hierarchicalLayoutDirections = ["LR","RL","UD","DU"];
  10234. this.physicsConfiguration = document.createElement('div');
  10235. this.physicsConfiguration.className = "PhysicsConfiguration";
  10236. this.physicsConfiguration.innerHTML = '' +
  10237. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  10238. '<tr>' +
  10239. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  10240. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>'+
  10241. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  10242. '</tr>'+
  10243. '</table>' +
  10244. '<table id="graph_BH_table" style="display:none">'+
  10245. '<tr><td><b>Barnes Hut</b></td></tr>'+
  10246. '<tr>'+
  10247. '<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>'+
  10248. '</tr>'+
  10249. '<tr>'+
  10250. '<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>'+
  10251. '</tr>'+
  10252. '<tr>'+
  10253. '<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>'+
  10254. '</tr>'+
  10255. '<tr>'+
  10256. '<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>'+
  10257. '</tr>'+
  10258. '<tr>'+
  10259. '<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>'+
  10260. '</tr>'+
  10261. '</table>'+
  10262. '<table id="graph_R_table" style="display:none">'+
  10263. '<tr><td><b>Repulsion</b></td></tr>'+
  10264. '<tr>'+
  10265. '<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>'+
  10266. '</tr>'+
  10267. '<tr>'+
  10268. '<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>'+
  10269. '</tr>'+
  10270. '<tr>'+
  10271. '<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>'+
  10272. '</tr>'+
  10273. '<tr>'+
  10274. '<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>'+
  10275. '</tr>'+
  10276. '<tr>'+
  10277. '<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>'+
  10278. '</tr>'+
  10279. '</table>'+
  10280. '<table id="graph_H_table" style="display:none">'+
  10281. '<tr><td width="150"><b>Hierarchical</b></td></tr>'+
  10282. '<tr>'+
  10283. '<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>'+
  10284. '</tr>'+
  10285. '<tr>'+
  10286. '<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>'+
  10287. '</tr>'+
  10288. '<tr>'+
  10289. '<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>'+
  10290. '</tr>'+
  10291. '<tr>'+
  10292. '<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>'+
  10293. '</tr>'+
  10294. '<tr>'+
  10295. '<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>'+
  10296. '</tr>'+
  10297. '<tr>'+
  10298. '<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>'+
  10299. '</tr>'+
  10300. '<tr>'+
  10301. '<td width="150px">levelSeparation</td><td>1</td><td><input type="range" min="0" max="' + this.constants.hierarchicalLayout.levelSeparation + '" value="150" 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>'+
  10302. '</tr>'+
  10303. '<tr>'+
  10304. '<td width="150px">nodeSpacing</td><td>1</td><td><input type="range" min="0" max="' + this.constants.hierarchicalLayout.nodeSpacing + '" value="100" 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>'+
  10305. '</tr>'+
  10306. '</table>'
  10307. this.containerElement.parentElement.insertBefore(this.physicsConfiguration,this.containerElement);
  10308. var rangeElement;
  10309. rangeElement = document.getElementById('graph_BH_gc');
  10310. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_gc',-1,"physics_barnesHut_gravitationalConstant");
  10311. rangeElement = document.getElementById('graph_BH_cg');
  10312. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_cg',1,"physics_centralGravity");
  10313. rangeElement = document.getElementById('graph_BH_sc');
  10314. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_sc',1,"physics_springConstant");
  10315. rangeElement = document.getElementById('graph_BH_sl');
  10316. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_sl',1,"physics_springLength");
  10317. rangeElement = document.getElementById('graph_BH_damp');
  10318. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_damp',1,"physics_damping");
  10319. rangeElement = document.getElementById('graph_R_nd');
  10320. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_nd',1,"physics_repulsion_nodeDistance");
  10321. rangeElement = document.getElementById('graph_R_cg');
  10322. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_cg',1,"physics_centralGravity");
  10323. rangeElement = document.getElementById('graph_R_sc');
  10324. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_sc',1,"physics_springConstant");
  10325. rangeElement = document.getElementById('graph_R_sl');
  10326. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_sl',1,"physics_springLength");
  10327. rangeElement = document.getElementById('graph_R_damp');
  10328. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_damp',1,"physics_damping");
  10329. rangeElement = document.getElementById('graph_H_nd');
  10330. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_nd',1,"physics_hierarchicalRepulsion_nodeDistance");
  10331. rangeElement = document.getElementById('graph_H_cg');
  10332. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_cg',1,"physics_centralGravity");
  10333. rangeElement = document.getElementById('graph_H_sc');
  10334. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_sc',1,"physics_springConstant");
  10335. rangeElement = document.getElementById('graph_H_sl');
  10336. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_sl',1,"physics_springLength");
  10337. rangeElement = document.getElementById('graph_H_damp');
  10338. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_damp',1,"physics_damping");
  10339. rangeElement = document.getElementById('graph_H_direction');
  10340. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_direction',hierarchicalLayoutDirections,"hierarchicalLayout_direction");
  10341. rangeElement = document.getElementById('graph_H_levsep');
  10342. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_levsep',1,"hierarchicalLayout_levelSeparation");
  10343. rangeElement = document.getElementById('graph_H_nspac');
  10344. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_nspac',1,"hierarchicalLayout_nodeSpacing");
  10345. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10346. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10347. var radioButton3 = document.getElementById("graph_physicsMethod3");
  10348. radioButton2.checked = true;
  10349. if (this.constants.physics.barnesHut.enabled) {
  10350. radioButton1.checked = true;
  10351. }
  10352. if (this.constants.hierarchicalLayout.enabled) {
  10353. radioButton3.checked = true;
  10354. }
  10355. switchConfigurations.apply(this);
  10356. radioButton1.onchange = switchConfigurations.bind(this);
  10357. radioButton2.onchange = switchConfigurations.bind(this);
  10358. radioButton3.onchange = switchConfigurations.bind(this);
  10359. }
  10360. },
  10361. _overWriteGraphConstants : function(constantsVariableName, value) {
  10362. var nameArray = constantsVariableName.split("_");
  10363. if (nameArray.length == 1) {
  10364. this.constants[nameArray[0]] = value;
  10365. }
  10366. else if (nameArray.length == 2) {
  10367. this.constants[nameArray[0]][nameArray[1]] = value;
  10368. }
  10369. else if (nameArray.length == 3) {
  10370. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  10371. }
  10372. }
  10373. }
  10374. function switchConfigurations () {
  10375. var ids = ["graph_BH_table","graph_R_table","graph_H_table"]
  10376. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  10377. var tableId = "graph_" + radioButton + "_table";
  10378. var table = document.getElementById(tableId);
  10379. table.style.display = "block";
  10380. for (var i = 0; i < ids.length; i++) {
  10381. if (ids[i] != tableId) {
  10382. table = document.getElementById(ids[i]);
  10383. table.style.display = "none";
  10384. }
  10385. }
  10386. this._restoreNodes();
  10387. if (radioButton == "R") {
  10388. this.constants.hierarchicalLayout.enabled = false;
  10389. this.constants.physics.hierarchicalRepulsion.enabeled = false;
  10390. this.constants.physics.barnesHut.enabled = false;
  10391. }
  10392. else if (radioButton == "H") {
  10393. this.constants.hierarchicalLayout.enabled = true;
  10394. this.constants.physics.hierarchicalRepulsion.enabeled = true;
  10395. this.constants.physics.barnesHut.enabled = false;
  10396. this._setupHierarchicalLayout();
  10397. }
  10398. else {
  10399. this.constants.hierarchicalLayout.enabled = false;
  10400. this.constants.physics.hierarchicalRepulsion.enabeled = false;
  10401. this.constants.physics.barnesHut.enabled = true;
  10402. }
  10403. this._loadSelectedForceSolver();
  10404. this.moving = true;
  10405. this.start();
  10406. }
  10407. function showValueOfRange (id,map,constantsVariableName) {
  10408. var valueId = id + "_value";
  10409. var rangeValue = document.getElementById(id).value;
  10410. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10411. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10412. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10413. this._setupHierarchicalLayout();
  10414. }
  10415. if (map instanceof Array) {
  10416. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  10417. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  10418. }
  10419. else {
  10420. document.getElementById(valueId).value = map * parseFloat(rangeValue);
  10421. this._overWriteGraphConstants(constantsVariableName,map * parseFloat(rangeValue));
  10422. }
  10423. this.moving = true;
  10424. this.start();
  10425. };
  10426. /**
  10427. * Created by Alex on 2/10/14.
  10428. */
  10429. var hierarchalRepulsionMixin = {
  10430. /**
  10431. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10432. * This field is linearly approximated.
  10433. *
  10434. * @private
  10435. */
  10436. _calculateNodeForces : function() {
  10437. var dx, dy, distance, fx, fy, combinedClusterSize,
  10438. repulsingForce, node1, node2, i, j;
  10439. var nodes = this.calculationNodes;
  10440. var nodeIndices = this.calculationNodeIndices;
  10441. // approximation constants
  10442. var b = 5;
  10443. var a_base = 0.5*-b;
  10444. // repulsing forces between nodes
  10445. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  10446. var minimumDistance = nodeDistance;
  10447. // we loop from i over all but the last entree in the array
  10448. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10449. for (i = 0; i < nodeIndices.length-1; i++) {
  10450. node1 = nodes[nodeIndices[i]];
  10451. for (j = i+1; j < nodeIndices.length; j++) {
  10452. node2 = nodes[nodeIndices[j]];
  10453. dx = node2.x - node1.x;
  10454. dy = node2.y - node1.y;
  10455. distance = Math.sqrt(dx * dx + dy * dy);
  10456. var a = a_base / minimumDistance;
  10457. if (distance < 2*minimumDistance) {
  10458. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10459. // normalize force with
  10460. if (distance == 0) {
  10461. distance = 0.01;
  10462. }
  10463. else {
  10464. repulsingForce = repulsingForce/distance;
  10465. }
  10466. fx = dx * repulsingForce;
  10467. fy = dy * repulsingForce;
  10468. node1.fx -= fx;
  10469. node1.fy -= fy;
  10470. node2.fx += fx;
  10471. node2.fy += fy;
  10472. }
  10473. }
  10474. }
  10475. }
  10476. }
  10477. /**
  10478. * Created by Alex on 2/10/14.
  10479. */
  10480. var barnesHutMixin = {
  10481. /**
  10482. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10483. * The Barnes Hut method is used to speed up this N-body simulation.
  10484. *
  10485. * @private
  10486. */
  10487. _calculateNodeForces : function() {
  10488. var node;
  10489. var nodes = this.calculationNodes;
  10490. var nodeIndices = this.calculationNodeIndices;
  10491. var nodeCount = nodeIndices.length;
  10492. this._formBarnesHutTree(nodes,nodeIndices);
  10493. var barnesHutTree = this.barnesHutTree;
  10494. // place the nodes one by one recursively
  10495. for (var i = 0; i < nodeCount; i++) {
  10496. node = nodes[nodeIndices[i]];
  10497. // starting with root is irrelevant, it never passes the BarnesHut condition
  10498. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10499. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10500. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10501. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10502. }
  10503. },
  10504. /**
  10505. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10506. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10507. *
  10508. * @param parentBranch
  10509. * @param node
  10510. * @private
  10511. */
  10512. _getForceContribution : function(parentBranch,node) {
  10513. // we get no force contribution from an empty region
  10514. if (parentBranch.childrenCount > 0) {
  10515. var dx,dy,distance;
  10516. // get the distance from the center of mass to the node.
  10517. dx = parentBranch.centerOfMass.x - node.x;
  10518. dy = parentBranch.centerOfMass.y - node.y;
  10519. distance = Math.sqrt(dx * dx + dy * dy);
  10520. // BarnesHut condition
  10521. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10522. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10523. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10524. // duplicate code to reduce function calls to speed up program
  10525. if (distance == 0) {
  10526. distance = 0.1*Math.random();
  10527. dx = distance;
  10528. }
  10529. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10530. var fx = dx * gravityForce;
  10531. var fy = dy * gravityForce;
  10532. node.fx += fx;
  10533. node.fy += fy;
  10534. }
  10535. else {
  10536. // Did not pass the condition, go into children if available
  10537. if (parentBranch.childrenCount == 4) {
  10538. this._getForceContribution(parentBranch.children.NW,node);
  10539. this._getForceContribution(parentBranch.children.NE,node);
  10540. this._getForceContribution(parentBranch.children.SW,node);
  10541. this._getForceContribution(parentBranch.children.SE,node);
  10542. }
  10543. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10544. if (parentBranch.children.data.id != node.id) { // if it is not self
  10545. // duplicate code to reduce function calls to speed up program
  10546. if (distance == 0) {
  10547. distance = 0.5*Math.random();
  10548. dx = distance;
  10549. }
  10550. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10551. var fx = dx * gravityForce;
  10552. var fy = dy * gravityForce;
  10553. node.fx += fx;
  10554. node.fy += fy;
  10555. }
  10556. }
  10557. }
  10558. }
  10559. },
  10560. /**
  10561. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10562. *
  10563. * @param nodes
  10564. * @param nodeIndices
  10565. * @private
  10566. */
  10567. _formBarnesHutTree : function(nodes,nodeIndices) {
  10568. var node;
  10569. var nodeCount = nodeIndices.length;
  10570. var minX = Number.MAX_VALUE,
  10571. minY = Number.MAX_VALUE,
  10572. maxX =-Number.MAX_VALUE,
  10573. maxY =-Number.MAX_VALUE;
  10574. // get the range of the nodes
  10575. for (var i = 0; i < nodeCount; i++) {
  10576. var x = nodes[nodeIndices[i]].x;
  10577. var y = nodes[nodeIndices[i]].y;
  10578. if (x < minX) { minX = x; }
  10579. if (x > maxX) { maxX = x; }
  10580. if (y < minY) { minY = y; }
  10581. if (y > maxY) { maxY = y; }
  10582. }
  10583. // make the range a square
  10584. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10585. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10586. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10587. var minimumTreeSize = 1e-5;
  10588. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10589. var halfRootSize = 0.5 * rootSize;
  10590. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10591. // construct the barnesHutTree
  10592. var barnesHutTree = {root:{
  10593. centerOfMass:{x:0,y:0}, // Center of Mass
  10594. mass:0,
  10595. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10596. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10597. size: rootSize,
  10598. calcSize: 1 / rootSize,
  10599. children: {data:null},
  10600. maxWidth: 0,
  10601. level: 0,
  10602. childrenCount: 4
  10603. }};
  10604. this._splitBranch(barnesHutTree.root);
  10605. // place the nodes one by one recursively
  10606. for (i = 0; i < nodeCount; i++) {
  10607. node = nodes[nodeIndices[i]];
  10608. this._placeInTree(barnesHutTree.root,node);
  10609. }
  10610. // make global
  10611. this.barnesHutTree = barnesHutTree
  10612. },
  10613. _updateBranchMass : function(parentBranch, node) {
  10614. var totalMass = parentBranch.mass + node.mass;
  10615. var totalMassInv = 1/totalMass;
  10616. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10617. parentBranch.centerOfMass.x *= totalMassInv;
  10618. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10619. parentBranch.centerOfMass.y *= totalMassInv;
  10620. parentBranch.mass = totalMass;
  10621. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10622. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10623. },
  10624. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10625. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10626. // update the mass of the branch.
  10627. this._updateBranchMass(parentBranch,node);
  10628. }
  10629. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10630. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10631. this._placeInRegion(parentBranch,node,"NW");
  10632. }
  10633. else { // in SW
  10634. this._placeInRegion(parentBranch,node,"SW");
  10635. }
  10636. }
  10637. else { // in NE or SE
  10638. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10639. this._placeInRegion(parentBranch,node,"NE");
  10640. }
  10641. else { // in SE
  10642. this._placeInRegion(parentBranch,node,"SE");
  10643. }
  10644. }
  10645. },
  10646. _placeInRegion : function(parentBranch,node,region) {
  10647. switch (parentBranch.children[region].childrenCount) {
  10648. case 0: // place node here
  10649. parentBranch.children[region].children.data = node;
  10650. parentBranch.children[region].childrenCount = 1;
  10651. this._updateBranchMass(parentBranch.children[region],node);
  10652. break;
  10653. case 1: // convert into children
  10654. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10655. // we move one node a pixel and we do not put it in the tree.
  10656. if (parentBranch.children[region].children.data.x == node.x &&
  10657. parentBranch.children[region].children.data.y == node.y) {
  10658. node.x += Math.random();
  10659. node.y += Math.random();
  10660. this._placeInTree(parentBranch,node, true);
  10661. }
  10662. else {
  10663. this._splitBranch(parentBranch.children[region]);
  10664. this._placeInTree(parentBranch.children[region],node);
  10665. }
  10666. break;
  10667. case 4: // place in branch
  10668. this._placeInTree(parentBranch.children[region],node);
  10669. break;
  10670. }
  10671. },
  10672. /**
  10673. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10674. * after the split is complete.
  10675. *
  10676. * @param parentBranch
  10677. * @private
  10678. */
  10679. _splitBranch : function(parentBranch) {
  10680. // if the branch is filled with a node, replace the node in the new subset.
  10681. var containedNode = null;
  10682. if (parentBranch.childrenCount == 1) {
  10683. containedNode = parentBranch.children.data;
  10684. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10685. }
  10686. parentBranch.childrenCount = 4;
  10687. parentBranch.children.data = null;
  10688. this._insertRegion(parentBranch,"NW");
  10689. this._insertRegion(parentBranch,"NE");
  10690. this._insertRegion(parentBranch,"SW");
  10691. this._insertRegion(parentBranch,"SE");
  10692. if (containedNode != null) {
  10693. this._placeInTree(parentBranch,containedNode);
  10694. }
  10695. },
  10696. /**
  10697. * This function subdivides the region into four new segments.
  10698. * Specifically, this inserts a single new segment.
  10699. * It fills the children section of the parentBranch
  10700. *
  10701. * @param parentBranch
  10702. * @param region
  10703. * @param parentRange
  10704. * @private
  10705. */
  10706. _insertRegion : function(parentBranch, region) {
  10707. var minX,maxX,minY,maxY;
  10708. var childSize = 0.5 * parentBranch.size;
  10709. switch (region) {
  10710. case "NW":
  10711. minX = parentBranch.range.minX;
  10712. maxX = parentBranch.range.minX + childSize;
  10713. minY = parentBranch.range.minY;
  10714. maxY = parentBranch.range.minY + childSize;
  10715. break;
  10716. case "NE":
  10717. minX = parentBranch.range.minX + childSize;
  10718. maxX = parentBranch.range.maxX;
  10719. minY = parentBranch.range.minY;
  10720. maxY = parentBranch.range.minY + childSize;
  10721. break;
  10722. case "SW":
  10723. minX = parentBranch.range.minX;
  10724. maxX = parentBranch.range.minX + childSize;
  10725. minY = parentBranch.range.minY + childSize;
  10726. maxY = parentBranch.range.maxY;
  10727. break;
  10728. case "SE":
  10729. minX = parentBranch.range.minX + childSize;
  10730. maxX = parentBranch.range.maxX;
  10731. minY = parentBranch.range.minY + childSize;
  10732. maxY = parentBranch.range.maxY;
  10733. break;
  10734. }
  10735. parentBranch.children[region] = {
  10736. centerOfMass:{x:0,y:0},
  10737. mass:0,
  10738. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10739. size: 0.5 * parentBranch.size,
  10740. calcSize: 2 * parentBranch.calcSize,
  10741. children: {data:null},
  10742. maxWidth: 0,
  10743. level: parentBranch.level+1,
  10744. childrenCount: 0
  10745. };
  10746. },
  10747. /**
  10748. * This function is for debugging purposed, it draws the tree.
  10749. *
  10750. * @param ctx
  10751. * @param color
  10752. * @private
  10753. */
  10754. _drawTree : function(ctx,color) {
  10755. if (this.barnesHutTree !== undefined) {
  10756. ctx.lineWidth = 1;
  10757. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10758. }
  10759. },
  10760. /**
  10761. * This function is for debugging purposes. It draws the branches recursively.
  10762. *
  10763. * @param branch
  10764. * @param ctx
  10765. * @param color
  10766. * @private
  10767. */
  10768. _drawBranch : function(branch,ctx,color) {
  10769. if (color === undefined) {
  10770. color = "#FF0000";
  10771. }
  10772. if (branch.childrenCount == 4) {
  10773. this._drawBranch(branch.children.NW,ctx);
  10774. this._drawBranch(branch.children.NE,ctx);
  10775. this._drawBranch(branch.children.SE,ctx);
  10776. this._drawBranch(branch.children.SW,ctx);
  10777. }
  10778. ctx.strokeStyle = color;
  10779. ctx.beginPath();
  10780. ctx.moveTo(branch.range.minX,branch.range.minY);
  10781. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10782. ctx.stroke();
  10783. ctx.beginPath();
  10784. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10785. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10786. ctx.stroke();
  10787. ctx.beginPath();
  10788. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10789. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10790. ctx.stroke();
  10791. ctx.beginPath();
  10792. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10793. ctx.lineTo(branch.range.minX,branch.range.minY);
  10794. ctx.stroke();
  10795. /*
  10796. if (branch.mass > 0) {
  10797. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  10798. ctx.stroke();
  10799. }
  10800. */
  10801. }
  10802. };
  10803. /**
  10804. * Created by Alex on 2/10/14.
  10805. */
  10806. var repulsionMixin = {
  10807. /**
  10808. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10809. * This field is linearly approximated.
  10810. *
  10811. * @private
  10812. */
  10813. _calculateNodeForces : function() {
  10814. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  10815. repulsingForce, node1, node2, i, j;
  10816. var nodes = this.calculationNodes;
  10817. var nodeIndices = this.calculationNodeIndices;
  10818. // approximation constants
  10819. var a_base = -2/3;
  10820. var b = 4/3;
  10821. // repulsing forces between nodes
  10822. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  10823. var minimumDistance = nodeDistance;
  10824. // we loop from i over all but the last entree in the array
  10825. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10826. for (i = 0; i < nodeIndices.length-1; i++) {
  10827. node1 = nodes[nodeIndices[i]];
  10828. for (j = i+1; j < nodeIndices.length; j++) {
  10829. node2 = nodes[nodeIndices[j]];
  10830. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  10831. dx = node2.x - node1.x;
  10832. dy = node2.y - node1.y;
  10833. distance = Math.sqrt(dx * dx + dy * dy);
  10834. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  10835. var a = a_base / minimumDistance;
  10836. if (distance < 2*minimumDistance) {
  10837. if (distance < 0.5*minimumDistance) {
  10838. repulsingForce = 1.0;
  10839. }
  10840. else {
  10841. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10842. }
  10843. // amplify the repulsion for clusters.
  10844. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  10845. repulsingForce = repulsingForce/distance;
  10846. fx = dx * repulsingForce;
  10847. fy = dy * repulsingForce;
  10848. node1.fx -= fx;
  10849. node1.fy -= fy;
  10850. node2.fx += fx;
  10851. node2.fy += fy;
  10852. }
  10853. }
  10854. }
  10855. }
  10856. }
  10857. var HierarchicalLayoutMixin = {
  10858. /**
  10859. * This is the main function to layout the nodes in a hierarchical way.
  10860. * It checks if the node details are supplied correctly
  10861. *
  10862. * @private
  10863. */
  10864. _setupHierarchicalLayout : function() {
  10865. if (this.constants.hierarchicalLayout.enabled == true) {
  10866. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  10867. this.constants.hierarchicalLayout.levelSeparation *= -1;
  10868. }
  10869. // get the size of the largest hubs and check if the user has defined a level for a node.
  10870. var hubsize = 0;
  10871. var node, nodeId;
  10872. var definedLevel = false;
  10873. var undefinedLevel = false;
  10874. for (nodeId in this.nodes) {
  10875. if (this.nodes.hasOwnProperty(nodeId)) {
  10876. node = this.nodes[nodeId];
  10877. if (node.level != -1) {
  10878. definedLevel = true;
  10879. }
  10880. else {
  10881. undefinedLevel = true;
  10882. }
  10883. if (hubsize < node.edges.length) {
  10884. hubsize = node.edges.length;
  10885. }
  10886. }
  10887. }
  10888. // if the user defined some levels but not all, alert and run without hierarchical layout
  10889. if (undefinedLevel == true && definedLevel == true) {
  10890. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.")
  10891. this.zoomExtent(true,this.constants.clustering.enabled);
  10892. if (!this.constants.clustering.enabled) {
  10893. this.start();
  10894. }
  10895. }
  10896. else {
  10897. // setup the system to use hierarchical method.
  10898. this._changeConstants();
  10899. // define levels if undefined by the users. Based on hubsize
  10900. if (undefinedLevel == true) {
  10901. this._determineLevels(hubsize);
  10902. }
  10903. // check the distribution of the nodes per level.
  10904. var distribution = this._getDistribution();
  10905. // place the nodes on the canvas. This also stablilizes the system.
  10906. this._placeNodesByHierarchy(distribution);
  10907. // start the simulation.
  10908. this.start();
  10909. }
  10910. }
  10911. },
  10912. /**
  10913. * This function places the nodes on the canvas based on the hierarchial distribution.
  10914. *
  10915. * @param {Object} distribution | obtained by the function this._getDistribution()
  10916. * @private
  10917. */
  10918. _placeNodesByHierarchy : function(distribution) {
  10919. var nodeId, node;
  10920. // start placing all the level 0 nodes first. Then recursively position their branches.
  10921. for (nodeId in distribution[0].nodes) {
  10922. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  10923. node = distribution[0].nodes[nodeId];
  10924. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10925. if (node.xFixed) {
  10926. node.x = distribution[0].minPos;
  10927. node.xFixed = false;
  10928. distribution[0].minPos += distribution[0].nodeSpacing;
  10929. }
  10930. }
  10931. else {
  10932. if (node.yFixed) {
  10933. node.y = distribution[0].minPos;
  10934. node.yFixed = false;
  10935. distribution[0].minPos += distribution[0].nodeSpacing;
  10936. }
  10937. }
  10938. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  10939. }
  10940. }
  10941. // stabilize the system after positioning. This function calls zoomExtent.
  10942. this._doStabilize();
  10943. },
  10944. /**
  10945. * This function get the distribution of levels based on hubsize
  10946. *
  10947. * @returns {Object}
  10948. * @private
  10949. */
  10950. _getDistribution : function() {
  10951. var distribution = {};
  10952. var nodeId, node;
  10953. // 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.
  10954. // the fix of X is removed after the x value has been set.
  10955. for (nodeId in this.nodes) {
  10956. if (this.nodes.hasOwnProperty(nodeId)) {
  10957. node = this.nodes[nodeId];
  10958. node.xFixed = true;
  10959. node.yFixed = true;
  10960. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  10961. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10962. }
  10963. else {
  10964. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  10965. }
  10966. if (!distribution.hasOwnProperty(node.level)) {
  10967. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  10968. }
  10969. distribution[node.level].amount += 1;
  10970. distribution[node.level].nodes[node.id] = node;
  10971. }
  10972. }
  10973. // determine the largest amount of nodes of all levels
  10974. var maxCount = 0;
  10975. for (var level in distribution) {
  10976. if (distribution.hasOwnProperty(level)) {
  10977. if (maxCount < distribution[level].amount) {
  10978. maxCount = distribution[level].amount;
  10979. }
  10980. }
  10981. }
  10982. // set the initial position and spacing of each nodes accordingly
  10983. for (var level in distribution) {
  10984. if (distribution.hasOwnProperty(level)) {
  10985. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  10986. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  10987. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  10988. }
  10989. }
  10990. return distribution;
  10991. },
  10992. /**
  10993. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  10994. *
  10995. * @param hubsize
  10996. * @private
  10997. */
  10998. _determineLevels : function(hubsize) {
  10999. var nodeId, node;
  11000. // determine hubs
  11001. for (nodeId in this.nodes) {
  11002. if (this.nodes.hasOwnProperty(nodeId)) {
  11003. node = this.nodes[nodeId];
  11004. if (node.edges.length == hubsize) {
  11005. node.level = 0;
  11006. }
  11007. }
  11008. }
  11009. // branch from hubs
  11010. for (nodeId in this.nodes) {
  11011. if (this.nodes.hasOwnProperty(nodeId)) {
  11012. node = this.nodes[nodeId];
  11013. if (node.level == 0) {
  11014. this._setLevel(1,node.edges,node.id);
  11015. }
  11016. }
  11017. }
  11018. },
  11019. /**
  11020. * Since hierarchical layout does not support:
  11021. * - smooth curves (based on the physics),
  11022. * - clustering (based on dynamic node counts)
  11023. *
  11024. * We disable both features so there will be no problems.
  11025. *
  11026. * @private
  11027. */
  11028. _changeConstants : function() {
  11029. this.constants.clustering.enabled = false;
  11030. this.constants.physics.barnesHut.enabled = false;
  11031. this.constants.physics.hierarchicalRepulsion.enabled = true;
  11032. this._loadSelectedForceSolver();
  11033. this.constants.smoothCurves = false;
  11034. this._configureSmoothCurves();
  11035. },
  11036. /**
  11037. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  11038. * on a X position that ensures there will be no overlap.
  11039. *
  11040. * @param edges
  11041. * @param parentId
  11042. * @param distribution
  11043. * @param parentLevel
  11044. * @private
  11045. */
  11046. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  11047. for (var i = 0; i < edges.length; i++) {
  11048. var childNode = null;
  11049. if (edges[i].toId == parentId) {
  11050. childNode = edges[i].from;
  11051. }
  11052. else {
  11053. childNode = edges[i].to;
  11054. }
  11055. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  11056. var nodeMoved = false;
  11057. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11058. if (childNode.xFixed && childNode.level > parentLevel) {
  11059. childNode.xFixed = false;
  11060. childNode.x = distribution[childNode.level].minPos;
  11061. nodeMoved = true;
  11062. }
  11063. }
  11064. else {
  11065. if (childNode.yFixed && childNode.level > parentLevel) {
  11066. childNode.yFixed = false;
  11067. childNode.y = distribution[childNode.level].minPos;
  11068. nodeMoved = true;
  11069. }
  11070. }
  11071. if (nodeMoved == true) {
  11072. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  11073. if (childNode.edges.length > 1) {
  11074. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  11075. }
  11076. }
  11077. }
  11078. },
  11079. /**
  11080. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  11081. *
  11082. * @param level
  11083. * @param edges
  11084. * @param parentId
  11085. * @private
  11086. */
  11087. _setLevel : function(level, edges, parentId) {
  11088. for (var i = 0; i < edges.length; i++) {
  11089. var childNode = null;
  11090. if (edges[i].toId == parentId) {
  11091. childNode = edges[i].from;
  11092. }
  11093. else {
  11094. childNode = edges[i].to;
  11095. }
  11096. if (childNode.level == -1 || childNode.level > level) {
  11097. childNode.level = level;
  11098. if (edges.length > 1) {
  11099. this._setLevel(level+1, childNode.edges, childNode.id);
  11100. }
  11101. }
  11102. }
  11103. },
  11104. /**
  11105. * Unfix nodes
  11106. *
  11107. * @private
  11108. */
  11109. _restoreNodes : function() {
  11110. for (nodeId in this.nodes) {
  11111. if (this.nodes.hasOwnProperty(nodeId)) {
  11112. this.nodes[nodeId].xFixed = false;
  11113. this.nodes[nodeId].yFixed = false;
  11114. }
  11115. }
  11116. }
  11117. };
  11118. /**
  11119. * Created by Alex on 2/4/14.
  11120. */
  11121. var manipulationMixin = {
  11122. /**
  11123. * clears the toolbar div element of children
  11124. *
  11125. * @private
  11126. */
  11127. _clearManipulatorBar : function() {
  11128. while (this.manipulationDiv.hasChildNodes()) {
  11129. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11130. }
  11131. },
  11132. /**
  11133. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  11134. * these functions to their original functionality, we saved them in this.cachedFunctions.
  11135. * This function restores these functions to their original function.
  11136. *
  11137. * @private
  11138. */
  11139. _restoreOverloadedFunctions : function() {
  11140. for (var functionName in this.cachedFunctions) {
  11141. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  11142. this[functionName] = this.cachedFunctions[functionName];
  11143. }
  11144. }
  11145. },
  11146. /**
  11147. * Enable or disable edit-mode.
  11148. *
  11149. * @private
  11150. */
  11151. _toggleEditMode : function() {
  11152. this.editMode = !this.editMode;
  11153. var toolbar = document.getElementById("graph-manipulationDiv");
  11154. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11155. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  11156. if (this.editMode == true) {
  11157. toolbar.style.display="block";
  11158. closeDiv.style.display="block";
  11159. editModeDiv.style.display="none";
  11160. closeDiv.onclick = this._toggleEditMode.bind(this);
  11161. }
  11162. else {
  11163. toolbar.style.display="none";
  11164. closeDiv.style.display="none";
  11165. editModeDiv.style.display="block";
  11166. closeDiv.onclick = null;
  11167. }
  11168. this._createManipulatorBar()
  11169. },
  11170. /**
  11171. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  11172. *
  11173. * @private
  11174. */
  11175. _createManipulatorBar : function() {
  11176. // remove bound functions
  11177. this.off('select', this.boundFunction);
  11178. // restore overloaded functions
  11179. this._restoreOverloadedFunctions();
  11180. // resume calculation
  11181. this.freezeSimulation = false;
  11182. // reset global variables
  11183. this.blockConnectingEdgeSelection = false;
  11184. this.forceAppendSelection = false
  11185. if (this.editMode == true) {
  11186. while (this.manipulationDiv.hasChildNodes()) {
  11187. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11188. }
  11189. // add the icons to the manipulator div
  11190. this.manipulationDiv.innerHTML = "" +
  11191. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  11192. "<span class='graph-manipulationLabel'>Add Node</span></span>" +
  11193. "<div class='graph-seperatorLine'></div>" +
  11194. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  11195. "<span class='graph-manipulationLabel'>Add Link</span></span>";
  11196. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11197. this.manipulationDiv.innerHTML += "" +
  11198. "<div class='graph-seperatorLine'></div>" +
  11199. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  11200. "<span class='graph-manipulationLabel'>Edit Node</span></span>";
  11201. }
  11202. if (this._selectionIsEmpty() == false) {
  11203. this.manipulationDiv.innerHTML += "" +
  11204. "<div class='graph-seperatorLine'></div>" +
  11205. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  11206. "<span class='graph-manipulationLabel'>Delete selected</span></span>";
  11207. }
  11208. // bind the icons
  11209. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  11210. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  11211. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  11212. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  11213. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11214. var editButton = document.getElementById("graph-manipulate-editNode");
  11215. editButton.onclick = this._editNode.bind(this);
  11216. }
  11217. if (this._selectionIsEmpty() == false) {
  11218. var deleteButton = document.getElementById("graph-manipulate-delete");
  11219. deleteButton.onclick = this._deleteSelected.bind(this);
  11220. }
  11221. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11222. closeDiv.onclick = this._toggleEditMode.bind(this);
  11223. this.boundFunction = this._createManipulatorBar.bind(this);
  11224. this.on('select', this.boundFunction);
  11225. }
  11226. else {
  11227. this.editModeDiv.innerHTML = "" +
  11228. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  11229. "<span class='graph-manipulationLabel'>Edit</span></span>"
  11230. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  11231. editModeButton.onclick = this._toggleEditMode.bind(this);
  11232. }
  11233. },
  11234. /**
  11235. * Create the toolbar for adding Nodes
  11236. *
  11237. * @private
  11238. */
  11239. _createAddNodeToolbar : function() {
  11240. // clear the toolbar
  11241. this._clearManipulatorBar();
  11242. this.off('select', this.boundFunction);
  11243. // create the toolbar contents
  11244. this.manipulationDiv.innerHTML = "" +
  11245. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11246. "<span class='graph-manipulationLabel'>Back</span></span>" +
  11247. "<div class='graph-seperatorLine'></div>" +
  11248. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11249. "<span class='graph-manipulationLabel'>Click in an empty space to place a new node</span></span>";
  11250. // bind the icon
  11251. var backButton = document.getElementById("graph-manipulate-back");
  11252. backButton.onclick = this._createManipulatorBar.bind(this);
  11253. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11254. this.boundFunction = this._addNode.bind(this);
  11255. this.on('select', this.boundFunction);
  11256. },
  11257. /**
  11258. * create the toolbar to connect nodes
  11259. *
  11260. * @private
  11261. */
  11262. _createAddEdgeToolbar : function() {
  11263. // clear the toolbar
  11264. this._clearManipulatorBar();
  11265. this._unselectAll(true);
  11266. this.freezeSimulation = true;
  11267. this.off('select', this.boundFunction);
  11268. this._unselectAll();
  11269. this.forceAppendSelection = false;
  11270. this.blockConnectingEdgeSelection = true;
  11271. this.manipulationDiv.innerHTML = "" +
  11272. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11273. "<span class='graph-manipulationLabel'>Back</span></span>" +
  11274. "<div class='graph-seperatorLine'></div>" +
  11275. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11276. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>Click on a node and drag the edge to another node to connect them.</span></span>";
  11277. // bind the icon
  11278. var backButton = document.getElementById("graph-manipulate-back");
  11279. backButton.onclick = this._createManipulatorBar.bind(this);
  11280. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11281. this.boundFunction = this._handleConnect.bind(this);
  11282. this.on('select', this.boundFunction);
  11283. // temporarily overload functions
  11284. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  11285. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  11286. this._handleTouch = this._handleConnect;
  11287. this._handleOnRelease = this._finishConnect;
  11288. // redraw to show the unselect
  11289. this._redraw();
  11290. },
  11291. /**
  11292. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11293. * to walk the user through the process.
  11294. *
  11295. * @private
  11296. */
  11297. _handleConnect : function(pointer) {
  11298. if (this._getSelectedNodeCount() == 0) {
  11299. var node = this._getNodeAt(pointer);
  11300. if (node != null) {
  11301. if (node.clusterSize > 1) {
  11302. alert("Cannot create edges to a cluster.")
  11303. }
  11304. else {
  11305. this._selectObject(node,false);
  11306. // create a node the temporary line can look at
  11307. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11308. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11309. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11310. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11311. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11312. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11313. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11314. // create a temporary edge
  11315. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11316. this.edges['connectionEdge'].from = node;
  11317. this.edges['connectionEdge'].connected = true;
  11318. this.edges['connectionEdge'].smooth = true;
  11319. this.edges['connectionEdge'].selected = true;
  11320. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11321. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11322. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11323. this._handleOnDrag = function(event) {
  11324. var pointer = this._getPointer(event.gesture.center);
  11325. this.sectors['support']['nodes']['targetNode'].x = this._canvasToX(pointer.x);
  11326. this.sectors['support']['nodes']['targetNode'].y = this._canvasToY(pointer.y);
  11327. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._canvasToX(pointer.x) + this.edges['connectionEdge'].from.x);
  11328. this.sectors['support']['nodes']['targetViaNode'].y = this._canvasToY(pointer.y);
  11329. };
  11330. this.moving = true;
  11331. this.start();
  11332. }
  11333. }
  11334. }
  11335. },
  11336. _finishConnect : function(pointer) {
  11337. if (this._getSelectedNodeCount() == 1) {
  11338. // restore the drag function
  11339. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11340. delete this.cachedFunctions["_handleOnDrag"];
  11341. // remember the edge id
  11342. var connectFromId = this.edges['connectionEdge'].fromId;
  11343. // remove the temporary nodes and edge
  11344. delete this.edges['connectionEdge']
  11345. delete this.sectors['support']['nodes']['targetNode'];
  11346. delete this.sectors['support']['nodes']['targetViaNode'];
  11347. var node = this._getNodeAt(pointer);
  11348. if (node != null) {
  11349. if (node.clusterSize > 1) {
  11350. alert("Cannot create edges to a cluster.")
  11351. }
  11352. else {
  11353. this._createEdge(connectFromId,node.id);
  11354. this._createManipulatorBar();
  11355. }
  11356. }
  11357. this._unselectAll();
  11358. }
  11359. },
  11360. /**
  11361. * Adds a node on the specified location
  11362. *
  11363. * @param {Object} pointer
  11364. */
  11365. _addNode : function() {
  11366. if (this._selectionIsEmpty() && this.editMode == true) {
  11367. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11368. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMove:true};
  11369. if (this.triggerFunctions.add) {
  11370. if (this.triggerFunctions.add.length == 2) {
  11371. var me = this;
  11372. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11373. me.createNodeOnClick = true;
  11374. me.nodesData.add(finalizedData);
  11375. me.createNodeOnClick = false;
  11376. me._createManipulatorBar();
  11377. me.moving = true;
  11378. me.start();
  11379. });
  11380. }
  11381. else {
  11382. alert("The function for add does not support two arguments (data,callback).");
  11383. this._createManipulatorBar();
  11384. this.moving = true;
  11385. this.start();
  11386. }
  11387. }
  11388. else {
  11389. this.createNodeOnClick = true;
  11390. this.nodesData.add(defaultData);
  11391. this.createNodeOnClick = false;
  11392. this._createManipulatorBar();
  11393. this.moving = true;
  11394. this.start();
  11395. }
  11396. }
  11397. },
  11398. /**
  11399. * connect two nodes with a new edge.
  11400. *
  11401. * @private
  11402. */
  11403. _createEdge : function(sourceNodeId,targetNodeId) {
  11404. if (this.editMode == true) {
  11405. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11406. if (this.triggerFunctions.connect) {
  11407. if (this.triggerFunctions.connect.length == 2) {
  11408. var me = this;
  11409. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11410. me.edgesData.add(finalizedData)
  11411. me.moving = true;
  11412. me.start();
  11413. });
  11414. }
  11415. else {
  11416. alert("The function for connect does not support two arguments (data,callback).");
  11417. this.moving = true;
  11418. this.start();
  11419. }
  11420. }
  11421. else {
  11422. this.edgesData.add(defaultData)
  11423. this.moving = true;
  11424. this.start();
  11425. }
  11426. }
  11427. },
  11428. /**
  11429. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11430. *
  11431. * @private
  11432. */
  11433. _editNode : function() {
  11434. if (this.triggerFunctions.edit && this.editMode == true) {
  11435. var node = this._getSelectedNode();
  11436. var data = {id:node.id,
  11437. label: node.label,
  11438. group: node.group,
  11439. shape: node.shape,
  11440. color: {
  11441. background:node.color.background,
  11442. border:node.color.border,
  11443. highlight: {
  11444. background:node.color.highlight.background,
  11445. border:node.color.highlight.border
  11446. }
  11447. }};
  11448. if (this.triggerFunctions.edit.length == 2) {
  11449. var me = this;
  11450. this.triggerFunctions.edit(data, function (finalizedData) {
  11451. me.nodesData.update(finalizedData);
  11452. me._createManipulatorBar();
  11453. me.moving = true;
  11454. me.start();
  11455. });
  11456. }
  11457. else {
  11458. alert("The function for edit does not support two arguments (data, callback).")
  11459. }
  11460. }
  11461. else {
  11462. alert("No edit function has been bound to this button.")
  11463. }
  11464. },
  11465. /**
  11466. * delete everything in the selection
  11467. *
  11468. * @private
  11469. */
  11470. _deleteSelected : function() {
  11471. if (!this._selectionIsEmpty() && this.editMode == true) {
  11472. if (!this._clusterInSelection()) {
  11473. var selectedNodes = this.getSelectedNodes();
  11474. var selectedEdges = this.getSelectedEdges();
  11475. if (this.triggerFunctions.delete) {
  11476. var me = this;
  11477. var data = {nodes: selectedNodes, edges: selectedEdges};
  11478. if (this.triggerFunctions.delete.length = 2) {
  11479. this.triggerFunctions.delete(data, function (finalizedData) {
  11480. me.edgesData.remove(finalizedData.edges);
  11481. me.nodesData.remove(finalizedData.nodes);
  11482. this._unselectAll();
  11483. me.moving = true;
  11484. me.start();
  11485. });
  11486. }
  11487. else {
  11488. alert("The function for edit does not support two arguments (data, callback).")
  11489. }
  11490. }
  11491. else {
  11492. this.edgesData.remove(selectedEdges);
  11493. this.nodesData.remove(selectedNodes);
  11494. this._unselectAll();
  11495. this.moving = true;
  11496. this.start();
  11497. }
  11498. }
  11499. else {
  11500. alert("Clusters cannot be deleted.");
  11501. }
  11502. }
  11503. }
  11504. };
  11505. /**
  11506. * Creation of the SectorMixin var.
  11507. *
  11508. * This contains all the functions the Graph object can use to employ the sector system.
  11509. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11510. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11511. *
  11512. * Alex de Mulder
  11513. * 21-01-2013
  11514. */
  11515. var SectorMixin = {
  11516. /**
  11517. * This function is only called by the setData function of the Graph object.
  11518. * This loads the global references into the active sector. This initializes the sector.
  11519. *
  11520. * @private
  11521. */
  11522. _putDataInSector : function() {
  11523. this.sectors["active"][this._sector()].nodes = this.nodes;
  11524. this.sectors["active"][this._sector()].edges = this.edges;
  11525. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11526. },
  11527. /**
  11528. * /**
  11529. * This function sets the global references to nodes, edges and nodeIndices back to
  11530. * those of the supplied (active) sector. If a type is defined, do the specific type
  11531. *
  11532. * @param {String} sectorId
  11533. * @param {String} [sectorType] | "active" or "frozen"
  11534. * @private
  11535. */
  11536. _switchToSector : function(sectorId, sectorType) {
  11537. if (sectorType === undefined || sectorType == "active") {
  11538. this._switchToActiveSector(sectorId);
  11539. }
  11540. else {
  11541. this._switchToFrozenSector(sectorId);
  11542. }
  11543. },
  11544. /**
  11545. * This function sets the global references to nodes, edges and nodeIndices back to
  11546. * those of the supplied active sector.
  11547. *
  11548. * @param sectorId
  11549. * @private
  11550. */
  11551. _switchToActiveSector : function(sectorId) {
  11552. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11553. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11554. this.edges = this.sectors["active"][sectorId]["edges"];
  11555. },
  11556. /**
  11557. * This function sets the global references to nodes, edges and nodeIndices back to
  11558. * those of the supplied active sector.
  11559. *
  11560. * @param sectorId
  11561. * @private
  11562. */
  11563. _switchToSupportSector : function() {
  11564. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11565. this.nodes = this.sectors["support"]["nodes"];
  11566. this.edges = this.sectors["support"]["edges"];
  11567. },
  11568. /**
  11569. * This function sets the global references to nodes, edges and nodeIndices back to
  11570. * those of the supplied frozen sector.
  11571. *
  11572. * @param sectorId
  11573. * @private
  11574. */
  11575. _switchToFrozenSector : function(sectorId) {
  11576. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11577. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11578. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11579. },
  11580. /**
  11581. * This function sets the global references to nodes, edges and nodeIndices back to
  11582. * those of the currently active sector.
  11583. *
  11584. * @private
  11585. */
  11586. _loadLatestSector : function() {
  11587. this._switchToSector(this._sector());
  11588. },
  11589. /**
  11590. * This function returns the currently active sector Id
  11591. *
  11592. * @returns {String}
  11593. * @private
  11594. */
  11595. _sector : function() {
  11596. return this.activeSector[this.activeSector.length-1];
  11597. },
  11598. /**
  11599. * This function returns the previously active sector Id
  11600. *
  11601. * @returns {String}
  11602. * @private
  11603. */
  11604. _previousSector : function() {
  11605. if (this.activeSector.length > 1) {
  11606. return this.activeSector[this.activeSector.length-2];
  11607. }
  11608. else {
  11609. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11610. }
  11611. },
  11612. /**
  11613. * We add the active sector at the end of the this.activeSector array
  11614. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11615. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11616. *
  11617. * @param newId
  11618. * @private
  11619. */
  11620. _setActiveSector : function(newId) {
  11621. this.activeSector.push(newId);
  11622. },
  11623. /**
  11624. * We remove the currently active sector id from the active sector stack. This happens when
  11625. * we reactivate the previously active sector
  11626. *
  11627. * @private
  11628. */
  11629. _forgetLastSector : function() {
  11630. this.activeSector.pop();
  11631. },
  11632. /**
  11633. * This function creates a new active sector with the supplied newId. This newId
  11634. * is the expanding node id.
  11635. *
  11636. * @param {String} newId | Id of the new active sector
  11637. * @private
  11638. */
  11639. _createNewSector : function(newId) {
  11640. // create the new sector
  11641. this.sectors["active"][newId] = {"nodes":{},
  11642. "edges":{},
  11643. "nodeIndices":[],
  11644. "formationScale": this.scale,
  11645. "drawingNode": undefined};
  11646. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11647. this.sectors["active"][newId]['drawingNode'] = new Node(
  11648. {id:newId,
  11649. color: {
  11650. background: "#eaefef",
  11651. border: "495c5e"
  11652. }
  11653. },{},{},this.constants);
  11654. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11655. },
  11656. /**
  11657. * This function removes the currently active sector. This is called when we create a new
  11658. * active sector.
  11659. *
  11660. * @param {String} sectorId | Id of the active sector that will be removed
  11661. * @private
  11662. */
  11663. _deleteActiveSector : function(sectorId) {
  11664. delete this.sectors["active"][sectorId];
  11665. },
  11666. /**
  11667. * This function removes the currently active sector. This is called when we reactivate
  11668. * the previously active sector.
  11669. *
  11670. * @param {String} sectorId | Id of the active sector that will be removed
  11671. * @private
  11672. */
  11673. _deleteFrozenSector : function(sectorId) {
  11674. delete this.sectors["frozen"][sectorId];
  11675. },
  11676. /**
  11677. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11678. * We copy the references, then delete the active entree.
  11679. *
  11680. * @param sectorId
  11681. * @private
  11682. */
  11683. _freezeSector : function(sectorId) {
  11684. // we move the set references from the active to the frozen stack.
  11685. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11686. // we have moved the sector data into the frozen set, we now remove it from the active set
  11687. this._deleteActiveSector(sectorId);
  11688. },
  11689. /**
  11690. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11691. * object to the "active" object.
  11692. *
  11693. * @param sectorId
  11694. * @private
  11695. */
  11696. _activateSector : function(sectorId) {
  11697. // we move the set references from the frozen to the active stack.
  11698. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11699. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11700. this._deleteFrozenSector(sectorId);
  11701. },
  11702. /**
  11703. * This function merges the data from the currently active sector with a frozen sector. This is used
  11704. * in the process of reverting back to the previously active sector.
  11705. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11706. * upon the creation of a new active sector.
  11707. *
  11708. * @param sectorId
  11709. * @private
  11710. */
  11711. _mergeThisWithFrozen : function(sectorId) {
  11712. // copy all nodes
  11713. for (var nodeId in this.nodes) {
  11714. if (this.nodes.hasOwnProperty(nodeId)) {
  11715. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11716. }
  11717. }
  11718. // copy all edges (if not fully clustered, else there are no edges)
  11719. for (var edgeId in this.edges) {
  11720. if (this.edges.hasOwnProperty(edgeId)) {
  11721. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11722. }
  11723. }
  11724. // merge the nodeIndices
  11725. for (var i = 0; i < this.nodeIndices.length; i++) {
  11726. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11727. }
  11728. },
  11729. /**
  11730. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11731. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11732. *
  11733. * @private
  11734. */
  11735. _collapseThisToSingleCluster : function() {
  11736. this.clusterToFit(1,false);
  11737. },
  11738. /**
  11739. * We create a new active sector from the node that we want to open.
  11740. *
  11741. * @param node
  11742. * @private
  11743. */
  11744. _addSector : function(node) {
  11745. // this is the currently active sector
  11746. var sector = this._sector();
  11747. // // this should allow me to select nodes from a frozen set.
  11748. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11749. // console.log("the node is part of the active sector");
  11750. // }
  11751. // else {
  11752. // console.log("I dont know what the fuck happened!!");
  11753. // }
  11754. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11755. delete this.nodes[node.id];
  11756. var unqiueIdentifier = util.randomUUID();
  11757. // we fully freeze the currently active sector
  11758. this._freezeSector(sector);
  11759. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11760. this._createNewSector(unqiueIdentifier);
  11761. // we add the active sector to the sectors array to be able to revert these steps later on
  11762. this._setActiveSector(unqiueIdentifier);
  11763. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11764. this._switchToSector(this._sector());
  11765. // finally we add the node we removed from our previous active sector to the new active sector
  11766. this.nodes[node.id] = node;
  11767. },
  11768. /**
  11769. * We close the sector that is currently open and revert back to the one before.
  11770. * If the active sector is the "default" sector, nothing happens.
  11771. *
  11772. * @private
  11773. */
  11774. _collapseSector : function() {
  11775. // the currently active sector
  11776. var sector = this._sector();
  11777. // we cannot collapse the default sector
  11778. if (sector != "default") {
  11779. if ((this.nodeIndices.length == 1) ||
  11780. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11781. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11782. var previousSector = this._previousSector();
  11783. // we collapse the sector back to a single cluster
  11784. this._collapseThisToSingleCluster();
  11785. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  11786. // This previous sector is the one we will reactivate
  11787. this._mergeThisWithFrozen(previousSector);
  11788. // the previously active (frozen) sector now has all the data from the currently active sector.
  11789. // we can now delete the active sector.
  11790. this._deleteActiveSector(sector);
  11791. // we activate the previously active (and currently frozen) sector.
  11792. this._activateSector(previousSector);
  11793. // we load the references from the newly active sector into the global references
  11794. this._switchToSector(previousSector);
  11795. // we forget the previously active sector because we reverted to the one before
  11796. this._forgetLastSector();
  11797. // finally, we update the node index list.
  11798. this._updateNodeIndexList();
  11799. // we refresh the list with calulation nodes and calculation node indices.
  11800. this._updateCalculationNodes();
  11801. }
  11802. }
  11803. },
  11804. /**
  11805. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11806. *
  11807. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11808. * | we dont pass the function itself because then the "this" is the window object
  11809. * | instead of the Graph object
  11810. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11811. * @private
  11812. */
  11813. _doInAllActiveSectors : function(runFunction,argument) {
  11814. if (argument === undefined) {
  11815. for (var sector in this.sectors["active"]) {
  11816. if (this.sectors["active"].hasOwnProperty(sector)) {
  11817. // switch the global references to those of this sector
  11818. this._switchToActiveSector(sector);
  11819. this[runFunction]();
  11820. }
  11821. }
  11822. }
  11823. else {
  11824. for (var sector in this.sectors["active"]) {
  11825. if (this.sectors["active"].hasOwnProperty(sector)) {
  11826. // switch the global references to those of this sector
  11827. this._switchToActiveSector(sector);
  11828. var args = Array.prototype.splice.call(arguments, 1);
  11829. if (args.length > 1) {
  11830. this[runFunction](args[0],args[1]);
  11831. }
  11832. else {
  11833. this[runFunction](argument);
  11834. }
  11835. }
  11836. }
  11837. }
  11838. // we revert the global references back to our active sector
  11839. this._loadLatestSector();
  11840. },
  11841. /**
  11842. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  11843. *
  11844. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11845. * | we dont pass the function itself because then the "this" is the window object
  11846. * | instead of the Graph object
  11847. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11848. * @private
  11849. */
  11850. _doInSupportSector : function(runFunction,argument) {
  11851. if (argument === undefined) {
  11852. this._switchToSupportSector();
  11853. this[runFunction]();
  11854. }
  11855. else {
  11856. this._switchToSupportSector();
  11857. var args = Array.prototype.splice.call(arguments, 1);
  11858. if (args.length > 1) {
  11859. this[runFunction](args[0],args[1]);
  11860. }
  11861. else {
  11862. this[runFunction](argument);
  11863. }
  11864. }
  11865. // we revert the global references back to our active sector
  11866. this._loadLatestSector();
  11867. },
  11868. /**
  11869. * This runs a function in all frozen sectors. This is used in the _redraw().
  11870. *
  11871. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11872. * | we don't pass the function itself because then the "this" is the window object
  11873. * | instead of the Graph object
  11874. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11875. * @private
  11876. */
  11877. _doInAllFrozenSectors : function(runFunction,argument) {
  11878. if (argument === undefined) {
  11879. for (var sector in this.sectors["frozen"]) {
  11880. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11881. // switch the global references to those of this sector
  11882. this._switchToFrozenSector(sector);
  11883. this[runFunction]();
  11884. }
  11885. }
  11886. }
  11887. else {
  11888. for (var sector in this.sectors["frozen"]) {
  11889. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  11890. // switch the global references to those of this sector
  11891. this._switchToFrozenSector(sector);
  11892. var args = Array.prototype.splice.call(arguments, 1);
  11893. if (args.length > 1) {
  11894. this[runFunction](args[0],args[1]);
  11895. }
  11896. else {
  11897. this[runFunction](argument);
  11898. }
  11899. }
  11900. }
  11901. }
  11902. this._loadLatestSector();
  11903. },
  11904. /**
  11905. * This runs a function in all sectors. This is used in the _redraw().
  11906. *
  11907. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  11908. * | we don't pass the function itself because then the "this" is the window object
  11909. * | instead of the Graph object
  11910. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  11911. * @private
  11912. */
  11913. _doInAllSectors : function(runFunction,argument) {
  11914. var args = Array.prototype.splice.call(arguments, 1);
  11915. if (argument === undefined) {
  11916. this._doInAllActiveSectors(runFunction);
  11917. this._doInAllFrozenSectors(runFunction);
  11918. }
  11919. else {
  11920. if (args.length > 1) {
  11921. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  11922. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  11923. }
  11924. else {
  11925. this._doInAllActiveSectors(runFunction,argument);
  11926. this._doInAllFrozenSectors(runFunction,argument);
  11927. }
  11928. }
  11929. },
  11930. /**
  11931. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  11932. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  11933. *
  11934. * @private
  11935. */
  11936. _clearNodeIndexList : function() {
  11937. var sector = this._sector();
  11938. this.sectors["active"][sector]["nodeIndices"] = [];
  11939. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  11940. },
  11941. /**
  11942. * Draw the encompassing sector node
  11943. *
  11944. * @param ctx
  11945. * @param sectorType
  11946. * @private
  11947. */
  11948. _drawSectorNodes : function(ctx,sectorType) {
  11949. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  11950. for (var sector in this.sectors[sectorType]) {
  11951. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  11952. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  11953. this._switchToSector(sector,sectorType);
  11954. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  11955. for (var nodeId in this.nodes) {
  11956. if (this.nodes.hasOwnProperty(nodeId)) {
  11957. node = this.nodes[nodeId];
  11958. node.resize(ctx);
  11959. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  11960. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  11961. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  11962. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  11963. }
  11964. }
  11965. node = this.sectors[sectorType][sector]["drawingNode"];
  11966. node.x = 0.5 * (maxX + minX);
  11967. node.y = 0.5 * (maxY + minY);
  11968. node.width = 2 * (node.x - minX);
  11969. node.height = 2 * (node.y - minY);
  11970. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  11971. node.setScale(this.scale);
  11972. node._drawCircle(ctx);
  11973. }
  11974. }
  11975. }
  11976. },
  11977. _drawAllSectorNodes : function(ctx) {
  11978. this._drawSectorNodes(ctx,"frozen");
  11979. this._drawSectorNodes(ctx,"active");
  11980. this._loadLatestSector();
  11981. }
  11982. };
  11983. /**
  11984. * Creation of the ClusterMixin var.
  11985. *
  11986. * This contains all the functions the Graph object can use to employ clustering
  11987. *
  11988. * Alex de Mulder
  11989. * 21-01-2013
  11990. */
  11991. var ClusterMixin = {
  11992. /**
  11993. * This is only called in the constructor of the graph object
  11994. *
  11995. */
  11996. startWithClustering : function() {
  11997. // cluster if the data set is big
  11998. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  11999. // updates the lables after clustering
  12000. this.updateLabels();
  12001. // this is called here because if clusterin is disabled, the start and stabilize are called in
  12002. // the setData function.
  12003. if (this.stabilize) {
  12004. this._doStabilize();
  12005. }
  12006. this.start();
  12007. },
  12008. /**
  12009. * This function clusters until the initialMaxNodes has been reached
  12010. *
  12011. * @param {Number} maxNumberOfNodes
  12012. * @param {Boolean} reposition
  12013. */
  12014. clusterToFit : function(maxNumberOfNodes, reposition) {
  12015. var numberOfNodes = this.nodeIndices.length;
  12016. var maxLevels = 50;
  12017. var level = 0;
  12018. // we first cluster the hubs, then we pull in the outliers, repeat
  12019. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  12020. if (level % 3 == 0) {
  12021. this.forceAggregateHubs(true);
  12022. this.normalizeClusterLevels();
  12023. }
  12024. else {
  12025. this.increaseClusterLevel(); // this also includes a cluster normalization
  12026. }
  12027. numberOfNodes = this.nodeIndices.length;
  12028. level += 1;
  12029. }
  12030. // after the clustering we reposition the nodes to reduce the initial chaos
  12031. if (level > 0 && reposition == true) {
  12032. this.repositionNodes();
  12033. }
  12034. this._updateCalculationNodes();
  12035. },
  12036. /**
  12037. * This function can be called to open up a specific cluster. It is only called by
  12038. * It will unpack the cluster back one level.
  12039. *
  12040. * @param node | Node object: cluster to open.
  12041. */
  12042. openCluster : function(node) {
  12043. var isMovingBeforeClustering = this.moving;
  12044. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  12045. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  12046. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  12047. this._addSector(node);
  12048. var level = 0;
  12049. // we decluster until we reach a decent number of nodes
  12050. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  12051. this.decreaseClusterLevel();
  12052. level += 1;
  12053. }
  12054. }
  12055. else {
  12056. this._expandClusterNode(node,false,true);
  12057. // update the index list, dynamic edges and labels
  12058. this._updateNodeIndexList();
  12059. this._updateDynamicEdges();
  12060. this._updateCalculationNodes();
  12061. this.updateLabels();
  12062. }
  12063. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12064. if (this.moving != isMovingBeforeClustering) {
  12065. this.start();
  12066. }
  12067. },
  12068. /**
  12069. * This calls the updateClustes with default arguments
  12070. */
  12071. updateClustersDefault : function() {
  12072. if (this.constants.clustering.enabled == true) {
  12073. this.updateClusters(0,false,false);
  12074. }
  12075. },
  12076. /**
  12077. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  12078. * be clustered with their connected node. This can be repeated as many times as needed.
  12079. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  12080. */
  12081. increaseClusterLevel : function() {
  12082. this.updateClusters(-1,false,true);
  12083. },
  12084. /**
  12085. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  12086. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  12087. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  12088. */
  12089. decreaseClusterLevel : function() {
  12090. this.updateClusters(1,false,true);
  12091. },
  12092. /**
  12093. * This is the main clustering function. It clusters and declusters on zoom or forced
  12094. * This function clusters on zoom, it can be called with a predefined zoom direction
  12095. * If out, check if we can form clusters, if in, check if we can open clusters.
  12096. * This function is only called from _zoom()
  12097. *
  12098. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  12099. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  12100. * @param {Boolean} force | enabled or disable forcing
  12101. *
  12102. */
  12103. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  12104. var isMovingBeforeClustering = this.moving;
  12105. var amountOfNodes = this.nodeIndices.length;
  12106. // on zoom out collapse the sector if the scale is at the level the sector was made
  12107. if (this.previousScale > this.scale && zoomDirection == 0) {
  12108. this._collapseSector();
  12109. }
  12110. // check if we zoom in or out
  12111. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12112. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  12113. // outer nodes determines if it is being clustered
  12114. this._formClusters(force);
  12115. }
  12116. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  12117. if (force == true) {
  12118. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  12119. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  12120. this._openClusters(recursive,force);
  12121. }
  12122. else {
  12123. // if a cluster takes up a set percentage of the active window
  12124. this._openClustersBySize();
  12125. }
  12126. }
  12127. this._updateNodeIndexList();
  12128. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  12129. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  12130. this._aggregateHubs(force);
  12131. this._updateNodeIndexList();
  12132. }
  12133. // we now reduce chains.
  12134. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12135. this.handleChains();
  12136. this._updateNodeIndexList();
  12137. }
  12138. this.previousScale = this.scale;
  12139. // rest of the update the index list, dynamic edges and labels
  12140. this._updateDynamicEdges();
  12141. this.updateLabels();
  12142. // if a cluster was formed, we increase the clusterSession
  12143. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  12144. this.clusterSession += 1;
  12145. // if clusters have been made, we normalize the cluster level
  12146. this.normalizeClusterLevels();
  12147. }
  12148. if (doNotStart == false || doNotStart === undefined) {
  12149. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12150. if (this.moving != isMovingBeforeClustering) {
  12151. this.start();
  12152. }
  12153. }
  12154. this._updateCalculationNodes();
  12155. },
  12156. /**
  12157. * This function handles the chains. It is called on every updateClusters().
  12158. */
  12159. handleChains : function() {
  12160. // after clustering we check how many chains there are
  12161. var chainPercentage = this._getChainFraction();
  12162. if (chainPercentage > this.constants.clustering.chainThreshold) {
  12163. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  12164. }
  12165. },
  12166. /**
  12167. * this functions starts clustering by hubs
  12168. * The minimum hub threshold is set globally
  12169. *
  12170. * @private
  12171. */
  12172. _aggregateHubs : function(force) {
  12173. this._getHubSize();
  12174. this._formClustersByHub(force,false);
  12175. },
  12176. /**
  12177. * This function is fired by keypress. It forces hubs to form.
  12178. *
  12179. */
  12180. forceAggregateHubs : function(doNotStart) {
  12181. var isMovingBeforeClustering = this.moving;
  12182. var amountOfNodes = this.nodeIndices.length;
  12183. this._aggregateHubs(true);
  12184. // update the index list, dynamic edges and labels
  12185. this._updateNodeIndexList();
  12186. this._updateDynamicEdges();
  12187. this.updateLabels();
  12188. // if a cluster was formed, we increase the clusterSession
  12189. if (this.nodeIndices.length != amountOfNodes) {
  12190. this.clusterSession += 1;
  12191. }
  12192. if (doNotStart == false || doNotStart === undefined) {
  12193. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12194. if (this.moving != isMovingBeforeClustering) {
  12195. this.start();
  12196. }
  12197. }
  12198. },
  12199. /**
  12200. * If a cluster takes up more than a set percentage of the screen, open the cluster
  12201. *
  12202. * @private
  12203. */
  12204. _openClustersBySize : function() {
  12205. for (var nodeId in this.nodes) {
  12206. if (this.nodes.hasOwnProperty(nodeId)) {
  12207. var node = this.nodes[nodeId];
  12208. if (node.inView() == true) {
  12209. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  12210. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  12211. this.openCluster(node);
  12212. }
  12213. }
  12214. }
  12215. }
  12216. },
  12217. /**
  12218. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  12219. * has to be opened based on the current zoom level.
  12220. *
  12221. * @private
  12222. */
  12223. _openClusters : function(recursive,force) {
  12224. for (var i = 0; i < this.nodeIndices.length; i++) {
  12225. var node = this.nodes[this.nodeIndices[i]];
  12226. this._expandClusterNode(node,recursive,force);
  12227. this._updateCalculationNodes();
  12228. }
  12229. },
  12230. /**
  12231. * This function checks if a node has to be opened. This is done by checking the zoom level.
  12232. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  12233. * This recursive behaviour is optional and can be set by the recursive argument.
  12234. *
  12235. * @param {Node} parentNode | to check for cluster and expand
  12236. * @param {Boolean} recursive | enabled or disable recursive calling
  12237. * @param {Boolean} force | enabled or disable forcing
  12238. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  12239. * @private
  12240. */
  12241. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  12242. // first check if node is a cluster
  12243. if (parentNode.clusterSize > 1) {
  12244. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  12245. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  12246. openAll = true;
  12247. }
  12248. recursive = openAll ? true : recursive;
  12249. // if the last child has been added on a smaller scale than current scale decluster
  12250. if (parentNode.formationScale < this.scale || force == true) {
  12251. // we will check if any of the contained child nodes should be removed from the cluster
  12252. for (var containedNodeId in parentNode.containedNodes) {
  12253. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  12254. var childNode = parentNode.containedNodes[containedNodeId];
  12255. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  12256. // the largest cluster is the one that comes from outside
  12257. if (force == true) {
  12258. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  12259. || openAll) {
  12260. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12261. }
  12262. }
  12263. else {
  12264. if (this._nodeInActiveArea(parentNode)) {
  12265. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12266. }
  12267. }
  12268. }
  12269. }
  12270. }
  12271. }
  12272. },
  12273. /**
  12274. * ONLY CALLED FROM _expandClusterNode
  12275. *
  12276. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  12277. * the child node from the parent contained_node object and put it back into the global nodes object.
  12278. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  12279. *
  12280. * @param {Node} parentNode | the parent node
  12281. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  12282. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  12283. * With force and recursive both true, the entire cluster is unpacked
  12284. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  12285. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  12286. * @private
  12287. */
  12288. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  12289. var childNode = parentNode.containedNodes[containedNodeId];
  12290. // if child node has been added on smaller scale than current, kick out
  12291. if (childNode.formationScale < this.scale || force == true) {
  12292. // unselect all selected items
  12293. this._unselectAll();
  12294. // put the child node back in the global nodes object
  12295. this.nodes[containedNodeId] = childNode;
  12296. // release the contained edges from this childNode back into the global edges
  12297. this._releaseContainedEdges(parentNode,childNode);
  12298. // reconnect rerouted edges to the childNode
  12299. this._connectEdgeBackToChild(parentNode,childNode);
  12300. // validate all edges in dynamicEdges
  12301. this._validateEdges(parentNode);
  12302. // undo the changes from the clustering operation on the parent node
  12303. parentNode.mass -= childNode.mass;
  12304. parentNode.clusterSize -= childNode.clusterSize;
  12305. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12306. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12307. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12308. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12309. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12310. // remove node from the list
  12311. delete parentNode.containedNodes[containedNodeId];
  12312. // check if there are other childs with this clusterSession in the parent.
  12313. var othersPresent = false;
  12314. for (var childNodeId in parentNode.containedNodes) {
  12315. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12316. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12317. othersPresent = true;
  12318. break;
  12319. }
  12320. }
  12321. }
  12322. // if there are no others, remove the cluster session from the list
  12323. if (othersPresent == false) {
  12324. parentNode.clusterSessions.pop();
  12325. }
  12326. this._repositionBezierNodes(childNode);
  12327. // this._repositionBezierNodes(parentNode);
  12328. // remove the clusterSession from the child node
  12329. childNode.clusterSession = 0;
  12330. // recalculate the size of the node on the next time the node is rendered
  12331. parentNode.clearSizeCache();
  12332. // restart the simulation to reorganise all nodes
  12333. this.moving = true;
  12334. }
  12335. // check if a further expansion step is possible if recursivity is enabled
  12336. if (recursive == true) {
  12337. this._expandClusterNode(childNode,recursive,force,openAll);
  12338. }
  12339. },
  12340. /**
  12341. * position the bezier nodes at the center of the edges
  12342. *
  12343. * @param node
  12344. * @private
  12345. */
  12346. _repositionBezierNodes : function(node) {
  12347. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12348. node.dynamicEdges[i].positionBezierNode();
  12349. }
  12350. },
  12351. /**
  12352. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12353. * This function is called only from updateClusters()
  12354. * forceLevelCollapse ignores the length of the edge and collapses one level
  12355. * This means that a node with only one edge will be clustered with its connected node
  12356. *
  12357. * @private
  12358. * @param {Boolean} force
  12359. */
  12360. _formClusters : function(force) {
  12361. if (force == false) {
  12362. this._formClustersByZoom();
  12363. }
  12364. else {
  12365. this._forceClustersByZoom();
  12366. }
  12367. },
  12368. /**
  12369. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12370. *
  12371. * @private
  12372. */
  12373. _formClustersByZoom : function() {
  12374. var dx,dy,length,
  12375. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12376. // check if any edges are shorter than minLength and start the clustering
  12377. // the clustering favours the node with the larger mass
  12378. for (var edgeId in this.edges) {
  12379. if (this.edges.hasOwnProperty(edgeId)) {
  12380. var edge = this.edges[edgeId];
  12381. if (edge.connected) {
  12382. if (edge.toId != edge.fromId) {
  12383. dx = (edge.to.x - edge.from.x);
  12384. dy = (edge.to.y - edge.from.y);
  12385. length = Math.sqrt(dx * dx + dy * dy);
  12386. if (length < minLength) {
  12387. // first check which node is larger
  12388. var parentNode = edge.from;
  12389. var childNode = edge.to;
  12390. if (edge.to.mass > edge.from.mass) {
  12391. parentNode = edge.to;
  12392. childNode = edge.from;
  12393. }
  12394. if (childNode.dynamicEdgesLength == 1) {
  12395. this._addToCluster(parentNode,childNode,false);
  12396. }
  12397. else if (parentNode.dynamicEdgesLength == 1) {
  12398. this._addToCluster(childNode,parentNode,false);
  12399. }
  12400. }
  12401. }
  12402. }
  12403. }
  12404. }
  12405. },
  12406. /**
  12407. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12408. * connected node.
  12409. *
  12410. * @private
  12411. */
  12412. _forceClustersByZoom : function() {
  12413. for (var nodeId in this.nodes) {
  12414. // another node could have absorbed this child.
  12415. if (this.nodes.hasOwnProperty(nodeId)) {
  12416. var childNode = this.nodes[nodeId];
  12417. // the edges can be swallowed by another decrease
  12418. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12419. var edge = childNode.dynamicEdges[0];
  12420. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12421. // group to the largest node
  12422. if (childNode.id != parentNode.id) {
  12423. if (parentNode.mass > childNode.mass) {
  12424. this._addToCluster(parentNode,childNode,true);
  12425. }
  12426. else {
  12427. this._addToCluster(childNode,parentNode,true);
  12428. }
  12429. }
  12430. }
  12431. }
  12432. }
  12433. },
  12434. /**
  12435. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12436. * This function clusters a node to its smallest connected neighbour.
  12437. *
  12438. * @param node
  12439. * @private
  12440. */
  12441. _clusterToSmallestNeighbour : function(node) {
  12442. var smallestNeighbour = -1;
  12443. var smallestNeighbourNode = null;
  12444. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12445. if (node.dynamicEdges[i] !== undefined) {
  12446. var neighbour = null;
  12447. if (node.dynamicEdges[i].fromId != node.id) {
  12448. neighbour = node.dynamicEdges[i].from;
  12449. }
  12450. else if (node.dynamicEdges[i].toId != node.id) {
  12451. neighbour = node.dynamicEdges[i].to;
  12452. }
  12453. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12454. smallestNeighbour = neighbour.clusterSessions.length;
  12455. smallestNeighbourNode = neighbour;
  12456. }
  12457. }
  12458. }
  12459. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12460. this._addToCluster(neighbour, node, true);
  12461. }
  12462. },
  12463. /**
  12464. * This function forms clusters from hubs, it loops over all nodes
  12465. *
  12466. * @param {Boolean} force | Disregard zoom level
  12467. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12468. * @private
  12469. */
  12470. _formClustersByHub : function(force, onlyEqual) {
  12471. // we loop over all nodes in the list
  12472. for (var nodeId in this.nodes) {
  12473. // we check if it is still available since it can be used by the clustering in this loop
  12474. if (this.nodes.hasOwnProperty(nodeId)) {
  12475. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12476. }
  12477. }
  12478. },
  12479. /**
  12480. * This function forms a cluster from a specific preselected hub node
  12481. *
  12482. * @param {Node} hubNode | the node we will cluster as a hub
  12483. * @param {Boolean} force | Disregard zoom level
  12484. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12485. * @param {Number} [absorptionSizeOffset] |
  12486. * @private
  12487. */
  12488. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12489. if (absorptionSizeOffset === undefined) {
  12490. absorptionSizeOffset = 0;
  12491. }
  12492. // we decide if the node is a hub
  12493. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12494. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12495. // initialize variables
  12496. var dx,dy,length;
  12497. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12498. var allowCluster = false;
  12499. // we create a list of edges because the dynamicEdges change over the course of this loop
  12500. var edgesIdarray = [];
  12501. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12502. for (var j = 0; j < amountOfInitialEdges; j++) {
  12503. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12504. }
  12505. // if the hub clustering is not forces, we check if one of the edges connected
  12506. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12507. if (force == false) {
  12508. allowCluster = false;
  12509. for (j = 0; j < amountOfInitialEdges; j++) {
  12510. var edge = this.edges[edgesIdarray[j]];
  12511. if (edge !== undefined) {
  12512. if (edge.connected) {
  12513. if (edge.toId != edge.fromId) {
  12514. dx = (edge.to.x - edge.from.x);
  12515. dy = (edge.to.y - edge.from.y);
  12516. length = Math.sqrt(dx * dx + dy * dy);
  12517. if (length < minLength) {
  12518. allowCluster = true;
  12519. break;
  12520. }
  12521. }
  12522. }
  12523. }
  12524. }
  12525. }
  12526. // start the clustering if allowed
  12527. if ((!force && allowCluster) || force) {
  12528. // we loop over all edges INITIALLY connected to this hub
  12529. for (j = 0; j < amountOfInitialEdges; j++) {
  12530. edge = this.edges[edgesIdarray[j]];
  12531. // the edge can be clustered by this function in a previous loop
  12532. if (edge !== undefined) {
  12533. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12534. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12535. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12536. (childNode.id != hubNode.id)) {
  12537. this._addToCluster(hubNode,childNode,force);
  12538. }
  12539. }
  12540. }
  12541. }
  12542. }
  12543. },
  12544. /**
  12545. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12546. *
  12547. * @param {Node} parentNode | this is the node that will house the child node
  12548. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12549. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12550. * @private
  12551. */
  12552. _addToCluster : function(parentNode, childNode, force) {
  12553. // join child node in the parent node
  12554. parentNode.containedNodes[childNode.id] = childNode;
  12555. // manage all the edges connected to the child and parent nodes
  12556. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12557. var edge = childNode.dynamicEdges[i];
  12558. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12559. this._addToContainedEdges(parentNode,childNode,edge);
  12560. }
  12561. else {
  12562. this._connectEdgeToCluster(parentNode,childNode,edge);
  12563. }
  12564. }
  12565. // a contained node has no dynamic edges.
  12566. childNode.dynamicEdges = [];
  12567. // remove circular edges from clusters
  12568. this._containCircularEdgesFromNode(parentNode,childNode);
  12569. // remove the childNode from the global nodes object
  12570. delete this.nodes[childNode.id];
  12571. // update the properties of the child and parent
  12572. var massBefore = parentNode.mass;
  12573. childNode.clusterSession = this.clusterSession;
  12574. parentNode.mass += childNode.mass;
  12575. parentNode.clusterSize += childNode.clusterSize;
  12576. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12577. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12578. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12579. parentNode.clusterSessions.push(this.clusterSession);
  12580. }
  12581. // forced clusters only open from screen size and double tap
  12582. if (force == true) {
  12583. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12584. parentNode.formationScale = 0;
  12585. }
  12586. else {
  12587. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12588. }
  12589. // recalculate the size of the node on the next time the node is rendered
  12590. parentNode.clearSizeCache();
  12591. // set the pop-out scale for the childnode
  12592. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12593. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12594. childNode.clearVelocity();
  12595. // the mass has altered, preservation of energy dictates the velocity to be updated
  12596. parentNode.updateVelocity(massBefore);
  12597. // restart the simulation to reorganise all nodes
  12598. this.moving = true;
  12599. },
  12600. /**
  12601. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12602. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12603. * It has to be called if a level is collapsed. It is called by _formClusters().
  12604. * @private
  12605. */
  12606. _updateDynamicEdges : function() {
  12607. for (var i = 0; i < this.nodeIndices.length; i++) {
  12608. var node = this.nodes[this.nodeIndices[i]];
  12609. node.dynamicEdgesLength = node.dynamicEdges.length;
  12610. // this corrects for multiple edges pointing at the same other node
  12611. var correction = 0;
  12612. if (node.dynamicEdgesLength > 1) {
  12613. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12614. var edgeToId = node.dynamicEdges[j].toId;
  12615. var edgeFromId = node.dynamicEdges[j].fromId;
  12616. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12617. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12618. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12619. correction += 1;
  12620. }
  12621. }
  12622. }
  12623. }
  12624. node.dynamicEdgesLength -= correction;
  12625. }
  12626. },
  12627. /**
  12628. * This adds an edge from the childNode to the contained edges of the parent node
  12629. *
  12630. * @param parentNode | Node object
  12631. * @param childNode | Node object
  12632. * @param edge | Edge object
  12633. * @private
  12634. */
  12635. _addToContainedEdges : function(parentNode, childNode, edge) {
  12636. // create an array object if it does not yet exist for this childNode
  12637. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12638. parentNode.containedEdges[childNode.id] = []
  12639. }
  12640. // add this edge to the list
  12641. parentNode.containedEdges[childNode.id].push(edge);
  12642. // remove the edge from the global edges object
  12643. delete this.edges[edge.id];
  12644. // remove the edge from the parent object
  12645. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12646. if (parentNode.dynamicEdges[i].id == edge.id) {
  12647. parentNode.dynamicEdges.splice(i,1);
  12648. break;
  12649. }
  12650. }
  12651. },
  12652. /**
  12653. * This function connects an edge that was connected to a child node to the parent node.
  12654. * It keeps track of which nodes it has been connected to with the originalId array.
  12655. *
  12656. * @param {Node} parentNode | Node object
  12657. * @param {Node} childNode | Node object
  12658. * @param {Edge} edge | Edge object
  12659. * @private
  12660. */
  12661. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12662. // handle circular edges
  12663. if (edge.toId == edge.fromId) {
  12664. this._addToContainedEdges(parentNode, childNode, edge);
  12665. }
  12666. else {
  12667. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12668. edge.originalToId.push(childNode.id);
  12669. edge.to = parentNode;
  12670. edge.toId = parentNode.id;
  12671. }
  12672. else { // edge connected to other node with the "from" side
  12673. edge.originalFromId.push(childNode.id);
  12674. edge.from = parentNode;
  12675. edge.fromId = parentNode.id;
  12676. }
  12677. this._addToReroutedEdges(parentNode,childNode,edge);
  12678. }
  12679. },
  12680. /**
  12681. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12682. * these edges inside of the cluster.
  12683. *
  12684. * @param parentNode
  12685. * @param childNode
  12686. * @private
  12687. */
  12688. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12689. // manage all the edges connected to the child and parent nodes
  12690. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12691. var edge = parentNode.dynamicEdges[i];
  12692. // handle circular edges
  12693. if (edge.toId == edge.fromId) {
  12694. this._addToContainedEdges(parentNode, childNode, edge);
  12695. }
  12696. }
  12697. },
  12698. /**
  12699. * This adds an edge from the childNode to the rerouted edges of the parent node
  12700. *
  12701. * @param parentNode | Node object
  12702. * @param childNode | Node object
  12703. * @param edge | Edge object
  12704. * @private
  12705. */
  12706. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12707. // create an array object if it does not yet exist for this childNode
  12708. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12709. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12710. parentNode.reroutedEdges[childNode.id] = [];
  12711. }
  12712. parentNode.reroutedEdges[childNode.id].push(edge);
  12713. // this edge becomes part of the dynamicEdges of the cluster node
  12714. parentNode.dynamicEdges.push(edge);
  12715. },
  12716. /**
  12717. * This function connects an edge that was connected to a cluster node back to the child node.
  12718. *
  12719. * @param parentNode | Node object
  12720. * @param childNode | Node object
  12721. * @private
  12722. */
  12723. _connectEdgeBackToChild : function(parentNode, childNode) {
  12724. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12725. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12726. var edge = parentNode.reroutedEdges[childNode.id][i];
  12727. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12728. edge.originalFromId.pop();
  12729. edge.fromId = childNode.id;
  12730. edge.from = childNode;
  12731. }
  12732. else {
  12733. edge.originalToId.pop();
  12734. edge.toId = childNode.id;
  12735. edge.to = childNode;
  12736. }
  12737. // append this edge to the list of edges connecting to the childnode
  12738. childNode.dynamicEdges.push(edge);
  12739. // remove the edge from the parent object
  12740. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12741. if (parentNode.dynamicEdges[j].id == edge.id) {
  12742. parentNode.dynamicEdges.splice(j,1);
  12743. break;
  12744. }
  12745. }
  12746. }
  12747. // remove the entry from the rerouted edges
  12748. delete parentNode.reroutedEdges[childNode.id];
  12749. }
  12750. },
  12751. /**
  12752. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12753. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12754. * parentNode
  12755. *
  12756. * @param parentNode | Node object
  12757. * @private
  12758. */
  12759. _validateEdges : function(parentNode) {
  12760. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12761. var edge = parentNode.dynamicEdges[i];
  12762. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12763. parentNode.dynamicEdges.splice(i,1);
  12764. }
  12765. }
  12766. },
  12767. /**
  12768. * This function released the contained edges back into the global domain and puts them back into the
  12769. * dynamic edges of both parent and child.
  12770. *
  12771. * @param {Node} parentNode |
  12772. * @param {Node} childNode |
  12773. * @private
  12774. */
  12775. _releaseContainedEdges : function(parentNode, childNode) {
  12776. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12777. var edge = parentNode.containedEdges[childNode.id][i];
  12778. // put the edge back in the global edges object
  12779. this.edges[edge.id] = edge;
  12780. // put the edge back in the dynamic edges of the child and parent
  12781. childNode.dynamicEdges.push(edge);
  12782. parentNode.dynamicEdges.push(edge);
  12783. }
  12784. // remove the entry from the contained edges
  12785. delete parentNode.containedEdges[childNode.id];
  12786. },
  12787. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  12788. /**
  12789. * This updates the node labels for all nodes (for debugging purposes)
  12790. */
  12791. updateLabels : function() {
  12792. var nodeId;
  12793. // update node labels
  12794. for (nodeId in this.nodes) {
  12795. if (this.nodes.hasOwnProperty(nodeId)) {
  12796. var node = this.nodes[nodeId];
  12797. if (node.clusterSize > 1) {
  12798. node.label = "[".concat(String(node.clusterSize),"]");
  12799. }
  12800. }
  12801. }
  12802. // update node labels
  12803. for (nodeId in this.nodes) {
  12804. if (this.nodes.hasOwnProperty(nodeId)) {
  12805. node = this.nodes[nodeId];
  12806. if (node.clusterSize == 1) {
  12807. if (node.originalLabel !== undefined) {
  12808. node.label = node.originalLabel;
  12809. }
  12810. else {
  12811. node.label = String(node.id);
  12812. }
  12813. }
  12814. }
  12815. }
  12816. // /* Debug Override */
  12817. // for (nodeId in this.nodes) {
  12818. // if (this.nodes.hasOwnProperty(nodeId)) {
  12819. // node = this.nodes[nodeId];
  12820. // node.label = String(node.level);
  12821. // }
  12822. // }
  12823. },
  12824. /**
  12825. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  12826. * if the rest of the nodes are already a few cluster levels in.
  12827. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  12828. * clustered enough to the clusterToSmallestNeighbours function.
  12829. */
  12830. normalizeClusterLevels : function() {
  12831. var maxLevel = 0;
  12832. var minLevel = 1e9;
  12833. var clusterLevel = 0;
  12834. // we loop over all nodes in the list
  12835. for (var nodeId in this.nodes) {
  12836. if (this.nodes.hasOwnProperty(nodeId)) {
  12837. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  12838. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  12839. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  12840. }
  12841. }
  12842. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  12843. var amountOfNodes = this.nodeIndices.length;
  12844. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  12845. // we loop over all nodes in the list
  12846. for (var nodeId in this.nodes) {
  12847. if (this.nodes.hasOwnProperty(nodeId)) {
  12848. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  12849. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  12850. }
  12851. }
  12852. }
  12853. this._updateNodeIndexList();
  12854. this._updateDynamicEdges();
  12855. // if a cluster was formed, we increase the clusterSession
  12856. if (this.nodeIndices.length != amountOfNodes) {
  12857. this.clusterSession += 1;
  12858. }
  12859. }
  12860. },
  12861. /**
  12862. * This function determines if the cluster we want to decluster is in the active area
  12863. * this means around the zoom center
  12864. *
  12865. * @param {Node} node
  12866. * @returns {boolean}
  12867. * @private
  12868. */
  12869. _nodeInActiveArea : function(node) {
  12870. return (
  12871. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12872. &&
  12873. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  12874. )
  12875. },
  12876. /**
  12877. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  12878. * It puts large clusters away from the center and randomizes the order.
  12879. *
  12880. */
  12881. repositionNodes : function() {
  12882. for (var i = 0; i < this.nodeIndices.length; i++) {
  12883. var node = this.nodes[this.nodeIndices[i]];
  12884. if ((node.xFixed == false || node.yFixed == false) && this.createNodeOnClick != true) {
  12885. var radius = this.constants.physics.springLength * Math.min(100,node.mass);
  12886. var angle = 2 * Math.PI * Math.random();
  12887. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  12888. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  12889. this._repositionBezierNodes(node);
  12890. }
  12891. }
  12892. },
  12893. /**
  12894. * We determine how many connections denote an important hub.
  12895. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  12896. *
  12897. * @private
  12898. */
  12899. _getHubSize : function() {
  12900. var average = 0;
  12901. var averageSquared = 0;
  12902. var hubCounter = 0;
  12903. var largestHub = 0;
  12904. for (var i = 0; i < this.nodeIndices.length; i++) {
  12905. var node = this.nodes[this.nodeIndices[i]];
  12906. if (node.dynamicEdgesLength > largestHub) {
  12907. largestHub = node.dynamicEdgesLength;
  12908. }
  12909. average += node.dynamicEdgesLength;
  12910. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  12911. hubCounter += 1;
  12912. }
  12913. average = average / hubCounter;
  12914. averageSquared = averageSquared / hubCounter;
  12915. var variance = averageSquared - Math.pow(average,2);
  12916. var standardDeviation = Math.sqrt(variance);
  12917. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  12918. // always have at least one to cluster
  12919. if (this.hubThreshold > largestHub) {
  12920. this.hubThreshold = largestHub;
  12921. }
  12922. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  12923. // console.log("hubThreshold:",this.hubThreshold);
  12924. },
  12925. /**
  12926. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12927. * with this amount we can cluster specifically on these chains.
  12928. *
  12929. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  12930. * @private
  12931. */
  12932. _reduceAmountOfChains : function(fraction) {
  12933. this.hubThreshold = 2;
  12934. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  12935. for (var nodeId in this.nodes) {
  12936. if (this.nodes.hasOwnProperty(nodeId)) {
  12937. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12938. if (reduceAmount > 0) {
  12939. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  12940. reduceAmount -= 1;
  12941. }
  12942. }
  12943. }
  12944. }
  12945. },
  12946. /**
  12947. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  12948. * with this amount we can cluster specifically on these chains.
  12949. *
  12950. * @private
  12951. */
  12952. _getChainFraction : function() {
  12953. var chains = 0;
  12954. var total = 0;
  12955. for (var nodeId in this.nodes) {
  12956. if (this.nodes.hasOwnProperty(nodeId)) {
  12957. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  12958. chains += 1;
  12959. }
  12960. total += 1;
  12961. }
  12962. }
  12963. return chains/total;
  12964. }
  12965. };
  12966. var SelectionMixin = {
  12967. /**
  12968. * This function can be called from the _doInAllSectors function
  12969. *
  12970. * @param object
  12971. * @param overlappingNodes
  12972. * @private
  12973. */
  12974. _getNodesOverlappingWith : function(object, overlappingNodes) {
  12975. var nodes = this.nodes;
  12976. for (var nodeId in nodes) {
  12977. if (nodes.hasOwnProperty(nodeId)) {
  12978. if (nodes[nodeId].isOverlappingWith(object)) {
  12979. overlappingNodes.push(nodeId);
  12980. }
  12981. }
  12982. }
  12983. },
  12984. /**
  12985. * retrieve all nodes overlapping with given object
  12986. * @param {Object} object An object with parameters left, top, right, bottom
  12987. * @return {Number[]} An array with id's of the overlapping nodes
  12988. * @private
  12989. */
  12990. _getAllNodesOverlappingWith : function (object) {
  12991. var overlappingNodes = [];
  12992. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  12993. return overlappingNodes;
  12994. },
  12995. /**
  12996. * Return a position object in canvasspace from a single point in screenspace
  12997. *
  12998. * @param pointer
  12999. * @returns {{left: number, top: number, right: number, bottom: number}}
  13000. * @private
  13001. */
  13002. _pointerToPositionObject : function(pointer) {
  13003. var x = this._canvasToX(pointer.x);
  13004. var y = this._canvasToY(pointer.y);
  13005. return {left: x,
  13006. top: y,
  13007. right: x,
  13008. bottom: y};
  13009. },
  13010. /**
  13011. * Get the top node at the a specific point (like a click)
  13012. *
  13013. * @param {{x: Number, y: Number}} pointer
  13014. * @return {Node | null} node
  13015. * @private
  13016. */
  13017. _getNodeAt : function (pointer) {
  13018. // we first check if this is an navigation controls element
  13019. var positionObject = this._pointerToPositionObject(pointer);
  13020. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  13021. // if there are overlapping nodes, select the last one, this is the
  13022. // one which is drawn on top of the others
  13023. if (overlappingNodes.length > 0) {
  13024. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  13025. }
  13026. else {
  13027. return null;
  13028. }
  13029. },
  13030. /**
  13031. * retrieve all edges overlapping with given object, selector is around center
  13032. * @param {Object} object An object with parameters left, top, right, bottom
  13033. * @return {Number[]} An array with id's of the overlapping nodes
  13034. * @private
  13035. */
  13036. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  13037. var edges = this.edges;
  13038. for (var edgeId in edges) {
  13039. if (edges.hasOwnProperty(edgeId)) {
  13040. if (edges[edgeId].isOverlappingWith(object)) {
  13041. overlappingEdges.push(edgeId);
  13042. }
  13043. }
  13044. }
  13045. },
  13046. /**
  13047. * retrieve all nodes overlapping with given object
  13048. * @param {Object} object An object with parameters left, top, right, bottom
  13049. * @return {Number[]} An array with id's of the overlapping nodes
  13050. * @private
  13051. */
  13052. _getAllEdgesOverlappingWith : function (object) {
  13053. var overlappingEdges = [];
  13054. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  13055. return overlappingEdges;
  13056. },
  13057. /**
  13058. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  13059. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  13060. *
  13061. * @param pointer
  13062. * @returns {null}
  13063. * @private
  13064. */
  13065. _getEdgeAt : function(pointer) {
  13066. var positionObject = this._pointerToPositionObject(pointer);
  13067. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  13068. if (overlappingEdges.length > 0) {
  13069. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  13070. }
  13071. else {
  13072. return null;
  13073. }
  13074. },
  13075. /**
  13076. * Add object to the selection array.
  13077. *
  13078. * @param obj
  13079. * @private
  13080. */
  13081. _addToSelection : function(obj) {
  13082. this.selectionObj[obj.id] = obj;
  13083. },
  13084. /**
  13085. * Remove a single option from selection.
  13086. *
  13087. * @param {Object} obj
  13088. * @private
  13089. */
  13090. _removeFromSelection : function(obj) {
  13091. delete this.selectionObj[obj.id];
  13092. },
  13093. /**
  13094. * Unselect all. The selectionObj is useful for this.
  13095. *
  13096. * @param {Boolean} [doNotTrigger] | ignore trigger
  13097. * @private
  13098. */
  13099. _unselectAll : function(doNotTrigger) {
  13100. if (doNotTrigger === undefined) {
  13101. doNotTrigger = false;
  13102. }
  13103. for (var objectId in this.selectionObj) {
  13104. if (this.selectionObj.hasOwnProperty(objectId)) {
  13105. this.selectionObj[objectId].unselect();
  13106. }
  13107. }
  13108. this.selectionObj = {};
  13109. if (doNotTrigger == false) {
  13110. this.emit('select', this.getSelection());
  13111. }
  13112. },
  13113. /**
  13114. * Unselect all clusters. The selectionObj is useful for this.
  13115. *
  13116. * @param {Boolean} [doNotTrigger] | ignore trigger
  13117. * @private
  13118. */
  13119. _unselectClusters : function(doNotTrigger) {
  13120. if (doNotTrigger === undefined) {
  13121. doNotTrigger = false;
  13122. }
  13123. for (var objectId in this.selectionObj) {
  13124. if (this.selectionObj.hasOwnProperty(objectId)) {
  13125. if (this.selectionObj[objectId] instanceof Node) {
  13126. if (this.selectionObj[objectId].clusterSize > 1) {
  13127. this.selectionObj[objectId].unselect();
  13128. this._removeFromSelection(this.selectionObj[objectId]);
  13129. }
  13130. }
  13131. }
  13132. }
  13133. if (doNotTrigger == false) {
  13134. this.emit('select', this.getSelection());
  13135. }
  13136. },
  13137. /**
  13138. * return the number of selected nodes
  13139. *
  13140. * @returns {number}
  13141. * @private
  13142. */
  13143. _getSelectedNodeCount : function() {
  13144. var count = 0;
  13145. for (var objectId in this.selectionObj) {
  13146. if (this.selectionObj.hasOwnProperty(objectId)) {
  13147. if (this.selectionObj[objectId] instanceof Node) {
  13148. count += 1;
  13149. }
  13150. }
  13151. }
  13152. return count;
  13153. },
  13154. /**
  13155. * return the number of selected nodes
  13156. *
  13157. * @returns {number}
  13158. * @private
  13159. */
  13160. _getSelectedNode : function() {
  13161. for (var objectId in this.selectionObj) {
  13162. if (this.selectionObj.hasOwnProperty(objectId)) {
  13163. if (this.selectionObj[objectId] instanceof Node) {
  13164. return this.selectionObj[objectId];
  13165. }
  13166. }
  13167. }
  13168. return null;
  13169. },
  13170. /**
  13171. * return the number of selected edges
  13172. *
  13173. * @returns {number}
  13174. * @private
  13175. */
  13176. _getSelectedEdgeCount : function() {
  13177. var count = 0;
  13178. for (var objectId in this.selectionObj) {
  13179. if (this.selectionObj.hasOwnProperty(objectId)) {
  13180. if (this.selectionObj[objectId] instanceof Edge) {
  13181. count += 1;
  13182. }
  13183. }
  13184. }
  13185. return count;
  13186. },
  13187. /**
  13188. * return the number of selected objects.
  13189. *
  13190. * @returns {number}
  13191. * @private
  13192. */
  13193. _getSelectedObjectCount : function() {
  13194. var count = 0;
  13195. for (var objectId in this.selectionObj) {
  13196. if (this.selectionObj.hasOwnProperty(objectId)) {
  13197. count += 1;
  13198. }
  13199. }
  13200. return count;
  13201. },
  13202. /**
  13203. * Check if anything is selected
  13204. *
  13205. * @returns {boolean}
  13206. * @private
  13207. */
  13208. _selectionIsEmpty : function() {
  13209. for(var objectId in this.selectionObj) {
  13210. if(this.selectionObj.hasOwnProperty(objectId)) {
  13211. return false;
  13212. }
  13213. }
  13214. return true;
  13215. },
  13216. /**
  13217. * check if one of the selected nodes is a cluster.
  13218. *
  13219. * @returns {boolean}
  13220. * @private
  13221. */
  13222. _clusterInSelection : function() {
  13223. for(var objectId in this.selectionObj) {
  13224. if(this.selectionObj.hasOwnProperty(objectId)) {
  13225. if (this.selectionObj[objectId] instanceof Node) {
  13226. if (this.selectionObj[objectId].clusterSize > 1) {
  13227. return true;
  13228. }
  13229. }
  13230. }
  13231. }
  13232. return false;
  13233. },
  13234. /**
  13235. * select the edges connected to the node that is being selected
  13236. *
  13237. * @param {Node} node
  13238. * @private
  13239. */
  13240. _selectConnectedEdges : function(node) {
  13241. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13242. var edge = node.dynamicEdges[i];
  13243. edge.select();
  13244. this._addToSelection(edge);
  13245. }
  13246. },
  13247. /**
  13248. * unselect the edges connected to the node that is being selected
  13249. *
  13250. * @param {Node} node
  13251. * @private
  13252. */
  13253. _unselectConnectedEdges : function(node) {
  13254. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13255. var edge = node.dynamicEdges[i];
  13256. edge.unselect();
  13257. this._removeFromSelection(edge);
  13258. }
  13259. },
  13260. /**
  13261. * This is called when someone clicks on a node. either select or deselect it.
  13262. * If there is an existing selection and we don't want to append to it, clear the existing selection
  13263. *
  13264. * @param {Node || Edge} object
  13265. * @param {Boolean} append
  13266. * @param {Boolean} [doNotTrigger] | ignore trigger
  13267. * @private
  13268. */
  13269. _selectObject : function(object, append, doNotTrigger) {
  13270. if (doNotTrigger === undefined) {
  13271. doNotTrigger = false;
  13272. }
  13273. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  13274. this._unselectAll(true);
  13275. }
  13276. if (object.selected == false) {
  13277. object.select();
  13278. this._addToSelection(object);
  13279. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  13280. this._selectConnectedEdges(object);
  13281. }
  13282. }
  13283. else {
  13284. object.unselect();
  13285. this._removeFromSelection(object);
  13286. }
  13287. if (doNotTrigger == false) {
  13288. this.emit('select', this.getSelection());
  13289. }
  13290. },
  13291. /**
  13292. * handles the selection part of the touch, only for navigation controls elements;
  13293. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13294. * This is the most responsive solution
  13295. *
  13296. * @param {Object} pointer
  13297. * @private
  13298. */
  13299. _handleTouch : function(pointer) {
  13300. },
  13301. /**
  13302. * handles the selection part of the tap;
  13303. *
  13304. * @param {Object} pointer
  13305. * @private
  13306. */
  13307. _handleTap : function(pointer) {
  13308. var node = this._getNodeAt(pointer);
  13309. if (node != null) {
  13310. this._selectObject(node,false);
  13311. }
  13312. else {
  13313. var edge = this._getEdgeAt(pointer);
  13314. if (edge != null) {
  13315. this._selectObject(edge,false);
  13316. }
  13317. else {
  13318. this._unselectAll();
  13319. }
  13320. }
  13321. this.emit("click", this.getSelection());
  13322. this._redraw();
  13323. },
  13324. /**
  13325. * handles the selection part of the double tap and opens a cluster if needed
  13326. *
  13327. * @param {Object} pointer
  13328. * @private
  13329. */
  13330. _handleDoubleTap : function(pointer) {
  13331. var node = this._getNodeAt(pointer);
  13332. if (node != null && node !== undefined) {
  13333. // we reset the areaCenter here so the opening of the node will occur
  13334. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  13335. "y" : this._canvasToY(pointer.y)};
  13336. this.openCluster(node);
  13337. }
  13338. this.emit("doubleClick", this.getSelection());
  13339. },
  13340. /**
  13341. * Handle the onHold selection part
  13342. *
  13343. * @param pointer
  13344. * @private
  13345. */
  13346. _handleOnHold : function(pointer) {
  13347. var node = this._getNodeAt(pointer);
  13348. if (node != null) {
  13349. this._selectObject(node,true);
  13350. }
  13351. else {
  13352. var edge = this._getEdgeAt(pointer);
  13353. if (edge != null) {
  13354. this._selectObject(edge,true);
  13355. }
  13356. }
  13357. this._redraw();
  13358. },
  13359. /**
  13360. * handle the onRelease event. These functions are here for the navigation controls module.
  13361. *
  13362. * @private
  13363. */
  13364. _handleOnRelease : function(pointer) {
  13365. },
  13366. /**
  13367. *
  13368. * retrieve the currently selected objects
  13369. * @return {Number[] | String[]} selection An array with the ids of the
  13370. * selected nodes.
  13371. */
  13372. getSelection : function() {
  13373. var nodeIds = this.getSelectedNodes();
  13374. var edgeIds = this.getSelectedEdges();
  13375. return {nodes:nodeIds, edges:edgeIds};
  13376. },
  13377. /**
  13378. *
  13379. * retrieve the currently selected nodes
  13380. * @return {String} selection An array with the ids of the
  13381. * selected nodes.
  13382. */
  13383. getSelectedNodes : function() {
  13384. var idArray = [];
  13385. for(var objectId in this.selectionObj) {
  13386. if(this.selectionObj.hasOwnProperty(objectId)) {
  13387. if (this.selectionObj[objectId] instanceof Node) {
  13388. idArray.push(objectId);
  13389. }
  13390. }
  13391. }
  13392. return idArray
  13393. },
  13394. /**
  13395. *
  13396. * retrieve the currently selected edges
  13397. * @return {Array} selection An array with the ids of the
  13398. * selected nodes.
  13399. */
  13400. getSelectedEdges : function() {
  13401. var idArray = [];
  13402. for(var objectId in this.selectionObj) {
  13403. if(this.selectionObj.hasOwnProperty(objectId)) {
  13404. if (this.selectionObj[objectId] instanceof Edge) {
  13405. idArray.push(objectId);
  13406. }
  13407. }
  13408. }
  13409. return idArray
  13410. },
  13411. /**
  13412. * select zero or more nodes
  13413. * @param {Number[] | String[]} selection An array with the ids of the
  13414. * selected nodes.
  13415. */
  13416. setSelection : function(selection) {
  13417. var i, iMax, id;
  13418. if (!selection || (selection.length == undefined))
  13419. throw 'Selection must be an array with ids';
  13420. // first unselect any selected node
  13421. this._unselectAll(true);
  13422. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13423. id = selection[i];
  13424. var node = this.nodes[id];
  13425. if (!node) {
  13426. throw new RangeError('Node with id "' + id + '" not found');
  13427. }
  13428. this._selectObject(node,true,true);
  13429. }
  13430. this.redraw();
  13431. },
  13432. /**
  13433. * Validate the selection: remove ids of nodes which no longer exist
  13434. * @private
  13435. */
  13436. _updateSelection : function () {
  13437. for(var objectId in this.selectionObj) {
  13438. if(this.selectionObj.hasOwnProperty(objectId)) {
  13439. if (this.selectionObj[objectId] instanceof Node) {
  13440. if (!this.nodes.hasOwnProperty(objectId)) {
  13441. delete this.selectionObj[objectId];
  13442. }
  13443. }
  13444. else { // assuming only edges and nodes are selected
  13445. if (!this.edges.hasOwnProperty(objectId)) {
  13446. delete this.selectionObj[objectId];
  13447. }
  13448. }
  13449. }
  13450. }
  13451. }
  13452. };
  13453. /**
  13454. * Created by Alex on 1/22/14.
  13455. */
  13456. var NavigationMixin = {
  13457. _cleanNavigation : function() {
  13458. // clean up previosu navigation items
  13459. var wrapper = document.getElementById('graph-navigation_wrapper');
  13460. if (wrapper != null) {
  13461. this.containerElement.removeChild(wrapper);
  13462. }
  13463. document.onmouseup = null;
  13464. },
  13465. /**
  13466. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13467. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13468. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13469. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13470. *
  13471. * @private
  13472. */
  13473. _loadNavigationElements : function() {
  13474. this._cleanNavigation();
  13475. this.navigationDivs = {};
  13476. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13477. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  13478. this.navigationDivs['wrapper'] = document.createElement('div');
  13479. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13480. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13481. for (var i = 0; i < navigationDivs.length; i++) {
  13482. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13483. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13484. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13485. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13486. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13487. }
  13488. document.onmouseup = this._stopMovement.bind(this);
  13489. },
  13490. /**
  13491. * this stops all movement induced by the navigation buttons
  13492. *
  13493. * @private
  13494. */
  13495. _stopMovement : function() {
  13496. this._xStopMoving();
  13497. this._yStopMoving();
  13498. this._stopZoom();
  13499. },
  13500. /**
  13501. * stops the actions performed by page up and down etc.
  13502. *
  13503. * @param event
  13504. * @private
  13505. */
  13506. _preventDefault : function(event) {
  13507. if (event !== undefined) {
  13508. if (event.preventDefault) {
  13509. event.preventDefault();
  13510. } else {
  13511. event.returnValue = false;
  13512. }
  13513. }
  13514. },
  13515. /**
  13516. * move the screen up
  13517. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13518. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13519. * To avoid this behaviour, we do the translation in the start loop.
  13520. *
  13521. * @private
  13522. */
  13523. _moveUp : function(event) {
  13524. console.log("here")
  13525. this.yIncrement = this.constants.keyboard.speed.y;
  13526. this.start(); // if there is no node movement, the calculation wont be done
  13527. this._preventDefault(event);
  13528. },
  13529. /**
  13530. * move the screen down
  13531. * @private
  13532. */
  13533. _moveDown : function(event) {
  13534. this.yIncrement = -this.constants.keyboard.speed.y;
  13535. this.start(); // if there is no node movement, the calculation wont be done
  13536. this._preventDefault(event);
  13537. },
  13538. /**
  13539. * move the screen left
  13540. * @private
  13541. */
  13542. _moveLeft : function(event) {
  13543. this.xIncrement = this.constants.keyboard.speed.x;
  13544. this.start(); // if there is no node movement, the calculation wont be done
  13545. this._preventDefault(event);
  13546. },
  13547. /**
  13548. * move the screen right
  13549. * @private
  13550. */
  13551. _moveRight : function(event) {
  13552. this.xIncrement = -this.constants.keyboard.speed.y;
  13553. this.start(); // if there is no node movement, the calculation wont be done
  13554. this._preventDefault(event);
  13555. },
  13556. /**
  13557. * Zoom in, using the same method as the movement.
  13558. * @private
  13559. */
  13560. _zoomIn : function(event) {
  13561. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13562. this.start(); // if there is no node movement, the calculation wont be done
  13563. this._preventDefault(event);
  13564. },
  13565. /**
  13566. * Zoom out
  13567. * @private
  13568. */
  13569. _zoomOut : function() {
  13570. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13571. this.start(); // if there is no node movement, the calculation wont be done
  13572. this._preventDefault(event);
  13573. },
  13574. /**
  13575. * Stop zooming and unhighlight the zoom controls
  13576. * @private
  13577. */
  13578. _stopZoom : function() {
  13579. this.zoomIncrement = 0;
  13580. },
  13581. /**
  13582. * Stop moving in the Y direction and unHighlight the up and down
  13583. * @private
  13584. */
  13585. _yStopMoving : function() {
  13586. this.yIncrement = 0;
  13587. },
  13588. /**
  13589. * Stop moving in the X direction and unHighlight left and right.
  13590. * @private
  13591. */
  13592. _xStopMoving : function() {
  13593. this.xIncrement = 0;
  13594. }
  13595. };
  13596. /**
  13597. * Created by Alex on 2/10/14.
  13598. */
  13599. var graphMixinLoaders = {
  13600. /**
  13601. * Load a mixin into the graph object
  13602. *
  13603. * @param {Object} sourceVariable | this object has to contain functions.
  13604. * @private
  13605. */
  13606. _loadMixin : function(sourceVariable) {
  13607. for (var mixinFunction in sourceVariable) {
  13608. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13609. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13610. }
  13611. }
  13612. },
  13613. /**
  13614. * removes a mixin from the graph object.
  13615. *
  13616. * @param {Object} sourceVariable | this object has to contain functions.
  13617. * @private
  13618. */
  13619. _clearMixin : function(sourceVariable) {
  13620. for (var mixinFunction in sourceVariable) {
  13621. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13622. Graph.prototype[mixinFunction] = undefined;
  13623. }
  13624. }
  13625. },
  13626. /**
  13627. * Mixin the physics system and initialize the parameters required.
  13628. *
  13629. * @private
  13630. */
  13631. _loadPhysicsSystem : function() {
  13632. this._loadMixin(physicsMixin);
  13633. this._loadSelectedForceSolver();
  13634. if (this.constants.configurePhysics == true) {
  13635. this._loadPhysicsConfiguration();
  13636. }
  13637. },
  13638. /**
  13639. * Mixin the cluster system and initialize the parameters required.
  13640. *
  13641. * @private
  13642. */
  13643. _loadClusterSystem : function() {
  13644. this.clusterSession = 0;
  13645. this.hubThreshold = 5;
  13646. this._loadMixin(ClusterMixin);
  13647. },
  13648. /**
  13649. * Mixin the sector system and initialize the parameters required
  13650. *
  13651. * @private
  13652. */
  13653. _loadSectorSystem : function() {
  13654. this.sectors = { },
  13655. this.activeSector = ["default"];
  13656. this.sectors["active"] = { },
  13657. this.sectors["active"]["default"] = {"nodes":{},
  13658. "edges":{},
  13659. "nodeIndices":[],
  13660. "formationScale": 1.0,
  13661. "drawingNode": undefined };
  13662. this.sectors["frozen"] = {},
  13663. this.sectors["support"] = {"nodes":{},
  13664. "edges":{},
  13665. "nodeIndices":[],
  13666. "formationScale": 1.0,
  13667. "drawingNode": undefined };
  13668. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13669. this._loadMixin(SectorMixin);
  13670. },
  13671. /**
  13672. * Mixin the selection system and initialize the parameters required
  13673. *
  13674. * @private
  13675. */
  13676. _loadSelectionSystem : function() {
  13677. this.selectionObj = { };
  13678. this._loadMixin(SelectionMixin);
  13679. },
  13680. /**
  13681. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13682. *
  13683. * @private
  13684. */
  13685. _loadManipulationSystem : function() {
  13686. // reset global variables -- these are used by the selection of nodes and edges.
  13687. this.blockConnectingEdgeSelection = false;
  13688. this.forceAppendSelection = false
  13689. if (this.constants.dataManipulation.enabled == true) {
  13690. // load the manipulator HTML elements. All styling done in css.
  13691. if (this.manipulationDiv === undefined) {
  13692. this.manipulationDiv = document.createElement('div');
  13693. this.manipulationDiv.className = 'graph-manipulationDiv';
  13694. this.manipulationDiv.id = 'graph-manipulationDiv';
  13695. if (this.editMode == true) {
  13696. this.manipulationDiv.style.display = "block";
  13697. }
  13698. else {
  13699. this.manipulationDiv.style.display = "none";
  13700. }
  13701. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13702. }
  13703. if (this.editModeDiv === undefined) {
  13704. this.editModeDiv = document.createElement('div');
  13705. this.editModeDiv.className = 'graph-manipulation-editMode';
  13706. this.editModeDiv.id = 'graph-manipulation-editMode';
  13707. if (this.editMode == true) {
  13708. this.editModeDiv.style.display = "none";
  13709. }
  13710. else {
  13711. this.editModeDiv.style.display = "block";
  13712. }
  13713. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13714. }
  13715. if (this.closeDiv === undefined) {
  13716. this.closeDiv = document.createElement('div');
  13717. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13718. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13719. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13720. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13721. }
  13722. // load the manipulation functions
  13723. this._loadMixin(manipulationMixin);
  13724. // create the manipulator toolbar
  13725. this._createManipulatorBar();
  13726. }
  13727. else {
  13728. if (this.manipulationDiv !== undefined) {
  13729. // removes all the bindings and overloads
  13730. this._createManipulatorBar();
  13731. // remove the manipulation divs
  13732. this.containerElement.removeChild(this.manipulationDiv);
  13733. this.containerElement.removeChild(this.editModeDiv);
  13734. this.containerElement.removeChild(this.closeDiv);
  13735. this.manipulationDiv = undefined;
  13736. this.editModeDiv = undefined;
  13737. this.closeDiv = undefined;
  13738. // remove the mixin functions
  13739. this._clearMixin(manipulationMixin);
  13740. }
  13741. }
  13742. },
  13743. /**
  13744. * Mixin the navigation (User Interface) system and initialize the parameters required
  13745. *
  13746. * @private
  13747. */
  13748. _loadNavigationControls : function() {
  13749. this._loadMixin(NavigationMixin);
  13750. // the clean function removes the button divs, this is done to remove the bindings.
  13751. this._cleanNavigation();
  13752. if (this.constants.navigation.enabled == true) {
  13753. this._loadNavigationElements();
  13754. }
  13755. },
  13756. /**
  13757. * Mixin the hierarchical layout system.
  13758. *
  13759. * @private
  13760. */
  13761. _loadHierarchySystem : function() {
  13762. this._loadMixin(HierarchicalLayoutMixin);
  13763. }
  13764. }
  13765. /**
  13766. * @constructor Graph
  13767. * Create a graph visualization, displaying nodes and edges.
  13768. *
  13769. * @param {Element} container The DOM element in which the Graph will
  13770. * be created. Normally a div element.
  13771. * @param {Object} data An object containing parameters
  13772. * {Array} nodes
  13773. * {Array} edges
  13774. * @param {Object} options Options
  13775. */
  13776. function Graph (container, data, options) {
  13777. this._initializeMixinLoaders();
  13778. // create variables and set default values
  13779. this.containerElement = container;
  13780. this.width = '100%';
  13781. this.height = '100%';
  13782. // render and calculation settings
  13783. this.renderRefreshRate = 60; // hz (fps)
  13784. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  13785. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  13786. this.maxRenderSteps = 3; // max amount of physics ticks per render step.
  13787. this.stabilize = true; // stabilize before displaying the graph
  13788. this.selectable = true;
  13789. // these functions are triggered when the dataset is edited
  13790. this.triggerFunctions = {add:null,edit:null,connect:null,delete:null};
  13791. // set constant values
  13792. this.constants = {
  13793. nodes: {
  13794. radiusMin: 5,
  13795. radiusMax: 20,
  13796. radius: 5,
  13797. shape: 'ellipse',
  13798. image: undefined,
  13799. widthMin: 16, // px
  13800. widthMax: 64, // px
  13801. fixed: false,
  13802. fontColor: 'black',
  13803. fontSize: 14, // px
  13804. fontFace: 'verdana',
  13805. level: -1,
  13806. color: {
  13807. border: '#2B7CE9',
  13808. background: '#97C2FC',
  13809. highlight: {
  13810. border: '#2B7CE9',
  13811. background: '#D2E5FF'
  13812. }
  13813. },
  13814. borderColor: '#2B7CE9',
  13815. backgroundColor: '#97C2FC',
  13816. highlightColor: '#D2E5FF',
  13817. group: undefined
  13818. },
  13819. edges: {
  13820. widthMin: 1,
  13821. widthMax: 15,
  13822. width: 1,
  13823. style: 'line',
  13824. color: '#848484',
  13825. fontColor: '#343434',
  13826. fontSize: 14, // px
  13827. fontFace: 'arial',
  13828. dash: {
  13829. length: 10,
  13830. gap: 5,
  13831. altLength: undefined
  13832. }
  13833. },
  13834. configurePhysics:false,
  13835. physics: {
  13836. barnesHut: {
  13837. enabled: true,
  13838. theta: 1 / 0.6, // inverted to save time during calculation
  13839. gravitationalConstant: -2000,
  13840. centralGravity: 0.3,
  13841. springLength: 100,
  13842. springConstant: 0.05,
  13843. damping: 0.09
  13844. },
  13845. repulsion: {
  13846. centralGravity: 0.1,
  13847. springLength: 200,
  13848. springConstant: 0.05,
  13849. nodeDistance: 100,
  13850. damping: 0.09
  13851. },
  13852. hierarchicalRepulsion: {
  13853. enabled: false,
  13854. centralGravity: 0.0,
  13855. springLength: 100,
  13856. springConstant: 0.01,
  13857. nodeDistance: 60,
  13858. damping: 0.09
  13859. },
  13860. damping: null,
  13861. centralGravity: null,
  13862. springLength: null,
  13863. springConstant: null
  13864. },
  13865. clustering: { // Per Node in Cluster = PNiC
  13866. enabled: false, // (Boolean) | global on/off switch for clustering.
  13867. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  13868. 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
  13869. 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
  13870. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  13871. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  13872. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  13873. 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.
  13874. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  13875. maxFontSize: 1000,
  13876. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  13877. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  13878. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  13879. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  13880. height: 1, // (px PNiC) | growth of the height per node in cluster.
  13881. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  13882. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  13883. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  13884. clusterLevelDifference: 2
  13885. },
  13886. navigation: {
  13887. enabled: false
  13888. },
  13889. keyboard: {
  13890. enabled: false,
  13891. speed: {x: 10, y: 10, zoom: 0.02}
  13892. },
  13893. dataManipulation: {
  13894. enabled: false,
  13895. initiallyVisible: false
  13896. },
  13897. hierarchicalLayout: {
  13898. enabled:false,
  13899. levelSeparation: 150,
  13900. nodeSpacing: 100,
  13901. direction: "UD" // UD, DU, LR, RL
  13902. },
  13903. smoothCurves: true,
  13904. maxVelocity: 10,
  13905. minVelocity: 0.1, // px/s
  13906. maxIterations: 1000 // maximum number of iteration to stabilize
  13907. };
  13908. this.editMode = this.constants.dataManipulation.initiallyVisible;
  13909. // Node variables
  13910. var graph = this;
  13911. this.groups = new Groups(); // object with groups
  13912. this.images = new Images(); // object with images
  13913. this.images.setOnloadCallback(function () {
  13914. graph._redraw();
  13915. });
  13916. // keyboard navigation variables
  13917. this.xIncrement = 0;
  13918. this.yIncrement = 0;
  13919. this.zoomIncrement = 0;
  13920. // loading all the mixins:
  13921. // load the force calculation functions, grouped under the physics system.
  13922. this._loadPhysicsSystem();
  13923. // create a frame and canvas
  13924. this._create();
  13925. // load the sector system. (mandatory, fully integrated with Graph)
  13926. this._loadSectorSystem();
  13927. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  13928. this._loadClusterSystem();
  13929. // load the selection system. (mandatory, required by Graph)
  13930. this._loadSelectionSystem();
  13931. // load the selection system. (mandatory, required by Graph)
  13932. this._loadHierarchySystem();
  13933. // apply options
  13934. this.setOptions(options);
  13935. // other vars
  13936. this.freezeSimulation = false;// freeze the simulation
  13937. this.cachedFunctions = {};
  13938. // containers for nodes and edges
  13939. this.calculationNodes = {};
  13940. this.calculationNodeIndices = [];
  13941. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  13942. this.nodes = {}; // object with Node objects
  13943. this.edges = {}; // object with Edge objects
  13944. // position and scale variables and objects
  13945. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  13946. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13947. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  13948. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  13949. this.scale = 1; // defining the global scale variable in the constructor
  13950. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  13951. // datasets or dataviews
  13952. this.nodesData = null; // A DataSet or DataView
  13953. this.edgesData = null; // A DataSet or DataView
  13954. // create event listeners used to subscribe on the DataSets of the nodes and edges
  13955. this.nodesListeners = {
  13956. 'add': function (event, params) {
  13957. graph._addNodes(params.items);
  13958. graph.start();
  13959. },
  13960. 'update': function (event, params) {
  13961. graph._updateNodes(params.items);
  13962. graph.start();
  13963. },
  13964. 'remove': function (event, params) {
  13965. graph._removeNodes(params.items);
  13966. graph.start();
  13967. }
  13968. };
  13969. this.edgesListeners = {
  13970. 'add': function (event, params) {
  13971. graph._addEdges(params.items);
  13972. graph.start();
  13973. },
  13974. 'update': function (event, params) {
  13975. graph._updateEdges(params.items);
  13976. graph.start();
  13977. },
  13978. 'remove': function (event, params) {
  13979. graph._removeEdges(params.items);
  13980. graph.start();
  13981. }
  13982. };
  13983. // properties for the animation
  13984. this.moving = true;
  13985. this.timer = undefined; // Scheduling function. Is definded in this.start();
  13986. // load data (the disable start variable will be the same as the enabled clustering)
  13987. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  13988. // hierarchical layout
  13989. if (this.constants.hierarchicalLayout.enabled == true) {
  13990. this._setupHierarchicalLayout();
  13991. }
  13992. else {
  13993. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  13994. if (this.stabilize == false) {
  13995. this.zoomExtent(true,this.constants.clustering.enabled);
  13996. }
  13997. }
  13998. // if clustering is disabled, the simulation will have started in the setData function
  13999. if (this.constants.clustering.enabled) {
  14000. this.startWithClustering();
  14001. }
  14002. }
  14003. // Extend Graph with an Emitter mixin
  14004. Emitter(Graph.prototype);
  14005. /**
  14006. * Get the script path where the vis.js library is located
  14007. *
  14008. * @returns {string | null} path Path or null when not found. Path does not
  14009. * end with a slash.
  14010. * @private
  14011. */
  14012. Graph.prototype._getScriptPath = function() {
  14013. var scripts = document.getElementsByTagName( 'script' );
  14014. // find script named vis.js or vis.min.js
  14015. for (var i = 0; i < scripts.length; i++) {
  14016. var src = scripts[i].src;
  14017. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  14018. if (match) {
  14019. // return path without the script name
  14020. return src.substring(0, src.length - match[0].length);
  14021. }
  14022. }
  14023. return null;
  14024. };
  14025. /**
  14026. * Find the center position of the graph
  14027. * @private
  14028. */
  14029. Graph.prototype._getRange = function() {
  14030. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  14031. for (var nodeId in this.nodes) {
  14032. if (this.nodes.hasOwnProperty(nodeId)) {
  14033. node = this.nodes[nodeId];
  14034. if (minX > (node.x)) {minX = node.x;}
  14035. if (maxX < (node.x)) {maxX = node.x;}
  14036. if (minY > (node.y)) {minY = node.y;}
  14037. if (maxY < (node.y)) {maxY = node.y;}
  14038. }
  14039. }
  14040. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14041. };
  14042. /**
  14043. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14044. * @returns {{x: number, y: number}}
  14045. * @private
  14046. */
  14047. Graph.prototype._findCenter = function(range) {
  14048. return {x: (0.5 * (range.maxX + range.minX)),
  14049. y: (0.5 * (range.maxY + range.minY))};
  14050. };
  14051. /**
  14052. * center the graph
  14053. *
  14054. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14055. */
  14056. Graph.prototype._centerGraph = function(range) {
  14057. var center = this._findCenter(range);
  14058. center.x *= this.scale;
  14059. center.y *= this.scale;
  14060. center.x -= 0.5 * this.frame.canvas.clientWidth;
  14061. center.y -= 0.5 * this.frame.canvas.clientHeight;
  14062. this._setTranslation(-center.x,-center.y); // set at 0,0
  14063. };
  14064. /**
  14065. * This function zooms out to fit all data on screen based on amount of nodes
  14066. *
  14067. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  14068. */
  14069. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  14070. if (initialZoom === undefined) {
  14071. initialZoom = false;
  14072. }
  14073. if (disableStart === undefined) {
  14074. disableStart = false;
  14075. }
  14076. var range = this._getRange();
  14077. var zoomLevel;
  14078. if (initialZoom == true) {
  14079. var numberOfNodes = this.nodeIndices.length;
  14080. if (this.constants.smoothCurves == true) {
  14081. if (this.constants.clustering.enabled == true &&
  14082. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14083. 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.
  14084. }
  14085. else {
  14086. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14087. }
  14088. }
  14089. else {
  14090. if (this.constants.clustering.enabled == true &&
  14091. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14092. 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.
  14093. }
  14094. else {
  14095. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14096. }
  14097. }
  14098. // correct for larger canvasses.
  14099. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  14100. zoomLevel *= factor;
  14101. }
  14102. else {
  14103. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  14104. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  14105. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  14106. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  14107. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  14108. }
  14109. if (zoomLevel > 1.0) {
  14110. zoomLevel = 1.0;
  14111. }
  14112. this._setScale(zoomLevel);
  14113. this._centerGraph(range);
  14114. if (disableStart == false) {
  14115. this.moving = true;
  14116. this.start();
  14117. }
  14118. };
  14119. /**
  14120. * Update the this.nodeIndices with the most recent node index list
  14121. * @private
  14122. */
  14123. Graph.prototype._updateNodeIndexList = function() {
  14124. this._clearNodeIndexList();
  14125. for (var idx in this.nodes) {
  14126. if (this.nodes.hasOwnProperty(idx)) {
  14127. this.nodeIndices.push(idx);
  14128. }
  14129. }
  14130. };
  14131. /**
  14132. * Set nodes and edges, and optionally options as well.
  14133. *
  14134. * @param {Object} data Object containing parameters:
  14135. * {Array | DataSet | DataView} [nodes] Array with nodes
  14136. * {Array | DataSet | DataView} [edges] Array with edges
  14137. * {String} [dot] String containing data in DOT format
  14138. * {Options} [options] Object with options
  14139. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  14140. */
  14141. Graph.prototype.setData = function(data, disableStart) {
  14142. if (disableStart === undefined) {
  14143. disableStart = false;
  14144. }
  14145. if (data && data.dot && (data.nodes || data.edges)) {
  14146. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  14147. ' parameter pair "nodes" and "edges", but not both.');
  14148. }
  14149. // set options
  14150. this.setOptions(data && data.options);
  14151. // set all data
  14152. if (data && data.dot) {
  14153. // parse DOT file
  14154. if(data && data.dot) {
  14155. var dotData = vis.util.DOTToGraph(data.dot);
  14156. this.setData(dotData);
  14157. return;
  14158. }
  14159. }
  14160. else {
  14161. this._setNodes(data && data.nodes);
  14162. this._setEdges(data && data.edges);
  14163. }
  14164. this._putDataInSector();
  14165. if (!disableStart) {
  14166. // find a stable position or start animating to a stable position
  14167. if (this.stabilize) {
  14168. this._doStabilize();
  14169. }
  14170. this.start();
  14171. }
  14172. };
  14173. /**
  14174. * Set options
  14175. * @param {Object} options
  14176. */
  14177. Graph.prototype.setOptions = function (options) {
  14178. if (options) {
  14179. var prop;
  14180. // retrieve parameter values
  14181. if (options.width !== undefined) {this.width = options.width;}
  14182. if (options.height !== undefined) {this.height = options.height;}
  14183. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14184. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14185. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14186. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14187. if (options.onAdd) {
  14188. this.triggerFunctions.add = options.onAdd;
  14189. }
  14190. if (options.onEdit) {
  14191. this.triggerFunctions.edit = options.onEdit;
  14192. }
  14193. if (options.onConnect) {
  14194. this.triggerFunctions.connect = options.onConnect;
  14195. }
  14196. if (options.onDelete) {
  14197. this.triggerFunctions.delete = options.onDelete;
  14198. }
  14199. if (options.physics) {
  14200. if (options.physics.barnesHut) {
  14201. this.constants.physics.barnesHut.enabled = true;
  14202. for (prop in options.physics.barnesHut) {
  14203. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14204. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14205. }
  14206. }
  14207. }
  14208. if (options.physics.repulsion) {
  14209. this.constants.physics.barnesHut.enabled = false;
  14210. for (prop in options.physics.repulsion) {
  14211. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14212. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14213. }
  14214. }
  14215. }
  14216. }
  14217. if (options.hierarchicalLayout) {
  14218. this.constants.hierarchicalLayout.enabled = true;
  14219. for (prop in options.hierarchicalLayout) {
  14220. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14221. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14222. }
  14223. }
  14224. }
  14225. else if (options.hierarchicalLayout !== undefined) {
  14226. this.constants.hierarchicalLayout.enabled = false;
  14227. }
  14228. if (options.clustering) {
  14229. this.constants.clustering.enabled = true;
  14230. for (prop in options.clustering) {
  14231. if (options.clustering.hasOwnProperty(prop)) {
  14232. this.constants.clustering[prop] = options.clustering[prop];
  14233. }
  14234. }
  14235. }
  14236. else if (options.clustering !== undefined) {
  14237. this.constants.clustering.enabled = false;
  14238. }
  14239. if (options.navigation) {
  14240. this.constants.navigation.enabled = true;
  14241. for (prop in options.navigation) {
  14242. if (options.navigation.hasOwnProperty(prop)) {
  14243. this.constants.navigation[prop] = options.navigation[prop];
  14244. }
  14245. }
  14246. }
  14247. else if (options.navigation !== undefined) {
  14248. this.constants.navigation.enabled = false;
  14249. }
  14250. if (options.keyboard) {
  14251. this.constants.keyboard.enabled = true;
  14252. for (prop in options.keyboard) {
  14253. if (options.keyboard.hasOwnProperty(prop)) {
  14254. this.constants.keyboard[prop] = options.keyboard[prop];
  14255. }
  14256. }
  14257. }
  14258. else if (options.keyboard !== undefined) {
  14259. this.constants.keyboard.enabled = false;
  14260. }
  14261. if (options.dataManipulation) {
  14262. this.constants.dataManipulation.enabled = true;
  14263. for (prop in options.dataManipulation) {
  14264. if (options.dataManipulation.hasOwnProperty(prop)) {
  14265. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14266. }
  14267. }
  14268. }
  14269. else if (options.dataManipulation !== undefined) {
  14270. this.constants.dataManipulation.enabled = false;
  14271. }
  14272. // TODO: work out these options and document them
  14273. if (options.edges) {
  14274. for (prop in options.edges) {
  14275. if (options.edges.hasOwnProperty(prop)) {
  14276. this.constants.edges[prop] = options.edges[prop];
  14277. }
  14278. }
  14279. if (!options.edges.fontColor) {
  14280. this.constants.edges.fontColor = options.edges.color;
  14281. }
  14282. // Added to support dashed lines
  14283. // David Jordan
  14284. // 2012-08-08
  14285. if (options.edges.dash) {
  14286. if (options.edges.dash.length !== undefined) {
  14287. this.constants.edges.dash.length = options.edges.dash.length;
  14288. }
  14289. if (options.edges.dash.gap !== undefined) {
  14290. this.constants.edges.dash.gap = options.edges.dash.gap;
  14291. }
  14292. if (options.edges.dash.altLength !== undefined) {
  14293. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14294. }
  14295. }
  14296. }
  14297. if (options.nodes) {
  14298. for (prop in options.nodes) {
  14299. if (options.nodes.hasOwnProperty(prop)) {
  14300. this.constants.nodes[prop] = options.nodes[prop];
  14301. }
  14302. }
  14303. if (options.nodes.color) {
  14304. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  14305. }
  14306. /*
  14307. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14308. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14309. */
  14310. }
  14311. if (options.groups) {
  14312. for (var groupname in options.groups) {
  14313. if (options.groups.hasOwnProperty(groupname)) {
  14314. var group = options.groups[groupname];
  14315. this.groups.add(groupname, group);
  14316. }
  14317. }
  14318. }
  14319. }
  14320. // (Re)loading the mixins that can be enabled or disabled in the options.
  14321. // load the force calculation functions, grouped under the physics system.
  14322. this._loadPhysicsSystem();
  14323. // load the navigation system.
  14324. this._loadNavigationControls();
  14325. // load the data manipulation system
  14326. this._loadManipulationSystem();
  14327. // configure the smooth curves
  14328. this._configureSmoothCurves();
  14329. // bind keys. If disabled, this will not do anything;
  14330. this._createKeyBinds();
  14331. this.setSize(this.width, this.height);
  14332. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14333. this._setScale(1);
  14334. this._redraw();
  14335. };
  14336. /**
  14337. * Create the main frame for the Graph.
  14338. * This function is executed once when a Graph object is created. The frame
  14339. * contains a canvas, and this canvas contains all objects like the axis and
  14340. * nodes.
  14341. * @private
  14342. */
  14343. Graph.prototype._create = function () {
  14344. // remove all elements from the container element.
  14345. while (this.containerElement.hasChildNodes()) {
  14346. this.containerElement.removeChild(this.containerElement.firstChild);
  14347. }
  14348. this.frame = document.createElement('div');
  14349. this.frame.className = 'graph-frame';
  14350. this.frame.style.position = 'relative';
  14351. this.frame.style.overflow = 'hidden';
  14352. this.frame.style.zIndex = "1";
  14353. // create the graph canvas (HTML canvas element)
  14354. this.frame.canvas = document.createElement( 'canvas' );
  14355. this.frame.canvas.style.position = 'relative';
  14356. this.frame.appendChild(this.frame.canvas);
  14357. if (!this.frame.canvas.getContext) {
  14358. var noCanvas = document.createElement( 'DIV' );
  14359. noCanvas.style.color = 'red';
  14360. noCanvas.style.fontWeight = 'bold' ;
  14361. noCanvas.style.padding = '10px';
  14362. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14363. this.frame.canvas.appendChild(noCanvas);
  14364. }
  14365. var me = this;
  14366. this.drag = {};
  14367. this.pinch = {};
  14368. this.hammer = Hammer(this.frame.canvas, {
  14369. prevent_default: true
  14370. });
  14371. this.hammer.on('tap', me._onTap.bind(me) );
  14372. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14373. this.hammer.on('hold', me._onHold.bind(me) );
  14374. this.hammer.on('pinch', me._onPinch.bind(me) );
  14375. this.hammer.on('touch', me._onTouch.bind(me) );
  14376. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14377. this.hammer.on('drag', me._onDrag.bind(me) );
  14378. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14379. this.hammer.on('release', me._onRelease.bind(me) );
  14380. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14381. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14382. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14383. // add the frame to the container element
  14384. this.containerElement.appendChild(this.frame);
  14385. };
  14386. /**
  14387. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14388. * @private
  14389. */
  14390. Graph.prototype._createKeyBinds = function() {
  14391. var me = this;
  14392. this.mousetrap = mousetrap;
  14393. this.mousetrap.reset();
  14394. if (this.constants.keyboard.enabled == true) {
  14395. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14396. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14397. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14398. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14399. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14400. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14401. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14402. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14403. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14404. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14405. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14406. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14407. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14408. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14409. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14410. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14411. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14412. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14413. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14414. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14415. }
  14416. if (this.constants.dataManipulation.enabled == true) {
  14417. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14418. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14419. }
  14420. };
  14421. /**
  14422. * Get the pointer location from a touch location
  14423. * @param {{pageX: Number, pageY: Number}} touch
  14424. * @return {{x: Number, y: Number}} pointer
  14425. * @private
  14426. */
  14427. Graph.prototype._getPointer = function (touch) {
  14428. return {
  14429. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14430. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14431. };
  14432. };
  14433. /**
  14434. * On start of a touch gesture, store the pointer
  14435. * @param event
  14436. * @private
  14437. */
  14438. Graph.prototype._onTouch = function (event) {
  14439. this.drag.pointer = this._getPointer(event.gesture.center);
  14440. this.drag.pinched = false;
  14441. this.pinch.scale = this._getScale();
  14442. this._handleTouch(this.drag.pointer);
  14443. };
  14444. /**
  14445. * handle drag start event
  14446. * @private
  14447. */
  14448. Graph.prototype._onDragStart = function () {
  14449. this._handleDragStart();
  14450. };
  14451. /**
  14452. * This function is called by _onDragStart.
  14453. * It is separated out because we can then overload it for the datamanipulation system.
  14454. *
  14455. * @private
  14456. */
  14457. Graph.prototype._handleDragStart = function() {
  14458. var drag = this.drag;
  14459. var node = this._getNodeAt(drag.pointer);
  14460. // note: drag.pointer is set in _onTouch to get the initial touch location
  14461. drag.dragging = true;
  14462. drag.selection = [];
  14463. drag.translation = this._getTranslation();
  14464. drag.nodeId = null;
  14465. if (node != null) {
  14466. drag.nodeId = node.id;
  14467. // select the clicked node if not yet selected
  14468. if (!node.isSelected()) {
  14469. this._selectObject(node,false);
  14470. }
  14471. // create an array with the selected nodes and their original location and status
  14472. for (var objectId in this.selectionObj) {
  14473. if (this.selectionObj.hasOwnProperty(objectId)) {
  14474. var object = this.selectionObj[objectId];
  14475. if (object instanceof Node) {
  14476. var s = {
  14477. id: object.id,
  14478. node: object,
  14479. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14480. x: object.x,
  14481. y: object.y,
  14482. xFixed: object.xFixed,
  14483. yFixed: object.yFixed
  14484. };
  14485. object.xFixed = true;
  14486. object.yFixed = true;
  14487. drag.selection.push(s);
  14488. }
  14489. }
  14490. }
  14491. }
  14492. };
  14493. /**
  14494. * handle drag event
  14495. * @private
  14496. */
  14497. Graph.prototype._onDrag = function (event) {
  14498. this._handleOnDrag(event)
  14499. };
  14500. /**
  14501. * This function is called by _onDrag.
  14502. * It is separated out because we can then overload it for the datamanipulation system.
  14503. *
  14504. * @private
  14505. */
  14506. Graph.prototype._handleOnDrag = function(event) {
  14507. if (this.drag.pinched) {
  14508. return;
  14509. }
  14510. var pointer = this._getPointer(event.gesture.center);
  14511. var me = this,
  14512. drag = this.drag,
  14513. selection = drag.selection;
  14514. if (selection && selection.length) {
  14515. // calculate delta's and new location
  14516. var deltaX = pointer.x - drag.pointer.x,
  14517. deltaY = pointer.y - drag.pointer.y;
  14518. // update position of all selected nodes
  14519. selection.forEach(function (s) {
  14520. var node = s.node;
  14521. if (!s.xFixed) {
  14522. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14523. }
  14524. if (!s.yFixed) {
  14525. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14526. }
  14527. });
  14528. // start _animationStep if not yet running
  14529. if (!this.moving) {
  14530. this.moving = true;
  14531. this.start();
  14532. }
  14533. }
  14534. else {
  14535. // move the graph
  14536. var diffX = pointer.x - this.drag.pointer.x;
  14537. var diffY = pointer.y - this.drag.pointer.y;
  14538. this._setTranslation(
  14539. this.drag.translation.x + diffX,
  14540. this.drag.translation.y + diffY);
  14541. this._redraw();
  14542. this.moved = true;
  14543. }
  14544. };
  14545. /**
  14546. * handle drag start event
  14547. * @private
  14548. */
  14549. Graph.prototype._onDragEnd = function () {
  14550. this.drag.dragging = false;
  14551. var selection = this.drag.selection;
  14552. if (selection) {
  14553. selection.forEach(function (s) {
  14554. // restore original xFixed and yFixed
  14555. s.node.xFixed = s.xFixed;
  14556. s.node.yFixed = s.yFixed;
  14557. });
  14558. }
  14559. };
  14560. /**
  14561. * handle tap/click event: select/unselect a node
  14562. * @private
  14563. */
  14564. Graph.prototype._onTap = function (event) {
  14565. var pointer = this._getPointer(event.gesture.center);
  14566. this.pointerPosition = pointer;
  14567. this._handleTap(pointer);
  14568. };
  14569. /**
  14570. * handle doubletap event
  14571. * @private
  14572. */
  14573. Graph.prototype._onDoubleTap = function (event) {
  14574. var pointer = this._getPointer(event.gesture.center);
  14575. this._handleDoubleTap(pointer);
  14576. };
  14577. /**
  14578. * handle long tap event: multi select nodes
  14579. * @private
  14580. */
  14581. Graph.prototype._onHold = function (event) {
  14582. var pointer = this._getPointer(event.gesture.center);
  14583. this.pointerPosition = pointer;
  14584. this._handleOnHold(pointer);
  14585. };
  14586. /**
  14587. * handle the release of the screen
  14588. *
  14589. * @private
  14590. */
  14591. Graph.prototype._onRelease = function (event) {
  14592. var pointer = this._getPointer(event.gesture.center);
  14593. this._handleOnRelease(pointer);
  14594. };
  14595. /**
  14596. * Handle pinch event
  14597. * @param event
  14598. * @private
  14599. */
  14600. Graph.prototype._onPinch = function (event) {
  14601. var pointer = this._getPointer(event.gesture.center);
  14602. this.drag.pinched = true;
  14603. if (!('scale' in this.pinch)) {
  14604. this.pinch.scale = 1;
  14605. }
  14606. // TODO: enabled moving while pinching?
  14607. var scale = this.pinch.scale * event.gesture.scale;
  14608. this._zoom(scale, pointer)
  14609. };
  14610. /**
  14611. * Zoom the graph in or out
  14612. * @param {Number} scale a number around 1, and between 0.01 and 10
  14613. * @param {{x: Number, y: Number}} pointer Position on screen
  14614. * @return {Number} appliedScale scale is limited within the boundaries
  14615. * @private
  14616. */
  14617. Graph.prototype._zoom = function(scale, pointer) {
  14618. var scaleOld = this._getScale();
  14619. if (scale < 0.00001) {
  14620. scale = 0.00001;
  14621. }
  14622. if (scale > 10) {
  14623. scale = 10;
  14624. }
  14625. // + this.frame.canvas.clientHeight / 2
  14626. var translation = this._getTranslation();
  14627. var scaleFrac = scale / scaleOld;
  14628. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14629. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14630. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  14631. "y" : this._canvasToY(pointer.y)};
  14632. this._setScale(scale);
  14633. this._setTranslation(tx, ty);
  14634. this.updateClustersDefault();
  14635. this._redraw();
  14636. return scale;
  14637. };
  14638. /**
  14639. * Event handler for mouse wheel event, used to zoom the timeline
  14640. * See http://adomas.org/javascript-mouse-wheel/
  14641. * https://github.com/EightMedia/hammer.js/issues/256
  14642. * @param {MouseEvent} event
  14643. * @private
  14644. */
  14645. Graph.prototype._onMouseWheel = function(event) {
  14646. // retrieve delta
  14647. var delta = 0;
  14648. if (event.wheelDelta) { /* IE/Opera. */
  14649. delta = event.wheelDelta/120;
  14650. } else if (event.detail) { /* Mozilla case. */
  14651. // In Mozilla, sign of delta is different than in IE.
  14652. // Also, delta is multiple of 3.
  14653. delta = -event.detail/3;
  14654. }
  14655. // If delta is nonzero, handle it.
  14656. // Basically, delta is now positive if wheel was scrolled up,
  14657. // and negative, if wheel was scrolled down.
  14658. if (delta) {
  14659. // calculate the new scale
  14660. var scale = this._getScale();
  14661. var zoom = delta / 10;
  14662. if (delta < 0) {
  14663. zoom = zoom / (1 - zoom);
  14664. }
  14665. scale *= (1 + zoom);
  14666. // calculate the pointer location
  14667. var gesture = util.fakeGesture(this, event);
  14668. var pointer = this._getPointer(gesture.center);
  14669. // apply the new scale
  14670. this._zoom(scale, pointer);
  14671. }
  14672. // Prevent default actions caused by mouse wheel.
  14673. event.preventDefault();
  14674. };
  14675. /**
  14676. * Mouse move handler for checking whether the title moves over a node with a title.
  14677. * @param {Event} event
  14678. * @private
  14679. */
  14680. Graph.prototype._onMouseMoveTitle = function (event) {
  14681. var gesture = util.fakeGesture(this, event);
  14682. var pointer = this._getPointer(gesture.center);
  14683. // check if the previously selected node is still selected
  14684. if (this.popupNode) {
  14685. this._checkHidePopup(pointer);
  14686. }
  14687. // start a timeout that will check if the mouse is positioned above
  14688. // an element
  14689. var me = this;
  14690. var checkShow = function() {
  14691. me._checkShowPopup(pointer);
  14692. };
  14693. if (this.popupTimer) {
  14694. clearInterval(this.popupTimer); // stop any running calculationTimer
  14695. }
  14696. if (!this.drag.dragging) {
  14697. this.popupTimer = setTimeout(checkShow, 300);
  14698. }
  14699. };
  14700. /**
  14701. * Check if there is an element on the given position in the graph
  14702. * (a node or edge). If so, and if this element has a title,
  14703. * show a popup window with its title.
  14704. *
  14705. * @param {{x:Number, y:Number}} pointer
  14706. * @private
  14707. */
  14708. Graph.prototype._checkShowPopup = function (pointer) {
  14709. var obj = {
  14710. left: this._canvasToX(pointer.x),
  14711. top: this._canvasToY(pointer.y),
  14712. right: this._canvasToX(pointer.x),
  14713. bottom: this._canvasToY(pointer.y)
  14714. };
  14715. var id;
  14716. var lastPopupNode = this.popupNode;
  14717. if (this.popupNode == undefined) {
  14718. // search the nodes for overlap, select the top one in case of multiple nodes
  14719. var nodes = this.nodes;
  14720. for (id in nodes) {
  14721. if (nodes.hasOwnProperty(id)) {
  14722. var node = nodes[id];
  14723. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  14724. this.popupNode = node;
  14725. break;
  14726. }
  14727. }
  14728. }
  14729. }
  14730. if (this.popupNode === undefined) {
  14731. // search the edges for overlap
  14732. var edges = this.edges;
  14733. for (id in edges) {
  14734. if (edges.hasOwnProperty(id)) {
  14735. var edge = edges[id];
  14736. if (edge.connected && (edge.getTitle() !== undefined) &&
  14737. edge.isOverlappingWith(obj)) {
  14738. this.popupNode = edge;
  14739. break;
  14740. }
  14741. }
  14742. }
  14743. }
  14744. if (this.popupNode) {
  14745. // show popup message window
  14746. if (this.popupNode != lastPopupNode) {
  14747. var me = this;
  14748. if (!me.popup) {
  14749. me.popup = new Popup(me.frame);
  14750. }
  14751. // adjust a small offset such that the mouse cursor is located in the
  14752. // bottom left location of the popup, and you can easily move over the
  14753. // popup area
  14754. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  14755. me.popup.setText(me.popupNode.getTitle());
  14756. me.popup.show();
  14757. }
  14758. }
  14759. else {
  14760. if (this.popup) {
  14761. this.popup.hide();
  14762. }
  14763. }
  14764. };
  14765. /**
  14766. * Check if the popup must be hided, which is the case when the mouse is no
  14767. * longer hovering on the object
  14768. * @param {{x:Number, y:Number}} pointer
  14769. * @private
  14770. */
  14771. Graph.prototype._checkHidePopup = function (pointer) {
  14772. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  14773. this.popupNode = undefined;
  14774. if (this.popup) {
  14775. this.popup.hide();
  14776. }
  14777. }
  14778. };
  14779. /**
  14780. * Set a new size for the graph
  14781. * @param {string} width Width in pixels or percentage (for example '800px'
  14782. * or '50%')
  14783. * @param {string} height Height in pixels or percentage (for example '400px'
  14784. * or '30%')
  14785. */
  14786. Graph.prototype.setSize = function(width, height) {
  14787. this.frame.style.width = width;
  14788. this.frame.style.height = height;
  14789. this.frame.canvas.style.width = '100%';
  14790. this.frame.canvas.style.height = '100%';
  14791. this.frame.canvas.width = this.frame.canvas.clientWidth;
  14792. this.frame.canvas.height = this.frame.canvas.clientHeight;
  14793. if (this.manipulationDiv !== undefined) {
  14794. this.manipulationDiv.style.width = this.frame.canvas.clientWidth;
  14795. }
  14796. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  14797. };
  14798. /**
  14799. * Set a data set with nodes for the graph
  14800. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  14801. * @private
  14802. */
  14803. Graph.prototype._setNodes = function(nodes) {
  14804. var oldNodesData = this.nodesData;
  14805. if (nodes instanceof DataSet || nodes instanceof DataView) {
  14806. this.nodesData = nodes;
  14807. }
  14808. else if (nodes instanceof Array) {
  14809. this.nodesData = new DataSet();
  14810. this.nodesData.add(nodes);
  14811. }
  14812. else if (!nodes) {
  14813. this.nodesData = new DataSet();
  14814. }
  14815. else {
  14816. throw new TypeError('Array or DataSet expected');
  14817. }
  14818. if (oldNodesData) {
  14819. // unsubscribe from old dataset
  14820. util.forEach(this.nodesListeners, function (callback, event) {
  14821. oldNodesData.off(event, callback);
  14822. });
  14823. }
  14824. // remove drawn nodes
  14825. this.nodes = {};
  14826. if (this.nodesData) {
  14827. // subscribe to new dataset
  14828. var me = this;
  14829. util.forEach(this.nodesListeners, function (callback, event) {
  14830. me.nodesData.on(event, callback);
  14831. });
  14832. // draw all new nodes
  14833. var ids = this.nodesData.getIds();
  14834. this._addNodes(ids);
  14835. }
  14836. this._updateSelection();
  14837. };
  14838. /**
  14839. * Add nodes
  14840. * @param {Number[] | String[]} ids
  14841. * @private
  14842. */
  14843. Graph.prototype._addNodes = function(ids) {
  14844. var id;
  14845. for (var i = 0, len = ids.length; i < len; i++) {
  14846. id = ids[i];
  14847. var data = this.nodesData.get(id);
  14848. var node = new Node(data, this.images, this.groups, this.constants);
  14849. this.nodes[id] = node; // note: this may replace an existing node
  14850. if ((node.xFixed == false || node.yFixed == false) && this.createNodeOnClick != true) {
  14851. var radius = 10 * 0.1*ids.length;
  14852. var angle = 2 * Math.PI * Math.random();
  14853. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  14854. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  14855. // note: no not use node.isMoving() here, as that gives the current
  14856. // velocity of the node, which is zero after creation of the node.
  14857. this.moving = true;
  14858. }
  14859. }
  14860. this._updateNodeIndexList();
  14861. this._updateCalculationNodes();
  14862. this._reconnectEdges();
  14863. this._updateValueRange(this.nodes);
  14864. this.updateLabels();
  14865. };
  14866. /**
  14867. * Update existing nodes, or create them when not yet existing
  14868. * @param {Number[] | String[]} ids
  14869. * @private
  14870. */
  14871. Graph.prototype._updateNodes = function(ids) {
  14872. var nodes = this.nodes,
  14873. nodesData = this.nodesData;
  14874. for (var i = 0, len = ids.length; i < len; i++) {
  14875. var id = ids[i];
  14876. var node = nodes[id];
  14877. var data = nodesData.get(id);
  14878. if (node) {
  14879. // update node
  14880. node.setProperties(data, this.constants);
  14881. }
  14882. else {
  14883. // create node
  14884. node = new Node(properties, this.images, this.groups, this.constants);
  14885. nodes[id] = node;
  14886. if (!node.isFixed()) {
  14887. this.moving = true;
  14888. }
  14889. }
  14890. }
  14891. this._updateNodeIndexList();
  14892. this._reconnectEdges();
  14893. this._updateValueRange(nodes);
  14894. };
  14895. /**
  14896. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  14897. * @param {Number[] | String[]} ids
  14898. * @private
  14899. */
  14900. Graph.prototype._removeNodes = function(ids) {
  14901. var nodes = this.nodes;
  14902. for (var i = 0, len = ids.length; i < len; i++) {
  14903. var id = ids[i];
  14904. delete nodes[id];
  14905. }
  14906. this._updateNodeIndexList();
  14907. this._reconnectEdges();
  14908. this._updateSelection();
  14909. this._updateValueRange(nodes);
  14910. };
  14911. /**
  14912. * Load edges by reading the data table
  14913. * @param {Array | DataSet | DataView} edges The data containing the edges.
  14914. * @private
  14915. * @private
  14916. */
  14917. Graph.prototype._setEdges = function(edges) {
  14918. var oldEdgesData = this.edgesData;
  14919. if (edges instanceof DataSet || edges instanceof DataView) {
  14920. this.edgesData = edges;
  14921. }
  14922. else if (edges instanceof Array) {
  14923. this.edgesData = new DataSet();
  14924. this.edgesData.add(edges);
  14925. }
  14926. else if (!edges) {
  14927. this.edgesData = new DataSet();
  14928. }
  14929. else {
  14930. throw new TypeError('Array or DataSet expected');
  14931. }
  14932. if (oldEdgesData) {
  14933. // unsubscribe from old dataset
  14934. util.forEach(this.edgesListeners, function (callback, event) {
  14935. oldEdgesData.off(event, callback);
  14936. });
  14937. }
  14938. // remove drawn edges
  14939. this.edges = {};
  14940. if (this.edgesData) {
  14941. // subscribe to new dataset
  14942. var me = this;
  14943. util.forEach(this.edgesListeners, function (callback, event) {
  14944. me.edgesData.on(event, callback);
  14945. });
  14946. // draw all new nodes
  14947. var ids = this.edgesData.getIds();
  14948. this._addEdges(ids);
  14949. }
  14950. this._reconnectEdges();
  14951. };
  14952. /**
  14953. * Add edges
  14954. * @param {Number[] | String[]} ids
  14955. * @private
  14956. */
  14957. Graph.prototype._addEdges = function (ids) {
  14958. var edges = this.edges,
  14959. edgesData = this.edgesData;
  14960. for (var i = 0, len = ids.length; i < len; i++) {
  14961. var id = ids[i];
  14962. var oldEdge = edges[id];
  14963. if (oldEdge) {
  14964. oldEdge.disconnect();
  14965. }
  14966. var data = edgesData.get(id, {"showInternalIds" : true});
  14967. edges[id] = new Edge(data, this, this.constants);
  14968. }
  14969. this.moving = true;
  14970. this._updateValueRange(edges);
  14971. this._createBezierNodes();
  14972. this._updateCalculationNodes();
  14973. };
  14974. /**
  14975. * Update existing edges, or create them when not yet existing
  14976. * @param {Number[] | String[]} ids
  14977. * @private
  14978. */
  14979. Graph.prototype._updateEdges = function (ids) {
  14980. var edges = this.edges,
  14981. edgesData = this.edgesData;
  14982. for (var i = 0, len = ids.length; i < len; i++) {
  14983. var id = ids[i];
  14984. var data = edgesData.get(id);
  14985. var edge = edges[id];
  14986. if (edge) {
  14987. // update edge
  14988. edge.disconnect();
  14989. edge.setProperties(data, this.constants);
  14990. edge.connect();
  14991. }
  14992. else {
  14993. // create edge
  14994. edge = new Edge(data, this, this.constants);
  14995. this.edges[id] = edge;
  14996. }
  14997. }
  14998. this._createBezierNodes();
  14999. this.moving = true;
  15000. this._updateValueRange(edges);
  15001. };
  15002. /**
  15003. * Remove existing edges. Non existing ids will be ignored
  15004. * @param {Number[] | String[]} ids
  15005. * @private
  15006. */
  15007. Graph.prototype._removeEdges = function (ids) {
  15008. var edges = this.edges;
  15009. for (var i = 0, len = ids.length; i < len; i++) {
  15010. var id = ids[i];
  15011. var edge = edges[id];
  15012. if (edge) {
  15013. if (edge.via != null) {
  15014. delete this.sectors['support']['nodes'][edge.via.id];
  15015. }
  15016. edge.disconnect();
  15017. delete edges[id];
  15018. }
  15019. }
  15020. this.moving = true;
  15021. this._updateValueRange(edges);
  15022. this._updateCalculationNodes();
  15023. };
  15024. /**
  15025. * Reconnect all edges
  15026. * @private
  15027. */
  15028. Graph.prototype._reconnectEdges = function() {
  15029. var id,
  15030. nodes = this.nodes,
  15031. edges = this.edges;
  15032. for (id in nodes) {
  15033. if (nodes.hasOwnProperty(id)) {
  15034. nodes[id].edges = [];
  15035. }
  15036. }
  15037. for (id in edges) {
  15038. if (edges.hasOwnProperty(id)) {
  15039. var edge = edges[id];
  15040. edge.from = null;
  15041. edge.to = null;
  15042. edge.connect();
  15043. }
  15044. }
  15045. };
  15046. /**
  15047. * Update the values of all object in the given array according to the current
  15048. * value range of the objects in the array.
  15049. * @param {Object} obj An object containing a set of Edges or Nodes
  15050. * The objects must have a method getValue() and
  15051. * setValueRange(min, max).
  15052. * @private
  15053. */
  15054. Graph.prototype._updateValueRange = function(obj) {
  15055. var id;
  15056. // determine the range of the objects
  15057. var valueMin = undefined;
  15058. var valueMax = undefined;
  15059. for (id in obj) {
  15060. if (obj.hasOwnProperty(id)) {
  15061. var value = obj[id].getValue();
  15062. if (value !== undefined) {
  15063. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  15064. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  15065. }
  15066. }
  15067. }
  15068. // adjust the range of all objects
  15069. if (valueMin !== undefined && valueMax !== undefined) {
  15070. for (id in obj) {
  15071. if (obj.hasOwnProperty(id)) {
  15072. obj[id].setValueRange(valueMin, valueMax);
  15073. }
  15074. }
  15075. }
  15076. };
  15077. /**
  15078. * Redraw the graph with the current data
  15079. * chart will be resized too.
  15080. */
  15081. Graph.prototype.redraw = function() {
  15082. this.setSize(this.width, this.height);
  15083. this._redraw();
  15084. };
  15085. /**
  15086. * Redraw the graph with the current data
  15087. * @private
  15088. */
  15089. Graph.prototype._redraw = function() {
  15090. var ctx = this.frame.canvas.getContext('2d');
  15091. // clear the canvas
  15092. var w = this.frame.canvas.width;
  15093. var h = this.frame.canvas.height;
  15094. ctx.clearRect(0, 0, w, h);
  15095. // set scaling and translation
  15096. ctx.save();
  15097. ctx.translate(this.translation.x, this.translation.y);
  15098. ctx.scale(this.scale, this.scale);
  15099. this.canvasTopLeft = {
  15100. "x": this._canvasToX(0),
  15101. "y": this._canvasToY(0)
  15102. };
  15103. this.canvasBottomRight = {
  15104. "x": this._canvasToX(this.frame.canvas.clientWidth),
  15105. "y": this._canvasToY(this.frame.canvas.clientHeight)
  15106. };
  15107. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15108. this._doInAllSectors("_drawEdges",ctx);
  15109. this._doInAllSectors("_drawNodes",ctx,false);
  15110. // this._doInSupportSector("_drawNodes",ctx,true);
  15111. // this._drawTree(ctx,"#F00F0F");
  15112. // restore original scaling and translation
  15113. ctx.restore();
  15114. };
  15115. /**
  15116. * Set the translation of the graph
  15117. * @param {Number} offsetX Horizontal offset
  15118. * @param {Number} offsetY Vertical offset
  15119. * @private
  15120. */
  15121. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15122. if (this.translation === undefined) {
  15123. this.translation = {
  15124. x: 0,
  15125. y: 0
  15126. };
  15127. }
  15128. if (offsetX !== undefined) {
  15129. this.translation.x = offsetX;
  15130. }
  15131. if (offsetY !== undefined) {
  15132. this.translation.y = offsetY;
  15133. }
  15134. };
  15135. /**
  15136. * Get the translation of the graph
  15137. * @return {Object} translation An object with parameters x and y, both a number
  15138. * @private
  15139. */
  15140. Graph.prototype._getTranslation = function() {
  15141. return {
  15142. x: this.translation.x,
  15143. y: this.translation.y
  15144. };
  15145. };
  15146. /**
  15147. * Scale the graph
  15148. * @param {Number} scale Scaling factor 1.0 is unscaled
  15149. * @private
  15150. */
  15151. Graph.prototype._setScale = function(scale) {
  15152. this.scale = scale;
  15153. };
  15154. /**
  15155. * Get the current scale of the graph
  15156. * @return {Number} scale Scaling factor 1.0 is unscaled
  15157. * @private
  15158. */
  15159. Graph.prototype._getScale = function() {
  15160. return this.scale;
  15161. };
  15162. /**
  15163. * Convert a horizontal point on the HTML canvas to the x-value of the model
  15164. * @param {number} x
  15165. * @returns {number}
  15166. * @private
  15167. */
  15168. Graph.prototype._canvasToX = function(x) {
  15169. return (x - this.translation.x) / this.scale;
  15170. };
  15171. /**
  15172. * Convert an x-value in the model to a horizontal point on the HTML canvas
  15173. * @param {number} x
  15174. * @returns {number}
  15175. * @private
  15176. */
  15177. Graph.prototype._xToCanvas = function(x) {
  15178. return x * this.scale + this.translation.x;
  15179. };
  15180. /**
  15181. * Convert a vertical point on the HTML canvas to the y-value of the model
  15182. * @param {number} y
  15183. * @returns {number}
  15184. * @private
  15185. */
  15186. Graph.prototype._canvasToY = function(y) {
  15187. return (y - this.translation.y) / this.scale;
  15188. };
  15189. /**
  15190. * Convert an y-value in the model to a vertical point on the HTML canvas
  15191. * @param {number} y
  15192. * @returns {number}
  15193. * @private
  15194. */
  15195. Graph.prototype._yToCanvas = function(y) {
  15196. return y * this.scale + this.translation.y ;
  15197. };
  15198. /**
  15199. * Redraw all nodes
  15200. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15201. * @param {CanvasRenderingContext2D} ctx
  15202. * @param {Boolean} [alwaysShow]
  15203. * @private
  15204. */
  15205. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  15206. if (alwaysShow === undefined) {
  15207. alwaysShow = false;
  15208. }
  15209. // first draw the unselected nodes
  15210. var nodes = this.nodes;
  15211. var selected = [];
  15212. for (var id in nodes) {
  15213. if (nodes.hasOwnProperty(id)) {
  15214. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15215. if (nodes[id].isSelected()) {
  15216. selected.push(id);
  15217. }
  15218. else {
  15219. if (nodes[id].inArea() || alwaysShow) {
  15220. nodes[id].draw(ctx);
  15221. }
  15222. }
  15223. }
  15224. }
  15225. // draw the selected nodes on top
  15226. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15227. if (nodes[selected[s]].inArea() || alwaysShow) {
  15228. nodes[selected[s]].draw(ctx);
  15229. }
  15230. }
  15231. };
  15232. /**
  15233. * Redraw all edges
  15234. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15235. * @param {CanvasRenderingContext2D} ctx
  15236. * @private
  15237. */
  15238. Graph.prototype._drawEdges = function(ctx) {
  15239. var edges = this.edges;
  15240. for (var id in edges) {
  15241. if (edges.hasOwnProperty(id)) {
  15242. var edge = edges[id];
  15243. edge.setScale(this.scale);
  15244. if (edge.connected) {
  15245. edges[id].draw(ctx);
  15246. }
  15247. }
  15248. }
  15249. };
  15250. /**
  15251. * Find a stable position for all nodes
  15252. * @private
  15253. */
  15254. Graph.prototype._doStabilize = function() {
  15255. // find stable position
  15256. var count = 0;
  15257. while (this.moving && count < this.constants.maxIterations) {
  15258. this._physicsTick();
  15259. count++;
  15260. }
  15261. this.zoomExtent(false,true);
  15262. };
  15263. /**
  15264. * Check if any of the nodes is still moving
  15265. * @param {number} vmin the minimum velocity considered as 'moving'
  15266. * @return {boolean} true if moving, false if non of the nodes is moving
  15267. * @private
  15268. */
  15269. Graph.prototype._isMoving = function(vmin) {
  15270. var nodes = this.nodes;
  15271. for (var id in nodes) {
  15272. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15273. return true;
  15274. }
  15275. }
  15276. return false;
  15277. };
  15278. /**
  15279. * /**
  15280. * Perform one discrete step for all nodes
  15281. *
  15282. * @private
  15283. */
  15284. Graph.prototype._discreteStepNodes = function() {
  15285. var interval = 0.65;
  15286. var nodes = this.nodes;
  15287. var nodeId;
  15288. if (this.constants.maxVelocity > 0) {
  15289. for (nodeId in nodes) {
  15290. if (nodes.hasOwnProperty(nodeId)) {
  15291. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15292. }
  15293. }
  15294. }
  15295. else {
  15296. for (nodeId in nodes) {
  15297. if (nodes.hasOwnProperty(nodeId)) {
  15298. nodes[nodeId].discreteStep(interval);
  15299. }
  15300. }
  15301. }
  15302. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15303. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15304. this.moving = true;
  15305. }
  15306. else {
  15307. this.moving = this._isMoving(vminCorrected);
  15308. }
  15309. };
  15310. Graph.prototype._physicsTick = function() {
  15311. if (!this.freezeSimulation) {
  15312. if (this.moving) {
  15313. this._doInAllActiveSectors("_initializeForceCalculation");
  15314. if (this.constants.smoothCurves) {
  15315. this._doInSupportSector("_discreteStepNodes");
  15316. }
  15317. this._doInAllActiveSectors("_discreteStepNodes");
  15318. this._findCenter(this._getRange())
  15319. }
  15320. }
  15321. };
  15322. /**
  15323. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15324. * It reschedules itself at the beginning of the function
  15325. *
  15326. * @private
  15327. */
  15328. Graph.prototype._animationStep = function() {
  15329. // reset the timer so a new scheduled animation step can be set
  15330. this.timer = undefined;
  15331. // handle the keyboad movement
  15332. this._handleNavigation();
  15333. // this schedules a new animation step
  15334. this.start();
  15335. // start the physics simulation
  15336. var calculationTime = Date.now();
  15337. var maxSteps = 1;
  15338. this._physicsTick();
  15339. var timeRequired = Date.now() - calculationTime;
  15340. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxRenderSteps) {
  15341. this._physicsTick();
  15342. timeRequired = Date.now() - calculationTime;
  15343. maxSteps++;
  15344. }
  15345. // start the rendering process
  15346. var renderTime = Date.now();
  15347. this._redraw();
  15348. this.renderTime = Date.now() - renderTime;
  15349. };
  15350. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15351. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15352. /**
  15353. * Schedule a animation step with the refreshrate interval.
  15354. *
  15355. * @poram {Boolean} runCalculationStep
  15356. */
  15357. Graph.prototype.start = function() {
  15358. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15359. if (!this.timer) {
  15360. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15361. }
  15362. }
  15363. else {
  15364. this._redraw();
  15365. }
  15366. };
  15367. /**
  15368. * Move the graph according to the keyboard presses.
  15369. *
  15370. * @private
  15371. */
  15372. Graph.prototype._handleNavigation = function() {
  15373. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15374. var translation = this._getTranslation();
  15375. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15376. }
  15377. if (this.zoomIncrement != 0) {
  15378. var center = {
  15379. x: this.frame.canvas.clientWidth / 2,
  15380. y: this.frame.canvas.clientHeight / 2
  15381. };
  15382. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15383. }
  15384. };
  15385. /**
  15386. * Freeze the _animationStep
  15387. */
  15388. Graph.prototype.toggleFreeze = function() {
  15389. if (this.freezeSimulation == false) {
  15390. this.freezeSimulation = true;
  15391. }
  15392. else {
  15393. this.freezeSimulation = false;
  15394. this.start();
  15395. }
  15396. };
  15397. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15398. if (disableStart === undefined) {
  15399. disableStart = true;
  15400. }
  15401. if (this.constants.smoothCurves == true) {
  15402. this._createBezierNodes();
  15403. }
  15404. else {
  15405. // delete the support nodes
  15406. this.sectors['support']['nodes'] = {};
  15407. for (var edgeId in this.edges) {
  15408. if (this.edges.hasOwnProperty(edgeId)) {
  15409. this.edges[edgeId].smooth = false;
  15410. this.edges[edgeId].via = null;
  15411. }
  15412. }
  15413. }
  15414. this._updateCalculationNodes();
  15415. if (!disableStart) {
  15416. this.moving = true;
  15417. this.start();
  15418. }
  15419. };
  15420. Graph.prototype._createBezierNodes = function() {
  15421. if (this.constants.smoothCurves == true) {
  15422. for (var edgeId in this.edges) {
  15423. if (this.edges.hasOwnProperty(edgeId)) {
  15424. var edge = this.edges[edgeId];
  15425. if (edge.via == null) {
  15426. edge.smooth = true;
  15427. var nodeId = "edgeId:".concat(edge.id);
  15428. this.sectors['support']['nodes'][nodeId] = new Node(
  15429. {id:nodeId,
  15430. mass:1,
  15431. shape:'circle',
  15432. internalMultiplier:1
  15433. },{},{},this.constants);
  15434. edge.via = this.sectors['support']['nodes'][nodeId];
  15435. edge.via.parentEdgeId = edge.id;
  15436. edge.positionBezierNode();
  15437. }
  15438. }
  15439. }
  15440. }
  15441. };
  15442. Graph.prototype._initializeMixinLoaders = function () {
  15443. for (var mixinFunction in graphMixinLoaders) {
  15444. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15445. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15446. }
  15447. }
  15448. };
  15449. /**
  15450. * vis.js module exports
  15451. */
  15452. var vis = {
  15453. util: util,
  15454. Controller: Controller,
  15455. DataSet: DataSet,
  15456. DataView: DataView,
  15457. Range: Range,
  15458. Stack: Stack,
  15459. TimeStep: TimeStep,
  15460. components: {
  15461. items: {
  15462. Item: Item,
  15463. ItemBox: ItemBox,
  15464. ItemPoint: ItemPoint,
  15465. ItemRange: ItemRange
  15466. },
  15467. Component: Component,
  15468. Panel: Panel,
  15469. RootPanel: RootPanel,
  15470. ItemSet: ItemSet,
  15471. TimeAxis: TimeAxis
  15472. },
  15473. graph: {
  15474. Node: Node,
  15475. Edge: Edge,
  15476. Popup: Popup,
  15477. Groups: Groups,
  15478. Images: Images
  15479. },
  15480. Timeline: Timeline,
  15481. Graph: Graph
  15482. };
  15483. /**
  15484. * CommonJS module exports
  15485. */
  15486. if (typeof exports !== 'undefined') {
  15487. exports = vis;
  15488. }
  15489. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15490. module.exports = vis;
  15491. }
  15492. /**
  15493. * AMD module exports
  15494. */
  15495. if (typeof(define) === 'function') {
  15496. define(function () {
  15497. return vis;
  15498. });
  15499. }
  15500. /**
  15501. * Window exports
  15502. */
  15503. if (typeof window !== 'undefined') {
  15504. // attach the module to the window, load as a regular javascript file
  15505. window['vis'] = vis;
  15506. }
  15507. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15508. /**
  15509. * Expose `Emitter`.
  15510. */
  15511. module.exports = Emitter;
  15512. /**
  15513. * Initialize a new `Emitter`.
  15514. *
  15515. * @api public
  15516. */
  15517. function Emitter(obj) {
  15518. if (obj) return mixin(obj);
  15519. };
  15520. /**
  15521. * Mixin the emitter properties.
  15522. *
  15523. * @param {Object} obj
  15524. * @return {Object}
  15525. * @api private
  15526. */
  15527. function mixin(obj) {
  15528. for (var key in Emitter.prototype) {
  15529. obj[key] = Emitter.prototype[key];
  15530. }
  15531. return obj;
  15532. }
  15533. /**
  15534. * Listen on the given `event` with `fn`.
  15535. *
  15536. * @param {String} event
  15537. * @param {Function} fn
  15538. * @return {Emitter}
  15539. * @api public
  15540. */
  15541. Emitter.prototype.on =
  15542. Emitter.prototype.addEventListener = function(event, fn){
  15543. this._callbacks = this._callbacks || {};
  15544. (this._callbacks[event] = this._callbacks[event] || [])
  15545. .push(fn);
  15546. return this;
  15547. };
  15548. /**
  15549. * Adds an `event` listener that will be invoked a single
  15550. * time then automatically removed.
  15551. *
  15552. * @param {String} event
  15553. * @param {Function} fn
  15554. * @return {Emitter}
  15555. * @api public
  15556. */
  15557. Emitter.prototype.once = function(event, fn){
  15558. var self = this;
  15559. this._callbacks = this._callbacks || {};
  15560. function on() {
  15561. self.off(event, on);
  15562. fn.apply(this, arguments);
  15563. }
  15564. on.fn = fn;
  15565. this.on(event, on);
  15566. return this;
  15567. };
  15568. /**
  15569. * Remove the given callback for `event` or all
  15570. * registered callbacks.
  15571. *
  15572. * @param {String} event
  15573. * @param {Function} fn
  15574. * @return {Emitter}
  15575. * @api public
  15576. */
  15577. Emitter.prototype.off =
  15578. Emitter.prototype.removeListener =
  15579. Emitter.prototype.removeAllListeners =
  15580. Emitter.prototype.removeEventListener = function(event, fn){
  15581. this._callbacks = this._callbacks || {};
  15582. // all
  15583. if (0 == arguments.length) {
  15584. this._callbacks = {};
  15585. return this;
  15586. }
  15587. // specific event
  15588. var callbacks = this._callbacks[event];
  15589. if (!callbacks) return this;
  15590. // remove all handlers
  15591. if (1 == arguments.length) {
  15592. delete this._callbacks[event];
  15593. return this;
  15594. }
  15595. // remove specific handler
  15596. var cb;
  15597. for (var i = 0; i < callbacks.length; i++) {
  15598. cb = callbacks[i];
  15599. if (cb === fn || cb.fn === fn) {
  15600. callbacks.splice(i, 1);
  15601. break;
  15602. }
  15603. }
  15604. return this;
  15605. };
  15606. /**
  15607. * Emit `event` with the given args.
  15608. *
  15609. * @param {String} event
  15610. * @param {Mixed} ...
  15611. * @return {Emitter}
  15612. */
  15613. Emitter.prototype.emit = function(event){
  15614. this._callbacks = this._callbacks || {};
  15615. var args = [].slice.call(arguments, 1)
  15616. , callbacks = this._callbacks[event];
  15617. if (callbacks) {
  15618. callbacks = callbacks.slice(0);
  15619. for (var i = 0, len = callbacks.length; i < len; ++i) {
  15620. callbacks[i].apply(this, args);
  15621. }
  15622. }
  15623. return this;
  15624. };
  15625. /**
  15626. * Return array of callbacks for `event`.
  15627. *
  15628. * @param {String} event
  15629. * @return {Array}
  15630. * @api public
  15631. */
  15632. Emitter.prototype.listeners = function(event){
  15633. this._callbacks = this._callbacks || {};
  15634. return this._callbacks[event] || [];
  15635. };
  15636. /**
  15637. * Check if this emitter has `event` handlers.
  15638. *
  15639. * @param {String} event
  15640. * @return {Boolean}
  15641. * @api public
  15642. */
  15643. Emitter.prototype.hasListeners = function(event){
  15644. return !! this.listeners(event).length;
  15645. };
  15646. },{}],3:[function(require,module,exports){
  15647. /*! Hammer.JS - v1.0.5 - 2013-04-07
  15648. * http://eightmedia.github.com/hammer.js
  15649. *
  15650. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  15651. * Licensed under the MIT license */
  15652. (function(window, undefined) {
  15653. 'use strict';
  15654. /**
  15655. * Hammer
  15656. * use this to create instances
  15657. * @param {HTMLElement} element
  15658. * @param {Object} options
  15659. * @returns {Hammer.Instance}
  15660. * @constructor
  15661. */
  15662. var Hammer = function(element, options) {
  15663. return new Hammer.Instance(element, options || {});
  15664. };
  15665. // default settings
  15666. Hammer.defaults = {
  15667. // add styles and attributes to the element to prevent the browser from doing
  15668. // its native behavior. this doesnt prevent the scrolling, but cancels
  15669. // the contextmenu, tap highlighting etc
  15670. // set to false to disable this
  15671. stop_browser_behavior: {
  15672. // this also triggers onselectstart=false for IE
  15673. userSelect: 'none',
  15674. // this makes the element blocking in IE10 >, you could experiment with the value
  15675. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  15676. touchAction: 'none',
  15677. touchCallout: 'none',
  15678. contentZooming: 'none',
  15679. userDrag: 'none',
  15680. tapHighlightColor: 'rgba(0,0,0,0)'
  15681. }
  15682. // more settings are defined per gesture at gestures.js
  15683. };
  15684. // detect touchevents
  15685. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  15686. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  15687. // dont use mouseevents on mobile devices
  15688. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  15689. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  15690. // eventtypes per touchevent (start, move, end)
  15691. // are filled by Hammer.event.determineEventTypes on setup
  15692. Hammer.EVENT_TYPES = {};
  15693. // direction defines
  15694. Hammer.DIRECTION_DOWN = 'down';
  15695. Hammer.DIRECTION_LEFT = 'left';
  15696. Hammer.DIRECTION_UP = 'up';
  15697. Hammer.DIRECTION_RIGHT = 'right';
  15698. // pointer type
  15699. Hammer.POINTER_MOUSE = 'mouse';
  15700. Hammer.POINTER_TOUCH = 'touch';
  15701. Hammer.POINTER_PEN = 'pen';
  15702. // touch event defines
  15703. Hammer.EVENT_START = 'start';
  15704. Hammer.EVENT_MOVE = 'move';
  15705. Hammer.EVENT_END = 'end';
  15706. // hammer document where the base events are added at
  15707. Hammer.DOCUMENT = document;
  15708. // plugins namespace
  15709. Hammer.plugins = {};
  15710. // if the window events are set...
  15711. Hammer.READY = false;
  15712. /**
  15713. * setup events to detect gestures on the document
  15714. */
  15715. function setup() {
  15716. if(Hammer.READY) {
  15717. return;
  15718. }
  15719. // find what eventtypes we add listeners to
  15720. Hammer.event.determineEventTypes();
  15721. // Register all gestures inside Hammer.gestures
  15722. for(var name in Hammer.gestures) {
  15723. if(Hammer.gestures.hasOwnProperty(name)) {
  15724. Hammer.detection.register(Hammer.gestures[name]);
  15725. }
  15726. }
  15727. // Add touch events on the document
  15728. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  15729. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  15730. // Hammer is ready...!
  15731. Hammer.READY = true;
  15732. }
  15733. /**
  15734. * create new hammer instance
  15735. * all methods should return the instance itself, so it is chainable.
  15736. * @param {HTMLElement} element
  15737. * @param {Object} [options={}]
  15738. * @returns {Hammer.Instance}
  15739. * @constructor
  15740. */
  15741. Hammer.Instance = function(element, options) {
  15742. var self = this;
  15743. // setup HammerJS window events and register all gestures
  15744. // this also sets up the default options
  15745. setup();
  15746. this.element = element;
  15747. // start/stop detection option
  15748. this.enabled = true;
  15749. // merge options
  15750. this.options = Hammer.utils.extend(
  15751. Hammer.utils.extend({}, Hammer.defaults),
  15752. options || {});
  15753. // add some css to the element to prevent the browser from doing its native behavoir
  15754. if(this.options.stop_browser_behavior) {
  15755. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  15756. }
  15757. // start detection on touchstart
  15758. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  15759. if(self.enabled) {
  15760. Hammer.detection.startDetect(self, ev);
  15761. }
  15762. });
  15763. // return instance
  15764. return this;
  15765. };
  15766. Hammer.Instance.prototype = {
  15767. /**
  15768. * bind events to the instance
  15769. * @param {String} gesture
  15770. * @param {Function} handler
  15771. * @returns {Hammer.Instance}
  15772. */
  15773. on: function onEvent(gesture, handler){
  15774. var gestures = gesture.split(' ');
  15775. for(var t=0; t<gestures.length; t++) {
  15776. this.element.addEventListener(gestures[t], handler, false);
  15777. }
  15778. return this;
  15779. },
  15780. /**
  15781. * unbind events to the instance
  15782. * @param {String} gesture
  15783. * @param {Function} handler
  15784. * @returns {Hammer.Instance}
  15785. */
  15786. off: function offEvent(gesture, handler){
  15787. var gestures = gesture.split(' ');
  15788. for(var t=0; t<gestures.length; t++) {
  15789. this.element.removeEventListener(gestures[t], handler, false);
  15790. }
  15791. return this;
  15792. },
  15793. /**
  15794. * trigger gesture event
  15795. * @param {String} gesture
  15796. * @param {Object} eventData
  15797. * @returns {Hammer.Instance}
  15798. */
  15799. trigger: function triggerEvent(gesture, eventData){
  15800. // create DOM event
  15801. var event = Hammer.DOCUMENT.createEvent('Event');
  15802. event.initEvent(gesture, true, true);
  15803. event.gesture = eventData;
  15804. // trigger on the target if it is in the instance element,
  15805. // this is for event delegation tricks
  15806. var element = this.element;
  15807. if(Hammer.utils.hasParent(eventData.target, element)) {
  15808. element = eventData.target;
  15809. }
  15810. element.dispatchEvent(event);
  15811. return this;
  15812. },
  15813. /**
  15814. * enable of disable hammer.js detection
  15815. * @param {Boolean} state
  15816. * @returns {Hammer.Instance}
  15817. */
  15818. enable: function enable(state) {
  15819. this.enabled = state;
  15820. return this;
  15821. }
  15822. };
  15823. /**
  15824. * this holds the last move event,
  15825. * used to fix empty touchend issue
  15826. * see the onTouch event for an explanation
  15827. * @type {Object}
  15828. */
  15829. var last_move_event = null;
  15830. /**
  15831. * when the mouse is hold down, this is true
  15832. * @type {Boolean}
  15833. */
  15834. var enable_detect = false;
  15835. /**
  15836. * when touch events have been fired, this is true
  15837. * @type {Boolean}
  15838. */
  15839. var touch_triggered = false;
  15840. Hammer.event = {
  15841. /**
  15842. * simple addEventListener
  15843. * @param {HTMLElement} element
  15844. * @param {String} type
  15845. * @param {Function} handler
  15846. */
  15847. bindDom: function(element, type, handler) {
  15848. var types = type.split(' ');
  15849. for(var t=0; t<types.length; t++) {
  15850. element.addEventListener(types[t], handler, false);
  15851. }
  15852. },
  15853. /**
  15854. * touch events with mouse fallback
  15855. * @param {HTMLElement} element
  15856. * @param {String} eventType like Hammer.EVENT_MOVE
  15857. * @param {Function} handler
  15858. */
  15859. onTouch: function onTouch(element, eventType, handler) {
  15860. var self = this;
  15861. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  15862. var sourceEventType = ev.type.toLowerCase();
  15863. // onmouseup, but when touchend has been fired we do nothing.
  15864. // this is for touchdevices which also fire a mouseup on touchend
  15865. if(sourceEventType.match(/mouse/) && touch_triggered) {
  15866. return;
  15867. }
  15868. // mousebutton must be down or a touch event
  15869. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  15870. sourceEventType.match(/pointerdown/) || // pointerevents touch
  15871. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  15872. ){
  15873. enable_detect = true;
  15874. }
  15875. // we are in a touch event, set the touch triggered bool to true,
  15876. // this for the conflicts that may occur on ios and android
  15877. if(sourceEventType.match(/touch|pointer/)) {
  15878. touch_triggered = true;
  15879. }
  15880. // count the total touches on the screen
  15881. var count_touches = 0;
  15882. // when touch has been triggered in this detection session
  15883. // and we are now handling a mouse event, we stop that to prevent conflicts
  15884. if(enable_detect) {
  15885. // update pointerevent
  15886. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  15887. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15888. }
  15889. // touch
  15890. else if(sourceEventType.match(/touch/)) {
  15891. count_touches = ev.touches.length;
  15892. }
  15893. // mouse
  15894. else if(!touch_triggered) {
  15895. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  15896. }
  15897. // if we are in a end event, but when we remove one touch and
  15898. // we still have enough, set eventType to move
  15899. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  15900. eventType = Hammer.EVENT_MOVE;
  15901. }
  15902. // no touches, force the end event
  15903. else if(!count_touches) {
  15904. eventType = Hammer.EVENT_END;
  15905. }
  15906. // because touchend has no touches, and we often want to use these in our gestures,
  15907. // we send the last move event as our eventData in touchend
  15908. if(!count_touches && last_move_event !== null) {
  15909. ev = last_move_event;
  15910. }
  15911. // store the last move event
  15912. else {
  15913. last_move_event = ev;
  15914. }
  15915. // trigger the handler
  15916. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  15917. // remove pointerevent from list
  15918. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  15919. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  15920. }
  15921. }
  15922. //debug(sourceEventType +" "+ eventType);
  15923. // on the end we reset everything
  15924. if(!count_touches) {
  15925. last_move_event = null;
  15926. enable_detect = false;
  15927. touch_triggered = false;
  15928. Hammer.PointerEvent.reset();
  15929. }
  15930. });
  15931. },
  15932. /**
  15933. * we have different events for each device/browser
  15934. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  15935. */
  15936. determineEventTypes: function determineEventTypes() {
  15937. // determine the eventtype we want to set
  15938. var types;
  15939. // pointerEvents magic
  15940. if(Hammer.HAS_POINTEREVENTS) {
  15941. types = Hammer.PointerEvent.getEvents();
  15942. }
  15943. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  15944. else if(Hammer.NO_MOUSEEVENTS) {
  15945. types = [
  15946. 'touchstart',
  15947. 'touchmove',
  15948. 'touchend touchcancel'];
  15949. }
  15950. // for non pointer events browsers and mixed browsers,
  15951. // like chrome on windows8 touch laptop
  15952. else {
  15953. types = [
  15954. 'touchstart mousedown',
  15955. 'touchmove mousemove',
  15956. 'touchend touchcancel mouseup'];
  15957. }
  15958. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  15959. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  15960. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  15961. },
  15962. /**
  15963. * create touchlist depending on the event
  15964. * @param {Object} ev
  15965. * @param {String} eventType used by the fakemultitouch plugin
  15966. */
  15967. getTouchList: function getTouchList(ev/*, eventType*/) {
  15968. // get the fake pointerEvent touchlist
  15969. if(Hammer.HAS_POINTEREVENTS) {
  15970. return Hammer.PointerEvent.getTouchList();
  15971. }
  15972. // get the touchlist
  15973. else if(ev.touches) {
  15974. return ev.touches;
  15975. }
  15976. // make fake touchlist from mouse position
  15977. else {
  15978. return [{
  15979. identifier: 1,
  15980. pageX: ev.pageX,
  15981. pageY: ev.pageY,
  15982. target: ev.target
  15983. }];
  15984. }
  15985. },
  15986. /**
  15987. * collect event data for Hammer js
  15988. * @param {HTMLElement} element
  15989. * @param {String} eventType like Hammer.EVENT_MOVE
  15990. * @param {Object} eventData
  15991. */
  15992. collectEventData: function collectEventData(element, eventType, ev) {
  15993. var touches = this.getTouchList(ev, eventType);
  15994. // find out pointerType
  15995. var pointerType = Hammer.POINTER_TOUCH;
  15996. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  15997. pointerType = Hammer.POINTER_MOUSE;
  15998. }
  15999. return {
  16000. center : Hammer.utils.getCenter(touches),
  16001. timeStamp : new Date().getTime(),
  16002. target : ev.target,
  16003. touches : touches,
  16004. eventType : eventType,
  16005. pointerType : pointerType,
  16006. srcEvent : ev,
  16007. /**
  16008. * prevent the browser default actions
  16009. * mostly used to disable scrolling of the browser
  16010. */
  16011. preventDefault: function() {
  16012. if(this.srcEvent.preventManipulation) {
  16013. this.srcEvent.preventManipulation();
  16014. }
  16015. if(this.srcEvent.preventDefault) {
  16016. this.srcEvent.preventDefault();
  16017. }
  16018. },
  16019. /**
  16020. * stop bubbling the event up to its parents
  16021. */
  16022. stopPropagation: function() {
  16023. this.srcEvent.stopPropagation();
  16024. },
  16025. /**
  16026. * immediately stop gesture detection
  16027. * might be useful after a swipe was detected
  16028. * @return {*}
  16029. */
  16030. stopDetect: function() {
  16031. return Hammer.detection.stopDetect();
  16032. }
  16033. };
  16034. }
  16035. };
  16036. Hammer.PointerEvent = {
  16037. /**
  16038. * holds all pointers
  16039. * @type {Object}
  16040. */
  16041. pointers: {},
  16042. /**
  16043. * get a list of pointers
  16044. * @returns {Array} touchlist
  16045. */
  16046. getTouchList: function() {
  16047. var self = this;
  16048. var touchlist = [];
  16049. // we can use forEach since pointerEvents only is in IE10
  16050. Object.keys(self.pointers).sort().forEach(function(id) {
  16051. touchlist.push(self.pointers[id]);
  16052. });
  16053. return touchlist;
  16054. },
  16055. /**
  16056. * update the position of a pointer
  16057. * @param {String} type Hammer.EVENT_END
  16058. * @param {Object} pointerEvent
  16059. */
  16060. updatePointer: function(type, pointerEvent) {
  16061. if(type == Hammer.EVENT_END) {
  16062. this.pointers = {};
  16063. }
  16064. else {
  16065. pointerEvent.identifier = pointerEvent.pointerId;
  16066. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16067. }
  16068. return Object.keys(this.pointers).length;
  16069. },
  16070. /**
  16071. * check if ev matches pointertype
  16072. * @param {String} pointerType Hammer.POINTER_MOUSE
  16073. * @param {PointerEvent} ev
  16074. */
  16075. matchType: function(pointerType, ev) {
  16076. if(!ev.pointerType) {
  16077. return false;
  16078. }
  16079. var types = {};
  16080. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16081. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16082. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16083. return types[pointerType];
  16084. },
  16085. /**
  16086. * get events
  16087. */
  16088. getEvents: function() {
  16089. return [
  16090. 'pointerdown MSPointerDown',
  16091. 'pointermove MSPointerMove',
  16092. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16093. ];
  16094. },
  16095. /**
  16096. * reset the list
  16097. */
  16098. reset: function() {
  16099. this.pointers = {};
  16100. }
  16101. };
  16102. Hammer.utils = {
  16103. /**
  16104. * extend method,
  16105. * also used for cloning when dest is an empty object
  16106. * @param {Object} dest
  16107. * @param {Object} src
  16108. * @parm {Boolean} merge do a merge
  16109. * @returns {Object} dest
  16110. */
  16111. extend: function extend(dest, src, merge) {
  16112. for (var key in src) {
  16113. if(dest[key] !== undefined && merge) {
  16114. continue;
  16115. }
  16116. dest[key] = src[key];
  16117. }
  16118. return dest;
  16119. },
  16120. /**
  16121. * find if a node is in the given parent
  16122. * used for event delegation tricks
  16123. * @param {HTMLElement} node
  16124. * @param {HTMLElement} parent
  16125. * @returns {boolean} has_parent
  16126. */
  16127. hasParent: function(node, parent) {
  16128. while(node){
  16129. if(node == parent) {
  16130. return true;
  16131. }
  16132. node = node.parentNode;
  16133. }
  16134. return false;
  16135. },
  16136. /**
  16137. * get the center of all the touches
  16138. * @param {Array} touches
  16139. * @returns {Object} center
  16140. */
  16141. getCenter: function getCenter(touches) {
  16142. var valuesX = [], valuesY = [];
  16143. for(var t= 0,len=touches.length; t<len; t++) {
  16144. valuesX.push(touches[t].pageX);
  16145. valuesY.push(touches[t].pageY);
  16146. }
  16147. return {
  16148. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  16149. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  16150. };
  16151. },
  16152. /**
  16153. * calculate the velocity between two points
  16154. * @param {Number} delta_time
  16155. * @param {Number} delta_x
  16156. * @param {Number} delta_y
  16157. * @returns {Object} velocity
  16158. */
  16159. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  16160. return {
  16161. x: Math.abs(delta_x / delta_time) || 0,
  16162. y: Math.abs(delta_y / delta_time) || 0
  16163. };
  16164. },
  16165. /**
  16166. * calculate the angle between two coordinates
  16167. * @param {Touch} touch1
  16168. * @param {Touch} touch2
  16169. * @returns {Number} angle
  16170. */
  16171. getAngle: function getAngle(touch1, touch2) {
  16172. var y = touch2.pageY - touch1.pageY,
  16173. x = touch2.pageX - touch1.pageX;
  16174. return Math.atan2(y, x) * 180 / Math.PI;
  16175. },
  16176. /**
  16177. * angle to direction define
  16178. * @param {Touch} touch1
  16179. * @param {Touch} touch2
  16180. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  16181. */
  16182. getDirection: function getDirection(touch1, touch2) {
  16183. var x = Math.abs(touch1.pageX - touch2.pageX),
  16184. y = Math.abs(touch1.pageY - touch2.pageY);
  16185. if(x >= y) {
  16186. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16187. }
  16188. else {
  16189. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16190. }
  16191. },
  16192. /**
  16193. * calculate the distance between two touches
  16194. * @param {Touch} touch1
  16195. * @param {Touch} touch2
  16196. * @returns {Number} distance
  16197. */
  16198. getDistance: function getDistance(touch1, touch2) {
  16199. var x = touch2.pageX - touch1.pageX,
  16200. y = touch2.pageY - touch1.pageY;
  16201. return Math.sqrt((x*x) + (y*y));
  16202. },
  16203. /**
  16204. * calculate the scale factor between two touchLists (fingers)
  16205. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16206. * @param {Array} start
  16207. * @param {Array} end
  16208. * @returns {Number} scale
  16209. */
  16210. getScale: function getScale(start, end) {
  16211. // need two fingers...
  16212. if(start.length >= 2 && end.length >= 2) {
  16213. return this.getDistance(end[0], end[1]) /
  16214. this.getDistance(start[0], start[1]);
  16215. }
  16216. return 1;
  16217. },
  16218. /**
  16219. * calculate the rotation degrees between two touchLists (fingers)
  16220. * @param {Array} start
  16221. * @param {Array} end
  16222. * @returns {Number} rotation
  16223. */
  16224. getRotation: function getRotation(start, end) {
  16225. // need two fingers
  16226. if(start.length >= 2 && end.length >= 2) {
  16227. return this.getAngle(end[1], end[0]) -
  16228. this.getAngle(start[1], start[0]);
  16229. }
  16230. return 0;
  16231. },
  16232. /**
  16233. * boolean if the direction is vertical
  16234. * @param {String} direction
  16235. * @returns {Boolean} is_vertical
  16236. */
  16237. isVertical: function isVertical(direction) {
  16238. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16239. },
  16240. /**
  16241. * stop browser default behavior with css props
  16242. * @param {HtmlElement} element
  16243. * @param {Object} css_props
  16244. */
  16245. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16246. var prop,
  16247. vendors = ['webkit','khtml','moz','ms','o',''];
  16248. if(!css_props || !element.style) {
  16249. return;
  16250. }
  16251. // with css properties for modern browsers
  16252. for(var i = 0; i < vendors.length; i++) {
  16253. for(var p in css_props) {
  16254. if(css_props.hasOwnProperty(p)) {
  16255. prop = p;
  16256. // vender prefix at the property
  16257. if(vendors[i]) {
  16258. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16259. }
  16260. // set the style
  16261. element.style[prop] = css_props[p];
  16262. }
  16263. }
  16264. }
  16265. // also the disable onselectstart
  16266. if(css_props.userSelect == 'none') {
  16267. element.onselectstart = function() {
  16268. return false;
  16269. };
  16270. }
  16271. }
  16272. };
  16273. Hammer.detection = {
  16274. // contains all registred Hammer.gestures in the correct order
  16275. gestures: [],
  16276. // data of the current Hammer.gesture detection session
  16277. current: null,
  16278. // the previous Hammer.gesture session data
  16279. // is a full clone of the previous gesture.current object
  16280. previous: null,
  16281. // when this becomes true, no gestures are fired
  16282. stopped: false,
  16283. /**
  16284. * start Hammer.gesture detection
  16285. * @param {Hammer.Instance} inst
  16286. * @param {Object} eventData
  16287. */
  16288. startDetect: function startDetect(inst, eventData) {
  16289. // already busy with a Hammer.gesture detection on an element
  16290. if(this.current) {
  16291. return;
  16292. }
  16293. this.stopped = false;
  16294. this.current = {
  16295. inst : inst, // reference to HammerInstance we're working for
  16296. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16297. lastEvent : false, // last eventData
  16298. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16299. };
  16300. this.detect(eventData);
  16301. },
  16302. /**
  16303. * Hammer.gesture detection
  16304. * @param {Object} eventData
  16305. * @param {Object} eventData
  16306. */
  16307. detect: function detect(eventData) {
  16308. if(!this.current || this.stopped) {
  16309. return;
  16310. }
  16311. // extend event data with calculations about scale, distance etc
  16312. eventData = this.extendEventData(eventData);
  16313. // instance options
  16314. var inst_options = this.current.inst.options;
  16315. // call Hammer.gesture handlers
  16316. for(var g=0,len=this.gestures.length; g<len; g++) {
  16317. var gesture = this.gestures[g];
  16318. // only when the instance options have enabled this gesture
  16319. if(!this.stopped && inst_options[gesture.name] !== false) {
  16320. // if a handler returns false, we stop with the detection
  16321. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16322. this.stopDetect();
  16323. break;
  16324. }
  16325. }
  16326. }
  16327. // store as previous event event
  16328. if(this.current) {
  16329. this.current.lastEvent = eventData;
  16330. }
  16331. // endevent, but not the last touch, so dont stop
  16332. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16333. this.stopDetect();
  16334. }
  16335. return eventData;
  16336. },
  16337. /**
  16338. * clear the Hammer.gesture vars
  16339. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16340. * to stop other Hammer.gestures from being fired
  16341. */
  16342. stopDetect: function stopDetect() {
  16343. // clone current data to the store as the previous gesture
  16344. // used for the double tap gesture, since this is an other gesture detect session
  16345. this.previous = Hammer.utils.extend({}, this.current);
  16346. // reset the current
  16347. this.current = null;
  16348. // stopped!
  16349. this.stopped = true;
  16350. },
  16351. /**
  16352. * extend eventData for Hammer.gestures
  16353. * @param {Object} ev
  16354. * @returns {Object} ev
  16355. */
  16356. extendEventData: function extendEventData(ev) {
  16357. var startEv = this.current.startEvent;
  16358. // if the touches change, set the new touches over the startEvent touches
  16359. // this because touchevents don't have all the touches on touchstart, or the
  16360. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16361. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16362. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16363. // extend 1 level deep to get the touchlist with the touch objects
  16364. startEv.touches = [];
  16365. for(var i=0,len=ev.touches.length; i<len; i++) {
  16366. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16367. }
  16368. }
  16369. var delta_time = ev.timeStamp - startEv.timeStamp,
  16370. delta_x = ev.center.pageX - startEv.center.pageX,
  16371. delta_y = ev.center.pageY - startEv.center.pageY,
  16372. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16373. Hammer.utils.extend(ev, {
  16374. deltaTime : delta_time,
  16375. deltaX : delta_x,
  16376. deltaY : delta_y,
  16377. velocityX : velocity.x,
  16378. velocityY : velocity.y,
  16379. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16380. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16381. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16382. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16383. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16384. startEvent : startEv
  16385. });
  16386. return ev;
  16387. },
  16388. /**
  16389. * register new gesture
  16390. * @param {Object} gesture object, see gestures.js for documentation
  16391. * @returns {Array} gestures
  16392. */
  16393. register: function register(gesture) {
  16394. // add an enable gesture options if there is no given
  16395. var options = gesture.defaults || {};
  16396. if(options[gesture.name] === undefined) {
  16397. options[gesture.name] = true;
  16398. }
  16399. // extend Hammer default options with the Hammer.gesture options
  16400. Hammer.utils.extend(Hammer.defaults, options, true);
  16401. // set its index
  16402. gesture.index = gesture.index || 1000;
  16403. // add Hammer.gesture to the list
  16404. this.gestures.push(gesture);
  16405. // sort the list by index
  16406. this.gestures.sort(function(a, b) {
  16407. if (a.index < b.index) {
  16408. return -1;
  16409. }
  16410. if (a.index > b.index) {
  16411. return 1;
  16412. }
  16413. return 0;
  16414. });
  16415. return this.gestures;
  16416. }
  16417. };
  16418. Hammer.gestures = Hammer.gestures || {};
  16419. /**
  16420. * Custom gestures
  16421. * ==============================
  16422. *
  16423. * Gesture object
  16424. * --------------------
  16425. * The object structure of a gesture:
  16426. *
  16427. * { name: 'mygesture',
  16428. * index: 1337,
  16429. * defaults: {
  16430. * mygesture_option: true
  16431. * }
  16432. * handler: function(type, ev, inst) {
  16433. * // trigger gesture event
  16434. * inst.trigger(this.name, ev);
  16435. * }
  16436. * }
  16437. * @param {String} name
  16438. * this should be the name of the gesture, lowercase
  16439. * it is also being used to disable/enable the gesture per instance config.
  16440. *
  16441. * @param {Number} [index=1000]
  16442. * the index of the gesture, where it is going to be in the stack of gestures detection
  16443. * like when you build an gesture that depends on the drag gesture, it is a good
  16444. * idea to place it after the index of the drag gesture.
  16445. *
  16446. * @param {Object} [defaults={}]
  16447. * the default settings of the gesture. these are added to the instance settings,
  16448. * and can be overruled per instance. you can also add the name of the gesture,
  16449. * but this is also added by default (and set to true).
  16450. *
  16451. * @param {Function} handler
  16452. * this handles the gesture detection of your custom gesture and receives the
  16453. * following arguments:
  16454. *
  16455. * @param {Object} eventData
  16456. * event data containing the following properties:
  16457. * timeStamp {Number} time the event occurred
  16458. * target {HTMLElement} target element
  16459. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16460. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16461. * center {Object} center position of the touches. contains pageX and pageY
  16462. * deltaTime {Number} the total time of the touches in the screen
  16463. * deltaX {Number} the delta on x axis we haved moved
  16464. * deltaY {Number} the delta on y axis we haved moved
  16465. * velocityX {Number} the velocity on the x
  16466. * velocityY {Number} the velocity on y
  16467. * angle {Number} the angle we are moving
  16468. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16469. * distance {Number} the distance we haved moved
  16470. * scale {Number} scaling of the touches, needs 2 touches
  16471. * rotation {Number} rotation of the touches, needs 2 touches *
  16472. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16473. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16474. * startEvent {Object} contains the same properties as above,
  16475. * but from the first touch. this is used to calculate
  16476. * distances, deltaTime, scaling etc
  16477. *
  16478. * @param {Hammer.Instance} inst
  16479. * the instance we are doing the detection for. you can get the options from
  16480. * the inst.options object and trigger the gesture event by calling inst.trigger
  16481. *
  16482. *
  16483. * Handle gestures
  16484. * --------------------
  16485. * inside the handler you can get/set Hammer.detection.current. This is the current
  16486. * detection session. It has the following properties
  16487. * @param {String} name
  16488. * contains the name of the gesture we have detected. it has not a real function,
  16489. * only to check in other gestures if something is detected.
  16490. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16491. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16492. *
  16493. * @readonly
  16494. * @param {Hammer.Instance} inst
  16495. * the instance we do the detection for
  16496. *
  16497. * @readonly
  16498. * @param {Object} startEvent
  16499. * contains the properties of the first gesture detection in this session.
  16500. * Used for calculations about timing, distance, etc.
  16501. *
  16502. * @readonly
  16503. * @param {Object} lastEvent
  16504. * contains all the properties of the last gesture detect in this session.
  16505. *
  16506. * after the gesture detection session has been completed (user has released the screen)
  16507. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16508. * this is usefull for gestures like doubletap, where you need to know if the
  16509. * previous gesture was a tap
  16510. *
  16511. * options that have been set by the instance can be received by calling inst.options
  16512. *
  16513. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16514. * The first param is the name of your gesture, the second the event argument
  16515. *
  16516. *
  16517. * Register gestures
  16518. * --------------------
  16519. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16520. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16521. * manually and pass your gesture object as a param
  16522. *
  16523. */
  16524. /**
  16525. * Hold
  16526. * Touch stays at the same place for x time
  16527. * @events hold
  16528. */
  16529. Hammer.gestures.Hold = {
  16530. name: 'hold',
  16531. index: 10,
  16532. defaults: {
  16533. hold_timeout : 500,
  16534. hold_threshold : 1
  16535. },
  16536. timer: null,
  16537. handler: function holdGesture(ev, inst) {
  16538. switch(ev.eventType) {
  16539. case Hammer.EVENT_START:
  16540. // clear any running timers
  16541. clearTimeout(this.timer);
  16542. // set the gesture so we can check in the timeout if it still is
  16543. Hammer.detection.current.name = this.name;
  16544. // set timer and if after the timeout it still is hold,
  16545. // we trigger the hold event
  16546. this.timer = setTimeout(function() {
  16547. if(Hammer.detection.current.name == 'hold') {
  16548. inst.trigger('hold', ev);
  16549. }
  16550. }, inst.options.hold_timeout);
  16551. break;
  16552. // when you move or end we clear the timer
  16553. case Hammer.EVENT_MOVE:
  16554. if(ev.distance > inst.options.hold_threshold) {
  16555. clearTimeout(this.timer);
  16556. }
  16557. break;
  16558. case Hammer.EVENT_END:
  16559. clearTimeout(this.timer);
  16560. break;
  16561. }
  16562. }
  16563. };
  16564. /**
  16565. * Tap/DoubleTap
  16566. * Quick touch at a place or double at the same place
  16567. * @events tap, doubletap
  16568. */
  16569. Hammer.gestures.Tap = {
  16570. name: 'tap',
  16571. index: 100,
  16572. defaults: {
  16573. tap_max_touchtime : 250,
  16574. tap_max_distance : 10,
  16575. tap_always : true,
  16576. doubletap_distance : 20,
  16577. doubletap_interval : 300
  16578. },
  16579. handler: function tapGesture(ev, inst) {
  16580. if(ev.eventType == Hammer.EVENT_END) {
  16581. // previous gesture, for the double tap since these are two different gesture detections
  16582. var prev = Hammer.detection.previous,
  16583. did_doubletap = false;
  16584. // when the touchtime is higher then the max touch time
  16585. // or when the moving distance is too much
  16586. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  16587. ev.distance > inst.options.tap_max_distance) {
  16588. return;
  16589. }
  16590. // check if double tap
  16591. if(prev && prev.name == 'tap' &&
  16592. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  16593. ev.distance < inst.options.doubletap_distance) {
  16594. inst.trigger('doubletap', ev);
  16595. did_doubletap = true;
  16596. }
  16597. // do a single tap
  16598. if(!did_doubletap || inst.options.tap_always) {
  16599. Hammer.detection.current.name = 'tap';
  16600. inst.trigger(Hammer.detection.current.name, ev);
  16601. }
  16602. }
  16603. }
  16604. };
  16605. /**
  16606. * Swipe
  16607. * triggers swipe events when the end velocity is above the threshold
  16608. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  16609. */
  16610. Hammer.gestures.Swipe = {
  16611. name: 'swipe',
  16612. index: 40,
  16613. defaults: {
  16614. // set 0 for unlimited, but this can conflict with transform
  16615. swipe_max_touches : 1,
  16616. swipe_velocity : 0.7
  16617. },
  16618. handler: function swipeGesture(ev, inst) {
  16619. if(ev.eventType == Hammer.EVENT_END) {
  16620. // max touches
  16621. if(inst.options.swipe_max_touches > 0 &&
  16622. ev.touches.length > inst.options.swipe_max_touches) {
  16623. return;
  16624. }
  16625. // when the distance we moved is too small we skip this gesture
  16626. // or we can be already in dragging
  16627. if(ev.velocityX > inst.options.swipe_velocity ||
  16628. ev.velocityY > inst.options.swipe_velocity) {
  16629. // trigger swipe events
  16630. inst.trigger(this.name, ev);
  16631. inst.trigger(this.name + ev.direction, ev);
  16632. }
  16633. }
  16634. }
  16635. };
  16636. /**
  16637. * Drag
  16638. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  16639. * moving left and right is a good practice. When all the drag events are blocking
  16640. * you disable scrolling on that area.
  16641. * @events drag, drapleft, dragright, dragup, dragdown
  16642. */
  16643. Hammer.gestures.Drag = {
  16644. name: 'drag',
  16645. index: 50,
  16646. defaults: {
  16647. drag_min_distance : 10,
  16648. // set 0 for unlimited, but this can conflict with transform
  16649. drag_max_touches : 1,
  16650. // prevent default browser behavior when dragging occurs
  16651. // be careful with it, it makes the element a blocking element
  16652. // when you are using the drag gesture, it is a good practice to set this true
  16653. drag_block_horizontal : false,
  16654. drag_block_vertical : false,
  16655. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  16656. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  16657. drag_lock_to_axis : false,
  16658. // drag lock only kicks in when distance > drag_lock_min_distance
  16659. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  16660. drag_lock_min_distance : 25
  16661. },
  16662. triggered: false,
  16663. handler: function dragGesture(ev, inst) {
  16664. // current gesture isnt drag, but dragged is true
  16665. // this means an other gesture is busy. now call dragend
  16666. if(Hammer.detection.current.name != this.name && this.triggered) {
  16667. inst.trigger(this.name +'end', ev);
  16668. this.triggered = false;
  16669. return;
  16670. }
  16671. // max touches
  16672. if(inst.options.drag_max_touches > 0 &&
  16673. ev.touches.length > inst.options.drag_max_touches) {
  16674. return;
  16675. }
  16676. switch(ev.eventType) {
  16677. case Hammer.EVENT_START:
  16678. this.triggered = false;
  16679. break;
  16680. case Hammer.EVENT_MOVE:
  16681. // when the distance we moved is too small we skip this gesture
  16682. // or we can be already in dragging
  16683. if(ev.distance < inst.options.drag_min_distance &&
  16684. Hammer.detection.current.name != this.name) {
  16685. return;
  16686. }
  16687. // we are dragging!
  16688. Hammer.detection.current.name = this.name;
  16689. // lock drag to axis?
  16690. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  16691. ev.drag_locked_to_axis = true;
  16692. }
  16693. var last_direction = Hammer.detection.current.lastEvent.direction;
  16694. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  16695. // keep direction on the axis that the drag gesture started on
  16696. if(Hammer.utils.isVertical(last_direction)) {
  16697. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16698. }
  16699. else {
  16700. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16701. }
  16702. }
  16703. // first time, trigger dragstart event
  16704. if(!this.triggered) {
  16705. inst.trigger(this.name +'start', ev);
  16706. this.triggered = true;
  16707. }
  16708. // trigger normal event
  16709. inst.trigger(this.name, ev);
  16710. // direction event, like dragdown
  16711. inst.trigger(this.name + ev.direction, ev);
  16712. // block the browser events
  16713. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  16714. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  16715. ev.preventDefault();
  16716. }
  16717. break;
  16718. case Hammer.EVENT_END:
  16719. // trigger dragend
  16720. if(this.triggered) {
  16721. inst.trigger(this.name +'end', ev);
  16722. }
  16723. this.triggered = false;
  16724. break;
  16725. }
  16726. }
  16727. };
  16728. /**
  16729. * Transform
  16730. * User want to scale or rotate with 2 fingers
  16731. * @events transform, pinch, pinchin, pinchout, rotate
  16732. */
  16733. Hammer.gestures.Transform = {
  16734. name: 'transform',
  16735. index: 45,
  16736. defaults: {
  16737. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  16738. transform_min_scale : 0.01,
  16739. // rotation in degrees
  16740. transform_min_rotation : 1,
  16741. // prevent default browser behavior when two touches are on the screen
  16742. // but it makes the element a blocking element
  16743. // when you are using the transform gesture, it is a good practice to set this true
  16744. transform_always_block : false
  16745. },
  16746. triggered: false,
  16747. handler: function transformGesture(ev, inst) {
  16748. // current gesture isnt drag, but dragged is true
  16749. // this means an other gesture is busy. now call dragend
  16750. if(Hammer.detection.current.name != this.name && this.triggered) {
  16751. inst.trigger(this.name +'end', ev);
  16752. this.triggered = false;
  16753. return;
  16754. }
  16755. // atleast multitouch
  16756. if(ev.touches.length < 2) {
  16757. return;
  16758. }
  16759. // prevent default when two fingers are on the screen
  16760. if(inst.options.transform_always_block) {
  16761. ev.preventDefault();
  16762. }
  16763. switch(ev.eventType) {
  16764. case Hammer.EVENT_START:
  16765. this.triggered = false;
  16766. break;
  16767. case Hammer.EVENT_MOVE:
  16768. var scale_threshold = Math.abs(1-ev.scale);
  16769. var rotation_threshold = Math.abs(ev.rotation);
  16770. // when the distance we moved is too small we skip this gesture
  16771. // or we can be already in dragging
  16772. if(scale_threshold < inst.options.transform_min_scale &&
  16773. rotation_threshold < inst.options.transform_min_rotation) {
  16774. return;
  16775. }
  16776. // we are transforming!
  16777. Hammer.detection.current.name = this.name;
  16778. // first time, trigger dragstart event
  16779. if(!this.triggered) {
  16780. inst.trigger(this.name +'start', ev);
  16781. this.triggered = true;
  16782. }
  16783. inst.trigger(this.name, ev); // basic transform event
  16784. // trigger rotate event
  16785. if(rotation_threshold > inst.options.transform_min_rotation) {
  16786. inst.trigger('rotate', ev);
  16787. }
  16788. // trigger pinch event
  16789. if(scale_threshold > inst.options.transform_min_scale) {
  16790. inst.trigger('pinch', ev);
  16791. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  16792. }
  16793. break;
  16794. case Hammer.EVENT_END:
  16795. // trigger dragend
  16796. if(this.triggered) {
  16797. inst.trigger(this.name +'end', ev);
  16798. }
  16799. this.triggered = false;
  16800. break;
  16801. }
  16802. }
  16803. };
  16804. /**
  16805. * Touch
  16806. * Called as first, tells the user has touched the screen
  16807. * @events touch
  16808. */
  16809. Hammer.gestures.Touch = {
  16810. name: 'touch',
  16811. index: -Infinity,
  16812. defaults: {
  16813. // call preventDefault at touchstart, and makes the element blocking by
  16814. // disabling the scrolling of the page, but it improves gestures like
  16815. // transforming and dragging.
  16816. // be careful with using this, it can be very annoying for users to be stuck
  16817. // on the page
  16818. prevent_default: false,
  16819. // disable mouse events, so only touch (or pen!) input triggers events
  16820. prevent_mouseevents: false
  16821. },
  16822. handler: function touchGesture(ev, inst) {
  16823. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  16824. ev.stopDetect();
  16825. return;
  16826. }
  16827. if(inst.options.prevent_default) {
  16828. ev.preventDefault();
  16829. }
  16830. if(ev.eventType == Hammer.EVENT_START) {
  16831. inst.trigger(this.name, ev);
  16832. }
  16833. }
  16834. };
  16835. /**
  16836. * Release
  16837. * Called as last, tells the user has released the screen
  16838. * @events release
  16839. */
  16840. Hammer.gestures.Release = {
  16841. name: 'release',
  16842. index: Infinity,
  16843. handler: function releaseGesture(ev, inst) {
  16844. if(ev.eventType == Hammer.EVENT_END) {
  16845. inst.trigger(this.name, ev);
  16846. }
  16847. }
  16848. };
  16849. // node export
  16850. if(typeof module === 'object' && typeof module.exports === 'object'){
  16851. module.exports = Hammer;
  16852. }
  16853. // just window export
  16854. else {
  16855. window.Hammer = Hammer;
  16856. // requireJS module definition
  16857. if(typeof window.define === 'function' && window.define.amd) {
  16858. window.define('hammer', [], function() {
  16859. return Hammer;
  16860. });
  16861. }
  16862. }
  16863. })(this);
  16864. },{}],4:[function(require,module,exports){
  16865. //! moment.js
  16866. //! version : 2.5.1
  16867. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  16868. //! license : MIT
  16869. //! momentjs.com
  16870. (function (undefined) {
  16871. /************************************
  16872. Constants
  16873. ************************************/
  16874. var moment,
  16875. VERSION = "2.5.1",
  16876. global = this,
  16877. round = Math.round,
  16878. i,
  16879. YEAR = 0,
  16880. MONTH = 1,
  16881. DATE = 2,
  16882. HOUR = 3,
  16883. MINUTE = 4,
  16884. SECOND = 5,
  16885. MILLISECOND = 6,
  16886. // internal storage for language config files
  16887. languages = {},
  16888. // moment internal properties
  16889. momentProperties = {
  16890. _isAMomentObject: null,
  16891. _i : null,
  16892. _f : null,
  16893. _l : null,
  16894. _strict : null,
  16895. _isUTC : null,
  16896. _offset : null, // optional. Combine with _isUTC
  16897. _pf : null,
  16898. _lang : null // optional
  16899. },
  16900. // check for nodeJS
  16901. hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
  16902. // ASP.NET json date format regex
  16903. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  16904. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  16905. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  16906. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  16907. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  16908. // format tokens
  16909. 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,
  16910. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  16911. // parsing token regexes
  16912. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  16913. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  16914. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  16915. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  16916. parseTokenDigits = /\d+/, // nonzero number of digits
  16917. 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.
  16918. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  16919. parseTokenT = /T/i, // T (ISO separator)
  16920. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  16921. //strict parsing regexes
  16922. parseTokenOneDigit = /\d/, // 0 - 9
  16923. parseTokenTwoDigits = /\d\d/, // 00 - 99
  16924. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  16925. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  16926. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  16927. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  16928. // iso 8601 regex
  16929. // 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)
  16930. 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)?)?$/,
  16931. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  16932. isoDates = [
  16933. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  16934. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  16935. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  16936. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  16937. ['YYYY-DDD', /\d{4}-\d{3}/]
  16938. ],
  16939. // iso time formats and regexes
  16940. isoTimes = [
  16941. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  16942. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  16943. ['HH:mm', /(T| )\d\d:\d\d/],
  16944. ['HH', /(T| )\d\d/]
  16945. ],
  16946. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  16947. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  16948. // getter and setter names
  16949. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  16950. unitMillisecondFactors = {
  16951. 'Milliseconds' : 1,
  16952. 'Seconds' : 1e3,
  16953. 'Minutes' : 6e4,
  16954. 'Hours' : 36e5,
  16955. 'Days' : 864e5,
  16956. 'Months' : 2592e6,
  16957. 'Years' : 31536e6
  16958. },
  16959. unitAliases = {
  16960. ms : 'millisecond',
  16961. s : 'second',
  16962. m : 'minute',
  16963. h : 'hour',
  16964. d : 'day',
  16965. D : 'date',
  16966. w : 'week',
  16967. W : 'isoWeek',
  16968. M : 'month',
  16969. y : 'year',
  16970. DDD : 'dayOfYear',
  16971. e : 'weekday',
  16972. E : 'isoWeekday',
  16973. gg: 'weekYear',
  16974. GG: 'isoWeekYear'
  16975. },
  16976. camelFunctions = {
  16977. dayofyear : 'dayOfYear',
  16978. isoweekday : 'isoWeekday',
  16979. isoweek : 'isoWeek',
  16980. weekyear : 'weekYear',
  16981. isoweekyear : 'isoWeekYear'
  16982. },
  16983. // format function strings
  16984. formatFunctions = {},
  16985. // tokens to ordinalize and pad
  16986. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  16987. paddedTokens = 'M D H h m s w W'.split(' '),
  16988. formatTokenFunctions = {
  16989. M : function () {
  16990. return this.month() + 1;
  16991. },
  16992. MMM : function (format) {
  16993. return this.lang().monthsShort(this, format);
  16994. },
  16995. MMMM : function (format) {
  16996. return this.lang().months(this, format);
  16997. },
  16998. D : function () {
  16999. return this.date();
  17000. },
  17001. DDD : function () {
  17002. return this.dayOfYear();
  17003. },
  17004. d : function () {
  17005. return this.day();
  17006. },
  17007. dd : function (format) {
  17008. return this.lang().weekdaysMin(this, format);
  17009. },
  17010. ddd : function (format) {
  17011. return this.lang().weekdaysShort(this, format);
  17012. },
  17013. dddd : function (format) {
  17014. return this.lang().weekdays(this, format);
  17015. },
  17016. w : function () {
  17017. return this.week();
  17018. },
  17019. W : function () {
  17020. return this.isoWeek();
  17021. },
  17022. YY : function () {
  17023. return leftZeroFill(this.year() % 100, 2);
  17024. },
  17025. YYYY : function () {
  17026. return leftZeroFill(this.year(), 4);
  17027. },
  17028. YYYYY : function () {
  17029. return leftZeroFill(this.year(), 5);
  17030. },
  17031. YYYYYY : function () {
  17032. var y = this.year(), sign = y >= 0 ? '+' : '-';
  17033. return sign + leftZeroFill(Math.abs(y), 6);
  17034. },
  17035. gg : function () {
  17036. return leftZeroFill(this.weekYear() % 100, 2);
  17037. },
  17038. gggg : function () {
  17039. return leftZeroFill(this.weekYear(), 4);
  17040. },
  17041. ggggg : function () {
  17042. return leftZeroFill(this.weekYear(), 5);
  17043. },
  17044. GG : function () {
  17045. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17046. },
  17047. GGGG : function () {
  17048. return leftZeroFill(this.isoWeekYear(), 4);
  17049. },
  17050. GGGGG : function () {
  17051. return leftZeroFill(this.isoWeekYear(), 5);
  17052. },
  17053. e : function () {
  17054. return this.weekday();
  17055. },
  17056. E : function () {
  17057. return this.isoWeekday();
  17058. },
  17059. a : function () {
  17060. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17061. },
  17062. A : function () {
  17063. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17064. },
  17065. H : function () {
  17066. return this.hours();
  17067. },
  17068. h : function () {
  17069. return this.hours() % 12 || 12;
  17070. },
  17071. m : function () {
  17072. return this.minutes();
  17073. },
  17074. s : function () {
  17075. return this.seconds();
  17076. },
  17077. S : function () {
  17078. return toInt(this.milliseconds() / 100);
  17079. },
  17080. SS : function () {
  17081. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17082. },
  17083. SSS : function () {
  17084. return leftZeroFill(this.milliseconds(), 3);
  17085. },
  17086. SSSS : function () {
  17087. return leftZeroFill(this.milliseconds(), 3);
  17088. },
  17089. Z : function () {
  17090. var a = -this.zone(),
  17091. b = "+";
  17092. if (a < 0) {
  17093. a = -a;
  17094. b = "-";
  17095. }
  17096. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  17097. },
  17098. ZZ : function () {
  17099. var a = -this.zone(),
  17100. b = "+";
  17101. if (a < 0) {
  17102. a = -a;
  17103. b = "-";
  17104. }
  17105. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  17106. },
  17107. z : function () {
  17108. return this.zoneAbbr();
  17109. },
  17110. zz : function () {
  17111. return this.zoneName();
  17112. },
  17113. X : function () {
  17114. return this.unix();
  17115. },
  17116. Q : function () {
  17117. return this.quarter();
  17118. }
  17119. },
  17120. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  17121. function defaultParsingFlags() {
  17122. // We need to deep clone this object, and es5 standard is not very
  17123. // helpful.
  17124. return {
  17125. empty : false,
  17126. unusedTokens : [],
  17127. unusedInput : [],
  17128. overflow : -2,
  17129. charsLeftOver : 0,
  17130. nullInput : false,
  17131. invalidMonth : null,
  17132. invalidFormat : false,
  17133. userInvalidated : false,
  17134. iso: false
  17135. };
  17136. }
  17137. function padToken(func, count) {
  17138. return function (a) {
  17139. return leftZeroFill(func.call(this, a), count);
  17140. };
  17141. }
  17142. function ordinalizeToken(func, period) {
  17143. return function (a) {
  17144. return this.lang().ordinal(func.call(this, a), period);
  17145. };
  17146. }
  17147. while (ordinalizeTokens.length) {
  17148. i = ordinalizeTokens.pop();
  17149. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  17150. }
  17151. while (paddedTokens.length) {
  17152. i = paddedTokens.pop();
  17153. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  17154. }
  17155. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  17156. /************************************
  17157. Constructors
  17158. ************************************/
  17159. function Language() {
  17160. }
  17161. // Moment prototype object
  17162. function Moment(config) {
  17163. checkOverflow(config);
  17164. extend(this, config);
  17165. }
  17166. // Duration Constructor
  17167. function Duration(duration) {
  17168. var normalizedInput = normalizeObjectUnits(duration),
  17169. years = normalizedInput.year || 0,
  17170. months = normalizedInput.month || 0,
  17171. weeks = normalizedInput.week || 0,
  17172. days = normalizedInput.day || 0,
  17173. hours = normalizedInput.hour || 0,
  17174. minutes = normalizedInput.minute || 0,
  17175. seconds = normalizedInput.second || 0,
  17176. milliseconds = normalizedInput.millisecond || 0;
  17177. // representation for dateAddRemove
  17178. this._milliseconds = +milliseconds +
  17179. seconds * 1e3 + // 1000
  17180. minutes * 6e4 + // 1000 * 60
  17181. hours * 36e5; // 1000 * 60 * 60
  17182. // Because of dateAddRemove treats 24 hours as different from a
  17183. // day when working around DST, we need to store them separately
  17184. this._days = +days +
  17185. weeks * 7;
  17186. // It is impossible translate months into days without knowing
  17187. // which months you are are talking about, so we have to store
  17188. // it separately.
  17189. this._months = +months +
  17190. years * 12;
  17191. this._data = {};
  17192. this._bubble();
  17193. }
  17194. /************************************
  17195. Helpers
  17196. ************************************/
  17197. function extend(a, b) {
  17198. for (var i in b) {
  17199. if (b.hasOwnProperty(i)) {
  17200. a[i] = b[i];
  17201. }
  17202. }
  17203. if (b.hasOwnProperty("toString")) {
  17204. a.toString = b.toString;
  17205. }
  17206. if (b.hasOwnProperty("valueOf")) {
  17207. a.valueOf = b.valueOf;
  17208. }
  17209. return a;
  17210. }
  17211. function cloneMoment(m) {
  17212. var result = {}, i;
  17213. for (i in m) {
  17214. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17215. result[i] = m[i];
  17216. }
  17217. }
  17218. return result;
  17219. }
  17220. function absRound(number) {
  17221. if (number < 0) {
  17222. return Math.ceil(number);
  17223. } else {
  17224. return Math.floor(number);
  17225. }
  17226. }
  17227. // left zero fill a number
  17228. // see http://jsperf.com/left-zero-filling for performance comparison
  17229. function leftZeroFill(number, targetLength, forceSign) {
  17230. var output = '' + Math.abs(number),
  17231. sign = number >= 0;
  17232. while (output.length < targetLength) {
  17233. output = '0' + output;
  17234. }
  17235. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17236. }
  17237. // helper function for _.addTime and _.subtractTime
  17238. function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
  17239. var milliseconds = duration._milliseconds,
  17240. days = duration._days,
  17241. months = duration._months,
  17242. minutes,
  17243. hours;
  17244. if (milliseconds) {
  17245. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17246. }
  17247. // store the minutes and hours so we can restore them
  17248. if (days || months) {
  17249. minutes = mom.minute();
  17250. hours = mom.hour();
  17251. }
  17252. if (days) {
  17253. mom.date(mom.date() + days * isAdding);
  17254. }
  17255. if (months) {
  17256. mom.month(mom.month() + months * isAdding);
  17257. }
  17258. if (milliseconds && !ignoreUpdateOffset) {
  17259. moment.updateOffset(mom);
  17260. }
  17261. // restore the minutes and hours after possibly changing dst
  17262. if (days || months) {
  17263. mom.minute(minutes);
  17264. mom.hour(hours);
  17265. }
  17266. }
  17267. // check if is an array
  17268. function isArray(input) {
  17269. return Object.prototype.toString.call(input) === '[object Array]';
  17270. }
  17271. function isDate(input) {
  17272. return Object.prototype.toString.call(input) === '[object Date]' ||
  17273. input instanceof Date;
  17274. }
  17275. // compare two arrays, return the number of differences
  17276. function compareArrays(array1, array2, dontConvert) {
  17277. var len = Math.min(array1.length, array2.length),
  17278. lengthDiff = Math.abs(array1.length - array2.length),
  17279. diffs = 0,
  17280. i;
  17281. for (i = 0; i < len; i++) {
  17282. if ((dontConvert && array1[i] !== array2[i]) ||
  17283. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17284. diffs++;
  17285. }
  17286. }
  17287. return diffs + lengthDiff;
  17288. }
  17289. function normalizeUnits(units) {
  17290. if (units) {
  17291. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17292. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17293. }
  17294. return units;
  17295. }
  17296. function normalizeObjectUnits(inputObject) {
  17297. var normalizedInput = {},
  17298. normalizedProp,
  17299. prop;
  17300. for (prop in inputObject) {
  17301. if (inputObject.hasOwnProperty(prop)) {
  17302. normalizedProp = normalizeUnits(prop);
  17303. if (normalizedProp) {
  17304. normalizedInput[normalizedProp] = inputObject[prop];
  17305. }
  17306. }
  17307. }
  17308. return normalizedInput;
  17309. }
  17310. function makeList(field) {
  17311. var count, setter;
  17312. if (field.indexOf('week') === 0) {
  17313. count = 7;
  17314. setter = 'day';
  17315. }
  17316. else if (field.indexOf('month') === 0) {
  17317. count = 12;
  17318. setter = 'month';
  17319. }
  17320. else {
  17321. return;
  17322. }
  17323. moment[field] = function (format, index) {
  17324. var i, getter,
  17325. method = moment.fn._lang[field],
  17326. results = [];
  17327. if (typeof format === 'number') {
  17328. index = format;
  17329. format = undefined;
  17330. }
  17331. getter = function (i) {
  17332. var m = moment().utc().set(setter, i);
  17333. return method.call(moment.fn._lang, m, format || '');
  17334. };
  17335. if (index != null) {
  17336. return getter(index);
  17337. }
  17338. else {
  17339. for (i = 0; i < count; i++) {
  17340. results.push(getter(i));
  17341. }
  17342. return results;
  17343. }
  17344. };
  17345. }
  17346. function toInt(argumentForCoercion) {
  17347. var coercedNumber = +argumentForCoercion,
  17348. value = 0;
  17349. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17350. if (coercedNumber >= 0) {
  17351. value = Math.floor(coercedNumber);
  17352. } else {
  17353. value = Math.ceil(coercedNumber);
  17354. }
  17355. }
  17356. return value;
  17357. }
  17358. function daysInMonth(year, month) {
  17359. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17360. }
  17361. function daysInYear(year) {
  17362. return isLeapYear(year) ? 366 : 365;
  17363. }
  17364. function isLeapYear(year) {
  17365. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17366. }
  17367. function checkOverflow(m) {
  17368. var overflow;
  17369. if (m._a && m._pf.overflow === -2) {
  17370. overflow =
  17371. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17372. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17373. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17374. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17375. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17376. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17377. -1;
  17378. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17379. overflow = DATE;
  17380. }
  17381. m._pf.overflow = overflow;
  17382. }
  17383. }
  17384. function isValid(m) {
  17385. if (m._isValid == null) {
  17386. m._isValid = !isNaN(m._d.getTime()) &&
  17387. m._pf.overflow < 0 &&
  17388. !m._pf.empty &&
  17389. !m._pf.invalidMonth &&
  17390. !m._pf.nullInput &&
  17391. !m._pf.invalidFormat &&
  17392. !m._pf.userInvalidated;
  17393. if (m._strict) {
  17394. m._isValid = m._isValid &&
  17395. m._pf.charsLeftOver === 0 &&
  17396. m._pf.unusedTokens.length === 0;
  17397. }
  17398. }
  17399. return m._isValid;
  17400. }
  17401. function normalizeLanguage(key) {
  17402. return key ? key.toLowerCase().replace('_', '-') : key;
  17403. }
  17404. // Return a moment from input, that is local/utc/zone equivalent to model.
  17405. function makeAs(input, model) {
  17406. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17407. moment(input).local();
  17408. }
  17409. /************************************
  17410. Languages
  17411. ************************************/
  17412. extend(Language.prototype, {
  17413. set : function (config) {
  17414. var prop, i;
  17415. for (i in config) {
  17416. prop = config[i];
  17417. if (typeof prop === 'function') {
  17418. this[i] = prop;
  17419. } else {
  17420. this['_' + i] = prop;
  17421. }
  17422. }
  17423. },
  17424. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17425. months : function (m) {
  17426. return this._months[m.month()];
  17427. },
  17428. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17429. monthsShort : function (m) {
  17430. return this._monthsShort[m.month()];
  17431. },
  17432. monthsParse : function (monthName) {
  17433. var i, mom, regex;
  17434. if (!this._monthsParse) {
  17435. this._monthsParse = [];
  17436. }
  17437. for (i = 0; i < 12; i++) {
  17438. // make the regex if we don't have it already
  17439. if (!this._monthsParse[i]) {
  17440. mom = moment.utc([2000, i]);
  17441. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17442. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17443. }
  17444. // test the regex
  17445. if (this._monthsParse[i].test(monthName)) {
  17446. return i;
  17447. }
  17448. }
  17449. },
  17450. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17451. weekdays : function (m) {
  17452. return this._weekdays[m.day()];
  17453. },
  17454. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17455. weekdaysShort : function (m) {
  17456. return this._weekdaysShort[m.day()];
  17457. },
  17458. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17459. weekdaysMin : function (m) {
  17460. return this._weekdaysMin[m.day()];
  17461. },
  17462. weekdaysParse : function (weekdayName) {
  17463. var i, mom, regex;
  17464. if (!this._weekdaysParse) {
  17465. this._weekdaysParse = [];
  17466. }
  17467. for (i = 0; i < 7; i++) {
  17468. // make the regex if we don't have it already
  17469. if (!this._weekdaysParse[i]) {
  17470. mom = moment([2000, 1]).day(i);
  17471. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17472. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17473. }
  17474. // test the regex
  17475. if (this._weekdaysParse[i].test(weekdayName)) {
  17476. return i;
  17477. }
  17478. }
  17479. },
  17480. _longDateFormat : {
  17481. LT : "h:mm A",
  17482. L : "MM/DD/YYYY",
  17483. LL : "MMMM D YYYY",
  17484. LLL : "MMMM D YYYY LT",
  17485. LLLL : "dddd, MMMM D YYYY LT"
  17486. },
  17487. longDateFormat : function (key) {
  17488. var output = this._longDateFormat[key];
  17489. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17490. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17491. return val.slice(1);
  17492. });
  17493. this._longDateFormat[key] = output;
  17494. }
  17495. return output;
  17496. },
  17497. isPM : function (input) {
  17498. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17499. // Using charAt should be more compatible.
  17500. return ((input + '').toLowerCase().charAt(0) === 'p');
  17501. },
  17502. _meridiemParse : /[ap]\.?m?\.?/i,
  17503. meridiem : function (hours, minutes, isLower) {
  17504. if (hours > 11) {
  17505. return isLower ? 'pm' : 'PM';
  17506. } else {
  17507. return isLower ? 'am' : 'AM';
  17508. }
  17509. },
  17510. _calendar : {
  17511. sameDay : '[Today at] LT',
  17512. nextDay : '[Tomorrow at] LT',
  17513. nextWeek : 'dddd [at] LT',
  17514. lastDay : '[Yesterday at] LT',
  17515. lastWeek : '[Last] dddd [at] LT',
  17516. sameElse : 'L'
  17517. },
  17518. calendar : function (key, mom) {
  17519. var output = this._calendar[key];
  17520. return typeof output === 'function' ? output.apply(mom) : output;
  17521. },
  17522. _relativeTime : {
  17523. future : "in %s",
  17524. past : "%s ago",
  17525. s : "a few seconds",
  17526. m : "a minute",
  17527. mm : "%d minutes",
  17528. h : "an hour",
  17529. hh : "%d hours",
  17530. d : "a day",
  17531. dd : "%d days",
  17532. M : "a month",
  17533. MM : "%d months",
  17534. y : "a year",
  17535. yy : "%d years"
  17536. },
  17537. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17538. var output = this._relativeTime[string];
  17539. return (typeof output === 'function') ?
  17540. output(number, withoutSuffix, string, isFuture) :
  17541. output.replace(/%d/i, number);
  17542. },
  17543. pastFuture : function (diff, output) {
  17544. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17545. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17546. },
  17547. ordinal : function (number) {
  17548. return this._ordinal.replace("%d", number);
  17549. },
  17550. _ordinal : "%d",
  17551. preparse : function (string) {
  17552. return string;
  17553. },
  17554. postformat : function (string) {
  17555. return string;
  17556. },
  17557. week : function (mom) {
  17558. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17559. },
  17560. _week : {
  17561. dow : 0, // Sunday is the first day of the week.
  17562. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17563. },
  17564. _invalidDate: 'Invalid date',
  17565. invalidDate: function () {
  17566. return this._invalidDate;
  17567. }
  17568. });
  17569. // Loads a language definition into the `languages` cache. The function
  17570. // takes a key and optionally values. If not in the browser and no values
  17571. // are provided, it will load the language file module. As a convenience,
  17572. // this function also returns the language values.
  17573. function loadLang(key, values) {
  17574. values.abbr = key;
  17575. if (!languages[key]) {
  17576. languages[key] = new Language();
  17577. }
  17578. languages[key].set(values);
  17579. return languages[key];
  17580. }
  17581. // Remove a language from the `languages` cache. Mostly useful in tests.
  17582. function unloadLang(key) {
  17583. delete languages[key];
  17584. }
  17585. // Determines which language definition to use and returns it.
  17586. //
  17587. // With no parameters, it will return the global language. If you
  17588. // pass in a language key, such as 'en', it will return the
  17589. // definition for 'en', so long as 'en' has already been loaded using
  17590. // moment.lang.
  17591. function getLangDefinition(key) {
  17592. var i = 0, j, lang, next, split,
  17593. get = function (k) {
  17594. if (!languages[k] && hasModule) {
  17595. try {
  17596. require('./lang/' + k);
  17597. } catch (e) { }
  17598. }
  17599. return languages[k];
  17600. };
  17601. if (!key) {
  17602. return moment.fn._lang;
  17603. }
  17604. if (!isArray(key)) {
  17605. //short-circuit everything else
  17606. lang = get(key);
  17607. if (lang) {
  17608. return lang;
  17609. }
  17610. key = [key];
  17611. }
  17612. //pick the language from the array
  17613. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  17614. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  17615. while (i < key.length) {
  17616. split = normalizeLanguage(key[i]).split('-');
  17617. j = split.length;
  17618. next = normalizeLanguage(key[i + 1]);
  17619. next = next ? next.split('-') : null;
  17620. while (j > 0) {
  17621. lang = get(split.slice(0, j).join('-'));
  17622. if (lang) {
  17623. return lang;
  17624. }
  17625. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  17626. //the next array item is better than a shallower substring of this one
  17627. break;
  17628. }
  17629. j--;
  17630. }
  17631. i++;
  17632. }
  17633. return moment.fn._lang;
  17634. }
  17635. /************************************
  17636. Formatting
  17637. ************************************/
  17638. function removeFormattingTokens(input) {
  17639. if (input.match(/\[[\s\S]/)) {
  17640. return input.replace(/^\[|\]$/g, "");
  17641. }
  17642. return input.replace(/\\/g, "");
  17643. }
  17644. function makeFormatFunction(format) {
  17645. var array = format.match(formattingTokens), i, length;
  17646. for (i = 0, length = array.length; i < length; i++) {
  17647. if (formatTokenFunctions[array[i]]) {
  17648. array[i] = formatTokenFunctions[array[i]];
  17649. } else {
  17650. array[i] = removeFormattingTokens(array[i]);
  17651. }
  17652. }
  17653. return function (mom) {
  17654. var output = "";
  17655. for (i = 0; i < length; i++) {
  17656. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  17657. }
  17658. return output;
  17659. };
  17660. }
  17661. // format date using native date object
  17662. function formatMoment(m, format) {
  17663. if (!m.isValid()) {
  17664. return m.lang().invalidDate();
  17665. }
  17666. format = expandFormat(format, m.lang());
  17667. if (!formatFunctions[format]) {
  17668. formatFunctions[format] = makeFormatFunction(format);
  17669. }
  17670. return formatFunctions[format](m);
  17671. }
  17672. function expandFormat(format, lang) {
  17673. var i = 5;
  17674. function replaceLongDateFormatTokens(input) {
  17675. return lang.longDateFormat(input) || input;
  17676. }
  17677. localFormattingTokens.lastIndex = 0;
  17678. while (i >= 0 && localFormattingTokens.test(format)) {
  17679. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  17680. localFormattingTokens.lastIndex = 0;
  17681. i -= 1;
  17682. }
  17683. return format;
  17684. }
  17685. /************************************
  17686. Parsing
  17687. ************************************/
  17688. // get the regex to find the next token
  17689. function getParseRegexForToken(token, config) {
  17690. var a, strict = config._strict;
  17691. switch (token) {
  17692. case 'DDDD':
  17693. return parseTokenThreeDigits;
  17694. case 'YYYY':
  17695. case 'GGGG':
  17696. case 'gggg':
  17697. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  17698. case 'Y':
  17699. case 'G':
  17700. case 'g':
  17701. return parseTokenSignedNumber;
  17702. case 'YYYYYY':
  17703. case 'YYYYY':
  17704. case 'GGGGG':
  17705. case 'ggggg':
  17706. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  17707. case 'S':
  17708. if (strict) { return parseTokenOneDigit; }
  17709. /* falls through */
  17710. case 'SS':
  17711. if (strict) { return parseTokenTwoDigits; }
  17712. /* falls through */
  17713. case 'SSS':
  17714. if (strict) { return parseTokenThreeDigits; }
  17715. /* falls through */
  17716. case 'DDD':
  17717. return parseTokenOneToThreeDigits;
  17718. case 'MMM':
  17719. case 'MMMM':
  17720. case 'dd':
  17721. case 'ddd':
  17722. case 'dddd':
  17723. return parseTokenWord;
  17724. case 'a':
  17725. case 'A':
  17726. return getLangDefinition(config._l)._meridiemParse;
  17727. case 'X':
  17728. return parseTokenTimestampMs;
  17729. case 'Z':
  17730. case 'ZZ':
  17731. return parseTokenTimezone;
  17732. case 'T':
  17733. return parseTokenT;
  17734. case 'SSSS':
  17735. return parseTokenDigits;
  17736. case 'MM':
  17737. case 'DD':
  17738. case 'YY':
  17739. case 'GG':
  17740. case 'gg':
  17741. case 'HH':
  17742. case 'hh':
  17743. case 'mm':
  17744. case 'ss':
  17745. case 'ww':
  17746. case 'WW':
  17747. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  17748. case 'M':
  17749. case 'D':
  17750. case 'd':
  17751. case 'H':
  17752. case 'h':
  17753. case 'm':
  17754. case 's':
  17755. case 'w':
  17756. case 'W':
  17757. case 'e':
  17758. case 'E':
  17759. return parseTokenOneOrTwoDigits;
  17760. default :
  17761. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  17762. return a;
  17763. }
  17764. }
  17765. function timezoneMinutesFromString(string) {
  17766. string = string || "";
  17767. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  17768. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  17769. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  17770. minutes = +(parts[1] * 60) + toInt(parts[2]);
  17771. return parts[0] === '+' ? -minutes : minutes;
  17772. }
  17773. // function to convert string input to date
  17774. function addTimeToArrayFromToken(token, input, config) {
  17775. var a, datePartArray = config._a;
  17776. switch (token) {
  17777. // MONTH
  17778. case 'M' : // fall through to MM
  17779. case 'MM' :
  17780. if (input != null) {
  17781. datePartArray[MONTH] = toInt(input) - 1;
  17782. }
  17783. break;
  17784. case 'MMM' : // fall through to MMMM
  17785. case 'MMMM' :
  17786. a = getLangDefinition(config._l).monthsParse(input);
  17787. // if we didn't find a month name, mark the date as invalid.
  17788. if (a != null) {
  17789. datePartArray[MONTH] = a;
  17790. } else {
  17791. config._pf.invalidMonth = input;
  17792. }
  17793. break;
  17794. // DAY OF MONTH
  17795. case 'D' : // fall through to DD
  17796. case 'DD' :
  17797. if (input != null) {
  17798. datePartArray[DATE] = toInt(input);
  17799. }
  17800. break;
  17801. // DAY OF YEAR
  17802. case 'DDD' : // fall through to DDDD
  17803. case 'DDDD' :
  17804. if (input != null) {
  17805. config._dayOfYear = toInt(input);
  17806. }
  17807. break;
  17808. // YEAR
  17809. case 'YY' :
  17810. datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  17811. break;
  17812. case 'YYYY' :
  17813. case 'YYYYY' :
  17814. case 'YYYYYY' :
  17815. datePartArray[YEAR] = toInt(input);
  17816. break;
  17817. // AM / PM
  17818. case 'a' : // fall through to A
  17819. case 'A' :
  17820. config._isPm = getLangDefinition(config._l).isPM(input);
  17821. break;
  17822. // 24 HOUR
  17823. case 'H' : // fall through to hh
  17824. case 'HH' : // fall through to hh
  17825. case 'h' : // fall through to hh
  17826. case 'hh' :
  17827. datePartArray[HOUR] = toInt(input);
  17828. break;
  17829. // MINUTE
  17830. case 'm' : // fall through to mm
  17831. case 'mm' :
  17832. datePartArray[MINUTE] = toInt(input);
  17833. break;
  17834. // SECOND
  17835. case 's' : // fall through to ss
  17836. case 'ss' :
  17837. datePartArray[SECOND] = toInt(input);
  17838. break;
  17839. // MILLISECOND
  17840. case 'S' :
  17841. case 'SS' :
  17842. case 'SSS' :
  17843. case 'SSSS' :
  17844. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  17845. break;
  17846. // UNIX TIMESTAMP WITH MS
  17847. case 'X':
  17848. config._d = new Date(parseFloat(input) * 1000);
  17849. break;
  17850. // TIMEZONE
  17851. case 'Z' : // fall through to ZZ
  17852. case 'ZZ' :
  17853. config._useUTC = true;
  17854. config._tzm = timezoneMinutesFromString(input);
  17855. break;
  17856. case 'w':
  17857. case 'ww':
  17858. case 'W':
  17859. case 'WW':
  17860. case 'd':
  17861. case 'dd':
  17862. case 'ddd':
  17863. case 'dddd':
  17864. case 'e':
  17865. case 'E':
  17866. token = token.substr(0, 1);
  17867. /* falls through */
  17868. case 'gg':
  17869. case 'gggg':
  17870. case 'GG':
  17871. case 'GGGG':
  17872. case 'GGGGG':
  17873. token = token.substr(0, 2);
  17874. if (input) {
  17875. config._w = config._w || {};
  17876. config._w[token] = input;
  17877. }
  17878. break;
  17879. }
  17880. }
  17881. // convert an array to a date.
  17882. // the array should mirror the parameters below
  17883. // note: all values past the year are optional and will default to the lowest possible value.
  17884. // [year, month, day , hour, minute, second, millisecond]
  17885. function dateFromConfig(config) {
  17886. var i, date, input = [], currentDate,
  17887. yearToUse, fixYear, w, temp, lang, weekday, week;
  17888. if (config._d) {
  17889. return;
  17890. }
  17891. currentDate = currentDateArray(config);
  17892. //compute day of the year from weeks and weekdays
  17893. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  17894. fixYear = function (val) {
  17895. var int_val = parseInt(val, 10);
  17896. return val ?
  17897. (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
  17898. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  17899. };
  17900. w = config._w;
  17901. if (w.GG != null || w.W != null || w.E != null) {
  17902. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  17903. }
  17904. else {
  17905. lang = getLangDefinition(config._l);
  17906. weekday = w.d != null ? parseWeekday(w.d, lang) :
  17907. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  17908. week = parseInt(w.w, 10) || 1;
  17909. //if we're parsing 'd', then the low day numbers may be next week
  17910. if (w.d != null && weekday < lang._week.dow) {
  17911. week++;
  17912. }
  17913. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  17914. }
  17915. config._a[YEAR] = temp.year;
  17916. config._dayOfYear = temp.dayOfYear;
  17917. }
  17918. //if the day of the year is set, figure out what it is
  17919. if (config._dayOfYear) {
  17920. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  17921. if (config._dayOfYear > daysInYear(yearToUse)) {
  17922. config._pf._overflowDayOfYear = true;
  17923. }
  17924. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  17925. config._a[MONTH] = date.getUTCMonth();
  17926. config._a[DATE] = date.getUTCDate();
  17927. }
  17928. // Default to current date.
  17929. // * if no year, month, day of month are given, default to today
  17930. // * if day of month is given, default month and year
  17931. // * if month is given, default only year
  17932. // * if year is given, don't default anything
  17933. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  17934. config._a[i] = input[i] = currentDate[i];
  17935. }
  17936. // Zero out whatever was not defaulted, including time
  17937. for (; i < 7; i++) {
  17938. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  17939. }
  17940. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  17941. input[HOUR] += toInt((config._tzm || 0) / 60);
  17942. input[MINUTE] += toInt((config._tzm || 0) % 60);
  17943. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  17944. }
  17945. function dateFromObject(config) {
  17946. var normalizedInput;
  17947. if (config._d) {
  17948. return;
  17949. }
  17950. normalizedInput = normalizeObjectUnits(config._i);
  17951. config._a = [
  17952. normalizedInput.year,
  17953. normalizedInput.month,
  17954. normalizedInput.day,
  17955. normalizedInput.hour,
  17956. normalizedInput.minute,
  17957. normalizedInput.second,
  17958. normalizedInput.millisecond
  17959. ];
  17960. dateFromConfig(config);
  17961. }
  17962. function currentDateArray(config) {
  17963. var now = new Date();
  17964. if (config._useUTC) {
  17965. return [
  17966. now.getUTCFullYear(),
  17967. now.getUTCMonth(),
  17968. now.getUTCDate()
  17969. ];
  17970. } else {
  17971. return [now.getFullYear(), now.getMonth(), now.getDate()];
  17972. }
  17973. }
  17974. // date from string and format string
  17975. function makeDateFromStringAndFormat(config) {
  17976. config._a = [];
  17977. config._pf.empty = true;
  17978. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  17979. var lang = getLangDefinition(config._l),
  17980. string = '' + config._i,
  17981. i, parsedInput, tokens, token, skipped,
  17982. stringLength = string.length,
  17983. totalParsedInputLength = 0;
  17984. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  17985. for (i = 0; i < tokens.length; i++) {
  17986. token = tokens[i];
  17987. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  17988. if (parsedInput) {
  17989. skipped = string.substr(0, string.indexOf(parsedInput));
  17990. if (skipped.length > 0) {
  17991. config._pf.unusedInput.push(skipped);
  17992. }
  17993. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  17994. totalParsedInputLength += parsedInput.length;
  17995. }
  17996. // don't parse if it's not a known token
  17997. if (formatTokenFunctions[token]) {
  17998. if (parsedInput) {
  17999. config._pf.empty = false;
  18000. }
  18001. else {
  18002. config._pf.unusedTokens.push(token);
  18003. }
  18004. addTimeToArrayFromToken(token, parsedInput, config);
  18005. }
  18006. else if (config._strict && !parsedInput) {
  18007. config._pf.unusedTokens.push(token);
  18008. }
  18009. }
  18010. // add remaining unparsed input length to the string
  18011. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  18012. if (string.length > 0) {
  18013. config._pf.unusedInput.push(string);
  18014. }
  18015. // handle am pm
  18016. if (config._isPm && config._a[HOUR] < 12) {
  18017. config._a[HOUR] += 12;
  18018. }
  18019. // if is 12 am, change hours to 0
  18020. if (config._isPm === false && config._a[HOUR] === 12) {
  18021. config._a[HOUR] = 0;
  18022. }
  18023. dateFromConfig(config);
  18024. checkOverflow(config);
  18025. }
  18026. function unescapeFormat(s) {
  18027. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  18028. return p1 || p2 || p3 || p4;
  18029. });
  18030. }
  18031. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  18032. function regexpEscape(s) {
  18033. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18034. }
  18035. // date from string and array of format strings
  18036. function makeDateFromStringAndArray(config) {
  18037. var tempConfig,
  18038. bestMoment,
  18039. scoreToBeat,
  18040. i,
  18041. currentScore;
  18042. if (config._f.length === 0) {
  18043. config._pf.invalidFormat = true;
  18044. config._d = new Date(NaN);
  18045. return;
  18046. }
  18047. for (i = 0; i < config._f.length; i++) {
  18048. currentScore = 0;
  18049. tempConfig = extend({}, config);
  18050. tempConfig._pf = defaultParsingFlags();
  18051. tempConfig._f = config._f[i];
  18052. makeDateFromStringAndFormat(tempConfig);
  18053. if (!isValid(tempConfig)) {
  18054. continue;
  18055. }
  18056. // if there is any input that was not parsed add a penalty for that format
  18057. currentScore += tempConfig._pf.charsLeftOver;
  18058. //or tokens
  18059. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18060. tempConfig._pf.score = currentScore;
  18061. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18062. scoreToBeat = currentScore;
  18063. bestMoment = tempConfig;
  18064. }
  18065. }
  18066. extend(config, bestMoment || tempConfig);
  18067. }
  18068. // date from iso format
  18069. function makeDateFromString(config) {
  18070. var i, l,
  18071. string = config._i,
  18072. match = isoRegex.exec(string);
  18073. if (match) {
  18074. config._pf.iso = true;
  18075. for (i = 0, l = isoDates.length; i < l; i++) {
  18076. if (isoDates[i][1].exec(string)) {
  18077. // match[5] should be "T" or undefined
  18078. config._f = isoDates[i][0] + (match[6] || " ");
  18079. break;
  18080. }
  18081. }
  18082. for (i = 0, l = isoTimes.length; i < l; i++) {
  18083. if (isoTimes[i][1].exec(string)) {
  18084. config._f += isoTimes[i][0];
  18085. break;
  18086. }
  18087. }
  18088. if (string.match(parseTokenTimezone)) {
  18089. config._f += "Z";
  18090. }
  18091. makeDateFromStringAndFormat(config);
  18092. }
  18093. else {
  18094. config._d = new Date(string);
  18095. }
  18096. }
  18097. function makeDateFromInput(config) {
  18098. var input = config._i,
  18099. matched = aspNetJsonRegex.exec(input);
  18100. if (input === undefined) {
  18101. config._d = new Date();
  18102. } else if (matched) {
  18103. config._d = new Date(+matched[1]);
  18104. } else if (typeof input === 'string') {
  18105. makeDateFromString(config);
  18106. } else if (isArray(input)) {
  18107. config._a = input.slice(0);
  18108. dateFromConfig(config);
  18109. } else if (isDate(input)) {
  18110. config._d = new Date(+input);
  18111. } else if (typeof(input) === 'object') {
  18112. dateFromObject(config);
  18113. } else {
  18114. config._d = new Date(input);
  18115. }
  18116. }
  18117. function makeDate(y, m, d, h, M, s, ms) {
  18118. //can't just apply() to create a date:
  18119. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  18120. var date = new Date(y, m, d, h, M, s, ms);
  18121. //the date constructor doesn't accept years < 1970
  18122. if (y < 1970) {
  18123. date.setFullYear(y);
  18124. }
  18125. return date;
  18126. }
  18127. function makeUTCDate(y) {
  18128. var date = new Date(Date.UTC.apply(null, arguments));
  18129. if (y < 1970) {
  18130. date.setUTCFullYear(y);
  18131. }
  18132. return date;
  18133. }
  18134. function parseWeekday(input, language) {
  18135. if (typeof input === 'string') {
  18136. if (!isNaN(input)) {
  18137. input = parseInt(input, 10);
  18138. }
  18139. else {
  18140. input = language.weekdaysParse(input);
  18141. if (typeof input !== 'number') {
  18142. return null;
  18143. }
  18144. }
  18145. }
  18146. return input;
  18147. }
  18148. /************************************
  18149. Relative Time
  18150. ************************************/
  18151. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  18152. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  18153. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  18154. }
  18155. function relativeTime(milliseconds, withoutSuffix, lang) {
  18156. var seconds = round(Math.abs(milliseconds) / 1000),
  18157. minutes = round(seconds / 60),
  18158. hours = round(minutes / 60),
  18159. days = round(hours / 24),
  18160. years = round(days / 365),
  18161. args = seconds < 45 && ['s', seconds] ||
  18162. minutes === 1 && ['m'] ||
  18163. minutes < 45 && ['mm', minutes] ||
  18164. hours === 1 && ['h'] ||
  18165. hours < 22 && ['hh', hours] ||
  18166. days === 1 && ['d'] ||
  18167. days <= 25 && ['dd', days] ||
  18168. days <= 45 && ['M'] ||
  18169. days < 345 && ['MM', round(days / 30)] ||
  18170. years === 1 && ['y'] || ['yy', years];
  18171. args[2] = withoutSuffix;
  18172. args[3] = milliseconds > 0;
  18173. args[4] = lang;
  18174. return substituteTimeAgo.apply({}, args);
  18175. }
  18176. /************************************
  18177. Week of Year
  18178. ************************************/
  18179. // firstDayOfWeek 0 = sun, 6 = sat
  18180. // the day of the week that starts the week
  18181. // (usually sunday or monday)
  18182. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18183. // the first week is the week that contains the first
  18184. // of this day of the week
  18185. // (eg. ISO weeks use thursday (4))
  18186. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18187. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18188. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18189. adjustedMoment;
  18190. if (daysToDayOfWeek > end) {
  18191. daysToDayOfWeek -= 7;
  18192. }
  18193. if (daysToDayOfWeek < end - 7) {
  18194. daysToDayOfWeek += 7;
  18195. }
  18196. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18197. return {
  18198. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18199. year: adjustedMoment.year()
  18200. };
  18201. }
  18202. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18203. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18204. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18205. weekday = weekday != null ? weekday : firstDayOfWeek;
  18206. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18207. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18208. return {
  18209. year: dayOfYear > 0 ? year : year - 1,
  18210. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18211. };
  18212. }
  18213. /************************************
  18214. Top Level Functions
  18215. ************************************/
  18216. function makeMoment(config) {
  18217. var input = config._i,
  18218. format = config._f;
  18219. if (input === null) {
  18220. return moment.invalid({nullInput: true});
  18221. }
  18222. if (typeof input === 'string') {
  18223. config._i = input = getLangDefinition().preparse(input);
  18224. }
  18225. if (moment.isMoment(input)) {
  18226. config = cloneMoment(input);
  18227. config._d = new Date(+input._d);
  18228. } else if (format) {
  18229. if (isArray(format)) {
  18230. makeDateFromStringAndArray(config);
  18231. } else {
  18232. makeDateFromStringAndFormat(config);
  18233. }
  18234. } else {
  18235. makeDateFromInput(config);
  18236. }
  18237. return new Moment(config);
  18238. }
  18239. moment = function (input, format, lang, strict) {
  18240. var c;
  18241. if (typeof(lang) === "boolean") {
  18242. strict = lang;
  18243. lang = undefined;
  18244. }
  18245. // object construction must be done this way.
  18246. // https://github.com/moment/moment/issues/1423
  18247. c = {};
  18248. c._isAMomentObject = true;
  18249. c._i = input;
  18250. c._f = format;
  18251. c._l = lang;
  18252. c._strict = strict;
  18253. c._isUTC = false;
  18254. c._pf = defaultParsingFlags();
  18255. return makeMoment(c);
  18256. };
  18257. // creating with utc
  18258. moment.utc = function (input, format, lang, strict) {
  18259. var c;
  18260. if (typeof(lang) === "boolean") {
  18261. strict = lang;
  18262. lang = undefined;
  18263. }
  18264. // object construction must be done this way.
  18265. // https://github.com/moment/moment/issues/1423
  18266. c = {};
  18267. c._isAMomentObject = true;
  18268. c._useUTC = true;
  18269. c._isUTC = true;
  18270. c._l = lang;
  18271. c._i = input;
  18272. c._f = format;
  18273. c._strict = strict;
  18274. c._pf = defaultParsingFlags();
  18275. return makeMoment(c).utc();
  18276. };
  18277. // creating with unix timestamp (in seconds)
  18278. moment.unix = function (input) {
  18279. return moment(input * 1000);
  18280. };
  18281. // duration
  18282. moment.duration = function (input, key) {
  18283. var duration = input,
  18284. // matching against regexp is expensive, do it on demand
  18285. match = null,
  18286. sign,
  18287. ret,
  18288. parseIso;
  18289. if (moment.isDuration(input)) {
  18290. duration = {
  18291. ms: input._milliseconds,
  18292. d: input._days,
  18293. M: input._months
  18294. };
  18295. } else if (typeof input === 'number') {
  18296. duration = {};
  18297. if (key) {
  18298. duration[key] = input;
  18299. } else {
  18300. duration.milliseconds = input;
  18301. }
  18302. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18303. sign = (match[1] === "-") ? -1 : 1;
  18304. duration = {
  18305. y: 0,
  18306. d: toInt(match[DATE]) * sign,
  18307. h: toInt(match[HOUR]) * sign,
  18308. m: toInt(match[MINUTE]) * sign,
  18309. s: toInt(match[SECOND]) * sign,
  18310. ms: toInt(match[MILLISECOND]) * sign
  18311. };
  18312. } else if (!!(match = isoDurationRegex.exec(input))) {
  18313. sign = (match[1] === "-") ? -1 : 1;
  18314. parseIso = function (inp) {
  18315. // We'd normally use ~~inp for this, but unfortunately it also
  18316. // converts floats to ints.
  18317. // inp may be undefined, so careful calling replace on it.
  18318. var res = inp && parseFloat(inp.replace(',', '.'));
  18319. // apply sign while we're at it
  18320. return (isNaN(res) ? 0 : res) * sign;
  18321. };
  18322. duration = {
  18323. y: parseIso(match[2]),
  18324. M: parseIso(match[3]),
  18325. d: parseIso(match[4]),
  18326. h: parseIso(match[5]),
  18327. m: parseIso(match[6]),
  18328. s: parseIso(match[7]),
  18329. w: parseIso(match[8])
  18330. };
  18331. }
  18332. ret = new Duration(duration);
  18333. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18334. ret._lang = input._lang;
  18335. }
  18336. return ret;
  18337. };
  18338. // version number
  18339. moment.version = VERSION;
  18340. // default format
  18341. moment.defaultFormat = isoFormat;
  18342. // This function will be called whenever a moment is mutated.
  18343. // It is intended to keep the offset in sync with the timezone.
  18344. moment.updateOffset = function () {};
  18345. // This function will load languages and then set the global language. If
  18346. // no arguments are passed in, it will simply return the current global
  18347. // language key.
  18348. moment.lang = function (key, values) {
  18349. var r;
  18350. if (!key) {
  18351. return moment.fn._lang._abbr;
  18352. }
  18353. if (values) {
  18354. loadLang(normalizeLanguage(key), values);
  18355. } else if (values === null) {
  18356. unloadLang(key);
  18357. key = 'en';
  18358. } else if (!languages[key]) {
  18359. getLangDefinition(key);
  18360. }
  18361. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18362. return r._abbr;
  18363. };
  18364. // returns language data
  18365. moment.langData = function (key) {
  18366. if (key && key._lang && key._lang._abbr) {
  18367. key = key._lang._abbr;
  18368. }
  18369. return getLangDefinition(key);
  18370. };
  18371. // compare moment object
  18372. moment.isMoment = function (obj) {
  18373. return obj instanceof Moment ||
  18374. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18375. };
  18376. // for typechecking Duration objects
  18377. moment.isDuration = function (obj) {
  18378. return obj instanceof Duration;
  18379. };
  18380. for (i = lists.length - 1; i >= 0; --i) {
  18381. makeList(lists[i]);
  18382. }
  18383. moment.normalizeUnits = function (units) {
  18384. return normalizeUnits(units);
  18385. };
  18386. moment.invalid = function (flags) {
  18387. var m = moment.utc(NaN);
  18388. if (flags != null) {
  18389. extend(m._pf, flags);
  18390. }
  18391. else {
  18392. m._pf.userInvalidated = true;
  18393. }
  18394. return m;
  18395. };
  18396. moment.parseZone = function (input) {
  18397. return moment(input).parseZone();
  18398. };
  18399. /************************************
  18400. Moment Prototype
  18401. ************************************/
  18402. extend(moment.fn = Moment.prototype, {
  18403. clone : function () {
  18404. return moment(this);
  18405. },
  18406. valueOf : function () {
  18407. return +this._d + ((this._offset || 0) * 60000);
  18408. },
  18409. unix : function () {
  18410. return Math.floor(+this / 1000);
  18411. },
  18412. toString : function () {
  18413. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18414. },
  18415. toDate : function () {
  18416. return this._offset ? new Date(+this) : this._d;
  18417. },
  18418. toISOString : function () {
  18419. var m = moment(this).utc();
  18420. if (0 < m.year() && m.year() <= 9999) {
  18421. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18422. } else {
  18423. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18424. }
  18425. },
  18426. toArray : function () {
  18427. var m = this;
  18428. return [
  18429. m.year(),
  18430. m.month(),
  18431. m.date(),
  18432. m.hours(),
  18433. m.minutes(),
  18434. m.seconds(),
  18435. m.milliseconds()
  18436. ];
  18437. },
  18438. isValid : function () {
  18439. return isValid(this);
  18440. },
  18441. isDSTShifted : function () {
  18442. if (this._a) {
  18443. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18444. }
  18445. return false;
  18446. },
  18447. parsingFlags : function () {
  18448. return extend({}, this._pf);
  18449. },
  18450. invalidAt: function () {
  18451. return this._pf.overflow;
  18452. },
  18453. utc : function () {
  18454. return this.zone(0);
  18455. },
  18456. local : function () {
  18457. this.zone(0);
  18458. this._isUTC = false;
  18459. return this;
  18460. },
  18461. format : function (inputString) {
  18462. var output = formatMoment(this, inputString || moment.defaultFormat);
  18463. return this.lang().postformat(output);
  18464. },
  18465. add : function (input, val) {
  18466. var dur;
  18467. // switch args to support add('s', 1) and add(1, 's')
  18468. if (typeof input === 'string') {
  18469. dur = moment.duration(+val, input);
  18470. } else {
  18471. dur = moment.duration(input, val);
  18472. }
  18473. addOrSubtractDurationFromMoment(this, dur, 1);
  18474. return this;
  18475. },
  18476. subtract : function (input, val) {
  18477. var dur;
  18478. // switch args to support subtract('s', 1) and subtract(1, 's')
  18479. if (typeof input === 'string') {
  18480. dur = moment.duration(+val, input);
  18481. } else {
  18482. dur = moment.duration(input, val);
  18483. }
  18484. addOrSubtractDurationFromMoment(this, dur, -1);
  18485. return this;
  18486. },
  18487. diff : function (input, units, asFloat) {
  18488. var that = makeAs(input, this),
  18489. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18490. diff, output;
  18491. units = normalizeUnits(units);
  18492. if (units === 'year' || units === 'month') {
  18493. // average number of days in the months in the given dates
  18494. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18495. // difference in months
  18496. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18497. // adjust by taking difference in days, average number of days
  18498. // and dst in the given months.
  18499. output += ((this - moment(this).startOf('month')) -
  18500. (that - moment(that).startOf('month'))) / diff;
  18501. // same as above but with zones, to negate all dst
  18502. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18503. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18504. if (units === 'year') {
  18505. output = output / 12;
  18506. }
  18507. } else {
  18508. diff = (this - that);
  18509. output = units === 'second' ? diff / 1e3 : // 1000
  18510. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18511. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18512. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18513. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18514. diff;
  18515. }
  18516. return asFloat ? output : absRound(output);
  18517. },
  18518. from : function (time, withoutSuffix) {
  18519. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18520. },
  18521. fromNow : function (withoutSuffix) {
  18522. return this.from(moment(), withoutSuffix);
  18523. },
  18524. calendar : function () {
  18525. // We want to compare the start of today, vs this.
  18526. // Getting start-of-today depends on whether we're zone'd or not.
  18527. var sod = makeAs(moment(), this).startOf('day'),
  18528. diff = this.diff(sod, 'days', true),
  18529. format = diff < -6 ? 'sameElse' :
  18530. diff < -1 ? 'lastWeek' :
  18531. diff < 0 ? 'lastDay' :
  18532. diff < 1 ? 'sameDay' :
  18533. diff < 2 ? 'nextDay' :
  18534. diff < 7 ? 'nextWeek' : 'sameElse';
  18535. return this.format(this.lang().calendar(format, this));
  18536. },
  18537. isLeapYear : function () {
  18538. return isLeapYear(this.year());
  18539. },
  18540. isDST : function () {
  18541. return (this.zone() < this.clone().month(0).zone() ||
  18542. this.zone() < this.clone().month(5).zone());
  18543. },
  18544. day : function (input) {
  18545. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  18546. if (input != null) {
  18547. input = parseWeekday(input, this.lang());
  18548. return this.add({ d : input - day });
  18549. } else {
  18550. return day;
  18551. }
  18552. },
  18553. month : function (input) {
  18554. var utc = this._isUTC ? 'UTC' : '',
  18555. dayOfMonth;
  18556. if (input != null) {
  18557. if (typeof input === 'string') {
  18558. input = this.lang().monthsParse(input);
  18559. if (typeof input !== 'number') {
  18560. return this;
  18561. }
  18562. }
  18563. dayOfMonth = this.date();
  18564. this.date(1);
  18565. this._d['set' + utc + 'Month'](input);
  18566. this.date(Math.min(dayOfMonth, this.daysInMonth()));
  18567. moment.updateOffset(this);
  18568. return this;
  18569. } else {
  18570. return this._d['get' + utc + 'Month']();
  18571. }
  18572. },
  18573. startOf: function (units) {
  18574. units = normalizeUnits(units);
  18575. // the following switch intentionally omits break keywords
  18576. // to utilize falling through the cases.
  18577. switch (units) {
  18578. case 'year':
  18579. this.month(0);
  18580. /* falls through */
  18581. case 'month':
  18582. this.date(1);
  18583. /* falls through */
  18584. case 'week':
  18585. case 'isoWeek':
  18586. case 'day':
  18587. this.hours(0);
  18588. /* falls through */
  18589. case 'hour':
  18590. this.minutes(0);
  18591. /* falls through */
  18592. case 'minute':
  18593. this.seconds(0);
  18594. /* falls through */
  18595. case 'second':
  18596. this.milliseconds(0);
  18597. /* falls through */
  18598. }
  18599. // weeks are a special case
  18600. if (units === 'week') {
  18601. this.weekday(0);
  18602. } else if (units === 'isoWeek') {
  18603. this.isoWeekday(1);
  18604. }
  18605. return this;
  18606. },
  18607. endOf: function (units) {
  18608. units = normalizeUnits(units);
  18609. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  18610. },
  18611. isAfter: function (input, units) {
  18612. units = typeof units !== 'undefined' ? units : 'millisecond';
  18613. return +this.clone().startOf(units) > +moment(input).startOf(units);
  18614. },
  18615. isBefore: function (input, units) {
  18616. units = typeof units !== 'undefined' ? units : 'millisecond';
  18617. return +this.clone().startOf(units) < +moment(input).startOf(units);
  18618. },
  18619. isSame: function (input, units) {
  18620. units = units || 'ms';
  18621. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  18622. },
  18623. min: function (other) {
  18624. other = moment.apply(null, arguments);
  18625. return other < this ? this : other;
  18626. },
  18627. max: function (other) {
  18628. other = moment.apply(null, arguments);
  18629. return other > this ? this : other;
  18630. },
  18631. zone : function (input) {
  18632. var offset = this._offset || 0;
  18633. if (input != null) {
  18634. if (typeof input === "string") {
  18635. input = timezoneMinutesFromString(input);
  18636. }
  18637. if (Math.abs(input) < 16) {
  18638. input = input * 60;
  18639. }
  18640. this._offset = input;
  18641. this._isUTC = true;
  18642. if (offset !== input) {
  18643. addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
  18644. }
  18645. } else {
  18646. return this._isUTC ? offset : this._d.getTimezoneOffset();
  18647. }
  18648. return this;
  18649. },
  18650. zoneAbbr : function () {
  18651. return this._isUTC ? "UTC" : "";
  18652. },
  18653. zoneName : function () {
  18654. return this._isUTC ? "Coordinated Universal Time" : "";
  18655. },
  18656. parseZone : function () {
  18657. if (this._tzm) {
  18658. this.zone(this._tzm);
  18659. } else if (typeof this._i === 'string') {
  18660. this.zone(this._i);
  18661. }
  18662. return this;
  18663. },
  18664. hasAlignedHourOffset : function (input) {
  18665. if (!input) {
  18666. input = 0;
  18667. }
  18668. else {
  18669. input = moment(input).zone();
  18670. }
  18671. return (this.zone() - input) % 60 === 0;
  18672. },
  18673. daysInMonth : function () {
  18674. return daysInMonth(this.year(), this.month());
  18675. },
  18676. dayOfYear : function (input) {
  18677. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  18678. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  18679. },
  18680. quarter : function () {
  18681. return Math.ceil((this.month() + 1.0) / 3.0);
  18682. },
  18683. weekYear : function (input) {
  18684. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  18685. return input == null ? year : this.add("y", (input - year));
  18686. },
  18687. isoWeekYear : function (input) {
  18688. var year = weekOfYear(this, 1, 4).year;
  18689. return input == null ? year : this.add("y", (input - year));
  18690. },
  18691. week : function (input) {
  18692. var week = this.lang().week(this);
  18693. return input == null ? week : this.add("d", (input - week) * 7);
  18694. },
  18695. isoWeek : function (input) {
  18696. var week = weekOfYear(this, 1, 4).week;
  18697. return input == null ? week : this.add("d", (input - week) * 7);
  18698. },
  18699. weekday : function (input) {
  18700. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  18701. return input == null ? weekday : this.add("d", input - weekday);
  18702. },
  18703. isoWeekday : function (input) {
  18704. // behaves the same as moment#day except
  18705. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  18706. // as a setter, sunday should belong to the previous week.
  18707. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  18708. },
  18709. get : function (units) {
  18710. units = normalizeUnits(units);
  18711. return this[units]();
  18712. },
  18713. set : function (units, value) {
  18714. units = normalizeUnits(units);
  18715. if (typeof this[units] === 'function') {
  18716. this[units](value);
  18717. }
  18718. return this;
  18719. },
  18720. // If passed a language key, it will set the language for this
  18721. // instance. Otherwise, it will return the language configuration
  18722. // variables for this instance.
  18723. lang : function (key) {
  18724. if (key === undefined) {
  18725. return this._lang;
  18726. } else {
  18727. this._lang = getLangDefinition(key);
  18728. return this;
  18729. }
  18730. }
  18731. });
  18732. // helper for adding shortcuts
  18733. function makeGetterAndSetter(name, key) {
  18734. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  18735. var utc = this._isUTC ? 'UTC' : '';
  18736. if (input != null) {
  18737. this._d['set' + utc + key](input);
  18738. moment.updateOffset(this);
  18739. return this;
  18740. } else {
  18741. return this._d['get' + utc + key]();
  18742. }
  18743. };
  18744. }
  18745. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  18746. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  18747. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  18748. }
  18749. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  18750. makeGetterAndSetter('year', 'FullYear');
  18751. // add plural methods
  18752. moment.fn.days = moment.fn.day;
  18753. moment.fn.months = moment.fn.month;
  18754. moment.fn.weeks = moment.fn.week;
  18755. moment.fn.isoWeeks = moment.fn.isoWeek;
  18756. // add aliased format methods
  18757. moment.fn.toJSON = moment.fn.toISOString;
  18758. /************************************
  18759. Duration Prototype
  18760. ************************************/
  18761. extend(moment.duration.fn = Duration.prototype, {
  18762. _bubble : function () {
  18763. var milliseconds = this._milliseconds,
  18764. days = this._days,
  18765. months = this._months,
  18766. data = this._data,
  18767. seconds, minutes, hours, years;
  18768. // The following code bubbles up values, see the tests for
  18769. // examples of what that means.
  18770. data.milliseconds = milliseconds % 1000;
  18771. seconds = absRound(milliseconds / 1000);
  18772. data.seconds = seconds % 60;
  18773. minutes = absRound(seconds / 60);
  18774. data.minutes = minutes % 60;
  18775. hours = absRound(minutes / 60);
  18776. data.hours = hours % 24;
  18777. days += absRound(hours / 24);
  18778. data.days = days % 30;
  18779. months += absRound(days / 30);
  18780. data.months = months % 12;
  18781. years = absRound(months / 12);
  18782. data.years = years;
  18783. },
  18784. weeks : function () {
  18785. return absRound(this.days() / 7);
  18786. },
  18787. valueOf : function () {
  18788. return this._milliseconds +
  18789. this._days * 864e5 +
  18790. (this._months % 12) * 2592e6 +
  18791. toInt(this._months / 12) * 31536e6;
  18792. },
  18793. humanize : function (withSuffix) {
  18794. var difference = +this,
  18795. output = relativeTime(difference, !withSuffix, this.lang());
  18796. if (withSuffix) {
  18797. output = this.lang().pastFuture(difference, output);
  18798. }
  18799. return this.lang().postformat(output);
  18800. },
  18801. add : function (input, val) {
  18802. // supports only 2.0-style add(1, 's') or add(moment)
  18803. var dur = moment.duration(input, val);
  18804. this._milliseconds += dur._milliseconds;
  18805. this._days += dur._days;
  18806. this._months += dur._months;
  18807. this._bubble();
  18808. return this;
  18809. },
  18810. subtract : function (input, val) {
  18811. var dur = moment.duration(input, val);
  18812. this._milliseconds -= dur._milliseconds;
  18813. this._days -= dur._days;
  18814. this._months -= dur._months;
  18815. this._bubble();
  18816. return this;
  18817. },
  18818. get : function (units) {
  18819. units = normalizeUnits(units);
  18820. return this[units.toLowerCase() + 's']();
  18821. },
  18822. as : function (units) {
  18823. units = normalizeUnits(units);
  18824. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  18825. },
  18826. lang : moment.fn.lang,
  18827. toIsoString : function () {
  18828. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  18829. var years = Math.abs(this.years()),
  18830. months = Math.abs(this.months()),
  18831. days = Math.abs(this.days()),
  18832. hours = Math.abs(this.hours()),
  18833. minutes = Math.abs(this.minutes()),
  18834. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  18835. if (!this.asSeconds()) {
  18836. // this is the same as C#'s (Noda) and python (isodate)...
  18837. // but not other JS (goog.date)
  18838. return 'P0D';
  18839. }
  18840. return (this.asSeconds() < 0 ? '-' : '') +
  18841. 'P' +
  18842. (years ? years + 'Y' : '') +
  18843. (months ? months + 'M' : '') +
  18844. (days ? days + 'D' : '') +
  18845. ((hours || minutes || seconds) ? 'T' : '') +
  18846. (hours ? hours + 'H' : '') +
  18847. (minutes ? minutes + 'M' : '') +
  18848. (seconds ? seconds + 'S' : '');
  18849. }
  18850. });
  18851. function makeDurationGetter(name) {
  18852. moment.duration.fn[name] = function () {
  18853. return this._data[name];
  18854. };
  18855. }
  18856. function makeDurationAsGetter(name, factor) {
  18857. moment.duration.fn['as' + name] = function () {
  18858. return +this / factor;
  18859. };
  18860. }
  18861. for (i in unitMillisecondFactors) {
  18862. if (unitMillisecondFactors.hasOwnProperty(i)) {
  18863. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  18864. makeDurationGetter(i.toLowerCase());
  18865. }
  18866. }
  18867. makeDurationAsGetter('Weeks', 6048e5);
  18868. moment.duration.fn.asMonths = function () {
  18869. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  18870. };
  18871. /************************************
  18872. Default Lang
  18873. ************************************/
  18874. // Set default language, other languages will inherit from English.
  18875. moment.lang('en', {
  18876. ordinal : function (number) {
  18877. var b = number % 10,
  18878. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  18879. (b === 1) ? 'st' :
  18880. (b === 2) ? 'nd' :
  18881. (b === 3) ? 'rd' : 'th';
  18882. return number + output;
  18883. }
  18884. });
  18885. /* EMBED_LANGUAGES */
  18886. /************************************
  18887. Exposing Moment
  18888. ************************************/
  18889. function makeGlobal(deprecate) {
  18890. var warned = false, local_moment = moment;
  18891. /*global ender:false */
  18892. if (typeof ender !== 'undefined') {
  18893. return;
  18894. }
  18895. // here, `this` means `window` in the browser, or `global` on the server
  18896. // add `moment` as a global object via a string identifier,
  18897. // for Closure Compiler "advanced" mode
  18898. if (deprecate) {
  18899. global.moment = function () {
  18900. if (!warned && console && console.warn) {
  18901. warned = true;
  18902. console.warn(
  18903. "Accessing Moment through the global scope is " +
  18904. "deprecated, and will be removed in an upcoming " +
  18905. "release.");
  18906. }
  18907. return local_moment.apply(null, arguments);
  18908. };
  18909. extend(global.moment, local_moment);
  18910. } else {
  18911. global['moment'] = moment;
  18912. }
  18913. }
  18914. // CommonJS module is defined
  18915. if (hasModule) {
  18916. module.exports = moment;
  18917. makeGlobal(true);
  18918. } else if (typeof define === "function" && define.amd) {
  18919. define("moment", function (require, exports, module) {
  18920. if (module.config && module.config() && module.config().noGlobal !== true) {
  18921. // If user provided noGlobal, he is aware of global
  18922. makeGlobal(module.config().noGlobal === undefined);
  18923. }
  18924. return moment;
  18925. });
  18926. } else {
  18927. makeGlobal();
  18928. }
  18929. }).call(this);
  18930. },{}],5:[function(require,module,exports){
  18931. /**
  18932. * Copyright 2012 Craig Campbell
  18933. *
  18934. * Licensed under the Apache License, Version 2.0 (the "License");
  18935. * you may not use this file except in compliance with the License.
  18936. * You may obtain a copy of the License at
  18937. *
  18938. * http://www.apache.org/licenses/LICENSE-2.0
  18939. *
  18940. * Unless required by applicable law or agreed to in writing, software
  18941. * distributed under the License is distributed on an "AS IS" BASIS,
  18942. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18943. * See the License for the specific language governing permissions and
  18944. * limitations under the License.
  18945. *
  18946. * Mousetrap is a simple keyboard shortcut library for Javascript with
  18947. * no external dependencies
  18948. *
  18949. * @version 1.1.2
  18950. * @url craig.is/killing/mice
  18951. */
  18952. /**
  18953. * mapping of special keycodes to their corresponding keys
  18954. *
  18955. * everything in this dictionary cannot use keypress events
  18956. * so it has to be here to map to the correct keycodes for
  18957. * keyup/keydown events
  18958. *
  18959. * @type {Object}
  18960. */
  18961. var _MAP = {
  18962. 8: 'backspace',
  18963. 9: 'tab',
  18964. 13: 'enter',
  18965. 16: 'shift',
  18966. 17: 'ctrl',
  18967. 18: 'alt',
  18968. 20: 'capslock',
  18969. 27: 'esc',
  18970. 32: 'space',
  18971. 33: 'pageup',
  18972. 34: 'pagedown',
  18973. 35: 'end',
  18974. 36: 'home',
  18975. 37: 'left',
  18976. 38: 'up',
  18977. 39: 'right',
  18978. 40: 'down',
  18979. 45: 'ins',
  18980. 46: 'del',
  18981. 91: 'meta',
  18982. 93: 'meta',
  18983. 224: 'meta'
  18984. },
  18985. /**
  18986. * mapping for special characters so they can support
  18987. *
  18988. * this dictionary is only used incase you want to bind a
  18989. * keyup or keydown event to one of these keys
  18990. *
  18991. * @type {Object}
  18992. */
  18993. _KEYCODE_MAP = {
  18994. 106: '*',
  18995. 107: '+',
  18996. 109: '-',
  18997. 110: '.',
  18998. 111 : '/',
  18999. 186: ';',
  19000. 187: '=',
  19001. 188: ',',
  19002. 189: '-',
  19003. 190: '.',
  19004. 191: '/',
  19005. 192: '`',
  19006. 219: '[',
  19007. 220: '\\',
  19008. 221: ']',
  19009. 222: '\''
  19010. },
  19011. /**
  19012. * this is a mapping of keys that require shift on a US keypad
  19013. * back to the non shift equivelents
  19014. *
  19015. * this is so you can use keyup events with these keys
  19016. *
  19017. * note that this will only work reliably on US keyboards
  19018. *
  19019. * @type {Object}
  19020. */
  19021. _SHIFT_MAP = {
  19022. '~': '`',
  19023. '!': '1',
  19024. '@': '2',
  19025. '#': '3',
  19026. '$': '4',
  19027. '%': '5',
  19028. '^': '6',
  19029. '&': '7',
  19030. '*': '8',
  19031. '(': '9',
  19032. ')': '0',
  19033. '_': '-',
  19034. '+': '=',
  19035. ':': ';',
  19036. '\"': '\'',
  19037. '<': ',',
  19038. '>': '.',
  19039. '?': '/',
  19040. '|': '\\'
  19041. },
  19042. /**
  19043. * this is a list of special strings you can use to map
  19044. * to modifier keys when you specify your keyboard shortcuts
  19045. *
  19046. * @type {Object}
  19047. */
  19048. _SPECIAL_ALIASES = {
  19049. 'option': 'alt',
  19050. 'command': 'meta',
  19051. 'return': 'enter',
  19052. 'escape': 'esc'
  19053. },
  19054. /**
  19055. * variable to store the flipped version of _MAP from above
  19056. * needed to check if we should use keypress or not when no action
  19057. * is specified
  19058. *
  19059. * @type {Object|undefined}
  19060. */
  19061. _REVERSE_MAP,
  19062. /**
  19063. * a list of all the callbacks setup via Mousetrap.bind()
  19064. *
  19065. * @type {Object}
  19066. */
  19067. _callbacks = {},
  19068. /**
  19069. * direct map of string combinations to callbacks used for trigger()
  19070. *
  19071. * @type {Object}
  19072. */
  19073. _direct_map = {},
  19074. /**
  19075. * keeps track of what level each sequence is at since multiple
  19076. * sequences can start out with the same sequence
  19077. *
  19078. * @type {Object}
  19079. */
  19080. _sequence_levels = {},
  19081. /**
  19082. * variable to store the setTimeout call
  19083. *
  19084. * @type {null|number}
  19085. */
  19086. _reset_timer,
  19087. /**
  19088. * temporary state where we will ignore the next keyup
  19089. *
  19090. * @type {boolean|string}
  19091. */
  19092. _ignore_next_keyup = false,
  19093. /**
  19094. * are we currently inside of a sequence?
  19095. * type of action ("keyup" or "keydown" or "keypress") or false
  19096. *
  19097. * @type {boolean|string}
  19098. */
  19099. _inside_sequence = false;
  19100. /**
  19101. * loop through the f keys, f1 to f19 and add them to the map
  19102. * programatically
  19103. */
  19104. for (var i = 1; i < 20; ++i) {
  19105. _MAP[111 + i] = 'f' + i;
  19106. }
  19107. /**
  19108. * loop through to map numbers on the numeric keypad
  19109. */
  19110. for (i = 0; i <= 9; ++i) {
  19111. _MAP[i + 96] = i;
  19112. }
  19113. /**
  19114. * cross browser add event method
  19115. *
  19116. * @param {Element|HTMLDocument} object
  19117. * @param {string} type
  19118. * @param {Function} callback
  19119. * @returns void
  19120. */
  19121. function _addEvent(object, type, callback) {
  19122. if (object.addEventListener) {
  19123. return object.addEventListener(type, callback, false);
  19124. }
  19125. object.attachEvent('on' + type, callback);
  19126. }
  19127. /**
  19128. * takes the event and returns the key character
  19129. *
  19130. * @param {Event} e
  19131. * @return {string}
  19132. */
  19133. function _characterFromEvent(e) {
  19134. // for keypress events we should return the character as is
  19135. if (e.type == 'keypress') {
  19136. return String.fromCharCode(e.which);
  19137. }
  19138. // for non keypress events the special maps are needed
  19139. if (_MAP[e.which]) {
  19140. return _MAP[e.which];
  19141. }
  19142. if (_KEYCODE_MAP[e.which]) {
  19143. return _KEYCODE_MAP[e.which];
  19144. }
  19145. // if it is not in the special map
  19146. return String.fromCharCode(e.which).toLowerCase();
  19147. }
  19148. /**
  19149. * should we stop this event before firing off callbacks
  19150. *
  19151. * @param {Event} e
  19152. * @return {boolean}
  19153. */
  19154. function _stop(e) {
  19155. var element = e.target || e.srcElement,
  19156. tag_name = element.tagName;
  19157. // if the element has the class "mousetrap" then no need to stop
  19158. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19159. return false;
  19160. }
  19161. // stop for input, select, and textarea
  19162. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19163. }
  19164. /**
  19165. * checks if two arrays are equal
  19166. *
  19167. * @param {Array} modifiers1
  19168. * @param {Array} modifiers2
  19169. * @returns {boolean}
  19170. */
  19171. function _modifiersMatch(modifiers1, modifiers2) {
  19172. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19173. }
  19174. /**
  19175. * resets all sequence counters except for the ones passed in
  19176. *
  19177. * @param {Object} do_not_reset
  19178. * @returns void
  19179. */
  19180. function _resetSequences(do_not_reset) {
  19181. do_not_reset = do_not_reset || {};
  19182. var active_sequences = false,
  19183. key;
  19184. for (key in _sequence_levels) {
  19185. if (do_not_reset[key]) {
  19186. active_sequences = true;
  19187. continue;
  19188. }
  19189. _sequence_levels[key] = 0;
  19190. }
  19191. if (!active_sequences) {
  19192. _inside_sequence = false;
  19193. }
  19194. }
  19195. /**
  19196. * finds all callbacks that match based on the keycode, modifiers,
  19197. * and action
  19198. *
  19199. * @param {string} character
  19200. * @param {Array} modifiers
  19201. * @param {string} action
  19202. * @param {boolean=} remove - should we remove any matches
  19203. * @param {string=} combination
  19204. * @returns {Array}
  19205. */
  19206. function _getMatches(character, modifiers, action, remove, combination) {
  19207. var i,
  19208. callback,
  19209. matches = [];
  19210. // if there are no events related to this keycode
  19211. if (!_callbacks[character]) {
  19212. return [];
  19213. }
  19214. // if a modifier key is coming up on its own we should allow it
  19215. if (action == 'keyup' && _isModifier(character)) {
  19216. modifiers = [character];
  19217. }
  19218. // loop through all callbacks for the key that was pressed
  19219. // and see if any of them match
  19220. for (i = 0; i < _callbacks[character].length; ++i) {
  19221. callback = _callbacks[character][i];
  19222. // if this is a sequence but it is not at the right level
  19223. // then move onto the next match
  19224. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19225. continue;
  19226. }
  19227. // if the action we are looking for doesn't match the action we got
  19228. // then we should keep going
  19229. if (action != callback.action) {
  19230. continue;
  19231. }
  19232. // if this is a keypress event that means that we need to only
  19233. // look at the character, otherwise check the modifiers as
  19234. // well
  19235. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19236. // remove is used so if you change your mind and call bind a
  19237. // second time with a new function the first one is overwritten
  19238. if (remove && callback.combo == combination) {
  19239. _callbacks[character].splice(i, 1);
  19240. }
  19241. matches.push(callback);
  19242. }
  19243. }
  19244. return matches;
  19245. }
  19246. /**
  19247. * takes a key event and figures out what the modifiers are
  19248. *
  19249. * @param {Event} e
  19250. * @returns {Array}
  19251. */
  19252. function _eventModifiers(e) {
  19253. var modifiers = [];
  19254. if (e.shiftKey) {
  19255. modifiers.push('shift');
  19256. }
  19257. if (e.altKey) {
  19258. modifiers.push('alt');
  19259. }
  19260. if (e.ctrlKey) {
  19261. modifiers.push('ctrl');
  19262. }
  19263. if (e.metaKey) {
  19264. modifiers.push('meta');
  19265. }
  19266. return modifiers;
  19267. }
  19268. /**
  19269. * actually calls the callback function
  19270. *
  19271. * if your callback function returns false this will use the jquery
  19272. * convention - prevent default and stop propogation on the event
  19273. *
  19274. * @param {Function} callback
  19275. * @param {Event} e
  19276. * @returns void
  19277. */
  19278. function _fireCallback(callback, e) {
  19279. if (callback(e) === false) {
  19280. if (e.preventDefault) {
  19281. e.preventDefault();
  19282. }
  19283. if (e.stopPropagation) {
  19284. e.stopPropagation();
  19285. }
  19286. e.returnValue = false;
  19287. e.cancelBubble = true;
  19288. }
  19289. }
  19290. /**
  19291. * handles a character key event
  19292. *
  19293. * @param {string} character
  19294. * @param {Event} e
  19295. * @returns void
  19296. */
  19297. function _handleCharacter(character, e) {
  19298. // if this event should not happen stop here
  19299. if (_stop(e)) {
  19300. return;
  19301. }
  19302. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19303. i,
  19304. do_not_reset = {},
  19305. processed_sequence_callback = false;
  19306. // loop through matching callbacks for this key event
  19307. for (i = 0; i < callbacks.length; ++i) {
  19308. // fire for all sequence callbacks
  19309. // this is because if for example you have multiple sequences
  19310. // bound such as "g i" and "g t" they both need to fire the
  19311. // callback for matching g cause otherwise you can only ever
  19312. // match the first one
  19313. if (callbacks[i].seq) {
  19314. processed_sequence_callback = true;
  19315. // keep a list of which sequences were matches for later
  19316. do_not_reset[callbacks[i].seq] = 1;
  19317. _fireCallback(callbacks[i].callback, e);
  19318. continue;
  19319. }
  19320. // if there were no sequence matches but we are still here
  19321. // that means this is a regular match so we should fire that
  19322. if (!processed_sequence_callback && !_inside_sequence) {
  19323. _fireCallback(callbacks[i].callback, e);
  19324. }
  19325. }
  19326. // if you are inside of a sequence and the key you are pressing
  19327. // is not a modifier key then we should reset all sequences
  19328. // that were not matched by this key event
  19329. if (e.type == _inside_sequence && !_isModifier(character)) {
  19330. _resetSequences(do_not_reset);
  19331. }
  19332. }
  19333. /**
  19334. * handles a keydown event
  19335. *
  19336. * @param {Event} e
  19337. * @returns void
  19338. */
  19339. function _handleKey(e) {
  19340. // normalize e.which for key events
  19341. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19342. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19343. var character = _characterFromEvent(e);
  19344. // no character found then stop
  19345. if (!character) {
  19346. return;
  19347. }
  19348. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19349. _ignore_next_keyup = false;
  19350. return;
  19351. }
  19352. _handleCharacter(character, e);
  19353. }
  19354. /**
  19355. * determines if the keycode specified is a modifier key or not
  19356. *
  19357. * @param {string} key
  19358. * @returns {boolean}
  19359. */
  19360. function _isModifier(key) {
  19361. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19362. }
  19363. /**
  19364. * called to set a 1 second timeout on the specified sequence
  19365. *
  19366. * this is so after each key press in the sequence you have 1 second
  19367. * to press the next key before you have to start over
  19368. *
  19369. * @returns void
  19370. */
  19371. function _resetSequenceTimer() {
  19372. clearTimeout(_reset_timer);
  19373. _reset_timer = setTimeout(_resetSequences, 1000);
  19374. }
  19375. /**
  19376. * reverses the map lookup so that we can look for specific keys
  19377. * to see what can and can't use keypress
  19378. *
  19379. * @return {Object}
  19380. */
  19381. function _getReverseMap() {
  19382. if (!_REVERSE_MAP) {
  19383. _REVERSE_MAP = {};
  19384. for (var key in _MAP) {
  19385. // pull out the numeric keypad from here cause keypress should
  19386. // be able to detect the keys from the character
  19387. if (key > 95 && key < 112) {
  19388. continue;
  19389. }
  19390. if (_MAP.hasOwnProperty(key)) {
  19391. _REVERSE_MAP[_MAP[key]] = key;
  19392. }
  19393. }
  19394. }
  19395. return _REVERSE_MAP;
  19396. }
  19397. /**
  19398. * picks the best action based on the key combination
  19399. *
  19400. * @param {string} key - character for key
  19401. * @param {Array} modifiers
  19402. * @param {string=} action passed in
  19403. */
  19404. function _pickBestAction(key, modifiers, action) {
  19405. // if no action was picked in we should try to pick the one
  19406. // that we think would work best for this key
  19407. if (!action) {
  19408. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19409. }
  19410. // modifier keys don't work as expected with keypress,
  19411. // switch to keydown
  19412. if (action == 'keypress' && modifiers.length) {
  19413. action = 'keydown';
  19414. }
  19415. return action;
  19416. }
  19417. /**
  19418. * binds a key sequence to an event
  19419. *
  19420. * @param {string} combo - combo specified in bind call
  19421. * @param {Array} keys
  19422. * @param {Function} callback
  19423. * @param {string=} action
  19424. * @returns void
  19425. */
  19426. function _bindSequence(combo, keys, callback, action) {
  19427. // start off by adding a sequence level record for this combination
  19428. // and setting the level to 0
  19429. _sequence_levels[combo] = 0;
  19430. // if there is no action pick the best one for the first key
  19431. // in the sequence
  19432. if (!action) {
  19433. action = _pickBestAction(keys[0], []);
  19434. }
  19435. /**
  19436. * callback to increase the sequence level for this sequence and reset
  19437. * all other sequences that were active
  19438. *
  19439. * @param {Event} e
  19440. * @returns void
  19441. */
  19442. var _increaseSequence = function(e) {
  19443. _inside_sequence = action;
  19444. ++_sequence_levels[combo];
  19445. _resetSequenceTimer();
  19446. },
  19447. /**
  19448. * wraps the specified callback inside of another function in order
  19449. * to reset all sequence counters as soon as this sequence is done
  19450. *
  19451. * @param {Event} e
  19452. * @returns void
  19453. */
  19454. _callbackAndReset = function(e) {
  19455. _fireCallback(callback, e);
  19456. // we should ignore the next key up if the action is key down
  19457. // or keypress. this is so if you finish a sequence and
  19458. // release the key the final key will not trigger a keyup
  19459. if (action !== 'keyup') {
  19460. _ignore_next_keyup = _characterFromEvent(e);
  19461. }
  19462. // weird race condition if a sequence ends with the key
  19463. // another sequence begins with
  19464. setTimeout(_resetSequences, 10);
  19465. },
  19466. i;
  19467. // loop through keys one at a time and bind the appropriate callback
  19468. // function. for any key leading up to the final one it should
  19469. // increase the sequence. after the final, it should reset all sequences
  19470. for (i = 0; i < keys.length; ++i) {
  19471. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19472. }
  19473. }
  19474. /**
  19475. * binds a single keyboard combination
  19476. *
  19477. * @param {string} combination
  19478. * @param {Function} callback
  19479. * @param {string=} action
  19480. * @param {string=} sequence_name - name of sequence if part of sequence
  19481. * @param {number=} level - what part of the sequence the command is
  19482. * @returns void
  19483. */
  19484. function _bindSingle(combination, callback, action, sequence_name, level) {
  19485. // make sure multiple spaces in a row become a single space
  19486. combination = combination.replace(/\s+/g, ' ');
  19487. var sequence = combination.split(' '),
  19488. i,
  19489. key,
  19490. keys,
  19491. modifiers = [];
  19492. // if this pattern is a sequence of keys then run through this method
  19493. // to reprocess each pattern one key at a time
  19494. if (sequence.length > 1) {
  19495. return _bindSequence(combination, sequence, callback, action);
  19496. }
  19497. // take the keys from this pattern and figure out what the actual
  19498. // pattern is all about
  19499. keys = combination === '+' ? ['+'] : combination.split('+');
  19500. for (i = 0; i < keys.length; ++i) {
  19501. key = keys[i];
  19502. // normalize key names
  19503. if (_SPECIAL_ALIASES[key]) {
  19504. key = _SPECIAL_ALIASES[key];
  19505. }
  19506. // if this is not a keypress event then we should
  19507. // be smart about using shift keys
  19508. // this will only work for US keyboards however
  19509. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  19510. key = _SHIFT_MAP[key];
  19511. modifiers.push('shift');
  19512. }
  19513. // if this key is a modifier then add it to the list of modifiers
  19514. if (_isModifier(key)) {
  19515. modifiers.push(key);
  19516. }
  19517. }
  19518. // depending on what the key combination is
  19519. // we will try to pick the best event for it
  19520. action = _pickBestAction(key, modifiers, action);
  19521. // make sure to initialize array if this is the first time
  19522. // a callback is added for this key
  19523. if (!_callbacks[key]) {
  19524. _callbacks[key] = [];
  19525. }
  19526. // remove an existing match if there is one
  19527. _getMatches(key, modifiers, action, !sequence_name, combination);
  19528. // add this call back to the array
  19529. // if it is a sequence put it at the beginning
  19530. // if not put it at the end
  19531. //
  19532. // this is important because the way these are processed expects
  19533. // the sequence ones to come first
  19534. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  19535. callback: callback,
  19536. modifiers: modifiers,
  19537. action: action,
  19538. seq: sequence_name,
  19539. level: level,
  19540. combo: combination
  19541. });
  19542. }
  19543. /**
  19544. * binds multiple combinations to the same callback
  19545. *
  19546. * @param {Array} combinations
  19547. * @param {Function} callback
  19548. * @param {string|undefined} action
  19549. * @returns void
  19550. */
  19551. function _bindMultiple(combinations, callback, action) {
  19552. for (var i = 0; i < combinations.length; ++i) {
  19553. _bindSingle(combinations[i], callback, action);
  19554. }
  19555. }
  19556. // start!
  19557. _addEvent(document, 'keypress', _handleKey);
  19558. _addEvent(document, 'keydown', _handleKey);
  19559. _addEvent(document, 'keyup', _handleKey);
  19560. var mousetrap = {
  19561. /**
  19562. * binds an event to mousetrap
  19563. *
  19564. * can be a single key, a combination of keys separated with +,
  19565. * a comma separated list of keys, an array of keys, or
  19566. * a sequence of keys separated by spaces
  19567. *
  19568. * be sure to list the modifier keys first to make sure that the
  19569. * correct key ends up getting bound (the last key in the pattern)
  19570. *
  19571. * @param {string|Array} keys
  19572. * @param {Function} callback
  19573. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  19574. * @returns void
  19575. */
  19576. bind: function(keys, callback, action) {
  19577. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  19578. _direct_map[keys + ':' + action] = callback;
  19579. return this;
  19580. },
  19581. /**
  19582. * unbinds an event to mousetrap
  19583. *
  19584. * the unbinding sets the callback function of the specified key combo
  19585. * to an empty function and deletes the corresponding key in the
  19586. * _direct_map dict.
  19587. *
  19588. * the keycombo+action has to be exactly the same as
  19589. * it was defined in the bind method
  19590. *
  19591. * TODO: actually remove this from the _callbacks dictionary instead
  19592. * of binding an empty function
  19593. *
  19594. * @param {string|Array} keys
  19595. * @param {string} action
  19596. * @returns void
  19597. */
  19598. unbind: function(keys, action) {
  19599. if (_direct_map[keys + ':' + action]) {
  19600. delete _direct_map[keys + ':' + action];
  19601. this.bind(keys, function() {}, action);
  19602. }
  19603. return this;
  19604. },
  19605. /**
  19606. * triggers an event that has already been bound
  19607. *
  19608. * @param {string} keys
  19609. * @param {string=} action
  19610. * @returns void
  19611. */
  19612. trigger: function(keys, action) {
  19613. _direct_map[keys + ':' + action]();
  19614. return this;
  19615. },
  19616. /**
  19617. * resets the library back to its initial state. this is useful
  19618. * if you want to clear out the current keyboard shortcuts and bind
  19619. * new ones - for example if you switch to another page
  19620. *
  19621. * @returns void
  19622. */
  19623. reset: function() {
  19624. _callbacks = {};
  19625. _direct_map = {};
  19626. return this;
  19627. }
  19628. };
  19629. module.exports = mousetrap;
  19630. },{}]},{},[1])
  19631. (1)
  19632. });