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.

23098 lines
678 KiB

10 years ago
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.7.4-SNAPSHOT
  8. * @date 2014-04-16
  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. * Parse a color property into an object with border, background, and
  897. * highlight colors
  898. * @param {Object | String} color
  899. * @return {Object} colorObject
  900. */
  901. util.parseColor = function(color) {
  902. var c;
  903. if (util.isString(color)) {
  904. if (util.isValidHex(color)) {
  905. var hsv = util.hexToHSV(color);
  906. var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
  907. var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
  908. var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
  909. var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
  910. c = {
  911. background: color,
  912. border:darkerColorHex,
  913. highlight: {
  914. background:lighterColorHex,
  915. border:darkerColorHex
  916. }
  917. };
  918. }
  919. else {
  920. c = {
  921. background:color,
  922. border:color,
  923. highlight: {
  924. background:color,
  925. border:color
  926. }
  927. };
  928. }
  929. }
  930. else {
  931. c = {};
  932. c.background = color.background || 'white';
  933. c.border = color.border || c.background;
  934. if (util.isString(color.highlight)) {
  935. c.highlight = {
  936. border: color.highlight,
  937. background: color.highlight
  938. }
  939. }
  940. else {
  941. c.highlight = {};
  942. c.highlight.background = color.highlight && color.highlight.background || c.background;
  943. c.highlight.border = color.highlight && color.highlight.border || c.border;
  944. }
  945. }
  946. return c;
  947. };
  948. /**
  949. * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
  950. *
  951. * @param {String} hex
  952. * @returns {{r: *, g: *, b: *}}
  953. */
  954. util.hexToRGB = function hexToRGB(hex) {
  955. hex = hex.replace("#","").toUpperCase();
  956. var a = util.GiveDec(hex.substring(0, 1));
  957. var b = util.GiveDec(hex.substring(1, 2));
  958. var c = util.GiveDec(hex.substring(2, 3));
  959. var d = util.GiveDec(hex.substring(3, 4));
  960. var e = util.GiveDec(hex.substring(4, 5));
  961. var f = util.GiveDec(hex.substring(5, 6));
  962. var r = (a * 16) + b;
  963. var g = (c * 16) + d;
  964. var b = (e * 16) + f;
  965. return {r:r,g:g,b:b};
  966. };
  967. util.RGBToHex = function RGBToHex(red,green,blue) {
  968. var a = util.GiveHex(Math.floor(red / 16));
  969. var b = util.GiveHex(red % 16);
  970. var c = util.GiveHex(Math.floor(green / 16));
  971. var d = util.GiveHex(green % 16);
  972. var e = util.GiveHex(Math.floor(blue / 16));
  973. var f = util.GiveHex(blue % 16);
  974. var hex = a + b + c + d + e + f;
  975. return "#" + hex;
  976. };
  977. /**
  978. * http://www.javascripter.net/faq/rgb2hsv.htm
  979. *
  980. * @param red
  981. * @param green
  982. * @param blue
  983. * @returns {*}
  984. * @constructor
  985. */
  986. util.RGBToHSV = function RGBToHSV (red,green,blue) {
  987. red=red/255; green=green/255; blue=blue/255;
  988. var minRGB = Math.min(red,Math.min(green,blue));
  989. var maxRGB = Math.max(red,Math.max(green,blue));
  990. // Black-gray-white
  991. if (minRGB == maxRGB) {
  992. return {h:0,s:0,v:minRGB};
  993. }
  994. // Colors other than black-gray-white:
  995. var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
  996. var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
  997. var hue = 60*(h - d/(maxRGB - minRGB))/360;
  998. var saturation = (maxRGB - minRGB)/maxRGB;
  999. var value = maxRGB;
  1000. return {h:hue,s:saturation,v:value};
  1001. };
  1002. /**
  1003. * https://gist.github.com/mjijackson/5311256
  1004. * @param hue
  1005. * @param saturation
  1006. * @param value
  1007. * @returns {{r: number, g: number, b: number}}
  1008. * @constructor
  1009. */
  1010. util.HSVToRGB = function HSVToRGB(h, s, v) {
  1011. var r, g, b;
  1012. var i = Math.floor(h * 6);
  1013. var f = h * 6 - i;
  1014. var p = v * (1 - s);
  1015. var q = v * (1 - f * s);
  1016. var t = v * (1 - (1 - f) * s);
  1017. switch (i % 6) {
  1018. case 0: r = v, g = t, b = p; break;
  1019. case 1: r = q, g = v, b = p; break;
  1020. case 2: r = p, g = v, b = t; break;
  1021. case 3: r = p, g = q, b = v; break;
  1022. case 4: r = t, g = p, b = v; break;
  1023. case 5: r = v, g = p, b = q; break;
  1024. }
  1025. return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
  1026. };
  1027. util.HSVToHex = function HSVToHex(h,s,v) {
  1028. var rgb = util.HSVToRGB(h,s,v);
  1029. return util.RGBToHex(rgb.r,rgb.g,rgb.b);
  1030. }
  1031. util.hexToHSV = function hexToHSV(hex) {
  1032. var rgb = util.hexToRGB(hex);
  1033. return util.RGBToHSV(rgb.r,rgb.g,rgb.b);
  1034. }
  1035. util.isValidHex = function isValidHex(hex) {
  1036. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1037. return isOk;
  1038. }
  1039. util.copyObject = function copyObject(objectFrom,objectTo) {
  1040. for (var i in objectFrom) {
  1041. if (objectFrom.hasOwnProperty(i)) {
  1042. if (typeof objectFrom[i] == "object") {
  1043. objectTo[i] = {};
  1044. util.copyObject(objectFrom[i],objectTo[i]);
  1045. }
  1046. else {
  1047. objectTo[i] = objectFrom[i];
  1048. }
  1049. }
  1050. }
  1051. }
  1052. /**
  1053. * DataSet
  1054. *
  1055. * Usage:
  1056. * var dataSet = new DataSet({
  1057. * fieldId: '_id',
  1058. * convert: {
  1059. * // ...
  1060. * }
  1061. * });
  1062. *
  1063. * dataSet.add(item);
  1064. * dataSet.add(data);
  1065. * dataSet.update(item);
  1066. * dataSet.update(data);
  1067. * dataSet.remove(id);
  1068. * dataSet.remove(ids);
  1069. * var data = dataSet.get();
  1070. * var data = dataSet.get(id);
  1071. * var data = dataSet.get(ids);
  1072. * var data = dataSet.get(ids, options, data);
  1073. * dataSet.clear();
  1074. *
  1075. * A data set can:
  1076. * - add/remove/update data
  1077. * - gives triggers upon changes in the data
  1078. * - can import/export data in various data formats
  1079. *
  1080. * @param {Object} [options] Available options:
  1081. * {String} fieldId Field name of the id in the
  1082. * items, 'id' by default.
  1083. * {Object.<String, String} convert
  1084. * A map with field names as key,
  1085. * and the field type as value.
  1086. * @constructor DataSet
  1087. */
  1088. // TODO: add a DataSet constructor DataSet(data, options)
  1089. function DataSet (options) {
  1090. this.id = util.randomUUID();
  1091. this.options = options || {};
  1092. this.data = {}; // map with data indexed by id
  1093. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1094. this.convert = {}; // field types by field name
  1095. this.showInternalIds = this.options.showInternalIds || false; // show internal ids with the get function
  1096. if (this.options.convert) {
  1097. for (var field in this.options.convert) {
  1098. if (this.options.convert.hasOwnProperty(field)) {
  1099. var value = this.options.convert[field];
  1100. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1101. this.convert[field] = 'Date';
  1102. }
  1103. else {
  1104. this.convert[field] = value;
  1105. }
  1106. }
  1107. }
  1108. }
  1109. // event subscribers
  1110. this.subscribers = {};
  1111. this.internalIds = {}; // internally generated id's
  1112. }
  1113. /**
  1114. * Subscribe to an event, add an event listener
  1115. * @param {String} event Event name. Available events: 'put', 'update',
  1116. * 'remove'
  1117. * @param {function} callback Callback method. Called with three parameters:
  1118. * {String} event
  1119. * {Object | null} params
  1120. * {String | Number} senderId
  1121. */
  1122. DataSet.prototype.on = function on (event, callback) {
  1123. var subscribers = this.subscribers[event];
  1124. if (!subscribers) {
  1125. subscribers = [];
  1126. this.subscribers[event] = subscribers;
  1127. }
  1128. subscribers.push({
  1129. callback: callback
  1130. });
  1131. };
  1132. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1133. DataSet.prototype.subscribe = DataSet.prototype.on;
  1134. /**
  1135. * Unsubscribe from an event, remove an event listener
  1136. * @param {String} event
  1137. * @param {function} callback
  1138. */
  1139. DataSet.prototype.off = function off(event, callback) {
  1140. var subscribers = this.subscribers[event];
  1141. if (subscribers) {
  1142. this.subscribers[event] = subscribers.filter(function (listener) {
  1143. return (listener.callback != callback);
  1144. });
  1145. }
  1146. };
  1147. // TODO: make this function deprecated (replaced with `on` since version 0.5)
  1148. DataSet.prototype.unsubscribe = DataSet.prototype.off;
  1149. /**
  1150. * Trigger an event
  1151. * @param {String} event
  1152. * @param {Object | null} params
  1153. * @param {String} [senderId] Optional id of the sender.
  1154. * @private
  1155. */
  1156. DataSet.prototype._trigger = function (event, params, senderId) {
  1157. if (event == '*') {
  1158. throw new Error('Cannot trigger event *');
  1159. }
  1160. var subscribers = [];
  1161. if (event in this.subscribers) {
  1162. subscribers = subscribers.concat(this.subscribers[event]);
  1163. }
  1164. if ('*' in this.subscribers) {
  1165. subscribers = subscribers.concat(this.subscribers['*']);
  1166. }
  1167. for (var i = 0; i < subscribers.length; i++) {
  1168. var subscriber = subscribers[i];
  1169. if (subscriber.callback) {
  1170. subscriber.callback(event, params, senderId || null);
  1171. }
  1172. }
  1173. };
  1174. /**
  1175. * Add data.
  1176. * Adding an item will fail when there already is an item with the same id.
  1177. * @param {Object | Array | DataTable} data
  1178. * @param {String} [senderId] Optional sender id
  1179. * @return {Array} addedIds Array with the ids of the added items
  1180. */
  1181. DataSet.prototype.add = function (data, senderId) {
  1182. var addedIds = [],
  1183. id,
  1184. me = this;
  1185. if (data instanceof Array) {
  1186. // Array
  1187. for (var i = 0, len = data.length; i < len; i++) {
  1188. id = me._addItem(data[i]);
  1189. addedIds.push(id);
  1190. }
  1191. }
  1192. else if (util.isDataTable(data)) {
  1193. // Google DataTable
  1194. var columns = this._getColumnNames(data);
  1195. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1196. var item = {};
  1197. for (var col = 0, cols = columns.length; col < cols; col++) {
  1198. var field = columns[col];
  1199. item[field] = data.getValue(row, col);
  1200. }
  1201. id = me._addItem(item);
  1202. addedIds.push(id);
  1203. }
  1204. }
  1205. else if (data instanceof Object) {
  1206. // Single item
  1207. id = me._addItem(data);
  1208. addedIds.push(id);
  1209. }
  1210. else {
  1211. throw new Error('Unknown dataType');
  1212. }
  1213. if (addedIds.length) {
  1214. this._trigger('add', {items: addedIds}, senderId);
  1215. }
  1216. return addedIds;
  1217. };
  1218. /**
  1219. * Update existing items. When an item does not exist, it will be created
  1220. * @param {Object | Array | DataTable} data
  1221. * @param {String} [senderId] Optional sender id
  1222. * @return {Array} updatedIds The ids of the added or updated items
  1223. */
  1224. DataSet.prototype.update = function (data, senderId) {
  1225. var addedIds = [],
  1226. updatedIds = [],
  1227. me = this,
  1228. fieldId = me.fieldId;
  1229. var addOrUpdate = function (item) {
  1230. var id = item[fieldId];
  1231. if (me.data[id]) {
  1232. // update item
  1233. id = me._updateItem(item);
  1234. updatedIds.push(id);
  1235. }
  1236. else {
  1237. // add new item
  1238. id = me._addItem(item);
  1239. addedIds.push(id);
  1240. }
  1241. };
  1242. if (data instanceof Array) {
  1243. // Array
  1244. for (var i = 0, len = data.length; i < len; i++) {
  1245. addOrUpdate(data[i]);
  1246. }
  1247. }
  1248. else if (util.isDataTable(data)) {
  1249. // Google DataTable
  1250. var columns = this._getColumnNames(data);
  1251. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1252. var item = {};
  1253. for (var col = 0, cols = columns.length; col < cols; col++) {
  1254. var field = columns[col];
  1255. item[field] = data.getValue(row, col);
  1256. }
  1257. addOrUpdate(item);
  1258. }
  1259. }
  1260. else if (data instanceof Object) {
  1261. // Single item
  1262. addOrUpdate(data);
  1263. }
  1264. else {
  1265. throw new Error('Unknown dataType');
  1266. }
  1267. if (addedIds.length) {
  1268. this._trigger('add', {items: addedIds}, senderId);
  1269. }
  1270. if (updatedIds.length) {
  1271. this._trigger('update', {items: updatedIds}, senderId);
  1272. }
  1273. return addedIds.concat(updatedIds);
  1274. };
  1275. /**
  1276. * Get a data item or multiple items.
  1277. *
  1278. * Usage:
  1279. *
  1280. * get()
  1281. * get(options: Object)
  1282. * get(options: Object, data: Array | DataTable)
  1283. *
  1284. * get(id: Number | String)
  1285. * get(id: Number | String, options: Object)
  1286. * get(id: Number | String, options: Object, data: Array | DataTable)
  1287. *
  1288. * get(ids: Number[] | String[])
  1289. * get(ids: Number[] | String[], options: Object)
  1290. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1291. *
  1292. * Where:
  1293. *
  1294. * {Number | String} id The id of an item
  1295. * {Number[] | String{}} ids An array with ids of items
  1296. * {Object} options An Object with options. Available options:
  1297. * {String} [type] Type of data to be returned. Can
  1298. * be 'DataTable' or 'Array' (default)
  1299. * {Object.<String, String>} [convert]
  1300. * {String[]} [fields] field names to be returned
  1301. * {function} [filter] filter items
  1302. * {String | function} [order] Order the items by
  1303. * a field name or custom sort function.
  1304. * {Array | DataTable} [data] If provided, items will be appended to this
  1305. * array or table. Required in case of Google
  1306. * DataTable.
  1307. *
  1308. * @throws Error
  1309. */
  1310. DataSet.prototype.get = function (args) {
  1311. var me = this;
  1312. var globalShowInternalIds = this.showInternalIds;
  1313. // parse the arguments
  1314. var id, ids, options, data;
  1315. var firstType = util.getType(arguments[0]);
  1316. if (firstType == 'String' || firstType == 'Number') {
  1317. // get(id [, options] [, data])
  1318. id = arguments[0];
  1319. options = arguments[1];
  1320. data = arguments[2];
  1321. }
  1322. else if (firstType == 'Array') {
  1323. // get(ids [, options] [, data])
  1324. ids = arguments[0];
  1325. options = arguments[1];
  1326. data = arguments[2];
  1327. }
  1328. else {
  1329. // get([, options] [, data])
  1330. options = arguments[0];
  1331. data = arguments[1];
  1332. }
  1333. // determine the return type
  1334. var type;
  1335. if (options && options.type) {
  1336. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1337. if (data && (type != util.getType(data))) {
  1338. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1339. 'does not correspond with specified options.type (' + options.type + ')');
  1340. }
  1341. if (type == 'DataTable' && !util.isDataTable(data)) {
  1342. throw new Error('Parameter "data" must be a DataTable ' +
  1343. 'when options.type is "DataTable"');
  1344. }
  1345. }
  1346. else if (data) {
  1347. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1348. }
  1349. else {
  1350. type = 'Array';
  1351. }
  1352. // we allow the setting of this value for a single get request.
  1353. if (options != undefined) {
  1354. if (options.showInternalIds != undefined) {
  1355. this.showInternalIds = options.showInternalIds;
  1356. }
  1357. }
  1358. // build options
  1359. var convert = options && options.convert || this.options.convert;
  1360. var filter = options && options.filter;
  1361. var items = [], item, itemId, i, len;
  1362. // convert items
  1363. if (id != undefined) {
  1364. // return a single item
  1365. item = me._getItem(id, convert);
  1366. if (filter && !filter(item)) {
  1367. item = null;
  1368. }
  1369. }
  1370. else if (ids != undefined) {
  1371. // return a subset of items
  1372. for (i = 0, len = ids.length; i < len; i++) {
  1373. item = me._getItem(ids[i], convert);
  1374. if (!filter || filter(item)) {
  1375. items.push(item);
  1376. }
  1377. }
  1378. }
  1379. else {
  1380. // return all items
  1381. for (itemId in this.data) {
  1382. if (this.data.hasOwnProperty(itemId)) {
  1383. item = me._getItem(itemId, convert);
  1384. if (!filter || filter(item)) {
  1385. items.push(item);
  1386. }
  1387. }
  1388. }
  1389. }
  1390. // restore the global value of showInternalIds
  1391. this.showInternalIds = globalShowInternalIds;
  1392. // order the results
  1393. if (options && options.order && id == undefined) {
  1394. this._sort(items, options.order);
  1395. }
  1396. // filter fields of the items
  1397. if (options && options.fields) {
  1398. var fields = options.fields;
  1399. if (id != undefined) {
  1400. item = this._filterFields(item, fields);
  1401. }
  1402. else {
  1403. for (i = 0, len = items.length; i < len; i++) {
  1404. items[i] = this._filterFields(items[i], fields);
  1405. }
  1406. }
  1407. }
  1408. // return the results
  1409. if (type == 'DataTable') {
  1410. var columns = this._getColumnNames(data);
  1411. if (id != undefined) {
  1412. // append a single item to the data table
  1413. me._appendRow(data, columns, item);
  1414. }
  1415. else {
  1416. // copy the items to the provided data table
  1417. for (i = 0, len = items.length; i < len; i++) {
  1418. me._appendRow(data, columns, items[i]);
  1419. }
  1420. }
  1421. return data;
  1422. }
  1423. else {
  1424. // return an array
  1425. if (id != undefined) {
  1426. // a single item
  1427. return item;
  1428. }
  1429. else {
  1430. // multiple items
  1431. if (data) {
  1432. // copy the items to the provided array
  1433. for (i = 0, len = items.length; i < len; i++) {
  1434. data.push(items[i]);
  1435. }
  1436. return data;
  1437. }
  1438. else {
  1439. // just return our array
  1440. return items;
  1441. }
  1442. }
  1443. }
  1444. };
  1445. /**
  1446. * Get ids of all items or from a filtered set of items.
  1447. * @param {Object} [options] An Object with options. Available options:
  1448. * {function} [filter] filter items
  1449. * {String | function} [order] Order the items by
  1450. * a field name or custom sort function.
  1451. * @return {Array} ids
  1452. */
  1453. DataSet.prototype.getIds = function (options) {
  1454. var data = this.data,
  1455. filter = options && options.filter,
  1456. order = options && options.order,
  1457. convert = options && options.convert || this.options.convert,
  1458. i,
  1459. len,
  1460. id,
  1461. item,
  1462. items,
  1463. ids = [];
  1464. if (filter) {
  1465. // get filtered items
  1466. if (order) {
  1467. // create ordered list
  1468. items = [];
  1469. for (id in data) {
  1470. if (data.hasOwnProperty(id)) {
  1471. item = this._getItem(id, convert);
  1472. if (filter(item)) {
  1473. items.push(item);
  1474. }
  1475. }
  1476. }
  1477. this._sort(items, order);
  1478. for (i = 0, len = items.length; i < len; i++) {
  1479. ids[i] = items[i][this.fieldId];
  1480. }
  1481. }
  1482. else {
  1483. // create unordered list
  1484. for (id in data) {
  1485. if (data.hasOwnProperty(id)) {
  1486. item = this._getItem(id, convert);
  1487. if (filter(item)) {
  1488. ids.push(item[this.fieldId]);
  1489. }
  1490. }
  1491. }
  1492. }
  1493. }
  1494. else {
  1495. // get all items
  1496. if (order) {
  1497. // create an ordered list
  1498. items = [];
  1499. for (id in data) {
  1500. if (data.hasOwnProperty(id)) {
  1501. items.push(data[id]);
  1502. }
  1503. }
  1504. this._sort(items, order);
  1505. for (i = 0, len = items.length; i < len; i++) {
  1506. ids[i] = items[i][this.fieldId];
  1507. }
  1508. }
  1509. else {
  1510. // create unordered list
  1511. for (id in data) {
  1512. if (data.hasOwnProperty(id)) {
  1513. item = data[id];
  1514. ids.push(item[this.fieldId]);
  1515. }
  1516. }
  1517. }
  1518. }
  1519. return ids;
  1520. };
  1521. /**
  1522. * Execute a callback function for every item in the dataset.
  1523. * The order of the items is not determined.
  1524. * @param {function} callback
  1525. * @param {Object} [options] Available options:
  1526. * {Object.<String, String>} [convert]
  1527. * {String[]} [fields] filter fields
  1528. * {function} [filter] filter items
  1529. * {String | function} [order] Order the items by
  1530. * a field name or custom sort function.
  1531. */
  1532. DataSet.prototype.forEach = function (callback, options) {
  1533. var filter = options && options.filter,
  1534. convert = options && options.convert || this.options.convert,
  1535. data = this.data,
  1536. item,
  1537. id;
  1538. if (options && options.order) {
  1539. // execute forEach on ordered list
  1540. var items = this.get(options);
  1541. for (var i = 0, len = items.length; i < len; i++) {
  1542. item = items[i];
  1543. id = item[this.fieldId];
  1544. callback(item, id);
  1545. }
  1546. }
  1547. else {
  1548. // unordered
  1549. for (id in data) {
  1550. if (data.hasOwnProperty(id)) {
  1551. item = this._getItem(id, convert);
  1552. if (!filter || filter(item)) {
  1553. callback(item, id);
  1554. }
  1555. }
  1556. }
  1557. }
  1558. };
  1559. /**
  1560. * Map every item in the dataset.
  1561. * @param {function} callback
  1562. * @param {Object} [options] Available options:
  1563. * {Object.<String, String>} [convert]
  1564. * {String[]} [fields] filter fields
  1565. * {function} [filter] filter items
  1566. * {String | function} [order] Order the items by
  1567. * a field name or custom sort function.
  1568. * @return {Object[]} mappedItems
  1569. */
  1570. DataSet.prototype.map = function (callback, options) {
  1571. var filter = options && options.filter,
  1572. convert = options && options.convert || this.options.convert,
  1573. mappedItems = [],
  1574. data = this.data,
  1575. item;
  1576. // convert and filter items
  1577. for (var id in data) {
  1578. if (data.hasOwnProperty(id)) {
  1579. item = this._getItem(id, convert);
  1580. if (!filter || filter(item)) {
  1581. mappedItems.push(callback(item, id));
  1582. }
  1583. }
  1584. }
  1585. // order items
  1586. if (options && options.order) {
  1587. this._sort(mappedItems, options.order);
  1588. }
  1589. return mappedItems;
  1590. };
  1591. /**
  1592. * Filter the fields of an item
  1593. * @param {Object} item
  1594. * @param {String[]} fields Field names
  1595. * @return {Object} filteredItem
  1596. * @private
  1597. */
  1598. DataSet.prototype._filterFields = function (item, fields) {
  1599. var filteredItem = {};
  1600. for (var field in item) {
  1601. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1602. filteredItem[field] = item[field];
  1603. }
  1604. }
  1605. return filteredItem;
  1606. };
  1607. /**
  1608. * Sort the provided array with items
  1609. * @param {Object[]} items
  1610. * @param {String | function} order A field name or custom sort function.
  1611. * @private
  1612. */
  1613. DataSet.prototype._sort = function (items, order) {
  1614. if (util.isString(order)) {
  1615. // order by provided field name
  1616. var name = order; // field name
  1617. items.sort(function (a, b) {
  1618. var av = a[name];
  1619. var bv = b[name];
  1620. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1621. });
  1622. }
  1623. else if (typeof order === 'function') {
  1624. // order by sort function
  1625. items.sort(order);
  1626. }
  1627. // TODO: extend order by an Object {field:String, direction:String}
  1628. // where direction can be 'asc' or 'desc'
  1629. else {
  1630. throw new TypeError('Order must be a function or a string');
  1631. }
  1632. };
  1633. /**
  1634. * Remove an object by pointer or by id
  1635. * @param {String | Number | Object | Array} id Object or id, or an array with
  1636. * objects or ids to be removed
  1637. * @param {String} [senderId] Optional sender id
  1638. * @return {Array} removedIds
  1639. */
  1640. DataSet.prototype.remove = function (id, senderId) {
  1641. var removedIds = [],
  1642. i, len, removedId;
  1643. if (id instanceof Array) {
  1644. for (i = 0, len = id.length; i < len; i++) {
  1645. removedId = this._remove(id[i]);
  1646. if (removedId != null) {
  1647. removedIds.push(removedId);
  1648. }
  1649. }
  1650. }
  1651. else {
  1652. removedId = this._remove(id);
  1653. if (removedId != null) {
  1654. removedIds.push(removedId);
  1655. }
  1656. }
  1657. if (removedIds.length) {
  1658. this._trigger('remove', {items: removedIds}, senderId);
  1659. }
  1660. return removedIds;
  1661. };
  1662. /**
  1663. * Remove an item by its id
  1664. * @param {Number | String | Object} id id or item
  1665. * @returns {Number | String | null} id
  1666. * @private
  1667. */
  1668. DataSet.prototype._remove = function (id) {
  1669. if (util.isNumber(id) || util.isString(id)) {
  1670. if (this.data[id]) {
  1671. delete this.data[id];
  1672. delete this.internalIds[id];
  1673. return id;
  1674. }
  1675. }
  1676. else if (id instanceof Object) {
  1677. var itemId = id[this.fieldId];
  1678. if (itemId && this.data[itemId]) {
  1679. delete this.data[itemId];
  1680. delete this.internalIds[itemId];
  1681. return itemId;
  1682. }
  1683. }
  1684. return null;
  1685. };
  1686. /**
  1687. * Clear the data
  1688. * @param {String} [senderId] Optional sender id
  1689. * @return {Array} removedIds The ids of all removed items
  1690. */
  1691. DataSet.prototype.clear = function (senderId) {
  1692. var ids = Object.keys(this.data);
  1693. this.data = {};
  1694. this.internalIds = {};
  1695. this._trigger('remove', {items: ids}, senderId);
  1696. return ids;
  1697. };
  1698. /**
  1699. * Find the item with maximum value of a specified field
  1700. * @param {String} field
  1701. * @return {Object | null} item Item containing max value, or null if no items
  1702. */
  1703. DataSet.prototype.max = function (field) {
  1704. var data = this.data,
  1705. max = null,
  1706. maxField = null;
  1707. for (var id in data) {
  1708. if (data.hasOwnProperty(id)) {
  1709. var item = data[id];
  1710. var itemField = item[field];
  1711. if (itemField != null && (!max || itemField > maxField)) {
  1712. max = item;
  1713. maxField = itemField;
  1714. }
  1715. }
  1716. }
  1717. return max;
  1718. };
  1719. /**
  1720. * Find the item with minimum value of a specified field
  1721. * @param {String} field
  1722. * @return {Object | null} item Item containing max value, or null if no items
  1723. */
  1724. DataSet.prototype.min = function (field) {
  1725. var data = this.data,
  1726. min = null,
  1727. minField = null;
  1728. for (var id in data) {
  1729. if (data.hasOwnProperty(id)) {
  1730. var item = data[id];
  1731. var itemField = item[field];
  1732. if (itemField != null && (!min || itemField < minField)) {
  1733. min = item;
  1734. minField = itemField;
  1735. }
  1736. }
  1737. }
  1738. return min;
  1739. };
  1740. /**
  1741. * Find all distinct values of a specified field
  1742. * @param {String} field
  1743. * @return {Array} values Array containing all distinct values. If the data
  1744. * items do not contain the specified field, an array
  1745. * containing a single value undefined is returned.
  1746. * The returned array is unordered.
  1747. */
  1748. DataSet.prototype.distinct = function (field) {
  1749. var data = this.data,
  1750. values = [],
  1751. fieldType = this.options.convert[field],
  1752. count = 0;
  1753. for (var prop in data) {
  1754. if (data.hasOwnProperty(prop)) {
  1755. var item = data[prop];
  1756. var value = util.convert(item[field], fieldType);
  1757. var exists = false;
  1758. for (var i = 0; i < count; i++) {
  1759. if (values[i] == value) {
  1760. exists = true;
  1761. break;
  1762. }
  1763. }
  1764. if (!exists) {
  1765. values[count] = value;
  1766. count++;
  1767. }
  1768. }
  1769. }
  1770. return values;
  1771. };
  1772. /**
  1773. * Add a single item. Will fail when an item with the same id already exists.
  1774. * @param {Object} item
  1775. * @return {String} id
  1776. * @private
  1777. */
  1778. DataSet.prototype._addItem = function (item) {
  1779. var id = item[this.fieldId];
  1780. if (id != undefined) {
  1781. // check whether this id is already taken
  1782. if (this.data[id]) {
  1783. // item already exists
  1784. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1785. }
  1786. }
  1787. else {
  1788. // generate an id
  1789. id = util.randomUUID();
  1790. item[this.fieldId] = id;
  1791. this.internalIds[id] = item;
  1792. }
  1793. var d = {};
  1794. for (var field in item) {
  1795. if (item.hasOwnProperty(field)) {
  1796. var fieldType = this.convert[field]; // type may be undefined
  1797. d[field] = util.convert(item[field], fieldType);
  1798. }
  1799. }
  1800. this.data[id] = d;
  1801. return id;
  1802. };
  1803. /**
  1804. * Get an item. Fields can be converted to a specific type
  1805. * @param {String} id
  1806. * @param {Object.<String, String>} [convert] field types to convert
  1807. * @return {Object | null} item
  1808. * @private
  1809. */
  1810. DataSet.prototype._getItem = function (id, convert) {
  1811. var field, value;
  1812. // get the item from the dataset
  1813. var raw = this.data[id];
  1814. if (!raw) {
  1815. return null;
  1816. }
  1817. // convert the items field types
  1818. var converted = {},
  1819. fieldId = this.fieldId,
  1820. internalIds = this.internalIds;
  1821. if (convert) {
  1822. for (field in raw) {
  1823. if (raw.hasOwnProperty(field)) {
  1824. value = raw[field];
  1825. // output all fields, except internal ids
  1826. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1827. converted[field] = util.convert(value, convert[field]);
  1828. }
  1829. }
  1830. }
  1831. }
  1832. else {
  1833. // no field types specified, no converting needed
  1834. for (field in raw) {
  1835. if (raw.hasOwnProperty(field)) {
  1836. value = raw[field];
  1837. // output all fields, except internal ids
  1838. if ((field != fieldId) || (!(value in internalIds) || this.showInternalIds)) {
  1839. converted[field] = value;
  1840. }
  1841. }
  1842. }
  1843. }
  1844. return converted;
  1845. };
  1846. /**
  1847. * Update a single item: merge with existing item.
  1848. * Will fail when the item has no id, or when there does not exist an item
  1849. * with the same id.
  1850. * @param {Object} item
  1851. * @return {String} id
  1852. * @private
  1853. */
  1854. DataSet.prototype._updateItem = function (item) {
  1855. var id = item[this.fieldId];
  1856. if (id == undefined) {
  1857. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1858. }
  1859. var d = this.data[id];
  1860. if (!d) {
  1861. // item doesn't exist
  1862. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1863. }
  1864. // merge with current item
  1865. for (var field in item) {
  1866. if (item.hasOwnProperty(field)) {
  1867. var fieldType = this.convert[field]; // type may be undefined
  1868. d[field] = util.convert(item[field], fieldType);
  1869. }
  1870. }
  1871. return id;
  1872. };
  1873. /**
  1874. * check if an id is an internal or external id
  1875. * @param id
  1876. * @returns {boolean}
  1877. * @private
  1878. */
  1879. DataSet.prototype.isInternalId = function(id) {
  1880. return (id in this.internalIds);
  1881. };
  1882. /**
  1883. * Get an array with the column names of a Google DataTable
  1884. * @param {DataTable} dataTable
  1885. * @return {String[]} columnNames
  1886. * @private
  1887. */
  1888. DataSet.prototype._getColumnNames = function (dataTable) {
  1889. var columns = [];
  1890. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1891. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1892. }
  1893. return columns;
  1894. };
  1895. /**
  1896. * Append an item as a row to the dataTable
  1897. * @param dataTable
  1898. * @param columns
  1899. * @param item
  1900. * @private
  1901. */
  1902. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1903. var row = dataTable.addRow();
  1904. for (var col = 0, cols = columns.length; col < cols; col++) {
  1905. var field = columns[col];
  1906. dataTable.setValue(row, col, item[field]);
  1907. }
  1908. };
  1909. /**
  1910. * DataView
  1911. *
  1912. * a dataview offers a filtered view on a dataset or an other dataview.
  1913. *
  1914. * @param {DataSet | DataView} data
  1915. * @param {Object} [options] Available options: see method get
  1916. *
  1917. * @constructor DataView
  1918. */
  1919. function DataView (data, options) {
  1920. this.id = util.randomUUID();
  1921. this.data = null;
  1922. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1923. this.options = options || {};
  1924. this.fieldId = 'id'; // name of the field containing id
  1925. this.subscribers = {}; // event subscribers
  1926. var me = this;
  1927. this.listener = function () {
  1928. me._onEvent.apply(me, arguments);
  1929. };
  1930. this.setData(data);
  1931. }
  1932. // TODO: implement a function .config() to dynamically update things like configured filter
  1933. // and trigger changes accordingly
  1934. /**
  1935. * Set a data source for the view
  1936. * @param {DataSet | DataView} data
  1937. */
  1938. DataView.prototype.setData = function (data) {
  1939. var ids, dataItems, i, len;
  1940. if (this.data) {
  1941. // unsubscribe from current dataset
  1942. if (this.data.unsubscribe) {
  1943. this.data.unsubscribe('*', this.listener);
  1944. }
  1945. // trigger a remove of all items in memory
  1946. ids = [];
  1947. for (var id in this.ids) {
  1948. if (this.ids.hasOwnProperty(id)) {
  1949. ids.push(id);
  1950. }
  1951. }
  1952. this.ids = {};
  1953. this._trigger('remove', {items: ids});
  1954. }
  1955. this.data = data;
  1956. if (this.data) {
  1957. // update fieldId
  1958. this.fieldId = this.options.fieldId ||
  1959. (this.data && this.data.options && this.data.options.fieldId) ||
  1960. 'id';
  1961. // trigger an add of all added items
  1962. ids = this.data.getIds({filter: this.options && this.options.filter});
  1963. for (i = 0, len = ids.length; i < len; i++) {
  1964. id = ids[i];
  1965. this.ids[id] = true;
  1966. }
  1967. this._trigger('add', {items: ids});
  1968. // subscribe to new dataset
  1969. if (this.data.on) {
  1970. this.data.on('*', this.listener);
  1971. }
  1972. }
  1973. };
  1974. /**
  1975. * Get data from the data view
  1976. *
  1977. * Usage:
  1978. *
  1979. * get()
  1980. * get(options: Object)
  1981. * get(options: Object, data: Array | DataTable)
  1982. *
  1983. * get(id: Number)
  1984. * get(id: Number, options: Object)
  1985. * get(id: Number, options: Object, data: Array | DataTable)
  1986. *
  1987. * get(ids: Number[])
  1988. * get(ids: Number[], options: Object)
  1989. * get(ids: Number[], options: Object, data: Array | DataTable)
  1990. *
  1991. * Where:
  1992. *
  1993. * {Number | String} id The id of an item
  1994. * {Number[] | String{}} ids An array with ids of items
  1995. * {Object} options An Object with options. Available options:
  1996. * {String} [type] Type of data to be returned. Can
  1997. * be 'DataTable' or 'Array' (default)
  1998. * {Object.<String, String>} [convert]
  1999. * {String[]} [fields] field names to be returned
  2000. * {function} [filter] filter items
  2001. * {String | function} [order] Order the items by
  2002. * a field name or custom sort function.
  2003. * {Array | DataTable} [data] If provided, items will be appended to this
  2004. * array or table. Required in case of Google
  2005. * DataTable.
  2006. * @param args
  2007. */
  2008. DataView.prototype.get = function (args) {
  2009. var me = this;
  2010. // parse the arguments
  2011. var ids, options, data;
  2012. var firstType = util.getType(arguments[0]);
  2013. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2014. // get(id(s) [, options] [, data])
  2015. ids = arguments[0]; // can be a single id or an array with ids
  2016. options = arguments[1];
  2017. data = arguments[2];
  2018. }
  2019. else {
  2020. // get([, options] [, data])
  2021. options = arguments[0];
  2022. data = arguments[1];
  2023. }
  2024. // extend the options with the default options and provided options
  2025. var viewOptions = util.extend({}, this.options, options);
  2026. // create a combined filter method when needed
  2027. if (this.options.filter && options && options.filter) {
  2028. viewOptions.filter = function (item) {
  2029. return me.options.filter(item) && options.filter(item);
  2030. }
  2031. }
  2032. // build up the call to the linked data set
  2033. var getArguments = [];
  2034. if (ids != undefined) {
  2035. getArguments.push(ids);
  2036. }
  2037. getArguments.push(viewOptions);
  2038. getArguments.push(data);
  2039. return this.data && this.data.get.apply(this.data, getArguments);
  2040. };
  2041. /**
  2042. * Get ids of all items or from a filtered set of items.
  2043. * @param {Object} [options] An Object with options. Available options:
  2044. * {function} [filter] filter items
  2045. * {String | function} [order] Order the items by
  2046. * a field name or custom sort function.
  2047. * @return {Array} ids
  2048. */
  2049. DataView.prototype.getIds = function (options) {
  2050. var ids;
  2051. if (this.data) {
  2052. var defaultFilter = this.options.filter;
  2053. var filter;
  2054. if (options && options.filter) {
  2055. if (defaultFilter) {
  2056. filter = function (item) {
  2057. return defaultFilter(item) && options.filter(item);
  2058. }
  2059. }
  2060. else {
  2061. filter = options.filter;
  2062. }
  2063. }
  2064. else {
  2065. filter = defaultFilter;
  2066. }
  2067. ids = this.data.getIds({
  2068. filter: filter,
  2069. order: options && options.order
  2070. });
  2071. }
  2072. else {
  2073. ids = [];
  2074. }
  2075. return ids;
  2076. };
  2077. /**
  2078. * Event listener. Will propagate all events from the connected data set to
  2079. * the subscribers of the DataView, but will filter the items and only trigger
  2080. * when there are changes in the filtered data set.
  2081. * @param {String} event
  2082. * @param {Object | null} params
  2083. * @param {String} senderId
  2084. * @private
  2085. */
  2086. DataView.prototype._onEvent = function (event, params, senderId) {
  2087. var i, len, id, item,
  2088. ids = params && params.items,
  2089. data = this.data,
  2090. added = [],
  2091. updated = [],
  2092. removed = [];
  2093. if (ids && data) {
  2094. switch (event) {
  2095. case 'add':
  2096. // filter the ids of the added items
  2097. for (i = 0, len = ids.length; i < len; i++) {
  2098. id = ids[i];
  2099. item = this.get(id);
  2100. if (item) {
  2101. this.ids[id] = true;
  2102. added.push(id);
  2103. }
  2104. }
  2105. break;
  2106. case 'update':
  2107. // determine the event from the views viewpoint: an updated
  2108. // item can be added, updated, or removed from this view.
  2109. for (i = 0, len = ids.length; i < len; i++) {
  2110. id = ids[i];
  2111. item = this.get(id);
  2112. if (item) {
  2113. if (this.ids[id]) {
  2114. updated.push(id);
  2115. }
  2116. else {
  2117. this.ids[id] = true;
  2118. added.push(id);
  2119. }
  2120. }
  2121. else {
  2122. if (this.ids[id]) {
  2123. delete this.ids[id];
  2124. removed.push(id);
  2125. }
  2126. else {
  2127. // nothing interesting for me :-(
  2128. }
  2129. }
  2130. }
  2131. break;
  2132. case 'remove':
  2133. // filter the ids of the removed items
  2134. for (i = 0, len = ids.length; i < len; i++) {
  2135. id = ids[i];
  2136. if (this.ids[id]) {
  2137. delete this.ids[id];
  2138. removed.push(id);
  2139. }
  2140. }
  2141. break;
  2142. }
  2143. if (added.length) {
  2144. this._trigger('add', {items: added}, senderId);
  2145. }
  2146. if (updated.length) {
  2147. this._trigger('update', {items: updated}, senderId);
  2148. }
  2149. if (removed.length) {
  2150. this._trigger('remove', {items: removed}, senderId);
  2151. }
  2152. }
  2153. };
  2154. // copy subscription functionality from DataSet
  2155. DataView.prototype.on = DataSet.prototype.on;
  2156. DataView.prototype.off = DataSet.prototype.off;
  2157. DataView.prototype._trigger = DataSet.prototype._trigger;
  2158. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2159. DataView.prototype.subscribe = DataView.prototype.on;
  2160. DataView.prototype.unsubscribe = DataView.prototype.off;
  2161. /**
  2162. * @constructor TimeStep
  2163. * The class TimeStep is an iterator for dates. You provide a start date and an
  2164. * end date. The class itself determines the best scale (step size) based on the
  2165. * provided start Date, end Date, and minimumStep.
  2166. *
  2167. * If minimumStep is provided, the step size is chosen as close as possible
  2168. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2169. * provided, the scale is set to 1 DAY.
  2170. * The minimumStep should correspond with the onscreen size of about 6 characters
  2171. *
  2172. * Alternatively, you can set a scale by hand.
  2173. * After creation, you can initialize the class by executing first(). Then you
  2174. * can iterate from the start date to the end date via next(). You can check if
  2175. * the end date is reached with the function hasNext(). After each step, you can
  2176. * retrieve the current date via getCurrent().
  2177. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2178. * days, to years.
  2179. *
  2180. * Version: 1.2
  2181. *
  2182. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2183. * or new Date(2010, 9, 21, 23, 45, 00)
  2184. * @param {Date} [end] The end date
  2185. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2186. */
  2187. TimeStep = function(start, end, minimumStep) {
  2188. // variables
  2189. this.current = new Date();
  2190. this._start = new Date();
  2191. this._end = new Date();
  2192. this.autoScale = true;
  2193. this.scale = TimeStep.SCALE.DAY;
  2194. this.step = 1;
  2195. // initialize the range
  2196. this.setRange(start, end, minimumStep);
  2197. };
  2198. /// enum scale
  2199. TimeStep.SCALE = {
  2200. MILLISECOND: 1,
  2201. SECOND: 2,
  2202. MINUTE: 3,
  2203. HOUR: 4,
  2204. DAY: 5,
  2205. WEEKDAY: 6,
  2206. MONTH: 7,
  2207. YEAR: 8
  2208. };
  2209. /**
  2210. * Set a new range
  2211. * If minimumStep is provided, the step size is chosen as close as possible
  2212. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2213. * provided, the scale is set to 1 DAY.
  2214. * The minimumStep should correspond with the onscreen size of about 6 characters
  2215. * @param {Date} [start] The start date and time.
  2216. * @param {Date} [end] The end date and time.
  2217. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2218. */
  2219. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2220. if (!(start instanceof Date) || !(end instanceof Date)) {
  2221. throw "No legal start or end date in method setRange";
  2222. }
  2223. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2224. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2225. if (this.autoScale) {
  2226. this.setMinimumStep(minimumStep);
  2227. }
  2228. };
  2229. /**
  2230. * Set the range iterator to the start date.
  2231. */
  2232. TimeStep.prototype.first = function() {
  2233. this.current = new Date(this._start.valueOf());
  2234. this.roundToMinor();
  2235. };
  2236. /**
  2237. * Round the current date to the first minor date value
  2238. * This must be executed once when the current date is set to start Date
  2239. */
  2240. TimeStep.prototype.roundToMinor = function() {
  2241. // round to floor
  2242. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2243. //noinspection FallthroughInSwitchStatementJS
  2244. switch (this.scale) {
  2245. case TimeStep.SCALE.YEAR:
  2246. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2247. this.current.setMonth(0);
  2248. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2249. case TimeStep.SCALE.DAY: // intentional fall through
  2250. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2251. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2252. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2253. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2254. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2255. }
  2256. if (this.step != 1) {
  2257. // round down to the first minor value that is a multiple of the current step size
  2258. switch (this.scale) {
  2259. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2260. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2261. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2262. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2263. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2264. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2265. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2266. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2267. default: break;
  2268. }
  2269. }
  2270. };
  2271. /**
  2272. * Check if the there is a next step
  2273. * @return {boolean} true if the current date has not passed the end date
  2274. */
  2275. TimeStep.prototype.hasNext = function () {
  2276. return (this.current.valueOf() <= this._end.valueOf());
  2277. };
  2278. /**
  2279. * Do the next step
  2280. */
  2281. TimeStep.prototype.next = function() {
  2282. var prev = this.current.valueOf();
  2283. // Two cases, needed to prevent issues with switching daylight savings
  2284. // (end of March and end of October)
  2285. if (this.current.getMonth() < 6) {
  2286. switch (this.scale) {
  2287. case TimeStep.SCALE.MILLISECOND:
  2288. this.current = new Date(this.current.valueOf() + this.step); break;
  2289. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2290. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2291. case TimeStep.SCALE.HOUR:
  2292. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2293. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2294. var h = this.current.getHours();
  2295. this.current.setHours(h - (h % this.step));
  2296. break;
  2297. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2298. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2299. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2300. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2301. default: break;
  2302. }
  2303. }
  2304. else {
  2305. switch (this.scale) {
  2306. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2307. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2308. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2309. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2310. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2311. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2312. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2313. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2314. default: break;
  2315. }
  2316. }
  2317. if (this.step != 1) {
  2318. // round down to the correct major value
  2319. switch (this.scale) {
  2320. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2321. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2322. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2323. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2324. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2325. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2326. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2327. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2328. default: break;
  2329. }
  2330. }
  2331. // safety mechanism: if current time is still unchanged, move to the end
  2332. if (this.current.valueOf() == prev) {
  2333. this.current = new Date(this._end.valueOf());
  2334. }
  2335. };
  2336. /**
  2337. * Get the current datetime
  2338. * @return {Date} current The current date
  2339. */
  2340. TimeStep.prototype.getCurrent = function() {
  2341. return this.current;
  2342. };
  2343. /**
  2344. * Set a custom scale. Autoscaling will be disabled.
  2345. * For example setScale(SCALE.MINUTES, 5) will result
  2346. * in minor steps of 5 minutes, and major steps of an hour.
  2347. *
  2348. * @param {TimeStep.SCALE} newScale
  2349. * A scale. Choose from SCALE.MILLISECOND,
  2350. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2351. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2352. * SCALE.YEAR.
  2353. * @param {Number} newStep A step size, by default 1. Choose for
  2354. * example 1, 2, 5, or 10.
  2355. */
  2356. TimeStep.prototype.setScale = function(newScale, newStep) {
  2357. this.scale = newScale;
  2358. if (newStep > 0) {
  2359. this.step = newStep;
  2360. }
  2361. this.autoScale = false;
  2362. };
  2363. /**
  2364. * Enable or disable autoscaling
  2365. * @param {boolean} enable If true, autoascaling is set true
  2366. */
  2367. TimeStep.prototype.setAutoScale = function (enable) {
  2368. this.autoScale = enable;
  2369. };
  2370. /**
  2371. * Automatically determine the scale that bests fits the provided minimum step
  2372. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2373. */
  2374. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2375. if (minimumStep == undefined) {
  2376. return;
  2377. }
  2378. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2379. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2380. var stepDay = (1000 * 60 * 60 * 24);
  2381. var stepHour = (1000 * 60 * 60);
  2382. var stepMinute = (1000 * 60);
  2383. var stepSecond = (1000);
  2384. var stepMillisecond= (1);
  2385. // find the smallest step that is larger than the provided minimumStep
  2386. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2387. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2388. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2389. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2390. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2391. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2392. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2393. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2394. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2395. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2396. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2397. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2398. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2399. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2400. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2401. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2402. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2403. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2404. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2405. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2406. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2407. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2408. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2409. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2410. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2411. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2412. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2413. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2414. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2415. };
  2416. /**
  2417. * Snap a date to a rounded value.
  2418. * The snap intervals are dependent on the current scale and step.
  2419. * @param {Date} date the date to be snapped.
  2420. * @return {Date} snappedDate
  2421. */
  2422. TimeStep.prototype.snap = function(date) {
  2423. var clone = new Date(date.valueOf());
  2424. if (this.scale == TimeStep.SCALE.YEAR) {
  2425. var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
  2426. clone.setFullYear(Math.round(year / this.step) * this.step);
  2427. clone.setMonth(0);
  2428. clone.setDate(0);
  2429. clone.setHours(0);
  2430. clone.setMinutes(0);
  2431. clone.setSeconds(0);
  2432. clone.setMilliseconds(0);
  2433. }
  2434. else if (this.scale == TimeStep.SCALE.MONTH) {
  2435. if (clone.getDate() > 15) {
  2436. clone.setDate(1);
  2437. clone.setMonth(clone.getMonth() + 1);
  2438. // important: first set Date to 1, after that change the month.
  2439. }
  2440. else {
  2441. clone.setDate(1);
  2442. }
  2443. clone.setHours(0);
  2444. clone.setMinutes(0);
  2445. clone.setSeconds(0);
  2446. clone.setMilliseconds(0);
  2447. }
  2448. else if (this.scale == TimeStep.SCALE.DAY ||
  2449. this.scale == TimeStep.SCALE.WEEKDAY) {
  2450. //noinspection FallthroughInSwitchStatementJS
  2451. switch (this.step) {
  2452. case 5:
  2453. case 2:
  2454. clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
  2455. default:
  2456. clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
  2457. }
  2458. clone.setMinutes(0);
  2459. clone.setSeconds(0);
  2460. clone.setMilliseconds(0);
  2461. }
  2462. else if (this.scale == TimeStep.SCALE.HOUR) {
  2463. switch (this.step) {
  2464. case 4:
  2465. clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
  2466. default:
  2467. clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
  2468. }
  2469. clone.setSeconds(0);
  2470. clone.setMilliseconds(0);
  2471. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2472. //noinspection FallthroughInSwitchStatementJS
  2473. switch (this.step) {
  2474. case 15:
  2475. case 10:
  2476. clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
  2477. clone.setSeconds(0);
  2478. break;
  2479. case 5:
  2480. clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
  2481. default:
  2482. clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
  2483. }
  2484. clone.setMilliseconds(0);
  2485. }
  2486. else if (this.scale == TimeStep.SCALE.SECOND) {
  2487. //noinspection FallthroughInSwitchStatementJS
  2488. switch (this.step) {
  2489. case 15:
  2490. case 10:
  2491. clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
  2492. clone.setMilliseconds(0);
  2493. break;
  2494. case 5:
  2495. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
  2496. default:
  2497. clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
  2498. }
  2499. }
  2500. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2501. var step = this.step > 5 ? this.step / 2 : 1;
  2502. clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step);
  2503. }
  2504. return clone;
  2505. };
  2506. /**
  2507. * Check if the current value is a major value (for example when the step
  2508. * is DAY, a major value is each first day of the MONTH)
  2509. * @return {boolean} true if current date is major, else false.
  2510. */
  2511. TimeStep.prototype.isMajor = function() {
  2512. switch (this.scale) {
  2513. case TimeStep.SCALE.MILLISECOND:
  2514. return (this.current.getMilliseconds() == 0);
  2515. case TimeStep.SCALE.SECOND:
  2516. return (this.current.getSeconds() == 0);
  2517. case TimeStep.SCALE.MINUTE:
  2518. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2519. // Note: this is no bug. Major label is equal for both minute and hour scale
  2520. case TimeStep.SCALE.HOUR:
  2521. return (this.current.getHours() == 0);
  2522. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2523. case TimeStep.SCALE.DAY:
  2524. return (this.current.getDate() == 1);
  2525. case TimeStep.SCALE.MONTH:
  2526. return (this.current.getMonth() == 0);
  2527. case TimeStep.SCALE.YEAR:
  2528. return false;
  2529. default:
  2530. return false;
  2531. }
  2532. };
  2533. /**
  2534. * Returns formatted text for the minor axislabel, depending on the current
  2535. * date and the scale. For example when scale is MINUTE, the current time is
  2536. * formatted as "hh:mm".
  2537. * @param {Date} [date] custom date. if not provided, current date is taken
  2538. */
  2539. TimeStep.prototype.getLabelMinor = function(date) {
  2540. if (date == undefined) {
  2541. date = this.current;
  2542. }
  2543. switch (this.scale) {
  2544. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2545. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2546. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2547. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2548. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2549. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2550. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2551. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2552. default: return '';
  2553. }
  2554. };
  2555. /**
  2556. * Returns formatted text for the major axis label, depending on the current
  2557. * date and the scale. For example when scale is MINUTE, the major scale is
  2558. * hours, and the hour will be formatted as "hh".
  2559. * @param {Date} [date] custom date. if not provided, current date is taken
  2560. */
  2561. TimeStep.prototype.getLabelMajor = function(date) {
  2562. if (date == undefined) {
  2563. date = this.current;
  2564. }
  2565. //noinspection FallthroughInSwitchStatementJS
  2566. switch (this.scale) {
  2567. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2568. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2569. case TimeStep.SCALE.MINUTE:
  2570. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2571. case TimeStep.SCALE.WEEKDAY:
  2572. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2573. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2574. case TimeStep.SCALE.YEAR: return '';
  2575. default: return '';
  2576. }
  2577. };
  2578. /**
  2579. * @constructor Stack
  2580. * Stacks items on top of each other.
  2581. * @param {ItemSet} itemset
  2582. * @param {Object} [options]
  2583. */
  2584. function Stack (itemset, options) {
  2585. this.itemset = itemset;
  2586. this.options = options || {};
  2587. this.defaultOptions = {
  2588. order: function (a, b) {
  2589. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  2590. // Order: ranges over non-ranges, ranged ordered by width, and
  2591. // lastly ordered by start.
  2592. if (a instanceof ItemRange) {
  2593. if (b instanceof ItemRange) {
  2594. var aInt = (a.data.end - a.data.start);
  2595. var bInt = (b.data.end - b.data.start);
  2596. return (aInt - bInt) || (a.data.start - b.data.start);
  2597. }
  2598. else {
  2599. return -1;
  2600. }
  2601. }
  2602. else {
  2603. if (b instanceof ItemRange) {
  2604. return 1;
  2605. }
  2606. else {
  2607. return (a.data.start - b.data.start);
  2608. }
  2609. }
  2610. },
  2611. margin: {
  2612. item: 10
  2613. }
  2614. };
  2615. this.ordered = []; // ordered items
  2616. }
  2617. /**
  2618. * Set options for the stack
  2619. * @param {Object} options Available options:
  2620. * {ItemSet} itemset
  2621. * {Number} margin
  2622. * {function} order Stacking order
  2623. */
  2624. Stack.prototype.setOptions = function setOptions (options) {
  2625. util.extend(this.options, options);
  2626. // TODO: register on data changes at the connected itemset, and update the changed part only and immediately
  2627. };
  2628. /**
  2629. * Stack the items such that they don't overlap. The items will have a minimal
  2630. * distance equal to options.margin.item.
  2631. */
  2632. Stack.prototype.update = function update() {
  2633. this._order();
  2634. this._stack();
  2635. };
  2636. /**
  2637. * Order the items. If a custom order function has been provided via the options,
  2638. * then this will be used.
  2639. * @private
  2640. */
  2641. Stack.prototype._order = function _order () {
  2642. var items = this.itemset.items;
  2643. if (!items) {
  2644. throw new Error('Cannot stack items: ItemSet does not contain items');
  2645. }
  2646. // TODO: store the sorted items, to have less work later on
  2647. var ordered = [];
  2648. var index = 0;
  2649. // items is a map (no array)
  2650. util.forEach(items, function (item) {
  2651. if (item.visible) {
  2652. ordered[index] = item;
  2653. index++;
  2654. }
  2655. });
  2656. //if a customer stack order function exists, use it.
  2657. var order = this.options.order || this.defaultOptions.order;
  2658. if (!(typeof order === 'function')) {
  2659. throw new Error('Option order must be a function');
  2660. }
  2661. ordered.sort(order);
  2662. this.ordered = ordered;
  2663. };
  2664. /**
  2665. * Adjust vertical positions of the events such that they don't overlap each
  2666. * other.
  2667. * @private
  2668. */
  2669. Stack.prototype._stack = function _stack () {
  2670. var i,
  2671. iMax,
  2672. ordered = this.ordered,
  2673. options = this.options,
  2674. orientation = options.orientation || this.defaultOptions.orientation,
  2675. axisOnTop = (orientation == 'top'),
  2676. margin;
  2677. if (options.margin && options.margin.item !== undefined) {
  2678. margin = options.margin.item;
  2679. }
  2680. else {
  2681. margin = this.defaultOptions.margin.item
  2682. }
  2683. // calculate new, non-overlapping positions
  2684. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  2685. var item = ordered[i];
  2686. var collidingItem = null;
  2687. do {
  2688. // TODO: optimize checking for overlap. when there is a gap without items,
  2689. // you only need to check for items from the next item on, not from zero
  2690. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  2691. if (collidingItem != null) {
  2692. // There is a collision. Reposition the event above the colliding element
  2693. if (axisOnTop) {
  2694. item.top = collidingItem.top + collidingItem.height + margin;
  2695. }
  2696. else {
  2697. item.top = collidingItem.top - item.height - margin;
  2698. }
  2699. }
  2700. } while (collidingItem);
  2701. }
  2702. };
  2703. /**
  2704. * Check if the destiny position of given item overlaps with any
  2705. * of the other items from index itemStart to itemEnd.
  2706. * @param {Array} items Array with items
  2707. * @param {int} itemIndex Number of the item to be checked for overlap
  2708. * @param {int} itemStart First item to be checked.
  2709. * @param {int} itemEnd Last item to be checked.
  2710. * @return {Object | null} colliding item, or undefined when no collisions
  2711. * @param {Number} margin A minimum required margin.
  2712. * If margin is provided, the two items will be
  2713. * marked colliding when they overlap or
  2714. * when the margin between the two is smaller than
  2715. * the requested margin.
  2716. */
  2717. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  2718. itemStart, itemEnd, margin) {
  2719. var collision = this.collision;
  2720. // we loop from end to start, as we suppose that the chance of a
  2721. // collision is larger for items at the end, so check these first.
  2722. var a = items[itemIndex];
  2723. for (var i = itemEnd; i >= itemStart; i--) {
  2724. var b = items[i];
  2725. if (collision(a, b, margin)) {
  2726. if (i != itemIndex) {
  2727. return b;
  2728. }
  2729. }
  2730. }
  2731. return null;
  2732. };
  2733. /**
  2734. * Test if the two provided items collide
  2735. * The items must have parameters left, width, top, and height.
  2736. * @param {Component} a The first item
  2737. * @param {Component} b The second item
  2738. * @param {Number} margin A minimum required margin.
  2739. * If margin is provided, the two items will be
  2740. * marked colliding when they overlap or
  2741. * when the margin between the two is smaller than
  2742. * the requested margin.
  2743. * @return {boolean} true if a and b collide, else false
  2744. */
  2745. Stack.prototype.collision = function collision (a, b, margin) {
  2746. return ((a.left - margin) < (b.left + b.width) &&
  2747. (a.left + a.width + margin) > b.left &&
  2748. (a.top - margin) < (b.top + b.height) &&
  2749. (a.top + a.height + margin) > b.top);
  2750. };
  2751. /**
  2752. * @constructor Range
  2753. * A Range controls a numeric range with a start and end value.
  2754. * The Range adjusts the range based on mouse events or programmatic changes,
  2755. * and triggers events when the range is changing or has been changed.
  2756. * @param {Object} [options] See description at Range.setOptions
  2757. * @extends Controller
  2758. */
  2759. function Range(options) {
  2760. this.id = util.randomUUID();
  2761. this.start = null; // Number
  2762. this.end = null; // Number
  2763. this.options = options || {};
  2764. this.setOptions(options);
  2765. }
  2766. // extend the Range prototype with an event emitter mixin
  2767. Emitter(Range.prototype);
  2768. /**
  2769. * Set options for the range controller
  2770. * @param {Object} options Available options:
  2771. * {Number} min Minimum value for start
  2772. * {Number} max Maximum value for end
  2773. * {Number} zoomMin Set a minimum value for
  2774. * (end - start).
  2775. * {Number} zoomMax Set a maximum value for
  2776. * (end - start).
  2777. */
  2778. Range.prototype.setOptions = function (options) {
  2779. util.extend(this.options, options);
  2780. // re-apply range with new limitations
  2781. if (this.start !== null && this.end !== null) {
  2782. this.setRange(this.start, this.end);
  2783. }
  2784. };
  2785. /**
  2786. * Test whether direction has a valid value
  2787. * @param {String} direction 'horizontal' or 'vertical'
  2788. */
  2789. function validateDirection (direction) {
  2790. if (direction != 'horizontal' && direction != 'vertical') {
  2791. throw new TypeError('Unknown direction "' + direction + '". ' +
  2792. 'Choose "horizontal" or "vertical".');
  2793. }
  2794. }
  2795. /**
  2796. * Add listeners for mouse and touch events to the component
  2797. * @param {Controller} controller
  2798. * @param {Component} component Should be a rootpanel
  2799. * @param {String} event Available events: 'move', 'zoom'
  2800. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2801. */
  2802. Range.prototype.subscribe = function (controller, component, event, direction) {
  2803. var me = this;
  2804. if (event == 'move') {
  2805. // drag start listener
  2806. controller.on('dragstart', function (event) {
  2807. me._onDragStart(event, component);
  2808. });
  2809. // drag listener
  2810. controller.on('drag', function (event) {
  2811. me._onDrag(event, component, direction);
  2812. });
  2813. // drag end listener
  2814. controller.on('dragend', function (event) {
  2815. me._onDragEnd(event, component);
  2816. });
  2817. // ignore dragging when holding
  2818. controller.on('hold', function (event) {
  2819. me._onHold();
  2820. });
  2821. }
  2822. else if (event == 'zoom') {
  2823. // mouse wheel
  2824. function mousewheel (event) {
  2825. me._onMouseWheel(event, component, direction);
  2826. }
  2827. controller.on('mousewheel', mousewheel);
  2828. controller.on('DOMMouseScroll', mousewheel); // For FF
  2829. // pinch
  2830. controller.on('touch', function (event) {
  2831. me._onTouch(event);
  2832. });
  2833. controller.on('pinch', function (event) {
  2834. me._onPinch(event, component, direction);
  2835. });
  2836. }
  2837. else {
  2838. throw new TypeError('Unknown event "' + event + '". ' +
  2839. 'Choose "move" or "zoom".');
  2840. }
  2841. };
  2842. /**
  2843. * Set a new start and end range
  2844. * @param {Number} [start]
  2845. * @param {Number} [end]
  2846. */
  2847. Range.prototype.setRange = function(start, end) {
  2848. var changed = this._applyRange(start, end);
  2849. if (changed) {
  2850. var params = {
  2851. start: this.start,
  2852. end: this.end
  2853. };
  2854. this.emit('rangechange', params);
  2855. this.emit('rangechanged', params);
  2856. }
  2857. };
  2858. /**
  2859. * Set a new start and end range. This method is the same as setRange, but
  2860. * does not trigger a range change and range changed event, and it returns
  2861. * true when the range is changed
  2862. * @param {Number} [start]
  2863. * @param {Number} [end]
  2864. * @return {Boolean} changed
  2865. * @private
  2866. */
  2867. Range.prototype._applyRange = function(start, end) {
  2868. var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
  2869. newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
  2870. max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
  2871. min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
  2872. diff;
  2873. // check for valid number
  2874. if (isNaN(newStart) || newStart === null) {
  2875. throw new Error('Invalid start "' + start + '"');
  2876. }
  2877. if (isNaN(newEnd) || newEnd === null) {
  2878. throw new Error('Invalid end "' + end + '"');
  2879. }
  2880. // prevent start < end
  2881. if (newEnd < newStart) {
  2882. newEnd = newStart;
  2883. }
  2884. // prevent start < min
  2885. if (min !== null) {
  2886. if (newStart < min) {
  2887. diff = (min - newStart);
  2888. newStart += diff;
  2889. newEnd += diff;
  2890. // prevent end > max
  2891. if (max != null) {
  2892. if (newEnd > max) {
  2893. newEnd = max;
  2894. }
  2895. }
  2896. }
  2897. }
  2898. // prevent end > max
  2899. if (max !== null) {
  2900. if (newEnd > max) {
  2901. diff = (newEnd - max);
  2902. newStart -= diff;
  2903. newEnd -= diff;
  2904. // prevent start < min
  2905. if (min != null) {
  2906. if (newStart < min) {
  2907. newStart = min;
  2908. }
  2909. }
  2910. }
  2911. }
  2912. // prevent (end-start) < zoomMin
  2913. if (this.options.zoomMin !== null) {
  2914. var zoomMin = parseFloat(this.options.zoomMin);
  2915. if (zoomMin < 0) {
  2916. zoomMin = 0;
  2917. }
  2918. if ((newEnd - newStart) < zoomMin) {
  2919. if ((this.end - this.start) === zoomMin) {
  2920. // ignore this action, we are already zoomed to the minimum
  2921. newStart = this.start;
  2922. newEnd = this.end;
  2923. }
  2924. else {
  2925. // zoom to the minimum
  2926. diff = (zoomMin - (newEnd - newStart));
  2927. newStart -= diff / 2;
  2928. newEnd += diff / 2;
  2929. }
  2930. }
  2931. }
  2932. // prevent (end-start) > zoomMax
  2933. if (this.options.zoomMax !== null) {
  2934. var zoomMax = parseFloat(this.options.zoomMax);
  2935. if (zoomMax < 0) {
  2936. zoomMax = 0;
  2937. }
  2938. if ((newEnd - newStart) > zoomMax) {
  2939. if ((this.end - this.start) === zoomMax) {
  2940. // ignore this action, we are already zoomed to the maximum
  2941. newStart = this.start;
  2942. newEnd = this.end;
  2943. }
  2944. else {
  2945. // zoom to the maximum
  2946. diff = ((newEnd - newStart) - zoomMax);
  2947. newStart += diff / 2;
  2948. newEnd -= diff / 2;
  2949. }
  2950. }
  2951. }
  2952. var changed = (this.start != newStart || this.end != newEnd);
  2953. this.start = newStart;
  2954. this.end = newEnd;
  2955. return changed;
  2956. };
  2957. /**
  2958. * Retrieve the current range.
  2959. * @return {Object} An object with start and end properties
  2960. */
  2961. Range.prototype.getRange = function() {
  2962. return {
  2963. start: this.start,
  2964. end: this.end
  2965. };
  2966. };
  2967. /**
  2968. * Calculate the conversion offset and scale for current range, based on
  2969. * the provided width
  2970. * @param {Number} width
  2971. * @returns {{offset: number, scale: number}} conversion
  2972. */
  2973. Range.prototype.conversion = function (width) {
  2974. return Range.conversion(this.start, this.end, width);
  2975. };
  2976. /**
  2977. * Static method to calculate the conversion offset and scale for a range,
  2978. * based on the provided start, end, and width
  2979. * @param {Number} start
  2980. * @param {Number} end
  2981. * @param {Number} width
  2982. * @returns {{offset: number, scale: number}} conversion
  2983. */
  2984. Range.conversion = function (start, end, width) {
  2985. if (width != 0 && (end - start != 0)) {
  2986. return {
  2987. offset: start,
  2988. scale: width / (end - start)
  2989. }
  2990. }
  2991. else {
  2992. return {
  2993. offset: 0,
  2994. scale: 1
  2995. };
  2996. }
  2997. };
  2998. // global (private) object to store drag params
  2999. var touchParams = {};
  3000. /**
  3001. * Start dragging horizontally or vertically
  3002. * @param {Event} event
  3003. * @param {Object} component
  3004. * @private
  3005. */
  3006. Range.prototype._onDragStart = function(event, component) {
  3007. // refuse to drag when we where pinching to prevent the timeline make a jump
  3008. // when releasing the fingers in opposite order from the touch screen
  3009. if (touchParams.ignore) return;
  3010. // TODO: reckon with option movable
  3011. touchParams.start = this.start;
  3012. touchParams.end = this.end;
  3013. var frame = component.frame;
  3014. if (frame) {
  3015. frame.style.cursor = 'move';
  3016. }
  3017. };
  3018. /**
  3019. * Perform dragging operating.
  3020. * @param {Event} event
  3021. * @param {Component} component
  3022. * @param {String} direction 'horizontal' or 'vertical'
  3023. * @private
  3024. */
  3025. Range.prototype._onDrag = function (event, component, direction) {
  3026. validateDirection(direction);
  3027. // TODO: reckon with option movable
  3028. // refuse to drag when we where pinching to prevent the timeline make a jump
  3029. // when releasing the fingers in opposite order from the touch screen
  3030. if (touchParams.ignore) return;
  3031. var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY,
  3032. interval = (touchParams.end - touchParams.start),
  3033. width = (direction == 'horizontal') ? component.width : component.height,
  3034. diffRange = -delta / width * interval;
  3035. this._applyRange(touchParams.start + diffRange, touchParams.end + diffRange);
  3036. this.emit('rangechange', {
  3037. start: this.start,
  3038. end: this.end
  3039. });
  3040. };
  3041. /**
  3042. * Stop dragging operating.
  3043. * @param {event} event
  3044. * @param {Component} component
  3045. * @private
  3046. */
  3047. Range.prototype._onDragEnd = function (event, component) {
  3048. // refuse to drag when we where pinching to prevent the timeline make a jump
  3049. // when releasing the fingers in opposite order from the touch screen
  3050. if (touchParams.ignore) return;
  3051. // TODO: reckon with option movable
  3052. if (component.frame) {
  3053. component.frame.style.cursor = 'auto';
  3054. }
  3055. // fire a rangechanged event
  3056. this.emit('rangechanged', {
  3057. start: this.start,
  3058. end: this.end
  3059. });
  3060. };
  3061. /**
  3062. * Event handler for mouse wheel event, used to zoom
  3063. * Code from http://adomas.org/javascript-mouse-wheel/
  3064. * @param {Event} event
  3065. * @param {Component} component
  3066. * @param {String} direction 'horizontal' or 'vertical'
  3067. * @private
  3068. */
  3069. Range.prototype._onMouseWheel = function(event, component, direction) {
  3070. validateDirection(direction);
  3071. // TODO: reckon with option zoomable
  3072. // retrieve delta
  3073. var delta = 0;
  3074. if (event.wheelDelta) { /* IE/Opera. */
  3075. delta = event.wheelDelta / 120;
  3076. } else if (event.detail) { /* Mozilla case. */
  3077. // In Mozilla, sign of delta is different than in IE.
  3078. // Also, delta is multiple of 3.
  3079. delta = -event.detail / 3;
  3080. }
  3081. // If delta is nonzero, handle it.
  3082. // Basically, delta is now positive if wheel was scrolled up,
  3083. // and negative, if wheel was scrolled down.
  3084. if (delta) {
  3085. // perform the zoom action. Delta is normally 1 or -1
  3086. // adjust a negative delta such that zooming in with delta 0.1
  3087. // equals zooming out with a delta -0.1
  3088. var scale;
  3089. if (delta < 0) {
  3090. scale = 1 - (delta / 5);
  3091. }
  3092. else {
  3093. scale = 1 / (1 + (delta / 5)) ;
  3094. }
  3095. // calculate center, the date to zoom around
  3096. var gesture = util.fakeGesture(this, event),
  3097. pointer = getPointer(gesture.center, component.frame),
  3098. pointerDate = this._pointerToDate(component, direction, pointer);
  3099. this.zoom(scale, pointerDate);
  3100. }
  3101. // Prevent default actions caused by mouse wheel
  3102. // (else the page and timeline both zoom and scroll)
  3103. event.preventDefault();
  3104. };
  3105. /**
  3106. * Start of a touch gesture
  3107. * @private
  3108. */
  3109. Range.prototype._onTouch = function (event) {
  3110. touchParams.start = this.start;
  3111. touchParams.end = this.end;
  3112. touchParams.ignore = false;
  3113. touchParams.center = null;
  3114. // don't move the range when dragging a selected event
  3115. // TODO: it's not so neat to have to know about the state of the ItemSet
  3116. var item = ItemSet.itemFromTarget(event);
  3117. if (item && item.selected && this.options.editable) {
  3118. touchParams.ignore = true;
  3119. }
  3120. };
  3121. /**
  3122. * On start of a hold gesture
  3123. * @private
  3124. */
  3125. Range.prototype._onHold = function () {
  3126. touchParams.ignore = true;
  3127. };
  3128. /**
  3129. * Handle pinch event
  3130. * @param {Event} event
  3131. * @param {Component} component
  3132. * @param {String} direction 'horizontal' or 'vertical'
  3133. * @private
  3134. */
  3135. Range.prototype._onPinch = function (event, component, direction) {
  3136. touchParams.ignore = true;
  3137. // TODO: reckon with option zoomable
  3138. if (event.gesture.touches.length > 1) {
  3139. if (!touchParams.center) {
  3140. touchParams.center = getPointer(event.gesture.center, component.frame);
  3141. }
  3142. var scale = 1 / event.gesture.scale,
  3143. initDate = this._pointerToDate(component, direction, touchParams.center),
  3144. center = getPointer(event.gesture.center, component.frame),
  3145. date = this._pointerToDate(component, direction, center),
  3146. delta = date - initDate; // TODO: utilize delta
  3147. // calculate new start and end
  3148. var newStart = parseInt(initDate + (touchParams.start - initDate) * scale);
  3149. var newEnd = parseInt(initDate + (touchParams.end - initDate) * scale);
  3150. // apply new range
  3151. this.setRange(newStart, newEnd);
  3152. }
  3153. };
  3154. /**
  3155. * Helper function to calculate the center date for zooming
  3156. * @param {Component} component
  3157. * @param {{x: Number, y: Number}} pointer
  3158. * @param {String} direction 'horizontal' or 'vertical'
  3159. * @return {number} date
  3160. * @private
  3161. */
  3162. Range.prototype._pointerToDate = function (component, direction, pointer) {
  3163. var conversion;
  3164. if (direction == 'horizontal') {
  3165. var width = component.width;
  3166. conversion = this.conversion(width);
  3167. return pointer.x / conversion.scale + conversion.offset;
  3168. }
  3169. else {
  3170. var height = component.height;
  3171. conversion = this.conversion(height);
  3172. return pointer.y / conversion.scale + conversion.offset;
  3173. }
  3174. };
  3175. /**
  3176. * Get the pointer location relative to the location of the dom element
  3177. * @param {{pageX: Number, pageY: Number}} touch
  3178. * @param {Element} element HTML DOM element
  3179. * @return {{x: Number, y: Number}} pointer
  3180. * @private
  3181. */
  3182. function getPointer (touch, element) {
  3183. return {
  3184. x: touch.pageX - vis.util.getAbsoluteLeft(element),
  3185. y: touch.pageY - vis.util.getAbsoluteTop(element)
  3186. };
  3187. }
  3188. /**
  3189. * Zoom the range the given scale in or out. Start and end date will
  3190. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3191. * date around which to zoom.
  3192. * For example, try scale = 0.9 or 1.1
  3193. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  3194. * values below 1 will zoom in.
  3195. * @param {Number} [center] Value representing a date around which will
  3196. * be zoomed.
  3197. */
  3198. Range.prototype.zoom = function(scale, center) {
  3199. // if centerDate is not provided, take it half between start Date and end Date
  3200. if (center == null) {
  3201. center = (this.start + this.end) / 2;
  3202. }
  3203. // calculate new start and end
  3204. var newStart = center + (this.start - center) * scale;
  3205. var newEnd = center + (this.end - center) * scale;
  3206. this.setRange(newStart, newEnd);
  3207. };
  3208. /**
  3209. * Move the range with a given delta to the left or right. Start and end
  3210. * value will be adjusted. For example, try delta = 0.1 or -0.1
  3211. * @param {Number} delta Moving amount. Positive value will move right,
  3212. * negative value will move left
  3213. */
  3214. Range.prototype.move = function(delta) {
  3215. // zoom start Date and end Date relative to the centerDate
  3216. var diff = (this.end - this.start);
  3217. // apply new values
  3218. var newStart = this.start + diff * delta;
  3219. var newEnd = this.end + diff * delta;
  3220. // TODO: reckon with min and max range
  3221. this.start = newStart;
  3222. this.end = newEnd;
  3223. };
  3224. /**
  3225. * Move the range to a new center point
  3226. * @param {Number} moveTo New center point of the range
  3227. */
  3228. Range.prototype.moveTo = function(moveTo) {
  3229. var center = (this.start + this.end) / 2;
  3230. var diff = center - moveTo;
  3231. // calculate new start and end
  3232. var newStart = this.start - diff;
  3233. var newEnd = this.end - diff;
  3234. this.setRange(newStart, newEnd);
  3235. };
  3236. /**
  3237. * @constructor Controller
  3238. *
  3239. * A Controller controls the reflows and repaints of all components,
  3240. * and is used as an event bus for all components.
  3241. */
  3242. function Controller () {
  3243. var me = this;
  3244. this.id = util.randomUUID();
  3245. this.components = {};
  3246. /**
  3247. * Listen for a 'request-reflow' event. The controller will schedule a reflow
  3248. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3249. * is false.
  3250. */
  3251. var reflowTimer = null;
  3252. this.on('request-reflow', function requestReflow(force) {
  3253. if (force) {
  3254. me.reflow();
  3255. }
  3256. else {
  3257. if (!reflowTimer) {
  3258. reflowTimer = setTimeout(function () {
  3259. reflowTimer = null;
  3260. me.reflow();
  3261. }, 0);
  3262. }
  3263. }
  3264. });
  3265. /**
  3266. * Request a repaint. The controller will schedule a repaint
  3267. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3268. * is false.
  3269. */
  3270. var repaintTimer = null;
  3271. this.on('request-repaint', function requestRepaint(force) {
  3272. if (force) {
  3273. me.repaint();
  3274. }
  3275. else {
  3276. if (!repaintTimer) {
  3277. repaintTimer = setTimeout(function () {
  3278. repaintTimer = null;
  3279. me.repaint();
  3280. }, 0);
  3281. }
  3282. }
  3283. });
  3284. }
  3285. // Extend controller with Emitter mixin
  3286. Emitter(Controller.prototype);
  3287. /**
  3288. * Add a component to the controller
  3289. * @param {Component} component
  3290. */
  3291. Controller.prototype.add = function add(component) {
  3292. // validate the component
  3293. if (component.id == undefined) {
  3294. throw new Error('Component has no field id');
  3295. }
  3296. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3297. throw new TypeError('Component must be an instance of ' +
  3298. 'prototype Component or Controller');
  3299. }
  3300. // add the component
  3301. component.setController(this);
  3302. this.components[component.id] = component;
  3303. };
  3304. /**
  3305. * Remove a component from the controller
  3306. * @param {Component | String} component
  3307. */
  3308. Controller.prototype.remove = function remove(component) {
  3309. var id;
  3310. for (id in this.components) {
  3311. if (this.components.hasOwnProperty(id)) {
  3312. if (id == component || this.components[id] === component) {
  3313. break;
  3314. }
  3315. }
  3316. }
  3317. if (id) {
  3318. // unregister the controller (gives the component the ability to unregister
  3319. // event listeners and clean up other stuff)
  3320. this.components[id].setController(null);
  3321. delete this.components[id];
  3322. }
  3323. };
  3324. /**
  3325. * Repaint all components
  3326. */
  3327. Controller.prototype.repaint = function repaint() {
  3328. var changed = false;
  3329. // cancel any running repaint request
  3330. if (this.repaintTimer) {
  3331. clearTimeout(this.repaintTimer);
  3332. this.repaintTimer = undefined;
  3333. }
  3334. var done = {};
  3335. function repaint(component, id) {
  3336. if (!(id in done)) {
  3337. // first repaint the components on which this component is dependent
  3338. if (component.depends) {
  3339. component.depends.forEach(function (dep) {
  3340. repaint(dep, dep.id);
  3341. });
  3342. }
  3343. if (component.parent) {
  3344. repaint(component.parent, component.parent.id);
  3345. }
  3346. // repaint the component itself and mark as done
  3347. changed = component.repaint() || changed;
  3348. done[id] = true;
  3349. }
  3350. }
  3351. util.forEach(this.components, repaint);
  3352. this.emit('repaint');
  3353. // immediately reflow when needed
  3354. if (changed) {
  3355. this.reflow();
  3356. }
  3357. // TODO: limit the number of nested reflows/repaints, prevent loop
  3358. };
  3359. /**
  3360. * Reflow all components
  3361. */
  3362. Controller.prototype.reflow = function reflow() {
  3363. var resized = false;
  3364. // cancel any running repaint request
  3365. if (this.reflowTimer) {
  3366. clearTimeout(this.reflowTimer);
  3367. this.reflowTimer = undefined;
  3368. }
  3369. var done = {};
  3370. function reflow(component, id) {
  3371. if (!(id in done)) {
  3372. // first reflow the components on which this component is dependent
  3373. if (component.depends) {
  3374. component.depends.forEach(function (dep) {
  3375. reflow(dep, dep.id);
  3376. });
  3377. }
  3378. if (component.parent) {
  3379. reflow(component.parent, component.parent.id);
  3380. }
  3381. // reflow the component itself and mark as done
  3382. resized = component.reflow() || resized;
  3383. done[id] = true;
  3384. }
  3385. }
  3386. util.forEach(this.components, reflow);
  3387. this.emit('reflow');
  3388. // immediately repaint when needed
  3389. if (resized) {
  3390. this.repaint();
  3391. }
  3392. // TODO: limit the number of nested reflows/repaints, prevent loop
  3393. };
  3394. /**
  3395. * Prototype for visual components
  3396. */
  3397. function Component () {
  3398. this.id = null;
  3399. this.parent = null;
  3400. this.depends = null;
  3401. this.controller = null;
  3402. this.options = null;
  3403. this.frame = null; // main DOM element
  3404. this.top = 0;
  3405. this.left = 0;
  3406. this.width = 0;
  3407. this.height = 0;
  3408. }
  3409. /**
  3410. * Set parameters for the frame. Parameters will be merged in current parameter
  3411. * set.
  3412. * @param {Object} options Available parameters:
  3413. * {String | function} [className]
  3414. * {String | Number | function} [left]
  3415. * {String | Number | function} [top]
  3416. * {String | Number | function} [width]
  3417. * {String | Number | function} [height]
  3418. */
  3419. Component.prototype.setOptions = function setOptions(options) {
  3420. if (options) {
  3421. util.extend(this.options, options);
  3422. if (this.controller) {
  3423. this.requestRepaint();
  3424. this.requestReflow();
  3425. }
  3426. }
  3427. };
  3428. /**
  3429. * Get an option value by name
  3430. * The function will first check this.options object, and else will check
  3431. * this.defaultOptions.
  3432. * @param {String} name
  3433. * @return {*} value
  3434. */
  3435. Component.prototype.getOption = function getOption(name) {
  3436. var value;
  3437. if (this.options) {
  3438. value = this.options[name];
  3439. }
  3440. if (value === undefined && this.defaultOptions) {
  3441. value = this.defaultOptions[name];
  3442. }
  3443. return value;
  3444. };
  3445. /**
  3446. * Set controller for this component, or remove current controller by passing
  3447. * null as parameter value.
  3448. * @param {Controller | null} controller
  3449. */
  3450. Component.prototype.setController = function setController (controller) {
  3451. this.controller = controller || null;
  3452. };
  3453. /**
  3454. * Get controller of this component
  3455. * @return {Controller} controller
  3456. */
  3457. Component.prototype.getController = function getController () {
  3458. return this.controller;
  3459. };
  3460. /**
  3461. * Get the container element of the component, which can be used by a child to
  3462. * add its own widgets. Not all components do have a container for childs, in
  3463. * that case null is returned.
  3464. * @returns {HTMLElement | null} container
  3465. */
  3466. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3467. Component.prototype.getContainer = function getContainer() {
  3468. // should be implemented by the component
  3469. return null;
  3470. };
  3471. /**
  3472. * Get the frame element of the component, the outer HTML DOM element.
  3473. * @returns {HTMLElement | null} frame
  3474. */
  3475. Component.prototype.getFrame = function getFrame() {
  3476. return this.frame;
  3477. };
  3478. /**
  3479. * Repaint the component
  3480. * @return {Boolean} changed
  3481. */
  3482. Component.prototype.repaint = function repaint() {
  3483. // should be implemented by the component
  3484. return false;
  3485. };
  3486. /**
  3487. * Reflow the component
  3488. * @return {Boolean} resized
  3489. */
  3490. Component.prototype.reflow = function reflow() {
  3491. // should be implemented by the component
  3492. return false;
  3493. };
  3494. /**
  3495. * Hide the component from the DOM
  3496. * @return {Boolean} changed
  3497. */
  3498. Component.prototype.hide = function hide() {
  3499. if (this.frame && this.frame.parentNode) {
  3500. this.frame.parentNode.removeChild(this.frame);
  3501. return true;
  3502. }
  3503. else {
  3504. return false;
  3505. }
  3506. };
  3507. /**
  3508. * Show the component in the DOM (when not already visible).
  3509. * A repaint will be executed when the component is not visible
  3510. * @return {Boolean} changed
  3511. */
  3512. Component.prototype.show = function show() {
  3513. if (!this.frame || !this.frame.parentNode) {
  3514. return this.repaint();
  3515. }
  3516. else {
  3517. return false;
  3518. }
  3519. };
  3520. /**
  3521. * Request a repaint. The controller will schedule a repaint
  3522. */
  3523. Component.prototype.requestRepaint = function requestRepaint() {
  3524. if (this.controller) {
  3525. this.controller.emit('request-repaint');
  3526. }
  3527. else {
  3528. throw new Error('Cannot request a repaint: no controller configured');
  3529. // TODO: just do a repaint when no parent is configured?
  3530. }
  3531. };
  3532. /**
  3533. * Request a reflow. The controller will schedule a reflow
  3534. */
  3535. Component.prototype.requestReflow = function requestReflow() {
  3536. if (this.controller) {
  3537. this.controller.emit('request-reflow');
  3538. }
  3539. else {
  3540. throw new Error('Cannot request a reflow: no controller configured');
  3541. // TODO: just do a reflow when no parent is configured?
  3542. }
  3543. };
  3544. /**
  3545. * A panel can contain components
  3546. * @param {Component} [parent]
  3547. * @param {Component[]} [depends] Components on which this components depends
  3548. * (except for the parent)
  3549. * @param {Object} [options] Available parameters:
  3550. * {String | Number | function} [left]
  3551. * {String | Number | function} [top]
  3552. * {String | Number | function} [width]
  3553. * {String | Number | function} [height]
  3554. * {String | function} [className]
  3555. * @constructor Panel
  3556. * @extends Component
  3557. */
  3558. function Panel(parent, depends, options) {
  3559. this.id = util.randomUUID();
  3560. this.parent = parent;
  3561. this.depends = depends;
  3562. this.options = options || {};
  3563. }
  3564. Panel.prototype = new Component();
  3565. /**
  3566. * Set options. Will extend the current options.
  3567. * @param {Object} [options] Available parameters:
  3568. * {String | function} [className]
  3569. * {String | Number | function} [left]
  3570. * {String | Number | function} [top]
  3571. * {String | Number | function} [width]
  3572. * {String | Number | function} [height]
  3573. */
  3574. Panel.prototype.setOptions = Component.prototype.setOptions;
  3575. /**
  3576. * Get the container element of the panel, which can be used by a child to
  3577. * add its own widgets.
  3578. * @returns {HTMLElement} container
  3579. */
  3580. Panel.prototype.getContainer = function () {
  3581. return this.frame;
  3582. };
  3583. /**
  3584. * Repaint the component
  3585. * @return {Boolean} changed
  3586. */
  3587. Panel.prototype.repaint = function () {
  3588. var changed = 0,
  3589. update = util.updateProperty,
  3590. asSize = util.option.asSize,
  3591. options = this.options,
  3592. frame = this.frame;
  3593. if (!frame) {
  3594. frame = document.createElement('div');
  3595. frame.className = 'vpanel';
  3596. var className = options.className;
  3597. if (className) {
  3598. if (typeof className == 'function') {
  3599. util.addClassName(frame, String(className()));
  3600. }
  3601. else {
  3602. util.addClassName(frame, String(className));
  3603. }
  3604. }
  3605. this.frame = frame;
  3606. changed += 1;
  3607. }
  3608. if (!frame.parentNode) {
  3609. if (!this.parent) {
  3610. throw new Error('Cannot repaint panel: no parent attached');
  3611. }
  3612. var parentContainer = this.parent.getContainer();
  3613. if (!parentContainer) {
  3614. throw new Error('Cannot repaint panel: parent has no container element');
  3615. }
  3616. parentContainer.appendChild(frame);
  3617. changed += 1;
  3618. }
  3619. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3620. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3621. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3622. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3623. return (changed > 0);
  3624. };
  3625. /**
  3626. * Reflow the component
  3627. * @return {Boolean} resized
  3628. */
  3629. Panel.prototype.reflow = function () {
  3630. var changed = 0,
  3631. update = util.updateProperty,
  3632. frame = this.frame;
  3633. if (frame) {
  3634. changed += update(this, 'top', frame.offsetTop);
  3635. changed += update(this, 'left', frame.offsetLeft);
  3636. changed += update(this, 'width', frame.offsetWidth);
  3637. changed += update(this, 'height', frame.offsetHeight);
  3638. }
  3639. else {
  3640. changed += 1;
  3641. }
  3642. return (changed > 0);
  3643. };
  3644. /**
  3645. * A root panel can hold components. The root panel must be initialized with
  3646. * a DOM element as container.
  3647. * @param {HTMLElement} container
  3648. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3649. * @constructor RootPanel
  3650. * @extends Panel
  3651. */
  3652. function RootPanel(container, options) {
  3653. this.id = util.randomUUID();
  3654. this.container = container;
  3655. // create functions to be used as DOM event listeners
  3656. var me = this;
  3657. this.hammer = null;
  3658. // create listeners for all interesting events, these events will be emitted
  3659. // via the controller
  3660. var events = [
  3661. 'touch', 'pinch', 'tap', 'doubletap', 'hold',
  3662. 'dragstart', 'drag', 'dragend',
  3663. 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is for Firefox
  3664. ];
  3665. this.listeners = {};
  3666. events.forEach(function (event) {
  3667. me.listeners[event] = function () {
  3668. var args = [event].concat(Array.prototype.slice.call(arguments, 0));
  3669. me.controller.emit.apply(me.controller, args);
  3670. };
  3671. });
  3672. this.options = options || {};
  3673. this.defaultOptions = {
  3674. autoResize: true
  3675. };
  3676. }
  3677. RootPanel.prototype = new Panel();
  3678. /**
  3679. * Set options. Will extend the current options.
  3680. * @param {Object} [options] Available parameters:
  3681. * {String | function} [className]
  3682. * {String | Number | function} [left]
  3683. * {String | Number | function} [top]
  3684. * {String | Number | function} [width]
  3685. * {String | Number | function} [height]
  3686. * {Boolean | function} [autoResize]
  3687. */
  3688. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3689. /**
  3690. * Repaint the component
  3691. * @return {Boolean} changed
  3692. */
  3693. RootPanel.prototype.repaint = function () {
  3694. var changed = 0,
  3695. update = util.updateProperty,
  3696. asSize = util.option.asSize,
  3697. options = this.options,
  3698. frame = this.frame;
  3699. if (!frame) {
  3700. frame = document.createElement('div');
  3701. this.frame = frame;
  3702. this._registerListeners();
  3703. changed += 1;
  3704. }
  3705. if (!frame.parentNode) {
  3706. if (!this.container) {
  3707. throw new Error('Cannot repaint root panel: no container attached');
  3708. }
  3709. this.container.appendChild(frame);
  3710. changed += 1;
  3711. }
  3712. frame.className = 'vis timeline rootpanel ' + options.orientation +
  3713. (options.editable ? ' editable' : '');
  3714. var className = options.className;
  3715. if (className) {
  3716. util.addClassName(frame, util.option.asString(className));
  3717. }
  3718. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3719. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3720. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3721. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3722. this._updateWatch();
  3723. return (changed > 0);
  3724. };
  3725. /**
  3726. * Reflow the component
  3727. * @return {Boolean} resized
  3728. */
  3729. RootPanel.prototype.reflow = function () {
  3730. var changed = 0,
  3731. update = util.updateProperty,
  3732. frame = this.frame;
  3733. if (frame) {
  3734. changed += update(this, 'top', frame.offsetTop);
  3735. changed += update(this, 'left', frame.offsetLeft);
  3736. changed += update(this, 'width', frame.offsetWidth);
  3737. changed += update(this, 'height', frame.offsetHeight);
  3738. }
  3739. else {
  3740. changed += 1;
  3741. }
  3742. return (changed > 0);
  3743. };
  3744. /**
  3745. * Update watching for resize, depending on the current option
  3746. * @private
  3747. */
  3748. RootPanel.prototype._updateWatch = function () {
  3749. var autoResize = this.getOption('autoResize');
  3750. if (autoResize) {
  3751. this._watch();
  3752. }
  3753. else {
  3754. this._unwatch();
  3755. }
  3756. };
  3757. /**
  3758. * Watch for changes in the size of the frame. On resize, the Panel will
  3759. * automatically redraw itself.
  3760. * @private
  3761. */
  3762. RootPanel.prototype._watch = function () {
  3763. var me = this;
  3764. this._unwatch();
  3765. var checkSize = function () {
  3766. var autoResize = me.getOption('autoResize');
  3767. if (!autoResize) {
  3768. // stop watching when the option autoResize is changed to false
  3769. me._unwatch();
  3770. return;
  3771. }
  3772. if (me.frame) {
  3773. // check whether the frame is resized
  3774. if ((me.frame.clientWidth != me.width) ||
  3775. (me.frame.clientHeight != me.height)) {
  3776. me.requestReflow();
  3777. }
  3778. }
  3779. };
  3780. // TODO: automatically cleanup the event listener when the frame is deleted
  3781. util.addEventListener(window, 'resize', checkSize);
  3782. this.watchTimer = setInterval(checkSize, 1000);
  3783. };
  3784. /**
  3785. * Stop watching for a resize of the frame.
  3786. * @private
  3787. */
  3788. RootPanel.prototype._unwatch = function () {
  3789. if (this.watchTimer) {
  3790. clearInterval(this.watchTimer);
  3791. this.watchTimer = undefined;
  3792. }
  3793. // TODO: remove event listener on window.resize
  3794. };
  3795. /**
  3796. * Set controller for this component, or remove current controller by passing
  3797. * null as parameter value.
  3798. * @param {Controller | null} controller
  3799. */
  3800. RootPanel.prototype.setController = function setController (controller) {
  3801. this.controller = controller || null;
  3802. if (this.controller) {
  3803. this._registerListeners();
  3804. }
  3805. else {
  3806. this._unregisterListeners();
  3807. }
  3808. };
  3809. /**
  3810. * Register event emitters emitted by the rootpanel
  3811. * @private
  3812. */
  3813. RootPanel.prototype._registerListeners = function () {
  3814. if (this.frame && this.controller && !this.hammer) {
  3815. this.hammer = Hammer(this.frame, {
  3816. prevent_default: true
  3817. });
  3818. for (var event in this.listeners) {
  3819. if (this.listeners.hasOwnProperty(event)) {
  3820. this.hammer.on(event, this.listeners[event]);
  3821. }
  3822. }
  3823. }
  3824. };
  3825. /**
  3826. * Unregister event emitters from the rootpanel
  3827. * @private
  3828. */
  3829. RootPanel.prototype._unregisterListeners = function () {
  3830. if (this.hammer) {
  3831. for (var event in this.listeners) {
  3832. if (this.listeners.hasOwnProperty(event)) {
  3833. this.hammer.off(event, this.listeners[event]);
  3834. }
  3835. }
  3836. this.hammer = null;
  3837. }
  3838. };
  3839. /**
  3840. * A horizontal time axis
  3841. * @param {Component} parent
  3842. * @param {Component[]} [depends] Components on which this components depends
  3843. * (except for the parent)
  3844. * @param {Object} [options] See TimeAxis.setOptions for the available
  3845. * options.
  3846. * @constructor TimeAxis
  3847. * @extends Component
  3848. */
  3849. function TimeAxis (parent, depends, options) {
  3850. this.id = util.randomUUID();
  3851. this.parent = parent;
  3852. this.depends = depends;
  3853. this.dom = {
  3854. majorLines: [],
  3855. majorTexts: [],
  3856. minorLines: [],
  3857. minorTexts: [],
  3858. redundant: {
  3859. majorLines: [],
  3860. majorTexts: [],
  3861. minorLines: [],
  3862. minorTexts: []
  3863. }
  3864. };
  3865. this.props = {
  3866. range: {
  3867. start: 0,
  3868. end: 0,
  3869. minimumStep: 0
  3870. },
  3871. lineTop: 0
  3872. };
  3873. this.options = options || {};
  3874. this.defaultOptions = {
  3875. orientation: 'bottom', // supported: 'top', 'bottom'
  3876. // TODO: implement timeaxis orientations 'left' and 'right'
  3877. showMinorLabels: true,
  3878. showMajorLabels: true
  3879. };
  3880. this.conversion = null;
  3881. this.range = null;
  3882. }
  3883. TimeAxis.prototype = new Component();
  3884. // TODO: comment options
  3885. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3886. /**
  3887. * Set a range (start and end)
  3888. * @param {Range | Object} range A Range or an object containing start and end.
  3889. */
  3890. TimeAxis.prototype.setRange = function (range) {
  3891. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3892. throw new TypeError('Range must be an instance of Range, ' +
  3893. 'or an object containing start and end.');
  3894. }
  3895. this.range = range;
  3896. };
  3897. /**
  3898. * Convert a position on screen (pixels) to a datetime
  3899. * @param {int} x Position on the screen in pixels
  3900. * @return {Date} time The datetime the corresponds with given position x
  3901. */
  3902. TimeAxis.prototype.toTime = function(x) {
  3903. var conversion = this.conversion;
  3904. return new Date(x / conversion.scale + conversion.offset);
  3905. };
  3906. /**
  3907. * Convert a datetime (Date object) into a position on the screen
  3908. * @param {Date} time A date
  3909. * @return {int} x The position on the screen in pixels which corresponds
  3910. * with the given date.
  3911. * @private
  3912. */
  3913. TimeAxis.prototype.toScreen = function(time) {
  3914. var conversion = this.conversion;
  3915. return (time.valueOf() - conversion.offset) * conversion.scale;
  3916. };
  3917. /**
  3918. * Repaint the component
  3919. * @return {Boolean} changed
  3920. */
  3921. TimeAxis.prototype.repaint = function () {
  3922. var changed = 0,
  3923. update = util.updateProperty,
  3924. asSize = util.option.asSize,
  3925. options = this.options,
  3926. orientation = this.getOption('orientation'),
  3927. props = this.props,
  3928. step = this.step;
  3929. var frame = this.frame;
  3930. if (!frame) {
  3931. frame = document.createElement('div');
  3932. this.frame = frame;
  3933. changed += 1;
  3934. }
  3935. frame.className = 'axis';
  3936. // TODO: custom className?
  3937. if (!frame.parentNode) {
  3938. if (!this.parent) {
  3939. throw new Error('Cannot repaint time axis: no parent attached');
  3940. }
  3941. var parentContainer = this.parent.getContainer();
  3942. if (!parentContainer) {
  3943. throw new Error('Cannot repaint time axis: parent has no container element');
  3944. }
  3945. parentContainer.appendChild(frame);
  3946. changed += 1;
  3947. }
  3948. var parent = frame.parentNode;
  3949. if (parent) {
  3950. var beforeChild = frame.nextSibling;
  3951. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3952. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3953. (this.props.parentHeight - this.height) + 'px' :
  3954. '0px';
  3955. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3956. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3957. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3958. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3959. // get characters width and height
  3960. this._repaintMeasureChars();
  3961. if (this.step) {
  3962. this._repaintStart();
  3963. step.first();
  3964. var xFirstMajorLabel = undefined;
  3965. var max = 0;
  3966. while (step.hasNext() && max < 1000) {
  3967. max++;
  3968. var cur = step.getCurrent(),
  3969. x = this.toScreen(cur),
  3970. isMajor = step.isMajor();
  3971. // TODO: lines must have a width, such that we can create css backgrounds
  3972. if (this.getOption('showMinorLabels')) {
  3973. this._repaintMinorText(x, step.getLabelMinor());
  3974. }
  3975. if (isMajor && this.getOption('showMajorLabels')) {
  3976. if (x > 0) {
  3977. if (xFirstMajorLabel == undefined) {
  3978. xFirstMajorLabel = x;
  3979. }
  3980. this._repaintMajorText(x, step.getLabelMajor());
  3981. }
  3982. this._repaintMajorLine(x);
  3983. }
  3984. else {
  3985. this._repaintMinorLine(x);
  3986. }
  3987. step.next();
  3988. }
  3989. // create a major label on the left when needed
  3990. if (this.getOption('showMajorLabels')) {
  3991. var leftTime = this.toTime(0),
  3992. leftText = step.getLabelMajor(leftTime),
  3993. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3994. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3995. this._repaintMajorText(0, leftText);
  3996. }
  3997. }
  3998. this._repaintEnd();
  3999. }
  4000. this._repaintLine();
  4001. // put frame online again
  4002. if (beforeChild) {
  4003. parent.insertBefore(frame, beforeChild);
  4004. }
  4005. else {
  4006. parent.appendChild(frame)
  4007. }
  4008. }
  4009. return (changed > 0);
  4010. };
  4011. /**
  4012. * Start a repaint. Move all DOM elements to a redundant list, where they
  4013. * can be picked for re-use, or can be cleaned up in the end
  4014. * @private
  4015. */
  4016. TimeAxis.prototype._repaintStart = function () {
  4017. var dom = this.dom,
  4018. redundant = dom.redundant;
  4019. redundant.majorLines = dom.majorLines;
  4020. redundant.majorTexts = dom.majorTexts;
  4021. redundant.minorLines = dom.minorLines;
  4022. redundant.minorTexts = dom.minorTexts;
  4023. dom.majorLines = [];
  4024. dom.majorTexts = [];
  4025. dom.minorLines = [];
  4026. dom.minorTexts = [];
  4027. };
  4028. /**
  4029. * End a repaint. Cleanup leftover DOM elements in the redundant list
  4030. * @private
  4031. */
  4032. TimeAxis.prototype._repaintEnd = function () {
  4033. util.forEach(this.dom.redundant, function (arr) {
  4034. while (arr.length) {
  4035. var elem = arr.pop();
  4036. if (elem && elem.parentNode) {
  4037. elem.parentNode.removeChild(elem);
  4038. }
  4039. }
  4040. });
  4041. };
  4042. /**
  4043. * Create a minor label for the axis at position x
  4044. * @param {Number} x
  4045. * @param {String} text
  4046. * @private
  4047. */
  4048. TimeAxis.prototype._repaintMinorText = function (x, text) {
  4049. // reuse redundant label
  4050. var label = this.dom.redundant.minorTexts.shift();
  4051. if (!label) {
  4052. // create new label
  4053. var content = document.createTextNode('');
  4054. label = document.createElement('div');
  4055. label.appendChild(content);
  4056. label.className = 'text minor';
  4057. this.frame.appendChild(label);
  4058. }
  4059. this.dom.minorTexts.push(label);
  4060. label.childNodes[0].nodeValue = text;
  4061. label.style.left = x + 'px';
  4062. label.style.top = this.props.minorLabelTop + 'px';
  4063. //label.title = title; // TODO: this is a heavy operation
  4064. };
  4065. /**
  4066. * Create a Major label for the axis at position x
  4067. * @param {Number} x
  4068. * @param {String} text
  4069. * @private
  4070. */
  4071. TimeAxis.prototype._repaintMajorText = function (x, text) {
  4072. // reuse redundant label
  4073. var label = this.dom.redundant.majorTexts.shift();
  4074. if (!label) {
  4075. // create label
  4076. var content = document.createTextNode(text);
  4077. label = document.createElement('div');
  4078. label.className = 'text major';
  4079. label.appendChild(content);
  4080. this.frame.appendChild(label);
  4081. }
  4082. this.dom.majorTexts.push(label);
  4083. label.childNodes[0].nodeValue = text;
  4084. label.style.top = this.props.majorLabelTop + 'px';
  4085. label.style.left = x + 'px';
  4086. //label.title = title; // TODO: this is a heavy operation
  4087. };
  4088. /**
  4089. * Create a minor line for the axis at position x
  4090. * @param {Number} x
  4091. * @private
  4092. */
  4093. TimeAxis.prototype._repaintMinorLine = function (x) {
  4094. // reuse redundant line
  4095. var line = this.dom.redundant.minorLines.shift();
  4096. if (!line) {
  4097. // create vertical line
  4098. line = document.createElement('div');
  4099. line.className = 'grid vertical minor';
  4100. this.frame.appendChild(line);
  4101. }
  4102. this.dom.minorLines.push(line);
  4103. var props = this.props;
  4104. line.style.top = props.minorLineTop + 'px';
  4105. line.style.height = props.minorLineHeight + 'px';
  4106. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  4107. };
  4108. /**
  4109. * Create a Major line for the axis at position x
  4110. * @param {Number} x
  4111. * @private
  4112. */
  4113. TimeAxis.prototype._repaintMajorLine = function (x) {
  4114. // reuse redundant line
  4115. var line = this.dom.redundant.majorLines.shift();
  4116. if (!line) {
  4117. // create vertical line
  4118. line = document.createElement('DIV');
  4119. line.className = 'grid vertical major';
  4120. this.frame.appendChild(line);
  4121. }
  4122. this.dom.majorLines.push(line);
  4123. var props = this.props;
  4124. line.style.top = props.majorLineTop + 'px';
  4125. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4126. line.style.height = props.majorLineHeight + 'px';
  4127. };
  4128. /**
  4129. * Repaint the horizontal line for the axis
  4130. * @private
  4131. */
  4132. TimeAxis.prototype._repaintLine = function() {
  4133. var line = this.dom.line,
  4134. frame = this.frame,
  4135. options = this.options;
  4136. // line before all axis elements
  4137. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4138. if (line) {
  4139. // put this line at the end of all childs
  4140. frame.removeChild(line);
  4141. frame.appendChild(line);
  4142. }
  4143. else {
  4144. // create the axis line
  4145. line = document.createElement('div');
  4146. line.className = 'grid horizontal major';
  4147. frame.appendChild(line);
  4148. this.dom.line = line;
  4149. }
  4150. line.style.top = this.props.lineTop + 'px';
  4151. }
  4152. else {
  4153. if (line && line.parentElement) {
  4154. frame.removeChild(line.line);
  4155. delete this.dom.line;
  4156. }
  4157. }
  4158. };
  4159. /**
  4160. * Create characters used to determine the size of text on the axis
  4161. * @private
  4162. */
  4163. TimeAxis.prototype._repaintMeasureChars = function () {
  4164. // calculate the width and height of a single character
  4165. // this is used to calculate the step size, and also the positioning of the
  4166. // axis
  4167. var dom = this.dom,
  4168. text;
  4169. if (!dom.measureCharMinor) {
  4170. text = document.createTextNode('0');
  4171. var measureCharMinor = document.createElement('DIV');
  4172. measureCharMinor.className = 'text minor measure';
  4173. measureCharMinor.appendChild(text);
  4174. this.frame.appendChild(measureCharMinor);
  4175. dom.measureCharMinor = measureCharMinor;
  4176. }
  4177. if (!dom.measureCharMajor) {
  4178. text = document.createTextNode('0');
  4179. var measureCharMajor = document.createElement('DIV');
  4180. measureCharMajor.className = 'text major measure';
  4181. measureCharMajor.appendChild(text);
  4182. this.frame.appendChild(measureCharMajor);
  4183. dom.measureCharMajor = measureCharMajor;
  4184. }
  4185. };
  4186. /**
  4187. * Reflow the component
  4188. * @return {Boolean} resized
  4189. */
  4190. TimeAxis.prototype.reflow = function () {
  4191. var changed = 0,
  4192. update = util.updateProperty,
  4193. frame = this.frame,
  4194. range = this.range;
  4195. if (!range) {
  4196. throw new Error('Cannot repaint time axis: no range configured');
  4197. }
  4198. if (frame) {
  4199. changed += update(this, 'top', frame.offsetTop);
  4200. changed += update(this, 'left', frame.offsetLeft);
  4201. // calculate size of a character
  4202. var props = this.props,
  4203. showMinorLabels = this.getOption('showMinorLabels'),
  4204. showMajorLabels = this.getOption('showMajorLabels'),
  4205. measureCharMinor = this.dom.measureCharMinor,
  4206. measureCharMajor = this.dom.measureCharMajor;
  4207. if (measureCharMinor) {
  4208. props.minorCharHeight = measureCharMinor.clientHeight;
  4209. props.minorCharWidth = measureCharMinor.clientWidth;
  4210. }
  4211. if (measureCharMajor) {
  4212. props.majorCharHeight = measureCharMajor.clientHeight;
  4213. props.majorCharWidth = measureCharMajor.clientWidth;
  4214. }
  4215. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4216. if (parentHeight != props.parentHeight) {
  4217. props.parentHeight = parentHeight;
  4218. changed += 1;
  4219. }
  4220. switch (this.getOption('orientation')) {
  4221. case 'bottom':
  4222. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4223. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4224. props.minorLabelTop = 0;
  4225. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4226. props.minorLineTop = -this.top;
  4227. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4228. props.minorLineWidth = 1; // TODO: really calculate width
  4229. props.majorLineTop = -this.top;
  4230. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4231. props.majorLineWidth = 1; // TODO: really calculate width
  4232. props.lineTop = 0;
  4233. break;
  4234. case 'top':
  4235. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4236. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4237. props.majorLabelTop = 0;
  4238. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4239. props.minorLineTop = props.minorLabelTop;
  4240. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4241. props.minorLineWidth = 1; // TODO: really calculate width
  4242. props.majorLineTop = 0;
  4243. props.majorLineHeight = Math.max(parentHeight - this.top);
  4244. props.majorLineWidth = 1; // TODO: really calculate width
  4245. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4246. break;
  4247. default:
  4248. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4249. }
  4250. var height = props.minorLabelHeight + props.majorLabelHeight;
  4251. changed += update(this, 'width', frame.offsetWidth);
  4252. changed += update(this, 'height', height);
  4253. // calculate range and step
  4254. this._updateConversion();
  4255. var start = util.convert(range.start, 'Number'),
  4256. end = util.convert(range.end, 'Number'),
  4257. minimumStep = this.toTime((props.minorCharWidth || 10) * 5).valueOf()
  4258. -this.toTime(0).valueOf();
  4259. this.step = new TimeStep(new Date(start), new Date(end), minimumStep);
  4260. changed += update(props.range, 'start', start);
  4261. changed += update(props.range, 'end', end);
  4262. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4263. }
  4264. return (changed > 0);
  4265. };
  4266. /**
  4267. * Calculate the scale and offset to convert a position on screen to the
  4268. * corresponding date and vice versa.
  4269. * After the method _updateConversion is executed once, the methods toTime
  4270. * and toScreen can be used.
  4271. * @private
  4272. */
  4273. TimeAxis.prototype._updateConversion = function() {
  4274. var range = this.range;
  4275. if (!range) {
  4276. throw new Error('No range configured');
  4277. }
  4278. if (range.conversion) {
  4279. this.conversion = range.conversion(this.width);
  4280. }
  4281. else {
  4282. this.conversion = Range.conversion(range.start, range.end, this.width);
  4283. }
  4284. };
  4285. /**
  4286. * Snap a date to a rounded value.
  4287. * The snap intervals are dependent on the current scale and step.
  4288. * @param {Date} date the date to be snapped.
  4289. * @return {Date} snappedDate
  4290. */
  4291. TimeAxis.prototype.snap = function snap (date) {
  4292. return this.step.snap(date);
  4293. };
  4294. /**
  4295. * A current time bar
  4296. * @param {Component} parent
  4297. * @param {Component[]} [depends] Components on which this components depends
  4298. * (except for the parent)
  4299. * @param {Object} [options] Available parameters:
  4300. * {Boolean} [showCurrentTime]
  4301. * @constructor CurrentTime
  4302. * @extends Component
  4303. */
  4304. function CurrentTime (parent, depends, options) {
  4305. this.id = util.randomUUID();
  4306. this.parent = parent;
  4307. this.depends = depends;
  4308. this.options = options || {};
  4309. this.defaultOptions = {
  4310. showCurrentTime: false
  4311. };
  4312. }
  4313. CurrentTime.prototype = new Component();
  4314. CurrentTime.prototype.setOptions = Component.prototype.setOptions;
  4315. /**
  4316. * Get the container element of the bar, which can be used by a child to
  4317. * add its own widgets.
  4318. * @returns {HTMLElement} container
  4319. */
  4320. CurrentTime.prototype.getContainer = function () {
  4321. return this.frame;
  4322. };
  4323. /**
  4324. * Repaint the component
  4325. * @return {Boolean} changed
  4326. */
  4327. CurrentTime.prototype.repaint = function () {
  4328. var bar = this.frame,
  4329. parent = this.parent,
  4330. parentContainer = parent.parent.getContainer();
  4331. if (!parent) {
  4332. throw new Error('Cannot repaint bar: no parent attached');
  4333. }
  4334. if (!parentContainer) {
  4335. throw new Error('Cannot repaint bar: parent has no container element');
  4336. }
  4337. if (!this.getOption('showCurrentTime')) {
  4338. if (bar) {
  4339. parentContainer.removeChild(bar);
  4340. delete this.frame;
  4341. }
  4342. return false;
  4343. }
  4344. if (!bar) {
  4345. bar = document.createElement('div');
  4346. bar.className = 'currenttime';
  4347. bar.style.position = 'absolute';
  4348. bar.style.top = '0px';
  4349. bar.style.height = '100%';
  4350. parentContainer.appendChild(bar);
  4351. this.frame = bar;
  4352. }
  4353. if (!parent.conversion) {
  4354. parent._updateConversion();
  4355. }
  4356. var now = new Date();
  4357. var x = parent.toScreen(now);
  4358. bar.style.left = x + 'px';
  4359. bar.title = 'Current time: ' + now;
  4360. // start a timer to adjust for the new time
  4361. if (this.currentTimeTimer !== undefined) {
  4362. clearTimeout(this.currentTimeTimer);
  4363. delete this.currentTimeTimer;
  4364. }
  4365. var timeline = this;
  4366. var interval = 1 / parent.conversion.scale / 2;
  4367. if (interval < 30) {
  4368. interval = 30;
  4369. }
  4370. this.currentTimeTimer = setTimeout(function() {
  4371. timeline.repaint();
  4372. }, interval);
  4373. return false;
  4374. };
  4375. /**
  4376. * A custom time bar
  4377. * @param {Component} parent
  4378. * @param {Component[]} [depends] Components on which this components depends
  4379. * (except for the parent)
  4380. * @param {Object} [options] Available parameters:
  4381. * {Boolean} [showCustomTime]
  4382. * @constructor CustomTime
  4383. * @extends Component
  4384. */
  4385. function CustomTime (parent, depends, options) {
  4386. this.id = util.randomUUID();
  4387. this.parent = parent;
  4388. this.depends = depends;
  4389. this.options = options || {};
  4390. this.defaultOptions = {
  4391. showCustomTime: false
  4392. };
  4393. this.customTime = new Date();
  4394. this.eventParams = {}; // stores state parameters while dragging the bar
  4395. }
  4396. CustomTime.prototype = new Component();
  4397. Emitter(CustomTime.prototype);
  4398. CustomTime.prototype.setOptions = Component.prototype.setOptions;
  4399. /**
  4400. * Get the container element of the bar, which can be used by a child to
  4401. * add its own widgets.
  4402. * @returns {HTMLElement} container
  4403. */
  4404. CustomTime.prototype.getContainer = function () {
  4405. return this.frame;
  4406. };
  4407. /**
  4408. * Repaint the component
  4409. * @return {Boolean} changed
  4410. */
  4411. CustomTime.prototype.repaint = function () {
  4412. var bar = this.frame,
  4413. parent = this.parent;
  4414. if (!parent) {
  4415. throw new Error('Cannot repaint bar: no parent attached');
  4416. }
  4417. var parentContainer = parent.parent.getContainer();
  4418. if (!parentContainer) {
  4419. throw new Error('Cannot repaint bar: parent has no container element');
  4420. }
  4421. if (!this.getOption('showCustomTime')) {
  4422. if (bar) {
  4423. parentContainer.removeChild(bar);
  4424. delete this.frame;
  4425. }
  4426. return false;
  4427. }
  4428. if (!bar) {
  4429. bar = document.createElement('div');
  4430. bar.className = 'customtime';
  4431. bar.style.position = 'absolute';
  4432. bar.style.top = '0px';
  4433. bar.style.height = '100%';
  4434. parentContainer.appendChild(bar);
  4435. var drag = document.createElement('div');
  4436. drag.style.position = 'relative';
  4437. drag.style.top = '0px';
  4438. drag.style.left = '-10px';
  4439. drag.style.height = '100%';
  4440. drag.style.width = '20px';
  4441. bar.appendChild(drag);
  4442. this.frame = bar;
  4443. // attach event listeners
  4444. this.hammer = Hammer(bar, {
  4445. prevent_default: true
  4446. });
  4447. this.hammer.on('dragstart', this._onDragStart.bind(this));
  4448. this.hammer.on('drag', this._onDrag.bind(this));
  4449. this.hammer.on('dragend', this._onDragEnd.bind(this));
  4450. }
  4451. if (!parent.conversion) {
  4452. parent._updateConversion();
  4453. }
  4454. var x = parent.toScreen(this.customTime);
  4455. bar.style.left = x + 'px';
  4456. bar.title = 'Time: ' + this.customTime;
  4457. return false;
  4458. };
  4459. /**
  4460. * Set custom time.
  4461. * @param {Date} time
  4462. */
  4463. CustomTime.prototype.setCustomTime = function(time) {
  4464. this.customTime = new Date(time.valueOf());
  4465. this.repaint();
  4466. };
  4467. /**
  4468. * Retrieve the current custom time.
  4469. * @return {Date} customTime
  4470. */
  4471. CustomTime.prototype.getCustomTime = function() {
  4472. return new Date(this.customTime.valueOf());
  4473. };
  4474. /**
  4475. * Start moving horizontally
  4476. * @param {Event} event
  4477. * @private
  4478. */
  4479. CustomTime.prototype._onDragStart = function(event) {
  4480. this.eventParams.customTime = this.customTime;
  4481. event.stopPropagation();
  4482. event.preventDefault();
  4483. };
  4484. /**
  4485. * Perform moving operating.
  4486. * @param {Event} event
  4487. * @private
  4488. */
  4489. CustomTime.prototype._onDrag = function (event) {
  4490. var deltaX = event.gesture.deltaX,
  4491. x = this.parent.toScreen(this.eventParams.customTime) + deltaX,
  4492. time = this.parent.toTime(x);
  4493. this.setCustomTime(time);
  4494. // fire a timechange event
  4495. if (this.controller) {
  4496. this.controller.emit('timechange', {
  4497. time: this.customTime
  4498. })
  4499. }
  4500. event.stopPropagation();
  4501. event.preventDefault();
  4502. };
  4503. /**
  4504. * Stop moving operating.
  4505. * @param {event} event
  4506. * @private
  4507. */
  4508. CustomTime.prototype._onDragEnd = function (event) {
  4509. // fire a timechanged event
  4510. if (this.controller) {
  4511. this.controller.emit('timechanged', {
  4512. time: this.customTime
  4513. })
  4514. }
  4515. event.stopPropagation();
  4516. event.preventDefault();
  4517. };
  4518. /**
  4519. * An ItemSet holds a set of items and ranges which can be displayed in a
  4520. * range. The width is determined by the parent of the ItemSet, and the height
  4521. * is determined by the size of the items.
  4522. * @param {Component} parent
  4523. * @param {Component[]} [depends] Components on which this components depends
  4524. * (except for the parent)
  4525. * @param {Object} [options] See ItemSet.setOptions for the available
  4526. * options.
  4527. * @constructor ItemSet
  4528. * @extends Panel
  4529. */
  4530. // TODO: improve performance by replacing all Array.forEach with a for loop
  4531. function ItemSet(parent, depends, options) {
  4532. this.id = util.randomUUID();
  4533. this.parent = parent;
  4534. this.depends = depends;
  4535. // event listeners
  4536. this.eventListeners = {
  4537. dragstart: this._onDragStart.bind(this),
  4538. drag: this._onDrag.bind(this),
  4539. dragend: this._onDragEnd.bind(this)
  4540. };
  4541. // one options object is shared by this itemset and all its items
  4542. this.options = options || {};
  4543. this.defaultOptions = {
  4544. type: 'box',
  4545. align: 'center',
  4546. orientation: 'bottom',
  4547. margin: {
  4548. axis: 20,
  4549. item: 10
  4550. },
  4551. padding: 5
  4552. };
  4553. this.dom = {};
  4554. var me = this;
  4555. this.itemsData = null; // DataSet
  4556. this.range = null; // Range or Object {start: number, end: number}
  4557. // data change listeners
  4558. this.listeners = {
  4559. 'add': function (event, params, senderId) {
  4560. if (senderId != me.id) {
  4561. me._onAdd(params.items);
  4562. }
  4563. },
  4564. 'update': function (event, params, senderId) {
  4565. if (senderId != me.id) {
  4566. me._onUpdate(params.items);
  4567. }
  4568. },
  4569. 'remove': function (event, params, senderId) {
  4570. if (senderId != me.id) {
  4571. me._onRemove(params.items);
  4572. }
  4573. }
  4574. };
  4575. this.items = {}; // object with an Item for every data item
  4576. this.selection = []; // list with the ids of all selected nodes
  4577. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4578. this.stack = new Stack(this, Object.create(this.options));
  4579. this.conversion = null;
  4580. this.touchParams = {}; // stores properties while dragging
  4581. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4582. }
  4583. ItemSet.prototype = new Panel();
  4584. // available item types will be registered here
  4585. ItemSet.types = {
  4586. box: ItemBox,
  4587. range: ItemRange,
  4588. rangeoverflow: ItemRangeOverflow,
  4589. point: ItemPoint
  4590. };
  4591. /**
  4592. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4593. * @param {Object} [options] The following options are available:
  4594. * {String | function} [className]
  4595. * class name for the itemset
  4596. * {String} [type]
  4597. * Default type for the items. Choose from 'box'
  4598. * (default), 'point', or 'range'. The default
  4599. * Style can be overwritten by individual items.
  4600. * {String} align
  4601. * Alignment for the items, only applicable for
  4602. * ItemBox. Choose 'center' (default), 'left', or
  4603. * 'right'.
  4604. * {String} orientation
  4605. * Orientation of the item set. Choose 'top' or
  4606. * 'bottom' (default).
  4607. * {Number} margin.axis
  4608. * Margin between the axis and the items in pixels.
  4609. * Default is 20.
  4610. * {Number} margin.item
  4611. * Margin between items in pixels. Default is 10.
  4612. * {Number} padding
  4613. * Padding of the contents of an item in pixels.
  4614. * Must correspond with the items css. Default is 5.
  4615. * {Function} snap
  4616. * Function to let items snap to nice dates when
  4617. * dragging items.
  4618. */
  4619. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4620. /**
  4621. * Set controller for this component
  4622. * @param {Controller | null} controller
  4623. */
  4624. ItemSet.prototype.setController = function setController (controller) {
  4625. var event;
  4626. // unregister old event listeners
  4627. if (this.controller) {
  4628. for (event in this.eventListeners) {
  4629. if (this.eventListeners.hasOwnProperty(event)) {
  4630. this.controller.off(event, this.eventListeners[event]);
  4631. }
  4632. }
  4633. }
  4634. this.controller = controller || null;
  4635. // register new event listeners
  4636. if (this.controller) {
  4637. for (event in this.eventListeners) {
  4638. if (this.eventListeners.hasOwnProperty(event)) {
  4639. this.controller.on(event, this.eventListeners[event]);
  4640. }
  4641. }
  4642. }
  4643. };
  4644. // attach event listeners for dragging items to the controller
  4645. (function (me) {
  4646. var _controller = null;
  4647. var _onDragStart = null;
  4648. var _onDrag = null;
  4649. var _onDragEnd = null;
  4650. Object.defineProperty(me, 'controller', {
  4651. get: function () {
  4652. return _controller;
  4653. },
  4654. set: function (controller) {
  4655. }
  4656. });
  4657. }) (this);
  4658. /**
  4659. * Set range (start and end).
  4660. * @param {Range | Object} range A Range or an object containing start and end.
  4661. */
  4662. ItemSet.prototype.setRange = function setRange(range) {
  4663. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4664. throw new TypeError('Range must be an instance of Range, ' +
  4665. 'or an object containing start and end.');
  4666. }
  4667. this.range = range;
  4668. };
  4669. /**
  4670. * Set selected items by their id. Replaces the current selection
  4671. * Unknown id's are silently ignored.
  4672. * @param {Array} [ids] An array with zero or more id's of the items to be
  4673. * selected. If ids is an empty array, all items will be
  4674. * unselected.
  4675. */
  4676. ItemSet.prototype.setSelection = function setSelection(ids) {
  4677. var i, ii, id, item, selection;
  4678. if (ids) {
  4679. if (!Array.isArray(ids)) {
  4680. throw new TypeError('Array expected');
  4681. }
  4682. // unselect currently selected items
  4683. for (i = 0, ii = this.selection.length; i < ii; i++) {
  4684. id = this.selection[i];
  4685. item = this.items[id];
  4686. if (item) item.unselect();
  4687. }
  4688. // select items
  4689. this.selection = [];
  4690. for (i = 0, ii = ids.length; i < ii; i++) {
  4691. id = ids[i];
  4692. item = this.items[id];
  4693. if (item) {
  4694. this.selection.push(id);
  4695. item.select();
  4696. }
  4697. }
  4698. if (this.controller) {
  4699. this.requestRepaint();
  4700. }
  4701. }
  4702. };
  4703. /**
  4704. * Get the selected items by their id
  4705. * @return {Array} ids The ids of the selected items
  4706. */
  4707. ItemSet.prototype.getSelection = function getSelection() {
  4708. return this.selection.concat([]);
  4709. };
  4710. /**
  4711. * Deselect a selected item
  4712. * @param {String | Number} id
  4713. * @private
  4714. */
  4715. ItemSet.prototype._deselect = function _deselect(id) {
  4716. var selection = this.selection;
  4717. for (var i = 0, ii = selection.length; i < ii; i++) {
  4718. if (selection[i] == id) { // non-strict comparison!
  4719. selection.splice(i, 1);
  4720. break;
  4721. }
  4722. }
  4723. };
  4724. /**
  4725. * Repaint the component
  4726. * @return {Boolean} changed
  4727. */
  4728. ItemSet.prototype.repaint = function repaint() {
  4729. var changed = 0,
  4730. update = util.updateProperty,
  4731. asSize = util.option.asSize,
  4732. options = this.options,
  4733. orientation = this.getOption('orientation'),
  4734. defaultOptions = this.defaultOptions,
  4735. frame = this.frame;
  4736. if (!frame) {
  4737. frame = document.createElement('div');
  4738. frame.className = 'itemset';
  4739. frame['timeline-itemset'] = this;
  4740. var className = options.className;
  4741. if (className) {
  4742. util.addClassName(frame, util.option.asString(className));
  4743. }
  4744. // create background panel
  4745. var background = document.createElement('div');
  4746. background.className = 'background';
  4747. frame.appendChild(background);
  4748. this.dom.background = background;
  4749. // create foreground panel
  4750. var foreground = document.createElement('div');
  4751. foreground.className = 'foreground';
  4752. frame.appendChild(foreground);
  4753. this.dom.foreground = foreground;
  4754. // create axis panel
  4755. var axis = document.createElement('div');
  4756. axis.className = 'itemset-axis';
  4757. //frame.appendChild(axis);
  4758. this.dom.axis = axis;
  4759. this.frame = frame;
  4760. changed += 1;
  4761. }
  4762. if (!this.parent) {
  4763. throw new Error('Cannot repaint itemset: no parent attached');
  4764. }
  4765. var parentContainer = this.parent.getContainer();
  4766. if (!parentContainer) {
  4767. throw new Error('Cannot repaint itemset: parent has no container element');
  4768. }
  4769. if (!frame.parentNode) {
  4770. parentContainer.appendChild(frame);
  4771. changed += 1;
  4772. }
  4773. if (!this.dom.axis.parentNode) {
  4774. parentContainer.appendChild(this.dom.axis);
  4775. changed += 1;
  4776. }
  4777. // reposition frame
  4778. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4779. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4780. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4781. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4782. // reposition axis
  4783. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4784. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4785. if (orientation == 'bottom') {
  4786. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4787. }
  4788. else { // orientation == 'top'
  4789. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4790. }
  4791. this._updateConversion();
  4792. var me = this,
  4793. queue = this.queue,
  4794. itemsData = this.itemsData,
  4795. items = this.items,
  4796. dataOptions = {
  4797. // TODO: cleanup
  4798. // fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type', 'className']
  4799. };
  4800. // show/hide added/changed/removed items
  4801. for (var id in queue) {
  4802. if (queue.hasOwnProperty(id)) {
  4803. var entry = queue[id],
  4804. item = items[id],
  4805. action = entry.action;
  4806. //noinspection FallthroughInSwitchStatementJS
  4807. switch (action) {
  4808. case 'add':
  4809. case 'update':
  4810. var itemData = itemsData && itemsData.get(id, dataOptions);
  4811. if (itemData) {
  4812. var type = itemData.type ||
  4813. (itemData.start && itemData.end && 'range') ||
  4814. options.type ||
  4815. 'box';
  4816. var constructor = ItemSet.types[type];
  4817. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4818. if (item) {
  4819. // update item
  4820. if (!constructor || !(item instanceof constructor)) {
  4821. // item type has changed, hide and delete the item
  4822. changed += item.hide();
  4823. item = null;
  4824. }
  4825. else {
  4826. item.data = itemData; // TODO: create a method item.setData ?
  4827. changed++;
  4828. }
  4829. }
  4830. if (!item) {
  4831. // create item
  4832. if (constructor) {
  4833. item = new constructor(me, itemData, options, defaultOptions);
  4834. item.id = entry.id; // we take entry.id, as id itself is stringified
  4835. changed++;
  4836. }
  4837. else {
  4838. throw new TypeError('Unknown item type "' + type + '"');
  4839. }
  4840. }
  4841. // force a repaint (not only a reposition)
  4842. item.repaint();
  4843. items[id] = item;
  4844. }
  4845. // update queue
  4846. delete queue[id];
  4847. break;
  4848. case 'remove':
  4849. if (item) {
  4850. // remove the item from the set selected items
  4851. if (item.selected) {
  4852. me._deselect(id);
  4853. }
  4854. // remove DOM of the item
  4855. changed += item.hide();
  4856. }
  4857. // update lists
  4858. delete items[id];
  4859. delete queue[id];
  4860. break;
  4861. default:
  4862. console.log('Error: unknown action "' + action + '"');
  4863. }
  4864. }
  4865. }
  4866. // reposition all items. Show items only when in the visible area
  4867. util.forEach(this.items, function (item) {
  4868. if (item.visible) {
  4869. changed += item.show();
  4870. item.reposition();
  4871. }
  4872. else {
  4873. changed += item.hide();
  4874. }
  4875. });
  4876. return (changed > 0);
  4877. };
  4878. /**
  4879. * Get the foreground container element
  4880. * @return {HTMLElement} foreground
  4881. */
  4882. ItemSet.prototype.getForeground = function getForeground() {
  4883. return this.dom.foreground;
  4884. };
  4885. /**
  4886. * Get the background container element
  4887. * @return {HTMLElement} background
  4888. */
  4889. ItemSet.prototype.getBackground = function getBackground() {
  4890. return this.dom.background;
  4891. };
  4892. /**
  4893. * Get the axis container element
  4894. * @return {HTMLElement} axis
  4895. */
  4896. ItemSet.prototype.getAxis = function getAxis() {
  4897. return this.dom.axis;
  4898. };
  4899. /**
  4900. * Reflow the component
  4901. * @return {Boolean} resized
  4902. */
  4903. ItemSet.prototype.reflow = function reflow () {
  4904. var changed = 0,
  4905. options = this.options,
  4906. marginAxis = (options.margin && 'axis' in options.margin) ? options.margin.axis : this.defaultOptions.margin.axis,
  4907. marginItem = (options.margin && 'item' in options.margin) ? options.margin.item : this.defaultOptions.margin.item,
  4908. update = util.updateProperty,
  4909. asNumber = util.option.asNumber,
  4910. asSize = util.option.asSize,
  4911. frame = this.frame;
  4912. if (frame) {
  4913. this._updateConversion();
  4914. util.forEach(this.items, function (item) {
  4915. changed += item.reflow();
  4916. });
  4917. // TODO: stack.update should be triggered via an event, in stack itself
  4918. // TODO: only update the stack when there are changed items
  4919. this.stack.update();
  4920. var maxHeight = asNumber(options.maxHeight);
  4921. var fixedHeight = (asSize(options.height) != null);
  4922. var height;
  4923. if (fixedHeight) {
  4924. height = frame.offsetHeight;
  4925. }
  4926. else {
  4927. // height is not specified, determine the height from the height and positioned items
  4928. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4929. if (visibleItems.length) {
  4930. var min = visibleItems[0].top;
  4931. var max = visibleItems[0].top + visibleItems[0].height;
  4932. util.forEach(visibleItems, function (item) {
  4933. min = Math.min(min, item.top);
  4934. max = Math.max(max, (item.top + item.height));
  4935. });
  4936. height = (max - min) + marginAxis + marginItem;
  4937. }
  4938. else {
  4939. height = marginAxis + marginItem;
  4940. }
  4941. }
  4942. if (maxHeight != null) {
  4943. height = Math.min(height, maxHeight);
  4944. }
  4945. changed += update(this, 'height', height);
  4946. // calculate height from items
  4947. changed += update(this, 'top', frame.offsetTop);
  4948. changed += update(this, 'left', frame.offsetLeft);
  4949. changed += update(this, 'width', frame.offsetWidth);
  4950. }
  4951. else {
  4952. changed += 1;
  4953. }
  4954. return (changed > 0);
  4955. };
  4956. /**
  4957. * Hide this component from the DOM
  4958. * @return {Boolean} changed
  4959. */
  4960. ItemSet.prototype.hide = function hide() {
  4961. var changed = false;
  4962. // remove the DOM
  4963. if (this.frame && this.frame.parentNode) {
  4964. this.frame.parentNode.removeChild(this.frame);
  4965. changed = true;
  4966. }
  4967. if (this.dom.axis && this.dom.axis.parentNode) {
  4968. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4969. changed = true;
  4970. }
  4971. return changed;
  4972. };
  4973. /**
  4974. * Set items
  4975. * @param {vis.DataSet | null} items
  4976. */
  4977. ItemSet.prototype.setItems = function setItems(items) {
  4978. var me = this,
  4979. ids,
  4980. oldItemsData = this.itemsData;
  4981. // replace the dataset
  4982. if (!items) {
  4983. this.itemsData = null;
  4984. }
  4985. else if (items instanceof DataSet || items instanceof DataView) {
  4986. this.itemsData = items;
  4987. }
  4988. else {
  4989. throw new TypeError('Data must be an instance of DataSet');
  4990. }
  4991. if (oldItemsData) {
  4992. // unsubscribe from old dataset
  4993. util.forEach(this.listeners, function (callback, event) {
  4994. oldItemsData.unsubscribe(event, callback);
  4995. });
  4996. // remove all drawn items
  4997. ids = oldItemsData.getIds();
  4998. this._onRemove(ids);
  4999. }
  5000. if (this.itemsData) {
  5001. // subscribe to new dataset
  5002. var id = this.id;
  5003. util.forEach(this.listeners, function (callback, event) {
  5004. me.itemsData.on(event, callback, id);
  5005. });
  5006. // draw all new items
  5007. ids = this.itemsData.getIds();
  5008. this._onAdd(ids);
  5009. }
  5010. };
  5011. /**
  5012. * Get the current items items
  5013. * @returns {vis.DataSet | null}
  5014. */
  5015. ItemSet.prototype.getItems = function getItems() {
  5016. return this.itemsData;
  5017. };
  5018. /**
  5019. * Remove an item by its id
  5020. * @param {String | Number} id
  5021. */
  5022. ItemSet.prototype.removeItem = function removeItem (id) {
  5023. var item = this.itemsData.get(id),
  5024. dataset = this._myDataSet();
  5025. if (item) {
  5026. // confirm deletion
  5027. this.options.onRemove(item, function (item) {
  5028. if (item) {
  5029. dataset.remove(item);
  5030. }
  5031. });
  5032. }
  5033. };
  5034. /**
  5035. * Handle updated items
  5036. * @param {Number[]} ids
  5037. * @private
  5038. */
  5039. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  5040. this._toQueue('update', ids);
  5041. };
  5042. /**
  5043. * Handle changed items
  5044. * @param {Number[]} ids
  5045. * @private
  5046. */
  5047. ItemSet.prototype._onAdd = function _onAdd(ids) {
  5048. this._toQueue('add', ids);
  5049. };
  5050. /**
  5051. * Handle removed items
  5052. * @param {Number[]} ids
  5053. * @private
  5054. */
  5055. ItemSet.prototype._onRemove = function _onRemove(ids) {
  5056. this._toQueue('remove', ids);
  5057. };
  5058. /**
  5059. * Put items in the queue to be added/updated/remove
  5060. * @param {String} action can be 'add', 'update', 'remove'
  5061. * @param {Number[]} ids
  5062. */
  5063. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  5064. var queue = this.queue;
  5065. ids.forEach(function (id) {
  5066. queue[id] = {
  5067. id: id,
  5068. action: action
  5069. };
  5070. });
  5071. if (this.controller) {
  5072. //this.requestReflow();
  5073. this.requestRepaint();
  5074. }
  5075. };
  5076. /**
  5077. * Calculate the scale and offset to convert a position on screen to the
  5078. * corresponding date and vice versa.
  5079. * After the method _updateConversion is executed once, the methods toTime
  5080. * and toScreen can be used.
  5081. * @private
  5082. */
  5083. ItemSet.prototype._updateConversion = function _updateConversion() {
  5084. var range = this.range;
  5085. if (!range) {
  5086. throw new Error('No range configured');
  5087. }
  5088. if (range.conversion) {
  5089. this.conversion = range.conversion(this.width);
  5090. }
  5091. else {
  5092. this.conversion = Range.conversion(range.start, range.end, this.width);
  5093. }
  5094. };
  5095. /**
  5096. * Convert a position on screen (pixels) to a datetime
  5097. * Before this method can be used, the method _updateConversion must be
  5098. * executed once.
  5099. * @param {int} x Position on the screen in pixels
  5100. * @return {Date} time The datetime the corresponds with given position x
  5101. */
  5102. ItemSet.prototype.toTime = function toTime(x) {
  5103. var conversion = this.conversion;
  5104. return new Date(x / conversion.scale + conversion.offset);
  5105. };
  5106. /**
  5107. * Convert a datetime (Date object) into a position on the screen
  5108. * Before this method can be used, the method _updateConversion must be
  5109. * executed once.
  5110. * @param {Date} time A date
  5111. * @return {int} x The position on the screen in pixels which corresponds
  5112. * with the given date.
  5113. */
  5114. ItemSet.prototype.toScreen = function toScreen(time) {
  5115. var conversion = this.conversion;
  5116. return (time.valueOf() - conversion.offset) * conversion.scale;
  5117. };
  5118. /**
  5119. * Start dragging the selected events
  5120. * @param {Event} event
  5121. * @private
  5122. */
  5123. ItemSet.prototype._onDragStart = function (event) {
  5124. if (!this.options.editable) {
  5125. return;
  5126. }
  5127. var item = ItemSet.itemFromTarget(event),
  5128. me = this;
  5129. if (item && item.selected) {
  5130. var dragLeftItem = event.target.dragLeftItem;
  5131. var dragRightItem = event.target.dragRightItem;
  5132. if (dragLeftItem) {
  5133. this.touchParams.itemProps = [{
  5134. item: dragLeftItem,
  5135. start: item.data.start.valueOf()
  5136. }];
  5137. }
  5138. else if (dragRightItem) {
  5139. this.touchParams.itemProps = [{
  5140. item: dragRightItem,
  5141. end: item.data.end.valueOf()
  5142. }];
  5143. }
  5144. else {
  5145. this.touchParams.itemProps = this.getSelection().map(function (id) {
  5146. var item = me.items[id];
  5147. var props = {
  5148. item: item
  5149. };
  5150. if ('start' in item.data) {
  5151. props.start = item.data.start.valueOf()
  5152. }
  5153. if ('end' in item.data) {
  5154. props.end = item.data.end.valueOf()
  5155. }
  5156. return props;
  5157. });
  5158. }
  5159. event.stopPropagation();
  5160. }
  5161. };
  5162. /**
  5163. * Drag selected items
  5164. * @param {Event} event
  5165. * @private
  5166. */
  5167. ItemSet.prototype._onDrag = function (event) {
  5168. if (this.touchParams.itemProps) {
  5169. var snap = this.options.snap || null,
  5170. deltaX = event.gesture.deltaX,
  5171. offset = deltaX / this.conversion.scale;
  5172. // move
  5173. this.touchParams.itemProps.forEach(function (props) {
  5174. if ('start' in props) {
  5175. var start = new Date(props.start + offset);
  5176. props.item.data.start = snap ? snap(start) : start;
  5177. }
  5178. if ('end' in props) {
  5179. var end = new Date(props.end + offset);
  5180. props.item.data.end = snap ? snap(end) : end;
  5181. }
  5182. });
  5183. // TODO: implement onMoving handler
  5184. // TODO: implement dragging from one group to another
  5185. this.requestReflow();
  5186. event.stopPropagation();
  5187. }
  5188. };
  5189. /**
  5190. * End of dragging selected items
  5191. * @param {Event} event
  5192. * @private
  5193. */
  5194. ItemSet.prototype._onDragEnd = function (event) {
  5195. if (this.touchParams.itemProps) {
  5196. // prepare a change set for the changed items
  5197. var changes = [],
  5198. me = this,
  5199. dataset = this._myDataSet(),
  5200. type;
  5201. this.touchParams.itemProps.forEach(function (props) {
  5202. var id = props.item.id,
  5203. item = me.itemsData.get(id);
  5204. var changed = false;
  5205. if ('start' in props.item.data) {
  5206. changed = (props.start != props.item.data.start.valueOf());
  5207. item.start = util.convert(props.item.data.start, dataset.convert['start']);
  5208. }
  5209. if ('end' in props.item.data) {
  5210. changed = changed || (props.end != props.item.data.end.valueOf());
  5211. item.end = util.convert(props.item.data.end, dataset.convert['end']);
  5212. }
  5213. // only apply changes when start or end is actually changed
  5214. if (changed) {
  5215. me.options.onMove(item, function (item) {
  5216. if (item) {
  5217. // apply changes
  5218. changes.push(item);
  5219. }
  5220. else {
  5221. // restore original values
  5222. if ('start' in props) props.item.data.start = props.start;
  5223. if ('end' in props) props.item.data.end = props.end;
  5224. me.requestReflow();
  5225. }
  5226. });
  5227. }
  5228. });
  5229. this.touchParams.itemProps = null;
  5230. // apply the changes to the data (if there are changes)
  5231. if (changes.length) {
  5232. dataset.update(changes);
  5233. }
  5234. event.stopPropagation();
  5235. }
  5236. };
  5237. /**
  5238. * Find an item from an event target:
  5239. * searches for the attribute 'timeline-item' in the event target's element tree
  5240. * @param {Event} event
  5241. * @return {Item | null} item
  5242. */
  5243. ItemSet.itemFromTarget = function itemFromTarget (event) {
  5244. var target = event.target;
  5245. while (target) {
  5246. if (target.hasOwnProperty('timeline-item')) {
  5247. return target['timeline-item'];
  5248. }
  5249. target = target.parentNode;
  5250. }
  5251. return null;
  5252. };
  5253. /**
  5254. * Find the ItemSet from an event target:
  5255. * searches for the attribute 'timeline-itemset' in the event target's element tree
  5256. * @param {Event} event
  5257. * @return {ItemSet | null} item
  5258. */
  5259. ItemSet.itemSetFromTarget = function itemSetFromTarget (event) {
  5260. var target = event.target;
  5261. while (target) {
  5262. if (target.hasOwnProperty('timeline-itemset')) {
  5263. return target['timeline-itemset'];
  5264. }
  5265. target = target.parentNode;
  5266. }
  5267. return null;
  5268. };
  5269. /**
  5270. * Find the DataSet to which this ItemSet is connected
  5271. * @returns {null | DataSet} dataset
  5272. * @private
  5273. */
  5274. ItemSet.prototype._myDataSet = function _myDataSet() {
  5275. // find the root DataSet
  5276. var dataset = this.itemsData;
  5277. while (dataset instanceof DataView) {
  5278. dataset = dataset.data;
  5279. }
  5280. return dataset;
  5281. };
  5282. /**
  5283. * @constructor Item
  5284. * @param {ItemSet} parent
  5285. * @param {Object} data Object containing (optional) parameters type,
  5286. * start, end, content, group, className.
  5287. * @param {Object} [options] Options to set initial property values
  5288. * @param {Object} [defaultOptions] default options
  5289. * // TODO: describe available options
  5290. */
  5291. function Item (parent, data, options, defaultOptions) {
  5292. this.parent = parent;
  5293. this.data = data;
  5294. this.dom = null;
  5295. this.options = options || {};
  5296. this.defaultOptions = defaultOptions || {};
  5297. this.selected = false;
  5298. this.visible = false;
  5299. this.top = 0;
  5300. this.left = 0;
  5301. this.width = 0;
  5302. this.height = 0;
  5303. this.offset = 0;
  5304. }
  5305. /**
  5306. * Select current item
  5307. */
  5308. Item.prototype.select = function select() {
  5309. this.selected = true;
  5310. if (this.visible) this.repaint();
  5311. };
  5312. /**
  5313. * Unselect current item
  5314. */
  5315. Item.prototype.unselect = function unselect() {
  5316. this.selected = false;
  5317. if (this.visible) this.repaint();
  5318. };
  5319. /**
  5320. * Show the Item in the DOM (when not already visible)
  5321. * @return {Boolean} changed
  5322. */
  5323. Item.prototype.show = function show() {
  5324. return false;
  5325. };
  5326. /**
  5327. * Hide the Item from the DOM (when visible)
  5328. * @return {Boolean} changed
  5329. */
  5330. Item.prototype.hide = function hide() {
  5331. return false;
  5332. };
  5333. /**
  5334. * Repaint the item
  5335. * @return {Boolean} changed
  5336. */
  5337. Item.prototype.repaint = function repaint() {
  5338. // should be implemented by the item
  5339. return false;
  5340. };
  5341. /**
  5342. * Reflow the item
  5343. * @return {Boolean} resized
  5344. */
  5345. Item.prototype.reflow = function reflow() {
  5346. // should be implemented by the item
  5347. return false;
  5348. };
  5349. /**
  5350. * Give the item a display offset in pixels
  5351. * @param {Number} offset Offset on screen in pixels
  5352. */
  5353. Item.prototype.setOffset = function setOffset(offset) {
  5354. this.offset = offset;
  5355. };
  5356. /**
  5357. * Repaint a delete button on the top right of the item when the item is selected
  5358. * @param {HTMLElement} anchor
  5359. * @private
  5360. */
  5361. Item.prototype._repaintDeleteButton = function (anchor) {
  5362. if (this.selected && this.options.editable && !this.dom.deleteButton) {
  5363. // create and show button
  5364. var parent = this.parent;
  5365. var id = this.id;
  5366. var deleteButton = document.createElement('div');
  5367. deleteButton.className = 'delete';
  5368. deleteButton.title = 'Delete this item';
  5369. Hammer(deleteButton, {
  5370. preventDefault: true
  5371. }).on('tap', function (event) {
  5372. parent.removeItem(id);
  5373. event.stopPropagation();
  5374. });
  5375. anchor.appendChild(deleteButton);
  5376. this.dom.deleteButton = deleteButton;
  5377. }
  5378. else if (!this.selected && this.dom.deleteButton) {
  5379. // remove button
  5380. if (this.dom.deleteButton.parentNode) {
  5381. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5382. }
  5383. this.dom.deleteButton = null;
  5384. }
  5385. };
  5386. /**
  5387. * @constructor ItemBox
  5388. * @extends Item
  5389. * @param {ItemSet} parent
  5390. * @param {Object} data Object containing parameters start
  5391. * content, className.
  5392. * @param {Object} [options] Options to set initial property values
  5393. * @param {Object} [defaultOptions] default options
  5394. * // TODO: describe available options
  5395. */
  5396. function ItemBox (parent, data, options, defaultOptions) {
  5397. this.props = {
  5398. dot: {
  5399. left: 0,
  5400. top: 0,
  5401. width: 0,
  5402. height: 0
  5403. },
  5404. line: {
  5405. top: 0,
  5406. left: 0,
  5407. width: 0,
  5408. height: 0
  5409. }
  5410. };
  5411. Item.call(this, parent, data, options, defaultOptions);
  5412. }
  5413. ItemBox.prototype = new Item (null, null);
  5414. /**
  5415. * Repaint the item
  5416. * @return {Boolean} changed
  5417. */
  5418. ItemBox.prototype.repaint = function repaint() {
  5419. // TODO: make an efficient repaint
  5420. var changed = false;
  5421. var dom = this.dom;
  5422. if (!dom) {
  5423. this._create();
  5424. dom = this.dom;
  5425. changed = true;
  5426. }
  5427. if (dom) {
  5428. if (!this.parent) {
  5429. throw new Error('Cannot repaint item: no parent attached');
  5430. }
  5431. if (!dom.box.parentNode) {
  5432. var foreground = this.parent.getForeground();
  5433. if (!foreground) {
  5434. throw new Error('Cannot repaint time axis: ' +
  5435. 'parent has no foreground container element');
  5436. }
  5437. foreground.appendChild(dom.box);
  5438. changed = true;
  5439. }
  5440. if (!dom.line.parentNode) {
  5441. var background = this.parent.getBackground();
  5442. if (!background) {
  5443. throw new Error('Cannot repaint time axis: ' +
  5444. 'parent has no background container element');
  5445. }
  5446. background.appendChild(dom.line);
  5447. changed = true;
  5448. }
  5449. if (!dom.dot.parentNode) {
  5450. var axis = this.parent.getAxis();
  5451. if (!background) {
  5452. throw new Error('Cannot repaint time axis: ' +
  5453. 'parent has no axis container element');
  5454. }
  5455. axis.appendChild(dom.dot);
  5456. changed = true;
  5457. }
  5458. this._repaintDeleteButton(dom.box);
  5459. // update contents
  5460. if (this.data.content != this.content) {
  5461. this.content = this.data.content;
  5462. if (this.content instanceof Element) {
  5463. dom.content.innerHTML = '';
  5464. dom.content.appendChild(this.content);
  5465. }
  5466. else if (this.data.content != undefined) {
  5467. dom.content.innerHTML = this.content;
  5468. }
  5469. else {
  5470. throw new Error('Property "content" missing in item ' + this.data.id);
  5471. }
  5472. changed = true;
  5473. }
  5474. // update class
  5475. var className = (this.data.className? ' ' + this.data.className : '') +
  5476. (this.selected ? ' selected' : '');
  5477. if (this.className != className) {
  5478. this.className = className;
  5479. dom.box.className = 'item box' + className;
  5480. dom.line.className = 'item line' + className;
  5481. dom.dot.className = 'item dot' + className;
  5482. changed = true;
  5483. }
  5484. }
  5485. return changed;
  5486. };
  5487. /**
  5488. * Show the item in the DOM (when not already visible). The items DOM will
  5489. * be created when needed.
  5490. * @return {Boolean} changed
  5491. */
  5492. ItemBox.prototype.show = function show() {
  5493. if (!this.dom || !this.dom.box.parentNode) {
  5494. return this.repaint();
  5495. }
  5496. else {
  5497. return false;
  5498. }
  5499. };
  5500. /**
  5501. * Hide the item from the DOM (when visible)
  5502. * @return {Boolean} changed
  5503. */
  5504. ItemBox.prototype.hide = function hide() {
  5505. var changed = false,
  5506. dom = this.dom;
  5507. if (dom) {
  5508. if (dom.box.parentNode) {
  5509. dom.box.parentNode.removeChild(dom.box);
  5510. changed = true;
  5511. }
  5512. if (dom.line.parentNode) {
  5513. dom.line.parentNode.removeChild(dom.line);
  5514. }
  5515. if (dom.dot.parentNode) {
  5516. dom.dot.parentNode.removeChild(dom.dot);
  5517. }
  5518. }
  5519. return changed;
  5520. };
  5521. /**
  5522. * Reflow the item: calculate its actual size and position from the DOM
  5523. * @return {boolean} resized returns true if the axis is resized
  5524. * @override
  5525. */
  5526. ItemBox.prototype.reflow = function reflow() {
  5527. var changed = 0,
  5528. update,
  5529. dom,
  5530. props,
  5531. options,
  5532. margin,
  5533. start,
  5534. align,
  5535. orientation,
  5536. top,
  5537. left,
  5538. data,
  5539. range;
  5540. if (this.data.start == undefined) {
  5541. throw new Error('Property "start" missing in item ' + this.data.id);
  5542. }
  5543. data = this.data;
  5544. range = this.parent && this.parent.range;
  5545. if (data && range) {
  5546. // TODO: account for the width of the item
  5547. var interval = (range.end - range.start);
  5548. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  5549. }
  5550. else {
  5551. this.visible = false;
  5552. }
  5553. if (this.visible) {
  5554. dom = this.dom;
  5555. if (dom) {
  5556. update = util.updateProperty;
  5557. props = this.props;
  5558. options = this.options;
  5559. start = this.parent.toScreen(this.data.start) + this.offset;
  5560. align = options.align || this.defaultOptions.align;
  5561. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5562. orientation = options.orientation || this.defaultOptions.orientation;
  5563. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5564. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5565. changed += update(props.line, 'width', dom.line.offsetWidth);
  5566. changed += update(props.line, 'height', dom.line.offsetHeight);
  5567. changed += update(props.line, 'top', dom.line.offsetTop);
  5568. changed += update(this, 'width', dom.box.offsetWidth);
  5569. changed += update(this, 'height', dom.box.offsetHeight);
  5570. if (align == 'right') {
  5571. left = start - this.width;
  5572. }
  5573. else if (align == 'left') {
  5574. left = start;
  5575. }
  5576. else {
  5577. // default or 'center'
  5578. left = start - this.width / 2;
  5579. }
  5580. changed += update(this, 'left', left);
  5581. changed += update(props.line, 'left', start - props.line.width / 2);
  5582. changed += update(props.dot, 'left', start - props.dot.width / 2);
  5583. changed += update(props.dot, 'top', -props.dot.height / 2);
  5584. if (orientation == 'top') {
  5585. top = margin;
  5586. changed += update(this, 'top', top);
  5587. }
  5588. else {
  5589. // default or 'bottom'
  5590. var parentHeight = this.parent.height;
  5591. top = parentHeight - this.height - margin;
  5592. changed += update(this, 'top', top);
  5593. }
  5594. }
  5595. else {
  5596. changed += 1;
  5597. }
  5598. }
  5599. return (changed > 0);
  5600. };
  5601. /**
  5602. * Create an items DOM
  5603. * @private
  5604. */
  5605. ItemBox.prototype._create = function _create() {
  5606. var dom = this.dom;
  5607. if (!dom) {
  5608. this.dom = dom = {};
  5609. // create the box
  5610. dom.box = document.createElement('DIV');
  5611. // className is updated in repaint()
  5612. // contents box (inside the background box). used for making margins
  5613. dom.content = document.createElement('DIV');
  5614. dom.content.className = 'content';
  5615. dom.box.appendChild(dom.content);
  5616. // line to axis
  5617. dom.line = document.createElement('DIV');
  5618. dom.line.className = 'line';
  5619. // dot on axis
  5620. dom.dot = document.createElement('DIV');
  5621. dom.dot.className = 'dot';
  5622. // attach this item as attribute
  5623. dom.box['timeline-item'] = this;
  5624. }
  5625. };
  5626. /**
  5627. * Reposition the item, recalculate its left, top, and width, using the current
  5628. * range and size of the items itemset
  5629. * @override
  5630. */
  5631. ItemBox.prototype.reposition = function reposition() {
  5632. var dom = this.dom,
  5633. props = this.props,
  5634. orientation = this.options.orientation || this.defaultOptions.orientation;
  5635. if (dom) {
  5636. var box = dom.box,
  5637. line = dom.line,
  5638. dot = dom.dot;
  5639. box.style.left = this.left + 'px';
  5640. box.style.top = this.top + 'px';
  5641. line.style.left = props.line.left + 'px';
  5642. if (orientation == 'top') {
  5643. line.style.top = 0 + 'px';
  5644. line.style.height = this.top + 'px';
  5645. }
  5646. else {
  5647. // orientation 'bottom'
  5648. line.style.top = (this.top + this.height) + 'px';
  5649. line.style.height = Math.max(this.parent.height - this.top - this.height +
  5650. this.props.dot.height / 2, 0) + 'px';
  5651. }
  5652. dot.style.left = props.dot.left + 'px';
  5653. dot.style.top = props.dot.top + 'px';
  5654. }
  5655. };
  5656. /**
  5657. * @constructor ItemPoint
  5658. * @extends Item
  5659. * @param {ItemSet} parent
  5660. * @param {Object} data Object containing parameters start
  5661. * content, className.
  5662. * @param {Object} [options] Options to set initial property values
  5663. * @param {Object} [defaultOptions] default options
  5664. * // TODO: describe available options
  5665. */
  5666. function ItemPoint (parent, data, options, defaultOptions) {
  5667. this.props = {
  5668. dot: {
  5669. top: 0,
  5670. width: 0,
  5671. height: 0
  5672. },
  5673. content: {
  5674. height: 0,
  5675. marginLeft: 0
  5676. }
  5677. };
  5678. Item.call(this, parent, data, options, defaultOptions);
  5679. }
  5680. ItemPoint.prototype = new Item (null, null);
  5681. /**
  5682. * Repaint the item
  5683. * @return {Boolean} changed
  5684. */
  5685. ItemPoint.prototype.repaint = function repaint() {
  5686. // TODO: make an efficient repaint
  5687. var changed = false;
  5688. var dom = this.dom;
  5689. if (!dom) {
  5690. this._create();
  5691. dom = this.dom;
  5692. changed = true;
  5693. }
  5694. if (dom) {
  5695. if (!this.parent) {
  5696. throw new Error('Cannot repaint item: no parent attached');
  5697. }
  5698. var foreground = this.parent.getForeground();
  5699. if (!foreground) {
  5700. throw new Error('Cannot repaint time axis: ' +
  5701. 'parent has no foreground container element');
  5702. }
  5703. if (!dom.point.parentNode) {
  5704. foreground.appendChild(dom.point);
  5705. foreground.appendChild(dom.point);
  5706. changed = true;
  5707. }
  5708. // update contents
  5709. if (this.data.content != this.content) {
  5710. this.content = this.data.content;
  5711. if (this.content instanceof Element) {
  5712. dom.content.innerHTML = '';
  5713. dom.content.appendChild(this.content);
  5714. }
  5715. else if (this.data.content != undefined) {
  5716. dom.content.innerHTML = this.content;
  5717. }
  5718. else {
  5719. throw new Error('Property "content" missing in item ' + this.data.id);
  5720. }
  5721. changed = true;
  5722. }
  5723. this._repaintDeleteButton(dom.point);
  5724. // update class
  5725. var className = (this.data.className? ' ' + this.data.className : '') +
  5726. (this.selected ? ' selected' : '');
  5727. if (this.className != className) {
  5728. this.className = className;
  5729. dom.point.className = 'item point' + className;
  5730. changed = true;
  5731. }
  5732. }
  5733. return changed;
  5734. };
  5735. /**
  5736. * Show the item in the DOM (when not already visible). The items DOM will
  5737. * be created when needed.
  5738. * @return {Boolean} changed
  5739. */
  5740. ItemPoint.prototype.show = function show() {
  5741. if (!this.dom || !this.dom.point.parentNode) {
  5742. return this.repaint();
  5743. }
  5744. else {
  5745. return false;
  5746. }
  5747. };
  5748. /**
  5749. * Hide the item from the DOM (when visible)
  5750. * @return {Boolean} changed
  5751. */
  5752. ItemPoint.prototype.hide = function hide() {
  5753. var changed = false,
  5754. dom = this.dom;
  5755. if (dom) {
  5756. if (dom.point.parentNode) {
  5757. dom.point.parentNode.removeChild(dom.point);
  5758. changed = true;
  5759. }
  5760. }
  5761. return changed;
  5762. };
  5763. /**
  5764. * Reflow the item: calculate its actual size from the DOM
  5765. * @return {boolean} resized returns true if the axis is resized
  5766. * @override
  5767. */
  5768. ItemPoint.prototype.reflow = function reflow() {
  5769. var changed = 0,
  5770. update,
  5771. dom,
  5772. props,
  5773. options,
  5774. margin,
  5775. orientation,
  5776. start,
  5777. top,
  5778. data,
  5779. range;
  5780. if (this.data.start == undefined) {
  5781. throw new Error('Property "start" missing in item ' + this.data.id);
  5782. }
  5783. data = this.data;
  5784. range = this.parent && this.parent.range;
  5785. if (data && range) {
  5786. // TODO: account for the width of the item
  5787. var interval = (range.end - range.start);
  5788. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  5789. }
  5790. else {
  5791. this.visible = false;
  5792. }
  5793. if (this.visible) {
  5794. dom = this.dom;
  5795. if (dom) {
  5796. update = util.updateProperty;
  5797. props = this.props;
  5798. options = this.options;
  5799. orientation = options.orientation || this.defaultOptions.orientation;
  5800. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5801. start = this.parent.toScreen(this.data.start) + this.offset;
  5802. changed += update(this, 'width', dom.point.offsetWidth);
  5803. changed += update(this, 'height', dom.point.offsetHeight);
  5804. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5805. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5806. changed += update(props.content, 'height', dom.content.offsetHeight);
  5807. if (orientation == 'top') {
  5808. top = margin;
  5809. }
  5810. else {
  5811. // default or 'bottom'
  5812. var parentHeight = this.parent.height;
  5813. top = Math.max(parentHeight - this.height - margin, 0);
  5814. }
  5815. changed += update(this, 'top', top);
  5816. changed += update(this, 'left', start - props.dot.width / 2);
  5817. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5818. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5819. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5820. }
  5821. else {
  5822. changed += 1;
  5823. }
  5824. }
  5825. return (changed > 0);
  5826. };
  5827. /**
  5828. * Create an items DOM
  5829. * @private
  5830. */
  5831. ItemPoint.prototype._create = function _create() {
  5832. var dom = this.dom;
  5833. if (!dom) {
  5834. this.dom = dom = {};
  5835. // background box
  5836. dom.point = document.createElement('div');
  5837. // className is updated in repaint()
  5838. // contents box, right from the dot
  5839. dom.content = document.createElement('div');
  5840. dom.content.className = 'content';
  5841. dom.point.appendChild(dom.content);
  5842. // dot at start
  5843. dom.dot = document.createElement('div');
  5844. dom.dot.className = 'dot';
  5845. dom.point.appendChild(dom.dot);
  5846. // attach this item as attribute
  5847. dom.point['timeline-item'] = this;
  5848. }
  5849. };
  5850. /**
  5851. * Reposition the item, recalculate its left, top, and width, using the current
  5852. * range and size of the items itemset
  5853. * @override
  5854. */
  5855. ItemPoint.prototype.reposition = function reposition() {
  5856. var dom = this.dom,
  5857. props = this.props;
  5858. if (dom) {
  5859. dom.point.style.top = this.top + 'px';
  5860. dom.point.style.left = this.left + 'px';
  5861. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5862. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5863. dom.dot.style.top = props.dot.top + 'px';
  5864. }
  5865. };
  5866. /**
  5867. * @constructor ItemRange
  5868. * @extends Item
  5869. * @param {ItemSet} parent
  5870. * @param {Object} data Object containing parameters start, end
  5871. * content, className.
  5872. * @param {Object} [options] Options to set initial property values
  5873. * @param {Object} [defaultOptions] default options
  5874. * // TODO: describe available options
  5875. */
  5876. function ItemRange (parent, data, options, defaultOptions) {
  5877. this.props = {
  5878. content: {
  5879. left: 0,
  5880. width: 0
  5881. }
  5882. };
  5883. Item.call(this, parent, data, options, defaultOptions);
  5884. }
  5885. ItemRange.prototype = new Item (null, null);
  5886. /**
  5887. * Repaint the item
  5888. * @return {Boolean} changed
  5889. */
  5890. ItemRange.prototype.repaint = function repaint() {
  5891. // TODO: make an efficient repaint
  5892. var changed = false;
  5893. var dom = this.dom;
  5894. if (!dom) {
  5895. this._create();
  5896. dom = this.dom;
  5897. changed = true;
  5898. }
  5899. if (dom) {
  5900. if (!this.parent) {
  5901. throw new Error('Cannot repaint item: no parent attached');
  5902. }
  5903. var foreground = this.parent.getForeground();
  5904. if (!foreground) {
  5905. throw new Error('Cannot repaint time axis: ' +
  5906. 'parent has no foreground container element');
  5907. }
  5908. if (!dom.box.parentNode) {
  5909. foreground.appendChild(dom.box);
  5910. changed = true;
  5911. }
  5912. // update content
  5913. if (this.data.content != this.content) {
  5914. this.content = this.data.content;
  5915. if (this.content instanceof Element) {
  5916. dom.content.innerHTML = '';
  5917. dom.content.appendChild(this.content);
  5918. }
  5919. else if (this.data.content != undefined) {
  5920. dom.content.innerHTML = this.content;
  5921. }
  5922. else {
  5923. throw new Error('Property "content" missing in item ' + this.data.id);
  5924. }
  5925. changed = true;
  5926. }
  5927. this._repaintDeleteButton(dom.box);
  5928. this._repaintDragLeft();
  5929. this._repaintDragRight();
  5930. // update class
  5931. var className = (this.data.className ? (' ' + this.data.className) : '') +
  5932. (this.selected ? ' selected' : '');
  5933. if (this.className != className) {
  5934. this.className = className;
  5935. dom.box.className = 'item range' + className;
  5936. changed = true;
  5937. }
  5938. }
  5939. return changed;
  5940. };
  5941. /**
  5942. * Show the item in the DOM (when not already visible). The items DOM will
  5943. * be created when needed.
  5944. * @return {Boolean} changed
  5945. */
  5946. ItemRange.prototype.show = function show() {
  5947. if (!this.dom || !this.dom.box.parentNode) {
  5948. return this.repaint();
  5949. }
  5950. else {
  5951. return false;
  5952. }
  5953. };
  5954. /**
  5955. * Hide the item from the DOM (when visible)
  5956. * @return {Boolean} changed
  5957. */
  5958. ItemRange.prototype.hide = function hide() {
  5959. var changed = false,
  5960. dom = this.dom;
  5961. if (dom) {
  5962. if (dom.box.parentNode) {
  5963. dom.box.parentNode.removeChild(dom.box);
  5964. changed = true;
  5965. }
  5966. }
  5967. return changed;
  5968. };
  5969. /**
  5970. * Reflow the item: calculate its actual size from the DOM
  5971. * @return {boolean} resized returns true if the axis is resized
  5972. * @override
  5973. */
  5974. ItemRange.prototype.reflow = function reflow() {
  5975. var changed = 0,
  5976. dom,
  5977. props,
  5978. options,
  5979. margin,
  5980. padding,
  5981. parent,
  5982. start,
  5983. end,
  5984. data,
  5985. range,
  5986. update,
  5987. box,
  5988. parentWidth,
  5989. contentLeft,
  5990. orientation,
  5991. top;
  5992. if (this.data.start == undefined) {
  5993. throw new Error('Property "start" missing in item ' + this.data.id);
  5994. }
  5995. if (this.data.end == undefined) {
  5996. throw new Error('Property "end" missing in item ' + this.data.id);
  5997. }
  5998. data = this.data;
  5999. range = this.parent && this.parent.range;
  6000. if (data && range) {
  6001. // TODO: account for the width of the item. Take some margin
  6002. this.visible = (data.start < range.end) && (data.end > range.start);
  6003. }
  6004. else {
  6005. this.visible = false;
  6006. }
  6007. if (this.visible) {
  6008. dom = this.dom;
  6009. if (dom) {
  6010. props = this.props;
  6011. options = this.options;
  6012. parent = this.parent;
  6013. start = parent.toScreen(this.data.start) + this.offset;
  6014. end = parent.toScreen(this.data.end) + this.offset;
  6015. update = util.updateProperty;
  6016. box = dom.box;
  6017. parentWidth = parent.width;
  6018. orientation = options.orientation || this.defaultOptions.orientation;
  6019. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  6020. padding = options.padding || this.defaultOptions.padding;
  6021. changed += update(props.content, 'width', dom.content.offsetWidth);
  6022. changed += update(this, 'height', box.offsetHeight);
  6023. // limit the width of the this, as browsers cannot draw very wide divs
  6024. if (start < -parentWidth) {
  6025. start = -parentWidth;
  6026. }
  6027. if (end > 2 * parentWidth) {
  6028. end = 2 * parentWidth;
  6029. }
  6030. // when range exceeds left of the window, position the contents at the left of the visible area
  6031. if (start < 0) {
  6032. contentLeft = Math.min(-start,
  6033. (end - start - props.content.width - 2 * padding));
  6034. // TODO: remove the need for options.padding. it's terrible.
  6035. }
  6036. else {
  6037. contentLeft = 0;
  6038. }
  6039. changed += update(props.content, 'left', contentLeft);
  6040. if (orientation == 'top') {
  6041. top = margin;
  6042. changed += update(this, 'top', top);
  6043. }
  6044. else {
  6045. // default or 'bottom'
  6046. top = parent.height - this.height - margin;
  6047. changed += update(this, 'top', top);
  6048. }
  6049. changed += update(this, 'left', start);
  6050. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  6051. }
  6052. else {
  6053. changed += 1;
  6054. }
  6055. }
  6056. return (changed > 0);
  6057. };
  6058. /**
  6059. * Create an items DOM
  6060. * @private
  6061. */
  6062. ItemRange.prototype._create = function _create() {
  6063. var dom = this.dom;
  6064. if (!dom) {
  6065. this.dom = dom = {};
  6066. // background box
  6067. dom.box = document.createElement('div');
  6068. // className is updated in repaint()
  6069. // contents box
  6070. dom.content = document.createElement('div');
  6071. dom.content.className = 'content';
  6072. dom.box.appendChild(dom.content);
  6073. // attach this item as attribute
  6074. dom.box['timeline-item'] = this;
  6075. }
  6076. };
  6077. /**
  6078. * Reposition the item, recalculate its left, top, and width, using the current
  6079. * range and size of the items itemset
  6080. * @override
  6081. */
  6082. ItemRange.prototype.reposition = function reposition() {
  6083. var dom = this.dom,
  6084. props = this.props;
  6085. if (dom) {
  6086. dom.box.style.top = this.top + 'px';
  6087. dom.box.style.left = this.left + 'px';
  6088. dom.box.style.width = this.width + 'px';
  6089. dom.content.style.left = props.content.left + 'px';
  6090. }
  6091. };
  6092. /**
  6093. * Repaint a drag area on the left side of the range when the range is selected
  6094. * @private
  6095. */
  6096. ItemRange.prototype._repaintDragLeft = function () {
  6097. if (this.selected && this.options.editable && !this.dom.dragLeft) {
  6098. // create and show drag area
  6099. var dragLeft = document.createElement('div');
  6100. dragLeft.className = 'drag-left';
  6101. dragLeft.dragLeftItem = this;
  6102. // TODO: this should be redundant?
  6103. Hammer(dragLeft, {
  6104. preventDefault: true
  6105. }).on('drag', function () {
  6106. //console.log('drag left')
  6107. });
  6108. this.dom.box.appendChild(dragLeft);
  6109. this.dom.dragLeft = dragLeft;
  6110. }
  6111. else if (!this.selected && this.dom.dragLeft) {
  6112. // delete drag area
  6113. if (this.dom.dragLeft.parentNode) {
  6114. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  6115. }
  6116. this.dom.dragLeft = null;
  6117. }
  6118. };
  6119. /**
  6120. * Repaint a drag area on the right side of the range when the range is selected
  6121. * @private
  6122. */
  6123. ItemRange.prototype._repaintDragRight = function () {
  6124. if (this.selected && this.options.editable && !this.dom.dragRight) {
  6125. // create and show drag area
  6126. var dragRight = document.createElement('div');
  6127. dragRight.className = 'drag-right';
  6128. dragRight.dragRightItem = this;
  6129. // TODO: this should be redundant?
  6130. Hammer(dragRight, {
  6131. preventDefault: true
  6132. }).on('drag', function () {
  6133. //console.log('drag right')
  6134. });
  6135. this.dom.box.appendChild(dragRight);
  6136. this.dom.dragRight = dragRight;
  6137. }
  6138. else if (!this.selected && this.dom.dragRight) {
  6139. // delete drag area
  6140. if (this.dom.dragRight.parentNode) {
  6141. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  6142. }
  6143. this.dom.dragRight = null;
  6144. }
  6145. };
  6146. /**
  6147. * @constructor ItemRangeOverflow
  6148. * @extends ItemRange
  6149. * @param {ItemSet} parent
  6150. * @param {Object} data Object containing parameters start, end
  6151. * content, className.
  6152. * @param {Object} [options] Options to set initial property values
  6153. * @param {Object} [defaultOptions] default options
  6154. * // TODO: describe available options
  6155. */
  6156. function ItemRangeOverflow (parent, data, options, defaultOptions) {
  6157. this.props = {
  6158. content: {
  6159. left: 0,
  6160. width: 0
  6161. }
  6162. };
  6163. // define a private property _width, which is the with of the range box
  6164. // adhering to the ranges start and end date. The property width has a
  6165. // getter which returns the max of border width and content width
  6166. this._width = 0;
  6167. Object.defineProperty(this, 'width', {
  6168. get: function () {
  6169. return (this.props.content && this._width < this.props.content.width) ?
  6170. this.props.content.width :
  6171. this._width;
  6172. },
  6173. set: function (width) {
  6174. this._width = width;
  6175. }
  6176. });
  6177. ItemRange.call(this, parent, data, options, defaultOptions);
  6178. }
  6179. ItemRangeOverflow.prototype = new ItemRange (null, null);
  6180. /**
  6181. * Repaint the item
  6182. * @return {Boolean} changed
  6183. */
  6184. ItemRangeOverflow.prototype.repaint = function repaint() {
  6185. // TODO: make an efficient repaint
  6186. var changed = false;
  6187. var dom = this.dom;
  6188. if (!dom) {
  6189. this._create();
  6190. dom = this.dom;
  6191. changed = true;
  6192. }
  6193. if (dom) {
  6194. if (!this.parent) {
  6195. throw new Error('Cannot repaint item: no parent attached');
  6196. }
  6197. var foreground = this.parent.getForeground();
  6198. if (!foreground) {
  6199. throw new Error('Cannot repaint time axis: ' +
  6200. 'parent has no foreground container element');
  6201. }
  6202. if (!dom.box.parentNode) {
  6203. foreground.appendChild(dom.box);
  6204. changed = true;
  6205. }
  6206. // update content
  6207. if (this.data.content != this.content) {
  6208. this.content = this.data.content;
  6209. if (this.content instanceof Element) {
  6210. dom.content.innerHTML = '';
  6211. dom.content.appendChild(this.content);
  6212. }
  6213. else if (this.data.content != undefined) {
  6214. dom.content.innerHTML = this.content;
  6215. }
  6216. else {
  6217. throw new Error('Property "content" missing in item ' + this.id);
  6218. }
  6219. changed = true;
  6220. }
  6221. this._repaintDeleteButton(dom.box);
  6222. this._repaintDragLeft();
  6223. this._repaintDragRight();
  6224. // update class
  6225. var className = (this.data.className? ' ' + this.data.className : '') +
  6226. (this.selected ? ' selected' : '');
  6227. if (this.className != className) {
  6228. this.className = className;
  6229. dom.box.className = 'item rangeoverflow' + className;
  6230. changed = true;
  6231. }
  6232. }
  6233. return changed;
  6234. };
  6235. /**
  6236. * Reposition the item, recalculate its left, top, and width, using the current
  6237. * range and size of the items itemset
  6238. * @override
  6239. */
  6240. ItemRangeOverflow.prototype.reposition = function reposition() {
  6241. var dom = this.dom,
  6242. props = this.props;
  6243. if (dom) {
  6244. dom.box.style.top = this.top + 'px';
  6245. dom.box.style.left = this.left + 'px';
  6246. dom.box.style.width = this._width + 'px';
  6247. dom.content.style.left = props.content.left + 'px';
  6248. }
  6249. };
  6250. /**
  6251. * @constructor Group
  6252. * @param {GroupSet} parent
  6253. * @param {Number | String} groupId
  6254. * @param {Object} [options] Options to set initial property values
  6255. * // TODO: describe available options
  6256. * @extends Component
  6257. */
  6258. function Group (parent, groupId, options) {
  6259. this.id = util.randomUUID();
  6260. this.parent = parent;
  6261. this.groupId = groupId;
  6262. this.itemset = null; // ItemSet
  6263. this.options = options || {};
  6264. this.options.top = 0;
  6265. this.props = {
  6266. label: {
  6267. width: 0,
  6268. height: 0
  6269. }
  6270. };
  6271. this.top = 0;
  6272. this.left = 0;
  6273. this.width = 0;
  6274. this.height = 0;
  6275. }
  6276. Group.prototype = new Component();
  6277. // TODO: comment
  6278. Group.prototype.setOptions = Component.prototype.setOptions;
  6279. /**
  6280. * Get the container element of the panel, which can be used by a child to
  6281. * add its own widgets.
  6282. * @returns {HTMLElement} container
  6283. */
  6284. Group.prototype.getContainer = function () {
  6285. return this.parent.getContainer();
  6286. };
  6287. /**
  6288. * Set item set for the group. The group will create a view on the itemset,
  6289. * filtered by the groups id.
  6290. * @param {DataSet | DataView} items
  6291. */
  6292. Group.prototype.setItems = function setItems(items) {
  6293. if (this.itemset) {
  6294. // remove current item set
  6295. this.itemset.hide();
  6296. this.itemset.setItems();
  6297. this.parent.controller.remove(this.itemset);
  6298. this.itemset = null;
  6299. }
  6300. if (items) {
  6301. var groupId = this.groupId;
  6302. var itemsetOptions = Object.create(this.options);
  6303. this.itemset = new ItemSet(this, null, itemsetOptions);
  6304. this.itemset.setRange(this.parent.range);
  6305. this.view = new DataView(items, {
  6306. filter: function (item) {
  6307. return item.group == groupId;
  6308. }
  6309. });
  6310. this.itemset.setItems(this.view);
  6311. this.parent.controller.add(this.itemset);
  6312. }
  6313. };
  6314. /**
  6315. * Set selected items by their id. Replaces the current selection.
  6316. * Unknown id's are silently ignored.
  6317. * @param {Array} [ids] An array with zero or more id's of the items to be
  6318. * selected. If ids is an empty array, all items will be
  6319. * unselected.
  6320. */
  6321. Group.prototype.setSelection = function setSelection(ids) {
  6322. if (this.itemset) this.itemset.setSelection(ids);
  6323. };
  6324. /**
  6325. * Get the selected items by their id
  6326. * @return {Array} ids The ids of the selected items
  6327. */
  6328. Group.prototype.getSelection = function getSelection() {
  6329. return this.itemset ? this.itemset.getSelection() : [];
  6330. };
  6331. /**
  6332. * Repaint the item
  6333. * @return {Boolean} changed
  6334. */
  6335. Group.prototype.repaint = function repaint() {
  6336. return false;
  6337. };
  6338. /**
  6339. * Reflow the item
  6340. * @return {Boolean} resized
  6341. */
  6342. Group.prototype.reflow = function reflow() {
  6343. var changed = 0,
  6344. update = util.updateProperty;
  6345. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  6346. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  6347. // TODO: reckon with the height of the group label
  6348. if (this.label) {
  6349. var inner = this.label.firstChild;
  6350. changed += update(this.props.label, 'width', inner.clientWidth);
  6351. changed += update(this.props.label, 'height', inner.clientHeight);
  6352. }
  6353. else {
  6354. changed += update(this.props.label, 'width', 0);
  6355. changed += update(this.props.label, 'height', 0);
  6356. }
  6357. return (changed > 0);
  6358. };
  6359. /**
  6360. * An GroupSet holds a set of groups
  6361. * @param {Component} parent
  6362. * @param {Component[]} [depends] Components on which this components depends
  6363. * (except for the parent)
  6364. * @param {Object} [options] See GroupSet.setOptions for the available
  6365. * options.
  6366. * @constructor GroupSet
  6367. * @extends Panel
  6368. */
  6369. function GroupSet(parent, depends, options) {
  6370. this.id = util.randomUUID();
  6371. this.parent = parent;
  6372. this.depends = depends;
  6373. this.options = options || {};
  6374. this.range = null; // Range or Object {start: number, end: number}
  6375. this.itemsData = null; // DataSet with items
  6376. this.groupsData = null; // DataSet with groups
  6377. this.groups = {}; // map with groups
  6378. this.dom = {};
  6379. this.props = {
  6380. labels: {
  6381. width: 0
  6382. }
  6383. };
  6384. // TODO: implement right orientation of the labels
  6385. // changes in groups are queued key/value map containing id/action
  6386. this.queue = {};
  6387. var me = this;
  6388. this.listeners = {
  6389. 'add': function (event, params) {
  6390. me._onAdd(params.items);
  6391. },
  6392. 'update': function (event, params) {
  6393. me._onUpdate(params.items);
  6394. },
  6395. 'remove': function (event, params) {
  6396. me._onRemove(params.items);
  6397. }
  6398. };
  6399. }
  6400. GroupSet.prototype = new Panel();
  6401. /**
  6402. * Set options for the GroupSet. Existing options will be extended/overwritten.
  6403. * @param {Object} [options] The following options are available:
  6404. * {String | function} groupsOrder
  6405. * TODO: describe options
  6406. */
  6407. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  6408. GroupSet.prototype.setRange = function (range) {
  6409. // TODO: implement setRange
  6410. };
  6411. /**
  6412. * Set items
  6413. * @param {vis.DataSet | null} items
  6414. */
  6415. GroupSet.prototype.setItems = function setItems(items) {
  6416. this.itemsData = items;
  6417. for (var id in this.groups) {
  6418. if (this.groups.hasOwnProperty(id)) {
  6419. var group = this.groups[id];
  6420. group.setItems(items);
  6421. }
  6422. }
  6423. };
  6424. /**
  6425. * Get items
  6426. * @return {vis.DataSet | null} items
  6427. */
  6428. GroupSet.prototype.getItems = function getItems() {
  6429. return this.itemsData;
  6430. };
  6431. /**
  6432. * Set range (start and end).
  6433. * @param {Range | Object} range A Range or an object containing start and end.
  6434. */
  6435. GroupSet.prototype.setRange = function setRange(range) {
  6436. this.range = range;
  6437. };
  6438. /**
  6439. * Set groups
  6440. * @param {vis.DataSet} groups
  6441. */
  6442. GroupSet.prototype.setGroups = function setGroups(groups) {
  6443. var me = this,
  6444. ids;
  6445. // unsubscribe from current dataset
  6446. if (this.groupsData) {
  6447. util.forEach(this.listeners, function (callback, event) {
  6448. me.groupsData.unsubscribe(event, callback);
  6449. });
  6450. // remove all drawn groups
  6451. ids = this.groupsData.getIds();
  6452. this._onRemove(ids);
  6453. }
  6454. // replace the dataset
  6455. if (!groups) {
  6456. this.groupsData = null;
  6457. }
  6458. else if (groups instanceof DataSet) {
  6459. this.groupsData = groups;
  6460. }
  6461. else {
  6462. this.groupsData = new DataSet({
  6463. convert: {
  6464. start: 'Date',
  6465. end: 'Date'
  6466. }
  6467. });
  6468. this.groupsData.add(groups);
  6469. }
  6470. if (this.groupsData) {
  6471. // subscribe to new dataset
  6472. var id = this.id;
  6473. util.forEach(this.listeners, function (callback, event) {
  6474. me.groupsData.on(event, callback, id);
  6475. });
  6476. // draw all new groups
  6477. ids = this.groupsData.getIds();
  6478. this._onAdd(ids);
  6479. }
  6480. };
  6481. /**
  6482. * Get groups
  6483. * @return {vis.DataSet | null} groups
  6484. */
  6485. GroupSet.prototype.getGroups = function getGroups() {
  6486. return this.groupsData;
  6487. };
  6488. /**
  6489. * Set selected items by their id. Replaces the current selection.
  6490. * Unknown id's are silently ignored.
  6491. * @param {Array} [ids] An array with zero or more id's of the items to be
  6492. * selected. If ids is an empty array, all items will be
  6493. * unselected.
  6494. */
  6495. GroupSet.prototype.setSelection = function setSelection(ids) {
  6496. var selection = [],
  6497. groups = this.groups;
  6498. // iterate over each of the groups
  6499. for (var id in groups) {
  6500. if (groups.hasOwnProperty(id)) {
  6501. var group = groups[id];
  6502. group.setSelection(ids);
  6503. }
  6504. }
  6505. return selection;
  6506. };
  6507. /**
  6508. * Get the selected items by their id
  6509. * @return {Array} ids The ids of the selected items
  6510. */
  6511. GroupSet.prototype.getSelection = function getSelection() {
  6512. var selection = [],
  6513. groups = this.groups;
  6514. // iterate over each of the groups
  6515. for (var id in groups) {
  6516. if (groups.hasOwnProperty(id)) {
  6517. var group = groups[id];
  6518. selection = selection.concat(group.getSelection());
  6519. }
  6520. }
  6521. return selection;
  6522. };
  6523. /**
  6524. * Repaint the component
  6525. * @return {Boolean} changed
  6526. */
  6527. GroupSet.prototype.repaint = function repaint() {
  6528. var changed = 0,
  6529. i, id, group, label,
  6530. update = util.updateProperty,
  6531. asSize = util.option.asSize,
  6532. asElement = util.option.asElement,
  6533. options = this.options,
  6534. frame = this.dom.frame,
  6535. labels = this.dom.labels,
  6536. labelSet = this.dom.labelSet;
  6537. // create frame
  6538. if (!this.parent) {
  6539. throw new Error('Cannot repaint groupset: no parent attached');
  6540. }
  6541. var parentContainer = this.parent.getContainer();
  6542. if (!parentContainer) {
  6543. throw new Error('Cannot repaint groupset: parent has no container element');
  6544. }
  6545. if (!frame) {
  6546. frame = document.createElement('div');
  6547. frame.className = 'groupset';
  6548. frame['timeline-groupset'] = this;
  6549. this.dom.frame = frame;
  6550. var className = options.className;
  6551. if (className) {
  6552. util.addClassName(frame, util.option.asString(className));
  6553. }
  6554. changed += 1;
  6555. }
  6556. if (!frame.parentNode) {
  6557. parentContainer.appendChild(frame);
  6558. changed += 1;
  6559. }
  6560. // create labels
  6561. var labelContainer = asElement(options.labelContainer);
  6562. if (!labelContainer) {
  6563. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  6564. }
  6565. if (!labels) {
  6566. labels = document.createElement('div');
  6567. labels.className = 'labels';
  6568. this.dom.labels = labels;
  6569. }
  6570. if (!labelSet) {
  6571. labelSet = document.createElement('div');
  6572. labelSet.className = 'label-set';
  6573. labels.appendChild(labelSet);
  6574. this.dom.labelSet = labelSet;
  6575. }
  6576. if (!labels.parentNode || labels.parentNode != labelContainer) {
  6577. if (labels.parentNode) {
  6578. labels.parentNode.removeChild(labels.parentNode);
  6579. }
  6580. labelContainer.appendChild(labels);
  6581. }
  6582. // reposition frame
  6583. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  6584. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  6585. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  6586. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  6587. // reposition labels
  6588. changed += update(labelSet.style, 'top', asSize(options.top, '0px'));
  6589. changed += update(labelSet.style, 'height', asSize(options.height, this.height + 'px'));
  6590. var me = this,
  6591. queue = this.queue,
  6592. groups = this.groups,
  6593. groupsData = this.groupsData;
  6594. // show/hide added/changed/removed groups
  6595. var ids = Object.keys(queue);
  6596. if (ids.length) {
  6597. ids.forEach(function (id) {
  6598. var action = queue[id];
  6599. var group = groups[id];
  6600. //noinspection FallthroughInSwitchStatementJS
  6601. switch (action) {
  6602. case 'add':
  6603. case 'update':
  6604. if (!group) {
  6605. var groupOptions = Object.create(me.options);
  6606. util.extend(groupOptions, {
  6607. height: null,
  6608. maxHeight: null
  6609. });
  6610. group = new Group(me, id, groupOptions);
  6611. group.setItems(me.itemsData); // attach items data
  6612. groups[id] = group;
  6613. me.controller.add(group);
  6614. }
  6615. // TODO: update group data
  6616. group.data = groupsData.get(id);
  6617. delete queue[id];
  6618. break;
  6619. case 'remove':
  6620. if (group) {
  6621. group.setItems(); // detach items data
  6622. delete groups[id];
  6623. me.controller.remove(group);
  6624. }
  6625. // update lists
  6626. delete queue[id];
  6627. break;
  6628. default:
  6629. console.log('Error: unknown action "' + action + '"');
  6630. }
  6631. });
  6632. // the groupset depends on each of the groups
  6633. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  6634. // TODO: apply dependencies of the groupset
  6635. // update the top positions of the groups in the correct order
  6636. var orderedGroups = this.groupsData.getIds({
  6637. order: this.options.groupOrder
  6638. });
  6639. for (i = 0; i < orderedGroups.length; i++) {
  6640. (function (group, prevGroup) {
  6641. var top = 0;
  6642. if (prevGroup) {
  6643. top = function () {
  6644. // TODO: top must reckon with options.maxHeight
  6645. return prevGroup.top + prevGroup.height;
  6646. }
  6647. }
  6648. group.setOptions({
  6649. top: top
  6650. });
  6651. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  6652. }
  6653. // (re)create the labels
  6654. while (labelSet.firstChild) {
  6655. labelSet.removeChild(labelSet.firstChild);
  6656. }
  6657. for (i = 0; i < orderedGroups.length; i++) {
  6658. id = orderedGroups[i];
  6659. label = this._createLabel(id);
  6660. labelSet.appendChild(label);
  6661. }
  6662. changed++;
  6663. }
  6664. // reposition the labels
  6665. // TODO: labels are not displayed correctly when orientation=='top'
  6666. // TODO: width of labelPanel is not immediately updated on a change in groups
  6667. for (id in groups) {
  6668. if (groups.hasOwnProperty(id)) {
  6669. group = groups[id];
  6670. label = group.label;
  6671. if (label) {
  6672. label.style.top = group.top + 'px';
  6673. label.style.height = group.height + 'px';
  6674. }
  6675. }
  6676. }
  6677. return (changed > 0);
  6678. };
  6679. /**
  6680. * Create a label for group with given id
  6681. * @param {Number} id
  6682. * @return {Element} label
  6683. * @private
  6684. */
  6685. GroupSet.prototype._createLabel = function(id) {
  6686. var group = this.groups[id];
  6687. var label = document.createElement('div');
  6688. label.className = 'vlabel';
  6689. var inner = document.createElement('div');
  6690. inner.className = 'inner';
  6691. label.appendChild(inner);
  6692. var content = group.data && group.data.content;
  6693. if (content instanceof Element) {
  6694. inner.appendChild(content);
  6695. }
  6696. else if (content != undefined) {
  6697. inner.innerHTML = content;
  6698. }
  6699. var className = group.data && group.data.className;
  6700. if (className) {
  6701. util.addClassName(label, className);
  6702. }
  6703. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  6704. return label;
  6705. };
  6706. /**
  6707. * Get container element
  6708. * @return {HTMLElement} container
  6709. */
  6710. GroupSet.prototype.getContainer = function getContainer() {
  6711. return this.dom.frame;
  6712. };
  6713. /**
  6714. * Get the width of the group labels
  6715. * @return {Number} width
  6716. */
  6717. GroupSet.prototype.getLabelsWidth = function getContainer() {
  6718. return this.props.labels.width;
  6719. };
  6720. /**
  6721. * Reflow the component
  6722. * @return {Boolean} resized
  6723. */
  6724. GroupSet.prototype.reflow = function reflow() {
  6725. var changed = 0,
  6726. id, group,
  6727. options = this.options,
  6728. update = util.updateProperty,
  6729. asNumber = util.option.asNumber,
  6730. asSize = util.option.asSize,
  6731. frame = this.dom.frame;
  6732. if (frame) {
  6733. var maxHeight = asNumber(options.maxHeight);
  6734. var fixedHeight = (asSize(options.height) != null);
  6735. var height;
  6736. if (fixedHeight) {
  6737. height = frame.offsetHeight;
  6738. }
  6739. else {
  6740. // height is not specified, calculate the sum of the height of all groups
  6741. height = 0;
  6742. for (id in this.groups) {
  6743. if (this.groups.hasOwnProperty(id)) {
  6744. group = this.groups[id];
  6745. height += group.height;
  6746. }
  6747. }
  6748. }
  6749. if (maxHeight != null) {
  6750. height = Math.min(height, maxHeight);
  6751. }
  6752. changed += update(this, 'height', height);
  6753. changed += update(this, 'top', frame.offsetTop);
  6754. changed += update(this, 'left', frame.offsetLeft);
  6755. changed += update(this, 'width', frame.offsetWidth);
  6756. }
  6757. // calculate the maximum width of the labels
  6758. var width = 0;
  6759. for (id in this.groups) {
  6760. if (this.groups.hasOwnProperty(id)) {
  6761. group = this.groups[id];
  6762. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  6763. width = Math.max(width, labelWidth);
  6764. }
  6765. }
  6766. changed += update(this.props.labels, 'width', width);
  6767. return (changed > 0);
  6768. };
  6769. /**
  6770. * Hide the component from the DOM
  6771. * @return {Boolean} changed
  6772. */
  6773. GroupSet.prototype.hide = function hide() {
  6774. if (this.dom.frame && this.dom.frame.parentNode) {
  6775. this.dom.frame.parentNode.removeChild(this.dom.frame);
  6776. return true;
  6777. }
  6778. else {
  6779. return false;
  6780. }
  6781. };
  6782. /**
  6783. * Show the component in the DOM (when not already visible).
  6784. * A repaint will be executed when the component is not visible
  6785. * @return {Boolean} changed
  6786. */
  6787. GroupSet.prototype.show = function show() {
  6788. if (!this.dom.frame || !this.dom.frame.parentNode) {
  6789. return this.repaint();
  6790. }
  6791. else {
  6792. return false;
  6793. }
  6794. };
  6795. /**
  6796. * Handle updated groups
  6797. * @param {Number[]} ids
  6798. * @private
  6799. */
  6800. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  6801. this._toQueue(ids, 'update');
  6802. };
  6803. /**
  6804. * Handle changed groups
  6805. * @param {Number[]} ids
  6806. * @private
  6807. */
  6808. GroupSet.prototype._onAdd = function _onAdd(ids) {
  6809. this._toQueue(ids, 'add');
  6810. };
  6811. /**
  6812. * Handle removed groups
  6813. * @param {Number[]} ids
  6814. * @private
  6815. */
  6816. GroupSet.prototype._onRemove = function _onRemove(ids) {
  6817. this._toQueue(ids, 'remove');
  6818. };
  6819. /**
  6820. * Put groups in the queue to be added/updated/remove
  6821. * @param {Number[]} ids
  6822. * @param {String} action can be 'add', 'update', 'remove'
  6823. */
  6824. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  6825. var queue = this.queue;
  6826. ids.forEach(function (id) {
  6827. queue[id] = action;
  6828. });
  6829. if (this.controller) {
  6830. //this.requestReflow();
  6831. this.requestRepaint();
  6832. }
  6833. };
  6834. /**
  6835. * Find the Group from an event target:
  6836. * searches for the attribute 'timeline-groupset' in the event target's element
  6837. * tree, then finds the right group in this groupset
  6838. * @param {Event} event
  6839. * @return {Group | null} group
  6840. */
  6841. GroupSet.groupFromTarget = function groupFromTarget (event) {
  6842. var groupset,
  6843. target = event.target;
  6844. while (target) {
  6845. if (target.hasOwnProperty('timeline-groupset')) {
  6846. groupset = target['timeline-groupset'];
  6847. break;
  6848. }
  6849. target = target.parentNode;
  6850. }
  6851. if (groupset) {
  6852. for (var groupId in groupset.groups) {
  6853. if (groupset.groups.hasOwnProperty(groupId)) {
  6854. var group = groupset.groups[groupId];
  6855. if (group.itemset && ItemSet.itemSetFromTarget(event) == group.itemset) {
  6856. return group;
  6857. }
  6858. }
  6859. }
  6860. }
  6861. return null;
  6862. };
  6863. /**
  6864. * Create a timeline visualization
  6865. * @param {HTMLElement} container
  6866. * @param {vis.DataSet | Array | google.visualization.DataTable} [items]
  6867. * @param {Object} [options] See Timeline.setOptions for the available options.
  6868. * @constructor
  6869. */
  6870. function Timeline (container, items, options) {
  6871. var me = this;
  6872. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6873. this.options = {
  6874. orientation: 'bottom',
  6875. autoResize: true,
  6876. editable: false,
  6877. selectable: true,
  6878. snap: null, // will be specified after timeaxis is created
  6879. min: null,
  6880. max: null,
  6881. zoomMin: 10, // milliseconds
  6882. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  6883. // moveable: true, // TODO: option moveable
  6884. // zoomable: true, // TODO: option zoomable
  6885. showMinorLabels: true,
  6886. showMajorLabels: true,
  6887. showCurrentTime: false,
  6888. showCustomTime: false,
  6889. onAdd: function (item, callback) {
  6890. callback(item);
  6891. },
  6892. onUpdate: function (item, callback) {
  6893. callback(item);
  6894. },
  6895. onMove: function (item, callback) {
  6896. callback(item);
  6897. },
  6898. onRemove: function (item, callback) {
  6899. callback(item);
  6900. }
  6901. };
  6902. // controller
  6903. this.controller = new Controller();
  6904. // root panel
  6905. if (!container) {
  6906. throw new Error('No container element provided');
  6907. }
  6908. var rootOptions = Object.create(this.options);
  6909. rootOptions.height = function () {
  6910. // TODO: change to height
  6911. if (me.options.height) {
  6912. // fixed height
  6913. return me.options.height;
  6914. }
  6915. else {
  6916. // auto height
  6917. return (me.timeaxis.height + me.content.height) + 'px';
  6918. }
  6919. };
  6920. this.rootPanel = new RootPanel(container, rootOptions);
  6921. this.controller.add(this.rootPanel);
  6922. // single select (or unselect) when tapping an item
  6923. this.controller.on('tap', this._onSelectItem.bind(this));
  6924. // multi select when holding mouse/touch, or on ctrl+click
  6925. this.controller.on('hold', this._onMultiSelectItem.bind(this));
  6926. // add item on doubletap
  6927. this.controller.on('doubletap', this._onAddItem.bind(this));
  6928. // item panel
  6929. var itemOptions = Object.create(this.options);
  6930. itemOptions.left = function () {
  6931. return me.labelPanel.width;
  6932. };
  6933. itemOptions.width = function () {
  6934. return me.rootPanel.width - me.labelPanel.width;
  6935. };
  6936. itemOptions.top = null;
  6937. itemOptions.height = null;
  6938. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  6939. this.controller.add(this.itemPanel);
  6940. // label panel
  6941. var labelOptions = Object.create(this.options);
  6942. labelOptions.top = null;
  6943. labelOptions.left = null;
  6944. labelOptions.height = null;
  6945. labelOptions.width = function () {
  6946. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  6947. return me.content.getLabelsWidth();
  6948. }
  6949. else {
  6950. return 0;
  6951. }
  6952. };
  6953. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  6954. this.controller.add(this.labelPanel);
  6955. // range
  6956. var rangeOptions = Object.create(this.options);
  6957. this.range = new Range(rangeOptions);
  6958. this.range.setRange(
  6959. now.clone().add('days', -3).valueOf(),
  6960. now.clone().add('days', 4).valueOf()
  6961. );
  6962. this.range.subscribe(this.controller, this.rootPanel, 'move', 'horizontal');
  6963. this.range.subscribe(this.controller, this.rootPanel, 'zoom', 'horizontal');
  6964. this.range.on('rangechange', function (properties) {
  6965. var force = true;
  6966. me.controller.emit('rangechange', properties);
  6967. me.controller.emit('request-reflow', force);
  6968. });
  6969. this.range.on('rangechanged', function (properties) {
  6970. var force = true;
  6971. me.controller.emit('rangechanged', properties);
  6972. me.controller.emit('request-reflow', force);
  6973. });
  6974. // time axis
  6975. var timeaxisOptions = Object.create(rootOptions);
  6976. timeaxisOptions.range = this.range;
  6977. timeaxisOptions.left = null;
  6978. timeaxisOptions.top = null;
  6979. timeaxisOptions.width = '100%';
  6980. timeaxisOptions.height = null;
  6981. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6982. this.timeaxis.setRange(this.range);
  6983. this.controller.add(this.timeaxis);
  6984. this.options.snap = this.timeaxis.snap.bind(this.timeaxis);
  6985. // current time bar
  6986. this.currenttime = new CurrentTime(this.timeaxis, [], rootOptions);
  6987. this.controller.add(this.currenttime);
  6988. // custom time bar
  6989. this.customtime = new CustomTime(this.timeaxis, [], rootOptions);
  6990. this.controller.add(this.customtime);
  6991. // create groupset
  6992. this.setGroups(null);
  6993. this.itemsData = null; // DataSet
  6994. this.groupsData = null; // DataSet
  6995. // apply options
  6996. if (options) {
  6997. this.setOptions(options);
  6998. }
  6999. // create itemset and groupset
  7000. if (items) {
  7001. this.setItems(items);
  7002. }
  7003. }
  7004. /**
  7005. * Add an event listener to the timeline
  7006. * @param {String} event Available events: select, rangechange, rangechanged,
  7007. * timechange, timechanged
  7008. * @param {function} callback
  7009. */
  7010. Timeline.prototype.on = function on (event, callback) {
  7011. this.controller.on(event, callback);
  7012. };
  7013. /**
  7014. * Add an event listener from the timeline
  7015. * @param {String} event
  7016. * @param {function} callback
  7017. */
  7018. Timeline.prototype.off = function off (event, callback) {
  7019. this.controller.off(event, callback);
  7020. };
  7021. /**
  7022. * Set options
  7023. * @param {Object} options TODO: describe the available options
  7024. */
  7025. Timeline.prototype.setOptions = function (options) {
  7026. util.extend(this.options, options);
  7027. // force update of range (apply new min/max etc.)
  7028. // both start and end are optional
  7029. this.range.setRange(options.start, options.end);
  7030. if ('editable' in options || 'selectable' in options) {
  7031. if (this.options.selectable) {
  7032. // force update of selection
  7033. this.setSelection(this.getSelection());
  7034. }
  7035. else {
  7036. // remove selection
  7037. this.setSelection([]);
  7038. }
  7039. }
  7040. // validate the callback functions
  7041. var validateCallback = (function (fn) {
  7042. if (!(this.options[fn] instanceof Function) || this.options[fn].length != 2) {
  7043. throw new Error('option ' + fn + ' must be a function ' + fn + '(item, callback)');
  7044. }
  7045. }).bind(this);
  7046. ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(validateCallback);
  7047. this.controller.reflow();
  7048. this.controller.repaint();
  7049. };
  7050. /**
  7051. * Set a custom time bar
  7052. * @param {Date} time
  7053. */
  7054. Timeline.prototype.setCustomTime = function (time) {
  7055. if (!this.customtime) {
  7056. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  7057. }
  7058. this.customtime.setCustomTime(time);
  7059. };
  7060. /**
  7061. * Retrieve the current custom time.
  7062. * @return {Date} customTime
  7063. */
  7064. Timeline.prototype.getCustomTime = function() {
  7065. if (!this.customtime) {
  7066. throw new Error('Cannot get custom time: Custom time bar is not enabled');
  7067. }
  7068. return this.customtime.getCustomTime();
  7069. };
  7070. /**
  7071. * Set items
  7072. * @param {vis.DataSet | Array | google.visualization.DataTable | null} items
  7073. */
  7074. Timeline.prototype.setItems = function(items) {
  7075. var initialLoad = (this.itemsData == null);
  7076. // convert to type DataSet when needed
  7077. var newDataSet;
  7078. if (!items) {
  7079. newDataSet = null;
  7080. }
  7081. else if (items instanceof DataSet) {
  7082. newDataSet = items;
  7083. }
  7084. if (!(items instanceof DataSet)) {
  7085. newDataSet = new DataSet({
  7086. convert: {
  7087. start: 'Date',
  7088. end: 'Date'
  7089. }
  7090. });
  7091. newDataSet.add(items);
  7092. }
  7093. // set items
  7094. this.itemsData = newDataSet;
  7095. this.content.setItems(newDataSet);
  7096. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  7097. // apply the data range as range
  7098. var dataRange = this.getItemRange();
  7099. // add 5% space on both sides
  7100. var start = dataRange.min;
  7101. var end = dataRange.max;
  7102. if (start != null && end != null) {
  7103. var interval = (end.valueOf() - start.valueOf());
  7104. if (interval <= 0) {
  7105. // prevent an empty interval
  7106. interval = 24 * 60 * 60 * 1000; // 1 day
  7107. }
  7108. start = new Date(start.valueOf() - interval * 0.05);
  7109. end = new Date(end.valueOf() + interval * 0.05);
  7110. }
  7111. // override specified start and/or end date
  7112. if (this.options.start != undefined) {
  7113. start = util.convert(this.options.start, 'Date');
  7114. }
  7115. if (this.options.end != undefined) {
  7116. end = util.convert(this.options.end, 'Date');
  7117. }
  7118. // apply range if there is a min or max available
  7119. if (start != null || end != null) {
  7120. this.range.setRange(start, end);
  7121. }
  7122. }
  7123. };
  7124. /**
  7125. * Set groups
  7126. * @param {vis.DataSet | Array | google.visualization.DataTable} groups
  7127. */
  7128. Timeline.prototype.setGroups = function(groups) {
  7129. var me = this;
  7130. this.groupsData = groups;
  7131. // switch content type between ItemSet or GroupSet when needed
  7132. var Type = this.groupsData ? GroupSet : ItemSet;
  7133. if (!(this.content instanceof Type)) {
  7134. // remove old content set
  7135. if (this.content) {
  7136. this.content.hide();
  7137. if (this.content.setItems) {
  7138. this.content.setItems(); // disconnect from items
  7139. }
  7140. if (this.content.setGroups) {
  7141. this.content.setGroups(); // disconnect from groups
  7142. }
  7143. this.controller.remove(this.content);
  7144. }
  7145. // create new content set
  7146. var options = Object.create(this.options);
  7147. util.extend(options, {
  7148. top: function () {
  7149. if (me.options.orientation == 'top') {
  7150. return me.timeaxis.height;
  7151. }
  7152. else {
  7153. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  7154. }
  7155. },
  7156. left: null,
  7157. width: '100%',
  7158. height: function () {
  7159. if (me.options.height) {
  7160. // fixed height
  7161. return me.itemPanel.height - me.timeaxis.height;
  7162. }
  7163. else {
  7164. // auto height
  7165. return null;
  7166. }
  7167. },
  7168. maxHeight: function () {
  7169. // TODO: change maxHeight to be a css string like '100%' or '300px'
  7170. if (me.options.maxHeight) {
  7171. if (!util.isNumber(me.options.maxHeight)) {
  7172. throw new TypeError('Number expected for property maxHeight');
  7173. }
  7174. return me.options.maxHeight - me.timeaxis.height;
  7175. }
  7176. else {
  7177. return null;
  7178. }
  7179. },
  7180. labelContainer: function () {
  7181. return me.labelPanel.getContainer();
  7182. }
  7183. });
  7184. this.content = new Type(this.itemPanel, [this.timeaxis], options);
  7185. if (this.content.setRange) {
  7186. this.content.setRange(this.range);
  7187. }
  7188. if (this.content.setItems) {
  7189. this.content.setItems(this.itemsData);
  7190. }
  7191. if (this.content.setGroups) {
  7192. this.content.setGroups(this.groupsData);
  7193. }
  7194. this.controller.add(this.content);
  7195. }
  7196. };
  7197. /**
  7198. * Get the data range of the item set.
  7199. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  7200. * When no minimum is found, min==null
  7201. * When no maximum is found, max==null
  7202. */
  7203. Timeline.prototype.getItemRange = function getItemRange() {
  7204. // calculate min from start filed
  7205. var itemsData = this.itemsData,
  7206. min = null,
  7207. max = null;
  7208. if (itemsData) {
  7209. // calculate the minimum value of the field 'start'
  7210. var minItem = itemsData.min('start');
  7211. min = minItem ? minItem.start.valueOf() : null;
  7212. // calculate maximum value of fields 'start' and 'end'
  7213. var maxStartItem = itemsData.max('start');
  7214. if (maxStartItem) {
  7215. max = maxStartItem.start.valueOf();
  7216. }
  7217. var maxEndItem = itemsData.max('end');
  7218. if (maxEndItem) {
  7219. if (max == null) {
  7220. max = maxEndItem.end.valueOf();
  7221. }
  7222. else {
  7223. max = Math.max(max, maxEndItem.end.valueOf());
  7224. }
  7225. }
  7226. }
  7227. return {
  7228. min: (min != null) ? new Date(min) : null,
  7229. max: (max != null) ? new Date(max) : null
  7230. };
  7231. };
  7232. /**
  7233. * Set selected items by their id. Replaces the current selection
  7234. * Unknown id's are silently ignored.
  7235. * @param {Array} [ids] An array with zero or more id's of the items to be
  7236. * selected. If ids is an empty array, all items will be
  7237. * unselected.
  7238. */
  7239. Timeline.prototype.setSelection = function setSelection (ids) {
  7240. if (this.content) this.content.setSelection(ids);
  7241. };
  7242. /**
  7243. * Get the selected items by their id
  7244. * @return {Array} ids The ids of the selected items
  7245. */
  7246. Timeline.prototype.getSelection = function getSelection() {
  7247. return this.content ? this.content.getSelection() : [];
  7248. };
  7249. /**
  7250. * Set the visible window. Both parameters are optional, you can change only
  7251. * start or only end.
  7252. * @param {Date | Number | String} [start] Start date of visible window
  7253. * @param {Date | Number | String} [end] End date of visible window
  7254. */
  7255. Timeline.prototype.setWindow = function setWindow(start, end) {
  7256. this.range.setRange(start, end);
  7257. };
  7258. /**
  7259. * Get the visible window
  7260. * @return {{start: Date, end: Date}} Visible range
  7261. */
  7262. Timeline.prototype.getWindow = function setWindow() {
  7263. var range = this.range.getRange();
  7264. return {
  7265. start: new Date(range.start),
  7266. end: new Date(range.end)
  7267. };
  7268. };
  7269. /**
  7270. * Handle selecting/deselecting an item when tapping it
  7271. * @param {Event} event
  7272. * @private
  7273. */
  7274. // TODO: move this function to ItemSet
  7275. Timeline.prototype._onSelectItem = function (event) {
  7276. if (!this.options.selectable) return;
  7277. var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
  7278. var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
  7279. if (ctrlKey || shiftKey) {
  7280. this._onMultiSelectItem(event);
  7281. return;
  7282. }
  7283. var item = ItemSet.itemFromTarget(event);
  7284. var selection = item ? [item.id] : [];
  7285. this.setSelection(selection);
  7286. this.controller.emit('select', {
  7287. items: this.getSelection()
  7288. });
  7289. event.stopPropagation();
  7290. };
  7291. /**
  7292. * Handle creation and updates of an item on double tap
  7293. * @param event
  7294. * @private
  7295. */
  7296. Timeline.prototype._onAddItem = function (event) {
  7297. if (!this.options.selectable) return;
  7298. if (!this.options.editable) return;
  7299. var me = this,
  7300. item = ItemSet.itemFromTarget(event);
  7301. if (item) {
  7302. // update item
  7303. // execute async handler to update the item (or cancel it)
  7304. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  7305. this.options.onUpdate(itemData, function (itemData) {
  7306. if (itemData) {
  7307. me.itemsData.update(itemData);
  7308. }
  7309. });
  7310. }
  7311. else {
  7312. // add item
  7313. var xAbs = vis.util.getAbsoluteLeft(this.rootPanel.frame);
  7314. var x = event.gesture.center.pageX - xAbs;
  7315. var newItem = {
  7316. start: this.timeaxis.snap(this._toTime(x)),
  7317. content: 'new item'
  7318. };
  7319. var id = util.randomUUID();
  7320. newItem[this.itemsData.fieldId] = id;
  7321. var group = GroupSet.groupFromTarget(event);
  7322. if (group) {
  7323. newItem.group = group.groupId;
  7324. }
  7325. // execute async handler to customize (or cancel) adding an item
  7326. this.options.onAdd(newItem, function (item) {
  7327. if (item) {
  7328. me.itemsData.add(newItem);
  7329. // select the created item after it is repainted
  7330. me.controller.once('repaint', function () {
  7331. me.setSelection([id]);
  7332. me.controller.emit('select', {
  7333. items: me.getSelection()
  7334. });
  7335. }.bind(me));
  7336. }
  7337. });
  7338. }
  7339. };
  7340. /**
  7341. * Handle selecting/deselecting multiple items when holding an item
  7342. * @param {Event} event
  7343. * @private
  7344. */
  7345. // TODO: move this function to ItemSet
  7346. Timeline.prototype._onMultiSelectItem = function (event) {
  7347. if (!this.options.selectable) return;
  7348. var selection,
  7349. item = ItemSet.itemFromTarget(event);
  7350. if (item) {
  7351. // multi select items
  7352. selection = this.getSelection(); // current selection
  7353. var index = selection.indexOf(item.id);
  7354. if (index == -1) {
  7355. // item is not yet selected -> select it
  7356. selection.push(item.id);
  7357. }
  7358. else {
  7359. // item is already selected -> deselect it
  7360. selection.splice(index, 1);
  7361. }
  7362. this.setSelection(selection);
  7363. this.controller.emit('select', {
  7364. items: this.getSelection()
  7365. });
  7366. event.stopPropagation();
  7367. }
  7368. };
  7369. /**
  7370. * Convert a position on screen (pixels) to a datetime
  7371. * @param {int} x Position on the screen in pixels
  7372. * @return {Date} time The datetime the corresponds with given position x
  7373. * @private
  7374. */
  7375. Timeline.prototype._toTime = function _toTime(x) {
  7376. var conversion = this.range.conversion(this.content.width);
  7377. return new Date(x / conversion.scale + conversion.offset);
  7378. };
  7379. /**
  7380. * Convert a datetime (Date object) into a position on the screen
  7381. * @param {Date} time A date
  7382. * @return {int} x The position on the screen in pixels which corresponds
  7383. * with the given date.
  7384. * @private
  7385. */
  7386. Timeline.prototype._toScreen = function _toScreen(time) {
  7387. var conversion = this.range.conversion(this.content.width);
  7388. return (time.valueOf() - conversion.offset) * conversion.scale;
  7389. };
  7390. (function(exports) {
  7391. /**
  7392. * Parse a text source containing data in DOT language into a JSON object.
  7393. * The object contains two lists: one with nodes and one with edges.
  7394. *
  7395. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  7396. *
  7397. * @param {String} data Text containing a graph in DOT-notation
  7398. * @return {Object} graph An object containing two parameters:
  7399. * {Object[]} nodes
  7400. * {Object[]} edges
  7401. */
  7402. function parseDOT (data) {
  7403. dot = data;
  7404. return parseGraph();
  7405. }
  7406. // token types enumeration
  7407. var TOKENTYPE = {
  7408. NULL : 0,
  7409. DELIMITER : 1,
  7410. IDENTIFIER: 2,
  7411. UNKNOWN : 3
  7412. };
  7413. // map with all delimiters
  7414. var DELIMITERS = {
  7415. '{': true,
  7416. '}': true,
  7417. '[': true,
  7418. ']': true,
  7419. ';': true,
  7420. '=': true,
  7421. ',': true,
  7422. '->': true,
  7423. '--': true
  7424. };
  7425. var dot = ''; // current dot file
  7426. var index = 0; // current index in dot file
  7427. var c = ''; // current token character in expr
  7428. var token = ''; // current token
  7429. var tokenType = TOKENTYPE.NULL; // type of the token
  7430. /**
  7431. * Get the first character from the dot file.
  7432. * The character is stored into the char c. If the end of the dot file is
  7433. * reached, the function puts an empty string in c.
  7434. */
  7435. function first() {
  7436. index = 0;
  7437. c = dot.charAt(0);
  7438. }
  7439. /**
  7440. * Get the next character from the dot file.
  7441. * The character is stored into the char c. If the end of the dot file is
  7442. * reached, the function puts an empty string in c.
  7443. */
  7444. function next() {
  7445. index++;
  7446. c = dot.charAt(index);
  7447. }
  7448. /**
  7449. * Preview the next character from the dot file.
  7450. * @return {String} cNext
  7451. */
  7452. function nextPreview() {
  7453. return dot.charAt(index + 1);
  7454. }
  7455. /**
  7456. * Test whether given character is alphabetic or numeric
  7457. * @param {String} c
  7458. * @return {Boolean} isAlphaNumeric
  7459. */
  7460. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  7461. function isAlphaNumeric(c) {
  7462. return regexAlphaNumeric.test(c);
  7463. }
  7464. /**
  7465. * Merge all properties of object b into object b
  7466. * @param {Object} a
  7467. * @param {Object} b
  7468. * @return {Object} a
  7469. */
  7470. function merge (a, b) {
  7471. if (!a) {
  7472. a = {};
  7473. }
  7474. if (b) {
  7475. for (var name in b) {
  7476. if (b.hasOwnProperty(name)) {
  7477. a[name] = b[name];
  7478. }
  7479. }
  7480. }
  7481. return a;
  7482. }
  7483. /**
  7484. * Set a value in an object, where the provided parameter name can be a
  7485. * path with nested parameters. For example:
  7486. *
  7487. * var obj = {a: 2};
  7488. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  7489. *
  7490. * @param {Object} obj
  7491. * @param {String} path A parameter name or dot-separated parameter path,
  7492. * like "color.highlight.border".
  7493. * @param {*} value
  7494. */
  7495. function setValue(obj, path, value) {
  7496. var keys = path.split('.');
  7497. var o = obj;
  7498. while (keys.length) {
  7499. var key = keys.shift();
  7500. if (keys.length) {
  7501. // this isn't the end point
  7502. if (!o[key]) {
  7503. o[key] = {};
  7504. }
  7505. o = o[key];
  7506. }
  7507. else {
  7508. // this is the end point
  7509. o[key] = value;
  7510. }
  7511. }
  7512. }
  7513. /**
  7514. * Add a node to a graph object. If there is already a node with
  7515. * the same id, their attributes will be merged.
  7516. * @param {Object} graph
  7517. * @param {Object} node
  7518. */
  7519. function addNode(graph, node) {
  7520. var i, len;
  7521. var current = null;
  7522. // find root graph (in case of subgraph)
  7523. var graphs = [graph]; // list with all graphs from current graph to root graph
  7524. var root = graph;
  7525. while (root.parent) {
  7526. graphs.push(root.parent);
  7527. root = root.parent;
  7528. }
  7529. // find existing node (at root level) by its id
  7530. if (root.nodes) {
  7531. for (i = 0, len = root.nodes.length; i < len; i++) {
  7532. if (node.id === root.nodes[i].id) {
  7533. current = root.nodes[i];
  7534. break;
  7535. }
  7536. }
  7537. }
  7538. if (!current) {
  7539. // this is a new node
  7540. current = {
  7541. id: node.id
  7542. };
  7543. if (graph.node) {
  7544. // clone default attributes
  7545. current.attr = merge(current.attr, graph.node);
  7546. }
  7547. }
  7548. // add node to this (sub)graph and all its parent graphs
  7549. for (i = graphs.length - 1; i >= 0; i--) {
  7550. var g = graphs[i];
  7551. if (!g.nodes) {
  7552. g.nodes = [];
  7553. }
  7554. if (g.nodes.indexOf(current) == -1) {
  7555. g.nodes.push(current);
  7556. }
  7557. }
  7558. // merge attributes
  7559. if (node.attr) {
  7560. current.attr = merge(current.attr, node.attr);
  7561. }
  7562. }
  7563. /**
  7564. * Add an edge to a graph object
  7565. * @param {Object} graph
  7566. * @param {Object} edge
  7567. */
  7568. function addEdge(graph, edge) {
  7569. if (!graph.edges) {
  7570. graph.edges = [];
  7571. }
  7572. graph.edges.push(edge);
  7573. if (graph.edge) {
  7574. var attr = merge({}, graph.edge); // clone default attributes
  7575. edge.attr = merge(attr, edge.attr); // merge attributes
  7576. }
  7577. }
  7578. /**
  7579. * Create an edge to a graph object
  7580. * @param {Object} graph
  7581. * @param {String | Number | Object} from
  7582. * @param {String | Number | Object} to
  7583. * @param {String} type
  7584. * @param {Object | null} attr
  7585. * @return {Object} edge
  7586. */
  7587. function createEdge(graph, from, to, type, attr) {
  7588. var edge = {
  7589. from: from,
  7590. to: to,
  7591. type: type
  7592. };
  7593. if (graph.edge) {
  7594. edge.attr = merge({}, graph.edge); // clone default attributes
  7595. }
  7596. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  7597. return edge;
  7598. }
  7599. /**
  7600. * Get next token in the current dot file.
  7601. * The token and token type are available as token and tokenType
  7602. */
  7603. function getToken() {
  7604. tokenType = TOKENTYPE.NULL;
  7605. token = '';
  7606. // skip over whitespaces
  7607. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7608. next();
  7609. }
  7610. do {
  7611. var isComment = false;
  7612. // skip comment
  7613. if (c == '#') {
  7614. // find the previous non-space character
  7615. var i = index - 1;
  7616. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  7617. i--;
  7618. }
  7619. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  7620. // the # is at the start of a line, this is indeed a line comment
  7621. while (c != '' && c != '\n') {
  7622. next();
  7623. }
  7624. isComment = true;
  7625. }
  7626. }
  7627. if (c == '/' && nextPreview() == '/') {
  7628. // skip line comment
  7629. while (c != '' && c != '\n') {
  7630. next();
  7631. }
  7632. isComment = true;
  7633. }
  7634. if (c == '/' && nextPreview() == '*') {
  7635. // skip block comment
  7636. while (c != '') {
  7637. if (c == '*' && nextPreview() == '/') {
  7638. // end of block comment found. skip these last two characters
  7639. next();
  7640. next();
  7641. break;
  7642. }
  7643. else {
  7644. next();
  7645. }
  7646. }
  7647. isComment = true;
  7648. }
  7649. // skip over whitespaces
  7650. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  7651. next();
  7652. }
  7653. }
  7654. while (isComment);
  7655. // check for end of dot file
  7656. if (c == '') {
  7657. // token is still empty
  7658. tokenType = TOKENTYPE.DELIMITER;
  7659. return;
  7660. }
  7661. // check for delimiters consisting of 2 characters
  7662. var c2 = c + nextPreview();
  7663. if (DELIMITERS[c2]) {
  7664. tokenType = TOKENTYPE.DELIMITER;
  7665. token = c2;
  7666. next();
  7667. next();
  7668. return;
  7669. }
  7670. // check for delimiters consisting of 1 character
  7671. if (DELIMITERS[c]) {
  7672. tokenType = TOKENTYPE.DELIMITER;
  7673. token = c;
  7674. next();
  7675. return;
  7676. }
  7677. // check for an identifier (number or string)
  7678. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  7679. if (isAlphaNumeric(c) || c == '-') {
  7680. token += c;
  7681. next();
  7682. while (isAlphaNumeric(c)) {
  7683. token += c;
  7684. next();
  7685. }
  7686. if (token == 'false') {
  7687. token = false; // convert to boolean
  7688. }
  7689. else if (token == 'true') {
  7690. token = true; // convert to boolean
  7691. }
  7692. else if (!isNaN(Number(token))) {
  7693. token = Number(token); // convert to number
  7694. }
  7695. tokenType = TOKENTYPE.IDENTIFIER;
  7696. return;
  7697. }
  7698. // check for a string enclosed by double quotes
  7699. if (c == '"') {
  7700. next();
  7701. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  7702. token += c;
  7703. if (c == '"') { // skip the escape character
  7704. next();
  7705. }
  7706. next();
  7707. }
  7708. if (c != '"') {
  7709. throw newSyntaxError('End of string " expected');
  7710. }
  7711. next();
  7712. tokenType = TOKENTYPE.IDENTIFIER;
  7713. return;
  7714. }
  7715. // something unknown is found, wrong characters, a syntax error
  7716. tokenType = TOKENTYPE.UNKNOWN;
  7717. while (c != '') {
  7718. token += c;
  7719. next();
  7720. }
  7721. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  7722. }
  7723. /**
  7724. * Parse a graph.
  7725. * @returns {Object} graph
  7726. */
  7727. function parseGraph() {
  7728. var graph = {};
  7729. first();
  7730. getToken();
  7731. // optional strict keyword
  7732. if (token == 'strict') {
  7733. graph.strict = true;
  7734. getToken();
  7735. }
  7736. // graph or digraph keyword
  7737. if (token == 'graph' || token == 'digraph') {
  7738. graph.type = token;
  7739. getToken();
  7740. }
  7741. // optional graph id
  7742. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7743. graph.id = token;
  7744. getToken();
  7745. }
  7746. // open angle bracket
  7747. if (token != '{') {
  7748. throw newSyntaxError('Angle bracket { expected');
  7749. }
  7750. getToken();
  7751. // statements
  7752. parseStatements(graph);
  7753. // close angle bracket
  7754. if (token != '}') {
  7755. throw newSyntaxError('Angle bracket } expected');
  7756. }
  7757. getToken();
  7758. // end of file
  7759. if (token !== '') {
  7760. throw newSyntaxError('End of file expected');
  7761. }
  7762. getToken();
  7763. // remove temporary default properties
  7764. delete graph.node;
  7765. delete graph.edge;
  7766. delete graph.graph;
  7767. return graph;
  7768. }
  7769. /**
  7770. * Parse a list with statements.
  7771. * @param {Object} graph
  7772. */
  7773. function parseStatements (graph) {
  7774. while (token !== '' && token != '}') {
  7775. parseStatement(graph);
  7776. if (token == ';') {
  7777. getToken();
  7778. }
  7779. }
  7780. }
  7781. /**
  7782. * Parse a single statement. Can be a an attribute statement, node
  7783. * statement, a series of node statements and edge statements, or a
  7784. * parameter.
  7785. * @param {Object} graph
  7786. */
  7787. function parseStatement(graph) {
  7788. // parse subgraph
  7789. var subgraph = parseSubgraph(graph);
  7790. if (subgraph) {
  7791. // edge statements
  7792. parseEdge(graph, subgraph);
  7793. return;
  7794. }
  7795. // parse an attribute statement
  7796. var attr = parseAttributeStatement(graph);
  7797. if (attr) {
  7798. return;
  7799. }
  7800. // parse node
  7801. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7802. throw newSyntaxError('Identifier expected');
  7803. }
  7804. var id = token; // id can be a string or a number
  7805. getToken();
  7806. if (token == '=') {
  7807. // id statement
  7808. getToken();
  7809. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7810. throw newSyntaxError('Identifier expected');
  7811. }
  7812. graph[id] = token;
  7813. getToken();
  7814. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  7815. }
  7816. else {
  7817. parseNodeStatement(graph, id);
  7818. }
  7819. }
  7820. /**
  7821. * Parse a subgraph
  7822. * @param {Object} graph parent graph object
  7823. * @return {Object | null} subgraph
  7824. */
  7825. function parseSubgraph (graph) {
  7826. var subgraph = null;
  7827. // optional subgraph keyword
  7828. if (token == 'subgraph') {
  7829. subgraph = {};
  7830. subgraph.type = 'subgraph';
  7831. getToken();
  7832. // optional graph id
  7833. if (tokenType == TOKENTYPE.IDENTIFIER) {
  7834. subgraph.id = token;
  7835. getToken();
  7836. }
  7837. }
  7838. // open angle bracket
  7839. if (token == '{') {
  7840. getToken();
  7841. if (!subgraph) {
  7842. subgraph = {};
  7843. }
  7844. subgraph.parent = graph;
  7845. subgraph.node = graph.node;
  7846. subgraph.edge = graph.edge;
  7847. subgraph.graph = graph.graph;
  7848. // statements
  7849. parseStatements(subgraph);
  7850. // close angle bracket
  7851. if (token != '}') {
  7852. throw newSyntaxError('Angle bracket } expected');
  7853. }
  7854. getToken();
  7855. // remove temporary default properties
  7856. delete subgraph.node;
  7857. delete subgraph.edge;
  7858. delete subgraph.graph;
  7859. delete subgraph.parent;
  7860. // register at the parent graph
  7861. if (!graph.subgraphs) {
  7862. graph.subgraphs = [];
  7863. }
  7864. graph.subgraphs.push(subgraph);
  7865. }
  7866. return subgraph;
  7867. }
  7868. /**
  7869. * parse an attribute statement like "node [shape=circle fontSize=16]".
  7870. * Available keywords are 'node', 'edge', 'graph'.
  7871. * The previous list with default attributes will be replaced
  7872. * @param {Object} graph
  7873. * @returns {String | null} keyword Returns the name of the parsed attribute
  7874. * (node, edge, graph), or null if nothing
  7875. * is parsed.
  7876. */
  7877. function parseAttributeStatement (graph) {
  7878. // attribute statements
  7879. if (token == 'node') {
  7880. getToken();
  7881. // node attributes
  7882. graph.node = parseAttributeList();
  7883. return 'node';
  7884. }
  7885. else if (token == 'edge') {
  7886. getToken();
  7887. // edge attributes
  7888. graph.edge = parseAttributeList();
  7889. return 'edge';
  7890. }
  7891. else if (token == 'graph') {
  7892. getToken();
  7893. // graph attributes
  7894. graph.graph = parseAttributeList();
  7895. return 'graph';
  7896. }
  7897. return null;
  7898. }
  7899. /**
  7900. * parse a node statement
  7901. * @param {Object} graph
  7902. * @param {String | Number} id
  7903. */
  7904. function parseNodeStatement(graph, id) {
  7905. // node statement
  7906. var node = {
  7907. id: id
  7908. };
  7909. var attr = parseAttributeList();
  7910. if (attr) {
  7911. node.attr = attr;
  7912. }
  7913. addNode(graph, node);
  7914. // edge statements
  7915. parseEdge(graph, id);
  7916. }
  7917. /**
  7918. * Parse an edge or a series of edges
  7919. * @param {Object} graph
  7920. * @param {String | Number} from Id of the from node
  7921. */
  7922. function parseEdge(graph, from) {
  7923. while (token == '->' || token == '--') {
  7924. var to;
  7925. var type = token;
  7926. getToken();
  7927. var subgraph = parseSubgraph(graph);
  7928. if (subgraph) {
  7929. to = subgraph;
  7930. }
  7931. else {
  7932. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7933. throw newSyntaxError('Identifier or subgraph expected');
  7934. }
  7935. to = token;
  7936. addNode(graph, {
  7937. id: to
  7938. });
  7939. getToken();
  7940. }
  7941. // parse edge attributes
  7942. var attr = parseAttributeList();
  7943. // create edge
  7944. var edge = createEdge(graph, from, to, type, attr);
  7945. addEdge(graph, edge);
  7946. from = to;
  7947. }
  7948. }
  7949. /**
  7950. * Parse a set with attributes,
  7951. * for example [label="1.000", shape=solid]
  7952. * @return {Object | null} attr
  7953. */
  7954. function parseAttributeList() {
  7955. var attr = null;
  7956. while (token == '[') {
  7957. getToken();
  7958. attr = {};
  7959. while (token !== '' && token != ']') {
  7960. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7961. throw newSyntaxError('Attribute name expected');
  7962. }
  7963. var name = token;
  7964. getToken();
  7965. if (token != '=') {
  7966. throw newSyntaxError('Equal sign = expected');
  7967. }
  7968. getToken();
  7969. if (tokenType != TOKENTYPE.IDENTIFIER) {
  7970. throw newSyntaxError('Attribute value expected');
  7971. }
  7972. var value = token;
  7973. setValue(attr, name, value); // name can be a path
  7974. getToken();
  7975. if (token ==',') {
  7976. getToken();
  7977. }
  7978. }
  7979. if (token != ']') {
  7980. throw newSyntaxError('Bracket ] expected');
  7981. }
  7982. getToken();
  7983. }
  7984. return attr;
  7985. }
  7986. /**
  7987. * Create a syntax error with extra information on current token and index.
  7988. * @param {String} message
  7989. * @returns {SyntaxError} err
  7990. */
  7991. function newSyntaxError(message) {
  7992. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  7993. }
  7994. /**
  7995. * Chop off text after a maximum length
  7996. * @param {String} text
  7997. * @param {Number} maxLength
  7998. * @returns {String}
  7999. */
  8000. function chop (text, maxLength) {
  8001. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  8002. }
  8003. /**
  8004. * Execute a function fn for each pair of elements in two arrays
  8005. * @param {Array | *} array1
  8006. * @param {Array | *} array2
  8007. * @param {function} fn
  8008. */
  8009. function forEach2(array1, array2, fn) {
  8010. if (array1 instanceof Array) {
  8011. array1.forEach(function (elem1) {
  8012. if (array2 instanceof Array) {
  8013. array2.forEach(function (elem2) {
  8014. fn(elem1, elem2);
  8015. });
  8016. }
  8017. else {
  8018. fn(elem1, array2);
  8019. }
  8020. });
  8021. }
  8022. else {
  8023. if (array2 instanceof Array) {
  8024. array2.forEach(function (elem2) {
  8025. fn(array1, elem2);
  8026. });
  8027. }
  8028. else {
  8029. fn(array1, array2);
  8030. }
  8031. }
  8032. }
  8033. /**
  8034. * Convert a string containing a graph in DOT language into a map containing
  8035. * with nodes and edges in the format of graph.
  8036. * @param {String} data Text containing a graph in DOT-notation
  8037. * @return {Object} graphData
  8038. */
  8039. function DOTToGraph (data) {
  8040. // parse the DOT file
  8041. var dotData = parseDOT(data);
  8042. var graphData = {
  8043. nodes: [],
  8044. edges: [],
  8045. options: {}
  8046. };
  8047. // copy the nodes
  8048. if (dotData.nodes) {
  8049. dotData.nodes.forEach(function (dotNode) {
  8050. var graphNode = {
  8051. id: dotNode.id,
  8052. label: String(dotNode.label || dotNode.id)
  8053. };
  8054. merge(graphNode, dotNode.attr);
  8055. if (graphNode.image) {
  8056. graphNode.shape = 'image';
  8057. }
  8058. graphData.nodes.push(graphNode);
  8059. });
  8060. }
  8061. // copy the edges
  8062. if (dotData.edges) {
  8063. /**
  8064. * Convert an edge in DOT format to an edge with VisGraph format
  8065. * @param {Object} dotEdge
  8066. * @returns {Object} graphEdge
  8067. */
  8068. function convertEdge(dotEdge) {
  8069. var graphEdge = {
  8070. from: dotEdge.from,
  8071. to: dotEdge.to
  8072. };
  8073. merge(graphEdge, dotEdge.attr);
  8074. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  8075. return graphEdge;
  8076. }
  8077. dotData.edges.forEach(function (dotEdge) {
  8078. var from, to;
  8079. if (dotEdge.from instanceof Object) {
  8080. from = dotEdge.from.nodes;
  8081. }
  8082. else {
  8083. from = {
  8084. id: dotEdge.from
  8085. }
  8086. }
  8087. if (dotEdge.to instanceof Object) {
  8088. to = dotEdge.to.nodes;
  8089. }
  8090. else {
  8091. to = {
  8092. id: dotEdge.to
  8093. }
  8094. }
  8095. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  8096. dotEdge.from.edges.forEach(function (subEdge) {
  8097. var graphEdge = convertEdge(subEdge);
  8098. graphData.edges.push(graphEdge);
  8099. });
  8100. }
  8101. forEach2(from, to, function (from, to) {
  8102. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  8103. var graphEdge = convertEdge(subEdge);
  8104. graphData.edges.push(graphEdge);
  8105. });
  8106. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  8107. dotEdge.to.edges.forEach(function (subEdge) {
  8108. var graphEdge = convertEdge(subEdge);
  8109. graphData.edges.push(graphEdge);
  8110. });
  8111. }
  8112. });
  8113. }
  8114. // copy the options
  8115. if (dotData.attr) {
  8116. graphData.options = dotData.attr;
  8117. }
  8118. return graphData;
  8119. }
  8120. // exports
  8121. exports.parseDOT = parseDOT;
  8122. exports.DOTToGraph = DOTToGraph;
  8123. })(typeof util !== 'undefined' ? util : exports);
  8124. /**
  8125. * Canvas shapes used by the Graph
  8126. */
  8127. if (typeof CanvasRenderingContext2D !== 'undefined') {
  8128. /**
  8129. * Draw a circle shape
  8130. */
  8131. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  8132. this.beginPath();
  8133. this.arc(x, y, r, 0, 2*Math.PI, false);
  8134. };
  8135. /**
  8136. * Draw a square shape
  8137. * @param {Number} x horizontal center
  8138. * @param {Number} y vertical center
  8139. * @param {Number} r size, width and height of the square
  8140. */
  8141. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  8142. this.beginPath();
  8143. this.rect(x - r, y - r, r * 2, r * 2);
  8144. };
  8145. /**
  8146. * Draw a triangle shape
  8147. * @param {Number} x horizontal center
  8148. * @param {Number} y vertical center
  8149. * @param {Number} r radius, half the length of the sides of the triangle
  8150. */
  8151. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  8152. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8153. this.beginPath();
  8154. var s = r * 2;
  8155. var s2 = s / 2;
  8156. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8157. var h = Math.sqrt(s * s - s2 * s2); // height
  8158. this.moveTo(x, y - (h - ir));
  8159. this.lineTo(x + s2, y + ir);
  8160. this.lineTo(x - s2, y + ir);
  8161. this.lineTo(x, y - (h - ir));
  8162. this.closePath();
  8163. };
  8164. /**
  8165. * Draw a triangle shape in downward orientation
  8166. * @param {Number} x horizontal center
  8167. * @param {Number} y vertical center
  8168. * @param {Number} r radius
  8169. */
  8170. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  8171. // http://en.wikipedia.org/wiki/Equilateral_triangle
  8172. this.beginPath();
  8173. var s = r * 2;
  8174. var s2 = s / 2;
  8175. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  8176. var h = Math.sqrt(s * s - s2 * s2); // height
  8177. this.moveTo(x, y + (h - ir));
  8178. this.lineTo(x + s2, y - ir);
  8179. this.lineTo(x - s2, y - ir);
  8180. this.lineTo(x, y + (h - ir));
  8181. this.closePath();
  8182. };
  8183. /**
  8184. * Draw a star shape, a star with 5 points
  8185. * @param {Number} x horizontal center
  8186. * @param {Number} y vertical center
  8187. * @param {Number} r radius, half the length of the sides of the triangle
  8188. */
  8189. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  8190. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  8191. this.beginPath();
  8192. for (var n = 0; n < 10; n++) {
  8193. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  8194. this.lineTo(
  8195. x + radius * Math.sin(n * 2 * Math.PI / 10),
  8196. y - radius * Math.cos(n * 2 * Math.PI / 10)
  8197. );
  8198. }
  8199. this.closePath();
  8200. };
  8201. /**
  8202. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  8203. */
  8204. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  8205. var r2d = Math.PI/180;
  8206. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  8207. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  8208. this.beginPath();
  8209. this.moveTo(x+r,y);
  8210. this.lineTo(x+w-r,y);
  8211. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  8212. this.lineTo(x+w,y+h-r);
  8213. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  8214. this.lineTo(x+r,y+h);
  8215. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  8216. this.lineTo(x,y+r);
  8217. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  8218. };
  8219. /**
  8220. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8221. */
  8222. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  8223. var kappa = .5522848,
  8224. ox = (w / 2) * kappa, // control point offset horizontal
  8225. oy = (h / 2) * kappa, // control point offset vertical
  8226. xe = x + w, // x-end
  8227. ye = y + h, // y-end
  8228. xm = x + w / 2, // x-middle
  8229. ym = y + h / 2; // y-middle
  8230. this.beginPath();
  8231. this.moveTo(x, ym);
  8232. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8233. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8234. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8235. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8236. };
  8237. /**
  8238. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  8239. */
  8240. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  8241. var f = 1/3;
  8242. var wEllipse = w;
  8243. var hEllipse = h * f;
  8244. var kappa = .5522848,
  8245. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  8246. oy = (hEllipse / 2) * kappa, // control point offset vertical
  8247. xe = x + wEllipse, // x-end
  8248. ye = y + hEllipse, // y-end
  8249. xm = x + wEllipse / 2, // x-middle
  8250. ym = y + hEllipse / 2, // y-middle
  8251. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  8252. yeb = y + h; // y-end, bottom ellipse
  8253. this.beginPath();
  8254. this.moveTo(xe, ym);
  8255. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  8256. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  8257. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  8258. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  8259. this.lineTo(xe, ymb);
  8260. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  8261. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  8262. this.lineTo(x, ym);
  8263. };
  8264. /**
  8265. * Draw an arrow point (no line)
  8266. */
  8267. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  8268. // tail
  8269. var xt = x - length * Math.cos(angle);
  8270. var yt = y - length * Math.sin(angle);
  8271. // inner tail
  8272. // TODO: allow to customize different shapes
  8273. var xi = x - length * 0.9 * Math.cos(angle);
  8274. var yi = y - length * 0.9 * Math.sin(angle);
  8275. // left
  8276. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  8277. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  8278. // right
  8279. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  8280. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  8281. this.beginPath();
  8282. this.moveTo(x, y);
  8283. this.lineTo(xl, yl);
  8284. this.lineTo(xi, yi);
  8285. this.lineTo(xr, yr);
  8286. this.closePath();
  8287. };
  8288. /**
  8289. * Sets up the dashedLine functionality for drawing
  8290. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  8291. * @author David Jordan
  8292. * @date 2012-08-08
  8293. */
  8294. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  8295. if (!dashArray) dashArray=[10,5];
  8296. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  8297. var dashCount = dashArray.length;
  8298. this.moveTo(x, y);
  8299. var dx = (x2-x), dy = (y2-y);
  8300. var slope = dy/dx;
  8301. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  8302. var dashIndex=0, draw=true;
  8303. while (distRemaining>=0.1){
  8304. var dashLength = dashArray[dashIndex++%dashCount];
  8305. if (dashLength > distRemaining) dashLength = distRemaining;
  8306. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  8307. if (dx<0) xStep = -xStep;
  8308. x += xStep;
  8309. y += slope*xStep;
  8310. this[draw ? 'lineTo' : 'moveTo'](x,y);
  8311. distRemaining -= dashLength;
  8312. draw = !draw;
  8313. }
  8314. };
  8315. // TODO: add diamond shape
  8316. }
  8317. /**
  8318. * @class Node
  8319. * A node. A node can be connected to other nodes via one or multiple edges.
  8320. * @param {object} properties An object containing properties for the node. All
  8321. * properties are optional, except for the id.
  8322. * {number} id Id of the node. Required
  8323. * {string} label Text label for the node
  8324. * {number} x Horizontal position of the node
  8325. * {number} y Vertical position of the node
  8326. * {string} shape Node shape, available:
  8327. * "database", "circle", "ellipse",
  8328. * "box", "image", "text", "dot",
  8329. * "star", "triangle", "triangleDown",
  8330. * "square"
  8331. * {string} image An image url
  8332. * {string} title An title text, can be HTML
  8333. * {anytype} group A group name or number
  8334. * @param {Graph.Images} imagelist A list with images. Only needed
  8335. * when the node has an image
  8336. * @param {Graph.Groups} grouplist A list with groups. Needed for
  8337. * retrieving group properties
  8338. * @param {Object} constants An object with default values for
  8339. * example for the color
  8340. *
  8341. */
  8342. function Node(properties, imagelist, grouplist, constants) {
  8343. this.selected = false;
  8344. this.edges = []; // all edges connected to this node
  8345. this.dynamicEdges = [];
  8346. this.reroutedEdges = {};
  8347. this.group = constants.nodes.group;
  8348. this.fontSize = constants.nodes.fontSize;
  8349. this.fontFace = constants.nodes.fontFace;
  8350. this.fontColor = constants.nodes.fontColor;
  8351. this.fontDrawThreshold = 3;
  8352. this.color = constants.nodes.color;
  8353. // set defaults for the properties
  8354. this.id = undefined;
  8355. this.shape = constants.nodes.shape;
  8356. this.image = constants.nodes.image;
  8357. this.x = null;
  8358. this.y = null;
  8359. this.xFixed = false;
  8360. this.yFixed = false;
  8361. this.horizontalAlignLeft = true; // these are for the navigation controls
  8362. this.verticalAlignTop = true; // these are for the navigation controls
  8363. this.radius = constants.nodes.radius;
  8364. this.baseRadiusValue = constants.nodes.radius;
  8365. this.radiusFixed = false;
  8366. this.radiusMin = constants.nodes.radiusMin;
  8367. this.radiusMax = constants.nodes.radiusMax;
  8368. this.level = -1;
  8369. this.preassignedLevel = false;
  8370. this.imagelist = imagelist;
  8371. this.grouplist = grouplist;
  8372. // physics properties
  8373. this.fx = 0.0; // external force x
  8374. this.fy = 0.0; // external force y
  8375. this.vx = 0.0; // velocity x
  8376. this.vy = 0.0; // velocity y
  8377. this.minForce = constants.minForce;
  8378. this.damping = constants.physics.damping;
  8379. this.mass = 1; // kg
  8380. this.fixedData = {x:null,y:null};
  8381. this.setProperties(properties, constants);
  8382. // creating the variables for clustering
  8383. this.resetCluster();
  8384. this.dynamicEdgesLength = 0;
  8385. this.clusterSession = 0;
  8386. this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width;
  8387. this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height;
  8388. this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius;
  8389. this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements;
  8390. this.growthIndicator = 0;
  8391. // variables to tell the node about the graph.
  8392. this.graphScaleInv = 1;
  8393. this.graphScale = 1;
  8394. this.canvasTopLeft = {"x": -300, "y": -300};
  8395. this.canvasBottomRight = {"x": 300, "y": 300};
  8396. this.parentEdgeId = null;
  8397. }
  8398. /**
  8399. * (re)setting the clustering variables and objects
  8400. */
  8401. Node.prototype.resetCluster = function() {
  8402. // clustering variables
  8403. this.formationScale = undefined; // this is used to determine when to open the cluster
  8404. this.clusterSize = 1; // this signifies the total amount of nodes in this cluster
  8405. this.containedNodes = {};
  8406. this.containedEdges = {};
  8407. this.clusterSessions = [];
  8408. };
  8409. /**
  8410. * Attach a edge to the node
  8411. * @param {Edge} edge
  8412. */
  8413. Node.prototype.attachEdge = function(edge) {
  8414. if (this.edges.indexOf(edge) == -1) {
  8415. this.edges.push(edge);
  8416. }
  8417. if (this.dynamicEdges.indexOf(edge) == -1) {
  8418. this.dynamicEdges.push(edge);
  8419. }
  8420. this.dynamicEdgesLength = this.dynamicEdges.length;
  8421. };
  8422. /**
  8423. * Detach a edge from the node
  8424. * @param {Edge} edge
  8425. */
  8426. Node.prototype.detachEdge = function(edge) {
  8427. var index = this.edges.indexOf(edge);
  8428. if (index != -1) {
  8429. this.edges.splice(index, 1);
  8430. this.dynamicEdges.splice(index, 1);
  8431. }
  8432. this.dynamicEdgesLength = this.dynamicEdges.length;
  8433. };
  8434. /**
  8435. * Set or overwrite properties for the node
  8436. * @param {Object} properties an object with properties
  8437. * @param {Object} constants and object with default, global properties
  8438. */
  8439. Node.prototype.setProperties = function(properties, constants) {
  8440. if (!properties) {
  8441. return;
  8442. }
  8443. this.originalLabel = undefined;
  8444. // basic properties
  8445. if (properties.id !== undefined) {this.id = properties.id;}
  8446. if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;}
  8447. if (properties.title !== undefined) {this.title = properties.title;}
  8448. if (properties.group !== undefined) {this.group = properties.group;}
  8449. if (properties.x !== undefined) {this.x = properties.x;}
  8450. if (properties.y !== undefined) {this.y = properties.y;}
  8451. if (properties.value !== undefined) {this.value = properties.value;}
  8452. if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
  8453. // physics
  8454. if (properties.mass !== undefined) {this.mass = properties.mass;}
  8455. // navigation controls properties
  8456. if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;}
  8457. if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;}
  8458. if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;}
  8459. if (this.id === undefined) {
  8460. throw "Node must have an id";
  8461. }
  8462. // copy group properties
  8463. if (this.group) {
  8464. var groupObj = this.grouplist.get(this.group);
  8465. for (var prop in groupObj) {
  8466. if (groupObj.hasOwnProperty(prop)) {
  8467. this[prop] = groupObj[prop];
  8468. }
  8469. }
  8470. }
  8471. // individual shape properties
  8472. if (properties.shape !== undefined) {this.shape = properties.shape;}
  8473. if (properties.image !== undefined) {this.image = properties.image;}
  8474. if (properties.radius !== undefined) {this.radius = properties.radius;}
  8475. if (properties.color !== undefined) {this.color = util.parseColor(properties.color);}
  8476. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  8477. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  8478. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  8479. if (this.image !== undefined && this.image != "") {
  8480. if (this.imagelist) {
  8481. this.imageObj = this.imagelist.load(this.image);
  8482. }
  8483. else {
  8484. throw "No imagelist provided";
  8485. }
  8486. }
  8487. this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX);
  8488. this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY);
  8489. this.radiusFixed = this.radiusFixed || (properties.radius !== undefined);
  8490. if (this.shape == 'image') {
  8491. this.radiusMin = constants.nodes.widthMin;
  8492. this.radiusMax = constants.nodes.widthMax;
  8493. }
  8494. // choose draw method depending on the shape
  8495. switch (this.shape) {
  8496. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  8497. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  8498. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  8499. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8500. // TODO: add diamond shape
  8501. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  8502. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  8503. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  8504. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  8505. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  8506. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  8507. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  8508. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  8509. }
  8510. // reset the size of the node, this can be changed
  8511. this._reset();
  8512. };
  8513. /**
  8514. * select this node
  8515. */
  8516. Node.prototype.select = function() {
  8517. this.selected = true;
  8518. this._reset();
  8519. };
  8520. /**
  8521. * unselect this node
  8522. */
  8523. Node.prototype.unselect = function() {
  8524. this.selected = false;
  8525. this._reset();
  8526. };
  8527. /**
  8528. * Reset the calculated size of the node, forces it to recalculate its size
  8529. */
  8530. Node.prototype.clearSizeCache = function() {
  8531. this._reset();
  8532. };
  8533. /**
  8534. * Reset the calculated size of the node, forces it to recalculate its size
  8535. * @private
  8536. */
  8537. Node.prototype._reset = function() {
  8538. this.width = undefined;
  8539. this.height = undefined;
  8540. };
  8541. /**
  8542. * get the title of this node.
  8543. * @return {string} title The title of the node, or undefined when no title
  8544. * has been set.
  8545. */
  8546. Node.prototype.getTitle = function() {
  8547. return typeof this.title === "function" ? this.title() : this.title;
  8548. };
  8549. /**
  8550. * Calculate the distance to the border of the Node
  8551. * @param {CanvasRenderingContext2D} ctx
  8552. * @param {Number} angle Angle in radians
  8553. * @returns {number} distance Distance to the border in pixels
  8554. */
  8555. Node.prototype.distanceToBorder = function (ctx, angle) {
  8556. var borderWidth = 1;
  8557. if (!this.width) {
  8558. this.resize(ctx);
  8559. }
  8560. switch (this.shape) {
  8561. case 'circle':
  8562. case 'dot':
  8563. return this.radius + borderWidth;
  8564. case 'ellipse':
  8565. var a = this.width / 2;
  8566. var b = this.height / 2;
  8567. var w = (Math.sin(angle) * a);
  8568. var h = (Math.cos(angle) * b);
  8569. return a * b / Math.sqrt(w * w + h * h);
  8570. // TODO: implement distanceToBorder for database
  8571. // TODO: implement distanceToBorder for triangle
  8572. // TODO: implement distanceToBorder for triangleDown
  8573. case 'box':
  8574. case 'image':
  8575. case 'text':
  8576. default:
  8577. if (this.width) {
  8578. return Math.min(
  8579. Math.abs(this.width / 2 / Math.cos(angle)),
  8580. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  8581. // TODO: reckon with border radius too in case of box
  8582. }
  8583. else {
  8584. return 0;
  8585. }
  8586. }
  8587. // TODO: implement calculation of distance to border for all shapes
  8588. };
  8589. /**
  8590. * Set forces acting on the node
  8591. * @param {number} fx Force in horizontal direction
  8592. * @param {number} fy Force in vertical direction
  8593. */
  8594. Node.prototype._setForce = function(fx, fy) {
  8595. this.fx = fx;
  8596. this.fy = fy;
  8597. };
  8598. /**
  8599. * Add forces acting on the node
  8600. * @param {number} fx Force in horizontal direction
  8601. * @param {number} fy Force in vertical direction
  8602. * @private
  8603. */
  8604. Node.prototype._addForce = function(fx, fy) {
  8605. this.fx += fx;
  8606. this.fy += fy;
  8607. };
  8608. /**
  8609. * Perform one discrete step for the node
  8610. * @param {number} interval Time interval in seconds
  8611. */
  8612. Node.prototype.discreteStep = function(interval) {
  8613. if (!this.xFixed) {
  8614. var dx = this.damping * this.vx; // damping force
  8615. var ax = (this.fx - dx) / this.mass; // acceleration
  8616. this.vx += ax * interval; // velocity
  8617. this.x += this.vx * interval; // position
  8618. }
  8619. if (!this.yFixed) {
  8620. var dy = this.damping * this.vy; // damping force
  8621. var ay = (this.fy - dy) / this.mass; // acceleration
  8622. this.vy += ay * interval; // velocity
  8623. this.y += this.vy * interval; // position
  8624. }
  8625. };
  8626. /**
  8627. * Perform one discrete step for the node
  8628. * @param {number} interval Time interval in seconds
  8629. */
  8630. Node.prototype.discreteStepLimited = function(interval, maxVelocity) {
  8631. if (!this.xFixed) {
  8632. var dx = this.damping * this.vx; // damping force
  8633. var ax = (this.fx - dx) / this.mass; // acceleration
  8634. this.vx += ax * interval; // velocity
  8635. this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx;
  8636. this.x += this.vx * interval; // position
  8637. }
  8638. else {
  8639. this.fx = 0;
  8640. }
  8641. if (!this.yFixed) {
  8642. var dy = this.damping * this.vy; // damping force
  8643. var ay = (this.fy - dy) / this.mass; // acceleration
  8644. this.vy += ay * interval; // velocity
  8645. this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy;
  8646. this.y += this.vy * interval; // position
  8647. }
  8648. else {
  8649. this.fy = 0;
  8650. }
  8651. };
  8652. /**
  8653. * Check if this node has a fixed x and y position
  8654. * @return {boolean} true if fixed, false if not
  8655. */
  8656. Node.prototype.isFixed = function() {
  8657. return (this.xFixed && this.yFixed);
  8658. };
  8659. /**
  8660. * Check if this node is moving
  8661. * @param {number} vmin the minimum velocity considered as "moving"
  8662. * @return {boolean} true if moving, false if it has no velocity
  8663. */
  8664. // TODO: replace this method with calculating the kinetic energy
  8665. Node.prototype.isMoving = function(vmin) {
  8666. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin);
  8667. };
  8668. /**
  8669. * check if this node is selecte
  8670. * @return {boolean} selected True if node is selected, else false
  8671. */
  8672. Node.prototype.isSelected = function() {
  8673. return this.selected;
  8674. };
  8675. /**
  8676. * Retrieve the value of the node. Can be undefined
  8677. * @return {Number} value
  8678. */
  8679. Node.prototype.getValue = function() {
  8680. return this.value;
  8681. };
  8682. /**
  8683. * Calculate the distance from the nodes location to the given location (x,y)
  8684. * @param {Number} x
  8685. * @param {Number} y
  8686. * @return {Number} value
  8687. */
  8688. Node.prototype.getDistance = function(x, y) {
  8689. var dx = this.x - x,
  8690. dy = this.y - y;
  8691. return Math.sqrt(dx * dx + dy * dy);
  8692. };
  8693. /**
  8694. * Adjust the value range of the node. The node will adjust it's radius
  8695. * based on its value.
  8696. * @param {Number} min
  8697. * @param {Number} max
  8698. */
  8699. Node.prototype.setValueRange = function(min, max) {
  8700. if (!this.radiusFixed && this.value !== undefined) {
  8701. if (max == min) {
  8702. this.radius = (this.radiusMin + this.radiusMax) / 2;
  8703. }
  8704. else {
  8705. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  8706. this.radius = (this.value - min) * scale + this.radiusMin;
  8707. }
  8708. }
  8709. this.baseRadiusValue = this.radius;
  8710. };
  8711. /**
  8712. * Draw this node in the given canvas
  8713. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8714. * @param {CanvasRenderingContext2D} ctx
  8715. */
  8716. Node.prototype.draw = function(ctx) {
  8717. throw "Draw method not initialized for node";
  8718. };
  8719. /**
  8720. * Recalculate the size of this node in the given canvas
  8721. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8722. * @param {CanvasRenderingContext2D} ctx
  8723. */
  8724. Node.prototype.resize = function(ctx) {
  8725. throw "Resize method not initialized for node";
  8726. };
  8727. /**
  8728. * Check if this object is overlapping with the provided object
  8729. * @param {Object} obj an object with parameters left, top, right, bottom
  8730. * @return {boolean} True if location is located on node
  8731. */
  8732. Node.prototype.isOverlappingWith = function(obj) {
  8733. return (this.left < obj.right &&
  8734. this.left + this.width > obj.left &&
  8735. this.top < obj.bottom &&
  8736. this.top + this.height > obj.top);
  8737. };
  8738. Node.prototype._resizeImage = function (ctx) {
  8739. // TODO: pre calculate the image size
  8740. if (!this.width || !this.height) { // undefined or 0
  8741. var width, height;
  8742. if (this.value) {
  8743. this.radius = this.baseRadiusValue;
  8744. var scale = this.imageObj.height / this.imageObj.width;
  8745. if (scale !== undefined) {
  8746. width = this.radius || this.imageObj.width;
  8747. height = this.radius * scale || this.imageObj.height;
  8748. }
  8749. else {
  8750. width = 0;
  8751. height = 0;
  8752. }
  8753. }
  8754. else {
  8755. width = this.imageObj.width;
  8756. height = this.imageObj.height;
  8757. }
  8758. this.width = width;
  8759. this.height = height;
  8760. this.growthIndicator = 0;
  8761. if (this.width > 0 && this.height > 0) {
  8762. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8763. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8764. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8765. this.growthIndicator = this.width - width;
  8766. }
  8767. }
  8768. };
  8769. Node.prototype._drawImage = function (ctx) {
  8770. this._resizeImage(ctx);
  8771. this.left = this.x - this.width / 2;
  8772. this.top = this.y - this.height / 2;
  8773. var yLabel;
  8774. if (this.imageObj.width != 0 ) {
  8775. // draw the shade
  8776. if (this.clusterSize > 1) {
  8777. var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0);
  8778. lineWidth *= this.graphScaleInv;
  8779. lineWidth = Math.min(0.2 * this.width,lineWidth);
  8780. ctx.globalAlpha = 0.5;
  8781. ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth);
  8782. }
  8783. // draw the image
  8784. ctx.globalAlpha = 1.0;
  8785. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  8786. yLabel = this.y + this.height / 2;
  8787. }
  8788. else {
  8789. // image still loading... just draw the label for now
  8790. yLabel = this.y;
  8791. }
  8792. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  8793. };
  8794. Node.prototype._resizeBox = function (ctx) {
  8795. if (!this.width) {
  8796. var margin = 5;
  8797. var textSize = this.getTextSize(ctx);
  8798. this.width = textSize.width + 2 * margin;
  8799. this.height = textSize.height + 2 * margin;
  8800. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8801. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8802. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  8803. // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8804. }
  8805. };
  8806. Node.prototype._drawBox = function (ctx) {
  8807. this._resizeBox(ctx);
  8808. this.left = this.x - this.width / 2;
  8809. this.top = this.y - this.height / 2;
  8810. var clusterLineWidth = 2.5;
  8811. var selectionLineWidth = 2;
  8812. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8813. // draw the outer border
  8814. if (this.clusterSize > 1) {
  8815. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8816. ctx.lineWidth *= this.graphScaleInv;
  8817. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8818. ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
  8819. ctx.stroke();
  8820. }
  8821. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8822. ctx.lineWidth *= this.graphScaleInv;
  8823. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8824. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8825. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  8826. ctx.fill();
  8827. ctx.stroke();
  8828. this._label(ctx, this.label, this.x, this.y);
  8829. };
  8830. Node.prototype._resizeDatabase = function (ctx) {
  8831. if (!this.width) {
  8832. var margin = 5;
  8833. var textSize = this.getTextSize(ctx);
  8834. var size = textSize.width + 2 * margin;
  8835. this.width = size;
  8836. this.height = size;
  8837. // scaling used for clustering
  8838. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8839. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8840. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8841. this.growthIndicator = this.width - size;
  8842. }
  8843. };
  8844. Node.prototype._drawDatabase = function (ctx) {
  8845. this._resizeDatabase(ctx);
  8846. this.left = this.x - this.width / 2;
  8847. this.top = this.y - this.height / 2;
  8848. var clusterLineWidth = 2.5;
  8849. var selectionLineWidth = 2;
  8850. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8851. // draw the outer border
  8852. if (this.clusterSize > 1) {
  8853. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8854. ctx.lineWidth *= this.graphScaleInv;
  8855. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8856. ctx.database(this.x - this.width/2 - 2*ctx.lineWidth, this.y - this.height*0.5 - 2*ctx.lineWidth, this.width + 4*ctx.lineWidth, this.height + 4*ctx.lineWidth);
  8857. ctx.stroke();
  8858. }
  8859. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8860. ctx.lineWidth *= this.graphScaleInv;
  8861. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8862. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8863. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  8864. ctx.fill();
  8865. ctx.stroke();
  8866. this._label(ctx, this.label, this.x, this.y);
  8867. };
  8868. Node.prototype._resizeCircle = function (ctx) {
  8869. if (!this.width) {
  8870. var margin = 5;
  8871. var textSize = this.getTextSize(ctx);
  8872. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  8873. this.radius = diameter / 2;
  8874. this.width = diameter;
  8875. this.height = diameter;
  8876. // scaling used for clustering
  8877. // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor;
  8878. // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor;
  8879. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8880. this.growthIndicator = this.radius - 0.5*diameter;
  8881. }
  8882. };
  8883. Node.prototype._drawCircle = function (ctx) {
  8884. this._resizeCircle(ctx);
  8885. this.left = this.x - this.width / 2;
  8886. this.top = this.y - this.height / 2;
  8887. var clusterLineWidth = 2.5;
  8888. var selectionLineWidth = 2;
  8889. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8890. // draw the outer border
  8891. if (this.clusterSize > 1) {
  8892. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8893. ctx.lineWidth *= this.graphScaleInv;
  8894. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8895. ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
  8896. ctx.stroke();
  8897. }
  8898. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8899. ctx.lineWidth *= this.graphScaleInv;
  8900. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8901. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8902. ctx.circle(this.x, this.y, this.radius);
  8903. ctx.fill();
  8904. ctx.stroke();
  8905. this._label(ctx, this.label, this.x, this.y);
  8906. };
  8907. Node.prototype._resizeEllipse = function (ctx) {
  8908. if (!this.width) {
  8909. var textSize = this.getTextSize(ctx);
  8910. this.width = textSize.width * 1.5;
  8911. this.height = textSize.height * 2;
  8912. if (this.width < this.height) {
  8913. this.width = this.height;
  8914. }
  8915. var defaultSize = this.width;
  8916. // scaling used for clustering
  8917. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8918. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8919. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  8920. this.growthIndicator = this.width - defaultSize;
  8921. }
  8922. };
  8923. Node.prototype._drawEllipse = function (ctx) {
  8924. this._resizeEllipse(ctx);
  8925. this.left = this.x - this.width / 2;
  8926. this.top = this.y - this.height / 2;
  8927. var clusterLineWidth = 2.5;
  8928. var selectionLineWidth = 2;
  8929. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8930. // draw the outer border
  8931. if (this.clusterSize > 1) {
  8932. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8933. ctx.lineWidth *= this.graphScaleInv;
  8934. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8935. ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
  8936. ctx.stroke();
  8937. }
  8938. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8939. ctx.lineWidth *= this.graphScaleInv;
  8940. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8941. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  8942. ctx.ellipse(this.left, this.top, this.width, this.height);
  8943. ctx.fill();
  8944. ctx.stroke();
  8945. this._label(ctx, this.label, this.x, this.y);
  8946. };
  8947. Node.prototype._drawDot = function (ctx) {
  8948. this._drawShape(ctx, 'circle');
  8949. };
  8950. Node.prototype._drawTriangle = function (ctx) {
  8951. this._drawShape(ctx, 'triangle');
  8952. };
  8953. Node.prototype._drawTriangleDown = function (ctx) {
  8954. this._drawShape(ctx, 'triangleDown');
  8955. };
  8956. Node.prototype._drawSquare = function (ctx) {
  8957. this._drawShape(ctx, 'square');
  8958. };
  8959. Node.prototype._drawStar = function (ctx) {
  8960. this._drawShape(ctx, 'star');
  8961. };
  8962. Node.prototype._resizeShape = function (ctx) {
  8963. if (!this.width) {
  8964. this.radius = this.baseRadiusValue;
  8965. var size = 2 * this.radius;
  8966. this.width = size;
  8967. this.height = size;
  8968. // scaling used for clustering
  8969. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  8970. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  8971. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor;
  8972. this.growthIndicator = this.width - size;
  8973. }
  8974. };
  8975. Node.prototype._drawShape = function (ctx, shape) {
  8976. this._resizeShape(ctx);
  8977. this.left = this.x - this.width / 2;
  8978. this.top = this.y - this.height / 2;
  8979. var clusterLineWidth = 2.5;
  8980. var selectionLineWidth = 2;
  8981. var radiusMultiplier = 2;
  8982. // choose draw method depending on the shape
  8983. switch (shape) {
  8984. case 'dot': radiusMultiplier = 2; break;
  8985. case 'square': radiusMultiplier = 2; break;
  8986. case 'triangle': radiusMultiplier = 3; break;
  8987. case 'triangleDown': radiusMultiplier = 3; break;
  8988. case 'star': radiusMultiplier = 4; break;
  8989. }
  8990. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  8991. // draw the outer border
  8992. if (this.clusterSize > 1) {
  8993. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  8994. ctx.lineWidth *= this.graphScaleInv;
  8995. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  8996. ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
  8997. ctx.stroke();
  8998. }
  8999. ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
  9000. ctx.lineWidth *= this.graphScaleInv;
  9001. ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
  9002. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  9003. ctx[shape](this.x, this.y, this.radius);
  9004. ctx.fill();
  9005. ctx.stroke();
  9006. if (this.label) {
  9007. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  9008. }
  9009. };
  9010. Node.prototype._resizeText = function (ctx) {
  9011. if (!this.width) {
  9012. var margin = 5;
  9013. var textSize = this.getTextSize(ctx);
  9014. this.width = textSize.width + 2 * margin;
  9015. this.height = textSize.height + 2 * margin;
  9016. // scaling used for clustering
  9017. this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor;
  9018. this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor;
  9019. this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor;
  9020. this.growthIndicator = this.width - (textSize.width + 2 * margin);
  9021. }
  9022. };
  9023. Node.prototype._drawText = function (ctx) {
  9024. this._resizeText(ctx);
  9025. this.left = this.x - this.width / 2;
  9026. this.top = this.y - this.height / 2;
  9027. this._label(ctx, this.label, this.x, this.y);
  9028. };
  9029. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  9030. if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) {
  9031. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9032. ctx.fillStyle = this.fontColor || "black";
  9033. ctx.textAlign = align || "center";
  9034. ctx.textBaseline = baseline || "middle";
  9035. var lines = text.split('\n'),
  9036. lineCount = lines.length,
  9037. fontSize = (this.fontSize + 4),
  9038. yLine = y + (1 - lineCount) / 2 * fontSize;
  9039. for (var i = 0; i < lineCount; i++) {
  9040. ctx.fillText(lines[i], x, yLine);
  9041. yLine += fontSize;
  9042. }
  9043. }
  9044. };
  9045. Node.prototype.getTextSize = function(ctx) {
  9046. if (this.label !== undefined) {
  9047. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  9048. var lines = this.label.split('\n'),
  9049. height = (this.fontSize + 4) * lines.length,
  9050. width = 0;
  9051. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  9052. width = Math.max(width, ctx.measureText(lines[i]).width);
  9053. }
  9054. return {"width": width, "height": height};
  9055. }
  9056. else {
  9057. return {"width": 0, "height": 0};
  9058. }
  9059. };
  9060. /**
  9061. * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn.
  9062. * there is a safety margin of 0.3 * width;
  9063. *
  9064. * @returns {boolean}
  9065. */
  9066. Node.prototype.inArea = function() {
  9067. if (this.width !== undefined) {
  9068. return (this.x + this.width*this.graphScaleInv >= this.canvasTopLeft.x &&
  9069. this.x - this.width*this.graphScaleInv < this.canvasBottomRight.x &&
  9070. this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y &&
  9071. this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y);
  9072. }
  9073. else {
  9074. return true;
  9075. }
  9076. };
  9077. /**
  9078. * checks if the core of the node is in the display area, this is used for opening clusters around zoom
  9079. * @returns {boolean}
  9080. */
  9081. Node.prototype.inView = function() {
  9082. return (this.x >= this.canvasTopLeft.x &&
  9083. this.x < this.canvasBottomRight.x &&
  9084. this.y >= this.canvasTopLeft.y &&
  9085. this.y < this.canvasBottomRight.y);
  9086. };
  9087. /**
  9088. * This allows the zoom level of the graph to influence the rendering
  9089. * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas
  9090. *
  9091. * @param scale
  9092. * @param canvasTopLeft
  9093. * @param canvasBottomRight
  9094. */
  9095. Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) {
  9096. this.graphScaleInv = 1.0/scale;
  9097. this.graphScale = scale;
  9098. this.canvasTopLeft = canvasTopLeft;
  9099. this.canvasBottomRight = canvasBottomRight;
  9100. };
  9101. /**
  9102. * This allows the zoom level of the graph to influence the rendering
  9103. *
  9104. * @param scale
  9105. */
  9106. Node.prototype.setScale = function(scale) {
  9107. this.graphScaleInv = 1.0/scale;
  9108. this.graphScale = scale;
  9109. };
  9110. /**
  9111. * set the velocity at 0. Is called when this node is contained in another during clustering
  9112. */
  9113. Node.prototype.clearVelocity = function() {
  9114. this.vx = 0;
  9115. this.vy = 0;
  9116. };
  9117. /**
  9118. * Basic preservation of (kinectic) energy
  9119. *
  9120. * @param massBeforeClustering
  9121. */
  9122. Node.prototype.updateVelocity = function(massBeforeClustering) {
  9123. var energyBefore = this.vx * this.vx * massBeforeClustering;
  9124. //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9125. this.vx = Math.sqrt(energyBefore/this.mass);
  9126. energyBefore = this.vy * this.vy * massBeforeClustering;
  9127. //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass);
  9128. this.vy = Math.sqrt(energyBefore/this.mass);
  9129. };
  9130. /**
  9131. * @class Edge
  9132. *
  9133. * A edge connects two nodes
  9134. * @param {Object} properties Object with properties. Must contain
  9135. * At least properties from and to.
  9136. * Available properties: from (number),
  9137. * to (number), label (string, color (string),
  9138. * width (number), style (string),
  9139. * length (number), title (string)
  9140. * @param {Graph} graph A graph object, used to find and edge to
  9141. * nodes.
  9142. * @param {Object} constants An object with default values for
  9143. * example for the color
  9144. */
  9145. function Edge (properties, graph, constants) {
  9146. if (!graph) {
  9147. throw "No graph provided";
  9148. }
  9149. this.graph = graph;
  9150. // initialize constants
  9151. this.widthMin = constants.edges.widthMin;
  9152. this.widthMax = constants.edges.widthMax;
  9153. // initialize variables
  9154. this.id = undefined;
  9155. this.fromId = undefined;
  9156. this.toId = undefined;
  9157. this.style = constants.edges.style;
  9158. this.title = undefined;
  9159. this.width = constants.edges.width;
  9160. this.value = undefined;
  9161. this.length = constants.physics.springLength;
  9162. this.customLength = false;
  9163. this.selected = false;
  9164. this.smooth = constants.smoothCurves;
  9165. this.from = null; // a node
  9166. this.to = null; // a node
  9167. this.via = null; // a temp node
  9168. // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
  9169. // by storing the original information we can revert to the original connection when the cluser is opened.
  9170. this.originalFromId = [];
  9171. this.originalToId = [];
  9172. this.connected = false;
  9173. // Added to support dashed lines
  9174. // David Jordan
  9175. // 2012-08-08
  9176. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  9177. this.color = {color:constants.edges.color.color,
  9178. highlight:constants.edges.color.highlight};
  9179. this.widthFixed = false;
  9180. this.lengthFixed = false;
  9181. this.setProperties(properties, constants);
  9182. }
  9183. /**
  9184. * Set or overwrite properties for the edge
  9185. * @param {Object} properties an object with properties
  9186. * @param {Object} constants and object with default, global properties
  9187. */
  9188. Edge.prototype.setProperties = function(properties, constants) {
  9189. if (!properties) {
  9190. return;
  9191. }
  9192. if (properties.from !== undefined) {this.fromId = properties.from;}
  9193. if (properties.to !== undefined) {this.toId = properties.to;}
  9194. if (properties.id !== undefined) {this.id = properties.id;}
  9195. if (properties.style !== undefined) {this.style = properties.style;}
  9196. if (properties.label !== undefined) {this.label = properties.label;}
  9197. if (this.label) {
  9198. this.fontSize = constants.edges.fontSize;
  9199. this.fontFace = constants.edges.fontFace;
  9200. this.fontColor = constants.edges.fontColor;
  9201. this.fontFill = constants.edges.fontFill;
  9202. if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
  9203. if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;}
  9204. if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;}
  9205. if (properties.fontFill !== undefined) {this.fontFill = properties.fontFill;}
  9206. }
  9207. if (properties.title !== undefined) {this.title = properties.title;}
  9208. if (properties.width !== undefined) {this.width = properties.width;}
  9209. if (properties.value !== undefined) {this.value = properties.value;}
  9210. if (properties.length !== undefined) {this.length = properties.length;
  9211. this.customLength = true;}
  9212. // Added to support dashed lines
  9213. // David Jordan
  9214. // 2012-08-08
  9215. if (properties.dash) {
  9216. if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;}
  9217. if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;}
  9218. if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;}
  9219. }
  9220. if (properties.color !== undefined) {
  9221. if (util.isString(properties.color)) {
  9222. this.color.color = properties.color;
  9223. this.color.highlight = properties.color;
  9224. }
  9225. else {
  9226. if (properties.color.color !== undefined) {this.color.color = properties.color.color;}
  9227. if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;}
  9228. }
  9229. }
  9230. // A node is connected when it has a from and to node.
  9231. this.connect();
  9232. this.widthFixed = this.widthFixed || (properties.width !== undefined);
  9233. this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
  9234. // set draw method based on style
  9235. switch (this.style) {
  9236. case 'line': this.draw = this._drawLine; break;
  9237. case 'arrow': this.draw = this._drawArrow; break;
  9238. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  9239. case 'dash-line': this.draw = this._drawDashLine; break;
  9240. default: this.draw = this._drawLine; break;
  9241. }
  9242. };
  9243. /**
  9244. * Connect an edge to its nodes
  9245. */
  9246. Edge.prototype.connect = function () {
  9247. this.disconnect();
  9248. this.from = this.graph.nodes[this.fromId] || null;
  9249. this.to = this.graph.nodes[this.toId] || null;
  9250. this.connected = (this.from && this.to);
  9251. if (this.connected) {
  9252. this.from.attachEdge(this);
  9253. this.to.attachEdge(this);
  9254. }
  9255. else {
  9256. if (this.from) {
  9257. this.from.detachEdge(this);
  9258. }
  9259. if (this.to) {
  9260. this.to.detachEdge(this);
  9261. }
  9262. }
  9263. };
  9264. /**
  9265. * Disconnect an edge from its nodes
  9266. */
  9267. Edge.prototype.disconnect = function () {
  9268. if (this.from) {
  9269. this.from.detachEdge(this);
  9270. this.from = null;
  9271. }
  9272. if (this.to) {
  9273. this.to.detachEdge(this);
  9274. this.to = null;
  9275. }
  9276. this.connected = false;
  9277. };
  9278. /**
  9279. * get the title of this edge.
  9280. * @return {string} title The title of the edge, or undefined when no title
  9281. * has been set.
  9282. */
  9283. Edge.prototype.getTitle = function() {
  9284. return typeof this.title === "function" ? this.title() : this.title;
  9285. };
  9286. /**
  9287. * Retrieve the value of the edge. Can be undefined
  9288. * @return {Number} value
  9289. */
  9290. Edge.prototype.getValue = function() {
  9291. return this.value;
  9292. };
  9293. /**
  9294. * Adjust the value range of the edge. The edge will adjust it's width
  9295. * based on its value.
  9296. * @param {Number} min
  9297. * @param {Number} max
  9298. */
  9299. Edge.prototype.setValueRange = function(min, max) {
  9300. if (!this.widthFixed && this.value !== undefined) {
  9301. var scale = (this.widthMax - this.widthMin) / (max - min);
  9302. this.width = (this.value - min) * scale + this.widthMin;
  9303. }
  9304. };
  9305. /**
  9306. * Redraw a edge
  9307. * Draw this edge in the given canvas
  9308. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9309. * @param {CanvasRenderingContext2D} ctx
  9310. */
  9311. Edge.prototype.draw = function(ctx) {
  9312. throw "Method draw not initialized in edge";
  9313. };
  9314. /**
  9315. * Check if this object is overlapping with the provided object
  9316. * @param {Object} obj an object with parameters left, top
  9317. * @return {boolean} True if location is located on the edge
  9318. */
  9319. Edge.prototype.isOverlappingWith = function(obj) {
  9320. if (this.connected) {
  9321. var distMax = 10;
  9322. var xFrom = this.from.x;
  9323. var yFrom = this.from.y;
  9324. var xTo = this.to.x;
  9325. var yTo = this.to.y;
  9326. var xObj = obj.left;
  9327. var yObj = obj.top;
  9328. var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  9329. return (dist < distMax);
  9330. }
  9331. else {
  9332. return false
  9333. }
  9334. };
  9335. /**
  9336. * Redraw a edge as a line
  9337. * Draw this edge in the given canvas
  9338. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9339. * @param {CanvasRenderingContext2D} ctx
  9340. * @private
  9341. */
  9342. Edge.prototype._drawLine = function(ctx) {
  9343. // set style
  9344. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9345. else {ctx.strokeStyle = this.color.color;}
  9346. ctx.lineWidth = this._getLineWidth();
  9347. if (this.from != this.to) {
  9348. // draw line
  9349. this._line(ctx);
  9350. // draw label
  9351. var point;
  9352. if (this.label) {
  9353. if (this.smooth == true) {
  9354. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9355. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9356. point = {x:midpointX, y:midpointY};
  9357. }
  9358. else {
  9359. point = this._pointOnLine(0.5);
  9360. }
  9361. this._label(ctx, this.label, point.x, point.y);
  9362. }
  9363. }
  9364. else {
  9365. var x, y;
  9366. var radius = this.length / 4;
  9367. var node = this.from;
  9368. if (!node.width) {
  9369. node.resize(ctx);
  9370. }
  9371. if (node.width > node.height) {
  9372. x = node.x + node.width / 2;
  9373. y = node.y - radius;
  9374. }
  9375. else {
  9376. x = node.x + radius;
  9377. y = node.y - node.height / 2;
  9378. }
  9379. this._circle(ctx, x, y, radius);
  9380. point = this._pointOnCircle(x, y, radius, 0.5);
  9381. this._label(ctx, this.label, point.x, point.y);
  9382. }
  9383. };
  9384. /**
  9385. * Get the line width of the edge. Depends on width and whether one of the
  9386. * connected nodes is selected.
  9387. * @return {Number} width
  9388. * @private
  9389. */
  9390. Edge.prototype._getLineWidth = function() {
  9391. if (this.selected == true) {
  9392. return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv;
  9393. }
  9394. else {
  9395. return this.width*this.graphScaleInv;
  9396. }
  9397. };
  9398. /**
  9399. * Draw a line between two nodes
  9400. * @param {CanvasRenderingContext2D} ctx
  9401. * @private
  9402. */
  9403. Edge.prototype._line = function (ctx) {
  9404. // draw a straight line
  9405. ctx.beginPath();
  9406. ctx.moveTo(this.from.x, this.from.y);
  9407. if (this.smooth == true) {
  9408. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9409. }
  9410. else {
  9411. ctx.lineTo(this.to.x, this.to.y);
  9412. }
  9413. ctx.stroke();
  9414. };
  9415. /**
  9416. * Draw a line from a node to itself, a circle
  9417. * @param {CanvasRenderingContext2D} ctx
  9418. * @param {Number} x
  9419. * @param {Number} y
  9420. * @param {Number} radius
  9421. * @private
  9422. */
  9423. Edge.prototype._circle = function (ctx, x, y, radius) {
  9424. // draw a circle
  9425. ctx.beginPath();
  9426. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9427. ctx.stroke();
  9428. };
  9429. /**
  9430. * Draw label with white background and with the middle at (x, y)
  9431. * @param {CanvasRenderingContext2D} ctx
  9432. * @param {String} text
  9433. * @param {Number} x
  9434. * @param {Number} y
  9435. * @private
  9436. */
  9437. Edge.prototype._label = function (ctx, text, x, y) {
  9438. if (text) {
  9439. // TODO: cache the calculated size
  9440. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  9441. this.fontSize + "px " + this.fontFace;
  9442. ctx.fillStyle = this.fontFill;
  9443. var width = ctx.measureText(text).width;
  9444. var height = this.fontSize;
  9445. var left = x - width / 2;
  9446. var top = y - height / 2;
  9447. ctx.fillRect(left, top, width, height);
  9448. // draw text
  9449. ctx.fillStyle = this.fontColor || "black";
  9450. ctx.textAlign = "left";
  9451. ctx.textBaseline = "top";
  9452. ctx.fillText(text, left, top);
  9453. }
  9454. };
  9455. /**
  9456. * Redraw a edge as a dashed line
  9457. * Draw this edge in the given canvas
  9458. * @author David Jordan
  9459. * @date 2012-08-08
  9460. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9461. * @param {CanvasRenderingContext2D} ctx
  9462. * @private
  9463. */
  9464. Edge.prototype._drawDashLine = function(ctx) {
  9465. // set style
  9466. if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
  9467. else {ctx.strokeStyle = this.color.color;}
  9468. ctx.lineWidth = this._getLineWidth();
  9469. // only firefox and chrome support this method, else we use the legacy one.
  9470. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
  9471. ctx.beginPath();
  9472. ctx.moveTo(this.from.x, this.from.y);
  9473. // configure the dash pattern
  9474. var pattern = [0];
  9475. if (this.dash.length !== undefined && this.dash.gap !== undefined) {
  9476. pattern = [this.dash.length,this.dash.gap];
  9477. }
  9478. else {
  9479. pattern = [5,5];
  9480. }
  9481. // set dash settings for chrome or firefox
  9482. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9483. ctx.setLineDash(pattern);
  9484. ctx.lineDashOffset = 0;
  9485. } else { //Firefox
  9486. ctx.mozDash = pattern;
  9487. ctx.mozDashOffset = 0;
  9488. }
  9489. // draw the line
  9490. if (this.smooth == true) {
  9491. ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
  9492. }
  9493. else {
  9494. ctx.lineTo(this.to.x, this.to.y);
  9495. }
  9496. ctx.stroke();
  9497. // restore the dash settings.
  9498. if (typeof ctx.setLineDash !== 'undefined') { //Chrome
  9499. ctx.setLineDash([0]);
  9500. ctx.lineDashOffset = 0;
  9501. } else { //Firefox
  9502. ctx.mozDash = [0];
  9503. ctx.mozDashOffset = 0;
  9504. }
  9505. }
  9506. else { // unsupporting smooth lines
  9507. // draw dashed line
  9508. ctx.beginPath();
  9509. ctx.lineCap = 'round';
  9510. if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
  9511. {
  9512. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9513. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  9514. }
  9515. 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
  9516. {
  9517. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  9518. [this.dash.length,this.dash.gap]);
  9519. }
  9520. else //If all else fails draw a line
  9521. {
  9522. ctx.moveTo(this.from.x, this.from.y);
  9523. ctx.lineTo(this.to.x, this.to.y);
  9524. }
  9525. ctx.stroke();
  9526. }
  9527. // draw label
  9528. if (this.label) {
  9529. var point;
  9530. if (this.smooth == true) {
  9531. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9532. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9533. point = {x:midpointX, y:midpointY};
  9534. }
  9535. else {
  9536. point = this._pointOnLine(0.5);
  9537. }
  9538. this._label(ctx, this.label, point.x, point.y);
  9539. }
  9540. };
  9541. /**
  9542. * Get a point on a line
  9543. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9544. * @return {Object} point
  9545. * @private
  9546. */
  9547. Edge.prototype._pointOnLine = function (percentage) {
  9548. return {
  9549. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  9550. y: (1 - percentage) * this.from.y + percentage * this.to.y
  9551. }
  9552. };
  9553. /**
  9554. * Get a point on a circle
  9555. * @param {Number} x
  9556. * @param {Number} y
  9557. * @param {Number} radius
  9558. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  9559. * @return {Object} point
  9560. * @private
  9561. */
  9562. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  9563. var angle = (percentage - 3/8) * 2 * Math.PI;
  9564. return {
  9565. x: x + radius * Math.cos(angle),
  9566. y: y - radius * Math.sin(angle)
  9567. }
  9568. };
  9569. /**
  9570. * Redraw a edge as a line with an arrow halfway the line
  9571. * Draw this edge in the given canvas
  9572. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9573. * @param {CanvasRenderingContext2D} ctx
  9574. * @private
  9575. */
  9576. Edge.prototype._drawArrowCenter = function(ctx) {
  9577. var point;
  9578. // set style
  9579. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9580. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9581. ctx.lineWidth = this._getLineWidth();
  9582. if (this.from != this.to) {
  9583. // draw line
  9584. this._line(ctx);
  9585. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9586. var length = 10 + 5 * this.width; // TODO: make customizable?
  9587. // draw an arrow halfway the line
  9588. if (this.smooth == true) {
  9589. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9590. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9591. point = {x:midpointX, y:midpointY};
  9592. }
  9593. else {
  9594. point = this._pointOnLine(0.5);
  9595. }
  9596. ctx.arrow(point.x, point.y, angle, length);
  9597. ctx.fill();
  9598. ctx.stroke();
  9599. // draw label
  9600. if (this.label) {
  9601. this._label(ctx, this.label, point.x, point.y);
  9602. }
  9603. }
  9604. else {
  9605. // draw circle
  9606. var x, y;
  9607. var radius = 0.25 * Math.max(100,this.length);
  9608. var node = this.from;
  9609. if (!node.width) {
  9610. node.resize(ctx);
  9611. }
  9612. if (node.width > node.height) {
  9613. x = node.x + node.width * 0.5;
  9614. y = node.y - radius;
  9615. }
  9616. else {
  9617. x = node.x + radius;
  9618. y = node.y - node.height * 0.5;
  9619. }
  9620. this._circle(ctx, x, y, radius);
  9621. // draw all arrows
  9622. var angle = 0.2 * Math.PI;
  9623. var length = 10 + 5 * this.width; // TODO: make customizable?
  9624. point = this._pointOnCircle(x, y, radius, 0.5);
  9625. ctx.arrow(point.x, point.y, angle, length);
  9626. ctx.fill();
  9627. ctx.stroke();
  9628. // draw label
  9629. if (this.label) {
  9630. point = this._pointOnCircle(x, y, radius, 0.5);
  9631. this._label(ctx, this.label, point.x, point.y);
  9632. }
  9633. }
  9634. };
  9635. /**
  9636. * Redraw a edge as a line with an arrow
  9637. * Draw this edge in the given canvas
  9638. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9639. * @param {CanvasRenderingContext2D} ctx
  9640. * @private
  9641. */
  9642. Edge.prototype._drawArrow = function(ctx) {
  9643. // set style
  9644. if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;}
  9645. else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;}
  9646. ctx.lineWidth = this._getLineWidth();
  9647. var angle, length;
  9648. //draw a line
  9649. if (this.from != this.to) {
  9650. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  9651. var dx = (this.to.x - this.from.x);
  9652. var dy = (this.to.y - this.from.y);
  9653. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9654. var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
  9655. var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
  9656. var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
  9657. var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
  9658. if (this.smooth == true) {
  9659. angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
  9660. dx = (this.to.x - this.via.x);
  9661. dy = (this.to.y - this.via.y);
  9662. edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  9663. }
  9664. var toBorderDist = this.to.distanceToBorder(ctx, angle);
  9665. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  9666. var xTo,yTo;
  9667. if (this.smooth == true) {
  9668. xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
  9669. yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
  9670. }
  9671. else {
  9672. xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
  9673. yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
  9674. }
  9675. ctx.beginPath();
  9676. ctx.moveTo(xFrom,yFrom);
  9677. if (this.smooth == true) {
  9678. ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
  9679. }
  9680. else {
  9681. ctx.lineTo(xTo, yTo);
  9682. }
  9683. ctx.stroke();
  9684. // draw arrow at the end of the line
  9685. length = 10 + 5 * this.width;
  9686. ctx.arrow(xTo, yTo, angle, length);
  9687. ctx.fill();
  9688. ctx.stroke();
  9689. // draw label
  9690. if (this.label) {
  9691. var point;
  9692. if (this.smooth == true) {
  9693. var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
  9694. var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
  9695. point = {x:midpointX, y:midpointY};
  9696. }
  9697. else {
  9698. point = this._pointOnLine(0.5);
  9699. }
  9700. this._label(ctx, this.label, point.x, point.y);
  9701. }
  9702. }
  9703. else {
  9704. // draw circle
  9705. var node = this.from;
  9706. var x, y, arrow;
  9707. var radius = 0.25 * Math.max(100,this.length);
  9708. if (!node.width) {
  9709. node.resize(ctx);
  9710. }
  9711. if (node.width > node.height) {
  9712. x = node.x + node.width * 0.5;
  9713. y = node.y - radius;
  9714. arrow = {
  9715. x: x,
  9716. y: node.y,
  9717. angle: 0.9 * Math.PI
  9718. };
  9719. }
  9720. else {
  9721. x = node.x + radius;
  9722. y = node.y - node.height * 0.5;
  9723. arrow = {
  9724. x: node.x,
  9725. y: y,
  9726. angle: 0.6 * Math.PI
  9727. };
  9728. }
  9729. ctx.beginPath();
  9730. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  9731. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  9732. ctx.stroke();
  9733. // draw all arrows
  9734. length = 10 + 5 * this.width; // TODO: make customizable?
  9735. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  9736. ctx.fill();
  9737. ctx.stroke();
  9738. // draw label
  9739. if (this.label) {
  9740. point = this._pointOnCircle(x, y, radius, 0.5);
  9741. this._label(ctx, this.label, point.x, point.y);
  9742. }
  9743. }
  9744. };
  9745. /**
  9746. * Calculate the distance between a point (x3,y3) and a line segment from
  9747. * (x1,y1) to (x2,y2).
  9748. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  9749. * @param {number} x1
  9750. * @param {number} y1
  9751. * @param {number} x2
  9752. * @param {number} y2
  9753. * @param {number} x3
  9754. * @param {number} y3
  9755. * @private
  9756. */
  9757. Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  9758. if (this.smooth == true) {
  9759. var minDistance = 1e9;
  9760. var i,t,x,y,dx,dy;
  9761. for (i = 0; i < 10; i++) {
  9762. t = 0.1*i;
  9763. x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2;
  9764. y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
  9765. dx = Math.abs(x3-x);
  9766. dy = Math.abs(y3-y);
  9767. minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
  9768. }
  9769. return minDistance
  9770. }
  9771. else {
  9772. var px = x2-x1,
  9773. py = y2-y1,
  9774. something = px*px + py*py,
  9775. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  9776. if (u > 1) {
  9777. u = 1;
  9778. }
  9779. else if (u < 0) {
  9780. u = 0;
  9781. }
  9782. var x = x1 + u * px,
  9783. y = y1 + u * py,
  9784. dx = x - x3,
  9785. dy = y - y3;
  9786. //# Note: If the actual distance does not matter,
  9787. //# if you only want to compare what this function
  9788. //# returns to other results of this function, you
  9789. //# can just return the squared distance instead
  9790. //# (i.e. remove the sqrt) to gain a little performance
  9791. return Math.sqrt(dx*dx + dy*dy);
  9792. }
  9793. };
  9794. /**
  9795. * This allows the zoom level of the graph to influence the rendering
  9796. *
  9797. * @param scale
  9798. */
  9799. Edge.prototype.setScale = function(scale) {
  9800. this.graphScaleInv = 1.0/scale;
  9801. };
  9802. Edge.prototype.select = function() {
  9803. this.selected = true;
  9804. };
  9805. Edge.prototype.unselect = function() {
  9806. this.selected = false;
  9807. };
  9808. Edge.prototype.positionBezierNode = function() {
  9809. if (this.via !== null) {
  9810. this.via.x = 0.5 * (this.from.x + this.to.x);
  9811. this.via.y = 0.5 * (this.from.y + this.to.y);
  9812. }
  9813. };
  9814. /**
  9815. * Popup is a class to create a popup window with some text
  9816. * @param {Element} container The container object.
  9817. * @param {Number} [x]
  9818. * @param {Number} [y]
  9819. * @param {String} [text]
  9820. * @param {Object} [style] An object containing borderColor,
  9821. * backgroundColor, etc.
  9822. */
  9823. function Popup(container, x, y, text, style) {
  9824. if (container) {
  9825. this.container = container;
  9826. }
  9827. else {
  9828. this.container = document.body;
  9829. }
  9830. // x, y and text are optional, see if a style object was passed in their place
  9831. if (style === undefined) {
  9832. if (typeof x === "object") {
  9833. style = x;
  9834. x = undefined;
  9835. } else if (typeof text === "object") {
  9836. style = text;
  9837. text = undefined;
  9838. } else {
  9839. // for backwards compatibility, in case clients other than Graph are creating Popup directly
  9840. style = {
  9841. fontColor: 'black',
  9842. fontSize: 14, // px
  9843. fontFace: 'verdana',
  9844. color: {
  9845. border: '#666',
  9846. background: '#FFFFC6'
  9847. }
  9848. }
  9849. }
  9850. }
  9851. this.x = 0;
  9852. this.y = 0;
  9853. this.padding = 5;
  9854. if (x !== undefined && y !== undefined ) {
  9855. this.setPosition(x, y);
  9856. }
  9857. if (text !== undefined) {
  9858. this.setText(text);
  9859. }
  9860. // create the frame
  9861. this.frame = document.createElement("div");
  9862. var styleAttr = this.frame.style;
  9863. styleAttr.position = "absolute";
  9864. styleAttr.visibility = "hidden";
  9865. styleAttr.border = "1px solid " + style.color.border;
  9866. styleAttr.color = style.fontColor;
  9867. styleAttr.fontSize = style.fontSize + "px";
  9868. styleAttr.fontFamily = style.fontFace;
  9869. styleAttr.padding = this.padding + "px";
  9870. styleAttr.backgroundColor = style.color.background;
  9871. styleAttr.borderRadius = "3px";
  9872. styleAttr.MozBorderRadius = "3px";
  9873. styleAttr.WebkitBorderRadius = "3px";
  9874. styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  9875. styleAttr.whiteSpace = "nowrap";
  9876. this.container.appendChild(this.frame);
  9877. }
  9878. /**
  9879. * @param {number} x Horizontal position of the popup window
  9880. * @param {number} y Vertical position of the popup window
  9881. */
  9882. Popup.prototype.setPosition = function(x, y) {
  9883. this.x = parseInt(x);
  9884. this.y = parseInt(y);
  9885. };
  9886. /**
  9887. * Set the text for the popup window. This can be HTML code
  9888. * @param {string} text
  9889. */
  9890. Popup.prototype.setText = function(text) {
  9891. this.frame.innerHTML = text;
  9892. };
  9893. /**
  9894. * Show the popup window
  9895. * @param {boolean} show Optional. Show or hide the window
  9896. */
  9897. Popup.prototype.show = function (show) {
  9898. if (show === undefined) {
  9899. show = true;
  9900. }
  9901. if (show) {
  9902. var height = this.frame.clientHeight;
  9903. var width = this.frame.clientWidth;
  9904. var maxHeight = this.frame.parentNode.clientHeight;
  9905. var maxWidth = this.frame.parentNode.clientWidth;
  9906. var top = (this.y - height);
  9907. if (top + height + this.padding > maxHeight) {
  9908. top = maxHeight - height - this.padding;
  9909. }
  9910. if (top < this.padding) {
  9911. top = this.padding;
  9912. }
  9913. var left = this.x;
  9914. if (left + width + this.padding > maxWidth) {
  9915. left = maxWidth - width - this.padding;
  9916. }
  9917. if (left < this.padding) {
  9918. left = this.padding;
  9919. }
  9920. this.frame.style.left = left + "px";
  9921. this.frame.style.top = top + "px";
  9922. this.frame.style.visibility = "visible";
  9923. }
  9924. else {
  9925. this.hide();
  9926. }
  9927. };
  9928. /**
  9929. * Hide the popup window
  9930. */
  9931. Popup.prototype.hide = function () {
  9932. this.frame.style.visibility = "hidden";
  9933. };
  9934. /**
  9935. * @class Groups
  9936. * This class can store groups and properties specific for groups.
  9937. */
  9938. Groups = function () {
  9939. this.clear();
  9940. this.defaultIndex = 0;
  9941. };
  9942. /**
  9943. * default constants for group colors
  9944. */
  9945. Groups.DEFAULT = [
  9946. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  9947. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  9948. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  9949. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  9950. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  9951. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  9952. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  9953. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  9954. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  9955. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  9956. ];
  9957. /**
  9958. * Clear all groups
  9959. */
  9960. Groups.prototype.clear = function () {
  9961. this.groups = {};
  9962. this.groups.length = function()
  9963. {
  9964. var i = 0;
  9965. for ( var p in this ) {
  9966. if (this.hasOwnProperty(p)) {
  9967. i++;
  9968. }
  9969. }
  9970. return i;
  9971. }
  9972. };
  9973. /**
  9974. * get group properties of a groupname. If groupname is not found, a new group
  9975. * is added.
  9976. * @param {*} groupname Can be a number, string, Date, etc.
  9977. * @return {Object} group The created group, containing all group properties
  9978. */
  9979. Groups.prototype.get = function (groupname) {
  9980. var group = this.groups[groupname];
  9981. if (group == undefined) {
  9982. // create new group
  9983. var index = this.defaultIndex % Groups.DEFAULT.length;
  9984. this.defaultIndex++;
  9985. group = {};
  9986. group.color = Groups.DEFAULT[index];
  9987. this.groups[groupname] = group;
  9988. }
  9989. return group;
  9990. };
  9991. /**
  9992. * Add a custom group style
  9993. * @param {String} groupname
  9994. * @param {Object} style An object containing borderColor,
  9995. * backgroundColor, etc.
  9996. * @return {Object} group The created group object
  9997. */
  9998. Groups.prototype.add = function (groupname, style) {
  9999. this.groups[groupname] = style;
  10000. if (style.color) {
  10001. style.color = util.parseColor(style.color);
  10002. }
  10003. return style;
  10004. };
  10005. /**
  10006. * @class Images
  10007. * This class loads images and keeps them stored.
  10008. */
  10009. Images = function () {
  10010. this.images = {};
  10011. this.callback = undefined;
  10012. };
  10013. /**
  10014. * Set an onload callback function. This will be called each time an image
  10015. * is loaded
  10016. * @param {function} callback
  10017. */
  10018. Images.prototype.setOnloadCallback = function(callback) {
  10019. this.callback = callback;
  10020. };
  10021. /**
  10022. *
  10023. * @param {string} url Url of the image
  10024. * @return {Image} img The image object
  10025. */
  10026. Images.prototype.load = function(url) {
  10027. var img = this.images[url];
  10028. if (img == undefined) {
  10029. // create the image
  10030. var images = this;
  10031. img = new Image();
  10032. this.images[url] = img;
  10033. img.onload = function() {
  10034. if (images.callback) {
  10035. images.callback(this);
  10036. }
  10037. };
  10038. img.src = url;
  10039. }
  10040. return img;
  10041. };
  10042. /**
  10043. * Created by Alex on 2/6/14.
  10044. */
  10045. var physicsMixin = {
  10046. /**
  10047. * Toggling barnes Hut calculation on and off.
  10048. *
  10049. * @private
  10050. */
  10051. _toggleBarnesHut : function() {
  10052. this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
  10053. this._loadSelectedForceSolver();
  10054. this.moving = true;
  10055. this.start();
  10056. },
  10057. /**
  10058. * This loads the node force solver based on the barnes hut or repulsion algorithm
  10059. *
  10060. * @private
  10061. */
  10062. _loadSelectedForceSolver : function() {
  10063. // this overloads the this._calculateNodeForces
  10064. if (this.constants.physics.barnesHut.enabled == true) {
  10065. this._clearMixin(repulsionMixin);
  10066. this._clearMixin(hierarchalRepulsionMixin);
  10067. this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
  10068. this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
  10069. this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
  10070. this.constants.physics.damping = this.constants.physics.barnesHut.damping;
  10071. this._loadMixin(barnesHutMixin);
  10072. }
  10073. else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
  10074. this._clearMixin(barnesHutMixin);
  10075. this._clearMixin(repulsionMixin);
  10076. this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
  10077. this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
  10078. this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
  10079. this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
  10080. this._loadMixin(hierarchalRepulsionMixin);
  10081. }
  10082. else {
  10083. this._clearMixin(barnesHutMixin);
  10084. this._clearMixin(hierarchalRepulsionMixin);
  10085. this.barnesHutTree = undefined;
  10086. this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
  10087. this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
  10088. this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
  10089. this.constants.physics.damping = this.constants.physics.repulsion.damping;
  10090. this._loadMixin(repulsionMixin);
  10091. }
  10092. },
  10093. /**
  10094. * Before calculating the forces, we check if we need to cluster to keep up performance and we check
  10095. * if there is more than one node. If it is just one node, we dont calculate anything.
  10096. *
  10097. * @private
  10098. */
  10099. _initializeForceCalculation : function() {
  10100. // stop calculation if there is only one node
  10101. if (this.nodeIndices.length == 1) {
  10102. this.nodes[this.nodeIndices[0]]._setForce(0,0);
  10103. }
  10104. else {
  10105. // if there are too many nodes on screen, we cluster without repositioning
  10106. if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
  10107. this.clusterToFit(this.constants.clustering.reduceToNodes, false);
  10108. }
  10109. // we now start the force calculation
  10110. this._calculateForces();
  10111. }
  10112. },
  10113. /**
  10114. * Calculate the external forces acting on the nodes
  10115. * Forces are caused by: edges, repulsing forces between nodes, gravity
  10116. * @private
  10117. */
  10118. _calculateForces : function() {
  10119. // Gravity is required to keep separated groups from floating off
  10120. // the forces are reset to zero in this loop by using _setForce instead
  10121. // of _addForce
  10122. this._calculateGravitationalForces();
  10123. this._calculateNodeForces();
  10124. if (this.constants.smoothCurves == true) {
  10125. this._calculateSpringForcesWithSupport();
  10126. }
  10127. else {
  10128. this._calculateSpringForces();
  10129. }
  10130. },
  10131. /**
  10132. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  10133. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  10134. * This function joins the datanodes and invisible (called support) nodes into one object.
  10135. * We do this so we do not contaminate this.nodes with the support nodes.
  10136. *
  10137. * @private
  10138. */
  10139. _updateCalculationNodes : function() {
  10140. if (this.constants.smoothCurves == true) {
  10141. this.calculationNodes = {};
  10142. this.calculationNodeIndices = [];
  10143. for (var nodeId in this.nodes) {
  10144. if (this.nodes.hasOwnProperty(nodeId)) {
  10145. this.calculationNodes[nodeId] = this.nodes[nodeId];
  10146. }
  10147. }
  10148. var supportNodes = this.sectors['support']['nodes'];
  10149. for (var supportNodeId in supportNodes) {
  10150. if (supportNodes.hasOwnProperty(supportNodeId)) {
  10151. if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
  10152. this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  10153. }
  10154. else {
  10155. supportNodes[supportNodeId]._setForce(0,0);
  10156. }
  10157. }
  10158. }
  10159. for (var idx in this.calculationNodes) {
  10160. if (this.calculationNodes.hasOwnProperty(idx)) {
  10161. this.calculationNodeIndices.push(idx);
  10162. }
  10163. }
  10164. }
  10165. else {
  10166. this.calculationNodes = this.nodes;
  10167. this.calculationNodeIndices = this.nodeIndices;
  10168. }
  10169. },
  10170. /**
  10171. * this function applies the central gravity effect to keep groups from floating off
  10172. *
  10173. * @private
  10174. */
  10175. _calculateGravitationalForces : function() {
  10176. var dx, dy, distance, node, i;
  10177. var nodes = this.calculationNodes;
  10178. var gravity = this.constants.physics.centralGravity;
  10179. var gravityForce = 0;
  10180. for (i = 0; i < this.calculationNodeIndices.length; i++) {
  10181. node = nodes[this.calculationNodeIndices[i]];
  10182. node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
  10183. // gravity does not apply when we are in a pocket sector
  10184. if (this._sector() == "default" && gravity != 0) {
  10185. dx = -node.x;
  10186. dy = -node.y;
  10187. distance = Math.sqrt(dx*dx + dy*dy);
  10188. gravityForce = (distance == 0) ? 0 : (gravity / distance);
  10189. node.fx = dx * gravityForce;
  10190. node.fy = dy * gravityForce;
  10191. }
  10192. else {
  10193. node.fx = 0;
  10194. node.fy = 0;
  10195. }
  10196. }
  10197. },
  10198. /**
  10199. * this function calculates the effects of the springs in the case of unsmooth curves.
  10200. *
  10201. * @private
  10202. */
  10203. _calculateSpringForces : function() {
  10204. var edgeLength, edge, edgeId;
  10205. var dx, dy, fx, fy, springForce, length;
  10206. var edges = this.edges;
  10207. // forces caused by the edges, modelled as springs
  10208. for (edgeId in edges) {
  10209. if (edges.hasOwnProperty(edgeId)) {
  10210. edge = edges[edgeId];
  10211. if (edge.connected) {
  10212. // only calculate forces if nodes are in the same sector
  10213. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10214. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  10215. // this implies that the edges between big clusters are longer
  10216. edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
  10217. dx = (edge.from.x - edge.to.x);
  10218. dy = (edge.from.y - edge.to.y);
  10219. length = Math.sqrt(dx * dx + dy * dy);
  10220. if (length == 0) {
  10221. length = 0.01;
  10222. }
  10223. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10224. fx = dx * springForce;
  10225. fy = dy * springForce;
  10226. edge.from.fx += fx;
  10227. edge.from.fy += fy;
  10228. edge.to.fx -= fx;
  10229. edge.to.fy -= fy;
  10230. }
  10231. }
  10232. }
  10233. }
  10234. },
  10235. /**
  10236. * This function calculates the springforces on the nodes, accounting for the support nodes.
  10237. *
  10238. * @private
  10239. */
  10240. _calculateSpringForcesWithSupport : function() {
  10241. var edgeLength, edge, edgeId, combinedClusterSize;
  10242. var edges = this.edges;
  10243. // forces caused by the edges, modelled as springs
  10244. for (edgeId in edges) {
  10245. if (edges.hasOwnProperty(edgeId)) {
  10246. edge = edges[edgeId];
  10247. if (edge.connected) {
  10248. // only calculate forces if nodes are in the same sector
  10249. if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
  10250. if (edge.via != null) {
  10251. var node1 = edge.to;
  10252. var node2 = edge.via;
  10253. var node3 = edge.from;
  10254. edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
  10255. combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
  10256. // this implies that the edges between big clusters are longer
  10257. edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
  10258. this._calculateSpringForce(node1,node2,0.5*edgeLength);
  10259. this._calculateSpringForce(node2,node3,0.5*edgeLength);
  10260. }
  10261. }
  10262. }
  10263. }
  10264. }
  10265. },
  10266. /**
  10267. * This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
  10268. *
  10269. * @param node1
  10270. * @param node2
  10271. * @param edgeLength
  10272. * @private
  10273. */
  10274. _calculateSpringForce : function(node1,node2,edgeLength) {
  10275. var dx, dy, fx, fy, springForce, length;
  10276. dx = (node1.x - node2.x);
  10277. dy = (node1.y - node2.y);
  10278. length = Math.sqrt(dx * dx + dy * dy);
  10279. if (length == 0) {
  10280. length = 0.01;
  10281. }
  10282. springForce = this.constants.physics.springConstant * (edgeLength - length) / length;
  10283. fx = dx * springForce;
  10284. fy = dy * springForce;
  10285. node1.fx += fx;
  10286. node1.fy += fy;
  10287. node2.fx -= fx;
  10288. node2.fy -= fy;
  10289. },
  10290. /**
  10291. * Load the HTML for the physics config and bind it
  10292. * @private
  10293. */
  10294. _loadPhysicsConfiguration : function() {
  10295. if (this.physicsConfiguration === undefined) {
  10296. this.backupConstants = {};
  10297. util.copyObject(this.constants,this.backupConstants);
  10298. var hierarchicalLayoutDirections = ["LR","RL","UD","DU"];
  10299. this.physicsConfiguration = document.createElement('div');
  10300. this.physicsConfiguration.className = "PhysicsConfiguration";
  10301. this.physicsConfiguration.innerHTML = '' +
  10302. '<table><tr><td><b>Simulation Mode:</b></td></tr>' +
  10303. '<tr>' +
  10304. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
  10305. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>'+
  10306. '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
  10307. '</tr>'+
  10308. '</table>' +
  10309. '<table id="graph_BH_table" style="display:none">'+
  10310. '<tr><td><b>Barnes Hut</b></td></tr>'+
  10311. '<tr>'+
  10312. '<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>'+
  10313. '</tr>'+
  10314. '<tr>'+
  10315. '<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>'+
  10316. '</tr>'+
  10317. '<tr>'+
  10318. '<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>'+
  10319. '</tr>'+
  10320. '<tr>'+
  10321. '<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>'+
  10322. '</tr>'+
  10323. '<tr>'+
  10324. '<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>'+
  10325. '</tr>'+
  10326. '</table>'+
  10327. '<table id="graph_R_table" style="display:none">'+
  10328. '<tr><td><b>Repulsion</b></td></tr>'+
  10329. '<tr>'+
  10330. '<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>'+
  10331. '</tr>'+
  10332. '<tr>'+
  10333. '<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>'+
  10334. '</tr>'+
  10335. '<tr>'+
  10336. '<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>'+
  10337. '</tr>'+
  10338. '<tr>'+
  10339. '<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>'+
  10340. '</tr>'+
  10341. '<tr>'+
  10342. '<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>'+
  10343. '</tr>'+
  10344. '</table>'+
  10345. '<table id="graph_H_table" style="display:none">'+
  10346. '<tr><td width="150"><b>Hierarchical</b></td></tr>'+
  10347. '<tr>'+
  10348. '<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>'+
  10349. '</tr>'+
  10350. '<tr>'+
  10351. '<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>'+
  10352. '</tr>'+
  10353. '<tr>'+
  10354. '<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>'+
  10355. '</tr>'+
  10356. '<tr>'+
  10357. '<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>'+
  10358. '</tr>'+
  10359. '<tr>'+
  10360. '<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>'+
  10361. '</tr>'+
  10362. '<tr>'+
  10363. '<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>'+
  10364. '</tr>'+
  10365. '<tr>'+
  10366. '<td width="150px">levelSeparation</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.levelSeparation + '" step="1" style="width:300px" id="graph_H_levsep"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.levelSeparation + '" id="graph_H_levsep_value" style="width:60px"></td>'+
  10367. '</tr>'+
  10368. '<tr>'+
  10369. '<td width="150px">nodeSpacing</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.nodeSpacing + '" step="1" style="width:300px" id="graph_H_nspac"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.nodeSpacing + '" id="graph_H_nspac_value" style="width:60px"></td>'+
  10370. '</tr>'+
  10371. '</table>' +
  10372. '<table><tr><td><b>Options:</b></td></tr>' +
  10373. '<tr>' +
  10374. '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
  10375. '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
  10376. '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
  10377. '</tr>'+
  10378. '</table>'
  10379. this.containerElement.parentElement.insertBefore(this.physicsConfiguration,this.containerElement);
  10380. this.optionsDiv = document.createElement("div");
  10381. this.optionsDiv.style.fontSize = "14px";
  10382. this.optionsDiv.style.fontFamily = "verdana";
  10383. this.containerElement.parentElement.insertBefore(this.optionsDiv,this.containerElement);
  10384. var rangeElement;
  10385. rangeElement = document.getElementById('graph_BH_gc');
  10386. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_gc',-1,"physics_barnesHut_gravitationalConstant");
  10387. rangeElement = document.getElementById('graph_BH_cg');
  10388. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_cg',1,"physics_centralGravity");
  10389. rangeElement = document.getElementById('graph_BH_sc');
  10390. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_sc',1,"physics_springConstant");
  10391. rangeElement = document.getElementById('graph_BH_sl');
  10392. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_sl',1,"physics_springLength");
  10393. rangeElement = document.getElementById('graph_BH_damp');
  10394. rangeElement.onchange = showValueOfRange.bind(this,'graph_BH_damp',1,"physics_damping");
  10395. rangeElement = document.getElementById('graph_R_nd');
  10396. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_nd',1,"physics_repulsion_nodeDistance");
  10397. rangeElement = document.getElementById('graph_R_cg');
  10398. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_cg',1,"physics_centralGravity");
  10399. rangeElement = document.getElementById('graph_R_sc');
  10400. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_sc',1,"physics_springConstant");
  10401. rangeElement = document.getElementById('graph_R_sl');
  10402. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_sl',1,"physics_springLength");
  10403. rangeElement = document.getElementById('graph_R_damp');
  10404. rangeElement.onchange = showValueOfRange.bind(this,'graph_R_damp',1,"physics_damping");
  10405. rangeElement = document.getElementById('graph_H_nd');
  10406. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_nd',1,"physics_hierarchicalRepulsion_nodeDistance");
  10407. rangeElement = document.getElementById('graph_H_cg');
  10408. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_cg',1,"physics_centralGravity");
  10409. rangeElement = document.getElementById('graph_H_sc');
  10410. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_sc',1,"physics_springConstant");
  10411. rangeElement = document.getElementById('graph_H_sl');
  10412. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_sl',1,"physics_springLength");
  10413. rangeElement = document.getElementById('graph_H_damp');
  10414. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_damp',1,"physics_damping");
  10415. rangeElement = document.getElementById('graph_H_direction');
  10416. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_direction',hierarchicalLayoutDirections,"hierarchicalLayout_direction");
  10417. rangeElement = document.getElementById('graph_H_levsep');
  10418. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_levsep',1,"hierarchicalLayout_levelSeparation");
  10419. rangeElement = document.getElementById('graph_H_nspac');
  10420. rangeElement.onchange = showValueOfRange.bind(this,'graph_H_nspac',1,"hierarchicalLayout_nodeSpacing");
  10421. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10422. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10423. var radioButton3 = document.getElementById("graph_physicsMethod3");
  10424. radioButton2.checked = true;
  10425. if (this.constants.physics.barnesHut.enabled) {
  10426. radioButton1.checked = true;
  10427. }
  10428. if (this.constants.hierarchicalLayout.enabled) {
  10429. radioButton3.checked = true;
  10430. }
  10431. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10432. var graph_repositionNodes = document.getElementById("graph_repositionNodes");
  10433. var graph_generateOptions = document.getElementById("graph_generateOptions");
  10434. graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
  10435. graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
  10436. graph_generateOptions.onclick = graphGenerateOptions.bind(this);
  10437. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10438. else {graph_toggleSmooth.style.background = "#FF8532";}
  10439. switchConfigurations.apply(this);
  10440. radioButton1.onchange = switchConfigurations.bind(this);
  10441. radioButton2.onchange = switchConfigurations.bind(this);
  10442. radioButton3.onchange = switchConfigurations.bind(this);
  10443. }
  10444. },
  10445. _overWriteGraphConstants : function(constantsVariableName, value) {
  10446. var nameArray = constantsVariableName.split("_");
  10447. if (nameArray.length == 1) {
  10448. this.constants[nameArray[0]] = value;
  10449. }
  10450. else if (nameArray.length == 2) {
  10451. this.constants[nameArray[0]][nameArray[1]] = value;
  10452. }
  10453. else if (nameArray.length == 3) {
  10454. this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
  10455. }
  10456. }
  10457. }
  10458. function graphToggleSmoothCurves () {
  10459. this.constants.smoothCurves = !this.constants.smoothCurves;
  10460. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10461. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10462. else {graph_toggleSmooth.style.background = "#FF8532";}
  10463. this._configureSmoothCurves(false);
  10464. };
  10465. function graphRepositionNodes () {
  10466. for (var nodeId in this.calculationNodes) {
  10467. if (this.calculationNodes.hasOwnProperty(nodeId)) {
  10468. this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
  10469. this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
  10470. }
  10471. }
  10472. if (this.constants.hierarchicalLayout.enabled == true) {
  10473. this._setupHierarchicalLayout();
  10474. }
  10475. else {
  10476. this.repositionNodes();
  10477. }
  10478. this.moving = true;
  10479. this.start();
  10480. };
  10481. function graphGenerateOptions () {
  10482. var options = "No options are required, default values used."
  10483. var optionsSpecific = [];
  10484. var radioButton1 = document.getElementById("graph_physicsMethod1");
  10485. var radioButton2 = document.getElementById("graph_physicsMethod2");
  10486. if (radioButton1.checked == true) {
  10487. if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
  10488. if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10489. if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10490. if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10491. if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10492. if (optionsSpecific.length != 0) {
  10493. options = "var options = {"
  10494. options += "physics: {barnesHut: {"
  10495. for (var i = 0; i < optionsSpecific.length; i++) {
  10496. options += optionsSpecific[i];
  10497. if (i < optionsSpecific.length - 1) {
  10498. options += ", "
  10499. }
  10500. }
  10501. options += '}}'
  10502. }
  10503. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10504. if (optionsSpecific.length == 0) {options = "var options = {";}
  10505. else {options += ", "}
  10506. options += "smoothCurves: " + this.constants.smoothCurves;
  10507. }
  10508. if (options != "No options are required, default values used.") {
  10509. options += '};'
  10510. }
  10511. }
  10512. else if (radioButton2.checked == true) {
  10513. options = "var options = {"
  10514. options += "physics: {barnesHut: {enabled: false}";
  10515. if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
  10516. if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10517. if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10518. if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10519. if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10520. if (optionsSpecific.length != 0) {
  10521. options += ", repulsion: {"
  10522. for (var i = 0; i < optionsSpecific.length; i++) {
  10523. options += optionsSpecific[i];
  10524. if (i < optionsSpecific.length - 1) {
  10525. options += ", "
  10526. }
  10527. }
  10528. options += '}}'
  10529. }
  10530. if (optionsSpecific.length == 0) {options += "}"}
  10531. if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
  10532. options += ", smoothCurves: " + this.constants.smoothCurves;
  10533. }
  10534. options += '};'
  10535. }
  10536. else {
  10537. options = "var options = {"
  10538. if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
  10539. if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
  10540. if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
  10541. if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
  10542. if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
  10543. if (optionsSpecific.length != 0) {
  10544. options += "physics: {hierarchicalRepulsion: {"
  10545. for (var i = 0; i < optionsSpecific.length; i++) {
  10546. options += optionsSpecific[i];
  10547. if (i < optionsSpecific.length - 1) {
  10548. options += ", ";
  10549. }
  10550. }
  10551. options += '}},';
  10552. }
  10553. options += 'hierarchicalLayout: {';
  10554. optionsSpecific = [];
  10555. if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
  10556. if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
  10557. if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
  10558. if (optionsSpecific.length != 0) {
  10559. for (var i = 0; i < optionsSpecific.length; i++) {
  10560. options += optionsSpecific[i];
  10561. if (i < optionsSpecific.length - 1) {
  10562. options += ", "
  10563. }
  10564. }
  10565. options += '}'
  10566. }
  10567. else {
  10568. options += "enabled:true}";
  10569. }
  10570. options += '};'
  10571. }
  10572. this.optionsDiv.innerHTML = options;
  10573. };
  10574. function switchConfigurations () {
  10575. var ids = ["graph_BH_table","graph_R_table","graph_H_table"]
  10576. var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
  10577. var tableId = "graph_" + radioButton + "_table";
  10578. var table = document.getElementById(tableId);
  10579. table.style.display = "block";
  10580. for (var i = 0; i < ids.length; i++) {
  10581. if (ids[i] != tableId) {
  10582. table = document.getElementById(ids[i]);
  10583. table.style.display = "none";
  10584. }
  10585. }
  10586. this._restoreNodes();
  10587. if (radioButton == "R") {
  10588. this.constants.hierarchicalLayout.enabled = false;
  10589. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10590. this.constants.physics.barnesHut.enabled = false;
  10591. }
  10592. else if (radioButton == "H") {
  10593. this.constants.hierarchicalLayout.enabled = true;
  10594. this.constants.physics.hierarchicalRepulsion.enabled = true;
  10595. this.constants.physics.barnesHut.enabled = false;
  10596. this._setupHierarchicalLayout();
  10597. }
  10598. else {
  10599. this.constants.hierarchicalLayout.enabled = false;
  10600. this.constants.physics.hierarchicalRepulsion.enabled = false;
  10601. this.constants.physics.barnesHut.enabled = true;
  10602. }
  10603. this._loadSelectedForceSolver();
  10604. var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
  10605. if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";}
  10606. else {graph_toggleSmooth.style.background = "#FF8532";}
  10607. this.moving = true;
  10608. this.start();
  10609. }
  10610. function showValueOfRange (id,map,constantsVariableName) {
  10611. var valueId = id + "_value";
  10612. var rangeValue = document.getElementById(id).value;
  10613. if (map instanceof Array) {
  10614. document.getElementById(valueId).value = map[parseInt(rangeValue)];
  10615. this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
  10616. }
  10617. else {
  10618. document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
  10619. this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
  10620. }
  10621. if (constantsVariableName == "hierarchicalLayout_direction" ||
  10622. constantsVariableName == "hierarchicalLayout_levelSeparation" ||
  10623. constantsVariableName == "hierarchicalLayout_nodeSpacing") {
  10624. this._setupHierarchicalLayout();
  10625. }
  10626. this.moving = true;
  10627. this.start();
  10628. };
  10629. /**
  10630. * Created by Alex on 2/10/14.
  10631. */
  10632. var hierarchalRepulsionMixin = {
  10633. /**
  10634. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  10635. * This field is linearly approximated.
  10636. *
  10637. * @private
  10638. */
  10639. _calculateNodeForces : function() {
  10640. var dx, dy, distance, fx, fy, combinedClusterSize,
  10641. repulsingForce, node1, node2, i, j;
  10642. var nodes = this.calculationNodes;
  10643. var nodeIndices = this.calculationNodeIndices;
  10644. // approximation constants
  10645. var b = 5;
  10646. var a_base = 0.5*-b;
  10647. // repulsing forces between nodes
  10648. var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
  10649. var minimumDistance = nodeDistance;
  10650. // we loop from i over all but the last entree in the array
  10651. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  10652. for (i = 0; i < nodeIndices.length-1; i++) {
  10653. node1 = nodes[nodeIndices[i]];
  10654. for (j = i+1; j < nodeIndices.length; j++) {
  10655. node2 = nodes[nodeIndices[j]];
  10656. dx = node2.x - node1.x;
  10657. dy = node2.y - node1.y;
  10658. distance = Math.sqrt(dx * dx + dy * dy);
  10659. var a = a_base / minimumDistance;
  10660. if (distance < 2*minimumDistance) {
  10661. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  10662. // normalize force with
  10663. if (distance == 0) {
  10664. distance = 0.01;
  10665. }
  10666. else {
  10667. repulsingForce = repulsingForce/distance;
  10668. }
  10669. fx = dx * repulsingForce;
  10670. fy = dy * repulsingForce;
  10671. node1.fx -= fx;
  10672. node1.fy -= fy;
  10673. node2.fx += fx;
  10674. node2.fy += fy;
  10675. }
  10676. }
  10677. }
  10678. }
  10679. }
  10680. /**
  10681. * Created by Alex on 2/10/14.
  10682. */
  10683. var barnesHutMixin = {
  10684. /**
  10685. * This function calculates the forces the nodes apply on eachother based on a gravitational model.
  10686. * The Barnes Hut method is used to speed up this N-body simulation.
  10687. *
  10688. * @private
  10689. */
  10690. _calculateNodeForces : function() {
  10691. var node;
  10692. var nodes = this.calculationNodes;
  10693. var nodeIndices = this.calculationNodeIndices;
  10694. var nodeCount = nodeIndices.length;
  10695. this._formBarnesHutTree(nodes,nodeIndices);
  10696. var barnesHutTree = this.barnesHutTree;
  10697. // place the nodes one by one recursively
  10698. for (var i = 0; i < nodeCount; i++) {
  10699. node = nodes[nodeIndices[i]];
  10700. // starting with root is irrelevant, it never passes the BarnesHut condition
  10701. this._getForceContribution(barnesHutTree.root.children.NW,node);
  10702. this._getForceContribution(barnesHutTree.root.children.NE,node);
  10703. this._getForceContribution(barnesHutTree.root.children.SW,node);
  10704. this._getForceContribution(barnesHutTree.root.children.SE,node);
  10705. }
  10706. },
  10707. /**
  10708. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  10709. * If a region contains a single node, we check if it is not itself, then we apply the force.
  10710. *
  10711. * @param parentBranch
  10712. * @param node
  10713. * @private
  10714. */
  10715. _getForceContribution : function(parentBranch,node) {
  10716. // we get no force contribution from an empty region
  10717. if (parentBranch.childrenCount > 0) {
  10718. var dx,dy,distance;
  10719. // get the distance from the center of mass to the node.
  10720. dx = parentBranch.centerOfMass.x - node.x;
  10721. dy = parentBranch.centerOfMass.y - node.y;
  10722. distance = Math.sqrt(dx * dx + dy * dy);
  10723. // BarnesHut condition
  10724. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  10725. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  10726. if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
  10727. // duplicate code to reduce function calls to speed up program
  10728. if (distance == 0) {
  10729. distance = 0.1*Math.random();
  10730. dx = distance;
  10731. }
  10732. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10733. var fx = dx * gravityForce;
  10734. var fy = dy * gravityForce;
  10735. node.fx += fx;
  10736. node.fy += fy;
  10737. }
  10738. else {
  10739. // Did not pass the condition, go into children if available
  10740. if (parentBranch.childrenCount == 4) {
  10741. this._getForceContribution(parentBranch.children.NW,node);
  10742. this._getForceContribution(parentBranch.children.NE,node);
  10743. this._getForceContribution(parentBranch.children.SW,node);
  10744. this._getForceContribution(parentBranch.children.SE,node);
  10745. }
  10746. else { // parentBranch must have only one node, if it was empty we wouldnt be here
  10747. if (parentBranch.children.data.id != node.id) { // if it is not self
  10748. // duplicate code to reduce function calls to speed up program
  10749. if (distance == 0) {
  10750. distance = 0.5*Math.random();
  10751. dx = distance;
  10752. }
  10753. var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
  10754. var fx = dx * gravityForce;
  10755. var fy = dy * gravityForce;
  10756. node.fx += fx;
  10757. node.fy += fy;
  10758. }
  10759. }
  10760. }
  10761. }
  10762. },
  10763. /**
  10764. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  10765. *
  10766. * @param nodes
  10767. * @param nodeIndices
  10768. * @private
  10769. */
  10770. _formBarnesHutTree : function(nodes,nodeIndices) {
  10771. var node;
  10772. var nodeCount = nodeIndices.length;
  10773. var minX = Number.MAX_VALUE,
  10774. minY = Number.MAX_VALUE,
  10775. maxX =-Number.MAX_VALUE,
  10776. maxY =-Number.MAX_VALUE;
  10777. // get the range of the nodes
  10778. for (var i = 0; i < nodeCount; i++) {
  10779. var x = nodes[nodeIndices[i]].x;
  10780. var y = nodes[nodeIndices[i]].y;
  10781. if (x < minX) { minX = x; }
  10782. if (x > maxX) { maxX = x; }
  10783. if (y < minY) { minY = y; }
  10784. if (y > maxY) { maxY = y; }
  10785. }
  10786. // make the range a square
  10787. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  10788. if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
  10789. else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
  10790. var minimumTreeSize = 1e-5;
  10791. var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
  10792. var halfRootSize = 0.5 * rootSize;
  10793. var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
  10794. // construct the barnesHutTree
  10795. var barnesHutTree = {root:{
  10796. centerOfMass:{x:0,y:0}, // Center of Mass
  10797. mass:0,
  10798. range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize,
  10799. minY:centerY-halfRootSize,maxY:centerY+halfRootSize},
  10800. size: rootSize,
  10801. calcSize: 1 / rootSize,
  10802. children: {data:null},
  10803. maxWidth: 0,
  10804. level: 0,
  10805. childrenCount: 4
  10806. }};
  10807. this._splitBranch(barnesHutTree.root);
  10808. // place the nodes one by one recursively
  10809. for (i = 0; i < nodeCount; i++) {
  10810. node = nodes[nodeIndices[i]];
  10811. this._placeInTree(barnesHutTree.root,node);
  10812. }
  10813. // make global
  10814. this.barnesHutTree = barnesHutTree
  10815. },
  10816. _updateBranchMass : function(parentBranch, node) {
  10817. var totalMass = parentBranch.mass + node.mass;
  10818. var totalMassInv = 1/totalMass;
  10819. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
  10820. parentBranch.centerOfMass.x *= totalMassInv;
  10821. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
  10822. parentBranch.centerOfMass.y *= totalMassInv;
  10823. parentBranch.mass = totalMass;
  10824. var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
  10825. parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
  10826. },
  10827. _placeInTree : function(parentBranch,node,skipMassUpdate) {
  10828. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  10829. // update the mass of the branch.
  10830. this._updateBranchMass(parentBranch,node);
  10831. }
  10832. if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
  10833. if (parentBranch.children.NW.range.maxY > node.y) { // in NW
  10834. this._placeInRegion(parentBranch,node,"NW");
  10835. }
  10836. else { // in SW
  10837. this._placeInRegion(parentBranch,node,"SW");
  10838. }
  10839. }
  10840. else { // in NE or SE
  10841. if (parentBranch.children.NW.range.maxY > node.y) { // in NE
  10842. this._placeInRegion(parentBranch,node,"NE");
  10843. }
  10844. else { // in SE
  10845. this._placeInRegion(parentBranch,node,"SE");
  10846. }
  10847. }
  10848. },
  10849. _placeInRegion : function(parentBranch,node,region) {
  10850. switch (parentBranch.children[region].childrenCount) {
  10851. case 0: // place node here
  10852. parentBranch.children[region].children.data = node;
  10853. parentBranch.children[region].childrenCount = 1;
  10854. this._updateBranchMass(parentBranch.children[region],node);
  10855. break;
  10856. case 1: // convert into children
  10857. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  10858. // we move one node a pixel and we do not put it in the tree.
  10859. if (parentBranch.children[region].children.data.x == node.x &&
  10860. parentBranch.children[region].children.data.y == node.y) {
  10861. node.x += Math.random();
  10862. node.y += Math.random();
  10863. }
  10864. else {
  10865. this._splitBranch(parentBranch.children[region]);
  10866. this._placeInTree(parentBranch.children[region],node);
  10867. }
  10868. break;
  10869. case 4: // place in branch
  10870. this._placeInTree(parentBranch.children[region],node);
  10871. break;
  10872. }
  10873. },
  10874. /**
  10875. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  10876. * after the split is complete.
  10877. *
  10878. * @param parentBranch
  10879. * @private
  10880. */
  10881. _splitBranch : function(parentBranch) {
  10882. // if the branch is filled with a node, replace the node in the new subset.
  10883. var containedNode = null;
  10884. if (parentBranch.childrenCount == 1) {
  10885. containedNode = parentBranch.children.data;
  10886. parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
  10887. }
  10888. parentBranch.childrenCount = 4;
  10889. parentBranch.children.data = null;
  10890. this._insertRegion(parentBranch,"NW");
  10891. this._insertRegion(parentBranch,"NE");
  10892. this._insertRegion(parentBranch,"SW");
  10893. this._insertRegion(parentBranch,"SE");
  10894. if (containedNode != null) {
  10895. this._placeInTree(parentBranch,containedNode);
  10896. }
  10897. },
  10898. /**
  10899. * This function subdivides the region into four new segments.
  10900. * Specifically, this inserts a single new segment.
  10901. * It fills the children section of the parentBranch
  10902. *
  10903. * @param parentBranch
  10904. * @param region
  10905. * @param parentRange
  10906. * @private
  10907. */
  10908. _insertRegion : function(parentBranch, region) {
  10909. var minX,maxX,minY,maxY;
  10910. var childSize = 0.5 * parentBranch.size;
  10911. switch (region) {
  10912. case "NW":
  10913. minX = parentBranch.range.minX;
  10914. maxX = parentBranch.range.minX + childSize;
  10915. minY = parentBranch.range.minY;
  10916. maxY = parentBranch.range.minY + childSize;
  10917. break;
  10918. case "NE":
  10919. minX = parentBranch.range.minX + childSize;
  10920. maxX = parentBranch.range.maxX;
  10921. minY = parentBranch.range.minY;
  10922. maxY = parentBranch.range.minY + childSize;
  10923. break;
  10924. case "SW":
  10925. minX = parentBranch.range.minX;
  10926. maxX = parentBranch.range.minX + childSize;
  10927. minY = parentBranch.range.minY + childSize;
  10928. maxY = parentBranch.range.maxY;
  10929. break;
  10930. case "SE":
  10931. minX = parentBranch.range.minX + childSize;
  10932. maxX = parentBranch.range.maxX;
  10933. minY = parentBranch.range.minY + childSize;
  10934. maxY = parentBranch.range.maxY;
  10935. break;
  10936. }
  10937. parentBranch.children[region] = {
  10938. centerOfMass:{x:0,y:0},
  10939. mass:0,
  10940. range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
  10941. size: 0.5 * parentBranch.size,
  10942. calcSize: 2 * parentBranch.calcSize,
  10943. children: {data:null},
  10944. maxWidth: 0,
  10945. level: parentBranch.level+1,
  10946. childrenCount: 0
  10947. };
  10948. },
  10949. /**
  10950. * This function is for debugging purposed, it draws the tree.
  10951. *
  10952. * @param ctx
  10953. * @param color
  10954. * @private
  10955. */
  10956. _drawTree : function(ctx,color) {
  10957. if (this.barnesHutTree !== undefined) {
  10958. ctx.lineWidth = 1;
  10959. this._drawBranch(this.barnesHutTree.root,ctx,color);
  10960. }
  10961. },
  10962. /**
  10963. * This function is for debugging purposes. It draws the branches recursively.
  10964. *
  10965. * @param branch
  10966. * @param ctx
  10967. * @param color
  10968. * @private
  10969. */
  10970. _drawBranch : function(branch,ctx,color) {
  10971. if (color === undefined) {
  10972. color = "#FF0000";
  10973. }
  10974. if (branch.childrenCount == 4) {
  10975. this._drawBranch(branch.children.NW,ctx);
  10976. this._drawBranch(branch.children.NE,ctx);
  10977. this._drawBranch(branch.children.SE,ctx);
  10978. this._drawBranch(branch.children.SW,ctx);
  10979. }
  10980. ctx.strokeStyle = color;
  10981. ctx.beginPath();
  10982. ctx.moveTo(branch.range.minX,branch.range.minY);
  10983. ctx.lineTo(branch.range.maxX,branch.range.minY);
  10984. ctx.stroke();
  10985. ctx.beginPath();
  10986. ctx.moveTo(branch.range.maxX,branch.range.minY);
  10987. ctx.lineTo(branch.range.maxX,branch.range.maxY);
  10988. ctx.stroke();
  10989. ctx.beginPath();
  10990. ctx.moveTo(branch.range.maxX,branch.range.maxY);
  10991. ctx.lineTo(branch.range.minX,branch.range.maxY);
  10992. ctx.stroke();
  10993. ctx.beginPath();
  10994. ctx.moveTo(branch.range.minX,branch.range.maxY);
  10995. ctx.lineTo(branch.range.minX,branch.range.minY);
  10996. ctx.stroke();
  10997. /*
  10998. if (branch.mass > 0) {
  10999. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  11000. ctx.stroke();
  11001. }
  11002. */
  11003. }
  11004. };
  11005. /**
  11006. * Created by Alex on 2/10/14.
  11007. */
  11008. var repulsionMixin = {
  11009. /**
  11010. * Calculate the forces the nodes apply on eachother based on a repulsion field.
  11011. * This field is linearly approximated.
  11012. *
  11013. * @private
  11014. */
  11015. _calculateNodeForces : function() {
  11016. var dx, dy, angle, distance, fx, fy, combinedClusterSize,
  11017. repulsingForce, node1, node2, i, j;
  11018. var nodes = this.calculationNodes;
  11019. var nodeIndices = this.calculationNodeIndices;
  11020. // approximation constants
  11021. var a_base = -2/3;
  11022. var b = 4/3;
  11023. // repulsing forces between nodes
  11024. var nodeDistance = this.constants.physics.repulsion.nodeDistance;
  11025. var minimumDistance = nodeDistance;
  11026. // we loop from i over all but the last entree in the array
  11027. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  11028. for (i = 0; i < nodeIndices.length-1; i++) {
  11029. node1 = nodes[nodeIndices[i]];
  11030. for (j = i+1; j < nodeIndices.length; j++) {
  11031. node2 = nodes[nodeIndices[j]];
  11032. combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
  11033. dx = node2.x - node1.x;
  11034. dy = node2.y - node1.y;
  11035. distance = Math.sqrt(dx * dx + dy * dy);
  11036. minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
  11037. var a = a_base / minimumDistance;
  11038. if (distance < 2*minimumDistance) {
  11039. if (distance < 0.5*minimumDistance) {
  11040. repulsingForce = 1.0;
  11041. }
  11042. else {
  11043. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
  11044. }
  11045. // amplify the repulsion for clusters.
  11046. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
  11047. repulsingForce = repulsingForce/distance;
  11048. fx = dx * repulsingForce;
  11049. fy = dy * repulsingForce;
  11050. node1.fx -= fx;
  11051. node1.fy -= fy;
  11052. node2.fx += fx;
  11053. node2.fy += fy;
  11054. }
  11055. }
  11056. }
  11057. }
  11058. }
  11059. var HierarchicalLayoutMixin = {
  11060. _resetLevels : function() {
  11061. for (var nodeId in this.nodes) {
  11062. if (this.nodes.hasOwnProperty(nodeId)) {
  11063. var node = this.nodes[nodeId];
  11064. if (node.preassignedLevel == false) {
  11065. node.level = -1;
  11066. }
  11067. }
  11068. }
  11069. },
  11070. /**
  11071. * This is the main function to layout the nodes in a hierarchical way.
  11072. * It checks if the node details are supplied correctly
  11073. *
  11074. * @private
  11075. */
  11076. _setupHierarchicalLayout : function() {
  11077. if (this.constants.hierarchicalLayout.enabled == true) {
  11078. if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
  11079. this.constants.hierarchicalLayout.levelSeparation *= -1;
  11080. }
  11081. else {
  11082. this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
  11083. }
  11084. // get the size of the largest hubs and check if the user has defined a level for a node.
  11085. var hubsize = 0;
  11086. var node, nodeId;
  11087. var definedLevel = false;
  11088. var undefinedLevel = false;
  11089. for (nodeId in this.nodes) {
  11090. if (this.nodes.hasOwnProperty(nodeId)) {
  11091. node = this.nodes[nodeId];
  11092. if (node.level != -1) {
  11093. definedLevel = true;
  11094. }
  11095. else {
  11096. undefinedLevel = true;
  11097. }
  11098. if (hubsize < node.edges.length) {
  11099. hubsize = node.edges.length;
  11100. }
  11101. }
  11102. }
  11103. // if the user defined some levels but not all, alert and run without hierarchical layout
  11104. if (undefinedLevel == true && definedLevel == true) {
  11105. alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.")
  11106. this.zoomExtent(true,this.constants.clustering.enabled);
  11107. if (!this.constants.clustering.enabled) {
  11108. this.start();
  11109. }
  11110. }
  11111. else {
  11112. // setup the system to use hierarchical method.
  11113. this._changeConstants();
  11114. // define levels if undefined by the users. Based on hubsize
  11115. if (undefinedLevel == true) {
  11116. this._determineLevels(hubsize);
  11117. }
  11118. // check the distribution of the nodes per level.
  11119. var distribution = this._getDistribution();
  11120. // place the nodes on the canvas. This also stablilizes the system.
  11121. this._placeNodesByHierarchy(distribution);
  11122. // start the simulation.
  11123. this.start();
  11124. }
  11125. }
  11126. },
  11127. /**
  11128. * This function places the nodes on the canvas based on the hierarchial distribution.
  11129. *
  11130. * @param {Object} distribution | obtained by the function this._getDistribution()
  11131. * @private
  11132. */
  11133. _placeNodesByHierarchy : function(distribution) {
  11134. var nodeId, node;
  11135. // start placing all the level 0 nodes first. Then recursively position their branches.
  11136. for (nodeId in distribution[0].nodes) {
  11137. if (distribution[0].nodes.hasOwnProperty(nodeId)) {
  11138. node = distribution[0].nodes[nodeId];
  11139. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11140. if (node.xFixed) {
  11141. node.x = distribution[0].minPos;
  11142. node.xFixed = false;
  11143. distribution[0].minPos += distribution[0].nodeSpacing;
  11144. }
  11145. }
  11146. else {
  11147. if (node.yFixed) {
  11148. node.y = distribution[0].minPos;
  11149. node.yFixed = false;
  11150. distribution[0].minPos += distribution[0].nodeSpacing;
  11151. }
  11152. }
  11153. this._placeBranchNodes(node.edges,node.id,distribution,node.level);
  11154. }
  11155. }
  11156. // stabilize the system after positioning. This function calls zoomExtent.
  11157. this._stabilize();
  11158. },
  11159. /**
  11160. * This function get the distribution of levels based on hubsize
  11161. *
  11162. * @returns {Object}
  11163. * @private
  11164. */
  11165. _getDistribution : function() {
  11166. var distribution = {};
  11167. var nodeId, node;
  11168. // 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.
  11169. // the fix of X is removed after the x value has been set.
  11170. for (nodeId in this.nodes) {
  11171. if (this.nodes.hasOwnProperty(nodeId)) {
  11172. node = this.nodes[nodeId];
  11173. node.xFixed = true;
  11174. node.yFixed = true;
  11175. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11176. node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
  11177. }
  11178. else {
  11179. node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
  11180. }
  11181. if (!distribution.hasOwnProperty(node.level)) {
  11182. distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
  11183. }
  11184. distribution[node.level].amount += 1;
  11185. distribution[node.level].nodes[node.id] = node;
  11186. }
  11187. }
  11188. // determine the largest amount of nodes of all levels
  11189. var maxCount = 0;
  11190. for (var level in distribution) {
  11191. if (distribution.hasOwnProperty(level)) {
  11192. if (maxCount < distribution[level].amount) {
  11193. maxCount = distribution[level].amount;
  11194. }
  11195. }
  11196. }
  11197. // set the initial position and spacing of each nodes accordingly
  11198. for (var level in distribution) {
  11199. if (distribution.hasOwnProperty(level)) {
  11200. distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
  11201. distribution[level].nodeSpacing /= (distribution[level].amount + 1);
  11202. distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
  11203. }
  11204. }
  11205. return distribution;
  11206. },
  11207. /**
  11208. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  11209. *
  11210. * @param hubsize
  11211. * @private
  11212. */
  11213. _determineLevels : function(hubsize) {
  11214. var nodeId, node;
  11215. // determine hubs
  11216. for (nodeId in this.nodes) {
  11217. if (this.nodes.hasOwnProperty(nodeId)) {
  11218. node = this.nodes[nodeId];
  11219. if (node.edges.length == hubsize) {
  11220. node.level = 0;
  11221. }
  11222. }
  11223. }
  11224. // branch from hubs
  11225. for (nodeId in this.nodes) {
  11226. if (this.nodes.hasOwnProperty(nodeId)) {
  11227. node = this.nodes[nodeId];
  11228. if (node.level == 0) {
  11229. this._setLevel(1,node.edges,node.id);
  11230. }
  11231. }
  11232. }
  11233. },
  11234. /**
  11235. * Since hierarchical layout does not support:
  11236. * - smooth curves (based on the physics),
  11237. * - clustering (based on dynamic node counts)
  11238. *
  11239. * We disable both features so there will be no problems.
  11240. *
  11241. * @private
  11242. */
  11243. _changeConstants : function() {
  11244. this.constants.clustering.enabled = false;
  11245. this.constants.physics.barnesHut.enabled = false;
  11246. this.constants.physics.hierarchicalRepulsion.enabled = true;
  11247. this._loadSelectedForceSolver();
  11248. this.constants.smoothCurves = false;
  11249. this._configureSmoothCurves();
  11250. },
  11251. /**
  11252. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  11253. * on a X position that ensures there will be no overlap.
  11254. *
  11255. * @param edges
  11256. * @param parentId
  11257. * @param distribution
  11258. * @param parentLevel
  11259. * @private
  11260. */
  11261. _placeBranchNodes : function(edges, parentId, distribution, parentLevel) {
  11262. for (var i = 0; i < edges.length; i++) {
  11263. var childNode = null;
  11264. if (edges[i].toId == parentId) {
  11265. childNode = edges[i].from;
  11266. }
  11267. else {
  11268. childNode = edges[i].to;
  11269. }
  11270. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  11271. var nodeMoved = false;
  11272. if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
  11273. if (childNode.xFixed && childNode.level > parentLevel) {
  11274. childNode.xFixed = false;
  11275. childNode.x = distribution[childNode.level].minPos;
  11276. nodeMoved = true;
  11277. }
  11278. }
  11279. else {
  11280. if (childNode.yFixed && childNode.level > parentLevel) {
  11281. childNode.yFixed = false;
  11282. childNode.y = distribution[childNode.level].minPos;
  11283. nodeMoved = true;
  11284. }
  11285. }
  11286. if (nodeMoved == true) {
  11287. distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
  11288. if (childNode.edges.length > 1) {
  11289. this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
  11290. }
  11291. }
  11292. }
  11293. },
  11294. /**
  11295. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  11296. *
  11297. * @param level
  11298. * @param edges
  11299. * @param parentId
  11300. * @private
  11301. */
  11302. _setLevel : function(level, edges, parentId) {
  11303. for (var i = 0; i < edges.length; i++) {
  11304. var childNode = null;
  11305. if (edges[i].toId == parentId) {
  11306. childNode = edges[i].from;
  11307. }
  11308. else {
  11309. childNode = edges[i].to;
  11310. }
  11311. if (childNode.level == -1 || childNode.level > level) {
  11312. childNode.level = level;
  11313. if (edges.length > 1) {
  11314. this._setLevel(level+1, childNode.edges, childNode.id);
  11315. }
  11316. }
  11317. }
  11318. },
  11319. /**
  11320. * Unfix nodes
  11321. *
  11322. * @private
  11323. */
  11324. _restoreNodes : function() {
  11325. for (nodeId in this.nodes) {
  11326. if (this.nodes.hasOwnProperty(nodeId)) {
  11327. this.nodes[nodeId].xFixed = false;
  11328. this.nodes[nodeId].yFixed = false;
  11329. }
  11330. }
  11331. }
  11332. };
  11333. /**
  11334. * Created by Alex on 2/4/14.
  11335. */
  11336. var manipulationMixin = {
  11337. /**
  11338. * clears the toolbar div element of children
  11339. *
  11340. * @private
  11341. */
  11342. _clearManipulatorBar : function() {
  11343. while (this.manipulationDiv.hasChildNodes()) {
  11344. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11345. }
  11346. },
  11347. /**
  11348. * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
  11349. * these functions to their original functionality, we saved them in this.cachedFunctions.
  11350. * This function restores these functions to their original function.
  11351. *
  11352. * @private
  11353. */
  11354. _restoreOverloadedFunctions : function() {
  11355. for (var functionName in this.cachedFunctions) {
  11356. if (this.cachedFunctions.hasOwnProperty(functionName)) {
  11357. this[functionName] = this.cachedFunctions[functionName];
  11358. }
  11359. }
  11360. },
  11361. /**
  11362. * Enable or disable edit-mode.
  11363. *
  11364. * @private
  11365. */
  11366. _toggleEditMode : function() {
  11367. this.editMode = !this.editMode;
  11368. var toolbar = document.getElementById("graph-manipulationDiv");
  11369. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11370. var editModeDiv = document.getElementById("graph-manipulation-editMode");
  11371. if (this.editMode == true) {
  11372. toolbar.style.display="block";
  11373. closeDiv.style.display="block";
  11374. editModeDiv.style.display="none";
  11375. closeDiv.onclick = this._toggleEditMode.bind(this);
  11376. }
  11377. else {
  11378. toolbar.style.display="none";
  11379. closeDiv.style.display="none";
  11380. editModeDiv.style.display="block";
  11381. closeDiv.onclick = null;
  11382. }
  11383. this._createManipulatorBar()
  11384. },
  11385. /**
  11386. * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  11387. *
  11388. * @private
  11389. */
  11390. _createManipulatorBar : function() {
  11391. // remove bound functions
  11392. if (this.boundFunction) {
  11393. this.off('select', this.boundFunction);
  11394. }
  11395. // restore overloaded functions
  11396. this._restoreOverloadedFunctions();
  11397. // resume calculation
  11398. this.freezeSimulation = false;
  11399. // reset global variables
  11400. this.blockConnectingEdgeSelection = false;
  11401. this.forceAppendSelection = false
  11402. if (this.editMode == true) {
  11403. while (this.manipulationDiv.hasChildNodes()) {
  11404. this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
  11405. }
  11406. // add the icons to the manipulator div
  11407. this.manipulationDiv.innerHTML = "" +
  11408. "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" +
  11409. "<span class='graph-manipulationLabel'>"+this.constants.labels['add'] +"</span></span>" +
  11410. "<div class='graph-seperatorLine'></div>" +
  11411. "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" +
  11412. "<span class='graph-manipulationLabel'>"+this.constants.labels['link'] +"</span></span>";
  11413. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11414. this.manipulationDiv.innerHTML += "" +
  11415. "<div class='graph-seperatorLine'></div>" +
  11416. "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" +
  11417. "<span class='graph-manipulationLabel'>"+this.constants.labels['editNode'] +"</span></span>";
  11418. }
  11419. if (this._selectionIsEmpty() == false) {
  11420. this.manipulationDiv.innerHTML += "" +
  11421. "<div class='graph-seperatorLine'></div>" +
  11422. "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" +
  11423. "<span class='graph-manipulationLabel'>"+this.constants.labels['delete'] +"</span></span>";
  11424. }
  11425. // bind the icons
  11426. var addNodeButton = document.getElementById("graph-manipulate-addNode");
  11427. addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
  11428. var addEdgeButton = document.getElementById("graph-manipulate-connectNode");
  11429. addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
  11430. if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
  11431. var editButton = document.getElementById("graph-manipulate-editNode");
  11432. editButton.onclick = this._editNode.bind(this);
  11433. }
  11434. if (this._selectionIsEmpty() == false) {
  11435. var deleteButton = document.getElementById("graph-manipulate-delete");
  11436. deleteButton.onclick = this._deleteSelected.bind(this);
  11437. }
  11438. var closeDiv = document.getElementById("graph-manipulation-closeDiv");
  11439. closeDiv.onclick = this._toggleEditMode.bind(this);
  11440. this.boundFunction = this._createManipulatorBar.bind(this);
  11441. this.on('select', this.boundFunction);
  11442. }
  11443. else {
  11444. this.editModeDiv.innerHTML = "" +
  11445. "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" +
  11446. "<span class='graph-manipulationLabel'>"+this.constants.labels['edit'] +"</span></span>"
  11447. var editModeButton = document.getElementById("graph-manipulate-editModeButton");
  11448. editModeButton.onclick = this._toggleEditMode.bind(this);
  11449. }
  11450. },
  11451. /**
  11452. * Create the toolbar for adding Nodes
  11453. *
  11454. * @private
  11455. */
  11456. _createAddNodeToolbar : function() {
  11457. // clear the toolbar
  11458. this._clearManipulatorBar();
  11459. if (this.boundFunction) {
  11460. this.off('select', this.boundFunction);
  11461. }
  11462. // create the toolbar contents
  11463. this.manipulationDiv.innerHTML = "" +
  11464. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11465. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11466. "<div class='graph-seperatorLine'></div>" +
  11467. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11468. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['addDescription'] + "</span></span>";
  11469. // bind the icon
  11470. var backButton = document.getElementById("graph-manipulate-back");
  11471. backButton.onclick = this._createManipulatorBar.bind(this);
  11472. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11473. this.boundFunction = this._addNode.bind(this);
  11474. this.on('select', this.boundFunction);
  11475. },
  11476. /**
  11477. * create the toolbar to connect nodes
  11478. *
  11479. * @private
  11480. */
  11481. _createAddEdgeToolbar : function() {
  11482. // clear the toolbar
  11483. this._clearManipulatorBar();
  11484. this._unselectAll(true);
  11485. this.freezeSimulation = true;
  11486. if (this.boundFunction) {
  11487. this.off('select', this.boundFunction);
  11488. }
  11489. this._unselectAll();
  11490. this.forceAppendSelection = false;
  11491. this.blockConnectingEdgeSelection = true;
  11492. this.manipulationDiv.innerHTML = "" +
  11493. "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" +
  11494. "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
  11495. "<div class='graph-seperatorLine'></div>" +
  11496. "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" +
  11497. "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['linkDescription'] + "</span></span>";
  11498. // bind the icon
  11499. var backButton = document.getElementById("graph-manipulate-back");
  11500. backButton.onclick = this._createManipulatorBar.bind(this);
  11501. // we use the boundFunction so we can reference it when we unbind it from the "select" event.
  11502. this.boundFunction = this._handleConnect.bind(this);
  11503. this.on('select', this.boundFunction);
  11504. // temporarily overload functions
  11505. this.cachedFunctions["_handleTouch"] = this._handleTouch;
  11506. this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
  11507. this._handleTouch = this._handleConnect;
  11508. this._handleOnRelease = this._finishConnect;
  11509. // redraw to show the unselect
  11510. this._redraw();
  11511. },
  11512. /**
  11513. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  11514. * to walk the user through the process.
  11515. *
  11516. * @private
  11517. */
  11518. _handleConnect : function(pointer) {
  11519. if (this._getSelectedNodeCount() == 0) {
  11520. var node = this._getNodeAt(pointer);
  11521. if (node != null) {
  11522. if (node.clusterSize > 1) {
  11523. alert("Cannot create edges to a cluster.")
  11524. }
  11525. else {
  11526. this._selectObject(node,false);
  11527. // create a node the temporary line can look at
  11528. this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
  11529. this.sectors['support']['nodes']['targetNode'].x = node.x;
  11530. this.sectors['support']['nodes']['targetNode'].y = node.y;
  11531. this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
  11532. this.sectors['support']['nodes']['targetViaNode'].x = node.x;
  11533. this.sectors['support']['nodes']['targetViaNode'].y = node.y;
  11534. this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
  11535. // create a temporary edge
  11536. this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
  11537. this.edges['connectionEdge'].from = node;
  11538. this.edges['connectionEdge'].connected = true;
  11539. this.edges['connectionEdge'].smooth = true;
  11540. this.edges['connectionEdge'].selected = true;
  11541. this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
  11542. this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
  11543. this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
  11544. this._handleOnDrag = function(event) {
  11545. var pointer = this._getPointer(event.gesture.center);
  11546. this.sectors['support']['nodes']['targetNode'].x = this._canvasToX(pointer.x);
  11547. this.sectors['support']['nodes']['targetNode'].y = this._canvasToY(pointer.y);
  11548. this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._canvasToX(pointer.x) + this.edges['connectionEdge'].from.x);
  11549. this.sectors['support']['nodes']['targetViaNode'].y = this._canvasToY(pointer.y);
  11550. };
  11551. this.moving = true;
  11552. this.start();
  11553. }
  11554. }
  11555. }
  11556. },
  11557. _finishConnect : function(pointer) {
  11558. if (this._getSelectedNodeCount() == 1) {
  11559. // restore the drag function
  11560. this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
  11561. delete this.cachedFunctions["_handleOnDrag"];
  11562. // remember the edge id
  11563. var connectFromId = this.edges['connectionEdge'].fromId;
  11564. // remove the temporary nodes and edge
  11565. delete this.edges['connectionEdge']
  11566. delete this.sectors['support']['nodes']['targetNode'];
  11567. delete this.sectors['support']['nodes']['targetViaNode'];
  11568. var node = this._getNodeAt(pointer);
  11569. if (node != null) {
  11570. if (node.clusterSize > 1) {
  11571. alert("Cannot create edges to a cluster.")
  11572. }
  11573. else {
  11574. this._createEdge(connectFromId,node.id);
  11575. this._createManipulatorBar();
  11576. }
  11577. }
  11578. this._unselectAll();
  11579. }
  11580. },
  11581. /**
  11582. * Adds a node on the specified location
  11583. *
  11584. * @param {Object} pointer
  11585. */
  11586. _addNode : function() {
  11587. if (this._selectionIsEmpty() && this.editMode == true) {
  11588. var positionObject = this._pointerToPositionObject(this.pointerPosition);
  11589. var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
  11590. if (this.triggerFunctions.add) {
  11591. if (this.triggerFunctions.add.length == 2) {
  11592. var me = this;
  11593. this.triggerFunctions.add(defaultData, function(finalizedData) {
  11594. me.nodesData.add(finalizedData);
  11595. me._createManipulatorBar();
  11596. me.moving = true;
  11597. me.start();
  11598. });
  11599. }
  11600. else {
  11601. alert(this.constants.labels['addError']);
  11602. this._createManipulatorBar();
  11603. this.moving = true;
  11604. this.start();
  11605. }
  11606. }
  11607. else {
  11608. this.nodesData.add(defaultData);
  11609. this._createManipulatorBar();
  11610. this.moving = true;
  11611. this.start();
  11612. }
  11613. }
  11614. },
  11615. /**
  11616. * connect two nodes with a new edge.
  11617. *
  11618. * @private
  11619. */
  11620. _createEdge : function(sourceNodeId,targetNodeId) {
  11621. if (this.editMode == true) {
  11622. var defaultData = {from:sourceNodeId, to:targetNodeId};
  11623. if (this.triggerFunctions.connect) {
  11624. if (this.triggerFunctions.connect.length == 2) {
  11625. var me = this;
  11626. this.triggerFunctions.connect(defaultData, function(finalizedData) {
  11627. me.edgesData.add(finalizedData)
  11628. me.moving = true;
  11629. me.start();
  11630. });
  11631. }
  11632. else {
  11633. alert(this.constants.labels["linkError"]);
  11634. this.moving = true;
  11635. this.start();
  11636. }
  11637. }
  11638. else {
  11639. this.edgesData.add(defaultData)
  11640. this.moving = true;
  11641. this.start();
  11642. }
  11643. }
  11644. },
  11645. /**
  11646. * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
  11647. *
  11648. * @private
  11649. */
  11650. _editNode : function() {
  11651. if (this.triggerFunctions.edit && this.editMode == true) {
  11652. var node = this._getSelectedNode();
  11653. var data = {id:node.id,
  11654. label: node.label,
  11655. group: node.group,
  11656. shape: node.shape,
  11657. color: {
  11658. background:node.color.background,
  11659. border:node.color.border,
  11660. highlight: {
  11661. background:node.color.highlight.background,
  11662. border:node.color.highlight.border
  11663. }
  11664. }};
  11665. if (this.triggerFunctions.edit.length == 2) {
  11666. var me = this;
  11667. this.triggerFunctions.edit(data, function (finalizedData) {
  11668. me.nodesData.update(finalizedData);
  11669. me._createManipulatorBar();
  11670. me.moving = true;
  11671. me.start();
  11672. });
  11673. }
  11674. else {
  11675. alert(this.constants.labels["editError"]);
  11676. }
  11677. }
  11678. else {
  11679. alert(this.constants.labels["editBoundError"]);
  11680. }
  11681. },
  11682. /**
  11683. * delete everything in the selection
  11684. *
  11685. * @private
  11686. */
  11687. _deleteSelected : function() {
  11688. if (!this._selectionIsEmpty() && this.editMode == true) {
  11689. if (!this._clusterInSelection()) {
  11690. var selectedNodes = this.getSelectedNodes();
  11691. var selectedEdges = this.getSelectedEdges();
  11692. if (this.triggerFunctions.delete) {
  11693. var me = this;
  11694. var data = {nodes: selectedNodes, edges: selectedEdges};
  11695. if (this.triggerFunctions.delete.length = 2) {
  11696. this.triggerFunctions.delete(data, function (finalizedData) {
  11697. me.edgesData.remove(finalizedData.edges);
  11698. me.nodesData.remove(finalizedData.nodes);
  11699. this._unselectAll();
  11700. me.moving = true;
  11701. me.start();
  11702. });
  11703. }
  11704. else {
  11705. alert(this.constants.labels["deleteError"])
  11706. }
  11707. }
  11708. else {
  11709. this.edgesData.remove(selectedEdges);
  11710. this.nodesData.remove(selectedNodes);
  11711. this._unselectAll();
  11712. this.moving = true;
  11713. this.start();
  11714. }
  11715. }
  11716. else {
  11717. alert(this.constants.labels["deleteClusterError"]);
  11718. }
  11719. }
  11720. }
  11721. };
  11722. /**
  11723. * Creation of the SectorMixin var.
  11724. *
  11725. * This contains all the functions the Graph object can use to employ the sector system.
  11726. * The sector system is always used by Graph, though the benefits only apply to the use of clustering.
  11727. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
  11728. *
  11729. * Alex de Mulder
  11730. * 21-01-2013
  11731. */
  11732. var SectorMixin = {
  11733. /**
  11734. * This function is only called by the setData function of the Graph object.
  11735. * This loads the global references into the active sector. This initializes the sector.
  11736. *
  11737. * @private
  11738. */
  11739. _putDataInSector : function() {
  11740. this.sectors["active"][this._sector()].nodes = this.nodes;
  11741. this.sectors["active"][this._sector()].edges = this.edges;
  11742. this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
  11743. },
  11744. /**
  11745. * /**
  11746. * This function sets the global references to nodes, edges and nodeIndices back to
  11747. * those of the supplied (active) sector. If a type is defined, do the specific type
  11748. *
  11749. * @param {String} sectorId
  11750. * @param {String} [sectorType] | "active" or "frozen"
  11751. * @private
  11752. */
  11753. _switchToSector : function(sectorId, sectorType) {
  11754. if (sectorType === undefined || sectorType == "active") {
  11755. this._switchToActiveSector(sectorId);
  11756. }
  11757. else {
  11758. this._switchToFrozenSector(sectorId);
  11759. }
  11760. },
  11761. /**
  11762. * This function sets the global references to nodes, edges and nodeIndices back to
  11763. * those of the supplied active sector.
  11764. *
  11765. * @param sectorId
  11766. * @private
  11767. */
  11768. _switchToActiveSector : function(sectorId) {
  11769. this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
  11770. this.nodes = this.sectors["active"][sectorId]["nodes"];
  11771. this.edges = this.sectors["active"][sectorId]["edges"];
  11772. },
  11773. /**
  11774. * This function sets the global references to nodes, edges and nodeIndices back to
  11775. * those of the supplied active sector.
  11776. *
  11777. * @param sectorId
  11778. * @private
  11779. */
  11780. _switchToSupportSector : function() {
  11781. this.nodeIndices = this.sectors["support"]["nodeIndices"];
  11782. this.nodes = this.sectors["support"]["nodes"];
  11783. this.edges = this.sectors["support"]["edges"];
  11784. },
  11785. /**
  11786. * This function sets the global references to nodes, edges and nodeIndices back to
  11787. * those of the supplied frozen sector.
  11788. *
  11789. * @param sectorId
  11790. * @private
  11791. */
  11792. _switchToFrozenSector : function(sectorId) {
  11793. this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
  11794. this.nodes = this.sectors["frozen"][sectorId]["nodes"];
  11795. this.edges = this.sectors["frozen"][sectorId]["edges"];
  11796. },
  11797. /**
  11798. * This function sets the global references to nodes, edges and nodeIndices back to
  11799. * those of the currently active sector.
  11800. *
  11801. * @private
  11802. */
  11803. _loadLatestSector : function() {
  11804. this._switchToSector(this._sector());
  11805. },
  11806. /**
  11807. * This function returns the currently active sector Id
  11808. *
  11809. * @returns {String}
  11810. * @private
  11811. */
  11812. _sector : function() {
  11813. return this.activeSector[this.activeSector.length-1];
  11814. },
  11815. /**
  11816. * This function returns the previously active sector Id
  11817. *
  11818. * @returns {String}
  11819. * @private
  11820. */
  11821. _previousSector : function() {
  11822. if (this.activeSector.length > 1) {
  11823. return this.activeSector[this.activeSector.length-2];
  11824. }
  11825. else {
  11826. throw new TypeError('there are not enough sectors in the this.activeSector array.');
  11827. }
  11828. },
  11829. /**
  11830. * We add the active sector at the end of the this.activeSector array
  11831. * This ensures it is the currently active sector returned by _sector() and it reaches the top
  11832. * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
  11833. *
  11834. * @param newId
  11835. * @private
  11836. */
  11837. _setActiveSector : function(newId) {
  11838. this.activeSector.push(newId);
  11839. },
  11840. /**
  11841. * We remove the currently active sector id from the active sector stack. This happens when
  11842. * we reactivate the previously active sector
  11843. *
  11844. * @private
  11845. */
  11846. _forgetLastSector : function() {
  11847. this.activeSector.pop();
  11848. },
  11849. /**
  11850. * This function creates a new active sector with the supplied newId. This newId
  11851. * is the expanding node id.
  11852. *
  11853. * @param {String} newId | Id of the new active sector
  11854. * @private
  11855. */
  11856. _createNewSector : function(newId) {
  11857. // create the new sector
  11858. this.sectors["active"][newId] = {"nodes":{},
  11859. "edges":{},
  11860. "nodeIndices":[],
  11861. "formationScale": this.scale,
  11862. "drawingNode": undefined};
  11863. // create the new sector render node. This gives visual feedback that you are in a new sector.
  11864. this.sectors["active"][newId]['drawingNode'] = new Node(
  11865. {id:newId,
  11866. color: {
  11867. background: "#eaefef",
  11868. border: "495c5e"
  11869. }
  11870. },{},{},this.constants);
  11871. this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
  11872. },
  11873. /**
  11874. * This function removes the currently active sector. This is called when we create a new
  11875. * active sector.
  11876. *
  11877. * @param {String} sectorId | Id of the active sector that will be removed
  11878. * @private
  11879. */
  11880. _deleteActiveSector : function(sectorId) {
  11881. delete this.sectors["active"][sectorId];
  11882. },
  11883. /**
  11884. * This function removes the currently active sector. This is called when we reactivate
  11885. * the previously active sector.
  11886. *
  11887. * @param {String} sectorId | Id of the active sector that will be removed
  11888. * @private
  11889. */
  11890. _deleteFrozenSector : function(sectorId) {
  11891. delete this.sectors["frozen"][sectorId];
  11892. },
  11893. /**
  11894. * Freezing an active sector means moving it from the "active" object to the "frozen" object.
  11895. * We copy the references, then delete the active entree.
  11896. *
  11897. * @param sectorId
  11898. * @private
  11899. */
  11900. _freezeSector : function(sectorId) {
  11901. // we move the set references from the active to the frozen stack.
  11902. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
  11903. // we have moved the sector data into the frozen set, we now remove it from the active set
  11904. this._deleteActiveSector(sectorId);
  11905. },
  11906. /**
  11907. * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
  11908. * object to the "active" object.
  11909. *
  11910. * @param sectorId
  11911. * @private
  11912. */
  11913. _activateSector : function(sectorId) {
  11914. // we move the set references from the frozen to the active stack.
  11915. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
  11916. // we have moved the sector data into the active set, we now remove it from the frozen stack
  11917. this._deleteFrozenSector(sectorId);
  11918. },
  11919. /**
  11920. * This function merges the data from the currently active sector with a frozen sector. This is used
  11921. * in the process of reverting back to the previously active sector.
  11922. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
  11923. * upon the creation of a new active sector.
  11924. *
  11925. * @param sectorId
  11926. * @private
  11927. */
  11928. _mergeThisWithFrozen : function(sectorId) {
  11929. // copy all nodes
  11930. for (var nodeId in this.nodes) {
  11931. if (this.nodes.hasOwnProperty(nodeId)) {
  11932. this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
  11933. }
  11934. }
  11935. // copy all edges (if not fully clustered, else there are no edges)
  11936. for (var edgeId in this.edges) {
  11937. if (this.edges.hasOwnProperty(edgeId)) {
  11938. this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
  11939. }
  11940. }
  11941. // merge the nodeIndices
  11942. for (var i = 0; i < this.nodeIndices.length; i++) {
  11943. this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
  11944. }
  11945. },
  11946. /**
  11947. * This clusters the sector to one cluster. It was a single cluster before this process started so
  11948. * we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
  11949. *
  11950. * @private
  11951. */
  11952. _collapseThisToSingleCluster : function() {
  11953. this.clusterToFit(1,false);
  11954. },
  11955. /**
  11956. * We create a new active sector from the node that we want to open.
  11957. *
  11958. * @param node
  11959. * @private
  11960. */
  11961. _addSector : function(node) {
  11962. // this is the currently active sector
  11963. var sector = this._sector();
  11964. // // this should allow me to select nodes from a frozen set.
  11965. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
  11966. // console.log("the node is part of the active sector");
  11967. // }
  11968. // else {
  11969. // console.log("I dont know what the fuck happened!!");
  11970. // }
  11971. // when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
  11972. delete this.nodes[node.id];
  11973. var unqiueIdentifier = util.randomUUID();
  11974. // we fully freeze the currently active sector
  11975. this._freezeSector(sector);
  11976. // we create a new active sector. This sector has the Id of the node to ensure uniqueness
  11977. this._createNewSector(unqiueIdentifier);
  11978. // we add the active sector to the sectors array to be able to revert these steps later on
  11979. this._setActiveSector(unqiueIdentifier);
  11980. // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
  11981. this._switchToSector(this._sector());
  11982. // finally we add the node we removed from our previous active sector to the new active sector
  11983. this.nodes[node.id] = node;
  11984. },
  11985. /**
  11986. * We close the sector that is currently open and revert back to the one before.
  11987. * If the active sector is the "default" sector, nothing happens.
  11988. *
  11989. * @private
  11990. */
  11991. _collapseSector : function() {
  11992. // the currently active sector
  11993. var sector = this._sector();
  11994. // we cannot collapse the default sector
  11995. if (sector != "default") {
  11996. if ((this.nodeIndices.length == 1) ||
  11997. (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  11998. (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  11999. var previousSector = this._previousSector();
  12000. // we collapse the sector back to a single cluster
  12001. this._collapseThisToSingleCluster();
  12002. // we move the remaining nodes, edges and nodeIndices to the previous sector.
  12003. // This previous sector is the one we will reactivate
  12004. this._mergeThisWithFrozen(previousSector);
  12005. // the previously active (frozen) sector now has all the data from the currently active sector.
  12006. // we can now delete the active sector.
  12007. this._deleteActiveSector(sector);
  12008. // we activate the previously active (and currently frozen) sector.
  12009. this._activateSector(previousSector);
  12010. // we load the references from the newly active sector into the global references
  12011. this._switchToSector(previousSector);
  12012. // we forget the previously active sector because we reverted to the one before
  12013. this._forgetLastSector();
  12014. // finally, we update the node index list.
  12015. this._updateNodeIndexList();
  12016. // we refresh the list with calulation nodes and calculation node indices.
  12017. this._updateCalculationNodes();
  12018. }
  12019. }
  12020. },
  12021. /**
  12022. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  12023. *
  12024. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  12025. * | we dont pass the function itself because then the "this" is the window object
  12026. * | instead of the Graph object
  12027. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12028. * @private
  12029. */
  12030. _doInAllActiveSectors : function(runFunction,argument) {
  12031. if (argument === undefined) {
  12032. for (var sector in this.sectors["active"]) {
  12033. if (this.sectors["active"].hasOwnProperty(sector)) {
  12034. // switch the global references to those of this sector
  12035. this._switchToActiveSector(sector);
  12036. this[runFunction]();
  12037. }
  12038. }
  12039. }
  12040. else {
  12041. for (var sector in this.sectors["active"]) {
  12042. if (this.sectors["active"].hasOwnProperty(sector)) {
  12043. // switch the global references to those of this sector
  12044. this._switchToActiveSector(sector);
  12045. var args = Array.prototype.splice.call(arguments, 1);
  12046. if (args.length > 1) {
  12047. this[runFunction](args[0],args[1]);
  12048. }
  12049. else {
  12050. this[runFunction](argument);
  12051. }
  12052. }
  12053. }
  12054. }
  12055. // we revert the global references back to our active sector
  12056. this._loadLatestSector();
  12057. },
  12058. /**
  12059. * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
  12060. *
  12061. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  12062. * | we dont pass the function itself because then the "this" is the window object
  12063. * | instead of the Graph object
  12064. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12065. * @private
  12066. */
  12067. _doInSupportSector : function(runFunction,argument) {
  12068. if (argument === undefined) {
  12069. this._switchToSupportSector();
  12070. this[runFunction]();
  12071. }
  12072. else {
  12073. this._switchToSupportSector();
  12074. var args = Array.prototype.splice.call(arguments, 1);
  12075. if (args.length > 1) {
  12076. this[runFunction](args[0],args[1]);
  12077. }
  12078. else {
  12079. this[runFunction](argument);
  12080. }
  12081. }
  12082. // we revert the global references back to our active sector
  12083. this._loadLatestSector();
  12084. },
  12085. /**
  12086. * This runs a function in all frozen sectors. This is used in the _redraw().
  12087. *
  12088. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  12089. * | we don't pass the function itself because then the "this" is the window object
  12090. * | instead of the Graph object
  12091. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12092. * @private
  12093. */
  12094. _doInAllFrozenSectors : function(runFunction,argument) {
  12095. if (argument === undefined) {
  12096. for (var sector in this.sectors["frozen"]) {
  12097. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  12098. // switch the global references to those of this sector
  12099. this._switchToFrozenSector(sector);
  12100. this[runFunction]();
  12101. }
  12102. }
  12103. }
  12104. else {
  12105. for (var sector in this.sectors["frozen"]) {
  12106. if (this.sectors["frozen"].hasOwnProperty(sector)) {
  12107. // switch the global references to those of this sector
  12108. this._switchToFrozenSector(sector);
  12109. var args = Array.prototype.splice.call(arguments, 1);
  12110. if (args.length > 1) {
  12111. this[runFunction](args[0],args[1]);
  12112. }
  12113. else {
  12114. this[runFunction](argument);
  12115. }
  12116. }
  12117. }
  12118. }
  12119. this._loadLatestSector();
  12120. },
  12121. /**
  12122. * This runs a function in all sectors. This is used in the _redraw().
  12123. *
  12124. * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
  12125. * | we don't pass the function itself because then the "this" is the window object
  12126. * | instead of the Graph object
  12127. * @param {*} [argument] | Optional: arguments to pass to the runFunction
  12128. * @private
  12129. */
  12130. _doInAllSectors : function(runFunction,argument) {
  12131. var args = Array.prototype.splice.call(arguments, 1);
  12132. if (argument === undefined) {
  12133. this._doInAllActiveSectors(runFunction);
  12134. this._doInAllFrozenSectors(runFunction);
  12135. }
  12136. else {
  12137. if (args.length > 1) {
  12138. this._doInAllActiveSectors(runFunction,args[0],args[1]);
  12139. this._doInAllFrozenSectors(runFunction,args[0],args[1]);
  12140. }
  12141. else {
  12142. this._doInAllActiveSectors(runFunction,argument);
  12143. this._doInAllFrozenSectors(runFunction,argument);
  12144. }
  12145. }
  12146. },
  12147. /**
  12148. * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
  12149. * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
  12150. *
  12151. * @private
  12152. */
  12153. _clearNodeIndexList : function() {
  12154. var sector = this._sector();
  12155. this.sectors["active"][sector]["nodeIndices"] = [];
  12156. this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
  12157. },
  12158. /**
  12159. * Draw the encompassing sector node
  12160. *
  12161. * @param ctx
  12162. * @param sectorType
  12163. * @private
  12164. */
  12165. _drawSectorNodes : function(ctx,sectorType) {
  12166. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  12167. for (var sector in this.sectors[sectorType]) {
  12168. if (this.sectors[sectorType].hasOwnProperty(sector)) {
  12169. if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
  12170. this._switchToSector(sector,sectorType);
  12171. minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
  12172. for (var nodeId in this.nodes) {
  12173. if (this.nodes.hasOwnProperty(nodeId)) {
  12174. node = this.nodes[nodeId];
  12175. node.resize(ctx);
  12176. if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
  12177. if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
  12178. if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
  12179. if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
  12180. }
  12181. }
  12182. node = this.sectors[sectorType][sector]["drawingNode"];
  12183. node.x = 0.5 * (maxX + minX);
  12184. node.y = 0.5 * (maxY + minY);
  12185. node.width = 2 * (node.x - minX);
  12186. node.height = 2 * (node.y - minY);
  12187. node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
  12188. node.setScale(this.scale);
  12189. node._drawCircle(ctx);
  12190. }
  12191. }
  12192. }
  12193. },
  12194. _drawAllSectorNodes : function(ctx) {
  12195. this._drawSectorNodes(ctx,"frozen");
  12196. this._drawSectorNodes(ctx,"active");
  12197. this._loadLatestSector();
  12198. }
  12199. };
  12200. /**
  12201. * Creation of the ClusterMixin var.
  12202. *
  12203. * This contains all the functions the Graph object can use to employ clustering
  12204. *
  12205. * Alex de Mulder
  12206. * 21-01-2013
  12207. */
  12208. var ClusterMixin = {
  12209. /**
  12210. * This is only called in the constructor of the graph object
  12211. *
  12212. */
  12213. startWithClustering : function() {
  12214. // cluster if the data set is big
  12215. this.clusterToFit(this.constants.clustering.initialMaxNodes, true);
  12216. // updates the lables after clustering
  12217. this.updateLabels();
  12218. // this is called here because if clusterin is disabled, the start and stabilize are called in
  12219. // the setData function.
  12220. if (this.stabilize) {
  12221. this._stabilize();
  12222. }
  12223. this.start();
  12224. },
  12225. /**
  12226. * This function clusters until the initialMaxNodes has been reached
  12227. *
  12228. * @param {Number} maxNumberOfNodes
  12229. * @param {Boolean} reposition
  12230. */
  12231. clusterToFit : function(maxNumberOfNodes, reposition) {
  12232. var numberOfNodes = this.nodeIndices.length;
  12233. var maxLevels = 50;
  12234. var level = 0;
  12235. // we first cluster the hubs, then we pull in the outliers, repeat
  12236. while (numberOfNodes > maxNumberOfNodes && level < maxLevels) {
  12237. if (level % 3 == 0) {
  12238. this.forceAggregateHubs(true);
  12239. this.normalizeClusterLevels();
  12240. }
  12241. else {
  12242. this.increaseClusterLevel(); // this also includes a cluster normalization
  12243. }
  12244. numberOfNodes = this.nodeIndices.length;
  12245. level += 1;
  12246. }
  12247. // after the clustering we reposition the nodes to reduce the initial chaos
  12248. if (level > 0 && reposition == true) {
  12249. this.repositionNodes();
  12250. }
  12251. this._updateCalculationNodes();
  12252. },
  12253. /**
  12254. * This function can be called to open up a specific cluster. It is only called by
  12255. * It will unpack the cluster back one level.
  12256. *
  12257. * @param node | Node object: cluster to open.
  12258. */
  12259. openCluster : function(node) {
  12260. var isMovingBeforeClustering = this.moving;
  12261. if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) &&
  12262. !(this._sector() == "default" && this.nodeIndices.length == 1)) {
  12263. // this loads a new sector, loads the nodes and edges and nodeIndices of it.
  12264. this._addSector(node);
  12265. var level = 0;
  12266. // we decluster until we reach a decent number of nodes
  12267. while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) {
  12268. this.decreaseClusterLevel();
  12269. level += 1;
  12270. }
  12271. }
  12272. else {
  12273. this._expandClusterNode(node,false,true);
  12274. // update the index list, dynamic edges and labels
  12275. this._updateNodeIndexList();
  12276. this._updateDynamicEdges();
  12277. this._updateCalculationNodes();
  12278. this.updateLabels();
  12279. }
  12280. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12281. if (this.moving != isMovingBeforeClustering) {
  12282. this.start();
  12283. }
  12284. },
  12285. /**
  12286. * This calls the updateClustes with default arguments
  12287. */
  12288. updateClustersDefault : function() {
  12289. if (this.constants.clustering.enabled == true) {
  12290. this.updateClusters(0,false,false);
  12291. }
  12292. },
  12293. /**
  12294. * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will
  12295. * be clustered with their connected node. This can be repeated as many times as needed.
  12296. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets.
  12297. */
  12298. increaseClusterLevel : function() {
  12299. this.updateClusters(-1,false,true);
  12300. },
  12301. /**
  12302. * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will
  12303. * be unpacked if they are a cluster. This can be repeated as many times as needed.
  12304. * This can be called externally (by a key-bind for instance) to look into clusters without zooming.
  12305. */
  12306. decreaseClusterLevel : function() {
  12307. this.updateClusters(1,false,true);
  12308. },
  12309. /**
  12310. * This is the main clustering function. It clusters and declusters on zoom or forced
  12311. * This function clusters on zoom, it can be called with a predefined zoom direction
  12312. * If out, check if we can form clusters, if in, check if we can open clusters.
  12313. * This function is only called from _zoom()
  12314. *
  12315. * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn
  12316. * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters
  12317. * @param {Boolean} force | enabled or disable forcing
  12318. *
  12319. */
  12320. updateClusters : function(zoomDirection,recursive,force,doNotStart) {
  12321. var isMovingBeforeClustering = this.moving;
  12322. var amountOfNodes = this.nodeIndices.length;
  12323. // on zoom out collapse the sector if the scale is at the level the sector was made
  12324. if (this.previousScale > this.scale && zoomDirection == 0) {
  12325. this._collapseSector();
  12326. }
  12327. // check if we zoom in or out
  12328. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12329. // forming clusters when forced pulls outliers in. When not forced, the edge length of the
  12330. // outer nodes determines if it is being clustered
  12331. this._formClusters(force);
  12332. }
  12333. else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in
  12334. if (force == true) {
  12335. // _openClusters checks for each node if the formationScale of the cluster is smaller than
  12336. // the current scale and if so, declusters. When forced, all clusters are reduced by one step
  12337. this._openClusters(recursive,force);
  12338. }
  12339. else {
  12340. // if a cluster takes up a set percentage of the active window
  12341. this._openClustersBySize();
  12342. }
  12343. }
  12344. this._updateNodeIndexList();
  12345. // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs
  12346. if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) {
  12347. this._aggregateHubs(force);
  12348. this._updateNodeIndexList();
  12349. }
  12350. // we now reduce chains.
  12351. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out
  12352. this.handleChains();
  12353. this._updateNodeIndexList();
  12354. }
  12355. this.previousScale = this.scale;
  12356. // rest of the update the index list, dynamic edges and labels
  12357. this._updateDynamicEdges();
  12358. this.updateLabels();
  12359. // if a cluster was formed, we increase the clusterSession
  12360. if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place
  12361. this.clusterSession += 1;
  12362. // if clusters have been made, we normalize the cluster level
  12363. this.normalizeClusterLevels();
  12364. }
  12365. if (doNotStart == false || doNotStart === undefined) {
  12366. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12367. if (this.moving != isMovingBeforeClustering) {
  12368. this.start();
  12369. }
  12370. }
  12371. this._updateCalculationNodes();
  12372. },
  12373. /**
  12374. * This function handles the chains. It is called on every updateClusters().
  12375. */
  12376. handleChains : function() {
  12377. // after clustering we check how many chains there are
  12378. var chainPercentage = this._getChainFraction();
  12379. if (chainPercentage > this.constants.clustering.chainThreshold) {
  12380. this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage)
  12381. }
  12382. },
  12383. /**
  12384. * this functions starts clustering by hubs
  12385. * The minimum hub threshold is set globally
  12386. *
  12387. * @private
  12388. */
  12389. _aggregateHubs : function(force) {
  12390. this._getHubSize();
  12391. this._formClustersByHub(force,false);
  12392. },
  12393. /**
  12394. * This function is fired by keypress. It forces hubs to form.
  12395. *
  12396. */
  12397. forceAggregateHubs : function(doNotStart) {
  12398. var isMovingBeforeClustering = this.moving;
  12399. var amountOfNodes = this.nodeIndices.length;
  12400. this._aggregateHubs(true);
  12401. // update the index list, dynamic edges and labels
  12402. this._updateNodeIndexList();
  12403. this._updateDynamicEdges();
  12404. this.updateLabels();
  12405. // if a cluster was formed, we increase the clusterSession
  12406. if (this.nodeIndices.length != amountOfNodes) {
  12407. this.clusterSession += 1;
  12408. }
  12409. if (doNotStart == false || doNotStart === undefined) {
  12410. // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded
  12411. if (this.moving != isMovingBeforeClustering) {
  12412. this.start();
  12413. }
  12414. }
  12415. },
  12416. /**
  12417. * If a cluster takes up more than a set percentage of the screen, open the cluster
  12418. *
  12419. * @private
  12420. */
  12421. _openClustersBySize : function() {
  12422. for (var nodeId in this.nodes) {
  12423. if (this.nodes.hasOwnProperty(nodeId)) {
  12424. var node = this.nodes[nodeId];
  12425. if (node.inView() == true) {
  12426. if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
  12427. (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
  12428. this.openCluster(node);
  12429. }
  12430. }
  12431. }
  12432. }
  12433. },
  12434. /**
  12435. * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it
  12436. * has to be opened based on the current zoom level.
  12437. *
  12438. * @private
  12439. */
  12440. _openClusters : function(recursive,force) {
  12441. for (var i = 0; i < this.nodeIndices.length; i++) {
  12442. var node = this.nodes[this.nodeIndices[i]];
  12443. this._expandClusterNode(node,recursive,force);
  12444. this._updateCalculationNodes();
  12445. }
  12446. },
  12447. /**
  12448. * This function checks if a node has to be opened. This is done by checking the zoom level.
  12449. * If the node contains child nodes, this function is recursively called on the child nodes as well.
  12450. * This recursive behaviour is optional and can be set by the recursive argument.
  12451. *
  12452. * @param {Node} parentNode | to check for cluster and expand
  12453. * @param {Boolean} recursive | enabled or disable recursive calling
  12454. * @param {Boolean} force | enabled or disable forcing
  12455. * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released
  12456. * @private
  12457. */
  12458. _expandClusterNode : function(parentNode, recursive, force, openAll) {
  12459. // first check if node is a cluster
  12460. if (parentNode.clusterSize > 1) {
  12461. // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20
  12462. if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) {
  12463. openAll = true;
  12464. }
  12465. recursive = openAll ? true : recursive;
  12466. // if the last child has been added on a smaller scale than current scale decluster
  12467. if (parentNode.formationScale < this.scale || force == true) {
  12468. // we will check if any of the contained child nodes should be removed from the cluster
  12469. for (var containedNodeId in parentNode.containedNodes) {
  12470. if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) {
  12471. var childNode = parentNode.containedNodes[containedNodeId];
  12472. // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that
  12473. // the largest cluster is the one that comes from outside
  12474. if (force == true) {
  12475. if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1]
  12476. || openAll) {
  12477. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12478. }
  12479. }
  12480. else {
  12481. if (this._nodeInActiveArea(parentNode)) {
  12482. this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll);
  12483. }
  12484. }
  12485. }
  12486. }
  12487. }
  12488. }
  12489. },
  12490. /**
  12491. * ONLY CALLED FROM _expandClusterNode
  12492. *
  12493. * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove
  12494. * the child node from the parent contained_node object and put it back into the global nodes object.
  12495. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object.
  12496. *
  12497. * @param {Node} parentNode | the parent node
  12498. * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node
  12499. * @param {Boolean} recursive | This will also check if the child needs to be expanded.
  12500. * With force and recursive both true, the entire cluster is unpacked
  12501. * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent
  12502. * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released
  12503. * @private
  12504. */
  12505. _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) {
  12506. var childNode = parentNode.containedNodes[containedNodeId];
  12507. // if child node has been added on smaller scale than current, kick out
  12508. if (childNode.formationScale < this.scale || force == true) {
  12509. // unselect all selected items
  12510. this._unselectAll();
  12511. // put the child node back in the global nodes object
  12512. this.nodes[containedNodeId] = childNode;
  12513. // release the contained edges from this childNode back into the global edges
  12514. this._releaseContainedEdges(parentNode,childNode);
  12515. // reconnect rerouted edges to the childNode
  12516. this._connectEdgeBackToChild(parentNode,childNode);
  12517. // validate all edges in dynamicEdges
  12518. this._validateEdges(parentNode);
  12519. // undo the changes from the clustering operation on the parent node
  12520. parentNode.mass -= childNode.mass;
  12521. parentNode.clusterSize -= childNode.clusterSize;
  12522. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12523. parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length;
  12524. // place the child node near the parent, not at the exact same location to avoid chaos in the system
  12525. childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random());
  12526. childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random());
  12527. // remove node from the list
  12528. delete parentNode.containedNodes[containedNodeId];
  12529. // check if there are other childs with this clusterSession in the parent.
  12530. var othersPresent = false;
  12531. for (var childNodeId in parentNode.containedNodes) {
  12532. if (parentNode.containedNodes.hasOwnProperty(childNodeId)) {
  12533. if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) {
  12534. othersPresent = true;
  12535. break;
  12536. }
  12537. }
  12538. }
  12539. // if there are no others, remove the cluster session from the list
  12540. if (othersPresent == false) {
  12541. parentNode.clusterSessions.pop();
  12542. }
  12543. this._repositionBezierNodes(childNode);
  12544. // this._repositionBezierNodes(parentNode);
  12545. // remove the clusterSession from the child node
  12546. childNode.clusterSession = 0;
  12547. // recalculate the size of the node on the next time the node is rendered
  12548. parentNode.clearSizeCache();
  12549. // restart the simulation to reorganise all nodes
  12550. this.moving = true;
  12551. }
  12552. // check if a further expansion step is possible if recursivity is enabled
  12553. if (recursive == true) {
  12554. this._expandClusterNode(childNode,recursive,force,openAll);
  12555. }
  12556. },
  12557. /**
  12558. * position the bezier nodes at the center of the edges
  12559. *
  12560. * @param node
  12561. * @private
  12562. */
  12563. _repositionBezierNodes : function(node) {
  12564. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12565. node.dynamicEdges[i].positionBezierNode();
  12566. }
  12567. },
  12568. /**
  12569. * This function checks if any nodes at the end of their trees have edges below a threshold length
  12570. * This function is called only from updateClusters()
  12571. * forceLevelCollapse ignores the length of the edge and collapses one level
  12572. * This means that a node with only one edge will be clustered with its connected node
  12573. *
  12574. * @private
  12575. * @param {Boolean} force
  12576. */
  12577. _formClusters : function(force) {
  12578. if (force == false) {
  12579. this._formClustersByZoom();
  12580. }
  12581. else {
  12582. this._forceClustersByZoom();
  12583. }
  12584. },
  12585. /**
  12586. * This function handles the clustering by zooming out, this is based on a minimum edge distance
  12587. *
  12588. * @private
  12589. */
  12590. _formClustersByZoom : function() {
  12591. var dx,dy,length,
  12592. minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12593. // check if any edges are shorter than minLength and start the clustering
  12594. // the clustering favours the node with the larger mass
  12595. for (var edgeId in this.edges) {
  12596. if (this.edges.hasOwnProperty(edgeId)) {
  12597. var edge = this.edges[edgeId];
  12598. if (edge.connected) {
  12599. if (edge.toId != edge.fromId) {
  12600. dx = (edge.to.x - edge.from.x);
  12601. dy = (edge.to.y - edge.from.y);
  12602. length = Math.sqrt(dx * dx + dy * dy);
  12603. if (length < minLength) {
  12604. // first check which node is larger
  12605. var parentNode = edge.from;
  12606. var childNode = edge.to;
  12607. if (edge.to.mass > edge.from.mass) {
  12608. parentNode = edge.to;
  12609. childNode = edge.from;
  12610. }
  12611. if (childNode.dynamicEdgesLength == 1) {
  12612. this._addToCluster(parentNode,childNode,false);
  12613. }
  12614. else if (parentNode.dynamicEdgesLength == 1) {
  12615. this._addToCluster(childNode,parentNode,false);
  12616. }
  12617. }
  12618. }
  12619. }
  12620. }
  12621. }
  12622. },
  12623. /**
  12624. * This function forces the graph to cluster all nodes with only one connecting edge to their
  12625. * connected node.
  12626. *
  12627. * @private
  12628. */
  12629. _forceClustersByZoom : function() {
  12630. for (var nodeId in this.nodes) {
  12631. // another node could have absorbed this child.
  12632. if (this.nodes.hasOwnProperty(nodeId)) {
  12633. var childNode = this.nodes[nodeId];
  12634. // the edges can be swallowed by another decrease
  12635. if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) {
  12636. var edge = childNode.dynamicEdges[0];
  12637. var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId];
  12638. // group to the largest node
  12639. if (childNode.id != parentNode.id) {
  12640. if (parentNode.mass > childNode.mass) {
  12641. this._addToCluster(parentNode,childNode,true);
  12642. }
  12643. else {
  12644. this._addToCluster(childNode,parentNode,true);
  12645. }
  12646. }
  12647. }
  12648. }
  12649. }
  12650. },
  12651. /**
  12652. * To keep the nodes of roughly equal size we normalize the cluster levels.
  12653. * This function clusters a node to its smallest connected neighbour.
  12654. *
  12655. * @param node
  12656. * @private
  12657. */
  12658. _clusterToSmallestNeighbour : function(node) {
  12659. var smallestNeighbour = -1;
  12660. var smallestNeighbourNode = null;
  12661. for (var i = 0; i < node.dynamicEdges.length; i++) {
  12662. if (node.dynamicEdges[i] !== undefined) {
  12663. var neighbour = null;
  12664. if (node.dynamicEdges[i].fromId != node.id) {
  12665. neighbour = node.dynamicEdges[i].from;
  12666. }
  12667. else if (node.dynamicEdges[i].toId != node.id) {
  12668. neighbour = node.dynamicEdges[i].to;
  12669. }
  12670. if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) {
  12671. smallestNeighbour = neighbour.clusterSessions.length;
  12672. smallestNeighbourNode = neighbour;
  12673. }
  12674. }
  12675. }
  12676. if (neighbour != null && this.nodes[neighbour.id] !== undefined) {
  12677. this._addToCluster(neighbour, node, true);
  12678. }
  12679. },
  12680. /**
  12681. * This function forms clusters from hubs, it loops over all nodes
  12682. *
  12683. * @param {Boolean} force | Disregard zoom level
  12684. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12685. * @private
  12686. */
  12687. _formClustersByHub : function(force, onlyEqual) {
  12688. // we loop over all nodes in the list
  12689. for (var nodeId in this.nodes) {
  12690. // we check if it is still available since it can be used by the clustering in this loop
  12691. if (this.nodes.hasOwnProperty(nodeId)) {
  12692. this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual);
  12693. }
  12694. }
  12695. },
  12696. /**
  12697. * This function forms a cluster from a specific preselected hub node
  12698. *
  12699. * @param {Node} hubNode | the node we will cluster as a hub
  12700. * @param {Boolean} force | Disregard zoom level
  12701. * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges
  12702. * @param {Number} [absorptionSizeOffset] |
  12703. * @private
  12704. */
  12705. _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) {
  12706. if (absorptionSizeOffset === undefined) {
  12707. absorptionSizeOffset = 0;
  12708. }
  12709. // we decide if the node is a hub
  12710. if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) ||
  12711. (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) {
  12712. // initialize variables
  12713. var dx,dy,length;
  12714. var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale;
  12715. var allowCluster = false;
  12716. // we create a list of edges because the dynamicEdges change over the course of this loop
  12717. var edgesIdarray = [];
  12718. var amountOfInitialEdges = hubNode.dynamicEdges.length;
  12719. for (var j = 0; j < amountOfInitialEdges; j++) {
  12720. edgesIdarray.push(hubNode.dynamicEdges[j].id);
  12721. }
  12722. // if the hub clustering is not forces, we check if one of the edges connected
  12723. // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold
  12724. if (force == false) {
  12725. allowCluster = false;
  12726. for (j = 0; j < amountOfInitialEdges; j++) {
  12727. var edge = this.edges[edgesIdarray[j]];
  12728. if (edge !== undefined) {
  12729. if (edge.connected) {
  12730. if (edge.toId != edge.fromId) {
  12731. dx = (edge.to.x - edge.from.x);
  12732. dy = (edge.to.y - edge.from.y);
  12733. length = Math.sqrt(dx * dx + dy * dy);
  12734. if (length < minLength) {
  12735. allowCluster = true;
  12736. break;
  12737. }
  12738. }
  12739. }
  12740. }
  12741. }
  12742. }
  12743. // start the clustering if allowed
  12744. if ((!force && allowCluster) || force) {
  12745. // we loop over all edges INITIALLY connected to this hub
  12746. for (j = 0; j < amountOfInitialEdges; j++) {
  12747. edge = this.edges[edgesIdarray[j]];
  12748. // the edge can be clustered by this function in a previous loop
  12749. if (edge !== undefined) {
  12750. var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId];
  12751. // we do not want hubs to merge with other hubs nor do we want to cluster itself.
  12752. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) &&
  12753. (childNode.id != hubNode.id)) {
  12754. this._addToCluster(hubNode,childNode,force);
  12755. }
  12756. }
  12757. }
  12758. }
  12759. }
  12760. },
  12761. /**
  12762. * This function adds the child node to the parent node, creating a cluster if it is not already.
  12763. *
  12764. * @param {Node} parentNode | this is the node that will house the child node
  12765. * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node
  12766. * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse
  12767. * @private
  12768. */
  12769. _addToCluster : function(parentNode, childNode, force) {
  12770. // join child node in the parent node
  12771. parentNode.containedNodes[childNode.id] = childNode;
  12772. // manage all the edges connected to the child and parent nodes
  12773. for (var i = 0; i < childNode.dynamicEdges.length; i++) {
  12774. var edge = childNode.dynamicEdges[i];
  12775. if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode
  12776. this._addToContainedEdges(parentNode,childNode,edge);
  12777. }
  12778. else {
  12779. this._connectEdgeToCluster(parentNode,childNode,edge);
  12780. }
  12781. }
  12782. // a contained node has no dynamic edges.
  12783. childNode.dynamicEdges = [];
  12784. // remove circular edges from clusters
  12785. this._containCircularEdgesFromNode(parentNode,childNode);
  12786. // remove the childNode from the global nodes object
  12787. delete this.nodes[childNode.id];
  12788. // update the properties of the child and parent
  12789. var massBefore = parentNode.mass;
  12790. childNode.clusterSession = this.clusterSession;
  12791. parentNode.mass += childNode.mass;
  12792. parentNode.clusterSize += childNode.clusterSize;
  12793. parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize);
  12794. // keep track of the clustersessions so we can open the cluster up as it has been formed.
  12795. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) {
  12796. parentNode.clusterSessions.push(this.clusterSession);
  12797. }
  12798. // forced clusters only open from screen size and double tap
  12799. if (force == true) {
  12800. // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3);
  12801. parentNode.formationScale = 0;
  12802. }
  12803. else {
  12804. parentNode.formationScale = this.scale; // The latest child has been added on this scale
  12805. }
  12806. // recalculate the size of the node on the next time the node is rendered
  12807. parentNode.clearSizeCache();
  12808. // set the pop-out scale for the childnode
  12809. parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale;
  12810. // nullify the movement velocity of the child, this is to avoid hectic behaviour
  12811. childNode.clearVelocity();
  12812. // the mass has altered, preservation of energy dictates the velocity to be updated
  12813. parentNode.updateVelocity(massBefore);
  12814. // restart the simulation to reorganise all nodes
  12815. this.moving = true;
  12816. },
  12817. /**
  12818. * This function will apply the changes made to the remainingEdges during the formation of the clusters.
  12819. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree.
  12820. * It has to be called if a level is collapsed. It is called by _formClusters().
  12821. * @private
  12822. */
  12823. _updateDynamicEdges : function() {
  12824. for (var i = 0; i < this.nodeIndices.length; i++) {
  12825. var node = this.nodes[this.nodeIndices[i]];
  12826. node.dynamicEdgesLength = node.dynamicEdges.length;
  12827. // this corrects for multiple edges pointing at the same other node
  12828. var correction = 0;
  12829. if (node.dynamicEdgesLength > 1) {
  12830. for (var j = 0; j < node.dynamicEdgesLength - 1; j++) {
  12831. var edgeToId = node.dynamicEdges[j].toId;
  12832. var edgeFromId = node.dynamicEdges[j].fromId;
  12833. for (var k = j+1; k < node.dynamicEdgesLength; k++) {
  12834. if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) ||
  12835. (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) {
  12836. correction += 1;
  12837. }
  12838. }
  12839. }
  12840. }
  12841. node.dynamicEdgesLength -= correction;
  12842. }
  12843. },
  12844. /**
  12845. * This adds an edge from the childNode to the contained edges of the parent node
  12846. *
  12847. * @param parentNode | Node object
  12848. * @param childNode | Node object
  12849. * @param edge | Edge object
  12850. * @private
  12851. */
  12852. _addToContainedEdges : function(parentNode, childNode, edge) {
  12853. // create an array object if it does not yet exist for this childNode
  12854. if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) {
  12855. parentNode.containedEdges[childNode.id] = []
  12856. }
  12857. // add this edge to the list
  12858. parentNode.containedEdges[childNode.id].push(edge);
  12859. // remove the edge from the global edges object
  12860. delete this.edges[edge.id];
  12861. // remove the edge from the parent object
  12862. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12863. if (parentNode.dynamicEdges[i].id == edge.id) {
  12864. parentNode.dynamicEdges.splice(i,1);
  12865. break;
  12866. }
  12867. }
  12868. },
  12869. /**
  12870. * This function connects an edge that was connected to a child node to the parent node.
  12871. * It keeps track of which nodes it has been connected to with the originalId array.
  12872. *
  12873. * @param {Node} parentNode | Node object
  12874. * @param {Node} childNode | Node object
  12875. * @param {Edge} edge | Edge object
  12876. * @private
  12877. */
  12878. _connectEdgeToCluster : function(parentNode, childNode, edge) {
  12879. // handle circular edges
  12880. if (edge.toId == edge.fromId) {
  12881. this._addToContainedEdges(parentNode, childNode, edge);
  12882. }
  12883. else {
  12884. if (edge.toId == childNode.id) { // edge connected to other node on the "to" side
  12885. edge.originalToId.push(childNode.id);
  12886. edge.to = parentNode;
  12887. edge.toId = parentNode.id;
  12888. }
  12889. else { // edge connected to other node with the "from" side
  12890. edge.originalFromId.push(childNode.id);
  12891. edge.from = parentNode;
  12892. edge.fromId = parentNode.id;
  12893. }
  12894. this._addToReroutedEdges(parentNode,childNode,edge);
  12895. }
  12896. },
  12897. /**
  12898. * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain
  12899. * these edges inside of the cluster.
  12900. *
  12901. * @param parentNode
  12902. * @param childNode
  12903. * @private
  12904. */
  12905. _containCircularEdgesFromNode : function(parentNode, childNode) {
  12906. // manage all the edges connected to the child and parent nodes
  12907. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12908. var edge = parentNode.dynamicEdges[i];
  12909. // handle circular edges
  12910. if (edge.toId == edge.fromId) {
  12911. this._addToContainedEdges(parentNode, childNode, edge);
  12912. }
  12913. }
  12914. },
  12915. /**
  12916. * This adds an edge from the childNode to the rerouted edges of the parent node
  12917. *
  12918. * @param parentNode | Node object
  12919. * @param childNode | Node object
  12920. * @param edge | Edge object
  12921. * @private
  12922. */
  12923. _addToReroutedEdges : function(parentNode, childNode, edge) {
  12924. // create an array object if it does not yet exist for this childNode
  12925. // we store the edge in the rerouted edges so we can restore it when the cluster pops open
  12926. if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) {
  12927. parentNode.reroutedEdges[childNode.id] = [];
  12928. }
  12929. parentNode.reroutedEdges[childNode.id].push(edge);
  12930. // this edge becomes part of the dynamicEdges of the cluster node
  12931. parentNode.dynamicEdges.push(edge);
  12932. },
  12933. /**
  12934. * This function connects an edge that was connected to a cluster node back to the child node.
  12935. *
  12936. * @param parentNode | Node object
  12937. * @param childNode | Node object
  12938. * @private
  12939. */
  12940. _connectEdgeBackToChild : function(parentNode, childNode) {
  12941. if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) {
  12942. for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) {
  12943. var edge = parentNode.reroutedEdges[childNode.id][i];
  12944. if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) {
  12945. edge.originalFromId.pop();
  12946. edge.fromId = childNode.id;
  12947. edge.from = childNode;
  12948. }
  12949. else {
  12950. edge.originalToId.pop();
  12951. edge.toId = childNode.id;
  12952. edge.to = childNode;
  12953. }
  12954. // append this edge to the list of edges connecting to the childnode
  12955. childNode.dynamicEdges.push(edge);
  12956. // remove the edge from the parent object
  12957. for (var j = 0; j < parentNode.dynamicEdges.length; j++) {
  12958. if (parentNode.dynamicEdges[j].id == edge.id) {
  12959. parentNode.dynamicEdges.splice(j,1);
  12960. break;
  12961. }
  12962. }
  12963. }
  12964. // remove the entry from the rerouted edges
  12965. delete parentNode.reroutedEdges[childNode.id];
  12966. }
  12967. },
  12968. /**
  12969. * When loops are clustered, an edge can be both in the rerouted array and the contained array.
  12970. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the
  12971. * parentNode
  12972. *
  12973. * @param parentNode | Node object
  12974. * @private
  12975. */
  12976. _validateEdges : function(parentNode) {
  12977. for (var i = 0; i < parentNode.dynamicEdges.length; i++) {
  12978. var edge = parentNode.dynamicEdges[i];
  12979. if (parentNode.id != edge.toId && parentNode.id != edge.fromId) {
  12980. parentNode.dynamicEdges.splice(i,1);
  12981. }
  12982. }
  12983. },
  12984. /**
  12985. * This function released the contained edges back into the global domain and puts them back into the
  12986. * dynamic edges of both parent and child.
  12987. *
  12988. * @param {Node} parentNode |
  12989. * @param {Node} childNode |
  12990. * @private
  12991. */
  12992. _releaseContainedEdges : function(parentNode, childNode) {
  12993. for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) {
  12994. var edge = parentNode.containedEdges[childNode.id][i];
  12995. // put the edge back in the global edges object
  12996. this.edges[edge.id] = edge;
  12997. // put the edge back in the dynamic edges of the child and parent
  12998. childNode.dynamicEdges.push(edge);
  12999. parentNode.dynamicEdges.push(edge);
  13000. }
  13001. // remove the entry from the contained edges
  13002. delete parentNode.containedEdges[childNode.id];
  13003. },
  13004. // ------------------- UTILITY FUNCTIONS ---------------------------- //
  13005. /**
  13006. * This updates the node labels for all nodes (for debugging purposes)
  13007. */
  13008. updateLabels : function() {
  13009. var nodeId;
  13010. // update node labels
  13011. for (nodeId in this.nodes) {
  13012. if (this.nodes.hasOwnProperty(nodeId)) {
  13013. var node = this.nodes[nodeId];
  13014. if (node.clusterSize > 1) {
  13015. node.label = "[".concat(String(node.clusterSize),"]");
  13016. }
  13017. }
  13018. }
  13019. // update node labels
  13020. for (nodeId in this.nodes) {
  13021. if (this.nodes.hasOwnProperty(nodeId)) {
  13022. node = this.nodes[nodeId];
  13023. if (node.clusterSize == 1) {
  13024. if (node.originalLabel !== undefined) {
  13025. node.label = node.originalLabel;
  13026. }
  13027. else {
  13028. node.label = String(node.id);
  13029. }
  13030. }
  13031. }
  13032. }
  13033. // /* Debug Override */
  13034. // for (nodeId in this.nodes) {
  13035. // if (this.nodes.hasOwnProperty(nodeId)) {
  13036. // node = this.nodes[nodeId];
  13037. // node.label = String(node.level);
  13038. // }
  13039. // }
  13040. },
  13041. /**
  13042. * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes
  13043. * if the rest of the nodes are already a few cluster levels in.
  13044. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not
  13045. * clustered enough to the clusterToSmallestNeighbours function.
  13046. */
  13047. normalizeClusterLevels : function() {
  13048. var maxLevel = 0;
  13049. var minLevel = 1e9;
  13050. var clusterLevel = 0;
  13051. // we loop over all nodes in the list
  13052. for (var nodeId in this.nodes) {
  13053. if (this.nodes.hasOwnProperty(nodeId)) {
  13054. clusterLevel = this.nodes[nodeId].clusterSessions.length;
  13055. if (maxLevel < clusterLevel) {maxLevel = clusterLevel;}
  13056. if (minLevel > clusterLevel) {minLevel = clusterLevel;}
  13057. }
  13058. }
  13059. if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) {
  13060. var amountOfNodes = this.nodeIndices.length;
  13061. var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference;
  13062. // we loop over all nodes in the list
  13063. for (var nodeId in this.nodes) {
  13064. if (this.nodes.hasOwnProperty(nodeId)) {
  13065. if (this.nodes[nodeId].clusterSessions.length < targetLevel) {
  13066. this._clusterToSmallestNeighbour(this.nodes[nodeId]);
  13067. }
  13068. }
  13069. }
  13070. this._updateNodeIndexList();
  13071. this._updateDynamicEdges();
  13072. // if a cluster was formed, we increase the clusterSession
  13073. if (this.nodeIndices.length != amountOfNodes) {
  13074. this.clusterSession += 1;
  13075. }
  13076. }
  13077. },
  13078. /**
  13079. * This function determines if the cluster we want to decluster is in the active area
  13080. * this means around the zoom center
  13081. *
  13082. * @param {Node} node
  13083. * @returns {boolean}
  13084. * @private
  13085. */
  13086. _nodeInActiveArea : function(node) {
  13087. return (
  13088. Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale
  13089. &&
  13090. Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale
  13091. )
  13092. },
  13093. /**
  13094. * This is an adaptation of the original repositioning function. This is called if the system is clustered initially
  13095. * It puts large clusters away from the center and randomizes the order.
  13096. *
  13097. */
  13098. repositionNodes : function() {
  13099. for (var i = 0; i < this.nodeIndices.length; i++) {
  13100. var node = this.nodes[this.nodeIndices[i]];
  13101. if ((node.xFixed == false || node.yFixed == false)) {
  13102. var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.mass);
  13103. var angle = 2 * Math.PI * Math.random();
  13104. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  13105. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  13106. this._repositionBezierNodes(node);
  13107. }
  13108. }
  13109. },
  13110. /**
  13111. * We determine how many connections denote an important hub.
  13112. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  13113. *
  13114. * @private
  13115. */
  13116. _getHubSize : function() {
  13117. var average = 0;
  13118. var averageSquared = 0;
  13119. var hubCounter = 0;
  13120. var largestHub = 0;
  13121. for (var i = 0; i < this.nodeIndices.length; i++) {
  13122. var node = this.nodes[this.nodeIndices[i]];
  13123. if (node.dynamicEdgesLength > largestHub) {
  13124. largestHub = node.dynamicEdgesLength;
  13125. }
  13126. average += node.dynamicEdgesLength;
  13127. averageSquared += Math.pow(node.dynamicEdgesLength,2);
  13128. hubCounter += 1;
  13129. }
  13130. average = average / hubCounter;
  13131. averageSquared = averageSquared / hubCounter;
  13132. var variance = averageSquared - Math.pow(average,2);
  13133. var standardDeviation = Math.sqrt(variance);
  13134. this.hubThreshold = Math.floor(average + 2*standardDeviation);
  13135. // always have at least one to cluster
  13136. if (this.hubThreshold > largestHub) {
  13137. this.hubThreshold = largestHub;
  13138. }
  13139. // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation);
  13140. // console.log("hubThreshold:",this.hubThreshold);
  13141. },
  13142. /**
  13143. * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  13144. * with this amount we can cluster specifically on these chains.
  13145. *
  13146. * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce
  13147. * @private
  13148. */
  13149. _reduceAmountOfChains : function(fraction) {
  13150. this.hubThreshold = 2;
  13151. var reduceAmount = Math.floor(this.nodeIndices.length * fraction);
  13152. for (var nodeId in this.nodes) {
  13153. if (this.nodes.hasOwnProperty(nodeId)) {
  13154. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  13155. if (reduceAmount > 0) {
  13156. this._formClusterFromHub(this.nodes[nodeId],true,true,1);
  13157. reduceAmount -= 1;
  13158. }
  13159. }
  13160. }
  13161. }
  13162. },
  13163. /**
  13164. * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods
  13165. * with this amount we can cluster specifically on these chains.
  13166. *
  13167. * @private
  13168. */
  13169. _getChainFraction : function() {
  13170. var chains = 0;
  13171. var total = 0;
  13172. for (var nodeId in this.nodes) {
  13173. if (this.nodes.hasOwnProperty(nodeId)) {
  13174. if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) {
  13175. chains += 1;
  13176. }
  13177. total += 1;
  13178. }
  13179. }
  13180. return chains/total;
  13181. }
  13182. };
  13183. var SelectionMixin = {
  13184. /**
  13185. * This function can be called from the _doInAllSectors function
  13186. *
  13187. * @param object
  13188. * @param overlappingNodes
  13189. * @private
  13190. */
  13191. _getNodesOverlappingWith : function(object, overlappingNodes) {
  13192. var nodes = this.nodes;
  13193. for (var nodeId in nodes) {
  13194. if (nodes.hasOwnProperty(nodeId)) {
  13195. if (nodes[nodeId].isOverlappingWith(object)) {
  13196. overlappingNodes.push(nodeId);
  13197. }
  13198. }
  13199. }
  13200. },
  13201. /**
  13202. * retrieve all nodes overlapping with given object
  13203. * @param {Object} object An object with parameters left, top, right, bottom
  13204. * @return {Number[]} An array with id's of the overlapping nodes
  13205. * @private
  13206. */
  13207. _getAllNodesOverlappingWith : function (object) {
  13208. var overlappingNodes = [];
  13209. this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
  13210. return overlappingNodes;
  13211. },
  13212. /**
  13213. * Return a position object in canvasspace from a single point in screenspace
  13214. *
  13215. * @param pointer
  13216. * @returns {{left: number, top: number, right: number, bottom: number}}
  13217. * @private
  13218. */
  13219. _pointerToPositionObject : function(pointer) {
  13220. var x = this._canvasToX(pointer.x);
  13221. var y = this._canvasToY(pointer.y);
  13222. return {left: x,
  13223. top: y,
  13224. right: x,
  13225. bottom: y};
  13226. },
  13227. /**
  13228. * Get the top node at the a specific point (like a click)
  13229. *
  13230. * @param {{x: Number, y: Number}} pointer
  13231. * @return {Node | null} node
  13232. * @private
  13233. */
  13234. _getNodeAt : function (pointer) {
  13235. // we first check if this is an navigation controls element
  13236. var positionObject = this._pointerToPositionObject(pointer);
  13237. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  13238. // if there are overlapping nodes, select the last one, this is the
  13239. // one which is drawn on top of the others
  13240. if (overlappingNodes.length > 0) {
  13241. return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
  13242. }
  13243. else {
  13244. return null;
  13245. }
  13246. },
  13247. /**
  13248. * retrieve all edges overlapping with given object, selector is around center
  13249. * @param {Object} object An object with parameters left, top, right, bottom
  13250. * @return {Number[]} An array with id's of the overlapping nodes
  13251. * @private
  13252. */
  13253. _getEdgesOverlappingWith : function (object, overlappingEdges) {
  13254. var edges = this.edges;
  13255. for (var edgeId in edges) {
  13256. if (edges.hasOwnProperty(edgeId)) {
  13257. if (edges[edgeId].isOverlappingWith(object)) {
  13258. overlappingEdges.push(edgeId);
  13259. }
  13260. }
  13261. }
  13262. },
  13263. /**
  13264. * retrieve all nodes overlapping with given object
  13265. * @param {Object} object An object with parameters left, top, right, bottom
  13266. * @return {Number[]} An array with id's of the overlapping nodes
  13267. * @private
  13268. */
  13269. _getAllEdgesOverlappingWith : function (object) {
  13270. var overlappingEdges = [];
  13271. this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
  13272. return overlappingEdges;
  13273. },
  13274. /**
  13275. * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
  13276. * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  13277. *
  13278. * @param pointer
  13279. * @returns {null}
  13280. * @private
  13281. */
  13282. _getEdgeAt : function(pointer) {
  13283. var positionObject = this._pointerToPositionObject(pointer);
  13284. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  13285. if (overlappingEdges.length > 0) {
  13286. return this.edges[overlappingEdges[overlappingEdges.length - 1]];
  13287. }
  13288. else {
  13289. return null;
  13290. }
  13291. },
  13292. /**
  13293. * Add object to the selection array.
  13294. *
  13295. * @param obj
  13296. * @private
  13297. */
  13298. _addToSelection : function(obj) {
  13299. if (obj instanceof Node) {
  13300. this.selectionObj.nodes[obj.id] = obj;
  13301. }
  13302. else {
  13303. this.selectionObj.edges[obj.id] = obj;
  13304. }
  13305. },
  13306. /**
  13307. * Remove a single option from selection.
  13308. *
  13309. * @param {Object} obj
  13310. * @private
  13311. */
  13312. _removeFromSelection : function(obj) {
  13313. if (obj instanceof Node) {
  13314. delete this.selectionObj.nodes[obj.id];
  13315. }
  13316. else {
  13317. delete this.selectionObj.edges[obj.id];
  13318. }
  13319. },
  13320. /**
  13321. * Unselect all. The selectionObj is useful for this.
  13322. *
  13323. * @param {Boolean} [doNotTrigger] | ignore trigger
  13324. * @private
  13325. */
  13326. _unselectAll : function(doNotTrigger) {
  13327. if (doNotTrigger === undefined) {
  13328. doNotTrigger = false;
  13329. }
  13330. for(var nodeId in this.selectionObj.nodes) {
  13331. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13332. this.selectionObj.nodes[nodeId].unselect();
  13333. }
  13334. }
  13335. for(var edgeId in this.selectionObj.edges) {
  13336. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13337. this.selectionObj.edges[edgeId].unselect();;
  13338. }
  13339. }
  13340. this.selectionObj = {nodes:{},edges:{}};
  13341. if (doNotTrigger == false) {
  13342. this.emit('select', this.getSelection());
  13343. }
  13344. },
  13345. /**
  13346. * Unselect all clusters. The selectionObj is useful for this.
  13347. *
  13348. * @param {Boolean} [doNotTrigger] | ignore trigger
  13349. * @private
  13350. */
  13351. _unselectClusters : function(doNotTrigger) {
  13352. if (doNotTrigger === undefined) {
  13353. doNotTrigger = false;
  13354. }
  13355. for (var nodeId in this.selectionObj.nodes) {
  13356. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13357. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13358. this.selectionObj.nodes[nodeId].unselect();
  13359. this._removeFromSelection(this.selectionObj.nodes[nodeId]);
  13360. }
  13361. }
  13362. }
  13363. if (doNotTrigger == false) {
  13364. this.emit('select', this.getSelection());
  13365. }
  13366. },
  13367. /**
  13368. * return the number of selected nodes
  13369. *
  13370. * @returns {number}
  13371. * @private
  13372. */
  13373. _getSelectedNodeCount : function() {
  13374. var count = 0;
  13375. for (var nodeId in this.selectionObj.nodes) {
  13376. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13377. count += 1;
  13378. }
  13379. }
  13380. return count;
  13381. },
  13382. /**
  13383. * return the number of selected nodes
  13384. *
  13385. * @returns {number}
  13386. * @private
  13387. */
  13388. _getSelectedNode : function() {
  13389. for (var nodeId in this.selectionObj.nodes) {
  13390. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13391. return this.selectionObj.nodes[nodeId];
  13392. }
  13393. }
  13394. return null;
  13395. },
  13396. /**
  13397. * return the number of selected edges
  13398. *
  13399. * @returns {number}
  13400. * @private
  13401. */
  13402. _getSelectedEdgeCount : function() {
  13403. var count = 0;
  13404. for (var edgeId in this.selectionObj.edges) {
  13405. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13406. count += 1;
  13407. }
  13408. }
  13409. return count;
  13410. },
  13411. /**
  13412. * return the number of selected objects.
  13413. *
  13414. * @returns {number}
  13415. * @private
  13416. */
  13417. _getSelectedObjectCount : function() {
  13418. var count = 0;
  13419. for(var nodeId in this.selectionObj.nodes) {
  13420. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13421. count += 1;
  13422. }
  13423. }
  13424. for(var edgeId in this.selectionObj.edges) {
  13425. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13426. count += 1;
  13427. }
  13428. }
  13429. return count;
  13430. },
  13431. /**
  13432. * Check if anything is selected
  13433. *
  13434. * @returns {boolean}
  13435. * @private
  13436. */
  13437. _selectionIsEmpty : function() {
  13438. for(var nodeId in this.selectionObj.nodes) {
  13439. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13440. return false;
  13441. }
  13442. }
  13443. for(var edgeId in this.selectionObj.edges) {
  13444. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13445. return false;
  13446. }
  13447. }
  13448. return true;
  13449. },
  13450. /**
  13451. * check if one of the selected nodes is a cluster.
  13452. *
  13453. * @returns {boolean}
  13454. * @private
  13455. */
  13456. _clusterInSelection : function() {
  13457. for(var nodeId in this.selectionObj.nodes) {
  13458. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13459. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  13460. return true;
  13461. }
  13462. }
  13463. }
  13464. return false;
  13465. },
  13466. /**
  13467. * select the edges connected to the node that is being selected
  13468. *
  13469. * @param {Node} node
  13470. * @private
  13471. */
  13472. _selectConnectedEdges : function(node) {
  13473. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13474. var edge = node.dynamicEdges[i];
  13475. edge.select();
  13476. this._addToSelection(edge);
  13477. }
  13478. },
  13479. /**
  13480. * unselect the edges connected to the node that is being selected
  13481. *
  13482. * @param {Node} node
  13483. * @private
  13484. */
  13485. _unselectConnectedEdges : function(node) {
  13486. for (var i = 0; i < node.dynamicEdges.length; i++) {
  13487. var edge = node.dynamicEdges[i];
  13488. edge.unselect();
  13489. this._removeFromSelection(edge);
  13490. }
  13491. },
  13492. /**
  13493. * This is called when someone clicks on a node. either select or deselect it.
  13494. * If there is an existing selection and we don't want to append to it, clear the existing selection
  13495. *
  13496. * @param {Node || Edge} object
  13497. * @param {Boolean} append
  13498. * @param {Boolean} [doNotTrigger] | ignore trigger
  13499. * @private
  13500. */
  13501. _selectObject : function(object, append, doNotTrigger) {
  13502. if (doNotTrigger === undefined) {
  13503. doNotTrigger = false;
  13504. }
  13505. if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
  13506. this._unselectAll(true);
  13507. }
  13508. if (object.selected == false) {
  13509. object.select();
  13510. this._addToSelection(object);
  13511. if (object instanceof Node && this.blockConnectingEdgeSelection == false) {
  13512. this._selectConnectedEdges(object);
  13513. }
  13514. }
  13515. else {
  13516. object.unselect();
  13517. this._removeFromSelection(object);
  13518. }
  13519. if (doNotTrigger == false) {
  13520. this.emit('select', this.getSelection());
  13521. }
  13522. },
  13523. /**
  13524. * handles the selection part of the touch, only for navigation controls elements;
  13525. * Touch is triggered before tap, also before hold. Hold triggers after a while.
  13526. * This is the most responsive solution
  13527. *
  13528. * @param {Object} pointer
  13529. * @private
  13530. */
  13531. _handleTouch : function(pointer) {
  13532. },
  13533. /**
  13534. * handles the selection part of the tap;
  13535. *
  13536. * @param {Object} pointer
  13537. * @private
  13538. */
  13539. _handleTap : function(pointer) {
  13540. var node = this._getNodeAt(pointer);
  13541. if (node != null) {
  13542. this._selectObject(node,false);
  13543. }
  13544. else {
  13545. var edge = this._getEdgeAt(pointer);
  13546. if (edge != null) {
  13547. this._selectObject(edge,false);
  13548. }
  13549. else {
  13550. this._unselectAll();
  13551. }
  13552. }
  13553. this.emit("click", this.getSelection());
  13554. this._redraw();
  13555. },
  13556. /**
  13557. * handles the selection part of the double tap and opens a cluster if needed
  13558. *
  13559. * @param {Object} pointer
  13560. * @private
  13561. */
  13562. _handleDoubleTap : function(pointer) {
  13563. var node = this._getNodeAt(pointer);
  13564. if (node != null && node !== undefined) {
  13565. // we reset the areaCenter here so the opening of the node will occur
  13566. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  13567. "y" : this._canvasToY(pointer.y)};
  13568. this.openCluster(node);
  13569. }
  13570. this.emit("doubleClick", this.getSelection());
  13571. },
  13572. /**
  13573. * Handle the onHold selection part
  13574. *
  13575. * @param pointer
  13576. * @private
  13577. */
  13578. _handleOnHold : function(pointer) {
  13579. var node = this._getNodeAt(pointer);
  13580. if (node != null) {
  13581. this._selectObject(node,true);
  13582. }
  13583. else {
  13584. var edge = this._getEdgeAt(pointer);
  13585. if (edge != null) {
  13586. this._selectObject(edge,true);
  13587. }
  13588. }
  13589. this._redraw();
  13590. },
  13591. /**
  13592. * handle the onRelease event. These functions are here for the navigation controls module.
  13593. *
  13594. * @private
  13595. */
  13596. _handleOnRelease : function(pointer) {
  13597. },
  13598. /**
  13599. *
  13600. * retrieve the currently selected objects
  13601. * @return {Number[] | String[]} selection An array with the ids of the
  13602. * selected nodes.
  13603. */
  13604. getSelection : function() {
  13605. var nodeIds = this.getSelectedNodes();
  13606. var edgeIds = this.getSelectedEdges();
  13607. return {nodes:nodeIds, edges:edgeIds};
  13608. },
  13609. /**
  13610. *
  13611. * retrieve the currently selected nodes
  13612. * @return {String} selection An array with the ids of the
  13613. * selected nodes.
  13614. */
  13615. getSelectedNodes : function() {
  13616. var idArray = [];
  13617. for(var nodeId in this.selectionObj.nodes) {
  13618. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13619. idArray.push(nodeId);
  13620. }
  13621. }
  13622. return idArray
  13623. },
  13624. /**
  13625. *
  13626. * retrieve the currently selected edges
  13627. * @return {Array} selection An array with the ids of the
  13628. * selected nodes.
  13629. */
  13630. getSelectedEdges : function() {
  13631. var idArray = [];
  13632. for(var edgeId in this.selectionObj.edges) {
  13633. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13634. idArray.push(edgeId);
  13635. }
  13636. }
  13637. return idArray;
  13638. },
  13639. /**
  13640. * select zero or more nodes
  13641. * @param {Number[] | String[]} selection An array with the ids of the
  13642. * selected nodes.
  13643. */
  13644. setSelection : function(selection) {
  13645. var i, iMax, id;
  13646. if (!selection || (selection.length == undefined))
  13647. throw 'Selection must be an array with ids';
  13648. // first unselect any selected node
  13649. this._unselectAll(true);
  13650. for (i = 0, iMax = selection.length; i < iMax; i++) {
  13651. id = selection[i];
  13652. var node = this.nodes[id];
  13653. if (!node) {
  13654. throw new RangeError('Node with id "' + id + '" not found');
  13655. }
  13656. this._selectObject(node,true,true);
  13657. }
  13658. this.redraw();
  13659. },
  13660. /**
  13661. * Validate the selection: remove ids of nodes which no longer exist
  13662. * @private
  13663. */
  13664. _updateSelection : function () {
  13665. for(var nodeId in this.selectionObj.nodes) {
  13666. if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  13667. if (!this.nodes.hasOwnProperty(nodeId)) {
  13668. delete this.selectionObj.nodes[nodeId];
  13669. }
  13670. }
  13671. }
  13672. for(var edgeId in this.selectionObj.edges) {
  13673. if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
  13674. if (!this.edges.hasOwnProperty(edgeId)) {
  13675. delete this.selectionObj.edges[edgeId];
  13676. }
  13677. }
  13678. }
  13679. }
  13680. };
  13681. /**
  13682. * Created by Alex on 1/22/14.
  13683. */
  13684. var NavigationMixin = {
  13685. _cleanNavigation : function() {
  13686. // clean up previosu navigation items
  13687. var wrapper = document.getElementById('graph-navigation_wrapper');
  13688. if (wrapper != null) {
  13689. this.containerElement.removeChild(wrapper);
  13690. }
  13691. document.onmouseup = null;
  13692. },
  13693. /**
  13694. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  13695. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  13696. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  13697. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  13698. *
  13699. * @private
  13700. */
  13701. _loadNavigationElements : function() {
  13702. this._cleanNavigation();
  13703. this.navigationDivs = {};
  13704. var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
  13705. var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
  13706. this.navigationDivs['wrapper'] = document.createElement('div');
  13707. this.navigationDivs['wrapper'].id = "graph-navigation_wrapper";
  13708. this.navigationDivs['wrapper'].style.position = "absolute";
  13709. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  13710. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  13711. this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
  13712. for (var i = 0; i < navigationDivs.length; i++) {
  13713. this.navigationDivs[navigationDivs[i]] = document.createElement('div');
  13714. this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i];
  13715. this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i];
  13716. this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
  13717. this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
  13718. }
  13719. document.onmouseup = this._stopMovement.bind(this);
  13720. },
  13721. /**
  13722. * this stops all movement induced by the navigation buttons
  13723. *
  13724. * @private
  13725. */
  13726. _stopMovement : function() {
  13727. this._xStopMoving();
  13728. this._yStopMoving();
  13729. this._stopZoom();
  13730. },
  13731. /**
  13732. * stops the actions performed by page up and down etc.
  13733. *
  13734. * @param event
  13735. * @private
  13736. */
  13737. _preventDefault : function(event) {
  13738. if (event !== undefined) {
  13739. if (event.preventDefault) {
  13740. event.preventDefault();
  13741. } else {
  13742. event.returnValue = false;
  13743. }
  13744. }
  13745. },
  13746. /**
  13747. * move the screen up
  13748. * By using the increments, instead of adding a fixed number to the translation, we keep fluent and
  13749. * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
  13750. * To avoid this behaviour, we do the translation in the start loop.
  13751. *
  13752. * @private
  13753. */
  13754. _moveUp : function(event) {
  13755. this.yIncrement = this.constants.keyboard.speed.y;
  13756. this.start(); // if there is no node movement, the calculation wont be done
  13757. this._preventDefault(event);
  13758. if (this.navigationDivs) {
  13759. this.navigationDivs['up'].className += " active";
  13760. }
  13761. },
  13762. /**
  13763. * move the screen down
  13764. * @private
  13765. */
  13766. _moveDown : function(event) {
  13767. this.yIncrement = -this.constants.keyboard.speed.y;
  13768. this.start(); // if there is no node movement, the calculation wont be done
  13769. this._preventDefault(event);
  13770. if (this.navigationDivs) {
  13771. this.navigationDivs['down'].className += " active";
  13772. }
  13773. },
  13774. /**
  13775. * move the screen left
  13776. * @private
  13777. */
  13778. _moveLeft : function(event) {
  13779. this.xIncrement = this.constants.keyboard.speed.x;
  13780. this.start(); // if there is no node movement, the calculation wont be done
  13781. this._preventDefault(event);
  13782. if (this.navigationDivs) {
  13783. this.navigationDivs['left'].className += " active";
  13784. }
  13785. },
  13786. /**
  13787. * move the screen right
  13788. * @private
  13789. */
  13790. _moveRight : function(event) {
  13791. this.xIncrement = -this.constants.keyboard.speed.y;
  13792. this.start(); // if there is no node movement, the calculation wont be done
  13793. this._preventDefault(event);
  13794. if (this.navigationDivs) {
  13795. this.navigationDivs['right'].className += " active";
  13796. }
  13797. },
  13798. /**
  13799. * Zoom in, using the same method as the movement.
  13800. * @private
  13801. */
  13802. _zoomIn : function(event) {
  13803. this.zoomIncrement = this.constants.keyboard.speed.zoom;
  13804. this.start(); // if there is no node movement, the calculation wont be done
  13805. this._preventDefault(event);
  13806. if (this.navigationDivs) {
  13807. this.navigationDivs['zoomIn'].className += " active";
  13808. }
  13809. },
  13810. /**
  13811. * Zoom out
  13812. * @private
  13813. */
  13814. _zoomOut : function() {
  13815. this.zoomIncrement = -this.constants.keyboard.speed.zoom;
  13816. this.start(); // if there is no node movement, the calculation wont be done
  13817. this._preventDefault(event);
  13818. if (this.navigationDivs) {
  13819. this.navigationDivs['zoomOut'].className += " active";
  13820. }
  13821. },
  13822. /**
  13823. * Stop zooming and unhighlight the zoom controls
  13824. * @private
  13825. */
  13826. _stopZoom : function() {
  13827. this.zoomIncrement = 0;
  13828. if (this.navigationDivs) {
  13829. this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active","");
  13830. this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active","");
  13831. }
  13832. },
  13833. /**
  13834. * Stop moving in the Y direction and unHighlight the up and down
  13835. * @private
  13836. */
  13837. _yStopMoving : function() {
  13838. this.yIncrement = 0;
  13839. if (this.navigationDivs) {
  13840. this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active","");
  13841. this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active","");
  13842. }
  13843. },
  13844. /**
  13845. * Stop moving in the X direction and unHighlight left and right.
  13846. * @private
  13847. */
  13848. _xStopMoving : function() {
  13849. this.xIncrement = 0;
  13850. if (this.navigationDivs) {
  13851. this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active","");
  13852. this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active","");
  13853. }
  13854. }
  13855. };
  13856. /**
  13857. * Created by Alex on 2/10/14.
  13858. */
  13859. var graphMixinLoaders = {
  13860. /**
  13861. * Load a mixin into the graph object
  13862. *
  13863. * @param {Object} sourceVariable | this object has to contain functions.
  13864. * @private
  13865. */
  13866. _loadMixin : function(sourceVariable) {
  13867. for (var mixinFunction in sourceVariable) {
  13868. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13869. Graph.prototype[mixinFunction] = sourceVariable[mixinFunction];
  13870. }
  13871. }
  13872. },
  13873. /**
  13874. * removes a mixin from the graph object.
  13875. *
  13876. * @param {Object} sourceVariable | this object has to contain functions.
  13877. * @private
  13878. */
  13879. _clearMixin : function(sourceVariable) {
  13880. for (var mixinFunction in sourceVariable) {
  13881. if (sourceVariable.hasOwnProperty(mixinFunction)) {
  13882. Graph.prototype[mixinFunction] = undefined;
  13883. }
  13884. }
  13885. },
  13886. /**
  13887. * Mixin the physics system and initialize the parameters required.
  13888. *
  13889. * @private
  13890. */
  13891. _loadPhysicsSystem : function() {
  13892. this._loadMixin(physicsMixin);
  13893. this._loadSelectedForceSolver();
  13894. if (this.constants.configurePhysics == true) {
  13895. this._loadPhysicsConfiguration();
  13896. }
  13897. },
  13898. /**
  13899. * Mixin the cluster system and initialize the parameters required.
  13900. *
  13901. * @private
  13902. */
  13903. _loadClusterSystem : function() {
  13904. this.clusterSession = 0;
  13905. this.hubThreshold = 5;
  13906. this._loadMixin(ClusterMixin);
  13907. },
  13908. /**
  13909. * Mixin the sector system and initialize the parameters required
  13910. *
  13911. * @private
  13912. */
  13913. _loadSectorSystem : function() {
  13914. this.sectors = { },
  13915. this.activeSector = ["default"];
  13916. this.sectors["active"] = { },
  13917. this.sectors["active"]["default"] = {"nodes":{},
  13918. "edges":{},
  13919. "nodeIndices":[],
  13920. "formationScale": 1.0,
  13921. "drawingNode": undefined };
  13922. this.sectors["frozen"] = {},
  13923. this.sectors["support"] = {"nodes":{},
  13924. "edges":{},
  13925. "nodeIndices":[],
  13926. "formationScale": 1.0,
  13927. "drawingNode": undefined };
  13928. this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
  13929. this._loadMixin(SectorMixin);
  13930. },
  13931. /**
  13932. * Mixin the selection system and initialize the parameters required
  13933. *
  13934. * @private
  13935. */
  13936. _loadSelectionSystem : function() {
  13937. this.selectionObj = {nodes:{},edges:{}};
  13938. this._loadMixin(SelectionMixin);
  13939. },
  13940. /**
  13941. * Mixin the navigationUI (User Interface) system and initialize the parameters required
  13942. *
  13943. * @private
  13944. */
  13945. _loadManipulationSystem : function() {
  13946. // reset global variables -- these are used by the selection of nodes and edges.
  13947. this.blockConnectingEdgeSelection = false;
  13948. this.forceAppendSelection = false
  13949. if (this.constants.dataManipulation.enabled == true) {
  13950. // load the manipulator HTML elements. All styling done in css.
  13951. if (this.manipulationDiv === undefined) {
  13952. this.manipulationDiv = document.createElement('div');
  13953. this.manipulationDiv.className = 'graph-manipulationDiv';
  13954. this.manipulationDiv.id = 'graph-manipulationDiv';
  13955. if (this.editMode == true) {
  13956. this.manipulationDiv.style.display = "block";
  13957. }
  13958. else {
  13959. this.manipulationDiv.style.display = "none";
  13960. }
  13961. this.containerElement.insertBefore(this.manipulationDiv, this.frame);
  13962. }
  13963. if (this.editModeDiv === undefined) {
  13964. this.editModeDiv = document.createElement('div');
  13965. this.editModeDiv.className = 'graph-manipulation-editMode';
  13966. this.editModeDiv.id = 'graph-manipulation-editMode';
  13967. if (this.editMode == true) {
  13968. this.editModeDiv.style.display = "none";
  13969. }
  13970. else {
  13971. this.editModeDiv.style.display = "block";
  13972. }
  13973. this.containerElement.insertBefore(this.editModeDiv, this.frame);
  13974. }
  13975. if (this.closeDiv === undefined) {
  13976. this.closeDiv = document.createElement('div');
  13977. this.closeDiv.className = 'graph-manipulation-closeDiv';
  13978. this.closeDiv.id = 'graph-manipulation-closeDiv';
  13979. this.closeDiv.style.display = this.manipulationDiv.style.display;
  13980. this.containerElement.insertBefore(this.closeDiv, this.frame);
  13981. }
  13982. // load the manipulation functions
  13983. this._loadMixin(manipulationMixin);
  13984. // create the manipulator toolbar
  13985. this._createManipulatorBar();
  13986. }
  13987. else {
  13988. if (this.manipulationDiv !== undefined) {
  13989. // removes all the bindings and overloads
  13990. this._createManipulatorBar();
  13991. // remove the manipulation divs
  13992. this.containerElement.removeChild(this.manipulationDiv);
  13993. this.containerElement.removeChild(this.editModeDiv);
  13994. this.containerElement.removeChild(this.closeDiv);
  13995. this.manipulationDiv = undefined;
  13996. this.editModeDiv = undefined;
  13997. this.closeDiv = undefined;
  13998. // remove the mixin functions
  13999. this._clearMixin(manipulationMixin);
  14000. }
  14001. }
  14002. },
  14003. /**
  14004. * Mixin the navigation (User Interface) system and initialize the parameters required
  14005. *
  14006. * @private
  14007. */
  14008. _loadNavigationControls : function() {
  14009. this._loadMixin(NavigationMixin);
  14010. // the clean function removes the button divs, this is done to remove the bindings.
  14011. this._cleanNavigation();
  14012. if (this.constants.navigation.enabled == true) {
  14013. this._loadNavigationElements();
  14014. }
  14015. },
  14016. /**
  14017. * Mixin the hierarchical layout system.
  14018. *
  14019. * @private
  14020. */
  14021. _loadHierarchySystem : function() {
  14022. this._loadMixin(HierarchicalLayoutMixin);
  14023. }
  14024. }
  14025. /**
  14026. * @constructor Graph
  14027. * Create a graph visualization, displaying nodes and edges.
  14028. *
  14029. * @param {Element} container The DOM element in which the Graph will
  14030. * be created. Normally a div element.
  14031. * @param {Object} data An object containing parameters
  14032. * {Array} nodes
  14033. * {Array} edges
  14034. * @param {Object} options Options
  14035. */
  14036. function Graph (container, data, options) {
  14037. this._initializeMixinLoaders();
  14038. // create variables and set default values
  14039. this.containerElement = container;
  14040. this.width = '100%';
  14041. this.height = '100%';
  14042. // render and calculation settings
  14043. this.renderRefreshRate = 60; // hz (fps)
  14044. this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on
  14045. this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame
  14046. this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step.
  14047. this.physicsDiscreteStepsize = 0.65; // discrete stepsize of the simulation
  14048. this.stabilize = true; // stabilize before displaying the graph
  14049. this.selectable = true;
  14050. this.initializing = true;
  14051. // these functions are triggered when the dataset is edited
  14052. this.triggerFunctions = {add:null,edit:null,connect:null,delete:null};
  14053. // set constant values
  14054. this.constants = {
  14055. nodes: {
  14056. radiusMin: 5,
  14057. radiusMax: 20,
  14058. radius: 5,
  14059. shape: 'ellipse',
  14060. image: undefined,
  14061. widthMin: 16, // px
  14062. widthMax: 64, // px
  14063. fixed: false,
  14064. fontColor: 'black',
  14065. fontSize: 14, // px
  14066. fontFace: 'verdana',
  14067. level: -1,
  14068. color: {
  14069. border: '#2B7CE9',
  14070. background: '#97C2FC',
  14071. highlight: {
  14072. border: '#2B7CE9',
  14073. background: '#D2E5FF'
  14074. }
  14075. },
  14076. borderColor: '#2B7CE9',
  14077. backgroundColor: '#97C2FC',
  14078. highlightColor: '#D2E5FF',
  14079. group: undefined
  14080. },
  14081. edges: {
  14082. widthMin: 1,
  14083. widthMax: 15,
  14084. width: 1,
  14085. style: 'line',
  14086. color: {
  14087. color:'#848484',
  14088. highlight:'#848484'
  14089. },
  14090. fontColor: '#343434',
  14091. fontSize: 14, // px
  14092. fontFace: 'arial',
  14093. fontFill: 'white',
  14094. dash: {
  14095. length: 10,
  14096. gap: 5,
  14097. altLength: undefined
  14098. }
  14099. },
  14100. configurePhysics:false,
  14101. physics: {
  14102. barnesHut: {
  14103. enabled: true,
  14104. theta: 1 / 0.6, // inverted to save time during calculation
  14105. gravitationalConstant: -2000,
  14106. centralGravity: 0.3,
  14107. springLength: 95,
  14108. springConstant: 0.04,
  14109. damping: 0.09
  14110. },
  14111. repulsion: {
  14112. centralGravity: 0.1,
  14113. springLength: 200,
  14114. springConstant: 0.05,
  14115. nodeDistance: 100,
  14116. damping: 0.09
  14117. },
  14118. hierarchicalRepulsion: {
  14119. enabled: false,
  14120. centralGravity: 0.0,
  14121. springLength: 100,
  14122. springConstant: 0.01,
  14123. nodeDistance: 60,
  14124. damping: 0.09
  14125. },
  14126. damping: null,
  14127. centralGravity: null,
  14128. springLength: null,
  14129. springConstant: null
  14130. },
  14131. clustering: { // Per Node in Cluster = PNiC
  14132. enabled: false, // (Boolean) | global on/off switch for clustering.
  14133. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold.
  14134. 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
  14135. 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
  14136. chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains).
  14137. clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered.
  14138. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector.
  14139. 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.
  14140. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px).
  14141. maxFontSize: 1000,
  14142. forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster).
  14143. distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster).
  14144. edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength.
  14145. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster.
  14146. height: 1, // (px PNiC) | growth of the height per node in cluster.
  14147. radius: 1}, // (px PNiC) | growth of the radius per node in cluster.
  14148. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster.
  14149. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open.
  14150. clusterLevelDifference: 2
  14151. },
  14152. navigation: {
  14153. enabled: false
  14154. },
  14155. keyboard: {
  14156. enabled: false,
  14157. speed: {x: 10, y: 10, zoom: 0.02}
  14158. },
  14159. dataManipulation: {
  14160. enabled: false,
  14161. initiallyVisible: false
  14162. },
  14163. hierarchicalLayout: {
  14164. enabled:false,
  14165. levelSeparation: 150,
  14166. nodeSpacing: 100,
  14167. direction: "UD" // UD, DU, LR, RL
  14168. },
  14169. freezeForStabilization: false,
  14170. smoothCurves: true,
  14171. maxVelocity: 10,
  14172. minVelocity: 0.1, // px/s
  14173. stabilizationIterations: 1000, // maximum number of iteration to stabilize
  14174. labels:{
  14175. add:"Add Node",
  14176. edit:"Edit",
  14177. link:"Add Link",
  14178. delete:"Delete selected",
  14179. editNode:"Edit Node",
  14180. back:"Back",
  14181. addDescription:"Click in an empty space to place a new node.",
  14182. linkDescription:"Click on a node and drag the edge to another node to connect them.",
  14183. addError:"The function for add does not support two arguments (data,callback).",
  14184. linkError:"The function for connect does not support two arguments (data,callback).",
  14185. editError:"The function for edit does not support two arguments (data, callback).",
  14186. editBoundError:"No edit function has been bound to this button.",
  14187. deleteError:"The function for delete does not support two arguments (data, callback).",
  14188. deleteClusterError:"Clusters cannot be deleted."
  14189. },
  14190. tooltip: {
  14191. delay: 300,
  14192. fontColor: 'black',
  14193. fontSize: 14, // px
  14194. fontFace: 'verdana',
  14195. color: {
  14196. border: '#666',
  14197. background: '#FFFFC6'
  14198. }
  14199. }
  14200. };
  14201. this.editMode = this.constants.dataManipulation.initiallyVisible;
  14202. // Node variables
  14203. var graph = this;
  14204. this.groups = new Groups(); // object with groups
  14205. this.images = new Images(); // object with images
  14206. this.images.setOnloadCallback(function () {
  14207. graph._redraw();
  14208. });
  14209. // keyboard navigation variables
  14210. this.xIncrement = 0;
  14211. this.yIncrement = 0;
  14212. this.zoomIncrement = 0;
  14213. // loading all the mixins:
  14214. // load the force calculation functions, grouped under the physics system.
  14215. this._loadPhysicsSystem();
  14216. // create a frame and canvas
  14217. this._create();
  14218. // load the sector system. (mandatory, fully integrated with Graph)
  14219. this._loadSectorSystem();
  14220. // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it)
  14221. this._loadClusterSystem();
  14222. // load the selection system. (mandatory, required by Graph)
  14223. this._loadSelectionSystem();
  14224. // load the selection system. (mandatory, required by Graph)
  14225. this._loadHierarchySystem();
  14226. // apply options
  14227. this.setOptions(options);
  14228. // other vars
  14229. this.freezeSimulation = false;// freeze the simulation
  14230. this.cachedFunctions = {};
  14231. // containers for nodes and edges
  14232. this.calculationNodes = {};
  14233. this.calculationNodeIndices = [];
  14234. this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation
  14235. this.nodes = {}; // object with Node objects
  14236. this.edges = {}; // object with Edge objects
  14237. // position and scale variables and objects
  14238. this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw.
  14239. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  14240. this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw
  14241. this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action
  14242. this.scale = 1; // defining the global scale variable in the constructor
  14243. this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out
  14244. // datasets or dataviews
  14245. this.nodesData = null; // A DataSet or DataView
  14246. this.edgesData = null; // A DataSet or DataView
  14247. // create event listeners used to subscribe on the DataSets of the nodes and edges
  14248. this.nodesListeners = {
  14249. 'add': function (event, params) {
  14250. graph._addNodes(params.items);
  14251. graph.start();
  14252. },
  14253. 'update': function (event, params) {
  14254. graph._updateNodes(params.items);
  14255. graph.start();
  14256. },
  14257. 'remove': function (event, params) {
  14258. graph._removeNodes(params.items);
  14259. graph.start();
  14260. }
  14261. };
  14262. this.edgesListeners = {
  14263. 'add': function (event, params) {
  14264. graph._addEdges(params.items);
  14265. graph.start();
  14266. },
  14267. 'update': function (event, params) {
  14268. graph._updateEdges(params.items);
  14269. graph.start();
  14270. },
  14271. 'remove': function (event, params) {
  14272. graph._removeEdges(params.items);
  14273. graph.start();
  14274. }
  14275. };
  14276. // properties for the animation
  14277. this.moving = true;
  14278. this.timer = undefined; // Scheduling function. Is definded in this.start();
  14279. // load data (the disable start variable will be the same as the enabled clustering)
  14280. this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled);
  14281. // hierarchical layout
  14282. this.initializing = false;
  14283. if (this.constants.hierarchicalLayout.enabled == true) {
  14284. this._setupHierarchicalLayout();
  14285. }
  14286. else {
  14287. // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here.
  14288. if (this.stabilize == false) {
  14289. this.zoomExtent(true,this.constants.clustering.enabled);
  14290. }
  14291. }
  14292. // if clustering is disabled, the simulation will have started in the setData function
  14293. if (this.constants.clustering.enabled) {
  14294. this.startWithClustering();
  14295. }
  14296. }
  14297. // Extend Graph with an Emitter mixin
  14298. Emitter(Graph.prototype);
  14299. /**
  14300. * Get the script path where the vis.js library is located
  14301. *
  14302. * @returns {string | null} path Path or null when not found. Path does not
  14303. * end with a slash.
  14304. * @private
  14305. */
  14306. Graph.prototype._getScriptPath = function() {
  14307. var scripts = document.getElementsByTagName( 'script' );
  14308. // find script named vis.js or vis.min.js
  14309. for (var i = 0; i < scripts.length; i++) {
  14310. var src = scripts[i].src;
  14311. var match = src && /\/?vis(.min)?\.js$/.exec(src);
  14312. if (match) {
  14313. // return path without the script name
  14314. return src.substring(0, src.length - match[0].length);
  14315. }
  14316. }
  14317. return null;
  14318. };
  14319. /**
  14320. * Find the center position of the graph
  14321. * @private
  14322. */
  14323. Graph.prototype._getRange = function() {
  14324. var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
  14325. for (var nodeId in this.nodes) {
  14326. if (this.nodes.hasOwnProperty(nodeId)) {
  14327. node = this.nodes[nodeId];
  14328. if (minX > (node.x)) {minX = node.x;}
  14329. if (maxX < (node.x)) {maxX = node.x;}
  14330. if (minY > (node.y)) {minY = node.y;}
  14331. if (maxY < (node.y)) {maxY = node.y;}
  14332. }
  14333. }
  14334. if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) {
  14335. minY = 0, maxY = 0, minX = 0, maxX = 0;
  14336. }
  14337. return {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14338. };
  14339. /**
  14340. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14341. * @returns {{x: number, y: number}}
  14342. * @private
  14343. */
  14344. Graph.prototype._findCenter = function(range) {
  14345. return {x: (0.5 * (range.maxX + range.minX)),
  14346. y: (0.5 * (range.maxY + range.minY))};
  14347. };
  14348. /**
  14349. * center the graph
  14350. *
  14351. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  14352. */
  14353. Graph.prototype._centerGraph = function(range) {
  14354. var center = this._findCenter(range);
  14355. center.x *= this.scale;
  14356. center.y *= this.scale;
  14357. center.x -= 0.5 * this.frame.canvas.clientWidth;
  14358. center.y -= 0.5 * this.frame.canvas.clientHeight;
  14359. this._setTranslation(-center.x,-center.y); // set at 0,0
  14360. };
  14361. /**
  14362. * This function zooms out to fit all data on screen based on amount of nodes
  14363. *
  14364. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  14365. */
  14366. Graph.prototype.zoomExtent = function(initialZoom, disableStart) {
  14367. if (initialZoom === undefined) {
  14368. initialZoom = false;
  14369. }
  14370. if (disableStart === undefined) {
  14371. disableStart = false;
  14372. }
  14373. var range = this._getRange();
  14374. var zoomLevel;
  14375. if (initialZoom == true) {
  14376. var numberOfNodes = this.nodeIndices.length;
  14377. if (this.constants.smoothCurves == true) {
  14378. if (this.constants.clustering.enabled == true &&
  14379. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14380. 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.
  14381. }
  14382. else {
  14383. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14384. }
  14385. }
  14386. else {
  14387. if (this.constants.clustering.enabled == true &&
  14388. numberOfNodes >= this.constants.clustering.initialMaxNodes) {
  14389. 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.
  14390. }
  14391. else {
  14392. zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  14393. }
  14394. }
  14395. // correct for larger canvasses.
  14396. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600);
  14397. zoomLevel *= factor;
  14398. }
  14399. else {
  14400. var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1;
  14401. var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1;
  14402. var xZoomLevel = this.frame.canvas.clientWidth / xDistance;
  14403. var yZoomLevel = this.frame.canvas.clientHeight / yDistance;
  14404. zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel;
  14405. }
  14406. if (zoomLevel > 1.0) {
  14407. zoomLevel = 1.0;
  14408. }
  14409. this._setScale(zoomLevel);
  14410. this._centerGraph(range);
  14411. if (disableStart == false) {
  14412. this.moving = true;
  14413. this.start();
  14414. }
  14415. };
  14416. /**
  14417. * Update the this.nodeIndices with the most recent node index list
  14418. * @private
  14419. */
  14420. Graph.prototype._updateNodeIndexList = function() {
  14421. this._clearNodeIndexList();
  14422. for (var idx in this.nodes) {
  14423. if (this.nodes.hasOwnProperty(idx)) {
  14424. this.nodeIndices.push(idx);
  14425. }
  14426. }
  14427. };
  14428. /**
  14429. * Set nodes and edges, and optionally options as well.
  14430. *
  14431. * @param {Object} data Object containing parameters:
  14432. * {Array | DataSet | DataView} [nodes] Array with nodes
  14433. * {Array | DataSet | DataView} [edges] Array with edges
  14434. * {String} [dot] String containing data in DOT format
  14435. * {Options} [options] Object with options
  14436. * @param {Boolean} [disableStart] | optional: disable the calling of the start function.
  14437. */
  14438. Graph.prototype.setData = function(data, disableStart) {
  14439. if (disableStart === undefined) {
  14440. disableStart = false;
  14441. }
  14442. if (data && data.dot && (data.nodes || data.edges)) {
  14443. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  14444. ' parameter pair "nodes" and "edges", but not both.');
  14445. }
  14446. // set options
  14447. this.setOptions(data && data.options);
  14448. // set all data
  14449. if (data && data.dot) {
  14450. // parse DOT file
  14451. if(data && data.dot) {
  14452. var dotData = vis.util.DOTToGraph(data.dot);
  14453. this.setData(dotData);
  14454. return;
  14455. }
  14456. }
  14457. else {
  14458. this._setNodes(data && data.nodes);
  14459. this._setEdges(data && data.edges);
  14460. }
  14461. this._putDataInSector();
  14462. if (!disableStart) {
  14463. // find a stable position or start animating to a stable position
  14464. if (this.stabilize) {
  14465. this._stabilize();
  14466. }
  14467. this.start();
  14468. }
  14469. };
  14470. /**
  14471. * Set options
  14472. * @param {Object} options
  14473. */
  14474. Graph.prototype.setOptions = function (options) {
  14475. if (options) {
  14476. var prop;
  14477. // retrieve parameter values
  14478. if (options.width !== undefined) {this.width = options.width;}
  14479. if (options.height !== undefined) {this.height = options.height;}
  14480. if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
  14481. if (options.selectable !== undefined) {this.selectable = options.selectable;}
  14482. if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
  14483. if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;}
  14484. if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
  14485. if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
  14486. if (options.labels !== undefined) {
  14487. for (prop in options.labels) {
  14488. if (options.labels.hasOwnProperty(prop)) {
  14489. this.constants.labels[prop] = options.labels[prop];
  14490. }
  14491. }
  14492. }
  14493. if (options.onAdd) {
  14494. this.triggerFunctions.add = options.onAdd;
  14495. }
  14496. if (options.onEdit) {
  14497. this.triggerFunctions.edit = options.onEdit;
  14498. }
  14499. if (options.onConnect) {
  14500. this.triggerFunctions.connect = options.onConnect;
  14501. }
  14502. if (options.onDelete) {
  14503. this.triggerFunctions.delete = options.onDelete;
  14504. }
  14505. if (options.physics) {
  14506. if (options.physics.barnesHut) {
  14507. this.constants.physics.barnesHut.enabled = true;
  14508. for (prop in options.physics.barnesHut) {
  14509. if (options.physics.barnesHut.hasOwnProperty(prop)) {
  14510. this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop];
  14511. }
  14512. }
  14513. }
  14514. if (options.physics.repulsion) {
  14515. this.constants.physics.barnesHut.enabled = false;
  14516. for (prop in options.physics.repulsion) {
  14517. if (options.physics.repulsion.hasOwnProperty(prop)) {
  14518. this.constants.physics.repulsion[prop] = options.physics.repulsion[prop];
  14519. }
  14520. }
  14521. }
  14522. }
  14523. if (options.hierarchicalLayout) {
  14524. this.constants.hierarchicalLayout.enabled = true;
  14525. for (prop in options.hierarchicalLayout) {
  14526. if (options.hierarchicalLayout.hasOwnProperty(prop)) {
  14527. this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop];
  14528. }
  14529. }
  14530. }
  14531. else if (options.hierarchicalLayout !== undefined) {
  14532. this.constants.hierarchicalLayout.enabled = false;
  14533. }
  14534. if (options.clustering) {
  14535. this.constants.clustering.enabled = true;
  14536. for (prop in options.clustering) {
  14537. if (options.clustering.hasOwnProperty(prop)) {
  14538. this.constants.clustering[prop] = options.clustering[prop];
  14539. }
  14540. }
  14541. }
  14542. else if (options.clustering !== undefined) {
  14543. this.constants.clustering.enabled = false;
  14544. }
  14545. if (options.navigation) {
  14546. this.constants.navigation.enabled = true;
  14547. for (prop in options.navigation) {
  14548. if (options.navigation.hasOwnProperty(prop)) {
  14549. this.constants.navigation[prop] = options.navigation[prop];
  14550. }
  14551. }
  14552. }
  14553. else if (options.navigation !== undefined) {
  14554. this.constants.navigation.enabled = false;
  14555. }
  14556. if (options.keyboard) {
  14557. this.constants.keyboard.enabled = true;
  14558. for (prop in options.keyboard) {
  14559. if (options.keyboard.hasOwnProperty(prop)) {
  14560. this.constants.keyboard[prop] = options.keyboard[prop];
  14561. }
  14562. }
  14563. }
  14564. else if (options.keyboard !== undefined) {
  14565. this.constants.keyboard.enabled = false;
  14566. }
  14567. if (options.dataManipulation) {
  14568. this.constants.dataManipulation.enabled = true;
  14569. for (prop in options.dataManipulation) {
  14570. if (options.dataManipulation.hasOwnProperty(prop)) {
  14571. this.constants.dataManipulation[prop] = options.dataManipulation[prop];
  14572. }
  14573. }
  14574. }
  14575. else if (options.dataManipulation !== undefined) {
  14576. this.constants.dataManipulation.enabled = false;
  14577. }
  14578. // TODO: work out these options and document them
  14579. if (options.edges) {
  14580. for (prop in options.edges) {
  14581. if (options.edges.hasOwnProperty(prop)) {
  14582. if (typeof options.edges[prop] != "object") {
  14583. this.constants.edges[prop] = options.edges[prop];
  14584. }
  14585. }
  14586. }
  14587. if (options.edges.color !== undefined) {
  14588. if (util.isString(options.edges.color)) {
  14589. this.constants.edges.color = {};
  14590. this.constants.edges.color.color = options.edges.color;
  14591. this.constants.edges.color.highlight = options.edges.color;
  14592. }
  14593. else {
  14594. if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;}
  14595. if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;}
  14596. }
  14597. }
  14598. if (!options.edges.fontColor) {
  14599. if (options.edges.color !== undefined) {
  14600. if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;}
  14601. else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;}
  14602. }
  14603. }
  14604. // Added to support dashed lines
  14605. // David Jordan
  14606. // 2012-08-08
  14607. if (options.edges.dash) {
  14608. if (options.edges.dash.length !== undefined) {
  14609. this.constants.edges.dash.length = options.edges.dash.length;
  14610. }
  14611. if (options.edges.dash.gap !== undefined) {
  14612. this.constants.edges.dash.gap = options.edges.dash.gap;
  14613. }
  14614. if (options.edges.dash.altLength !== undefined) {
  14615. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  14616. }
  14617. }
  14618. }
  14619. if (options.nodes) {
  14620. for (prop in options.nodes) {
  14621. if (options.nodes.hasOwnProperty(prop)) {
  14622. this.constants.nodes[prop] = options.nodes[prop];
  14623. }
  14624. }
  14625. if (options.nodes.color) {
  14626. this.constants.nodes.color = util.parseColor(options.nodes.color);
  14627. }
  14628. /*
  14629. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  14630. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  14631. */
  14632. }
  14633. if (options.groups) {
  14634. for (var groupname in options.groups) {
  14635. if (options.groups.hasOwnProperty(groupname)) {
  14636. var group = options.groups[groupname];
  14637. this.groups.add(groupname, group);
  14638. }
  14639. }
  14640. }
  14641. if (options.tooltip) {
  14642. for (prop in options.tooltip) {
  14643. if (options.tooltip.hasOwnProperty(prop)) {
  14644. this.constants.tooltip[prop] = options.tooltip[prop];
  14645. }
  14646. }
  14647. if (options.tooltip.color) {
  14648. this.constants.tooltip.color = util.parseColor(options.tooltip.color);
  14649. }
  14650. }
  14651. }
  14652. // (Re)loading the mixins that can be enabled or disabled in the options.
  14653. // load the force calculation functions, grouped under the physics system.
  14654. this._loadPhysicsSystem();
  14655. // load the navigation system.
  14656. this._loadNavigationControls();
  14657. // load the data manipulation system
  14658. this._loadManipulationSystem();
  14659. // configure the smooth curves
  14660. this._configureSmoothCurves();
  14661. // bind keys. If disabled, this will not do anything;
  14662. this._createKeyBinds();
  14663. this.setSize(this.width, this.height);
  14664. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  14665. this._setScale(1);
  14666. this._redraw();
  14667. };
  14668. /**
  14669. * Create the main frame for the Graph.
  14670. * This function is executed once when a Graph object is created. The frame
  14671. * contains a canvas, and this canvas contains all objects like the axis and
  14672. * nodes.
  14673. * @private
  14674. */
  14675. Graph.prototype._create = function () {
  14676. // remove all elements from the container element.
  14677. while (this.containerElement.hasChildNodes()) {
  14678. this.containerElement.removeChild(this.containerElement.firstChild);
  14679. }
  14680. this.frame = document.createElement('div');
  14681. this.frame.className = 'graph-frame';
  14682. this.frame.style.position = 'relative';
  14683. this.frame.style.overflow = 'hidden';
  14684. this.frame.style.zIndex = "1";
  14685. // create the graph canvas (HTML canvas element)
  14686. this.frame.canvas = document.createElement( 'canvas' );
  14687. this.frame.canvas.style.position = 'relative';
  14688. this.frame.appendChild(this.frame.canvas);
  14689. if (!this.frame.canvas.getContext) {
  14690. var noCanvas = document.createElement( 'DIV' );
  14691. noCanvas.style.color = 'red';
  14692. noCanvas.style.fontWeight = 'bold' ;
  14693. noCanvas.style.padding = '10px';
  14694. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  14695. this.frame.canvas.appendChild(noCanvas);
  14696. }
  14697. var me = this;
  14698. this.drag = {};
  14699. this.pinch = {};
  14700. this.hammer = Hammer(this.frame.canvas, {
  14701. prevent_default: true
  14702. });
  14703. this.hammer.on('tap', me._onTap.bind(me) );
  14704. this.hammer.on('doubletap', me._onDoubleTap.bind(me) );
  14705. this.hammer.on('hold', me._onHold.bind(me) );
  14706. this.hammer.on('pinch', me._onPinch.bind(me) );
  14707. this.hammer.on('touch', me._onTouch.bind(me) );
  14708. this.hammer.on('dragstart', me._onDragStart.bind(me) );
  14709. this.hammer.on('drag', me._onDrag.bind(me) );
  14710. this.hammer.on('dragend', me._onDragEnd.bind(me) );
  14711. this.hammer.on('release', me._onRelease.bind(me) );
  14712. this.hammer.on('mousewheel',me._onMouseWheel.bind(me) );
  14713. this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF
  14714. this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) );
  14715. // add the frame to the container element
  14716. this.containerElement.appendChild(this.frame);
  14717. };
  14718. /**
  14719. * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin
  14720. * @private
  14721. */
  14722. Graph.prototype._createKeyBinds = function() {
  14723. var me = this;
  14724. this.mousetrap = mousetrap;
  14725. this.mousetrap.reset();
  14726. if (this.constants.keyboard.enabled == true) {
  14727. this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown");
  14728. this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup");
  14729. this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown");
  14730. this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup");
  14731. this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown");
  14732. this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup");
  14733. this.mousetrap.bind("right",this._moveRight.bind(me), "keydown");
  14734. this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup");
  14735. this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown");
  14736. this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup");
  14737. this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown");
  14738. this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup");
  14739. this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown");
  14740. this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup");
  14741. this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown");
  14742. this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup");
  14743. this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown");
  14744. this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup");
  14745. this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown");
  14746. this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup");
  14747. }
  14748. if (this.constants.dataManipulation.enabled == true) {
  14749. this.mousetrap.bind("escape",this._createManipulatorBar.bind(me));
  14750. this.mousetrap.bind("del",this._deleteSelected.bind(me));
  14751. }
  14752. };
  14753. /**
  14754. * Get the pointer location from a touch location
  14755. * @param {{pageX: Number, pageY: Number}} touch
  14756. * @return {{x: Number, y: Number}} pointer
  14757. * @private
  14758. */
  14759. Graph.prototype._getPointer = function (touch) {
  14760. return {
  14761. x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
  14762. y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
  14763. };
  14764. };
  14765. /**
  14766. * On start of a touch gesture, store the pointer
  14767. * @param event
  14768. * @private
  14769. */
  14770. Graph.prototype._onTouch = function (event) {
  14771. this.drag.pointer = this._getPointer(event.gesture.center);
  14772. this.drag.pinched = false;
  14773. this.pinch.scale = this._getScale();
  14774. this._handleTouch(this.drag.pointer);
  14775. };
  14776. /**
  14777. * handle drag start event
  14778. * @private
  14779. */
  14780. Graph.prototype._onDragStart = function () {
  14781. this._handleDragStart();
  14782. };
  14783. /**
  14784. * This function is called by _onDragStart.
  14785. * It is separated out because we can then overload it for the datamanipulation system.
  14786. *
  14787. * @private
  14788. */
  14789. Graph.prototype._handleDragStart = function() {
  14790. var drag = this.drag;
  14791. var node = this._getNodeAt(drag.pointer);
  14792. // note: drag.pointer is set in _onTouch to get the initial touch location
  14793. drag.dragging = true;
  14794. drag.selection = [];
  14795. drag.translation = this._getTranslation();
  14796. drag.nodeId = null;
  14797. if (node != null) {
  14798. drag.nodeId = node.id;
  14799. // select the clicked node if not yet selected
  14800. if (!node.isSelected()) {
  14801. this._selectObject(node,false);
  14802. }
  14803. // create an array with the selected nodes and their original location and status
  14804. for (var objectId in this.selectionObj.nodes) {
  14805. if (this.selectionObj.nodes.hasOwnProperty(objectId)) {
  14806. var object = this.selectionObj.nodes[objectId];
  14807. var s = {
  14808. id: object.id,
  14809. node: object,
  14810. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  14811. x: object.x,
  14812. y: object.y,
  14813. xFixed: object.xFixed,
  14814. yFixed: object.yFixed
  14815. };
  14816. object.xFixed = true;
  14817. object.yFixed = true;
  14818. drag.selection.push(s);
  14819. }
  14820. }
  14821. }
  14822. };
  14823. /**
  14824. * handle drag event
  14825. * @private
  14826. */
  14827. Graph.prototype._onDrag = function (event) {
  14828. this._handleOnDrag(event)
  14829. };
  14830. /**
  14831. * This function is called by _onDrag.
  14832. * It is separated out because we can then overload it for the datamanipulation system.
  14833. *
  14834. * @private
  14835. */
  14836. Graph.prototype._handleOnDrag = function(event) {
  14837. if (this.drag.pinched) {
  14838. return;
  14839. }
  14840. var pointer = this._getPointer(event.gesture.center);
  14841. var me = this,
  14842. drag = this.drag,
  14843. selection = drag.selection;
  14844. if (selection && selection.length) {
  14845. // calculate delta's and new location
  14846. var deltaX = pointer.x - drag.pointer.x,
  14847. deltaY = pointer.y - drag.pointer.y;
  14848. // update position of all selected nodes
  14849. selection.forEach(function (s) {
  14850. var node = s.node;
  14851. if (!s.xFixed) {
  14852. node.x = me._canvasToX(me._xToCanvas(s.x) + deltaX);
  14853. }
  14854. if (!s.yFixed) {
  14855. node.y = me._canvasToY(me._yToCanvas(s.y) + deltaY);
  14856. }
  14857. });
  14858. // start _animationStep if not yet running
  14859. if (!this.moving) {
  14860. this.moving = true;
  14861. this.start();
  14862. }
  14863. }
  14864. else {
  14865. // move the graph
  14866. var diffX = pointer.x - this.drag.pointer.x;
  14867. var diffY = pointer.y - this.drag.pointer.y;
  14868. this._setTranslation(
  14869. this.drag.translation.x + diffX,
  14870. this.drag.translation.y + diffY);
  14871. this._redraw();
  14872. this.moved = true;
  14873. }
  14874. };
  14875. /**
  14876. * handle drag start event
  14877. * @private
  14878. */
  14879. Graph.prototype._onDragEnd = function () {
  14880. this.drag.dragging = false;
  14881. var selection = this.drag.selection;
  14882. if (selection) {
  14883. selection.forEach(function (s) {
  14884. // restore original xFixed and yFixed
  14885. s.node.xFixed = s.xFixed;
  14886. s.node.yFixed = s.yFixed;
  14887. });
  14888. }
  14889. };
  14890. /**
  14891. * handle tap/click event: select/unselect a node
  14892. * @private
  14893. */
  14894. Graph.prototype._onTap = function (event) {
  14895. var pointer = this._getPointer(event.gesture.center);
  14896. this.pointerPosition = pointer;
  14897. this._handleTap(pointer);
  14898. };
  14899. /**
  14900. * handle doubletap event
  14901. * @private
  14902. */
  14903. Graph.prototype._onDoubleTap = function (event) {
  14904. var pointer = this._getPointer(event.gesture.center);
  14905. this._handleDoubleTap(pointer);
  14906. };
  14907. /**
  14908. * handle long tap event: multi select nodes
  14909. * @private
  14910. */
  14911. Graph.prototype._onHold = function (event) {
  14912. var pointer = this._getPointer(event.gesture.center);
  14913. this.pointerPosition = pointer;
  14914. this._handleOnHold(pointer);
  14915. };
  14916. /**
  14917. * handle the release of the screen
  14918. *
  14919. * @private
  14920. */
  14921. Graph.prototype._onRelease = function (event) {
  14922. var pointer = this._getPointer(event.gesture.center);
  14923. this._handleOnRelease(pointer);
  14924. };
  14925. /**
  14926. * Handle pinch event
  14927. * @param event
  14928. * @private
  14929. */
  14930. Graph.prototype._onPinch = function (event) {
  14931. var pointer = this._getPointer(event.gesture.center);
  14932. this.drag.pinched = true;
  14933. if (!('scale' in this.pinch)) {
  14934. this.pinch.scale = 1;
  14935. }
  14936. // TODO: enabled moving while pinching?
  14937. var scale = this.pinch.scale * event.gesture.scale;
  14938. this._zoom(scale, pointer)
  14939. };
  14940. /**
  14941. * Zoom the graph in or out
  14942. * @param {Number} scale a number around 1, and between 0.01 and 10
  14943. * @param {{x: Number, y: Number}} pointer Position on screen
  14944. * @return {Number} appliedScale scale is limited within the boundaries
  14945. * @private
  14946. */
  14947. Graph.prototype._zoom = function(scale, pointer) {
  14948. var scaleOld = this._getScale();
  14949. if (scale < 0.00001) {
  14950. scale = 0.00001;
  14951. }
  14952. if (scale > 10) {
  14953. scale = 10;
  14954. }
  14955. // + this.frame.canvas.clientHeight / 2
  14956. var translation = this._getTranslation();
  14957. var scaleFrac = scale / scaleOld;
  14958. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  14959. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  14960. this.areaCenter = {"x" : this._canvasToX(pointer.x),
  14961. "y" : this._canvasToY(pointer.y)};
  14962. this._setScale(scale);
  14963. this._setTranslation(tx, ty);
  14964. this.updateClustersDefault();
  14965. this._redraw();
  14966. return scale;
  14967. };
  14968. /**
  14969. * Event handler for mouse wheel event, used to zoom the timeline
  14970. * See http://adomas.org/javascript-mouse-wheel/
  14971. * https://github.com/EightMedia/hammer.js/issues/256
  14972. * @param {MouseEvent} event
  14973. * @private
  14974. */
  14975. Graph.prototype._onMouseWheel = function(event) {
  14976. // retrieve delta
  14977. var delta = 0;
  14978. if (event.wheelDelta) { /* IE/Opera. */
  14979. delta = event.wheelDelta/120;
  14980. } else if (event.detail) { /* Mozilla case. */
  14981. // In Mozilla, sign of delta is different than in IE.
  14982. // Also, delta is multiple of 3.
  14983. delta = -event.detail/3;
  14984. }
  14985. // If delta is nonzero, handle it.
  14986. // Basically, delta is now positive if wheel was scrolled up,
  14987. // and negative, if wheel was scrolled down.
  14988. if (delta) {
  14989. // calculate the new scale
  14990. var scale = this._getScale();
  14991. var zoom = delta / 10;
  14992. if (delta < 0) {
  14993. zoom = zoom / (1 - zoom);
  14994. }
  14995. scale *= (1 + zoom);
  14996. // calculate the pointer location
  14997. var gesture = util.fakeGesture(this, event);
  14998. var pointer = this._getPointer(gesture.center);
  14999. // apply the new scale
  15000. this._zoom(scale, pointer);
  15001. }
  15002. // Prevent default actions caused by mouse wheel.
  15003. event.preventDefault();
  15004. };
  15005. /**
  15006. * Mouse move handler for checking whether the title moves over a node with a title.
  15007. * @param {Event} event
  15008. * @private
  15009. */
  15010. Graph.prototype._onMouseMoveTitle = function (event) {
  15011. var gesture = util.fakeGesture(this, event);
  15012. var pointer = this._getPointer(gesture.center);
  15013. // check if the previously selected node is still selected
  15014. if (this.popupNode) {
  15015. this._checkHidePopup(pointer);
  15016. }
  15017. // start a timeout that will check if the mouse is positioned above
  15018. // an element
  15019. var me = this;
  15020. var checkShow = function() {
  15021. me._checkShowPopup(pointer);
  15022. };
  15023. if (this.popupTimer) {
  15024. clearInterval(this.popupTimer); // stop any running calculationTimer
  15025. }
  15026. if (!this.drag.dragging) {
  15027. this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay);
  15028. }
  15029. };
  15030. /**
  15031. * Check if there is an element on the given position in the graph
  15032. * (a node or edge). If so, and if this element has a title,
  15033. * show a popup window with its title.
  15034. *
  15035. * @param {{x:Number, y:Number}} pointer
  15036. * @private
  15037. */
  15038. Graph.prototype._checkShowPopup = function (pointer) {
  15039. var obj = {
  15040. left: this._canvasToX(pointer.x),
  15041. top: this._canvasToY(pointer.y),
  15042. right: this._canvasToX(pointer.x),
  15043. bottom: this._canvasToY(pointer.y)
  15044. };
  15045. var id;
  15046. var lastPopupNode = this.popupNode;
  15047. if (this.popupNode == undefined) {
  15048. // search the nodes for overlap, select the top one in case of multiple nodes
  15049. var nodes = this.nodes;
  15050. for (id in nodes) {
  15051. if (nodes.hasOwnProperty(id)) {
  15052. var node = nodes[id];
  15053. if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) {
  15054. this.popupNode = node;
  15055. break;
  15056. }
  15057. }
  15058. }
  15059. }
  15060. if (this.popupNode === undefined) {
  15061. // search the edges for overlap
  15062. var edges = this.edges;
  15063. for (id in edges) {
  15064. if (edges.hasOwnProperty(id)) {
  15065. var edge = edges[id];
  15066. if (edge.connected && (edge.getTitle() !== undefined) &&
  15067. edge.isOverlappingWith(obj)) {
  15068. this.popupNode = edge;
  15069. break;
  15070. }
  15071. }
  15072. }
  15073. }
  15074. if (this.popupNode) {
  15075. // show popup message window
  15076. if (this.popupNode != lastPopupNode) {
  15077. var me = this;
  15078. if (!me.popup) {
  15079. me.popup = new Popup(me.frame, me.constants.tooltip);
  15080. }
  15081. // adjust a small offset such that the mouse cursor is located in the
  15082. // bottom left location of the popup, and you can easily move over the
  15083. // popup area
  15084. me.popup.setPosition(pointer.x - 3, pointer.y - 3);
  15085. me.popup.setText(me.popupNode.getTitle());
  15086. me.popup.show();
  15087. }
  15088. }
  15089. else {
  15090. if (this.popup) {
  15091. this.popup.hide();
  15092. }
  15093. }
  15094. };
  15095. /**
  15096. * Check if the popup must be hided, which is the case when the mouse is no
  15097. * longer hovering on the object
  15098. * @param {{x:Number, y:Number}} pointer
  15099. * @private
  15100. */
  15101. Graph.prototype._checkHidePopup = function (pointer) {
  15102. if (!this.popupNode || !this._getNodeAt(pointer) ) {
  15103. this.popupNode = undefined;
  15104. if (this.popup) {
  15105. this.popup.hide();
  15106. }
  15107. }
  15108. };
  15109. /**
  15110. * Set a new size for the graph
  15111. * @param {string} width Width in pixels or percentage (for example '800px'
  15112. * or '50%')
  15113. * @param {string} height Height in pixels or percentage (for example '400px'
  15114. * or '30%')
  15115. */
  15116. Graph.prototype.setSize = function(width, height) {
  15117. this.frame.style.width = width;
  15118. this.frame.style.height = height;
  15119. this.frame.canvas.style.width = '100%';
  15120. this.frame.canvas.style.height = '100%';
  15121. this.frame.canvas.width = this.frame.canvas.clientWidth;
  15122. this.frame.canvas.height = this.frame.canvas.clientHeight;
  15123. if (this.manipulationDiv !== undefined) {
  15124. this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px";
  15125. }
  15126. if (this.navigationDivs !== undefined) {
  15127. if (this.navigationDivs['wrapper'] !== undefined) {
  15128. this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
  15129. this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
  15130. }
  15131. }
  15132. this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height});
  15133. };
  15134. /**
  15135. * Set a data set with nodes for the graph
  15136. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  15137. * @private
  15138. */
  15139. Graph.prototype._setNodes = function(nodes) {
  15140. var oldNodesData = this.nodesData;
  15141. if (nodes instanceof DataSet || nodes instanceof DataView) {
  15142. this.nodesData = nodes;
  15143. }
  15144. else if (nodes instanceof Array) {
  15145. this.nodesData = new DataSet();
  15146. this.nodesData.add(nodes);
  15147. }
  15148. else if (!nodes) {
  15149. this.nodesData = new DataSet();
  15150. }
  15151. else {
  15152. throw new TypeError('Array or DataSet expected');
  15153. }
  15154. if (oldNodesData) {
  15155. // unsubscribe from old dataset
  15156. util.forEach(this.nodesListeners, function (callback, event) {
  15157. oldNodesData.off(event, callback);
  15158. });
  15159. }
  15160. // remove drawn nodes
  15161. this.nodes = {};
  15162. if (this.nodesData) {
  15163. // subscribe to new dataset
  15164. var me = this;
  15165. util.forEach(this.nodesListeners, function (callback, event) {
  15166. me.nodesData.on(event, callback);
  15167. });
  15168. // draw all new nodes
  15169. var ids = this.nodesData.getIds();
  15170. this._addNodes(ids);
  15171. }
  15172. this._updateSelection();
  15173. };
  15174. /**
  15175. * Add nodes
  15176. * @param {Number[] | String[]} ids
  15177. * @private
  15178. */
  15179. Graph.prototype._addNodes = function(ids) {
  15180. var id;
  15181. for (var i = 0, len = ids.length; i < len; i++) {
  15182. id = ids[i];
  15183. var data = this.nodesData.get(id);
  15184. var node = new Node(data, this.images, this.groups, this.constants);
  15185. this.nodes[id] = node; // note: this may replace an existing node
  15186. if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) {
  15187. var radius = 10 * 0.1*ids.length;
  15188. var angle = 2 * Math.PI * Math.random();
  15189. if (node.xFixed == false) {node.x = radius * Math.cos(angle);}
  15190. if (node.yFixed == false) {node.y = radius * Math.sin(angle);}
  15191. }
  15192. this.moving = true;
  15193. }
  15194. this._updateNodeIndexList();
  15195. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15196. this._resetLevels();
  15197. this._setupHierarchicalLayout();
  15198. }
  15199. this._updateCalculationNodes();
  15200. this._reconnectEdges();
  15201. this._updateValueRange(this.nodes);
  15202. this.updateLabels();
  15203. };
  15204. /**
  15205. * Update existing nodes, or create them when not yet existing
  15206. * @param {Number[] | String[]} ids
  15207. * @private
  15208. */
  15209. Graph.prototype._updateNodes = function(ids) {
  15210. var nodes = this.nodes,
  15211. nodesData = this.nodesData;
  15212. for (var i = 0, len = ids.length; i < len; i++) {
  15213. var id = ids[i];
  15214. var node = nodes[id];
  15215. var data = nodesData.get(id);
  15216. if (node) {
  15217. // update node
  15218. node.setProperties(data, this.constants);
  15219. }
  15220. else {
  15221. // create node
  15222. node = new Node(properties, this.images, this.groups, this.constants);
  15223. nodes[id] = node;
  15224. if (!node.isFixed()) {
  15225. this.moving = true;
  15226. }
  15227. }
  15228. }
  15229. this._updateNodeIndexList();
  15230. this._reconnectEdges();
  15231. this._updateValueRange(nodes);
  15232. };
  15233. /**
  15234. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  15235. * @param {Number[] | String[]} ids
  15236. * @private
  15237. */
  15238. Graph.prototype._removeNodes = function(ids) {
  15239. var nodes = this.nodes;
  15240. for (var i = 0, len = ids.length; i < len; i++) {
  15241. var id = ids[i];
  15242. delete nodes[id];
  15243. }
  15244. this._updateNodeIndexList();
  15245. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15246. this._resetLevels();
  15247. this._setupHierarchicalLayout();
  15248. }
  15249. this._updateCalculationNodes();
  15250. this._reconnectEdges();
  15251. this._updateSelection();
  15252. this._updateValueRange(nodes);
  15253. };
  15254. /**
  15255. * Load edges by reading the data table
  15256. * @param {Array | DataSet | DataView} edges The data containing the edges.
  15257. * @private
  15258. * @private
  15259. */
  15260. Graph.prototype._setEdges = function(edges) {
  15261. var oldEdgesData = this.edgesData;
  15262. if (edges instanceof DataSet || edges instanceof DataView) {
  15263. this.edgesData = edges;
  15264. }
  15265. else if (edges instanceof Array) {
  15266. this.edgesData = new DataSet();
  15267. this.edgesData.add(edges);
  15268. }
  15269. else if (!edges) {
  15270. this.edgesData = new DataSet();
  15271. }
  15272. else {
  15273. throw new TypeError('Array or DataSet expected');
  15274. }
  15275. if (oldEdgesData) {
  15276. // unsubscribe from old dataset
  15277. util.forEach(this.edgesListeners, function (callback, event) {
  15278. oldEdgesData.off(event, callback);
  15279. });
  15280. }
  15281. // remove drawn edges
  15282. this.edges = {};
  15283. if (this.edgesData) {
  15284. // subscribe to new dataset
  15285. var me = this;
  15286. util.forEach(this.edgesListeners, function (callback, event) {
  15287. me.edgesData.on(event, callback);
  15288. });
  15289. // draw all new nodes
  15290. var ids = this.edgesData.getIds();
  15291. this._addEdges(ids);
  15292. }
  15293. this._reconnectEdges();
  15294. };
  15295. /**
  15296. * Add edges
  15297. * @param {Number[] | String[]} ids
  15298. * @private
  15299. */
  15300. Graph.prototype._addEdges = function (ids) {
  15301. var edges = this.edges,
  15302. edgesData = this.edgesData;
  15303. for (var i = 0, len = ids.length; i < len; i++) {
  15304. var id = ids[i];
  15305. var oldEdge = edges[id];
  15306. if (oldEdge) {
  15307. oldEdge.disconnect();
  15308. }
  15309. var data = edgesData.get(id, {"showInternalIds" : true});
  15310. edges[id] = new Edge(data, this, this.constants);
  15311. }
  15312. this.moving = true;
  15313. this._updateValueRange(edges);
  15314. this._createBezierNodes();
  15315. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15316. this._resetLevels();
  15317. this._setupHierarchicalLayout();
  15318. }
  15319. this._updateCalculationNodes();
  15320. };
  15321. /**
  15322. * Update existing edges, or create them when not yet existing
  15323. * @param {Number[] | String[]} ids
  15324. * @private
  15325. */
  15326. Graph.prototype._updateEdges = function (ids) {
  15327. var edges = this.edges,
  15328. edgesData = this.edgesData;
  15329. for (var i = 0, len = ids.length; i < len; i++) {
  15330. var id = ids[i];
  15331. var data = edgesData.get(id);
  15332. var edge = edges[id];
  15333. if (edge) {
  15334. // update edge
  15335. edge.disconnect();
  15336. edge.setProperties(data, this.constants);
  15337. edge.connect();
  15338. }
  15339. else {
  15340. // create edge
  15341. edge = new Edge(data, this, this.constants);
  15342. this.edges[id] = edge;
  15343. }
  15344. }
  15345. this._createBezierNodes();
  15346. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15347. this._resetLevels();
  15348. this._setupHierarchicalLayout();
  15349. }
  15350. this.moving = true;
  15351. this._updateValueRange(edges);
  15352. };
  15353. /**
  15354. * Remove existing edges. Non existing ids will be ignored
  15355. * @param {Number[] | String[]} ids
  15356. * @private
  15357. */
  15358. Graph.prototype._removeEdges = function (ids) {
  15359. var edges = this.edges;
  15360. for (var i = 0, len = ids.length; i < len; i++) {
  15361. var id = ids[i];
  15362. var edge = edges[id];
  15363. if (edge) {
  15364. if (edge.via != null) {
  15365. delete this.sectors['support']['nodes'][edge.via.id];
  15366. }
  15367. edge.disconnect();
  15368. delete edges[id];
  15369. }
  15370. }
  15371. this.moving = true;
  15372. this._updateValueRange(edges);
  15373. if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) {
  15374. this._resetLevels();
  15375. this._setupHierarchicalLayout();
  15376. }
  15377. this._updateCalculationNodes();
  15378. };
  15379. /**
  15380. * Reconnect all edges
  15381. * @private
  15382. */
  15383. Graph.prototype._reconnectEdges = function() {
  15384. var id,
  15385. nodes = this.nodes,
  15386. edges = this.edges;
  15387. for (id in nodes) {
  15388. if (nodes.hasOwnProperty(id)) {
  15389. nodes[id].edges = [];
  15390. }
  15391. }
  15392. for (id in edges) {
  15393. if (edges.hasOwnProperty(id)) {
  15394. var edge = edges[id];
  15395. edge.from = null;
  15396. edge.to = null;
  15397. edge.connect();
  15398. }
  15399. }
  15400. };
  15401. /**
  15402. * Update the values of all object in the given array according to the current
  15403. * value range of the objects in the array.
  15404. * @param {Object} obj An object containing a set of Edges or Nodes
  15405. * The objects must have a method getValue() and
  15406. * setValueRange(min, max).
  15407. * @private
  15408. */
  15409. Graph.prototype._updateValueRange = function(obj) {
  15410. var id;
  15411. // determine the range of the objects
  15412. var valueMin = undefined;
  15413. var valueMax = undefined;
  15414. for (id in obj) {
  15415. if (obj.hasOwnProperty(id)) {
  15416. var value = obj[id].getValue();
  15417. if (value !== undefined) {
  15418. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  15419. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  15420. }
  15421. }
  15422. }
  15423. // adjust the range of all objects
  15424. if (valueMin !== undefined && valueMax !== undefined) {
  15425. for (id in obj) {
  15426. if (obj.hasOwnProperty(id)) {
  15427. obj[id].setValueRange(valueMin, valueMax);
  15428. }
  15429. }
  15430. }
  15431. };
  15432. /**
  15433. * Redraw the graph with the current data
  15434. * chart will be resized too.
  15435. */
  15436. Graph.prototype.redraw = function() {
  15437. this.setSize(this.width, this.height);
  15438. this._redraw();
  15439. };
  15440. /**
  15441. * Redraw the graph with the current data
  15442. * @private
  15443. */
  15444. Graph.prototype._redraw = function() {
  15445. var ctx = this.frame.canvas.getContext('2d');
  15446. // clear the canvas
  15447. var w = this.frame.canvas.width;
  15448. var h = this.frame.canvas.height;
  15449. ctx.clearRect(0, 0, w, h);
  15450. // set scaling and translation
  15451. ctx.save();
  15452. ctx.translate(this.translation.x, this.translation.y);
  15453. ctx.scale(this.scale, this.scale);
  15454. this.canvasTopLeft = {
  15455. "x": this._canvasToX(0),
  15456. "y": this._canvasToY(0)
  15457. };
  15458. this.canvasBottomRight = {
  15459. "x": this._canvasToX(this.frame.canvas.clientWidth),
  15460. "y": this._canvasToY(this.frame.canvas.clientHeight)
  15461. };
  15462. this._doInAllSectors("_drawAllSectorNodes",ctx);
  15463. this._doInAllSectors("_drawEdges",ctx);
  15464. this._doInAllSectors("_drawNodes",ctx,false);
  15465. // this._doInSupportSector("_drawNodes",ctx,true);
  15466. // this._drawTree(ctx,"#F00F0F");
  15467. // restore original scaling and translation
  15468. ctx.restore();
  15469. };
  15470. /**
  15471. * Set the translation of the graph
  15472. * @param {Number} offsetX Horizontal offset
  15473. * @param {Number} offsetY Vertical offset
  15474. * @private
  15475. */
  15476. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  15477. if (this.translation === undefined) {
  15478. this.translation = {
  15479. x: 0,
  15480. y: 0
  15481. };
  15482. }
  15483. if (offsetX !== undefined) {
  15484. this.translation.x = offsetX;
  15485. }
  15486. if (offsetY !== undefined) {
  15487. this.translation.y = offsetY;
  15488. }
  15489. };
  15490. /**
  15491. * Get the translation of the graph
  15492. * @return {Object} translation An object with parameters x and y, both a number
  15493. * @private
  15494. */
  15495. Graph.prototype._getTranslation = function() {
  15496. return {
  15497. x: this.translation.x,
  15498. y: this.translation.y
  15499. };
  15500. };
  15501. /**
  15502. * Scale the graph
  15503. * @param {Number} scale Scaling factor 1.0 is unscaled
  15504. * @private
  15505. */
  15506. Graph.prototype._setScale = function(scale) {
  15507. this.scale = scale;
  15508. };
  15509. /**
  15510. * Get the current scale of the graph
  15511. * @return {Number} scale Scaling factor 1.0 is unscaled
  15512. * @private
  15513. */
  15514. Graph.prototype._getScale = function() {
  15515. return this.scale;
  15516. };
  15517. /**
  15518. * Convert a horizontal point on the HTML canvas to the x-value of the model
  15519. * @param {number} x
  15520. * @returns {number}
  15521. * @private
  15522. */
  15523. Graph.prototype._canvasToX = function(x) {
  15524. return (x - this.translation.x) / this.scale;
  15525. };
  15526. /**
  15527. * Convert an x-value in the model to a horizontal point on the HTML canvas
  15528. * @param {number} x
  15529. * @returns {number}
  15530. * @private
  15531. */
  15532. Graph.prototype._xToCanvas = function(x) {
  15533. return x * this.scale + this.translation.x;
  15534. };
  15535. /**
  15536. * Convert a vertical point on the HTML canvas to the y-value of the model
  15537. * @param {number} y
  15538. * @returns {number}
  15539. * @private
  15540. */
  15541. Graph.prototype._canvasToY = function(y) {
  15542. return (y - this.translation.y) / this.scale;
  15543. };
  15544. /**
  15545. * Convert an y-value in the model to a vertical point on the HTML canvas
  15546. * @param {number} y
  15547. * @returns {number}
  15548. * @private
  15549. */
  15550. Graph.prototype._yToCanvas = function(y) {
  15551. return y * this.scale + this.translation.y ;
  15552. };
  15553. /**
  15554. * Redraw all nodes
  15555. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15556. * @param {CanvasRenderingContext2D} ctx
  15557. * @param {Boolean} [alwaysShow]
  15558. * @private
  15559. */
  15560. Graph.prototype._drawNodes = function(ctx,alwaysShow) {
  15561. if (alwaysShow === undefined) {
  15562. alwaysShow = false;
  15563. }
  15564. // first draw the unselected nodes
  15565. var nodes = this.nodes;
  15566. var selected = [];
  15567. for (var id in nodes) {
  15568. if (nodes.hasOwnProperty(id)) {
  15569. nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight);
  15570. if (nodes[id].isSelected()) {
  15571. selected.push(id);
  15572. }
  15573. else {
  15574. if (nodes[id].inArea() || alwaysShow) {
  15575. nodes[id].draw(ctx);
  15576. }
  15577. }
  15578. }
  15579. }
  15580. // draw the selected nodes on top
  15581. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  15582. if (nodes[selected[s]].inArea() || alwaysShow) {
  15583. nodes[selected[s]].draw(ctx);
  15584. }
  15585. }
  15586. };
  15587. /**
  15588. * Redraw all edges
  15589. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  15590. * @param {CanvasRenderingContext2D} ctx
  15591. * @private
  15592. */
  15593. Graph.prototype._drawEdges = function(ctx) {
  15594. var edges = this.edges;
  15595. for (var id in edges) {
  15596. if (edges.hasOwnProperty(id)) {
  15597. var edge = edges[id];
  15598. edge.setScale(this.scale);
  15599. if (edge.connected) {
  15600. edges[id].draw(ctx);
  15601. }
  15602. }
  15603. }
  15604. };
  15605. /**
  15606. * Find a stable position for all nodes
  15607. * @private
  15608. */
  15609. Graph.prototype._stabilize = function() {
  15610. if (this.constants.freezeForStabilization == true) {
  15611. this._freezeDefinedNodes();
  15612. }
  15613. // find stable position
  15614. var count = 0;
  15615. while (this.moving && count < this.constants.stabilizationIterations) {
  15616. this._physicsTick();
  15617. count++;
  15618. }
  15619. this.zoomExtent(false,true);
  15620. if (this.constants.freezeForStabilization == true) {
  15621. this._restoreFrozenNodes();
  15622. }
  15623. this.emit("stabilized",{iterations:count});
  15624. };
  15625. Graph.prototype._freezeDefinedNodes = function() {
  15626. var nodes = this.nodes;
  15627. for (var id in nodes) {
  15628. if (nodes.hasOwnProperty(id)) {
  15629. if (nodes[id].x != null && nodes[id].y != null) {
  15630. nodes[id].fixedData.x = nodes[id].xFixed;
  15631. nodes[id].fixedData.y = nodes[id].yFixed;
  15632. nodes[id].xFixed = true;
  15633. nodes[id].yFixed = true;
  15634. }
  15635. }
  15636. }
  15637. };
  15638. Graph.prototype._restoreFrozenNodes = function() {
  15639. var nodes = this.nodes;
  15640. for (var id in nodes) {
  15641. if (nodes.hasOwnProperty(id)) {
  15642. if (nodes[id].fixedData.x != null) {
  15643. nodes[id].xFixed = nodes[id].fixedData.x;
  15644. nodes[id].yFixed = nodes[id].fixedData.y;
  15645. }
  15646. }
  15647. }
  15648. };
  15649. /**
  15650. * Check if any of the nodes is still moving
  15651. * @param {number} vmin the minimum velocity considered as 'moving'
  15652. * @return {boolean} true if moving, false if non of the nodes is moving
  15653. * @private
  15654. */
  15655. Graph.prototype._isMoving = function(vmin) {
  15656. var nodes = this.nodes;
  15657. for (var id in nodes) {
  15658. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  15659. return true;
  15660. }
  15661. }
  15662. return false;
  15663. };
  15664. /**
  15665. * /**
  15666. * Perform one discrete step for all nodes
  15667. *
  15668. * @private
  15669. */
  15670. Graph.prototype._discreteStepNodes = function() {
  15671. var interval = this.physicsDiscreteStepsize;
  15672. var nodes = this.nodes;
  15673. var nodeId;
  15674. var nodesPresent = false;
  15675. if (this.constants.maxVelocity > 0) {
  15676. for (nodeId in nodes) {
  15677. if (nodes.hasOwnProperty(nodeId)) {
  15678. nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity);
  15679. nodesPresent = true;
  15680. }
  15681. }
  15682. }
  15683. else {
  15684. for (nodeId in nodes) {
  15685. if (nodes.hasOwnProperty(nodeId)) {
  15686. nodes[nodeId].discreteStep(interval);
  15687. nodesPresent = true;
  15688. }
  15689. }
  15690. }
  15691. if (nodesPresent == true) {
  15692. var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05);
  15693. if (vminCorrected > 0.5*this.constants.maxVelocity) {
  15694. this.moving = true;
  15695. }
  15696. else {
  15697. this.moving = this._isMoving(vminCorrected);
  15698. }
  15699. }
  15700. };
  15701. Graph.prototype._physicsTick = function() {
  15702. if (!this.freezeSimulation) {
  15703. if (this.moving) {
  15704. this._doInAllActiveSectors("_initializeForceCalculation");
  15705. this._doInAllActiveSectors("_discreteStepNodes");
  15706. if (this.constants.smoothCurves) {
  15707. this._doInSupportSector("_discreteStepNodes");
  15708. }
  15709. this._findCenter(this._getRange())
  15710. }
  15711. }
  15712. };
  15713. /**
  15714. * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick.
  15715. * It reschedules itself at the beginning of the function
  15716. *
  15717. * @private
  15718. */
  15719. Graph.prototype._animationStep = function() {
  15720. // reset the timer so a new scheduled animation step can be set
  15721. this.timer = undefined;
  15722. // handle the keyboad movement
  15723. this._handleNavigation();
  15724. // this schedules a new animation step
  15725. this.start();
  15726. // start the physics simulation
  15727. var calculationTime = Date.now();
  15728. var maxSteps = 1;
  15729. this._physicsTick();
  15730. var timeRequired = Date.now() - calculationTime;
  15731. while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) {
  15732. this._physicsTick();
  15733. timeRequired = Date.now() - calculationTime;
  15734. maxSteps++;
  15735. }
  15736. // start the rendering process
  15737. var renderTime = Date.now();
  15738. this._redraw();
  15739. this.renderTime = Date.now() - renderTime;
  15740. };
  15741. if (typeof window !== 'undefined') {
  15742. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
  15743. window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  15744. }
  15745. /**
  15746. * Schedule a animation step with the refreshrate interval.
  15747. */
  15748. Graph.prototype.start = function() {
  15749. if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
  15750. if (!this.timer) {
  15751. var ua = navigator.userAgent.toLowerCase();
  15752. if (ua.indexOf('safari') != -1) {
  15753. if (ua.indexOf('chrome') <= -1) {
  15754. // safari
  15755. this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15756. }
  15757. else {
  15758. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15759. }
  15760. }
  15761. else{
  15762. this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function
  15763. }
  15764. }
  15765. }
  15766. else {
  15767. this._redraw();
  15768. }
  15769. };
  15770. /**
  15771. * Move the graph according to the keyboard presses.
  15772. *
  15773. * @private
  15774. */
  15775. Graph.prototype._handleNavigation = function() {
  15776. if (this.xIncrement != 0 || this.yIncrement != 0) {
  15777. var translation = this._getTranslation();
  15778. this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement);
  15779. }
  15780. if (this.zoomIncrement != 0) {
  15781. var center = {
  15782. x: this.frame.canvas.clientWidth / 2,
  15783. y: this.frame.canvas.clientHeight / 2
  15784. };
  15785. this._zoom(this.scale*(1 + this.zoomIncrement), center);
  15786. }
  15787. };
  15788. /**
  15789. * Freeze the _animationStep
  15790. */
  15791. Graph.prototype.toggleFreeze = function() {
  15792. if (this.freezeSimulation == false) {
  15793. this.freezeSimulation = true;
  15794. }
  15795. else {
  15796. this.freezeSimulation = false;
  15797. this.start();
  15798. }
  15799. };
  15800. Graph.prototype._configureSmoothCurves = function(disableStart) {
  15801. if (disableStart === undefined) {
  15802. disableStart = true;
  15803. }
  15804. if (this.constants.smoothCurves == true) {
  15805. this._createBezierNodes();
  15806. }
  15807. else {
  15808. // delete the support nodes
  15809. this.sectors['support']['nodes'] = {};
  15810. for (var edgeId in this.edges) {
  15811. if (this.edges.hasOwnProperty(edgeId)) {
  15812. this.edges[edgeId].smooth = false;
  15813. this.edges[edgeId].via = null;
  15814. }
  15815. }
  15816. }
  15817. this._updateCalculationNodes();
  15818. if (!disableStart) {
  15819. this.moving = true;
  15820. this.start();
  15821. }
  15822. };
  15823. Graph.prototype._createBezierNodes = function() {
  15824. if (this.constants.smoothCurves == true) {
  15825. for (var edgeId in this.edges) {
  15826. if (this.edges.hasOwnProperty(edgeId)) {
  15827. var edge = this.edges[edgeId];
  15828. if (edge.via == null) {
  15829. edge.smooth = true;
  15830. var nodeId = "edgeId:".concat(edge.id);
  15831. this.sectors['support']['nodes'][nodeId] = new Node(
  15832. {id:nodeId,
  15833. mass:1,
  15834. shape:'circle',
  15835. image:"",
  15836. internalMultiplier:1
  15837. },{},{},this.constants);
  15838. edge.via = this.sectors['support']['nodes'][nodeId];
  15839. edge.via.parentEdgeId = edge.id;
  15840. edge.positionBezierNode();
  15841. }
  15842. }
  15843. }
  15844. }
  15845. };
  15846. Graph.prototype._initializeMixinLoaders = function () {
  15847. for (var mixinFunction in graphMixinLoaders) {
  15848. if (graphMixinLoaders.hasOwnProperty(mixinFunction)) {
  15849. Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction];
  15850. }
  15851. }
  15852. };
  15853. /**
  15854. * Load the XY positions of the nodes into the dataset.
  15855. */
  15856. Graph.prototype.storePosition = function() {
  15857. var dataArray = [];
  15858. for (var nodeId in this.nodes) {
  15859. if (this.nodes.hasOwnProperty(nodeId)) {
  15860. var node = this.nodes[nodeId];
  15861. var allowedToMoveX = !this.nodes.xFixed;
  15862. var allowedToMoveY = !this.nodes.yFixed;
  15863. if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) {
  15864. dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY});
  15865. }
  15866. }
  15867. }
  15868. this.nodesData.update(dataArray);
  15869. };
  15870. /**
  15871. * vis.js module exports
  15872. */
  15873. var vis = {
  15874. util: util,
  15875. Controller: Controller,
  15876. DataSet: DataSet,
  15877. DataView: DataView,
  15878. Range: Range,
  15879. Stack: Stack,
  15880. TimeStep: TimeStep,
  15881. components: {
  15882. items: {
  15883. Item: Item,
  15884. ItemBox: ItemBox,
  15885. ItemPoint: ItemPoint,
  15886. ItemRange: ItemRange
  15887. },
  15888. Component: Component,
  15889. Panel: Panel,
  15890. RootPanel: RootPanel,
  15891. ItemSet: ItemSet,
  15892. TimeAxis: TimeAxis
  15893. },
  15894. graph: {
  15895. Node: Node,
  15896. Edge: Edge,
  15897. Popup: Popup,
  15898. Groups: Groups,
  15899. Images: Images
  15900. },
  15901. Timeline: Timeline,
  15902. Graph: Graph
  15903. };
  15904. /**
  15905. * CommonJS module exports
  15906. */
  15907. if (typeof exports !== 'undefined') {
  15908. exports = vis;
  15909. }
  15910. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  15911. module.exports = vis;
  15912. }
  15913. /**
  15914. * AMD module exports
  15915. */
  15916. if (typeof(define) === 'function') {
  15917. define(function () {
  15918. return vis;
  15919. });
  15920. }
  15921. /**
  15922. * Window exports
  15923. */
  15924. if (typeof window !== 'undefined') {
  15925. // attach the module to the window, load as a regular javascript file
  15926. window['vis'] = vis;
  15927. }
  15928. },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){
  15929. /**
  15930. * Expose `Emitter`.
  15931. */
  15932. module.exports = Emitter;
  15933. /**
  15934. * Initialize a new `Emitter`.
  15935. *
  15936. * @api public
  15937. */
  15938. function Emitter(obj) {
  15939. if (obj) return mixin(obj);
  15940. };
  15941. /**
  15942. * Mixin the emitter properties.
  15943. *
  15944. * @param {Object} obj
  15945. * @return {Object}
  15946. * @api private
  15947. */
  15948. function mixin(obj) {
  15949. for (var key in Emitter.prototype) {
  15950. obj[key] = Emitter.prototype[key];
  15951. }
  15952. return obj;
  15953. }
  15954. /**
  15955. * Listen on the given `event` with `fn`.
  15956. *
  15957. * @param {String} event
  15958. * @param {Function} fn
  15959. * @return {Emitter}
  15960. * @api public
  15961. */
  15962. Emitter.prototype.on =
  15963. Emitter.prototype.addEventListener = function(event, fn){
  15964. this._callbacks = this._callbacks || {};
  15965. (this._callbacks[event] = this._callbacks[event] || [])
  15966. .push(fn);
  15967. return this;
  15968. };
  15969. /**
  15970. * Adds an `event` listener that will be invoked a single
  15971. * time then automatically removed.
  15972. *
  15973. * @param {String} event
  15974. * @param {Function} fn
  15975. * @return {Emitter}
  15976. * @api public
  15977. */
  15978. Emitter.prototype.once = function(event, fn){
  15979. var self = this;
  15980. this._callbacks = this._callbacks || {};
  15981. function on() {
  15982. self.off(event, on);
  15983. fn.apply(this, arguments);
  15984. }
  15985. on.fn = fn;
  15986. this.on(event, on);
  15987. return this;
  15988. };
  15989. /**
  15990. * Remove the given callback for `event` or all
  15991. * registered callbacks.
  15992. *
  15993. * @param {String} event
  15994. * @param {Function} fn
  15995. * @return {Emitter}
  15996. * @api public
  15997. */
  15998. Emitter.prototype.off =
  15999. Emitter.prototype.removeListener =
  16000. Emitter.prototype.removeAllListeners =
  16001. Emitter.prototype.removeEventListener = function(event, fn){
  16002. this._callbacks = this._callbacks || {};
  16003. // all
  16004. if (0 == arguments.length) {
  16005. this._callbacks = {};
  16006. return this;
  16007. }
  16008. // specific event
  16009. var callbacks = this._callbacks[event];
  16010. if (!callbacks) return this;
  16011. // remove all handlers
  16012. if (1 == arguments.length) {
  16013. delete this._callbacks[event];
  16014. return this;
  16015. }
  16016. // remove specific handler
  16017. var cb;
  16018. for (var i = 0; i < callbacks.length; i++) {
  16019. cb = callbacks[i];
  16020. if (cb === fn || cb.fn === fn) {
  16021. callbacks.splice(i, 1);
  16022. break;
  16023. }
  16024. }
  16025. return this;
  16026. };
  16027. /**
  16028. * Emit `event` with the given args.
  16029. *
  16030. * @param {String} event
  16031. * @param {Mixed} ...
  16032. * @return {Emitter}
  16033. */
  16034. Emitter.prototype.emit = function(event){
  16035. this._callbacks = this._callbacks || {};
  16036. var args = [].slice.call(arguments, 1)
  16037. , callbacks = this._callbacks[event];
  16038. if (callbacks) {
  16039. callbacks = callbacks.slice(0);
  16040. for (var i = 0, len = callbacks.length; i < len; ++i) {
  16041. callbacks[i].apply(this, args);
  16042. }
  16043. }
  16044. return this;
  16045. };
  16046. /**
  16047. * Return array of callbacks for `event`.
  16048. *
  16049. * @param {String} event
  16050. * @return {Array}
  16051. * @api public
  16052. */
  16053. Emitter.prototype.listeners = function(event){
  16054. this._callbacks = this._callbacks || {};
  16055. return this._callbacks[event] || [];
  16056. };
  16057. /**
  16058. * Check if this emitter has `event` handlers.
  16059. *
  16060. * @param {String} event
  16061. * @return {Boolean}
  16062. * @api public
  16063. */
  16064. Emitter.prototype.hasListeners = function(event){
  16065. return !! this.listeners(event).length;
  16066. };
  16067. },{}],3:[function(require,module,exports){
  16068. /*! Hammer.JS - v1.0.5 - 2013-04-07
  16069. * http://eightmedia.github.com/hammer.js
  16070. *
  16071. * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
  16072. * Licensed under the MIT license */
  16073. (function(window, undefined) {
  16074. 'use strict';
  16075. /**
  16076. * Hammer
  16077. * use this to create instances
  16078. * @param {HTMLElement} element
  16079. * @param {Object} options
  16080. * @returns {Hammer.Instance}
  16081. * @constructor
  16082. */
  16083. var Hammer = function(element, options) {
  16084. return new Hammer.Instance(element, options || {});
  16085. };
  16086. // default settings
  16087. Hammer.defaults = {
  16088. // add styles and attributes to the element to prevent the browser from doing
  16089. // its native behavior. this doesnt prevent the scrolling, but cancels
  16090. // the contextmenu, tap highlighting etc
  16091. // set to false to disable this
  16092. stop_browser_behavior: {
  16093. // this also triggers onselectstart=false for IE
  16094. userSelect: 'none',
  16095. // this makes the element blocking in IE10 >, you could experiment with the value
  16096. // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
  16097. touchAction: 'none',
  16098. touchCallout: 'none',
  16099. contentZooming: 'none',
  16100. userDrag: 'none',
  16101. tapHighlightColor: 'rgba(0,0,0,0)'
  16102. }
  16103. // more settings are defined per gesture at gestures.js
  16104. };
  16105. // detect touchevents
  16106. Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  16107. Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  16108. // dont use mouseevents on mobile devices
  16109. Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  16110. Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);
  16111. // eventtypes per touchevent (start, move, end)
  16112. // are filled by Hammer.event.determineEventTypes on setup
  16113. Hammer.EVENT_TYPES = {};
  16114. // direction defines
  16115. Hammer.DIRECTION_DOWN = 'down';
  16116. Hammer.DIRECTION_LEFT = 'left';
  16117. Hammer.DIRECTION_UP = 'up';
  16118. Hammer.DIRECTION_RIGHT = 'right';
  16119. // pointer type
  16120. Hammer.POINTER_MOUSE = 'mouse';
  16121. Hammer.POINTER_TOUCH = 'touch';
  16122. Hammer.POINTER_PEN = 'pen';
  16123. // touch event defines
  16124. Hammer.EVENT_START = 'start';
  16125. Hammer.EVENT_MOVE = 'move';
  16126. Hammer.EVENT_END = 'end';
  16127. // hammer document where the base events are added at
  16128. Hammer.DOCUMENT = document;
  16129. // plugins namespace
  16130. Hammer.plugins = {};
  16131. // if the window events are set...
  16132. Hammer.READY = false;
  16133. /**
  16134. * setup events to detect gestures on the document
  16135. */
  16136. function setup() {
  16137. if(Hammer.READY) {
  16138. return;
  16139. }
  16140. // find what eventtypes we add listeners to
  16141. Hammer.event.determineEventTypes();
  16142. // Register all gestures inside Hammer.gestures
  16143. for(var name in Hammer.gestures) {
  16144. if(Hammer.gestures.hasOwnProperty(name)) {
  16145. Hammer.detection.register(Hammer.gestures[name]);
  16146. }
  16147. }
  16148. // Add touch events on the document
  16149. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
  16150. Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);
  16151. // Hammer is ready...!
  16152. Hammer.READY = true;
  16153. }
  16154. /**
  16155. * create new hammer instance
  16156. * all methods should return the instance itself, so it is chainable.
  16157. * @param {HTMLElement} element
  16158. * @param {Object} [options={}]
  16159. * @returns {Hammer.Instance}
  16160. * @constructor
  16161. */
  16162. Hammer.Instance = function(element, options) {
  16163. var self = this;
  16164. // setup HammerJS window events and register all gestures
  16165. // this also sets up the default options
  16166. setup();
  16167. this.element = element;
  16168. // start/stop detection option
  16169. this.enabled = true;
  16170. // merge options
  16171. this.options = Hammer.utils.extend(
  16172. Hammer.utils.extend({}, Hammer.defaults),
  16173. options || {});
  16174. // add some css to the element to prevent the browser from doing its native behavoir
  16175. if(this.options.stop_browser_behavior) {
  16176. Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  16177. }
  16178. // start detection on touchstart
  16179. Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
  16180. if(self.enabled) {
  16181. Hammer.detection.startDetect(self, ev);
  16182. }
  16183. });
  16184. // return instance
  16185. return this;
  16186. };
  16187. Hammer.Instance.prototype = {
  16188. /**
  16189. * bind events to the instance
  16190. * @param {String} gesture
  16191. * @param {Function} handler
  16192. * @returns {Hammer.Instance}
  16193. */
  16194. on: function onEvent(gesture, handler){
  16195. var gestures = gesture.split(' ');
  16196. for(var t=0; t<gestures.length; t++) {
  16197. this.element.addEventListener(gestures[t], handler, false);
  16198. }
  16199. return this;
  16200. },
  16201. /**
  16202. * unbind events to the instance
  16203. * @param {String} gesture
  16204. * @param {Function} handler
  16205. * @returns {Hammer.Instance}
  16206. */
  16207. off: function offEvent(gesture, handler){
  16208. var gestures = gesture.split(' ');
  16209. for(var t=0; t<gestures.length; t++) {
  16210. this.element.removeEventListener(gestures[t], handler, false);
  16211. }
  16212. return this;
  16213. },
  16214. /**
  16215. * trigger gesture event
  16216. * @param {String} gesture
  16217. * @param {Object} eventData
  16218. * @returns {Hammer.Instance}
  16219. */
  16220. trigger: function triggerEvent(gesture, eventData){
  16221. // create DOM event
  16222. var event = Hammer.DOCUMENT.createEvent('Event');
  16223. event.initEvent(gesture, true, true);
  16224. event.gesture = eventData;
  16225. // trigger on the target if it is in the instance element,
  16226. // this is for event delegation tricks
  16227. var element = this.element;
  16228. if(Hammer.utils.hasParent(eventData.target, element)) {
  16229. element = eventData.target;
  16230. }
  16231. element.dispatchEvent(event);
  16232. return this;
  16233. },
  16234. /**
  16235. * enable of disable hammer.js detection
  16236. * @param {Boolean} state
  16237. * @returns {Hammer.Instance}
  16238. */
  16239. enable: function enable(state) {
  16240. this.enabled = state;
  16241. return this;
  16242. }
  16243. };
  16244. /**
  16245. * this holds the last move event,
  16246. * used to fix empty touchend issue
  16247. * see the onTouch event for an explanation
  16248. * @type {Object}
  16249. */
  16250. var last_move_event = null;
  16251. /**
  16252. * when the mouse is hold down, this is true
  16253. * @type {Boolean}
  16254. */
  16255. var enable_detect = false;
  16256. /**
  16257. * when touch events have been fired, this is true
  16258. * @type {Boolean}
  16259. */
  16260. var touch_triggered = false;
  16261. Hammer.event = {
  16262. /**
  16263. * simple addEventListener
  16264. * @param {HTMLElement} element
  16265. * @param {String} type
  16266. * @param {Function} handler
  16267. */
  16268. bindDom: function(element, type, handler) {
  16269. var types = type.split(' ');
  16270. for(var t=0; t<types.length; t++) {
  16271. element.addEventListener(types[t], handler, false);
  16272. }
  16273. },
  16274. /**
  16275. * touch events with mouse fallback
  16276. * @param {HTMLElement} element
  16277. * @param {String} eventType like Hammer.EVENT_MOVE
  16278. * @param {Function} handler
  16279. */
  16280. onTouch: function onTouch(element, eventType, handler) {
  16281. var self = this;
  16282. this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  16283. var sourceEventType = ev.type.toLowerCase();
  16284. // onmouseup, but when touchend has been fired we do nothing.
  16285. // this is for touchdevices which also fire a mouseup on touchend
  16286. if(sourceEventType.match(/mouse/) && touch_triggered) {
  16287. return;
  16288. }
  16289. // mousebutton must be down or a touch event
  16290. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  16291. sourceEventType.match(/pointerdown/) || // pointerevents touch
  16292. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  16293. ){
  16294. enable_detect = true;
  16295. }
  16296. // we are in a touch event, set the touch triggered bool to true,
  16297. // this for the conflicts that may occur on ios and android
  16298. if(sourceEventType.match(/touch|pointer/)) {
  16299. touch_triggered = true;
  16300. }
  16301. // count the total touches on the screen
  16302. var count_touches = 0;
  16303. // when touch has been triggered in this detection session
  16304. // and we are now handling a mouse event, we stop that to prevent conflicts
  16305. if(enable_detect) {
  16306. // update pointerevent
  16307. if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
  16308. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16309. }
  16310. // touch
  16311. else if(sourceEventType.match(/touch/)) {
  16312. count_touches = ev.touches.length;
  16313. }
  16314. // mouse
  16315. else if(!touch_triggered) {
  16316. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  16317. }
  16318. // if we are in a end event, but when we remove one touch and
  16319. // we still have enough, set eventType to move
  16320. if(count_touches > 0 && eventType == Hammer.EVENT_END) {
  16321. eventType = Hammer.EVENT_MOVE;
  16322. }
  16323. // no touches, force the end event
  16324. else if(!count_touches) {
  16325. eventType = Hammer.EVENT_END;
  16326. }
  16327. // because touchend has no touches, and we often want to use these in our gestures,
  16328. // we send the last move event as our eventData in touchend
  16329. if(!count_touches && last_move_event !== null) {
  16330. ev = last_move_event;
  16331. }
  16332. // store the last move event
  16333. else {
  16334. last_move_event = ev;
  16335. }
  16336. // trigger the handler
  16337. handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));
  16338. // remove pointerevent from list
  16339. if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
  16340. count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
  16341. }
  16342. }
  16343. //debug(sourceEventType +" "+ eventType);
  16344. // on the end we reset everything
  16345. if(!count_touches) {
  16346. last_move_event = null;
  16347. enable_detect = false;
  16348. touch_triggered = false;
  16349. Hammer.PointerEvent.reset();
  16350. }
  16351. });
  16352. },
  16353. /**
  16354. * we have different events for each device/browser
  16355. * determine what we need and set them in the Hammer.EVENT_TYPES constant
  16356. */
  16357. determineEventTypes: function determineEventTypes() {
  16358. // determine the eventtype we want to set
  16359. var types;
  16360. // pointerEvents magic
  16361. if(Hammer.HAS_POINTEREVENTS) {
  16362. types = Hammer.PointerEvent.getEvents();
  16363. }
  16364. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  16365. else if(Hammer.NO_MOUSEEVENTS) {
  16366. types = [
  16367. 'touchstart',
  16368. 'touchmove',
  16369. 'touchend touchcancel'];
  16370. }
  16371. // for non pointer events browsers and mixed browsers,
  16372. // like chrome on windows8 touch laptop
  16373. else {
  16374. types = [
  16375. 'touchstart mousedown',
  16376. 'touchmove mousemove',
  16377. 'touchend touchcancel mouseup'];
  16378. }
  16379. Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0];
  16380. Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1];
  16381. Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2];
  16382. },
  16383. /**
  16384. * create touchlist depending on the event
  16385. * @param {Object} ev
  16386. * @param {String} eventType used by the fakemultitouch plugin
  16387. */
  16388. getTouchList: function getTouchList(ev/*, eventType*/) {
  16389. // get the fake pointerEvent touchlist
  16390. if(Hammer.HAS_POINTEREVENTS) {
  16391. return Hammer.PointerEvent.getTouchList();
  16392. }
  16393. // get the touchlist
  16394. else if(ev.touches) {
  16395. return ev.touches;
  16396. }
  16397. // make fake touchlist from mouse position
  16398. else {
  16399. return [{
  16400. identifier: 1,
  16401. pageX: ev.pageX,
  16402. pageY: ev.pageY,
  16403. target: ev.target
  16404. }];
  16405. }
  16406. },
  16407. /**
  16408. * collect event data for Hammer js
  16409. * @param {HTMLElement} element
  16410. * @param {String} eventType like Hammer.EVENT_MOVE
  16411. * @param {Object} eventData
  16412. */
  16413. collectEventData: function collectEventData(element, eventType, ev) {
  16414. var touches = this.getTouchList(ev, eventType);
  16415. // find out pointerType
  16416. var pointerType = Hammer.POINTER_TOUCH;
  16417. if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
  16418. pointerType = Hammer.POINTER_MOUSE;
  16419. }
  16420. return {
  16421. center : Hammer.utils.getCenter(touches),
  16422. timeStamp : new Date().getTime(),
  16423. target : ev.target,
  16424. touches : touches,
  16425. eventType : eventType,
  16426. pointerType : pointerType,
  16427. srcEvent : ev,
  16428. /**
  16429. * prevent the browser default actions
  16430. * mostly used to disable scrolling of the browser
  16431. */
  16432. preventDefault: function() {
  16433. if(this.srcEvent.preventManipulation) {
  16434. this.srcEvent.preventManipulation();
  16435. }
  16436. if(this.srcEvent.preventDefault) {
  16437. this.srcEvent.preventDefault();
  16438. }
  16439. },
  16440. /**
  16441. * stop bubbling the event up to its parents
  16442. */
  16443. stopPropagation: function() {
  16444. this.srcEvent.stopPropagation();
  16445. },
  16446. /**
  16447. * immediately stop gesture detection
  16448. * might be useful after a swipe was detected
  16449. * @return {*}
  16450. */
  16451. stopDetect: function() {
  16452. return Hammer.detection.stopDetect();
  16453. }
  16454. };
  16455. }
  16456. };
  16457. Hammer.PointerEvent = {
  16458. /**
  16459. * holds all pointers
  16460. * @type {Object}
  16461. */
  16462. pointers: {},
  16463. /**
  16464. * get a list of pointers
  16465. * @returns {Array} touchlist
  16466. */
  16467. getTouchList: function() {
  16468. var self = this;
  16469. var touchlist = [];
  16470. // we can use forEach since pointerEvents only is in IE10
  16471. Object.keys(self.pointers).sort().forEach(function(id) {
  16472. touchlist.push(self.pointers[id]);
  16473. });
  16474. return touchlist;
  16475. },
  16476. /**
  16477. * update the position of a pointer
  16478. * @param {String} type Hammer.EVENT_END
  16479. * @param {Object} pointerEvent
  16480. */
  16481. updatePointer: function(type, pointerEvent) {
  16482. if(type == Hammer.EVENT_END) {
  16483. this.pointers = {};
  16484. }
  16485. else {
  16486. pointerEvent.identifier = pointerEvent.pointerId;
  16487. this.pointers[pointerEvent.pointerId] = pointerEvent;
  16488. }
  16489. return Object.keys(this.pointers).length;
  16490. },
  16491. /**
  16492. * check if ev matches pointertype
  16493. * @param {String} pointerType Hammer.POINTER_MOUSE
  16494. * @param {PointerEvent} ev
  16495. */
  16496. matchType: function(pointerType, ev) {
  16497. if(!ev.pointerType) {
  16498. return false;
  16499. }
  16500. var types = {};
  16501. types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
  16502. types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
  16503. types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
  16504. return types[pointerType];
  16505. },
  16506. /**
  16507. * get events
  16508. */
  16509. getEvents: function() {
  16510. return [
  16511. 'pointerdown MSPointerDown',
  16512. 'pointermove MSPointerMove',
  16513. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  16514. ];
  16515. },
  16516. /**
  16517. * reset the list
  16518. */
  16519. reset: function() {
  16520. this.pointers = {};
  16521. }
  16522. };
  16523. Hammer.utils = {
  16524. /**
  16525. * extend method,
  16526. * also used for cloning when dest is an empty object
  16527. * @param {Object} dest
  16528. * @param {Object} src
  16529. * @parm {Boolean} merge do a merge
  16530. * @returns {Object} dest
  16531. */
  16532. extend: function extend(dest, src, merge) {
  16533. for (var key in src) {
  16534. if(dest[key] !== undefined && merge) {
  16535. continue;
  16536. }
  16537. dest[key] = src[key];
  16538. }
  16539. return dest;
  16540. },
  16541. /**
  16542. * find if a node is in the given parent
  16543. * used for event delegation tricks
  16544. * @param {HTMLElement} node
  16545. * @param {HTMLElement} parent
  16546. * @returns {boolean} has_parent
  16547. */
  16548. hasParent: function(node, parent) {
  16549. while(node){
  16550. if(node == parent) {
  16551. return true;
  16552. }
  16553. node = node.parentNode;
  16554. }
  16555. return false;
  16556. },
  16557. /**
  16558. * get the center of all the touches
  16559. * @param {Array} touches
  16560. * @returns {Object} center
  16561. */
  16562. getCenter: function getCenter(touches) {
  16563. var valuesX = [], valuesY = [];
  16564. for(var t= 0,len=touches.length; t<len; t++) {
  16565. valuesX.push(touches[t].pageX);
  16566. valuesY.push(touches[t].pageY);
  16567. }
  16568. return {
  16569. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  16570. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  16571. };
  16572. },
  16573. /**
  16574. * calculate the velocity between two points
  16575. * @param {Number} delta_time
  16576. * @param {Number} delta_x
  16577. * @param {Number} delta_y
  16578. * @returns {Object} velocity
  16579. */
  16580. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  16581. return {
  16582. x: Math.abs(delta_x / delta_time) || 0,
  16583. y: Math.abs(delta_y / delta_time) || 0
  16584. };
  16585. },
  16586. /**
  16587. * calculate the angle between two coordinates
  16588. * @param {Touch} touch1
  16589. * @param {Touch} touch2
  16590. * @returns {Number} angle
  16591. */
  16592. getAngle: function getAngle(touch1, touch2) {
  16593. var y = touch2.pageY - touch1.pageY,
  16594. x = touch2.pageX - touch1.pageX;
  16595. return Math.atan2(y, x) * 180 / Math.PI;
  16596. },
  16597. /**
  16598. * angle to direction define
  16599. * @param {Touch} touch1
  16600. * @param {Touch} touch2
  16601. * @returns {String} direction constant, like Hammer.DIRECTION_LEFT
  16602. */
  16603. getDirection: function getDirection(touch1, touch2) {
  16604. var x = Math.abs(touch1.pageX - touch2.pageX),
  16605. y = Math.abs(touch1.pageY - touch2.pageY);
  16606. if(x >= y) {
  16607. return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  16608. }
  16609. else {
  16610. return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  16611. }
  16612. },
  16613. /**
  16614. * calculate the distance between two touches
  16615. * @param {Touch} touch1
  16616. * @param {Touch} touch2
  16617. * @returns {Number} distance
  16618. */
  16619. getDistance: function getDistance(touch1, touch2) {
  16620. var x = touch2.pageX - touch1.pageX,
  16621. y = touch2.pageY - touch1.pageY;
  16622. return Math.sqrt((x*x) + (y*y));
  16623. },
  16624. /**
  16625. * calculate the scale factor between two touchLists (fingers)
  16626. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  16627. * @param {Array} start
  16628. * @param {Array} end
  16629. * @returns {Number} scale
  16630. */
  16631. getScale: function getScale(start, end) {
  16632. // need two fingers...
  16633. if(start.length >= 2 && end.length >= 2) {
  16634. return this.getDistance(end[0], end[1]) /
  16635. this.getDistance(start[0], start[1]);
  16636. }
  16637. return 1;
  16638. },
  16639. /**
  16640. * calculate the rotation degrees between two touchLists (fingers)
  16641. * @param {Array} start
  16642. * @param {Array} end
  16643. * @returns {Number} rotation
  16644. */
  16645. getRotation: function getRotation(start, end) {
  16646. // need two fingers
  16647. if(start.length >= 2 && end.length >= 2) {
  16648. return this.getAngle(end[1], end[0]) -
  16649. this.getAngle(start[1], start[0]);
  16650. }
  16651. return 0;
  16652. },
  16653. /**
  16654. * boolean if the direction is vertical
  16655. * @param {String} direction
  16656. * @returns {Boolean} is_vertical
  16657. */
  16658. isVertical: function isVertical(direction) {
  16659. return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
  16660. },
  16661. /**
  16662. * stop browser default behavior with css props
  16663. * @param {HtmlElement} element
  16664. * @param {Object} css_props
  16665. */
  16666. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
  16667. var prop,
  16668. vendors = ['webkit','khtml','moz','ms','o',''];
  16669. if(!css_props || !element.style) {
  16670. return;
  16671. }
  16672. // with css properties for modern browsers
  16673. for(var i = 0; i < vendors.length; i++) {
  16674. for(var p in css_props) {
  16675. if(css_props.hasOwnProperty(p)) {
  16676. prop = p;
  16677. // vender prefix at the property
  16678. if(vendors[i]) {
  16679. prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
  16680. }
  16681. // set the style
  16682. element.style[prop] = css_props[p];
  16683. }
  16684. }
  16685. }
  16686. // also the disable onselectstart
  16687. if(css_props.userSelect == 'none') {
  16688. element.onselectstart = function() {
  16689. return false;
  16690. };
  16691. }
  16692. }
  16693. };
  16694. Hammer.detection = {
  16695. // contains all registred Hammer.gestures in the correct order
  16696. gestures: [],
  16697. // data of the current Hammer.gesture detection session
  16698. current: null,
  16699. // the previous Hammer.gesture session data
  16700. // is a full clone of the previous gesture.current object
  16701. previous: null,
  16702. // when this becomes true, no gestures are fired
  16703. stopped: false,
  16704. /**
  16705. * start Hammer.gesture detection
  16706. * @param {Hammer.Instance} inst
  16707. * @param {Object} eventData
  16708. */
  16709. startDetect: function startDetect(inst, eventData) {
  16710. // already busy with a Hammer.gesture detection on an element
  16711. if(this.current) {
  16712. return;
  16713. }
  16714. this.stopped = false;
  16715. this.current = {
  16716. inst : inst, // reference to HammerInstance we're working for
  16717. startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
  16718. lastEvent : false, // last eventData
  16719. name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  16720. };
  16721. this.detect(eventData);
  16722. },
  16723. /**
  16724. * Hammer.gesture detection
  16725. * @param {Object} eventData
  16726. * @param {Object} eventData
  16727. */
  16728. detect: function detect(eventData) {
  16729. if(!this.current || this.stopped) {
  16730. return;
  16731. }
  16732. // extend event data with calculations about scale, distance etc
  16733. eventData = this.extendEventData(eventData);
  16734. // instance options
  16735. var inst_options = this.current.inst.options;
  16736. // call Hammer.gesture handlers
  16737. for(var g=0,len=this.gestures.length; g<len; g++) {
  16738. var gesture = this.gestures[g];
  16739. // only when the instance options have enabled this gesture
  16740. if(!this.stopped && inst_options[gesture.name] !== false) {
  16741. // if a handler returns false, we stop with the detection
  16742. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  16743. this.stopDetect();
  16744. break;
  16745. }
  16746. }
  16747. }
  16748. // store as previous event event
  16749. if(this.current) {
  16750. this.current.lastEvent = eventData;
  16751. }
  16752. // endevent, but not the last touch, so dont stop
  16753. if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
  16754. this.stopDetect();
  16755. }
  16756. return eventData;
  16757. },
  16758. /**
  16759. * clear the Hammer.gesture vars
  16760. * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
  16761. * to stop other Hammer.gestures from being fired
  16762. */
  16763. stopDetect: function stopDetect() {
  16764. // clone current data to the store as the previous gesture
  16765. // used for the double tap gesture, since this is an other gesture detect session
  16766. this.previous = Hammer.utils.extend({}, this.current);
  16767. // reset the current
  16768. this.current = null;
  16769. // stopped!
  16770. this.stopped = true;
  16771. },
  16772. /**
  16773. * extend eventData for Hammer.gestures
  16774. * @param {Object} ev
  16775. * @returns {Object} ev
  16776. */
  16777. extendEventData: function extendEventData(ev) {
  16778. var startEv = this.current.startEvent;
  16779. // if the touches change, set the new touches over the startEvent touches
  16780. // this because touchevents don't have all the touches on touchstart, or the
  16781. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  16782. // but, sometimes it happens that both fingers are touching at the EXACT same time
  16783. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  16784. // extend 1 level deep to get the touchlist with the touch objects
  16785. startEv.touches = [];
  16786. for(var i=0,len=ev.touches.length; i<len; i++) {
  16787. startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
  16788. }
  16789. }
  16790. var delta_time = ev.timeStamp - startEv.timeStamp,
  16791. delta_x = ev.center.pageX - startEv.center.pageX,
  16792. delta_y = ev.center.pageY - startEv.center.pageY,
  16793. velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);
  16794. Hammer.utils.extend(ev, {
  16795. deltaTime : delta_time,
  16796. deltaX : delta_x,
  16797. deltaY : delta_y,
  16798. velocityX : velocity.x,
  16799. velocityY : velocity.y,
  16800. distance : Hammer.utils.getDistance(startEv.center, ev.center),
  16801. angle : Hammer.utils.getAngle(startEv.center, ev.center),
  16802. direction : Hammer.utils.getDirection(startEv.center, ev.center),
  16803. scale : Hammer.utils.getScale(startEv.touches, ev.touches),
  16804. rotation : Hammer.utils.getRotation(startEv.touches, ev.touches),
  16805. startEvent : startEv
  16806. });
  16807. return ev;
  16808. },
  16809. /**
  16810. * register new gesture
  16811. * @param {Object} gesture object, see gestures.js for documentation
  16812. * @returns {Array} gestures
  16813. */
  16814. register: function register(gesture) {
  16815. // add an enable gesture options if there is no given
  16816. var options = gesture.defaults || {};
  16817. if(options[gesture.name] === undefined) {
  16818. options[gesture.name] = true;
  16819. }
  16820. // extend Hammer default options with the Hammer.gesture options
  16821. Hammer.utils.extend(Hammer.defaults, options, true);
  16822. // set its index
  16823. gesture.index = gesture.index || 1000;
  16824. // add Hammer.gesture to the list
  16825. this.gestures.push(gesture);
  16826. // sort the list by index
  16827. this.gestures.sort(function(a, b) {
  16828. if (a.index < b.index) {
  16829. return -1;
  16830. }
  16831. if (a.index > b.index) {
  16832. return 1;
  16833. }
  16834. return 0;
  16835. });
  16836. return this.gestures;
  16837. }
  16838. };
  16839. Hammer.gestures = Hammer.gestures || {};
  16840. /**
  16841. * Custom gestures
  16842. * ==============================
  16843. *
  16844. * Gesture object
  16845. * --------------------
  16846. * The object structure of a gesture:
  16847. *
  16848. * { name: 'mygesture',
  16849. * index: 1337,
  16850. * defaults: {
  16851. * mygesture_option: true
  16852. * }
  16853. * handler: function(type, ev, inst) {
  16854. * // trigger gesture event
  16855. * inst.trigger(this.name, ev);
  16856. * }
  16857. * }
  16858. * @param {String} name
  16859. * this should be the name of the gesture, lowercase
  16860. * it is also being used to disable/enable the gesture per instance config.
  16861. *
  16862. * @param {Number} [index=1000]
  16863. * the index of the gesture, where it is going to be in the stack of gestures detection
  16864. * like when you build an gesture that depends on the drag gesture, it is a good
  16865. * idea to place it after the index of the drag gesture.
  16866. *
  16867. * @param {Object} [defaults={}]
  16868. * the default settings of the gesture. these are added to the instance settings,
  16869. * and can be overruled per instance. you can also add the name of the gesture,
  16870. * but this is also added by default (and set to true).
  16871. *
  16872. * @param {Function} handler
  16873. * this handles the gesture detection of your custom gesture and receives the
  16874. * following arguments:
  16875. *
  16876. * @param {Object} eventData
  16877. * event data containing the following properties:
  16878. * timeStamp {Number} time the event occurred
  16879. * target {HTMLElement} target element
  16880. * touches {Array} touches (fingers, pointers, mouse) on the screen
  16881. * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
  16882. * center {Object} center position of the touches. contains pageX and pageY
  16883. * deltaTime {Number} the total time of the touches in the screen
  16884. * deltaX {Number} the delta on x axis we haved moved
  16885. * deltaY {Number} the delta on y axis we haved moved
  16886. * velocityX {Number} the velocity on the x
  16887. * velocityY {Number} the velocity on y
  16888. * angle {Number} the angle we are moving
  16889. * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
  16890. * distance {Number} the distance we haved moved
  16891. * scale {Number} scaling of the touches, needs 2 touches
  16892. * rotation {Number} rotation of the touches, needs 2 touches *
  16893. * eventType {String} matches Hammer.EVENT_START|MOVE|END
  16894. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  16895. * startEvent {Object} contains the same properties as above,
  16896. * but from the first touch. this is used to calculate
  16897. * distances, deltaTime, scaling etc
  16898. *
  16899. * @param {Hammer.Instance} inst
  16900. * the instance we are doing the detection for. you can get the options from
  16901. * the inst.options object and trigger the gesture event by calling inst.trigger
  16902. *
  16903. *
  16904. * Handle gestures
  16905. * --------------------
  16906. * inside the handler you can get/set Hammer.detection.current. This is the current
  16907. * detection session. It has the following properties
  16908. * @param {String} name
  16909. * contains the name of the gesture we have detected. it has not a real function,
  16910. * only to check in other gestures if something is detected.
  16911. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  16912. * check if the current gesture is 'drag' by accessing Hammer.detection.current.name
  16913. *
  16914. * @readonly
  16915. * @param {Hammer.Instance} inst
  16916. * the instance we do the detection for
  16917. *
  16918. * @readonly
  16919. * @param {Object} startEvent
  16920. * contains the properties of the first gesture detection in this session.
  16921. * Used for calculations about timing, distance, etc.
  16922. *
  16923. * @readonly
  16924. * @param {Object} lastEvent
  16925. * contains all the properties of the last gesture detect in this session.
  16926. *
  16927. * after the gesture detection session has been completed (user has released the screen)
  16928. * the Hammer.detection.current object is copied into Hammer.detection.previous,
  16929. * this is usefull for gestures like doubletap, where you need to know if the
  16930. * previous gesture was a tap
  16931. *
  16932. * options that have been set by the instance can be received by calling inst.options
  16933. *
  16934. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  16935. * The first param is the name of your gesture, the second the event argument
  16936. *
  16937. *
  16938. * Register gestures
  16939. * --------------------
  16940. * When an gesture is added to the Hammer.gestures object, it is auto registered
  16941. * at the setup of the first Hammer instance. You can also call Hammer.detection.register
  16942. * manually and pass your gesture object as a param
  16943. *
  16944. */
  16945. /**
  16946. * Hold
  16947. * Touch stays at the same place for x time
  16948. * @events hold
  16949. */
  16950. Hammer.gestures.Hold = {
  16951. name: 'hold',
  16952. index: 10,
  16953. defaults: {
  16954. hold_timeout : 500,
  16955. hold_threshold : 1
  16956. },
  16957. timer: null,
  16958. handler: function holdGesture(ev, inst) {
  16959. switch(ev.eventType) {
  16960. case Hammer.EVENT_START:
  16961. // clear any running timers
  16962. clearTimeout(this.timer);
  16963. // set the gesture so we can check in the timeout if it still is
  16964. Hammer.detection.current.name = this.name;
  16965. // set timer and if after the timeout it still is hold,
  16966. // we trigger the hold event
  16967. this.timer = setTimeout(function() {
  16968. if(Hammer.detection.current.name == 'hold') {
  16969. inst.trigger('hold', ev);
  16970. }
  16971. }, inst.options.hold_timeout);
  16972. break;
  16973. // when you move or end we clear the timer
  16974. case Hammer.EVENT_MOVE:
  16975. if(ev.distance > inst.options.hold_threshold) {
  16976. clearTimeout(this.timer);
  16977. }
  16978. break;
  16979. case Hammer.EVENT_END:
  16980. clearTimeout(this.timer);
  16981. break;
  16982. }
  16983. }
  16984. };
  16985. /**
  16986. * Tap/DoubleTap
  16987. * Quick touch at a place or double at the same place
  16988. * @events tap, doubletap
  16989. */
  16990. Hammer.gestures.Tap = {
  16991. name: 'tap',
  16992. index: 100,
  16993. defaults: {
  16994. tap_max_touchtime : 250,
  16995. tap_max_distance : 10,
  16996. tap_always : true,
  16997. doubletap_distance : 20,
  16998. doubletap_interval : 300
  16999. },
  17000. handler: function tapGesture(ev, inst) {
  17001. if(ev.eventType == Hammer.EVENT_END) {
  17002. // previous gesture, for the double tap since these are two different gesture detections
  17003. var prev = Hammer.detection.previous,
  17004. did_doubletap = false;
  17005. // when the touchtime is higher then the max touch time
  17006. // or when the moving distance is too much
  17007. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  17008. ev.distance > inst.options.tap_max_distance) {
  17009. return;
  17010. }
  17011. // check if double tap
  17012. if(prev && prev.name == 'tap' &&
  17013. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  17014. ev.distance < inst.options.doubletap_distance) {
  17015. inst.trigger('doubletap', ev);
  17016. did_doubletap = true;
  17017. }
  17018. // do a single tap
  17019. if(!did_doubletap || inst.options.tap_always) {
  17020. Hammer.detection.current.name = 'tap';
  17021. inst.trigger(Hammer.detection.current.name, ev);
  17022. }
  17023. }
  17024. }
  17025. };
  17026. /**
  17027. * Swipe
  17028. * triggers swipe events when the end velocity is above the threshold
  17029. * @events swipe, swipeleft, swiperight, swipeup, swipedown
  17030. */
  17031. Hammer.gestures.Swipe = {
  17032. name: 'swipe',
  17033. index: 40,
  17034. defaults: {
  17035. // set 0 for unlimited, but this can conflict with transform
  17036. swipe_max_touches : 1,
  17037. swipe_velocity : 0.7
  17038. },
  17039. handler: function swipeGesture(ev, inst) {
  17040. if(ev.eventType == Hammer.EVENT_END) {
  17041. // max touches
  17042. if(inst.options.swipe_max_touches > 0 &&
  17043. ev.touches.length > inst.options.swipe_max_touches) {
  17044. return;
  17045. }
  17046. // when the distance we moved is too small we skip this gesture
  17047. // or we can be already in dragging
  17048. if(ev.velocityX > inst.options.swipe_velocity ||
  17049. ev.velocityY > inst.options.swipe_velocity) {
  17050. // trigger swipe events
  17051. inst.trigger(this.name, ev);
  17052. inst.trigger(this.name + ev.direction, ev);
  17053. }
  17054. }
  17055. }
  17056. };
  17057. /**
  17058. * Drag
  17059. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  17060. * moving left and right is a good practice. When all the drag events are blocking
  17061. * you disable scrolling on that area.
  17062. * @events drag, drapleft, dragright, dragup, dragdown
  17063. */
  17064. Hammer.gestures.Drag = {
  17065. name: 'drag',
  17066. index: 50,
  17067. defaults: {
  17068. drag_min_distance : 10,
  17069. // set 0 for unlimited, but this can conflict with transform
  17070. drag_max_touches : 1,
  17071. // prevent default browser behavior when dragging occurs
  17072. // be careful with it, it makes the element a blocking element
  17073. // when you are using the drag gesture, it is a good practice to set this true
  17074. drag_block_horizontal : false,
  17075. drag_block_vertical : false,
  17076. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  17077. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  17078. drag_lock_to_axis : false,
  17079. // drag lock only kicks in when distance > drag_lock_min_distance
  17080. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  17081. drag_lock_min_distance : 25
  17082. },
  17083. triggered: false,
  17084. handler: function dragGesture(ev, inst) {
  17085. // current gesture isnt drag, but dragged is true
  17086. // this means an other gesture is busy. now call dragend
  17087. if(Hammer.detection.current.name != this.name && this.triggered) {
  17088. inst.trigger(this.name +'end', ev);
  17089. this.triggered = false;
  17090. return;
  17091. }
  17092. // max touches
  17093. if(inst.options.drag_max_touches > 0 &&
  17094. ev.touches.length > inst.options.drag_max_touches) {
  17095. return;
  17096. }
  17097. switch(ev.eventType) {
  17098. case Hammer.EVENT_START:
  17099. this.triggered = false;
  17100. break;
  17101. case Hammer.EVENT_MOVE:
  17102. // when the distance we moved is too small we skip this gesture
  17103. // or we can be already in dragging
  17104. if(ev.distance < inst.options.drag_min_distance &&
  17105. Hammer.detection.current.name != this.name) {
  17106. return;
  17107. }
  17108. // we are dragging!
  17109. Hammer.detection.current.name = this.name;
  17110. // lock drag to axis?
  17111. if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
  17112. ev.drag_locked_to_axis = true;
  17113. }
  17114. var last_direction = Hammer.detection.current.lastEvent.direction;
  17115. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  17116. // keep direction on the axis that the drag gesture started on
  17117. if(Hammer.utils.isVertical(last_direction)) {
  17118. ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
  17119. }
  17120. else {
  17121. ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
  17122. }
  17123. }
  17124. // first time, trigger dragstart event
  17125. if(!this.triggered) {
  17126. inst.trigger(this.name +'start', ev);
  17127. this.triggered = true;
  17128. }
  17129. // trigger normal event
  17130. inst.trigger(this.name, ev);
  17131. // direction event, like dragdown
  17132. inst.trigger(this.name + ev.direction, ev);
  17133. // block the browser events
  17134. if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
  17135. (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
  17136. ev.preventDefault();
  17137. }
  17138. break;
  17139. case Hammer.EVENT_END:
  17140. // trigger dragend
  17141. if(this.triggered) {
  17142. inst.trigger(this.name +'end', ev);
  17143. }
  17144. this.triggered = false;
  17145. break;
  17146. }
  17147. }
  17148. };
  17149. /**
  17150. * Transform
  17151. * User want to scale or rotate with 2 fingers
  17152. * @events transform, pinch, pinchin, pinchout, rotate
  17153. */
  17154. Hammer.gestures.Transform = {
  17155. name: 'transform',
  17156. index: 45,
  17157. defaults: {
  17158. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  17159. transform_min_scale : 0.01,
  17160. // rotation in degrees
  17161. transform_min_rotation : 1,
  17162. // prevent default browser behavior when two touches are on the screen
  17163. // but it makes the element a blocking element
  17164. // when you are using the transform gesture, it is a good practice to set this true
  17165. transform_always_block : false
  17166. },
  17167. triggered: false,
  17168. handler: function transformGesture(ev, inst) {
  17169. // current gesture isnt drag, but dragged is true
  17170. // this means an other gesture is busy. now call dragend
  17171. if(Hammer.detection.current.name != this.name && this.triggered) {
  17172. inst.trigger(this.name +'end', ev);
  17173. this.triggered = false;
  17174. return;
  17175. }
  17176. // atleast multitouch
  17177. if(ev.touches.length < 2) {
  17178. return;
  17179. }
  17180. // prevent default when two fingers are on the screen
  17181. if(inst.options.transform_always_block) {
  17182. ev.preventDefault();
  17183. }
  17184. switch(ev.eventType) {
  17185. case Hammer.EVENT_START:
  17186. this.triggered = false;
  17187. break;
  17188. case Hammer.EVENT_MOVE:
  17189. var scale_threshold = Math.abs(1-ev.scale);
  17190. var rotation_threshold = Math.abs(ev.rotation);
  17191. // when the distance we moved is too small we skip this gesture
  17192. // or we can be already in dragging
  17193. if(scale_threshold < inst.options.transform_min_scale &&
  17194. rotation_threshold < inst.options.transform_min_rotation) {
  17195. return;
  17196. }
  17197. // we are transforming!
  17198. Hammer.detection.current.name = this.name;
  17199. // first time, trigger dragstart event
  17200. if(!this.triggered) {
  17201. inst.trigger(this.name +'start', ev);
  17202. this.triggered = true;
  17203. }
  17204. inst.trigger(this.name, ev); // basic transform event
  17205. // trigger rotate event
  17206. if(rotation_threshold > inst.options.transform_min_rotation) {
  17207. inst.trigger('rotate', ev);
  17208. }
  17209. // trigger pinch event
  17210. if(scale_threshold > inst.options.transform_min_scale) {
  17211. inst.trigger('pinch', ev);
  17212. inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
  17213. }
  17214. break;
  17215. case Hammer.EVENT_END:
  17216. // trigger dragend
  17217. if(this.triggered) {
  17218. inst.trigger(this.name +'end', ev);
  17219. }
  17220. this.triggered = false;
  17221. break;
  17222. }
  17223. }
  17224. };
  17225. /**
  17226. * Touch
  17227. * Called as first, tells the user has touched the screen
  17228. * @events touch
  17229. */
  17230. Hammer.gestures.Touch = {
  17231. name: 'touch',
  17232. index: -Infinity,
  17233. defaults: {
  17234. // call preventDefault at touchstart, and makes the element blocking by
  17235. // disabling the scrolling of the page, but it improves gestures like
  17236. // transforming and dragging.
  17237. // be careful with using this, it can be very annoying for users to be stuck
  17238. // on the page
  17239. prevent_default: false,
  17240. // disable mouse events, so only touch (or pen!) input triggers events
  17241. prevent_mouseevents: false
  17242. },
  17243. handler: function touchGesture(ev, inst) {
  17244. if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
  17245. ev.stopDetect();
  17246. return;
  17247. }
  17248. if(inst.options.prevent_default) {
  17249. ev.preventDefault();
  17250. }
  17251. if(ev.eventType == Hammer.EVENT_START) {
  17252. inst.trigger(this.name, ev);
  17253. }
  17254. }
  17255. };
  17256. /**
  17257. * Release
  17258. * Called as last, tells the user has released the screen
  17259. * @events release
  17260. */
  17261. Hammer.gestures.Release = {
  17262. name: 'release',
  17263. index: Infinity,
  17264. handler: function releaseGesture(ev, inst) {
  17265. if(ev.eventType == Hammer.EVENT_END) {
  17266. inst.trigger(this.name, ev);
  17267. }
  17268. }
  17269. };
  17270. // node export
  17271. if(typeof module === 'object' && typeof module.exports === 'object'){
  17272. module.exports = Hammer;
  17273. }
  17274. // just window export
  17275. else {
  17276. window.Hammer = Hammer;
  17277. // requireJS module definition
  17278. if(typeof window.define === 'function' && window.define.amd) {
  17279. window.define('hammer', [], function() {
  17280. return Hammer;
  17281. });
  17282. }
  17283. }
  17284. })(this);
  17285. },{}],4:[function(require,module,exports){
  17286. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};//! moment.js
  17287. //! version : 2.6.0
  17288. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  17289. //! license : MIT
  17290. //! momentjs.com
  17291. (function (undefined) {
  17292. /************************************
  17293. Constants
  17294. ************************************/
  17295. var moment,
  17296. VERSION = "2.6.0",
  17297. // the global-scope this is NOT the global object in Node.js
  17298. globalScope = typeof global !== 'undefined' ? global : this,
  17299. oldGlobalMoment,
  17300. round = Math.round,
  17301. i,
  17302. YEAR = 0,
  17303. MONTH = 1,
  17304. DATE = 2,
  17305. HOUR = 3,
  17306. MINUTE = 4,
  17307. SECOND = 5,
  17308. MILLISECOND = 6,
  17309. // internal storage for language config files
  17310. languages = {},
  17311. // moment internal properties
  17312. momentProperties = {
  17313. _isAMomentObject: null,
  17314. _i : null,
  17315. _f : null,
  17316. _l : null,
  17317. _strict : null,
  17318. _isUTC : null,
  17319. _offset : null, // optional. Combine with _isUTC
  17320. _pf : null,
  17321. _lang : null // optional
  17322. },
  17323. // check for nodeJS
  17324. hasModule = (typeof module !== 'undefined' && module.exports),
  17325. // ASP.NET json date format regex
  17326. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  17327. aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
  17328. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  17329. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  17330. isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
  17331. // format tokens
  17332. formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,
  17333. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  17334. // parsing token regexes
  17335. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  17336. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  17337. parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
  17338. parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  17339. parseTokenDigits = /\d+/, // nonzero number of digits
  17340. 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.
  17341. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  17342. parseTokenT = /T/i, // T (ISO separator)
  17343. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  17344. parseTokenOrdinal = /\d{1,2}/,
  17345. //strict parsing regexes
  17346. parseTokenOneDigit = /\d/, // 0 - 9
  17347. parseTokenTwoDigits = /\d\d/, // 00 - 99
  17348. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  17349. parseTokenFourDigits = /\d{4}/, // 0000 - 9999
  17350. parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
  17351. parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
  17352. // iso 8601 regex
  17353. // 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)
  17354. 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)?)?$/,
  17355. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  17356. isoDates = [
  17357. ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
  17358. ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
  17359. ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
  17360. ['GGGG-[W]WW', /\d{4}-W\d{2}/],
  17361. ['YYYY-DDD', /\d{4}-\d{3}/]
  17362. ],
  17363. // iso time formats and regexes
  17364. isoTimes = [
  17365. ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
  17366. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  17367. ['HH:mm', /(T| )\d\d:\d\d/],
  17368. ['HH', /(T| )\d\d/]
  17369. ],
  17370. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  17371. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  17372. // getter and setter names
  17373. proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  17374. unitMillisecondFactors = {
  17375. 'Milliseconds' : 1,
  17376. 'Seconds' : 1e3,
  17377. 'Minutes' : 6e4,
  17378. 'Hours' : 36e5,
  17379. 'Days' : 864e5,
  17380. 'Months' : 2592e6,
  17381. 'Years' : 31536e6
  17382. },
  17383. unitAliases = {
  17384. ms : 'millisecond',
  17385. s : 'second',
  17386. m : 'minute',
  17387. h : 'hour',
  17388. d : 'day',
  17389. D : 'date',
  17390. w : 'week',
  17391. W : 'isoWeek',
  17392. M : 'month',
  17393. Q : 'quarter',
  17394. y : 'year',
  17395. DDD : 'dayOfYear',
  17396. e : 'weekday',
  17397. E : 'isoWeekday',
  17398. gg: 'weekYear',
  17399. GG: 'isoWeekYear'
  17400. },
  17401. camelFunctions = {
  17402. dayofyear : 'dayOfYear',
  17403. isoweekday : 'isoWeekday',
  17404. isoweek : 'isoWeek',
  17405. weekyear : 'weekYear',
  17406. isoweekyear : 'isoWeekYear'
  17407. },
  17408. // format function strings
  17409. formatFunctions = {},
  17410. // tokens to ordinalize and pad
  17411. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  17412. paddedTokens = 'M D H h m s w W'.split(' '),
  17413. formatTokenFunctions = {
  17414. M : function () {
  17415. return this.month() + 1;
  17416. },
  17417. MMM : function (format) {
  17418. return this.lang().monthsShort(this, format);
  17419. },
  17420. MMMM : function (format) {
  17421. return this.lang().months(this, format);
  17422. },
  17423. D : function () {
  17424. return this.date();
  17425. },
  17426. DDD : function () {
  17427. return this.dayOfYear();
  17428. },
  17429. d : function () {
  17430. return this.day();
  17431. },
  17432. dd : function (format) {
  17433. return this.lang().weekdaysMin(this, format);
  17434. },
  17435. ddd : function (format) {
  17436. return this.lang().weekdaysShort(this, format);
  17437. },
  17438. dddd : function (format) {
  17439. return this.lang().weekdays(this, format);
  17440. },
  17441. w : function () {
  17442. return this.week();
  17443. },
  17444. W : function () {
  17445. return this.isoWeek();
  17446. },
  17447. YY : function () {
  17448. return leftZeroFill(this.year() % 100, 2);
  17449. },
  17450. YYYY : function () {
  17451. return leftZeroFill(this.year(), 4);
  17452. },
  17453. YYYYY : function () {
  17454. return leftZeroFill(this.year(), 5);
  17455. },
  17456. YYYYYY : function () {
  17457. var y = this.year(), sign = y >= 0 ? '+' : '-';
  17458. return sign + leftZeroFill(Math.abs(y), 6);
  17459. },
  17460. gg : function () {
  17461. return leftZeroFill(this.weekYear() % 100, 2);
  17462. },
  17463. gggg : function () {
  17464. return leftZeroFill(this.weekYear(), 4);
  17465. },
  17466. ggggg : function () {
  17467. return leftZeroFill(this.weekYear(), 5);
  17468. },
  17469. GG : function () {
  17470. return leftZeroFill(this.isoWeekYear() % 100, 2);
  17471. },
  17472. GGGG : function () {
  17473. return leftZeroFill(this.isoWeekYear(), 4);
  17474. },
  17475. GGGGG : function () {
  17476. return leftZeroFill(this.isoWeekYear(), 5);
  17477. },
  17478. e : function () {
  17479. return this.weekday();
  17480. },
  17481. E : function () {
  17482. return this.isoWeekday();
  17483. },
  17484. a : function () {
  17485. return this.lang().meridiem(this.hours(), this.minutes(), true);
  17486. },
  17487. A : function () {
  17488. return this.lang().meridiem(this.hours(), this.minutes(), false);
  17489. },
  17490. H : function () {
  17491. return this.hours();
  17492. },
  17493. h : function () {
  17494. return this.hours() % 12 || 12;
  17495. },
  17496. m : function () {
  17497. return this.minutes();
  17498. },
  17499. s : function () {
  17500. return this.seconds();
  17501. },
  17502. S : function () {
  17503. return toInt(this.milliseconds() / 100);
  17504. },
  17505. SS : function () {
  17506. return leftZeroFill(toInt(this.milliseconds() / 10), 2);
  17507. },
  17508. SSS : function () {
  17509. return leftZeroFill(this.milliseconds(), 3);
  17510. },
  17511. SSSS : function () {
  17512. return leftZeroFill(this.milliseconds(), 3);
  17513. },
  17514. Z : function () {
  17515. var a = -this.zone(),
  17516. b = "+";
  17517. if (a < 0) {
  17518. a = -a;
  17519. b = "-";
  17520. }
  17521. return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
  17522. },
  17523. ZZ : function () {
  17524. var a = -this.zone(),
  17525. b = "+";
  17526. if (a < 0) {
  17527. a = -a;
  17528. b = "-";
  17529. }
  17530. return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
  17531. },
  17532. z : function () {
  17533. return this.zoneAbbr();
  17534. },
  17535. zz : function () {
  17536. return this.zoneName();
  17537. },
  17538. X : function () {
  17539. return this.unix();
  17540. },
  17541. Q : function () {
  17542. return this.quarter();
  17543. }
  17544. },
  17545. lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
  17546. function defaultParsingFlags() {
  17547. // We need to deep clone this object, and es5 standard is not very
  17548. // helpful.
  17549. return {
  17550. empty : false,
  17551. unusedTokens : [],
  17552. unusedInput : [],
  17553. overflow : -2,
  17554. charsLeftOver : 0,
  17555. nullInput : false,
  17556. invalidMonth : null,
  17557. invalidFormat : false,
  17558. userInvalidated : false,
  17559. iso: false
  17560. };
  17561. }
  17562. function deprecate(msg, fn) {
  17563. var firstTime = true;
  17564. function printMsg() {
  17565. if (moment.suppressDeprecationWarnings === false &&
  17566. typeof console !== 'undefined' && console.warn) {
  17567. console.warn("Deprecation warning: " + msg);
  17568. }
  17569. }
  17570. return extend(function () {
  17571. if (firstTime) {
  17572. printMsg();
  17573. firstTime = false;
  17574. }
  17575. return fn.apply(this, arguments);
  17576. }, fn);
  17577. }
  17578. function padToken(func, count) {
  17579. return function (a) {
  17580. return leftZeroFill(func.call(this, a), count);
  17581. };
  17582. }
  17583. function ordinalizeToken(func, period) {
  17584. return function (a) {
  17585. return this.lang().ordinal(func.call(this, a), period);
  17586. };
  17587. }
  17588. while (ordinalizeTokens.length) {
  17589. i = ordinalizeTokens.pop();
  17590. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
  17591. }
  17592. while (paddedTokens.length) {
  17593. i = paddedTokens.pop();
  17594. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  17595. }
  17596. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  17597. /************************************
  17598. Constructors
  17599. ************************************/
  17600. function Language() {
  17601. }
  17602. // Moment prototype object
  17603. function Moment(config) {
  17604. checkOverflow(config);
  17605. extend(this, config);
  17606. }
  17607. // Duration Constructor
  17608. function Duration(duration) {
  17609. var normalizedInput = normalizeObjectUnits(duration),
  17610. years = normalizedInput.year || 0,
  17611. quarters = normalizedInput.quarter || 0,
  17612. months = normalizedInput.month || 0,
  17613. weeks = normalizedInput.week || 0,
  17614. days = normalizedInput.day || 0,
  17615. hours = normalizedInput.hour || 0,
  17616. minutes = normalizedInput.minute || 0,
  17617. seconds = normalizedInput.second || 0,
  17618. milliseconds = normalizedInput.millisecond || 0;
  17619. // representation for dateAddRemove
  17620. this._milliseconds = +milliseconds +
  17621. seconds * 1e3 + // 1000
  17622. minutes * 6e4 + // 1000 * 60
  17623. hours * 36e5; // 1000 * 60 * 60
  17624. // Because of dateAddRemove treats 24 hours as different from a
  17625. // day when working around DST, we need to store them separately
  17626. this._days = +days +
  17627. weeks * 7;
  17628. // It is impossible translate months into days without knowing
  17629. // which months you are are talking about, so we have to store
  17630. // it separately.
  17631. this._months = +months +
  17632. quarters * 3 +
  17633. years * 12;
  17634. this._data = {};
  17635. this._bubble();
  17636. }
  17637. /************************************
  17638. Helpers
  17639. ************************************/
  17640. function extend(a, b) {
  17641. for (var i in b) {
  17642. if (b.hasOwnProperty(i)) {
  17643. a[i] = b[i];
  17644. }
  17645. }
  17646. if (b.hasOwnProperty("toString")) {
  17647. a.toString = b.toString;
  17648. }
  17649. if (b.hasOwnProperty("valueOf")) {
  17650. a.valueOf = b.valueOf;
  17651. }
  17652. return a;
  17653. }
  17654. function cloneMoment(m) {
  17655. var result = {}, i;
  17656. for (i in m) {
  17657. if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
  17658. result[i] = m[i];
  17659. }
  17660. }
  17661. return result;
  17662. }
  17663. function absRound(number) {
  17664. if (number < 0) {
  17665. return Math.ceil(number);
  17666. } else {
  17667. return Math.floor(number);
  17668. }
  17669. }
  17670. // left zero fill a number
  17671. // see http://jsperf.com/left-zero-filling for performance comparison
  17672. function leftZeroFill(number, targetLength, forceSign) {
  17673. var output = '' + Math.abs(number),
  17674. sign = number >= 0;
  17675. while (output.length < targetLength) {
  17676. output = '0' + output;
  17677. }
  17678. return (sign ? (forceSign ? '+' : '') : '-') + output;
  17679. }
  17680. // helper function for _.addTime and _.subtractTime
  17681. function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
  17682. var milliseconds = duration._milliseconds,
  17683. days = duration._days,
  17684. months = duration._months;
  17685. updateOffset = updateOffset == null ? true : updateOffset;
  17686. if (milliseconds) {
  17687. mom._d.setTime(+mom._d + milliseconds * isAdding);
  17688. }
  17689. if (days) {
  17690. rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
  17691. }
  17692. if (months) {
  17693. rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
  17694. }
  17695. if (updateOffset) {
  17696. moment.updateOffset(mom, days || months);
  17697. }
  17698. }
  17699. // check if is an array
  17700. function isArray(input) {
  17701. return Object.prototype.toString.call(input) === '[object Array]';
  17702. }
  17703. function isDate(input) {
  17704. return Object.prototype.toString.call(input) === '[object Date]' ||
  17705. input instanceof Date;
  17706. }
  17707. // compare two arrays, return the number of differences
  17708. function compareArrays(array1, array2, dontConvert) {
  17709. var len = Math.min(array1.length, array2.length),
  17710. lengthDiff = Math.abs(array1.length - array2.length),
  17711. diffs = 0,
  17712. i;
  17713. for (i = 0; i < len; i++) {
  17714. if ((dontConvert && array1[i] !== array2[i]) ||
  17715. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  17716. diffs++;
  17717. }
  17718. }
  17719. return diffs + lengthDiff;
  17720. }
  17721. function normalizeUnits(units) {
  17722. if (units) {
  17723. var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
  17724. units = unitAliases[units] || camelFunctions[lowered] || lowered;
  17725. }
  17726. return units;
  17727. }
  17728. function normalizeObjectUnits(inputObject) {
  17729. var normalizedInput = {},
  17730. normalizedProp,
  17731. prop;
  17732. for (prop in inputObject) {
  17733. if (inputObject.hasOwnProperty(prop)) {
  17734. normalizedProp = normalizeUnits(prop);
  17735. if (normalizedProp) {
  17736. normalizedInput[normalizedProp] = inputObject[prop];
  17737. }
  17738. }
  17739. }
  17740. return normalizedInput;
  17741. }
  17742. function makeList(field) {
  17743. var count, setter;
  17744. if (field.indexOf('week') === 0) {
  17745. count = 7;
  17746. setter = 'day';
  17747. }
  17748. else if (field.indexOf('month') === 0) {
  17749. count = 12;
  17750. setter = 'month';
  17751. }
  17752. else {
  17753. return;
  17754. }
  17755. moment[field] = function (format, index) {
  17756. var i, getter,
  17757. method = moment.fn._lang[field],
  17758. results = [];
  17759. if (typeof format === 'number') {
  17760. index = format;
  17761. format = undefined;
  17762. }
  17763. getter = function (i) {
  17764. var m = moment().utc().set(setter, i);
  17765. return method.call(moment.fn._lang, m, format || '');
  17766. };
  17767. if (index != null) {
  17768. return getter(index);
  17769. }
  17770. else {
  17771. for (i = 0; i < count; i++) {
  17772. results.push(getter(i));
  17773. }
  17774. return results;
  17775. }
  17776. };
  17777. }
  17778. function toInt(argumentForCoercion) {
  17779. var coercedNumber = +argumentForCoercion,
  17780. value = 0;
  17781. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  17782. if (coercedNumber >= 0) {
  17783. value = Math.floor(coercedNumber);
  17784. } else {
  17785. value = Math.ceil(coercedNumber);
  17786. }
  17787. }
  17788. return value;
  17789. }
  17790. function daysInMonth(year, month) {
  17791. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  17792. }
  17793. function weeksInYear(year, dow, doy) {
  17794. return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
  17795. }
  17796. function daysInYear(year) {
  17797. return isLeapYear(year) ? 366 : 365;
  17798. }
  17799. function isLeapYear(year) {
  17800. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  17801. }
  17802. function checkOverflow(m) {
  17803. var overflow;
  17804. if (m._a && m._pf.overflow === -2) {
  17805. overflow =
  17806. m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
  17807. m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
  17808. m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
  17809. m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
  17810. m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
  17811. m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
  17812. -1;
  17813. if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  17814. overflow = DATE;
  17815. }
  17816. m._pf.overflow = overflow;
  17817. }
  17818. }
  17819. function isValid(m) {
  17820. if (m._isValid == null) {
  17821. m._isValid = !isNaN(m._d.getTime()) &&
  17822. m._pf.overflow < 0 &&
  17823. !m._pf.empty &&
  17824. !m._pf.invalidMonth &&
  17825. !m._pf.nullInput &&
  17826. !m._pf.invalidFormat &&
  17827. !m._pf.userInvalidated;
  17828. if (m._strict) {
  17829. m._isValid = m._isValid &&
  17830. m._pf.charsLeftOver === 0 &&
  17831. m._pf.unusedTokens.length === 0;
  17832. }
  17833. }
  17834. return m._isValid;
  17835. }
  17836. function normalizeLanguage(key) {
  17837. return key ? key.toLowerCase().replace('_', '-') : key;
  17838. }
  17839. // Return a moment from input, that is local/utc/zone equivalent to model.
  17840. function makeAs(input, model) {
  17841. return model._isUTC ? moment(input).zone(model._offset || 0) :
  17842. moment(input).local();
  17843. }
  17844. /************************************
  17845. Languages
  17846. ************************************/
  17847. extend(Language.prototype, {
  17848. set : function (config) {
  17849. var prop, i;
  17850. for (i in config) {
  17851. prop = config[i];
  17852. if (typeof prop === 'function') {
  17853. this[i] = prop;
  17854. } else {
  17855. this['_' + i] = prop;
  17856. }
  17857. }
  17858. },
  17859. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  17860. months : function (m) {
  17861. return this._months[m.month()];
  17862. },
  17863. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  17864. monthsShort : function (m) {
  17865. return this._monthsShort[m.month()];
  17866. },
  17867. monthsParse : function (monthName) {
  17868. var i, mom, regex;
  17869. if (!this._monthsParse) {
  17870. this._monthsParse = [];
  17871. }
  17872. for (i = 0; i < 12; i++) {
  17873. // make the regex if we don't have it already
  17874. if (!this._monthsParse[i]) {
  17875. mom = moment.utc([2000, i]);
  17876. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  17877. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17878. }
  17879. // test the regex
  17880. if (this._monthsParse[i].test(monthName)) {
  17881. return i;
  17882. }
  17883. }
  17884. },
  17885. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  17886. weekdays : function (m) {
  17887. return this._weekdays[m.day()];
  17888. },
  17889. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  17890. weekdaysShort : function (m) {
  17891. return this._weekdaysShort[m.day()];
  17892. },
  17893. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  17894. weekdaysMin : function (m) {
  17895. return this._weekdaysMin[m.day()];
  17896. },
  17897. weekdaysParse : function (weekdayName) {
  17898. var i, mom, regex;
  17899. if (!this._weekdaysParse) {
  17900. this._weekdaysParse = [];
  17901. }
  17902. for (i = 0; i < 7; i++) {
  17903. // make the regex if we don't have it already
  17904. if (!this._weekdaysParse[i]) {
  17905. mom = moment([2000, 1]).day(i);
  17906. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  17907. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  17908. }
  17909. // test the regex
  17910. if (this._weekdaysParse[i].test(weekdayName)) {
  17911. return i;
  17912. }
  17913. }
  17914. },
  17915. _longDateFormat : {
  17916. LT : "h:mm A",
  17917. L : "MM/DD/YYYY",
  17918. LL : "MMMM D YYYY",
  17919. LLL : "MMMM D YYYY LT",
  17920. LLLL : "dddd, MMMM D YYYY LT"
  17921. },
  17922. longDateFormat : function (key) {
  17923. var output = this._longDateFormat[key];
  17924. if (!output && this._longDateFormat[key.toUpperCase()]) {
  17925. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  17926. return val.slice(1);
  17927. });
  17928. this._longDateFormat[key] = output;
  17929. }
  17930. return output;
  17931. },
  17932. isPM : function (input) {
  17933. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  17934. // Using charAt should be more compatible.
  17935. return ((input + '').toLowerCase().charAt(0) === 'p');
  17936. },
  17937. _meridiemParse : /[ap]\.?m?\.?/i,
  17938. meridiem : function (hours, minutes, isLower) {
  17939. if (hours > 11) {
  17940. return isLower ? 'pm' : 'PM';
  17941. } else {
  17942. return isLower ? 'am' : 'AM';
  17943. }
  17944. },
  17945. _calendar : {
  17946. sameDay : '[Today at] LT',
  17947. nextDay : '[Tomorrow at] LT',
  17948. nextWeek : 'dddd [at] LT',
  17949. lastDay : '[Yesterday at] LT',
  17950. lastWeek : '[Last] dddd [at] LT',
  17951. sameElse : 'L'
  17952. },
  17953. calendar : function (key, mom) {
  17954. var output = this._calendar[key];
  17955. return typeof output === 'function' ? output.apply(mom) : output;
  17956. },
  17957. _relativeTime : {
  17958. future : "in %s",
  17959. past : "%s ago",
  17960. s : "a few seconds",
  17961. m : "a minute",
  17962. mm : "%d minutes",
  17963. h : "an hour",
  17964. hh : "%d hours",
  17965. d : "a day",
  17966. dd : "%d days",
  17967. M : "a month",
  17968. MM : "%d months",
  17969. y : "a year",
  17970. yy : "%d years"
  17971. },
  17972. relativeTime : function (number, withoutSuffix, string, isFuture) {
  17973. var output = this._relativeTime[string];
  17974. return (typeof output === 'function') ?
  17975. output(number, withoutSuffix, string, isFuture) :
  17976. output.replace(/%d/i, number);
  17977. },
  17978. pastFuture : function (diff, output) {
  17979. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  17980. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  17981. },
  17982. ordinal : function (number) {
  17983. return this._ordinal.replace("%d", number);
  17984. },
  17985. _ordinal : "%d",
  17986. preparse : function (string) {
  17987. return string;
  17988. },
  17989. postformat : function (string) {
  17990. return string;
  17991. },
  17992. week : function (mom) {
  17993. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  17994. },
  17995. _week : {
  17996. dow : 0, // Sunday is the first day of the week.
  17997. doy : 6 // The week that contains Jan 1st is the first week of the year.
  17998. },
  17999. _invalidDate: 'Invalid date',
  18000. invalidDate: function () {
  18001. return this._invalidDate;
  18002. }
  18003. });
  18004. // Loads a language definition into the `languages` cache. The function
  18005. // takes a key and optionally values. If not in the browser and no values
  18006. // are provided, it will load the language file module. As a convenience,
  18007. // this function also returns the language values.
  18008. function loadLang(key, values) {
  18009. values.abbr = key;
  18010. if (!languages[key]) {
  18011. languages[key] = new Language();
  18012. }
  18013. languages[key].set(values);
  18014. return languages[key];
  18015. }
  18016. // Remove a language from the `languages` cache. Mostly useful in tests.
  18017. function unloadLang(key) {
  18018. delete languages[key];
  18019. }
  18020. // Determines which language definition to use and returns it.
  18021. //
  18022. // With no parameters, it will return the global language. If you
  18023. // pass in a language key, such as 'en', it will return the
  18024. // definition for 'en', so long as 'en' has already been loaded using
  18025. // moment.lang.
  18026. function getLangDefinition(key) {
  18027. var i = 0, j, lang, next, split,
  18028. get = function (k) {
  18029. if (!languages[k] && hasModule) {
  18030. try {
  18031. require('./lang/' + k);
  18032. } catch (e) { }
  18033. }
  18034. return languages[k];
  18035. };
  18036. if (!key) {
  18037. return moment.fn._lang;
  18038. }
  18039. if (!isArray(key)) {
  18040. //short-circuit everything else
  18041. lang = get(key);
  18042. if (lang) {
  18043. return lang;
  18044. }
  18045. key = [key];
  18046. }
  18047. //pick the language from the array
  18048. //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  18049. //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  18050. while (i < key.length) {
  18051. split = normalizeLanguage(key[i]).split('-');
  18052. j = split.length;
  18053. next = normalizeLanguage(key[i + 1]);
  18054. next = next ? next.split('-') : null;
  18055. while (j > 0) {
  18056. lang = get(split.slice(0, j).join('-'));
  18057. if (lang) {
  18058. return lang;
  18059. }
  18060. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  18061. //the next array item is better than a shallower substring of this one
  18062. break;
  18063. }
  18064. j--;
  18065. }
  18066. i++;
  18067. }
  18068. return moment.fn._lang;
  18069. }
  18070. /************************************
  18071. Formatting
  18072. ************************************/
  18073. function removeFormattingTokens(input) {
  18074. if (input.match(/\[[\s\S]/)) {
  18075. return input.replace(/^\[|\]$/g, "");
  18076. }
  18077. return input.replace(/\\/g, "");
  18078. }
  18079. function makeFormatFunction(format) {
  18080. var array = format.match(formattingTokens), i, length;
  18081. for (i = 0, length = array.length; i < length; i++) {
  18082. if (formatTokenFunctions[array[i]]) {
  18083. array[i] = formatTokenFunctions[array[i]];
  18084. } else {
  18085. array[i] = removeFormattingTokens(array[i]);
  18086. }
  18087. }
  18088. return function (mom) {
  18089. var output = "";
  18090. for (i = 0; i < length; i++) {
  18091. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  18092. }
  18093. return output;
  18094. };
  18095. }
  18096. // format date using native date object
  18097. function formatMoment(m, format) {
  18098. if (!m.isValid()) {
  18099. return m.lang().invalidDate();
  18100. }
  18101. format = expandFormat(format, m.lang());
  18102. if (!formatFunctions[format]) {
  18103. formatFunctions[format] = makeFormatFunction(format);
  18104. }
  18105. return formatFunctions[format](m);
  18106. }
  18107. function expandFormat(format, lang) {
  18108. var i = 5;
  18109. function replaceLongDateFormatTokens(input) {
  18110. return lang.longDateFormat(input) || input;
  18111. }
  18112. localFormattingTokens.lastIndex = 0;
  18113. while (i >= 0 && localFormattingTokens.test(format)) {
  18114. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  18115. localFormattingTokens.lastIndex = 0;
  18116. i -= 1;
  18117. }
  18118. return format;
  18119. }
  18120. /************************************
  18121. Parsing
  18122. ************************************/
  18123. // get the regex to find the next token
  18124. function getParseRegexForToken(token, config) {
  18125. var a, strict = config._strict;
  18126. switch (token) {
  18127. case 'Q':
  18128. return parseTokenOneDigit;
  18129. case 'DDDD':
  18130. return parseTokenThreeDigits;
  18131. case 'YYYY':
  18132. case 'GGGG':
  18133. case 'gggg':
  18134. return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
  18135. case 'Y':
  18136. case 'G':
  18137. case 'g':
  18138. return parseTokenSignedNumber;
  18139. case 'YYYYYY':
  18140. case 'YYYYY':
  18141. case 'GGGGG':
  18142. case 'ggggg':
  18143. return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
  18144. case 'S':
  18145. if (strict) { return parseTokenOneDigit; }
  18146. /* falls through */
  18147. case 'SS':
  18148. if (strict) { return parseTokenTwoDigits; }
  18149. /* falls through */
  18150. case 'SSS':
  18151. if (strict) { return parseTokenThreeDigits; }
  18152. /* falls through */
  18153. case 'DDD':
  18154. return parseTokenOneToThreeDigits;
  18155. case 'MMM':
  18156. case 'MMMM':
  18157. case 'dd':
  18158. case 'ddd':
  18159. case 'dddd':
  18160. return parseTokenWord;
  18161. case 'a':
  18162. case 'A':
  18163. return getLangDefinition(config._l)._meridiemParse;
  18164. case 'X':
  18165. return parseTokenTimestampMs;
  18166. case 'Z':
  18167. case 'ZZ':
  18168. return parseTokenTimezone;
  18169. case 'T':
  18170. return parseTokenT;
  18171. case 'SSSS':
  18172. return parseTokenDigits;
  18173. case 'MM':
  18174. case 'DD':
  18175. case 'YY':
  18176. case 'GG':
  18177. case 'gg':
  18178. case 'HH':
  18179. case 'hh':
  18180. case 'mm':
  18181. case 'ss':
  18182. case 'ww':
  18183. case 'WW':
  18184. return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
  18185. case 'M':
  18186. case 'D':
  18187. case 'd':
  18188. case 'H':
  18189. case 'h':
  18190. case 'm':
  18191. case 's':
  18192. case 'w':
  18193. case 'W':
  18194. case 'e':
  18195. case 'E':
  18196. return parseTokenOneOrTwoDigits;
  18197. case 'Do':
  18198. return parseTokenOrdinal;
  18199. default :
  18200. a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
  18201. return a;
  18202. }
  18203. }
  18204. function timezoneMinutesFromString(string) {
  18205. string = string || "";
  18206. var possibleTzMatches = (string.match(parseTokenTimezone) || []),
  18207. tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
  18208. parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
  18209. minutes = +(parts[1] * 60) + toInt(parts[2]);
  18210. return parts[0] === '+' ? -minutes : minutes;
  18211. }
  18212. // function to convert string input to date
  18213. function addTimeToArrayFromToken(token, input, config) {
  18214. var a, datePartArray = config._a;
  18215. switch (token) {
  18216. // QUARTER
  18217. case 'Q':
  18218. if (input != null) {
  18219. datePartArray[MONTH] = (toInt(input) - 1) * 3;
  18220. }
  18221. break;
  18222. // MONTH
  18223. case 'M' : // fall through to MM
  18224. case 'MM' :
  18225. if (input != null) {
  18226. datePartArray[MONTH] = toInt(input) - 1;
  18227. }
  18228. break;
  18229. case 'MMM' : // fall through to MMMM
  18230. case 'MMMM' :
  18231. a = getLangDefinition(config._l).monthsParse(input);
  18232. // if we didn't find a month name, mark the date as invalid.
  18233. if (a != null) {
  18234. datePartArray[MONTH] = a;
  18235. } else {
  18236. config._pf.invalidMonth = input;
  18237. }
  18238. break;
  18239. // DAY OF MONTH
  18240. case 'D' : // fall through to DD
  18241. case 'DD' :
  18242. if (input != null) {
  18243. datePartArray[DATE] = toInt(input);
  18244. }
  18245. break;
  18246. case 'Do' :
  18247. if (input != null) {
  18248. datePartArray[DATE] = toInt(parseInt(input, 10));
  18249. }
  18250. break;
  18251. // DAY OF YEAR
  18252. case 'DDD' : // fall through to DDDD
  18253. case 'DDDD' :
  18254. if (input != null) {
  18255. config._dayOfYear = toInt(input);
  18256. }
  18257. break;
  18258. // YEAR
  18259. case 'YY' :
  18260. datePartArray[YEAR] = moment.parseTwoDigitYear(input);
  18261. break;
  18262. case 'YYYY' :
  18263. case 'YYYYY' :
  18264. case 'YYYYYY' :
  18265. datePartArray[YEAR] = toInt(input);
  18266. break;
  18267. // AM / PM
  18268. case 'a' : // fall through to A
  18269. case 'A' :
  18270. config._isPm = getLangDefinition(config._l).isPM(input);
  18271. break;
  18272. // 24 HOUR
  18273. case 'H' : // fall through to hh
  18274. case 'HH' : // fall through to hh
  18275. case 'h' : // fall through to hh
  18276. case 'hh' :
  18277. datePartArray[HOUR] = toInt(input);
  18278. break;
  18279. // MINUTE
  18280. case 'm' : // fall through to mm
  18281. case 'mm' :
  18282. datePartArray[MINUTE] = toInt(input);
  18283. break;
  18284. // SECOND
  18285. case 's' : // fall through to ss
  18286. case 'ss' :
  18287. datePartArray[SECOND] = toInt(input);
  18288. break;
  18289. // MILLISECOND
  18290. case 'S' :
  18291. case 'SS' :
  18292. case 'SSS' :
  18293. case 'SSSS' :
  18294. datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
  18295. break;
  18296. // UNIX TIMESTAMP WITH MS
  18297. case 'X':
  18298. config._d = new Date(parseFloat(input) * 1000);
  18299. break;
  18300. // TIMEZONE
  18301. case 'Z' : // fall through to ZZ
  18302. case 'ZZ' :
  18303. config._useUTC = true;
  18304. config._tzm = timezoneMinutesFromString(input);
  18305. break;
  18306. case 'w':
  18307. case 'ww':
  18308. case 'W':
  18309. case 'WW':
  18310. case 'd':
  18311. case 'dd':
  18312. case 'ddd':
  18313. case 'dddd':
  18314. case 'e':
  18315. case 'E':
  18316. token = token.substr(0, 1);
  18317. /* falls through */
  18318. case 'gg':
  18319. case 'gggg':
  18320. case 'GG':
  18321. case 'GGGG':
  18322. case 'GGGGG':
  18323. token = token.substr(0, 2);
  18324. if (input) {
  18325. config._w = config._w || {};
  18326. config._w[token] = input;
  18327. }
  18328. break;
  18329. }
  18330. }
  18331. // convert an array to a date.
  18332. // the array should mirror the parameters below
  18333. // note: all values past the year are optional and will default to the lowest possible value.
  18334. // [year, month, day , hour, minute, second, millisecond]
  18335. function dateFromConfig(config) {
  18336. var i, date, input = [], currentDate,
  18337. yearToUse, fixYear, w, temp, lang, weekday, week;
  18338. if (config._d) {
  18339. return;
  18340. }
  18341. currentDate = currentDateArray(config);
  18342. //compute day of the year from weeks and weekdays
  18343. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  18344. fixYear = function (val) {
  18345. var intVal = parseInt(val, 10);
  18346. return val ?
  18347. (val.length < 3 ? (intVal > 68 ? 1900 + intVal : 2000 + intVal) : intVal) :
  18348. (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
  18349. };
  18350. w = config._w;
  18351. if (w.GG != null || w.W != null || w.E != null) {
  18352. temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
  18353. }
  18354. else {
  18355. lang = getLangDefinition(config._l);
  18356. weekday = w.d != null ? parseWeekday(w.d, lang) :
  18357. (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
  18358. week = parseInt(w.w, 10) || 1;
  18359. //if we're parsing 'd', then the low day numbers may be next week
  18360. if (w.d != null && weekday < lang._week.dow) {
  18361. week++;
  18362. }
  18363. temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
  18364. }
  18365. config._a[YEAR] = temp.year;
  18366. config._dayOfYear = temp.dayOfYear;
  18367. }
  18368. //if the day of the year is set, figure out what it is
  18369. if (config._dayOfYear) {
  18370. yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
  18371. if (config._dayOfYear > daysInYear(yearToUse)) {
  18372. config._pf._overflowDayOfYear = true;
  18373. }
  18374. date = makeUTCDate(yearToUse, 0, config._dayOfYear);
  18375. config._a[MONTH] = date.getUTCMonth();
  18376. config._a[DATE] = date.getUTCDate();
  18377. }
  18378. // Default to current date.
  18379. // * if no year, month, day of month are given, default to today
  18380. // * if day of month is given, default month and year
  18381. // * if month is given, default only year
  18382. // * if year is given, don't default anything
  18383. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  18384. config._a[i] = input[i] = currentDate[i];
  18385. }
  18386. // Zero out whatever was not defaulted, including time
  18387. for (; i < 7; i++) {
  18388. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  18389. }
  18390. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  18391. input[HOUR] += toInt((config._tzm || 0) / 60);
  18392. input[MINUTE] += toInt((config._tzm || 0) % 60);
  18393. config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
  18394. }
  18395. function dateFromObject(config) {
  18396. var normalizedInput;
  18397. if (config._d) {
  18398. return;
  18399. }
  18400. normalizedInput = normalizeObjectUnits(config._i);
  18401. config._a = [
  18402. normalizedInput.year,
  18403. normalizedInput.month,
  18404. normalizedInput.day,
  18405. normalizedInput.hour,
  18406. normalizedInput.minute,
  18407. normalizedInput.second,
  18408. normalizedInput.millisecond
  18409. ];
  18410. dateFromConfig(config);
  18411. }
  18412. function currentDateArray(config) {
  18413. var now = new Date();
  18414. if (config._useUTC) {
  18415. return [
  18416. now.getUTCFullYear(),
  18417. now.getUTCMonth(),
  18418. now.getUTCDate()
  18419. ];
  18420. } else {
  18421. return [now.getFullYear(), now.getMonth(), now.getDate()];
  18422. }
  18423. }
  18424. // date from string and format string
  18425. function makeDateFromStringAndFormat(config) {
  18426. config._a = [];
  18427. config._pf.empty = true;
  18428. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  18429. var lang = getLangDefinition(config._l),
  18430. string = '' + config._i,
  18431. i, parsedInput, tokens, token, skipped,
  18432. stringLength = string.length,
  18433. totalParsedInputLength = 0;
  18434. tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
  18435. for (i = 0; i < tokens.length; i++) {
  18436. token = tokens[i];
  18437. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  18438. if (parsedInput) {
  18439. skipped = string.substr(0, string.indexOf(parsedInput));
  18440. if (skipped.length > 0) {
  18441. config._pf.unusedInput.push(skipped);
  18442. }
  18443. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  18444. totalParsedInputLength += parsedInput.length;
  18445. }
  18446. // don't parse if it's not a known token
  18447. if (formatTokenFunctions[token]) {
  18448. if (parsedInput) {
  18449. config._pf.empty = false;
  18450. }
  18451. else {
  18452. config._pf.unusedTokens.push(token);
  18453. }
  18454. addTimeToArrayFromToken(token, parsedInput, config);
  18455. }
  18456. else if (config._strict && !parsedInput) {
  18457. config._pf.unusedTokens.push(token);
  18458. }
  18459. }
  18460. // add remaining unparsed input length to the string
  18461. config._pf.charsLeftOver = stringLength - totalParsedInputLength;
  18462. if (string.length > 0) {
  18463. config._pf.unusedInput.push(string);
  18464. }
  18465. // handle am pm
  18466. if (config._isPm && config._a[HOUR] < 12) {
  18467. config._a[HOUR] += 12;
  18468. }
  18469. // if is 12 am, change hours to 0
  18470. if (config._isPm === false && config._a[HOUR] === 12) {
  18471. config._a[HOUR] = 0;
  18472. }
  18473. dateFromConfig(config);
  18474. checkOverflow(config);
  18475. }
  18476. function unescapeFormat(s) {
  18477. return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  18478. return p1 || p2 || p3 || p4;
  18479. });
  18480. }
  18481. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  18482. function regexpEscape(s) {
  18483. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  18484. }
  18485. // date from string and array of format strings
  18486. function makeDateFromStringAndArray(config) {
  18487. var tempConfig,
  18488. bestMoment,
  18489. scoreToBeat,
  18490. i,
  18491. currentScore;
  18492. if (config._f.length === 0) {
  18493. config._pf.invalidFormat = true;
  18494. config._d = new Date(NaN);
  18495. return;
  18496. }
  18497. for (i = 0; i < config._f.length; i++) {
  18498. currentScore = 0;
  18499. tempConfig = extend({}, config);
  18500. tempConfig._pf = defaultParsingFlags();
  18501. tempConfig._f = config._f[i];
  18502. makeDateFromStringAndFormat(tempConfig);
  18503. if (!isValid(tempConfig)) {
  18504. continue;
  18505. }
  18506. // if there is any input that was not parsed add a penalty for that format
  18507. currentScore += tempConfig._pf.charsLeftOver;
  18508. //or tokens
  18509. currentScore += tempConfig._pf.unusedTokens.length * 10;
  18510. tempConfig._pf.score = currentScore;
  18511. if (scoreToBeat == null || currentScore < scoreToBeat) {
  18512. scoreToBeat = currentScore;
  18513. bestMoment = tempConfig;
  18514. }
  18515. }
  18516. extend(config, bestMoment || tempConfig);
  18517. }
  18518. // date from iso format
  18519. function makeDateFromString(config) {
  18520. var i, l,
  18521. string = config._i,
  18522. match = isoRegex.exec(string);
  18523. if (match) {
  18524. config._pf.iso = true;
  18525. for (i = 0, l = isoDates.length; i < l; i++) {
  18526. if (isoDates[i][1].exec(string)) {
  18527. // match[5] should be "T" or undefined
  18528. config._f = isoDates[i][0] + (match[6] || " ");
  18529. break;
  18530. }
  18531. }
  18532. for (i = 0, l = isoTimes.length; i < l; i++) {
  18533. if (isoTimes[i][1].exec(string)) {
  18534. config._f += isoTimes[i][0];
  18535. break;
  18536. }
  18537. }
  18538. if (string.match(parseTokenTimezone)) {
  18539. config._f += "Z";
  18540. }
  18541. makeDateFromStringAndFormat(config);
  18542. }
  18543. else {
  18544. moment.createFromInputFallback(config);
  18545. }
  18546. }
  18547. function makeDateFromInput(config) {
  18548. var input = config._i,
  18549. matched = aspNetJsonRegex.exec(input);
  18550. if (input === undefined) {
  18551. config._d = new Date();
  18552. } else if (matched) {
  18553. config._d = new Date(+matched[1]);
  18554. } else if (typeof input === 'string') {
  18555. makeDateFromString(config);
  18556. } else if (isArray(input)) {
  18557. config._a = input.slice(0);
  18558. dateFromConfig(config);
  18559. } else if (isDate(input)) {
  18560. config._d = new Date(+input);
  18561. } else if (typeof(input) === 'object') {
  18562. dateFromObject(config);
  18563. } else if (typeof(input) === 'number') {
  18564. // from milliseconds
  18565. config._d = new Date(input);
  18566. } else {
  18567. moment.createFromInputFallback(config);
  18568. }
  18569. }
  18570. function makeDate(y, m, d, h, M, s, ms) {
  18571. //can't just apply() to create a date:
  18572. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  18573. var date = new Date(y, m, d, h, M, s, ms);
  18574. //the date constructor doesn't accept years < 1970
  18575. if (y < 1970) {
  18576. date.setFullYear(y);
  18577. }
  18578. return date;
  18579. }
  18580. function makeUTCDate(y) {
  18581. var date = new Date(Date.UTC.apply(null, arguments));
  18582. if (y < 1970) {
  18583. date.setUTCFullYear(y);
  18584. }
  18585. return date;
  18586. }
  18587. function parseWeekday(input, language) {
  18588. if (typeof input === 'string') {
  18589. if (!isNaN(input)) {
  18590. input = parseInt(input, 10);
  18591. }
  18592. else {
  18593. input = language.weekdaysParse(input);
  18594. if (typeof input !== 'number') {
  18595. return null;
  18596. }
  18597. }
  18598. }
  18599. return input;
  18600. }
  18601. /************************************
  18602. Relative Time
  18603. ************************************/
  18604. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  18605. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  18606. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  18607. }
  18608. function relativeTime(milliseconds, withoutSuffix, lang) {
  18609. var seconds = round(Math.abs(milliseconds) / 1000),
  18610. minutes = round(seconds / 60),
  18611. hours = round(minutes / 60),
  18612. days = round(hours / 24),
  18613. years = round(days / 365),
  18614. args = seconds < 45 && ['s', seconds] ||
  18615. minutes === 1 && ['m'] ||
  18616. minutes < 45 && ['mm', minutes] ||
  18617. hours === 1 && ['h'] ||
  18618. hours < 22 && ['hh', hours] ||
  18619. days === 1 && ['d'] ||
  18620. days <= 25 && ['dd', days] ||
  18621. days <= 45 && ['M'] ||
  18622. days < 345 && ['MM', round(days / 30)] ||
  18623. years === 1 && ['y'] || ['yy', years];
  18624. args[2] = withoutSuffix;
  18625. args[3] = milliseconds > 0;
  18626. args[4] = lang;
  18627. return substituteTimeAgo.apply({}, args);
  18628. }
  18629. /************************************
  18630. Week of Year
  18631. ************************************/
  18632. // firstDayOfWeek 0 = sun, 6 = sat
  18633. // the day of the week that starts the week
  18634. // (usually sunday or monday)
  18635. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  18636. // the first week is the week that contains the first
  18637. // of this day of the week
  18638. // (eg. ISO weeks use thursday (4))
  18639. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  18640. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  18641. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
  18642. adjustedMoment;
  18643. if (daysToDayOfWeek > end) {
  18644. daysToDayOfWeek -= 7;
  18645. }
  18646. if (daysToDayOfWeek < end - 7) {
  18647. daysToDayOfWeek += 7;
  18648. }
  18649. adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
  18650. return {
  18651. week: Math.ceil(adjustedMoment.dayOfYear() / 7),
  18652. year: adjustedMoment.year()
  18653. };
  18654. }
  18655. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  18656. function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
  18657. var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
  18658. weekday = weekday != null ? weekday : firstDayOfWeek;
  18659. daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
  18660. dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
  18661. return {
  18662. year: dayOfYear > 0 ? year : year - 1,
  18663. dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
  18664. };
  18665. }
  18666. /************************************
  18667. Top Level Functions
  18668. ************************************/
  18669. function makeMoment(config) {
  18670. var input = config._i,
  18671. format = config._f;
  18672. if (input === null || (format === undefined && input === '')) {
  18673. return moment.invalid({nullInput: true});
  18674. }
  18675. if (typeof input === 'string') {
  18676. config._i = input = getLangDefinition().preparse(input);
  18677. }
  18678. if (moment.isMoment(input)) {
  18679. config = cloneMoment(input);
  18680. config._d = new Date(+input._d);
  18681. } else if (format) {
  18682. if (isArray(format)) {
  18683. makeDateFromStringAndArray(config);
  18684. } else {
  18685. makeDateFromStringAndFormat(config);
  18686. }
  18687. } else {
  18688. makeDateFromInput(config);
  18689. }
  18690. return new Moment(config);
  18691. }
  18692. moment = function (input, format, lang, strict) {
  18693. var c;
  18694. if (typeof(lang) === "boolean") {
  18695. strict = lang;
  18696. lang = undefined;
  18697. }
  18698. // object construction must be done this way.
  18699. // https://github.com/moment/moment/issues/1423
  18700. c = {};
  18701. c._isAMomentObject = true;
  18702. c._i = input;
  18703. c._f = format;
  18704. c._l = lang;
  18705. c._strict = strict;
  18706. c._isUTC = false;
  18707. c._pf = defaultParsingFlags();
  18708. return makeMoment(c);
  18709. };
  18710. moment.suppressDeprecationWarnings = false;
  18711. moment.createFromInputFallback = deprecate(
  18712. "moment construction falls back to js Date. This is " +
  18713. "discouraged and will be removed in upcoming major " +
  18714. "release. Please refer to " +
  18715. "https://github.com/moment/moment/issues/1407 for more info.",
  18716. function (config) {
  18717. config._d = new Date(config._i);
  18718. });
  18719. // creating with utc
  18720. moment.utc = function (input, format, lang, strict) {
  18721. var c;
  18722. if (typeof(lang) === "boolean") {
  18723. strict = lang;
  18724. lang = undefined;
  18725. }
  18726. // object construction must be done this way.
  18727. // https://github.com/moment/moment/issues/1423
  18728. c = {};
  18729. c._isAMomentObject = true;
  18730. c._useUTC = true;
  18731. c._isUTC = true;
  18732. c._l = lang;
  18733. c._i = input;
  18734. c._f = format;
  18735. c._strict = strict;
  18736. c._pf = defaultParsingFlags();
  18737. return makeMoment(c).utc();
  18738. };
  18739. // creating with unix timestamp (in seconds)
  18740. moment.unix = function (input) {
  18741. return moment(input * 1000);
  18742. };
  18743. // duration
  18744. moment.duration = function (input, key) {
  18745. var duration = input,
  18746. // matching against regexp is expensive, do it on demand
  18747. match = null,
  18748. sign,
  18749. ret,
  18750. parseIso;
  18751. if (moment.isDuration(input)) {
  18752. duration = {
  18753. ms: input._milliseconds,
  18754. d: input._days,
  18755. M: input._months
  18756. };
  18757. } else if (typeof input === 'number') {
  18758. duration = {};
  18759. if (key) {
  18760. duration[key] = input;
  18761. } else {
  18762. duration.milliseconds = input;
  18763. }
  18764. } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
  18765. sign = (match[1] === "-") ? -1 : 1;
  18766. duration = {
  18767. y: 0,
  18768. d: toInt(match[DATE]) * sign,
  18769. h: toInt(match[HOUR]) * sign,
  18770. m: toInt(match[MINUTE]) * sign,
  18771. s: toInt(match[SECOND]) * sign,
  18772. ms: toInt(match[MILLISECOND]) * sign
  18773. };
  18774. } else if (!!(match = isoDurationRegex.exec(input))) {
  18775. sign = (match[1] === "-") ? -1 : 1;
  18776. parseIso = function (inp) {
  18777. // We'd normally use ~~inp for this, but unfortunately it also
  18778. // converts floats to ints.
  18779. // inp may be undefined, so careful calling replace on it.
  18780. var res = inp && parseFloat(inp.replace(',', '.'));
  18781. // apply sign while we're at it
  18782. return (isNaN(res) ? 0 : res) * sign;
  18783. };
  18784. duration = {
  18785. y: parseIso(match[2]),
  18786. M: parseIso(match[3]),
  18787. d: parseIso(match[4]),
  18788. h: parseIso(match[5]),
  18789. m: parseIso(match[6]),
  18790. s: parseIso(match[7]),
  18791. w: parseIso(match[8])
  18792. };
  18793. }
  18794. ret = new Duration(duration);
  18795. if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
  18796. ret._lang = input._lang;
  18797. }
  18798. return ret;
  18799. };
  18800. // version number
  18801. moment.version = VERSION;
  18802. // default format
  18803. moment.defaultFormat = isoFormat;
  18804. // Plugins that add properties should also add the key here (null value),
  18805. // so we can properly clone ourselves.
  18806. moment.momentProperties = momentProperties;
  18807. // This function will be called whenever a moment is mutated.
  18808. // It is intended to keep the offset in sync with the timezone.
  18809. moment.updateOffset = function () {};
  18810. // This function will load languages and then set the global language. If
  18811. // no arguments are passed in, it will simply return the current global
  18812. // language key.
  18813. moment.lang = function (key, values) {
  18814. var r;
  18815. if (!key) {
  18816. return moment.fn._lang._abbr;
  18817. }
  18818. if (values) {
  18819. loadLang(normalizeLanguage(key), values);
  18820. } else if (values === null) {
  18821. unloadLang(key);
  18822. key = 'en';
  18823. } else if (!languages[key]) {
  18824. getLangDefinition(key);
  18825. }
  18826. r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  18827. return r._abbr;
  18828. };
  18829. // returns language data
  18830. moment.langData = function (key) {
  18831. if (key && key._lang && key._lang._abbr) {
  18832. key = key._lang._abbr;
  18833. }
  18834. return getLangDefinition(key);
  18835. };
  18836. // compare moment object
  18837. moment.isMoment = function (obj) {
  18838. return obj instanceof Moment ||
  18839. (obj != null && obj.hasOwnProperty('_isAMomentObject'));
  18840. };
  18841. // for typechecking Duration objects
  18842. moment.isDuration = function (obj) {
  18843. return obj instanceof Duration;
  18844. };
  18845. for (i = lists.length - 1; i >= 0; --i) {
  18846. makeList(lists[i]);
  18847. }
  18848. moment.normalizeUnits = function (units) {
  18849. return normalizeUnits(units);
  18850. };
  18851. moment.invalid = function (flags) {
  18852. var m = moment.utc(NaN);
  18853. if (flags != null) {
  18854. extend(m._pf, flags);
  18855. }
  18856. else {
  18857. m._pf.userInvalidated = true;
  18858. }
  18859. return m;
  18860. };
  18861. moment.parseZone = function () {
  18862. return moment.apply(null, arguments).parseZone();
  18863. };
  18864. moment.parseTwoDigitYear = function (input) {
  18865. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  18866. };
  18867. /************************************
  18868. Moment Prototype
  18869. ************************************/
  18870. extend(moment.fn = Moment.prototype, {
  18871. clone : function () {
  18872. return moment(this);
  18873. },
  18874. valueOf : function () {
  18875. return +this._d + ((this._offset || 0) * 60000);
  18876. },
  18877. unix : function () {
  18878. return Math.floor(+this / 1000);
  18879. },
  18880. toString : function () {
  18881. return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  18882. },
  18883. toDate : function () {
  18884. return this._offset ? new Date(+this) : this._d;
  18885. },
  18886. toISOString : function () {
  18887. var m = moment(this).utc();
  18888. if (0 < m.year() && m.year() <= 9999) {
  18889. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18890. } else {
  18891. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  18892. }
  18893. },
  18894. toArray : function () {
  18895. var m = this;
  18896. return [
  18897. m.year(),
  18898. m.month(),
  18899. m.date(),
  18900. m.hours(),
  18901. m.minutes(),
  18902. m.seconds(),
  18903. m.milliseconds()
  18904. ];
  18905. },
  18906. isValid : function () {
  18907. return isValid(this);
  18908. },
  18909. isDSTShifted : function () {
  18910. if (this._a) {
  18911. return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
  18912. }
  18913. return false;
  18914. },
  18915. parsingFlags : function () {
  18916. return extend({}, this._pf);
  18917. },
  18918. invalidAt: function () {
  18919. return this._pf.overflow;
  18920. },
  18921. utc : function () {
  18922. return this.zone(0);
  18923. },
  18924. local : function () {
  18925. this.zone(0);
  18926. this._isUTC = false;
  18927. return this;
  18928. },
  18929. format : function (inputString) {
  18930. var output = formatMoment(this, inputString || moment.defaultFormat);
  18931. return this.lang().postformat(output);
  18932. },
  18933. add : function (input, val) {
  18934. var dur;
  18935. // switch args to support add('s', 1) and add(1, 's')
  18936. if (typeof input === 'string') {
  18937. dur = moment.duration(+val, input);
  18938. } else {
  18939. dur = moment.duration(input, val);
  18940. }
  18941. addOrSubtractDurationFromMoment(this, dur, 1);
  18942. return this;
  18943. },
  18944. subtract : function (input, val) {
  18945. var dur;
  18946. // switch args to support subtract('s', 1) and subtract(1, 's')
  18947. if (typeof input === 'string') {
  18948. dur = moment.duration(+val, input);
  18949. } else {
  18950. dur = moment.duration(input, val);
  18951. }
  18952. addOrSubtractDurationFromMoment(this, dur, -1);
  18953. return this;
  18954. },
  18955. diff : function (input, units, asFloat) {
  18956. var that = makeAs(input, this),
  18957. zoneDiff = (this.zone() - that.zone()) * 6e4,
  18958. diff, output;
  18959. units = normalizeUnits(units);
  18960. if (units === 'year' || units === 'month') {
  18961. // average number of days in the months in the given dates
  18962. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  18963. // difference in months
  18964. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  18965. // adjust by taking difference in days, average number of days
  18966. // and dst in the given months.
  18967. output += ((this - moment(this).startOf('month')) -
  18968. (that - moment(that).startOf('month'))) / diff;
  18969. // same as above but with zones, to negate all dst
  18970. output -= ((this.zone() - moment(this).startOf('month').zone()) -
  18971. (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
  18972. if (units === 'year') {
  18973. output = output / 12;
  18974. }
  18975. } else {
  18976. diff = (this - that);
  18977. output = units === 'second' ? diff / 1e3 : // 1000
  18978. units === 'minute' ? diff / 6e4 : // 1000 * 60
  18979. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  18980. units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  18981. units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  18982. diff;
  18983. }
  18984. return asFloat ? output : absRound(output);
  18985. },
  18986. from : function (time, withoutSuffix) {
  18987. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  18988. },
  18989. fromNow : function (withoutSuffix) {
  18990. return this.from(moment(), withoutSuffix);
  18991. },
  18992. calendar : function () {
  18993. // We want to compare the start of today, vs this.
  18994. // Getting start-of-today depends on whether we're zone'd or not.
  18995. var sod = makeAs(moment(), this).startOf('day'),
  18996. diff = this.diff(sod, 'days', true),
  18997. format = diff < -6 ? 'sameElse' :
  18998. diff < -1 ? 'lastWeek' :
  18999. diff < 0 ? 'lastDay' :
  19000. diff < 1 ? 'sameDay' :
  19001. diff < 2 ? 'nextDay' :
  19002. diff < 7 ? 'nextWeek' : 'sameElse';
  19003. return this.format(this.lang().calendar(format, this));
  19004. },
  19005. isLeapYear : function () {
  19006. return isLeapYear(this.year());
  19007. },
  19008. isDST : function () {
  19009. return (this.zone() < this.clone().month(0).zone() ||
  19010. this.zone() < this.clone().month(5).zone());
  19011. },
  19012. day : function (input) {
  19013. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  19014. if (input != null) {
  19015. input = parseWeekday(input, this.lang());
  19016. return this.add({ d : input - day });
  19017. } else {
  19018. return day;
  19019. }
  19020. },
  19021. month : makeAccessor('Month', true),
  19022. startOf: function (units) {
  19023. units = normalizeUnits(units);
  19024. // the following switch intentionally omits break keywords
  19025. // to utilize falling through the cases.
  19026. switch (units) {
  19027. case 'year':
  19028. this.month(0);
  19029. /* falls through */
  19030. case 'quarter':
  19031. case 'month':
  19032. this.date(1);
  19033. /* falls through */
  19034. case 'week':
  19035. case 'isoWeek':
  19036. case 'day':
  19037. this.hours(0);
  19038. /* falls through */
  19039. case 'hour':
  19040. this.minutes(0);
  19041. /* falls through */
  19042. case 'minute':
  19043. this.seconds(0);
  19044. /* falls through */
  19045. case 'second':
  19046. this.milliseconds(0);
  19047. /* falls through */
  19048. }
  19049. // weeks are a special case
  19050. if (units === 'week') {
  19051. this.weekday(0);
  19052. } else if (units === 'isoWeek') {
  19053. this.isoWeekday(1);
  19054. }
  19055. // quarters are also special
  19056. if (units === 'quarter') {
  19057. this.month(Math.floor(this.month() / 3) * 3);
  19058. }
  19059. return this;
  19060. },
  19061. endOf: function (units) {
  19062. units = normalizeUnits(units);
  19063. return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
  19064. },
  19065. isAfter: function (input, units) {
  19066. units = typeof units !== 'undefined' ? units : 'millisecond';
  19067. return +this.clone().startOf(units) > +moment(input).startOf(units);
  19068. },
  19069. isBefore: function (input, units) {
  19070. units = typeof units !== 'undefined' ? units : 'millisecond';
  19071. return +this.clone().startOf(units) < +moment(input).startOf(units);
  19072. },
  19073. isSame: function (input, units) {
  19074. units = units || 'ms';
  19075. return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
  19076. },
  19077. min: function (other) {
  19078. other = moment.apply(null, arguments);
  19079. return other < this ? this : other;
  19080. },
  19081. max: function (other) {
  19082. other = moment.apply(null, arguments);
  19083. return other > this ? this : other;
  19084. },
  19085. // keepTime = true means only change the timezone, without affecting
  19086. // the local hour. So 5:31:26 +0300 --[zone(2, true)]--> 5:31:26 +0200
  19087. // It is possible that 5:31:26 doesn't exist int zone +0200, so we
  19088. // adjust the time as needed, to be valid.
  19089. //
  19090. // Keeping the time actually adds/subtracts (one hour)
  19091. // from the actual represented time. That is why we call updateOffset
  19092. // a second time. In case it wants us to change the offset again
  19093. // _changeInProgress == true case, then we have to adjust, because
  19094. // there is no such time in the given timezone.
  19095. zone : function (input, keepTime) {
  19096. var offset = this._offset || 0;
  19097. if (input != null) {
  19098. if (typeof input === "string") {
  19099. input = timezoneMinutesFromString(input);
  19100. }
  19101. if (Math.abs(input) < 16) {
  19102. input = input * 60;
  19103. }
  19104. this._offset = input;
  19105. this._isUTC = true;
  19106. if (offset !== input) {
  19107. if (!keepTime || this._changeInProgress) {
  19108. addOrSubtractDurationFromMoment(this,
  19109. moment.duration(offset - input, 'm'), 1, false);
  19110. } else if (!this._changeInProgress) {
  19111. this._changeInProgress = true;
  19112. moment.updateOffset(this, true);
  19113. this._changeInProgress = null;
  19114. }
  19115. }
  19116. } else {
  19117. return this._isUTC ? offset : this._d.getTimezoneOffset();
  19118. }
  19119. return this;
  19120. },
  19121. zoneAbbr : function () {
  19122. return this._isUTC ? "UTC" : "";
  19123. },
  19124. zoneName : function () {
  19125. return this._isUTC ? "Coordinated Universal Time" : "";
  19126. },
  19127. parseZone : function () {
  19128. if (this._tzm) {
  19129. this.zone(this._tzm);
  19130. } else if (typeof this._i === 'string') {
  19131. this.zone(this._i);
  19132. }
  19133. return this;
  19134. },
  19135. hasAlignedHourOffset : function (input) {
  19136. if (!input) {
  19137. input = 0;
  19138. }
  19139. else {
  19140. input = moment(input).zone();
  19141. }
  19142. return (this.zone() - input) % 60 === 0;
  19143. },
  19144. daysInMonth : function () {
  19145. return daysInMonth(this.year(), this.month());
  19146. },
  19147. dayOfYear : function (input) {
  19148. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  19149. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  19150. },
  19151. quarter : function (input) {
  19152. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  19153. },
  19154. weekYear : function (input) {
  19155. var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
  19156. return input == null ? year : this.add("y", (input - year));
  19157. },
  19158. isoWeekYear : function (input) {
  19159. var year = weekOfYear(this, 1, 4).year;
  19160. return input == null ? year : this.add("y", (input - year));
  19161. },
  19162. week : function (input) {
  19163. var week = this.lang().week(this);
  19164. return input == null ? week : this.add("d", (input - week) * 7);
  19165. },
  19166. isoWeek : function (input) {
  19167. var week = weekOfYear(this, 1, 4).week;
  19168. return input == null ? week : this.add("d", (input - week) * 7);
  19169. },
  19170. weekday : function (input) {
  19171. var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
  19172. return input == null ? weekday : this.add("d", input - weekday);
  19173. },
  19174. isoWeekday : function (input) {
  19175. // behaves the same as moment#day except
  19176. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  19177. // as a setter, sunday should belong to the previous week.
  19178. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  19179. },
  19180. isoWeeksInYear : function () {
  19181. return weeksInYear(this.year(), 1, 4);
  19182. },
  19183. weeksInYear : function () {
  19184. var weekInfo = this._lang._week;
  19185. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  19186. },
  19187. get : function (units) {
  19188. units = normalizeUnits(units);
  19189. return this[units]();
  19190. },
  19191. set : function (units, value) {
  19192. units = normalizeUnits(units);
  19193. if (typeof this[units] === 'function') {
  19194. this[units](value);
  19195. }
  19196. return this;
  19197. },
  19198. // If passed a language key, it will set the language for this
  19199. // instance. Otherwise, it will return the language configuration
  19200. // variables for this instance.
  19201. lang : function (key) {
  19202. if (key === undefined) {
  19203. return this._lang;
  19204. } else {
  19205. this._lang = getLangDefinition(key);
  19206. return this;
  19207. }
  19208. }
  19209. });
  19210. function rawMonthSetter(mom, value) {
  19211. var dayOfMonth;
  19212. // TODO: Move this out of here!
  19213. if (typeof value === 'string') {
  19214. value = mom.lang().monthsParse(value);
  19215. // TODO: Another silent failure?
  19216. if (typeof value !== 'number') {
  19217. return mom;
  19218. }
  19219. }
  19220. dayOfMonth = Math.min(mom.date(),
  19221. daysInMonth(mom.year(), value));
  19222. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  19223. return mom;
  19224. }
  19225. function rawGetter(mom, unit) {
  19226. return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
  19227. }
  19228. function rawSetter(mom, unit, value) {
  19229. if (unit === 'Month') {
  19230. return rawMonthSetter(mom, value);
  19231. } else {
  19232. return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  19233. }
  19234. }
  19235. function makeAccessor(unit, keepTime) {
  19236. return function (value) {
  19237. if (value != null) {
  19238. rawSetter(this, unit, value);
  19239. moment.updateOffset(this, keepTime);
  19240. return this;
  19241. } else {
  19242. return rawGetter(this, unit);
  19243. }
  19244. };
  19245. }
  19246. moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
  19247. moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
  19248. moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
  19249. // Setting the hour should keep the time, because the user explicitly
  19250. // specified which hour he wants. So trying to maintain the same hour (in
  19251. // a new timezone) makes sense. Adding/subtracting hours does not follow
  19252. // this rule.
  19253. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
  19254. // moment.fn.month is defined separately
  19255. moment.fn.date = makeAccessor('Date', true);
  19256. moment.fn.dates = deprecate("dates accessor is deprecated. Use date instead.", makeAccessor('Date', true));
  19257. moment.fn.year = makeAccessor('FullYear', true);
  19258. moment.fn.years = deprecate("years accessor is deprecated. Use year instead.", makeAccessor('FullYear', true));
  19259. // add plural methods
  19260. moment.fn.days = moment.fn.day;
  19261. moment.fn.months = moment.fn.month;
  19262. moment.fn.weeks = moment.fn.week;
  19263. moment.fn.isoWeeks = moment.fn.isoWeek;
  19264. moment.fn.quarters = moment.fn.quarter;
  19265. // add aliased format methods
  19266. moment.fn.toJSON = moment.fn.toISOString;
  19267. /************************************
  19268. Duration Prototype
  19269. ************************************/
  19270. extend(moment.duration.fn = Duration.prototype, {
  19271. _bubble : function () {
  19272. var milliseconds = this._milliseconds,
  19273. days = this._days,
  19274. months = this._months,
  19275. data = this._data,
  19276. seconds, minutes, hours, years;
  19277. // The following code bubbles up values, see the tests for
  19278. // examples of what that means.
  19279. data.milliseconds = milliseconds % 1000;
  19280. seconds = absRound(milliseconds / 1000);
  19281. data.seconds = seconds % 60;
  19282. minutes = absRound(seconds / 60);
  19283. data.minutes = minutes % 60;
  19284. hours = absRound(minutes / 60);
  19285. data.hours = hours % 24;
  19286. days += absRound(hours / 24);
  19287. data.days = days % 30;
  19288. months += absRound(days / 30);
  19289. data.months = months % 12;
  19290. years = absRound(months / 12);
  19291. data.years = years;
  19292. },
  19293. weeks : function () {
  19294. return absRound(this.days() / 7);
  19295. },
  19296. valueOf : function () {
  19297. return this._milliseconds +
  19298. this._days * 864e5 +
  19299. (this._months % 12) * 2592e6 +
  19300. toInt(this._months / 12) * 31536e6;
  19301. },
  19302. humanize : function (withSuffix) {
  19303. var difference = +this,
  19304. output = relativeTime(difference, !withSuffix, this.lang());
  19305. if (withSuffix) {
  19306. output = this.lang().pastFuture(difference, output);
  19307. }
  19308. return this.lang().postformat(output);
  19309. },
  19310. add : function (input, val) {
  19311. // supports only 2.0-style add(1, 's') or add(moment)
  19312. var dur = moment.duration(input, val);
  19313. this._milliseconds += dur._milliseconds;
  19314. this._days += dur._days;
  19315. this._months += dur._months;
  19316. this._bubble();
  19317. return this;
  19318. },
  19319. subtract : function (input, val) {
  19320. var dur = moment.duration(input, val);
  19321. this._milliseconds -= dur._milliseconds;
  19322. this._days -= dur._days;
  19323. this._months -= dur._months;
  19324. this._bubble();
  19325. return this;
  19326. },
  19327. get : function (units) {
  19328. units = normalizeUnits(units);
  19329. return this[units.toLowerCase() + 's']();
  19330. },
  19331. as : function (units) {
  19332. units = normalizeUnits(units);
  19333. return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
  19334. },
  19335. lang : moment.fn.lang,
  19336. toIsoString : function () {
  19337. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  19338. var years = Math.abs(this.years()),
  19339. months = Math.abs(this.months()),
  19340. days = Math.abs(this.days()),
  19341. hours = Math.abs(this.hours()),
  19342. minutes = Math.abs(this.minutes()),
  19343. seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
  19344. if (!this.asSeconds()) {
  19345. // this is the same as C#'s (Noda) and python (isodate)...
  19346. // but not other JS (goog.date)
  19347. return 'P0D';
  19348. }
  19349. return (this.asSeconds() < 0 ? '-' : '') +
  19350. 'P' +
  19351. (years ? years + 'Y' : '') +
  19352. (months ? months + 'M' : '') +
  19353. (days ? days + 'D' : '') +
  19354. ((hours || minutes || seconds) ? 'T' : '') +
  19355. (hours ? hours + 'H' : '') +
  19356. (minutes ? minutes + 'M' : '') +
  19357. (seconds ? seconds + 'S' : '');
  19358. }
  19359. });
  19360. function makeDurationGetter(name) {
  19361. moment.duration.fn[name] = function () {
  19362. return this._data[name];
  19363. };
  19364. }
  19365. function makeDurationAsGetter(name, factor) {
  19366. moment.duration.fn['as' + name] = function () {
  19367. return +this / factor;
  19368. };
  19369. }
  19370. for (i in unitMillisecondFactors) {
  19371. if (unitMillisecondFactors.hasOwnProperty(i)) {
  19372. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  19373. makeDurationGetter(i.toLowerCase());
  19374. }
  19375. }
  19376. makeDurationAsGetter('Weeks', 6048e5);
  19377. moment.duration.fn.asMonths = function () {
  19378. return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
  19379. };
  19380. /************************************
  19381. Default Lang
  19382. ************************************/
  19383. // Set default language, other languages will inherit from English.
  19384. moment.lang('en', {
  19385. ordinal : function (number) {
  19386. var b = number % 10,
  19387. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  19388. (b === 1) ? 'st' :
  19389. (b === 2) ? 'nd' :
  19390. (b === 3) ? 'rd' : 'th';
  19391. return number + output;
  19392. }
  19393. });
  19394. /* EMBED_LANGUAGES */
  19395. /************************************
  19396. Exposing Moment
  19397. ************************************/
  19398. function makeGlobal(shouldDeprecate) {
  19399. /*global ender:false */
  19400. if (typeof ender !== 'undefined') {
  19401. return;
  19402. }
  19403. oldGlobalMoment = globalScope.moment;
  19404. if (shouldDeprecate) {
  19405. globalScope.moment = deprecate(
  19406. "Accessing Moment through the global scope is " +
  19407. "deprecated, and will be removed in an upcoming " +
  19408. "release.",
  19409. moment);
  19410. } else {
  19411. globalScope.moment = moment;
  19412. }
  19413. }
  19414. // CommonJS module is defined
  19415. if (hasModule) {
  19416. module.exports = moment;
  19417. } else if (typeof define === "function" && define.amd) {
  19418. define("moment", function (require, exports, module) {
  19419. if (module.config && module.config() && module.config().noGlobal === true) {
  19420. // release the global variable
  19421. globalScope.moment = oldGlobalMoment;
  19422. }
  19423. return moment;
  19424. });
  19425. makeGlobal(true);
  19426. } else {
  19427. makeGlobal();
  19428. }
  19429. }).call(this);
  19430. },{}],5:[function(require,module,exports){
  19431. /**
  19432. * Copyright 2012 Craig Campbell
  19433. *
  19434. * Licensed under the Apache License, Version 2.0 (the "License");
  19435. * you may not use this file except in compliance with the License.
  19436. * You may obtain a copy of the License at
  19437. *
  19438. * http://www.apache.org/licenses/LICENSE-2.0
  19439. *
  19440. * Unless required by applicable law or agreed to in writing, software
  19441. * distributed under the License is distributed on an "AS IS" BASIS,
  19442. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19443. * See the License for the specific language governing permissions and
  19444. * limitations under the License.
  19445. *
  19446. * Mousetrap is a simple keyboard shortcut library for Javascript with
  19447. * no external dependencies
  19448. *
  19449. * @version 1.1.2
  19450. * @url craig.is/killing/mice
  19451. */
  19452. /**
  19453. * mapping of special keycodes to their corresponding keys
  19454. *
  19455. * everything in this dictionary cannot use keypress events
  19456. * so it has to be here to map to the correct keycodes for
  19457. * keyup/keydown events
  19458. *
  19459. * @type {Object}
  19460. */
  19461. var _MAP = {
  19462. 8: 'backspace',
  19463. 9: 'tab',
  19464. 13: 'enter',
  19465. 16: 'shift',
  19466. 17: 'ctrl',
  19467. 18: 'alt',
  19468. 20: 'capslock',
  19469. 27: 'esc',
  19470. 32: 'space',
  19471. 33: 'pageup',
  19472. 34: 'pagedown',
  19473. 35: 'end',
  19474. 36: 'home',
  19475. 37: 'left',
  19476. 38: 'up',
  19477. 39: 'right',
  19478. 40: 'down',
  19479. 45: 'ins',
  19480. 46: 'del',
  19481. 91: 'meta',
  19482. 93: 'meta',
  19483. 224: 'meta'
  19484. },
  19485. /**
  19486. * mapping for special characters so they can support
  19487. *
  19488. * this dictionary is only used incase you want to bind a
  19489. * keyup or keydown event to one of these keys
  19490. *
  19491. * @type {Object}
  19492. */
  19493. _KEYCODE_MAP = {
  19494. 106: '*',
  19495. 107: '+',
  19496. 109: '-',
  19497. 110: '.',
  19498. 111 : '/',
  19499. 186: ';',
  19500. 187: '=',
  19501. 188: ',',
  19502. 189: '-',
  19503. 190: '.',
  19504. 191: '/',
  19505. 192: '`',
  19506. 219: '[',
  19507. 220: '\\',
  19508. 221: ']',
  19509. 222: '\''
  19510. },
  19511. /**
  19512. * this is a mapping of keys that require shift on a US keypad
  19513. * back to the non shift equivelents
  19514. *
  19515. * this is so you can use keyup events with these keys
  19516. *
  19517. * note that this will only work reliably on US keyboards
  19518. *
  19519. * @type {Object}
  19520. */
  19521. _SHIFT_MAP = {
  19522. '~': '`',
  19523. '!': '1',
  19524. '@': '2',
  19525. '#': '3',
  19526. '$': '4',
  19527. '%': '5',
  19528. '^': '6',
  19529. '&': '7',
  19530. '*': '8',
  19531. '(': '9',
  19532. ')': '0',
  19533. '_': '-',
  19534. '+': '=',
  19535. ':': ';',
  19536. '\"': '\'',
  19537. '<': ',',
  19538. '>': '.',
  19539. '?': '/',
  19540. '|': '\\'
  19541. },
  19542. /**
  19543. * this is a list of special strings you can use to map
  19544. * to modifier keys when you specify your keyboard shortcuts
  19545. *
  19546. * @type {Object}
  19547. */
  19548. _SPECIAL_ALIASES = {
  19549. 'option': 'alt',
  19550. 'command': 'meta',
  19551. 'return': 'enter',
  19552. 'escape': 'esc'
  19553. },
  19554. /**
  19555. * variable to store the flipped version of _MAP from above
  19556. * needed to check if we should use keypress or not when no action
  19557. * is specified
  19558. *
  19559. * @type {Object|undefined}
  19560. */
  19561. _REVERSE_MAP,
  19562. /**
  19563. * a list of all the callbacks setup via Mousetrap.bind()
  19564. *
  19565. * @type {Object}
  19566. */
  19567. _callbacks = {},
  19568. /**
  19569. * direct map of string combinations to callbacks used for trigger()
  19570. *
  19571. * @type {Object}
  19572. */
  19573. _direct_map = {},
  19574. /**
  19575. * keeps track of what level each sequence is at since multiple
  19576. * sequences can start out with the same sequence
  19577. *
  19578. * @type {Object}
  19579. */
  19580. _sequence_levels = {},
  19581. /**
  19582. * variable to store the setTimeout call
  19583. *
  19584. * @type {null|number}
  19585. */
  19586. _reset_timer,
  19587. /**
  19588. * temporary state where we will ignore the next keyup
  19589. *
  19590. * @type {boolean|string}
  19591. */
  19592. _ignore_next_keyup = false,
  19593. /**
  19594. * are we currently inside of a sequence?
  19595. * type of action ("keyup" or "keydown" or "keypress") or false
  19596. *
  19597. * @type {boolean|string}
  19598. */
  19599. _inside_sequence = false;
  19600. /**
  19601. * loop through the f keys, f1 to f19 and add them to the map
  19602. * programatically
  19603. */
  19604. for (var i = 1; i < 20; ++i) {
  19605. _MAP[111 + i] = 'f' + i;
  19606. }
  19607. /**
  19608. * loop through to map numbers on the numeric keypad
  19609. */
  19610. for (i = 0; i <= 9; ++i) {
  19611. _MAP[i + 96] = i;
  19612. }
  19613. /**
  19614. * cross browser add event method
  19615. *
  19616. * @param {Element|HTMLDocument} object
  19617. * @param {string} type
  19618. * @param {Function} callback
  19619. * @returns void
  19620. */
  19621. function _addEvent(object, type, callback) {
  19622. if (object.addEventListener) {
  19623. return object.addEventListener(type, callback, false);
  19624. }
  19625. object.attachEvent('on' + type, callback);
  19626. }
  19627. /**
  19628. * takes the event and returns the key character
  19629. *
  19630. * @param {Event} e
  19631. * @return {string}
  19632. */
  19633. function _characterFromEvent(e) {
  19634. // for keypress events we should return the character as is
  19635. if (e.type == 'keypress') {
  19636. return String.fromCharCode(e.which);
  19637. }
  19638. // for non keypress events the special maps are needed
  19639. if (_MAP[e.which]) {
  19640. return _MAP[e.which];
  19641. }
  19642. if (_KEYCODE_MAP[e.which]) {
  19643. return _KEYCODE_MAP[e.which];
  19644. }
  19645. // if it is not in the special map
  19646. return String.fromCharCode(e.which).toLowerCase();
  19647. }
  19648. /**
  19649. * should we stop this event before firing off callbacks
  19650. *
  19651. * @param {Event} e
  19652. * @return {boolean}
  19653. */
  19654. function _stop(e) {
  19655. var element = e.target || e.srcElement,
  19656. tag_name = element.tagName;
  19657. // if the element has the class "mousetrap" then no need to stop
  19658. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  19659. return false;
  19660. }
  19661. // stop for input, select, and textarea
  19662. return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
  19663. }
  19664. /**
  19665. * checks if two arrays are equal
  19666. *
  19667. * @param {Array} modifiers1
  19668. * @param {Array} modifiers2
  19669. * @returns {boolean}
  19670. */
  19671. function _modifiersMatch(modifiers1, modifiers2) {
  19672. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  19673. }
  19674. /**
  19675. * resets all sequence counters except for the ones passed in
  19676. *
  19677. * @param {Object} do_not_reset
  19678. * @returns void
  19679. */
  19680. function _resetSequences(do_not_reset) {
  19681. do_not_reset = do_not_reset || {};
  19682. var active_sequences = false,
  19683. key;
  19684. for (key in _sequence_levels) {
  19685. if (do_not_reset[key]) {
  19686. active_sequences = true;
  19687. continue;
  19688. }
  19689. _sequence_levels[key] = 0;
  19690. }
  19691. if (!active_sequences) {
  19692. _inside_sequence = false;
  19693. }
  19694. }
  19695. /**
  19696. * finds all callbacks that match based on the keycode, modifiers,
  19697. * and action
  19698. *
  19699. * @param {string} character
  19700. * @param {Array} modifiers
  19701. * @param {string} action
  19702. * @param {boolean=} remove - should we remove any matches
  19703. * @param {string=} combination
  19704. * @returns {Array}
  19705. */
  19706. function _getMatches(character, modifiers, action, remove, combination) {
  19707. var i,
  19708. callback,
  19709. matches = [];
  19710. // if there are no events related to this keycode
  19711. if (!_callbacks[character]) {
  19712. return [];
  19713. }
  19714. // if a modifier key is coming up on its own we should allow it
  19715. if (action == 'keyup' && _isModifier(character)) {
  19716. modifiers = [character];
  19717. }
  19718. // loop through all callbacks for the key that was pressed
  19719. // and see if any of them match
  19720. for (i = 0; i < _callbacks[character].length; ++i) {
  19721. callback = _callbacks[character][i];
  19722. // if this is a sequence but it is not at the right level
  19723. // then move onto the next match
  19724. if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
  19725. continue;
  19726. }
  19727. // if the action we are looking for doesn't match the action we got
  19728. // then we should keep going
  19729. if (action != callback.action) {
  19730. continue;
  19731. }
  19732. // if this is a keypress event that means that we need to only
  19733. // look at the character, otherwise check the modifiers as
  19734. // well
  19735. if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
  19736. // remove is used so if you change your mind and call bind a
  19737. // second time with a new function the first one is overwritten
  19738. if (remove && callback.combo == combination) {
  19739. _callbacks[character].splice(i, 1);
  19740. }
  19741. matches.push(callback);
  19742. }
  19743. }
  19744. return matches;
  19745. }
  19746. /**
  19747. * takes a key event and figures out what the modifiers are
  19748. *
  19749. * @param {Event} e
  19750. * @returns {Array}
  19751. */
  19752. function _eventModifiers(e) {
  19753. var modifiers = [];
  19754. if (e.shiftKey) {
  19755. modifiers.push('shift');
  19756. }
  19757. if (e.altKey) {
  19758. modifiers.push('alt');
  19759. }
  19760. if (e.ctrlKey) {
  19761. modifiers.push('ctrl');
  19762. }
  19763. if (e.metaKey) {
  19764. modifiers.push('meta');
  19765. }
  19766. return modifiers;
  19767. }
  19768. /**
  19769. * actually calls the callback function
  19770. *
  19771. * if your callback function returns false this will use the jquery
  19772. * convention - prevent default and stop propogation on the event
  19773. *
  19774. * @param {Function} callback
  19775. * @param {Event} e
  19776. * @returns void
  19777. */
  19778. function _fireCallback(callback, e) {
  19779. if (callback(e) === false) {
  19780. if (e.preventDefault) {
  19781. e.preventDefault();
  19782. }
  19783. if (e.stopPropagation) {
  19784. e.stopPropagation();
  19785. }
  19786. e.returnValue = false;
  19787. e.cancelBubble = true;
  19788. }
  19789. }
  19790. /**
  19791. * handles a character key event
  19792. *
  19793. * @param {string} character
  19794. * @param {Event} e
  19795. * @returns void
  19796. */
  19797. function _handleCharacter(character, e) {
  19798. // if this event should not happen stop here
  19799. if (_stop(e)) {
  19800. return;
  19801. }
  19802. var callbacks = _getMatches(character, _eventModifiers(e), e.type),
  19803. i,
  19804. do_not_reset = {},
  19805. processed_sequence_callback = false;
  19806. // loop through matching callbacks for this key event
  19807. for (i = 0; i < callbacks.length; ++i) {
  19808. // fire for all sequence callbacks
  19809. // this is because if for example you have multiple sequences
  19810. // bound such as "g i" and "g t" they both need to fire the
  19811. // callback for matching g cause otherwise you can only ever
  19812. // match the first one
  19813. if (callbacks[i].seq) {
  19814. processed_sequence_callback = true;
  19815. // keep a list of which sequences were matches for later
  19816. do_not_reset[callbacks[i].seq] = 1;
  19817. _fireCallback(callbacks[i].callback, e);
  19818. continue;
  19819. }
  19820. // if there were no sequence matches but we are still here
  19821. // that means this is a regular match so we should fire that
  19822. if (!processed_sequence_callback && !_inside_sequence) {
  19823. _fireCallback(callbacks[i].callback, e);
  19824. }
  19825. }
  19826. // if you are inside of a sequence and the key you are pressing
  19827. // is not a modifier key then we should reset all sequences
  19828. // that were not matched by this key event
  19829. if (e.type == _inside_sequence && !_isModifier(character)) {
  19830. _resetSequences(do_not_reset);
  19831. }
  19832. }
  19833. /**
  19834. * handles a keydown event
  19835. *
  19836. * @param {Event} e
  19837. * @returns void
  19838. */
  19839. function _handleKey(e) {
  19840. // normalize e.which for key events
  19841. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  19842. e.which = typeof e.which == "number" ? e.which : e.keyCode;
  19843. var character = _characterFromEvent(e);
  19844. // no character found then stop
  19845. if (!character) {
  19846. return;
  19847. }
  19848. if (e.type == 'keyup' && _ignore_next_keyup == character) {
  19849. _ignore_next_keyup = false;
  19850. return;
  19851. }
  19852. _handleCharacter(character, e);
  19853. }
  19854. /**
  19855. * determines if the keycode specified is a modifier key or not
  19856. *
  19857. * @param {string} key
  19858. * @returns {boolean}
  19859. */
  19860. function _isModifier(key) {
  19861. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  19862. }
  19863. /**
  19864. * called to set a 1 second timeout on the specified sequence
  19865. *
  19866. * this is so after each key press in the sequence you have 1 second
  19867. * to press the next key before you have to start over
  19868. *
  19869. * @returns void
  19870. */
  19871. function _resetSequenceTimer() {
  19872. clearTimeout(_reset_timer);
  19873. _reset_timer = setTimeout(_resetSequences, 1000);
  19874. }
  19875. /**
  19876. * reverses the map lookup so that we can look for specific keys
  19877. * to see what can and can't use keypress
  19878. *
  19879. * @return {Object}
  19880. */
  19881. function _getReverseMap() {
  19882. if (!_REVERSE_MAP) {
  19883. _REVERSE_MAP = {};
  19884. for (var key in _MAP) {
  19885. // pull out the numeric keypad from here cause keypress should
  19886. // be able to detect the keys from the character
  19887. if (key > 95 && key < 112) {
  19888. continue;
  19889. }
  19890. if (_MAP.hasOwnProperty(key)) {
  19891. _REVERSE_MAP[_MAP[key]] = key;
  19892. }
  19893. }
  19894. }
  19895. return _REVERSE_MAP;
  19896. }
  19897. /**
  19898. * picks the best action based on the key combination
  19899. *
  19900. * @param {string} key - character for key
  19901. * @param {Array} modifiers
  19902. * @param {string=} action passed in
  19903. */
  19904. function _pickBestAction(key, modifiers, action) {
  19905. // if no action was picked in we should try to pick the one
  19906. // that we think would work best for this key
  19907. if (!action) {
  19908. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  19909. }
  19910. // modifier keys don't work as expected with keypress,
  19911. // switch to keydown
  19912. if (action == 'keypress' && modifiers.length) {
  19913. action = 'keydown';
  19914. }
  19915. return action;
  19916. }
  19917. /**
  19918. * binds a key sequence to an event
  19919. *
  19920. * @param {string} combo - combo specified in bind call
  19921. * @param {Array} keys
  19922. * @param {Function} callback
  19923. * @param {string=} action
  19924. * @returns void
  19925. */
  19926. function _bindSequence(combo, keys, callback, action) {
  19927. // start off by adding a sequence level record for this combination
  19928. // and setting the level to 0
  19929. _sequence_levels[combo] = 0;
  19930. // if there is no action pick the best one for the first key
  19931. // in the sequence
  19932. if (!action) {
  19933. action = _pickBestAction(keys[0], []);
  19934. }
  19935. /**
  19936. * callback to increase the sequence level for this sequence and reset
  19937. * all other sequences that were active
  19938. *
  19939. * @param {Event} e
  19940. * @returns void
  19941. */
  19942. var _increaseSequence = function(e) {
  19943. _inside_sequence = action;
  19944. ++_sequence_levels[combo];
  19945. _resetSequenceTimer();
  19946. },
  19947. /**
  19948. * wraps the specified callback inside of another function in order
  19949. * to reset all sequence counters as soon as this sequence is done
  19950. *
  19951. * @param {Event} e
  19952. * @returns void
  19953. */
  19954. _callbackAndReset = function(e) {
  19955. _fireCallback(callback, e);
  19956. // we should ignore the next key up if the action is key down
  19957. // or keypress. this is so if you finish a sequence and
  19958. // release the key the final key will not trigger a keyup
  19959. if (action !== 'keyup') {
  19960. _ignore_next_keyup = _characterFromEvent(e);
  19961. }
  19962. // weird race condition if a sequence ends with the key
  19963. // another sequence begins with
  19964. setTimeout(_resetSequences, 10);
  19965. },
  19966. i;
  19967. // loop through keys one at a time and bind the appropriate callback
  19968. // function. for any key leading up to the final one it should
  19969. // increase the sequence. after the final, it should reset all sequences
  19970. for (i = 0; i < keys.length; ++i) {
  19971. _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
  19972. }
  19973. }
  19974. /**
  19975. * binds a single keyboard combination
  19976. *
  19977. * @param {string} combination
  19978. * @param {Function} callback
  19979. * @param {string=} action
  19980. * @param {string=} sequence_name - name of sequence if part of sequence
  19981. * @param {number=} level - what part of the sequence the command is
  19982. * @returns void
  19983. */
  19984. function _bindSingle(combination, callback, action, sequence_name, level) {
  19985. // make sure multiple spaces in a row become a single space
  19986. combination = combination.replace(/\s+/g, ' ');
  19987. var sequence = combination.split(' '),
  19988. i,
  19989. key,
  19990. keys,
  19991. modifiers = [];
  19992. // if this pattern is a sequence of keys then run through this method
  19993. // to reprocess each pattern one key at a time
  19994. if (sequence.length > 1) {
  19995. return _bindSequence(combination, sequence, callback, action);
  19996. }
  19997. // take the keys from this pattern and figure out what the actual
  19998. // pattern is all about
  19999. keys = combination === '+' ? ['+'] : combination.split('+');
  20000. for (i = 0; i < keys.length; ++i) {
  20001. key = keys[i];
  20002. // normalize key names
  20003. if (_SPECIAL_ALIASES[key]) {
  20004. key = _SPECIAL_ALIASES[key];
  20005. }
  20006. // if this is not a keypress event then we should
  20007. // be smart about using shift keys
  20008. // this will only work for US keyboards however
  20009. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  20010. key = _SHIFT_MAP[key];
  20011. modifiers.push('shift');
  20012. }
  20013. // if this key is a modifier then add it to the list of modifiers
  20014. if (_isModifier(key)) {
  20015. modifiers.push(key);
  20016. }
  20017. }
  20018. // depending on what the key combination is
  20019. // we will try to pick the best event for it
  20020. action = _pickBestAction(key, modifiers, action);
  20021. // make sure to initialize array if this is the first time
  20022. // a callback is added for this key
  20023. if (!_callbacks[key]) {
  20024. _callbacks[key] = [];
  20025. }
  20026. // remove an existing match if there is one
  20027. _getMatches(key, modifiers, action, !sequence_name, combination);
  20028. // add this call back to the array
  20029. // if it is a sequence put it at the beginning
  20030. // if not put it at the end
  20031. //
  20032. // this is important because the way these are processed expects
  20033. // the sequence ones to come first
  20034. _callbacks[key][sequence_name ? 'unshift' : 'push']({
  20035. callback: callback,
  20036. modifiers: modifiers,
  20037. action: action,
  20038. seq: sequence_name,
  20039. level: level,
  20040. combo: combination
  20041. });
  20042. }
  20043. /**
  20044. * binds multiple combinations to the same callback
  20045. *
  20046. * @param {Array} combinations
  20047. * @param {Function} callback
  20048. * @param {string|undefined} action
  20049. * @returns void
  20050. */
  20051. function _bindMultiple(combinations, callback, action) {
  20052. for (var i = 0; i < combinations.length; ++i) {
  20053. _bindSingle(combinations[i], callback, action);
  20054. }
  20055. }
  20056. // start!
  20057. _addEvent(document, 'keypress', _handleKey);
  20058. _addEvent(document, 'keydown', _handleKey);
  20059. _addEvent(document, 'keyup', _handleKey);
  20060. var mousetrap = {
  20061. /**
  20062. * binds an event to mousetrap
  20063. *
  20064. * can be a single key, a combination of keys separated with +,
  20065. * a comma separated list of keys, an array of keys, or
  20066. * a sequence of keys separated by spaces
  20067. *
  20068. * be sure to list the modifier keys first to make sure that the
  20069. * correct key ends up getting bound (the last key in the pattern)
  20070. *
  20071. * @param {string|Array} keys
  20072. * @param {Function} callback
  20073. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  20074. * @returns void
  20075. */
  20076. bind: function(keys, callback, action) {
  20077. _bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
  20078. _direct_map[keys + ':' + action] = callback;
  20079. return this;
  20080. },
  20081. /**
  20082. * unbinds an event to mousetrap
  20083. *
  20084. * the unbinding sets the callback function of the specified key combo
  20085. * to an empty function and deletes the corresponding key in the
  20086. * _direct_map dict.
  20087. *
  20088. * the keycombo+action has to be exactly the same as
  20089. * it was defined in the bind method
  20090. *
  20091. * TODO: actually remove this from the _callbacks dictionary instead
  20092. * of binding an empty function
  20093. *
  20094. * @param {string|Array} keys
  20095. * @param {string} action
  20096. * @returns void
  20097. */
  20098. unbind: function(keys, action) {
  20099. if (_direct_map[keys + ':' + action]) {
  20100. delete _direct_map[keys + ':' + action];
  20101. this.bind(keys, function() {}, action);
  20102. }
  20103. return this;
  20104. },
  20105. /**
  20106. * triggers an event that has already been bound
  20107. *
  20108. * @param {string} keys
  20109. * @param {string=} action
  20110. * @returns void
  20111. */
  20112. trigger: function(keys, action) {
  20113. _direct_map[keys + ':' + action]();
  20114. return this;
  20115. },
  20116. /**
  20117. * resets the library back to its initial state. this is useful
  20118. * if you want to clear out the current keyboard shortcuts and bind
  20119. * new ones - for example if you switch to another page
  20120. *
  20121. * @returns void
  20122. */
  20123. reset: function() {
  20124. _callbacks = {};
  20125. _direct_map = {};
  20126. return this;
  20127. }
  20128. };
  20129. module.exports = mousetrap;
  20130. },{}]},{},[1])
  20131. (1)
  20132. });